hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d48ceb23fd98de8284939f8d83ea8f14ebbb5d01 | 26,327 | cpp | C++ | blast/src/serial/datatool/aliasstr.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | blast/src/serial/datatool/aliasstr.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | blast/src/serial/datatool/aliasstr.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | /* $Id: aliasstr.cpp 539688 2017-06-26 16:58:28Z gouriano $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Aleksey Grichenko
*
* File Description:
* Type info for aliased type generation: includes, used classes, C code etc.
*/
#include <ncbi_pch.hpp>
#include <corelib/ncbiutil.hpp>
#include "datatool.hpp"
#include "exceptions.hpp"
#include "type.hpp"
#include "aliasstr.hpp"
#include "reftype.hpp"
#include "statictype.hpp"
#include "stdstr.hpp"
#include "code.hpp"
#include "srcutil.hpp"
#include "classstr.hpp"
#include "enumstr.hpp"
#include <serial/serialdef.hpp>
BEGIN_NCBI_SCOPE
CAliasTypeStrings::CAliasTypeStrings(const string& externalName,
const string& className,
CTypeStrings& ref_type,
const CComments& comments)
: TParent(comments),
m_ExternalName(externalName),
m_ClassName(className),
m_RefType(&ref_type),
m_FullAlias(false),
m_Nested(false)
{
}
CAliasTypeStrings::~CAliasTypeStrings(void)
{
}
CAliasTypeStrings::EKind CAliasTypeStrings::GetKind(void) const
{
if (DataType() && DataType()->IsTypeAlias()) {
EKind kind = m_RefType->GetKind();
if (kind == eKindStd || kind == eKindEnum || kind == eKindString) {
return eKindClass;
}
return eKindObject;
}
return eKindOther;
}
string CAliasTypeStrings::GetClassName(void) const
{
return m_ClassName;
}
string CAliasTypeStrings::GetExternalName(void) const
{
return m_ExternalName;
}
string CAliasTypeStrings::GetCType(const CNamespace& /*ns*/) const
{
return GetClassName();
}
string CAliasTypeStrings::GetPrefixedCType(const CNamespace& ns,
const string& /*methodPrefix*/) const
{
return GetCType(ns);
}
bool CAliasTypeStrings::HaveSpecialRef(void) const
{
return m_RefType->HaveSpecialRef();
}
string CAliasTypeStrings::GetRef(const CNamespace& ns) const
{
if (DataType() && DataType()->IsTypeAlias()) {
return "CLASS, ("+GetCType(ns)+')';
}
return m_RefType->GetRef(ns);
}
bool CAliasTypeStrings::CanBeKey(void) const
{
return m_RefType->CanBeKey();
}
bool CAliasTypeStrings::CanBeCopied(void) const
{
return m_RefType->CanBeCopied();
}
string CAliasTypeStrings::NewInstance(const string& init,
const string& place) const
{
return m_RefType->NewInstance(init, place);
}
string CAliasTypeStrings::GetInitializer(void) const
{
string r = m_RefType->GetInitializer();
CTypeStrings::EKind kind = m_RefType->GetKind();
if (!r.empty() && kind != eKindClass && kind != eKindObject)
{
r = GetClassName() + "(" + r + ")";
}
return r;
}
string CAliasTypeStrings::GetDestructionCode(const string& expr) const
{
return m_RefType->GetDestructionCode(expr);
}
string CAliasTypeStrings::GetIsSetCode(const string& var) const
{
return m_RefType->GetIsSetCode(var);
}
string CAliasTypeStrings::GetResetCode(const string& var) const
{
return m_RefType->GetResetCode(var);
}
string CAliasTypeStrings::GetDefaultCode(const string& var) const
{
// No value - return empty string
if ( var.empty() ) {
return NcbiEmptyString;
}
// Return var for classes, else cast var to the aliased type
return GetCType(GetNamespace()) + "(" + var + ")";
}
void CAliasTypeStrings::GenerateCode(CClassContext& ctx) const
{
const CNamespace& ns = ctx.GetNamespace();
string ref_name = m_RefType->GetCType(ns);
string className;
if (m_Nested) {
className = GetClassName();
} else {
className = GetClassName() + "_Base";
}
CClassCode code(ctx, className);
string methodPrefix = code.GetMethodPrefix();
string classFullName(GetClassName());
if (m_Nested) {
classFullName = NStr::TrimSuffix_Unsafe(methodPrefix, "::");
}
bool is_class = false;
bool is_ref_to_alias = false;
const CClassTypeStrings::SMemberInfo* mem_alias = nullptr;
bool mem_isnull = false;
bool type_alias = DataType() && DataType()->IsTypeAlias();
AutoPtr<CTypeStrings> mem_type;
CTypeStrings::EKind kind = m_RefType->GetKind();
switch ( kind ) {
case eKindClass:
case eKindObject:
{
string name(ref_name);
const CClassRefTypeStrings* cls =
dynamic_cast<const CClassRefTypeStrings*>(m_RefType.get());
if (cls) {
name = cls->GetClassName();
}
code.SetParentClass(name, m_RefType->GetNamespace());
}
is_class = true;
is_ref_to_alias = (dynamic_cast<const CAliasRefTypeStrings*>(m_RefType.get()) != NULL);
// only if we have two members, and one of them is attlist
// that is, if it was created by DTDParser::CompositeNode
if (!is_ref_to_alias && DataType() && !DataType()->IsASNDataSpec() && DataType()->IsReference()) {
const CReferenceDataType* reftype = dynamic_cast<const CReferenceDataType*>(DataType());
const CDataType* resolved = reftype->Resolve();
if (resolved && resolved != reftype) {
CClassTypeStrings* typeStr = resolved->GetTypeStr();
bool has_attlist = false;
if (typeStr && typeStr->m_Members.size() == 2) {
for ( const auto& ir: typeStr->m_Members ) {
if (ir.attlist) {
has_attlist = true;
} else {
mem_alias = &ir;
mem_isnull = ir.haveFlag ? (dynamic_cast<CNullTypeStrings*>(ir.type.get()) != 0) : false;
}
}
if (!has_attlist || mem_alias->externalName != reftype->GetUserTypeName()) {
mem_alias = nullptr;
}
} else {
mem_isnull = dynamic_cast<const CNullDataType*>(resolved) != nullptr;
}
}
}
break;
case eKindStd:
case eKindEnum:
code.SetParentClass("CStdAliasBase< " + ref_name + " >",
CNamespace::KNCBINamespace);
break;
case eKindString:
code.SetParentClass("CStringAliasBase< " + ref_name + " >",
CNamespace::KNCBINamespace);
break;
case eKindOther: // for vector< char >
code.SetParentClass("CStringAliasBase< " + ref_name + " >",
CNamespace::KNCBINamespace);
break;
case eKindPointer:
case eKindRef:
case eKindContainer:
NCBI_THROW(CDatatoolException, eNotImplemented,
"Invalid aliased type: " + ref_name);
}
if (m_Nested && type_alias && !mem_alias && !DataType()->HasTag() &&
!DataType()->IsInUniSeq() &&
DataType()->GetTagType() == CAsnBinaryDefs::eAutomatic)
{
bool is_std = kind == eKindStd || kind == eKindEnum || kind == eKindString || kind == eKindOther;
if (!is_std) {
m_RefType->GenerateTypeCode(ctx);
code.SetEmptyClassCode();
return;
}
}
string parentNamespaceRef =
code.GetNamespace().GetNamespaceRef(code.GetParentClassNamespace());
BeginClassDeclaration(ctx);
// constructor
code.ClassPublic() <<
" " << className << "(void);\n" <<
"\n";
code.MethodStart(true) <<
methodPrefix << className << "(void)\n" <<
"{\n" <<
"}\n" <<
"\n";
m_RefType->GenerateTypeCode(ctx);
if ( is_class ) {
if (is_ref_to_alias) {
code.ClassPublic() <<
" // type info\n"
" DECLARE_STD_ALIAS_TYPE_INFO();\n"
"\n";
} else {
code.ClassPublic() <<
" // type info\n"
" DECLARE_INTERNAL_TYPE_INFO();\n"
"\n";
}
// m_RefType->GenerateTypeCode(ctx);
// I have strong feeling that this was a bad idea
// and these methods should be removed
if (/*!mem_isnull &&*/ !type_alias) {
code.ClassPublic() <<
" // parent type getter/setter\n" <<
" const " << ref_name << "& Get(void) const;\n" <<
" " << ref_name << "& Set(void);\n";
code.MethodStart(true) <<
"const " << ref_name << "& " << methodPrefix << "Get(void) const\n" <<
"{\n" <<
" return *this;\n" <<
"}\n\n";
code.MethodStart(true) <<
ref_name << "& " << methodPrefix << "Set(void)\n" <<
"{\n" <<
" return *this;\n" <<
"}\n\n";
}
if (type_alias && mem_alias) {
string extname(m_ClassName);
if (NStr::StartsWith(extname, "C_")) {
NStr::TrimPrefixInPlace(extname, "C_");
} else if (NStr::StartsWith(extname, "C")) {
NStr::TrimPrefixInPlace(extname, "C");
}
string mem_extname(mem_alias->cName);
code.ClassPublic() << "\n";
if (!mem_isnull) {
code.ClassPublic() << " typedef "
<< "Tparent::" << mem_alias->tName << " T" << extname << ";\n";
}
code.ClassPublic() <<
" bool IsSet" << extname << "(void) const {\n" <<
" return Tparent::IsSet" << mem_extname << "();\n" <<
" }\n";
code.ClassPublic() <<
" bool CanGet" << extname << "(void) const {\n" <<
" return Tparent::CanGet" << mem_extname << "();\n" <<
" }\n";
code.ClassPublic() <<
" void Reset" << extname << "(void) {\n" <<
" Tparent::Reset" << mem_extname << "();\n" <<
" }\n";
if (mem_isnull) {
code.ClassPublic() << " " <<
"void" << " Set" << extname << "(void) {\n" <<
" Tparent::Set" << mem_extname << "();\n" <<
" }\n";
} else {
code.ClassPublic() << " const " <<
"T" << extname << "& Get" << extname << "(void) const {\n" <<
" return Tparent::Get" << mem_extname << "();\n" <<
" }\n";
code.ClassPublic() << " " <<
"T" << extname << "& Set" << extname << "(void) {\n" <<
" return Tparent::Set" << mem_extname << "();\n" <<
" }\n";
// if (mem_alias->dataType && mem_alias->dataType->IsPrimitive()) {
if (mem_alias->type->CanBeCopied()) {
code.ClassPublic() << " " <<
"void" << " Set" << extname << "(const T" << extname << "& value) {\n" <<
" Tparent::Set" << mem_extname << "(value);\n" <<
" }\n";
if (mem_alias->simple && m_Nested) {
code.ClassPublic() << " " <<
className << "(const" << " T" << extname << "& value) : Tparent(value) {\n }\n";
code.ClassPublic() << " " <<
className << "& operator=(const" << " T" << extname << "& value) {\n" <<
" Tparent::operator=(value);\n" <<
" return *this;\n" <<
" }\n";
}
}
}
}
}
else {
code.ClassPublic() <<
" // type info\n"
" DECLARE_STD_ALIAS_TYPE_INFO();\n"
"\n";
string constr_decl = className + "(const " + ref_name + "& data)";
code.ClassPublic() <<
" // explicit constructor from the primitive type\n" <<
" explicit " << constr_decl << ";\n";
code.MethodStart(true) <<
methodPrefix << constr_decl << "\n" <<
" : " << parentNamespaceRef << code.GetParentClassName() << "(data)\n" <<
"{\n" <<
"}\n" <<
"\n";
// I/O operators
bool kindIO = kind == eKindStd || kind == eKindEnum ||
kind == eKindString || kind == eKindPointer;
code.MethodStart(true) <<
"NCBI_NS_NCBI::CNcbiOstream& operator<<\n" <<
"(NCBI_NS_NCBI::CNcbiOstream& str, const " << (m_Nested ? classFullName : className) << "& obj)\n" <<
"{\n";
if (kindIO) {
code.Methods(true) <<
" if (NCBI_NS_NCBI::MSerial_Flags::HasSerialFormatting(str)) {\n" <<
" return WriteObject(str,&obj,obj.GetTypeInfo());\n" <<
" }\n" <<
" str << obj.Get();\n" <<
" return str;\n";
} else {
code.Methods(true) <<
" return WriteObject(str,&obj,obj.GetTypeInfo());\n";
}
code.Methods(true) << "}\n\n";
code.MethodStart(true) <<
"NCBI_NS_NCBI::CNcbiIstream& operator>>\n" <<
"(NCBI_NS_NCBI::CNcbiIstream& str, " << (m_Nested ? classFullName : className) << "& obj)\n" <<
"{\n";
if (kindIO) {
code.Methods(true) <<
" if (NCBI_NS_NCBI::MSerial_Flags::HasSerialFormatting(str)) {\n" <<
" return ReadObject(str,&obj,obj.GetTypeInfo());\n" <<
" }\n";
if (kind == eKindEnum && m_RefType->GetEnumName() == ref_name)
{
code.Methods(true) <<
" std::underlying_type<" << ref_name <<">::type v;\n" <<
" str >> v;\n" <<
" obj.Set((" << ref_name << ")v);\n";
}
else
{
code.Methods(true) <<
" str >> obj.Set();\n";
}
code.Methods(true) <<
" return str;\n";
} else {
code.Methods(true) <<
" return ReadObject(str,&obj,obj.GetTypeInfo());\n";
}
code.Methods(true) << "}\n\n";
}
// define typeinfo method
{
// code.CPPIncludes().insert("serial/aliasinfo");
CNcbiOstream& methods = code.Methods();
methods << "BEGIN";
if (m_Nested) {
methods << "_NESTED";
}
if (dynamic_cast<const CEnumRefTypeStrings*>(m_RefType.get())) {
methods << "_ENUM";
}
methods << "_ALIAS_INFO(\""
<< GetExternalName() << "\", "
<< classFullName << ", "
<< m_RefType->GetRef(ns) << ")\n"
"{\n";
if ( !GetModuleName().empty() ) {
methods <<
" SET_ALIAS_MODULE(\"" << GetModuleName() << "\");\n";
}
const CDataType* dataType = DataType();
if (dataType) {
if (dataType->HasTag()) {
methods <<
" SET_ASN_TAGGED_TYPE_INFO(" <<"SetTag, (" << dataType->GetTag() <<',' <<
dataType->GetTagClassString(dataType->GetTagClass()) << ',' <<
dataType->GetTagTypeString(dataType->GetTagType()) <<"));\n";
} else if (dataType->GetTagType() != CAsnBinaryDefs::eAutomatic) {
methods <<
" SET_ASN_TAGGED_TYPE_INFO(" <<"SetTagType, (" <<
dataType->GetTagTypeString(dataType->GetTagType()) <<"));\n";
}
}
methods << " SET_";
if ( is_class ) {
methods << "CLASS";
}
else {
methods << "STD";
}
methods <<
"_ALIAS_DATA_PTR;\n";
if (mem_alias || type_alias || this->IsFullAlias()) {
methods <<
" SET_FULL_ALIAS;\n";
}
methods << " info->CodeVersion(" << DATATOOL_VERSION << ");\n";
methods << " info->DataSpec(" << CDataType::GetSourceDataSpecString() << ");\n";
methods <<
"}\n"
"END_ALIAS_INFO\n"
"\n";
}
}
void CAliasTypeStrings::GenerateUserHPPCode(CNcbiOstream& out) const
{
// m_RefType->GenerateUserHPPCode(out);
const CNamespace& ns = GetNamespace();
string ref_name = m_RefType->GetCType(ns);
string className = GetClassName();
if (CClassCode::GetDoxygenComments()) {
out
<< "\n"
<< "/** @addtogroup ";
if (!CClassCode::GetDoxygenGroup().empty()) {
out << CClassCode::GetDoxygenGroup();
} else {
out << "dataspec_" << GetDoxygenModuleName();
}
out
<< "\n *\n"
<< " * @{\n"
<< " */\n\n";
}
out <<
"/////////////////////////////////////////////////////////////////////////////\n";
if (CClassCode::GetDoxygenComments()) {
out <<
"///\n"
"/// " << className << " --\n"
"///\n\n";
}
out << "class ";
if ( !CClassCode::GetExportSpecifier().empty() )
out << CClassCode::GetExportSpecifier() << " ";
out << GetClassName()<<" : public "<<GetClassName()<<"_Base\n"
"{\n"
" typedef "<<GetClassName()<<"_Base Tparent;\n"
"public:\n";
out <<
" " << GetClassName() << "(void) {}\n"
"\n";
bool is_class = false;
const CClassTypeStrings::SMemberInfo* mem_alias = nullptr;
bool mem_isnull = false;
AutoPtr<CTypeStrings> mem_type;
switch ( m_RefType->GetKind() ) {
case eKindClass:
case eKindObject:
is_class = true;
if (DataType()->IsReference()) {
const CReferenceDataType* reftype = dynamic_cast<const CReferenceDataType*>(DataType());
const CDataType* resolved = reftype->Resolve();
if (resolved && resolved != reftype) {
CClassTypeStrings* typeStr = resolved->GetTypeStr();
bool has_attlist = false;
if (typeStr) {
if (typeStr->m_Members.size() == 2) {
for ( const auto& ir: typeStr->m_Members ) {
if (ir.attlist) {
has_attlist = true;
} else {
mem_alias = &ir;
mem_isnull = ir.haveFlag ? (dynamic_cast<CNullTypeStrings*>(ir.type.get()) != 0) : false;
}
}
if (!has_attlist || mem_alias->externalName != reftype->GetUserTypeName()) {
mem_alias = nullptr;
}
}
if (mem_alias && mem_alias->dataType && !mem_alias->dataType->IsStdType()) {
mem_alias = nullptr;
}
} else {
mem_isnull = dynamic_cast<const CNullDataType*>(resolved) != nullptr;
if (!mem_isnull && !resolved->IsAlias() && resolved->IsStdType()) {
mem_type = resolved->GenerateCode();
const CClassTypeStrings* mem_class = dynamic_cast<const CClassTypeStrings*>(mem_type.get());
if (mem_class && mem_class->m_Members.size() == 1) {
mem_alias = &(mem_class->m_Members.front());
}
}
}
}
}
break;
default:
is_class = false;
break;
}
if ( !is_class ) {
// Generate type convertions
out <<
" /// Explicit constructor from the primitive type.\n" <<
" explicit " << className + "(const " + ref_name + "& value)" << "\n"
" : Tparent(value) {}\n\n";
}
else if (mem_alias) {
#if 0
string tname = mem_alias->type->GetCType(ns); // or mem_alias->tName?
#else
string tname = "Tparent::" + mem_alias->tName;
out << " // typedef " << mem_alias->type->GetCType(ns) << " " << mem_alias->tName << ";\n\n";
#endif
string mem_extname(mem_alias->cName);
out <<
" /// Constructor from the primitive type.\n" <<
" " << className << "(const " << tname << "& value) {\n" <<
" Set" << mem_extname << "(value);\n" <<
" }\n";
out <<
" /// Assignment operator\n" <<
" " << className << "& operator=(const " << tname << "& value) {\n" <<
" Set" << mem_extname << "(value);\n" <<
" return *this;\n" <<
" }\n";
#if 0
out <<
" /// Conversion operator\n" <<
" operator const " << tname << "& (void) {\n" <<
" return Get" << mem_extname << "();\n" <<
" }\n" <<
" operator " << tname << "& (void) {\n" <<
" return Set" << mem_extname << "();\n" <<
" }\n";
#endif
}
out << "};\n";
if (CClassCode::GetDoxygenComments()) {
out << "/* @} */\n";
}
out << "\n";
}
void CAliasTypeStrings::GenerateUserCPPCode(CNcbiOstream& /* out */) const
{
//m_RefType->GenerateUserCPPCode(out);
}
void CAliasTypeStrings::GenerateTypeCode(CClassContext& ctx) const
{
if (DataType()->IsTypeAlias()) {
m_Nested = true;
GenerateCode(ctx);
m_Nested = false;
return;
}
m_RefType->GenerateTypeCode(ctx);
}
void CAliasTypeStrings::GeneratePointerTypeCode(CClassContext& ctx) const
{
if (DataType()->IsTypeAlias()) {
m_Nested = true;
GenerateCode(ctx);
m_Nested = false;
return;
}
m_RefType->GeneratePointerTypeCode(ctx);
}
CAliasRefTypeStrings::CAliasRefTypeStrings(const string& className,
const CNamespace& ns,
const string& fileName,
CTypeStrings& ref_type,
const CComments& comments)
: CParent(comments),
m_ClassName(className),
m_Namespace(ns),
m_FileName(fileName),
m_RefType(&ref_type),
m_IsObject(m_RefType->GetKind() == eKindObject)
{
}
CTypeStrings::EKind CAliasRefTypeStrings::GetKind(void) const
{
return m_IsObject ? eKindObject : eKindClass;
}
const CNamespace& CAliasRefTypeStrings::GetNamespace(void) const
{
return m_Namespace;
}
void CAliasRefTypeStrings::GenerateTypeCode(CClassContext& ctx) const
{
ctx.HPPIncludes().insert(m_FileName);
}
void CAliasRefTypeStrings::GeneratePointerTypeCode(CClassContext& ctx) const
{
ctx.AddForwardDeclaration(m_ClassName, m_Namespace);
ctx.CPPIncludes().insert(m_FileName);
}
string CAliasRefTypeStrings::GetCType(const CNamespace& ns) const
{
return ns.GetNamespaceRef(m_Namespace) + m_ClassName;
}
string CAliasRefTypeStrings::GetPrefixedCType(const CNamespace& ns,
const string& /*methodPrefix*/) const
{
return GetCType(ns);
}
bool CAliasRefTypeStrings::HaveSpecialRef(void) const
{
return m_RefType->HaveSpecialRef();
}
string CAliasRefTypeStrings::GetRef(const CNamespace& ns) const
{
return "CLASS, ("+GetCType(ns)+')';
}
bool CAliasRefTypeStrings::CanBeKey(void) const
{
return m_RefType->CanBeKey();
}
bool CAliasRefTypeStrings::CanBeCopied(void) const
{
return m_RefType->CanBeCopied();
}
string CAliasRefTypeStrings::GetInitializer(void) const
{
return m_IsObject ?
NcbiEmptyString :
GetDefaultCode(m_RefType->GetInitializer());
}
string CAliasRefTypeStrings::GetDestructionCode(const string& expr) const
{
return m_IsObject ?
NcbiEmptyString :
m_RefType->GetDestructionCode(expr);
}
string CAliasRefTypeStrings::GetIsSetCode(const string& var) const
{
return m_RefType->GetIsSetCode(var);
}
string CAliasRefTypeStrings::GetResetCode(const string& var) const
{
return m_IsObject ?
var + ".Reset();\n" :
m_RefType->GetResetCode(var + ".Set()");
}
string CAliasRefTypeStrings::GetDefaultCode(const string& var) const
{
// No value - return empty string
if ( m_IsObject || var.empty() ) {
return NcbiEmptyString;
}
// Cast var to the aliased type
return GetCType(GetNamespace()) + "(" + var + ")";
}
void CAliasRefTypeStrings::GenerateCode(CClassContext& ctx) const
{
m_RefType->GenerateCode(ctx);
}
void CAliasRefTypeStrings::GenerateUserHPPCode(CNcbiOstream& out) const
{
m_RefType->GenerateUserHPPCode(out);
}
void CAliasRefTypeStrings::GenerateUserCPPCode(CNcbiOstream& out) const
{
m_RefType->GenerateUserCPPCode(out);
}
END_NCBI_SCOPE
| 34.459424 | 121 | 0.512326 | mycolab |
d48e6d4501bd9a61aedb5138d3e0d499ed60ec4e | 356 | cpp | C++ | libs/libc/unistd.cpp | jasonwer/WingOS | 1e3b8b272bc93542fda48ed1cf3226e63c923f39 | [
"BSD-2-Clause"
] | null | null | null | libs/libc/unistd.cpp | jasonwer/WingOS | 1e3b8b272bc93542fda48ed1cf3226e63c923f39 | [
"BSD-2-Clause"
] | null | null | null | libs/libc/unistd.cpp | jasonwer/WingOS | 1e3b8b272bc93542fda48ed1cf3226e63c923f39 | [
"BSD-2-Clause"
] | null | null | null | #include "unistd.h"
#include <kern/syscall.h>
unsigned int sleep(unsigned int sec)
{
timespec time = {0, 0};
time.tv_sec = sec;
return sys::sys$nano_sleep(&time, nullptr);
}
suseconds_t usleep(suseconds_t sec)
{
timespec time = {0, 0};
time.tv_sec = 0;
time.tv_nsec = sec * 1000;
return sys::sys$nano_sleep(&time, nullptr);
}
| 19.777778 | 47 | 0.646067 | jasonwer |
d491235b19967c3e37bae70df66dc0064295c7ca | 6,351 | cpp | C++ | VirtualBox-5.0.0/src/VBox/Main/webservice/split-soapC.cpp | egraba/vbox_openbsd | 6cb82f2eed1fa697d088cecc91722b55b19713c2 | [
"MIT"
] | 1 | 2015-04-30T14:18:45.000Z | 2015-04-30T14:18:45.000Z | VirtualBox-5.0.0/src/VBox/Main/webservice/split-soapC.cpp | egraba/vbox_openbsd | 6cb82f2eed1fa697d088cecc91722b55b19713c2 | [
"MIT"
] | null | null | null | VirtualBox-5.0.0/src/VBox/Main/webservice/split-soapC.cpp | egraba/vbox_openbsd | 6cb82f2eed1fa697d088cecc91722b55b19713c2 | [
"MIT"
] | null | null | null | /** @file
* File splitter: splits soapC.cpp into manageable pieces. It is somewhat
* intelligent and avoids splitting inside functions or similar places.
*/
/*
* Copyright (C) 2009-2010 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
int main(int argc, char *argv[])
{
int rc = 0;
FILE *pFileIn = NULL;
FILE *pFileOut = NULL;
char *pBuffer = NULL;
do
{
if (argc != 4)
{
fprintf(stderr, "split-soapC: Must be started with exactly three arguments,\n"
"1) the input file, 2) the directory where to put the output files and\n"
"3) the number chunks to create.\n");
rc = 2;
break;
}
char *pEnd = NULL;
unsigned long cChunk = strtoul(argv[3], &pEnd, 0);
if (cChunk == ULONG_MAX || cChunk == 0 || !argv[3] || *pEnd)
{
fprintf(stderr, "split-soapC: Given argument \"%s\" is not a valid chunk count.\n", argv[3]);
rc = 2;
break;
}
pFileIn = fopen(argv[1], "rb");
if (!pFileIn)
{
fprintf(stderr, "split-soapC: Cannot open file \"%s\" for reading.\n", argv[1]);
rc = 2;
break;
}
int rc2 = fseek(pFileIn, 0, SEEK_END);
long cbFileIn = ftell(pFileIn);
int rc3 = fseek(pFileIn, 0, SEEK_SET);
if (rc3 == -1 || rc2 == -1 || cbFileIn < 0)
{
fprintf(stderr, "split-soapC: Seek failure.\n");
rc = 2;
break;
}
if (!(pBuffer = (char*)malloc(cbFileIn + 1)))
{
fprintf(stderr, "split-soapC: Failed to allocate %ld bytes.\n", cbFileIn);
rc = 2;
break;
}
if (fread(pBuffer, 1, cbFileIn, pFileIn) != (size_t)cbFileIn)
{
fprintf(stderr, "split-soapC: Failed to read %ld bytes from input file.\n", cbFileIn);
rc = 2;
break;
}
pBuffer[cbFileIn] = '\0';
const char *pLine = pBuffer;
unsigned long cbChunk = cbFileIn / cChunk;
unsigned long cFiles = 0;
unsigned long uLimit = 0;
unsigned long cbWritten = 0;
unsigned long cIfNesting = 0;
unsigned long cBraceNesting = 0;
unsigned long cLinesSinceStaticMap = ~0UL / 2;
bool fJustZero = false;
do
{
if (!pFileOut)
{
/* construct output filename */
char szFilename[1024];
sprintf(szFilename, "%s/soapC-%lu.cpp", argv[2], ++cFiles);
szFilename[sizeof(szFilename)-1] = '\0';
printf("info: soapC-%lu.cpp\n", cFiles);
/* create output file */
if (!(pFileOut = fopen(szFilename, "wb")))
{
fprintf(stderr, "split-soapC: Failed to open file \"%s\" for writing\n", szFilename);
rc = 2;
break;
}
if (cFiles > 1)
fprintf(pFileOut, "#include \"soapH.h\"%s\n",
#ifdef RT_OS_WINDOWS
"\r"
#else /* !RT_OS_WINDOWS */
""
#endif /* !RT_OS_WINDOWS */
);
uLimit += cbChunk;
cLinesSinceStaticMap = ~0UL / 2;
}
/* find begin of next line and print current line */
const char *pNextLine = strchr(pLine, '\n');
size_t cbLine;
if (pNextLine)
{
pNextLine++;
cbLine = pNextLine - pLine;
}
else
cbLine = strlen(pLine);
if (fwrite(pLine, 1, cbLine, pFileOut) != cbLine)
{
fprintf(stderr, "split-soapC: Failed to write to output file\n");
rc = 2;
break;
}
cbWritten += cbLine;
/* process nesting depth information */
if (!strncmp(pLine, "#if", 3))
cIfNesting++;
else if (!strncmp(pLine, "#endif", 6))
{
cIfNesting--;
if (!cBraceNesting && !cIfNesting)
fJustZero = true;
}
else
{
for (const char *p = pLine; p < pLine + cbLine; p++)
{
if (*p == '{')
cBraceNesting++;
else if (*p == '}')
{
cBraceNesting--;
if (!cBraceNesting && !cIfNesting)
fJustZero = true;
}
}
}
/* look for static variables used for enum conversion. */
if (!strncmp(pLine, "static const struct soap_code_map", sizeof("static const struct soap_code_map") - 1))
cLinesSinceStaticMap = 0;
else
cLinesSinceStaticMap++;
/* start a new output file if necessary and possible */
if ( cbWritten >= uLimit
&& cIfNesting == 0
&& fJustZero
&& cFiles < cChunk
&& cLinesSinceStaticMap > 150 /*hack!*/)
{
fclose(pFileOut);
pFileOut = NULL;
}
if (rc)
break;
fJustZero = false;
pLine = pNextLine;
} while (pLine);
printf("split-soapC: Created %lu files.\n", cFiles);
} while (0);
if (pBuffer)
free(pBuffer);
if (pFileIn)
fclose(pFileIn);
if (pFileOut)
fclose(pFileOut);
return rc;
}
| 31.597015 | 118 | 0.471894 | egraba |
d491564c71c02486d74c18544dd6e9165346ab3f | 6,337 | hpp | C++ | include/dragon/graph/graph.hpp | parth-07/dragon | 2e771d698398303c8ae6d603d28bc3acfa116181 | [
"MIT"
] | 1 | 2021-02-24T17:51:32.000Z | 2021-02-24T17:51:32.000Z | include/dragon/graph/graph.hpp | parth-07/dragon | 2e771d698398303c8ae6d603d28bc3acfa116181 | [
"MIT"
] | 1 | 2021-02-24T17:57:04.000Z | 2021-05-17T11:09:40.000Z | include/dragon/graph/graph.hpp | parth-07/ds-and-algos | 2e771d698398303c8ae6d603d28bc3acfa116181 | [
"MIT"
] | null | null | null | #ifndef DRAGON_GRAPH_GRAPH_HPP
#define DRAGON_GRAPH_GRAPH_HPP
#include <limits>
#include <map>
#include <vector>
namespace dragon {
/**
* `Graph` is an efficient, easy to use generic implementation of the basic
* graph data structure.
*
* @param ValueT type of value of graph nodes.
* @param EdgeValueT type of weight of graph edges.
*
* @note `Graph` do not support multiple edges between the same nodes.
*/
template <typename ValueT, typename EdgeValueT = int> class Graph {
public:
using ValueType = ValueT;
using EdgeValueType = EdgeValueT;
using SizeType = std::size_t;
using AdjacencyStructureType = std::map<SizeType, EdgeValueType>;
class Node;
using size_type = SizeType; // NOLINT
private:
template <typename T> using Sequence = std::vector<T>;
using NodeSequenceType = Sequence<Node>;
public:
using iterator = typename NodeSequenceType::iterator; // NOLINT
using const_iterator = typename NodeSequenceType::const_iterator; // NOLINT
public:
static constexpr SizeType npos = std::numeric_limits<SizeType>::max();
static constexpr EdgeValueType
nweight = std::numeric_limits<EdgeValueType>::max();
public:
Graph(SizeType sz = 0, SizeType root = 0) : m_root(root) {
for (auto i = 0U; i < sz; ++i) {
m_nodes.emplace_back(i);
}
}
Graph(const Graph&) = default;
Graph(Graph&&) noexcept = default;
Graph& operator=(const Graph&) = default;
Graph& operator=(Graph&&) noexcept = default;
~Graph() = default;
/// Returns a reference to ith node of the graph.
auto& operator[](SizeType index) { return m_nodes[index]; }
auto& operator[](SizeType index) const { return m_nodes[index]; }
/// Returns begin iterator for the nodes of the graph.
auto begin() { return m_nodes.begin(); }
auto begin() const { return m_nodes.begin(); }
/// Returns end iterator for the nodes of the graph.
auto end() { return m_nodes.end(); }
auto end() const { return m_nodes.end(); }
auto cbegin() const { return m_nodes.cbegin(); }
auto cend() const { return m_nodes.cend(); }
/**
* Clears all nodes of the graph.
*/
void clear();
/**
* Adds a weighted directed edge from node `u` to `v` (`u` -> `v`),
*
* If an edge already exists from node `u` to node `v`, then the edge weight
* is updated.
*
* @param u first node of the edge.
* @param v second node of the edge.
* @param weight weight of the edge.
*/
void add_directed_edge(SizeType u_i, SizeType v_i, EdgeValueType weight = 1);
/**
* Adds a weighted undirected edge between node `u` and `v`.
*
* If an undirected edge already exists between nodes `u` and `v`, then the
* edge weight is updated.
*
* @param u first node of the edge.
* @param v second node of the edge.
* @param weight weight of the edge.
*/
void add_undirected_edge(SizeType u_i, SizeType v_i,
EdgeValueType weight = 1);
/**
* Remove a directed edge from node `u` to `v`.
*
* Does nothing if no directed edge exist from node `u` to `v`.
*
* @param u_i index of the first node
* @param v_i index of the second node
*/
void remove_directed_edge(SizeType u_i, SizeType v_i);
/**
* Remove an undirected edge between nodes `u` and `v`.
*
* Does nothing if no undirected edge exist between nodes `u` and `v`.
*/
void remove_undirected_edge(SizeType u_i, SizeType v_i);
/// Reset all nodes color to `Color::white`.
void reset_color();
/// Returns the number of nodes in the graph.
auto size() const;
/// Returns the index of the root node.
auto root() const;
enum class Color { white, grey, black };
/**
* `Node` is a data structure to represent a node of the graph.
*/
class Node {
public:
Node(SizeType index) : m_index(index) {}
Node(SizeType index, ValueType p_value) : m_index(index), value(p_value) {}
Node(const Node&) = default;
Node(Node&&) noexcept = default;
Node& operator=(const Node&) = default;
Node& operator=(Node&&) noexcept = default;
~Node() = default;
public:
SizeType index() const { return m_index; }
ValueType value;
AdjacencyStructureType edges;
Color color = Color::white;
SizeType parent = npos, depth = npos;
private:
const SizeType m_index;
};
public:
const NodeSequenceType& nodes = m_nodes; // NOLINT
private:
/// Stores nodes of the graph.
NodeSequenceType m_nodes;
/// Stores index of the root node.
const SizeType m_root;
};
template <typename ValueT, typename EdgeValueT>
constexpr typename Graph<ValueT, EdgeValueT>::SizeType
Graph<ValueT, EdgeValueT>::npos;
template <typename ValueT, typename EdgeValueT>
constexpr typename Graph<ValueT, EdgeValueT>::EdgeValueType
Graph<ValueT, EdgeValueT>::nweight;
template <typename ValueT, typename EdgeValueT>
void Graph<ValueT, EdgeValueT>::add_directed_edge(SizeType u_i, SizeType v_i,
EdgeValueType weight) {
m_nodes[u_i].edges[v_i] = weight;
}
template <typename ValueT, typename EdgeValueT>
void Graph<ValueT, EdgeValueT>::add_undirected_edge(SizeType u_i, SizeType v_i,
EdgeValueType weight) {
m_nodes[u_i].edges[v_i] = weight;
m_nodes[v_i].edges[u_i] = weight;
}
template <typename ValueT, typename EdgeValueT>
void Graph<ValueT, EdgeValueT>::remove_directed_edge(SizeType u_i,
SizeType v_i) {
m_nodes[u_i].edges.erase(v_i);
}
template <typename ValueT, typename EdgeValueT>
void Graph<ValueT, EdgeValueT>::remove_undirected_edge(SizeType u_i,
SizeType v_i) {
m_nodes[u_i].edges.erase(v_i);
m_nodes[v_i].edges.erase(u_i);
}
template <typename ValueT, typename EdgeValueT>
void Graph<ValueT, EdgeValueT>::clear() {
m_nodes.clear();
}
template <typename ValueT, typename EdgeValueT>
void Graph<ValueT, EdgeValueT>::reset_color() {
for (auto& node : m_nodes) {
node.color = Color::white;
}
}
template <typename ValueT, typename EdgeValueT>
auto Graph<ValueT, EdgeValueT>::size() const {
return m_nodes.size();
}
template <typename ValueT, typename EdgeValueT>
auto Graph<ValueT, EdgeValueT>::root() const {
return m_root;
}
} // namespace dragon
#endif | 29.751174 | 79 | 0.666246 | parth-07 |
d4920a50c87fa9d13beb31e4dc100568b5c133c4 | 15,448 | cpp | C++ | Classes/GameLayer.cpp | NeilKleistGao/Zelda-External-Assassin-Plan | e172b181ffc04a78d4ce14ca75fc09049bc3c70a | [
"MIT"
] | 1 | 2019-07-01T13:44:25.000Z | 2019-07-01T13:44:25.000Z | Classes/GameLayer.cpp | NeilKleistGao/Zelda-External-Assassin-Plan | e172b181ffc04a78d4ce14ca75fc09049bc3c70a | [
"MIT"
] | 3 | 2019-07-06T14:32:56.000Z | 2019-07-11T05:57:43.000Z | Classes/GameLayer.cpp | NeilKleistGao/Zelda-External-Assassin-Plan | e172b181ffc04a78d4ce14ca75fc09049bc3c70a | [
"MIT"
] | null | null | null | #include <algorithm>
#include <cmath>
#include "GameLayer.h"
#include "Player.h"
#include "MapManager.h"
#include "PauseScene.h"
#include "Config.h"
#include "Enemy.h"
#include "SelectScene.h"
#include "Bullet.h"
#include "GameVictoryScene.h"
#include "GameProcess.h"
#include "PauseUILayer.h"
#include "audio/include/AudioEngine.h"
#include "Debuger.h"
using namespace cocos2d;
using namespace experimental;
GameLayer::~GameLayer() {
NotificationCenter::getInstance()->removeAllObservers(this);
}
GameLayer* GameLayer::create(int level) {
auto layer = new(std::nothrow) GameLayer();
if (layer && layer->init(level)) {
layer->autorelease();
}
else if (layer) {
delete layer;
layer = nullptr;
}
return layer;
}
bool GameLayer::init(int level) {
if (!Layer::init()) {
return false;
}
currentLevel = level;
this->isInteractable = false;
this->isMovable = true;
this->isTransition = false;
this->damageTaken = 0;
auto visibleSize = Director::getInstance()->getVisibleSize();
auto origion = Director::getInstance()->getVisibleOrigin();
AudioEngine::stopAll();
bgmID = AudioEngine::play2d("music/" + std::to_string(level) + ".mp3", true, 0.5f);
//add map
auto map = MapManager::create(level);
map->setPosition(Vec2::ZERO);
map->setName("map");
this->addChild(map, 0);
//add player
auto player = Player::create("Game/playerDown0.png");
player->setName("player");
player->setScale(3.2, 3.2);
player->setPosition(map->getPlayerPosition());
player->setOrigion(player->getPosition());
this->addChild(player, 1);
auto shadow = Sprite::create("Game/shadow.png");
shadow->setPosition(Vec2(origion.x + visibleSize.width / 2, origion.y + visibleSize.height / 2));
shadow->setName("shadow");
shadow->setOpacity(0);
this->addChild(shadow, 20);
//add contact call back function
auto plistener = EventListenerPhysicsContact::create();
plistener->onContactBegin = [this](PhysicsContact& cont) -> bool {
cont.getShapeA()->getBody()->resetForces();
cont.getShapeB()->getBody()->resetForces();
this->onContactBegin(cont.getShapeA()->getBody()->getNode(), cont.getShapeB()->getBody()->getNode());
return true;
};
plistener->onContactSeparate = [this](PhysicsContact& cont) {
cont.getShapeA()->getBody()->resetForces();
cont.getShapeB()->getBody()->resetForces();
this->onContactEnd(cont.getShapeA()->getBody()->getNode(), cont.getShapeB()->getBody()->getNode());
};
Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(plistener, this);
//add keyboard call back function
auto klistener = EventListenerKeyboard::create();
klistener->onKeyPressed = [player,this](EventKeyboard::KeyCode code, Event* event){
if (this->isMovable && player->getStatus() != Unit::Status::Jump) {
switch (code)
{
case EventKeyboard::KeyCode::KEY_A:
player->setDirection(Unit::Direction::Left);
player->move();
break;
case EventKeyboard::KeyCode::KEY_D:
player->setDirection(Unit::Direction::Right);
player->move();
break;
case EventKeyboard::KeyCode::KEY_S:
player->setDirection(Unit::Direction::Down);
player->move();
break;
case EventKeyboard::KeyCode::KEY_W:
player->setDirection(Unit::Direction::Up);
player->move();
break;
}
}
if (!player->getIsMoving()) {
switch (code)
{
case EventKeyboard::KeyCode::KEY_J:
//interact
if (!this->interact()) {
this->close();
}
break;
case EventKeyboard::KeyCode::KEY_L:
//fire
if (player->checkBulletReady()) {
player->fire();
this->fire();
}
break;
case EventKeyboard::KeyCode::KEY_K:
//jump
if (player->getStatus() != Unit::Status::Jump && player->hasCollection("plumage")) {
player->stop();
player->move(Unit::Status::Jump);
AudioEngine::play2d("music/jump.mp3", false, 0.5f);
}
break;
case EventKeyboard::KeyCode::KEY_ESCAPE:
//pause game
if (!isTransition) {
auto scene = PauseScene::createScene();
auto layer = dynamic_cast<PauseUILayer*>(scene->getChildByName("layer"));
layer->recievePlayerData(player);
Director::getInstance()->pushScene(dynamic_cast<Scene*>(this->getParent()));
Director::getInstance()->replaceScene(TransitionFade::create(0.5f, scene));
}
break;
}
}
};
klistener->onKeyReleased = [player](cocos2d::EventKeyboard::KeyCode code, cocos2d::Event* event) {
if (code == EventKeyboard::KeyCode::KEY_A || code == EventKeyboard::KeyCode::KEY_D
|| code == EventKeyboard::KeyCode::KEY_S || code == EventKeyboard::KeyCode::KEY_W) {
player->stop();
}
};
Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(klistener, this);
//add schedule
this->schedule(schedule_selector(GameLayer::check));
NotificationCenter::getInstance()->addObserver(this, callfuncO_selector(GameLayer::resume), "resume", nullptr);
return true;
}
void GameLayer::resume(Ref*) {
//restart all schedule
auto player = this->getChildByName("player");
player->unscheduleAllSelectors();
player->schedule(schedule_selector(Player::update));
player->schedule(schedule_selector(Player::blink));
auto map = this->getChildByName("map");
auto list = map->getChildren();
this->unscheduleAllSelectors();
this->schedule(schedule_selector(GameLayer::check));
for (auto node : list) {
if (node->getName().substr(0, 5) == "enemy") {
node->unscheduleAllSelectors();
node->schedule(schedule_selector(Enemy::update));
node->schedule(schedule_selector(Enemy::patrol));
}
}
}
void GameLayer::onContactBegin(cocos2d::Node* node1, cocos2d::Node* node2) {
if (node1 == nullptr || node2 == nullptr) {
return;
}
if (node2->getName() == "player" || node2->getName() == "bullet") {
std::swap(node1, node2);
}
if (node1->getName() == "player" && node2->getName() == "box") {
node2->setTag(this->interactingFlag);
this->isInteractable = true;
}
else if (node1->getName() == "player" && node2->getName() == "mov") {
auto player = dynamic_cast<Player*>(node1);
if (player->hasCollection("strengthGloove")) {
node2->setTag(this->movableFlag);
this->push();
}
}
else if (node1->getName() == "player" && node2->getName().substr(0, 5) == "enemy") {
auto enemy = dynamic_cast<Enemy*>(node2);
damageTaken += enemy->getDamage();
}
else if (node1->getName() == "player" && node2->getName() == "trans") {
auto pos = static_cast<std::pair<Vec2, Vec2>*>(node2->getUserData());
auto player = dynamic_cast<Player*>(node1);
player->setUserData(pos);
this->isTransition = true;
this->schedule(schedule_selector(GameLayer::turnOff));//turn off and make transition
}
else if (node1->getName() == "player" && node2->getName() == "door") {
auto player = dynamic_cast<Player*>(node1);
auto require = *static_cast<std::string*>(node2->getUserData());
//if have key required, open it; otherwise, let player find it
if (player->hasCollection(require)) {
auto map = dynamic_cast<MapManager*>(this->getChildByName("map"));
map->openDoor(node2->getPosition());
map->removeChild(node2);
AudioEngine::pause(bgmID);
AudioEngine::play2d("music/open.mp3", false, 0.5f);
AudioEngine::resumeAll();
}
else{
require = "You need:" + require + "*" + std::to_string(player->getPositionY());
auto msg = String::createWithData((const unsigned char*)(require.c_str()), require.length());
msg->retain();
NotificationCenter::getInstance()->postNotification("show", msg);
this->isMovable = false;
}
}
else if (node1->getName() == "player" && node2->getName() == "boss") {
if (currentLevel - 1 == Process::getInstance()->FileGet()) {
Process::getInstance()->FileModify();
}
Director::getInstance()->replaceScene(TransitionFade::create(0.5f, GameVictoryScene::createScene()));
}
else if (node1->getName() == "bullet" && node2->getName() != "player") {
if (node2->getName().substr(0, 5) == "enemy") {
auto player = dynamic_cast<Player*>(this->getChildByName("player"));
auto enemy = dynamic_cast<Enemy*>(node2);
if (enemy->hurt(player->getDamage())) {
auto map = this->getChildByName("map");
map->removeChild(node2);
}
}
this->removeChild(node1);
}
}
void GameLayer::turnOff(float) {
auto shadow = dynamic_cast<Sprite*>(this->getChildByName("shadow"));
shadow->setOpacity(shadow->getOpacity() + 5);
if (shadow->getOpacity() == 255) {
auto player = dynamic_cast<Player*>(this->getChildByName("player"));
auto pos = static_cast<std::pair<Vec2, Vec2>*>(player->getUserData());
auto map = dynamic_cast<MapManager*>(this->getChildByName("map"));
//reset map's and player's position
map->setPosition(map->getPositionX() + pos->first.x, map->getPositionY() + pos->first.y);
map->setOffset(pos->first);
player->setPosition(pos->second);
player->setOrigion(pos->second);
this->schedule(schedule_selector(GameLayer::turnOff));
this->unschedule(schedule_selector(GameLayer::turnOff));
this->schedule(schedule_selector(GameLayer::turnOn));
}
}
void GameLayer::turnOn(float) {
auto shadow = dynamic_cast<Sprite*>(this->getChildByName("shadow"));
shadow->setOpacity(shadow->getOpacity() - 5);
if (shadow->getOpacity() == 0) {
this->unschedule(schedule_selector(GameLayer::turnOn));
this->isTransition = false;
}
}
void GameLayer::onContactEnd(cocos2d::Node* node1, cocos2d::Node* node2){
if (node1 == nullptr || node2 == nullptr) {
return;
}
if (node2->getName() == "player") {
std::swap(node1, node2);
}
if (node1->getName() == "player" && node2->getName() == "box") {
node2->setTag(0);
this->isInteractable = false;
}
else if (node1->getName() == "player" && node2->getName() == "mov") {
node2->setTag(0);
}
else if (node1->getName() == "player" && node2->getName().substr(0, 5) == "enemy") {
auto enemy = dynamic_cast<Enemy*>(node2);
damageTaken -= enemy->getDamage();
}
}
bool GameLayer::interact() {
if (!this->isInteractable) {
return false;
}
auto visibleSize = Director::getInstance()->getVisibleSize();
auto map = dynamic_cast<MapManager*>(this->getChildByName("map"));
auto box = dynamic_cast<Sprite*>(map->getChildByTag(this->interactingFlag));
auto player = dynamic_cast<Player*>(this->getChildByName("player"));
box->setSpriteFrame(SpriteFrame::create("Game/boxOpen.png", Rect(0, 0, 64, 64)));
std::string content = *static_cast<std::string*>(box->getUserData());
auto offset = map->getOffset();
//there is something in the box
if (content != "") {
this->isMovable = false;
AudioEngine::pause(bgmID);
interactionID = AudioEngine::play2d("music/get.mp3", false, 0.5f);
std::string temp = content;
temp += "*";
temp += std::to_string(player->getPositionY());
auto msg = String::createWithData((const unsigned char*)(temp.c_str()), temp.length());
msg->retain();
NotificationCenter::getInstance()->postNotification("show", msg);
auto data = Config::getInstance()->getObject(content);
auto pic = Sprite::create(data.image_path);
pic->setScale(3, 3);
pic->setPosition(box->getPositionX() + offset.x, box->getPositionY() + offset.y + pic->getBoundingBox().size.height / 2);
pic->setName("temp");
this->addChild(pic, 1);
player->addCollection(content);
//clear the box
content = "";
box->setUserData(new std::string(content));
return true;
}
return false;
}
void GameLayer::push() {
auto map = dynamic_cast<MapManager*>(this->getChildByName("map"));
auto player = dynamic_cast<Player*>(this->getChildByName("player"));
auto mov = map->getChildByTag(movableFlag);
bool flag = false;
Vec2 next = mov->getPosition(), offset = map->getOffset();
switch(player->getDirection()) {
case Unit::Direction::Up:
flag = (player->getPositionY() - offset.y < mov->getPositionY() && abs(player->getPositionX() - offset.x - mov->getPositionX()) <= map->getTileSize() / 2);
next.y += map->getTileSize();
break;
case Unit::Direction::Down:
flag = (player->getPositionY() - offset.y > mov->getPositionY() && abs(player->getPositionX() - offset.x - mov->getPositionX()) <= map->getTileSize() / 2);
next.y -= map->getTileSize();
break;
case Unit::Direction::Left:
flag = (player->getPositionX() - offset.x > mov->getPositionX() && abs(player->getPositionY() - offset.y - mov->getPositionY()) <= map->getTileSize() / 2);
next.x -= map->getTileSize();
break;
case Unit::Direction::Right:
flag = (player->getPositionX() - offset.x < mov->getPositionX() && abs(player->getPositionY() - offset.y - mov->getPositionY()) <= map->getTileSize() / 2);
next.x += map->getTileSize();
break;
}
if (flag && map->isNull(next)) {
map->resetMovableObject(mov->getPosition(), next);
mov->setPosition(next);
mov->setName("");
mov->setTag(0);
}
}
void GameLayer::check(float dt) {
auto map = dynamic_cast<MapManager*>(this->getChildByName("map"));
auto player = dynamic_cast<Player*>(this->getChildByName("player"));
auto realPos = player->getPosition() - map->getOffset() - Vec2(0, player->getBoundingBox().size.height / 2);
bool hasHurted = false;
if (map->isHole(realPos)) {
if (player->getStatus() != Unit::Status::Jump) {
hasHurted = true;
}
}
//in the water
if (map->isWater(realPos)) {
if (player->hasCollection("fipperWebFoot")) {
if (player->getIsMoving()) {
player->stop();
player->move(Unit::Status::Swim);
}
else {
player->move(Unit::Status::Swim);
player->stop();
}
}
else {
hasHurted = true;
}
}
else if (player->getStatus() == Unit::Status::Swim)/*above a hole*/ {
player->stop();
player->move(Unit::Status::Stand);
}
if (hasHurted) {
this->isMovable = false;
player->move();
player->stop();
player->hurt(1);
player->resetPosition();
this->isMovable = true;
}
//dead, GG
if (player->hurt(damageTaken)) {
this->isMovable = false;
Director::getInstance()->replaceScene(SelectScene::createScene());
}
else if (damageTimer > 0) {
damageTimer -= dt;
}
else if (damageTaken > 0) {
if (damageTimer <= 0.0f) {
player->setProtection(true);
damageTimer = 1.0f;
}
}
if (damageTimer <= 0.0f) {
player->setProtection(false);
}
}
void GameLayer::fire() {
auto player = dynamic_cast<Player*>(this->getChildByName("player"));
Unit::Direction dir = player->getDirection();
auto bullet = Bullet::create();
bullet->setName("bullet");
auto size = player->getBoundingBox().size;
switch (dir)
{
case Unit::Up:
bullet->setVelocity(Vec2(0, 1));
bullet->setPosition(Vec2(player->getPositionX(), player->getPositionY() + size.height / 2));
break;
case Unit::Down:
bullet->setVelocity(Vec2(0, -1));
bullet->setPosition(Vec2(player->getPositionX(), player->getPositionY() - size.height / 2));
break;
case Unit::Left:
bullet->setVelocity(Vec2(-1, 0));
bullet->setPosition(Vec2(player->getPositionX() - size.width / 2, player->getPositionY()));
break;
case Unit::Right:
bullet->setVelocity(Vec2(1, 0));
bullet->setPosition(Vec2(player->getPositionX() + size.width / 2, player->getPositionY()));
break;
}
this->addChild(bullet, 2);
AudioEngine::pause(bgmID);
AudioEngine::play2d("music/fire.mp3", false, 0.5f);
AudioEngine::resumeAll();
}
void GameLayer::close() {
auto pic = this->getChildByName("temp");
this->isMovable = true;
NotificationCenter::getInstance()->postNotification("hide");
if (pic) {
this->removeChild(pic, true);
AudioEngine::stop(interactionID);
AudioEngine::resumeAll();
}
} | 30.054475 | 157 | 0.669666 | NeilKleistGao |
d49271aab644f8d38800109d637721cba882a027 | 11,956 | cpp | C++ | cmd/silkrpc_toolbox.cpp | enriavil1/silkrpc | 1fa2109658d4c89b6cfdd5190d919bd1324f367e | [
"Apache-2.0"
] | null | null | null | cmd/silkrpc_toolbox.cpp | enriavil1/silkrpc | 1fa2109658d4c89b6cfdd5190d919bd1324f367e | [
"Apache-2.0"
] | null | null | null | cmd/silkrpc_toolbox.cpp | enriavil1/silkrpc | 1fa2109658d4c89b6cfdd5190d919bd1324f367e | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2020-2021 The Silkrpc 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 <iostream>
#include <string>
#include <absl/flags/flag.h>
#include <absl/flags/parse.h>
#include <absl/flags/usage.h>
#include <silkworm/common/util.hpp>
#include <silkrpc/common/constants.hpp>
#include <silkrpc/common/log.hpp>
int ethbackend_async(const std::string& target);
int ethbackend_coroutines(const std::string& target);
int ethbackend(const std::string& target);
int kv_seek_async_callback(const std::string& target, const std::string& table_name, const silkworm::Bytes& key, uint32_t timeout);
int kv_seek_async_coroutines(const std::string& target, const std::string& table_name, const silkworm::Bytes& key, uint32_t timeout);
int kv_seek_async(const std::string& target, const std::string& table_name, const silkworm::Bytes& key, uint32_t timeout);
int kv_seek_both(const std::string& target, const std::string& table_name, const silkworm::Bytes& key, const silkworm::Bytes& subkey);
int kv_seek(const std::string& target, const std::string& table_name, const silkworm::Bytes& key);
ABSL_FLAG(std::string, key, "", "key as hex string w/o leading 0x");
ABSL_FLAG(silkrpc::LogLevel, logLevel, silkrpc::LogLevel::Critical, "logging level as string");
ABSL_FLAG(std::string, seekkey, "", "seek key as hex string w/o leading 0x");
ABSL_FLAG(std::string, subkey, "", "subkey as hex string w/o leading 0x");
ABSL_FLAG(std::string, tool, "", "gRPC remote interface tool name as string");
ABSL_FLAG(std::string, target, silkrpc::kDefaultTarget, "Erigon location as string <address>:<port>");
ABSL_FLAG(std::string, table, "", "database table name as string");
ABSL_FLAG(uint32_t, timeout, silkrpc::kDefaultTimeout.count(), "gRPC call timeout as integer");
int ethbackend_async(int argc, char* argv[]) {
auto target{absl::GetFlag(FLAGS_target)};
if (target.empty() || target.find(":") == std::string::npos) {
std::cerr << "Parameter target is invalid: [" << target << "]\n";
std::cerr << "Use --target flag to specify the location of Erigon running instance\n";
return -1;
}
return ethbackend_async(target);
}
int ethbackend_coroutines(int argc, char* argv[]) {
auto target{absl::GetFlag(FLAGS_target)};
if (target.empty() || target.find(":") == std::string::npos) {
std::cerr << "Parameter target is invalid: [" << target << "]\n";
std::cerr << "Use --target flag to specify the location of Erigon running instance\n";
return -1;
}
return ethbackend_coroutines(target);
}
int ethbackend(int argc, char* argv[]) {
auto target{absl::GetFlag(FLAGS_target)};
if (target.empty() || target.find(":") == std::string::npos) {
std::cerr << "Parameter target is invalid: [" << target << "]\n";
std::cerr << "Use --target flag to specify the location of Erigon running instance\n";
return -1;
}
return ethbackend(target);
}
int kv_seek_async_callback(int argc, char* argv[]) {
auto target{absl::GetFlag(FLAGS_target)};
if (target.empty() || target.find(":") == std::string::npos) {
std::cerr << "Parameter target is invalid: [" << target << "]\n";
std::cerr << "Use --target flag to specify the location of Erigon running instance\n";
return -1;
}
auto table_name{absl::GetFlag(FLAGS_table)};
if (table_name.empty()) {
std::cerr << "Parameter table is invalid: [" << table_name << "]\n";
std::cerr << "Use --table flag to specify the name of Erigon database table\n";
return -1;
}
auto key{absl::GetFlag(FLAGS_key)};
const auto key_bytes = silkworm::from_hex(key);
if (key.empty() || !key_bytes.has_value()) {
std::cerr << "Parameter key is invalid: [" << key << "]\n";
std::cerr << "Use --key flag to specify the key in key-value dupsort table\n";
return -1;
}
auto timeout{absl::GetFlag(FLAGS_timeout)};
if (timeout < 0) {
std::cerr << "Parameter timeout is invalid: [" << timeout << "]\n";
std::cerr << "Use --timeout flag to specify the timeout in msecs for Erigon KV gRPC calls\n";
return -1;
}
return kv_seek_async_callback(target, table_name, key_bytes.value(), timeout);
}
int kv_seek_async_coroutines(int argc, char* argv[]) {
auto target{absl::GetFlag(FLAGS_target)};
if (target.empty() || target.find(":") == std::string::npos) {
std::cerr << "Parameter target is invalid: [" << target << "]\n";
std::cerr << "Use --target flag to specify the location of Erigon running instance\n";
return -1;
}
auto table_name{absl::GetFlag(FLAGS_table)};
if (table_name.empty()) {
std::cerr << "Parameter table is invalid: [" << table_name << "]\n";
std::cerr << "Use --table flag to specify the name of Erigon database table\n";
return -1;
}
auto key{absl::GetFlag(FLAGS_key)};
const auto key_bytes = silkworm::from_hex(key);
if (key.empty() || !key_bytes.has_value()) {
std::cerr << "Parameter key is invalid: [" << key << "]\n";
std::cerr << "Use --key flag to specify the key in key-value dupsort table\n";
return -1;
}
auto timeout{absl::GetFlag(FLAGS_timeout)};
if (timeout < 0) {
std::cerr << "Parameter timeout is invalid: [" << timeout << "]\n";
std::cerr << "Use --timeout flag to specify the timeout in msecs for Erigon KV gRPC calls\n";
return -1;
}
return kv_seek_async_coroutines(target, table_name, key_bytes.value(), timeout);
}
int kv_seek_async(int argc, char* argv[]) {
auto target{absl::GetFlag(FLAGS_target)};
if (target.empty() || target.find(":") == std::string::npos) {
std::cerr << "Parameter target is invalid: [" << target << "]\n";
std::cerr << "Use --target flag to specify the location of Erigon running instance\n";
return -1;
}
auto table_name{absl::GetFlag(FLAGS_table)};
if (table_name.empty()) {
std::cerr << "Parameter table is invalid: [" << table_name << "]\n";
std::cerr << "Use --table flag to specify the name of Erigon database table\n";
return -1;
}
auto key{absl::GetFlag(FLAGS_key)};
const auto key_bytes = silkworm::from_hex(key);
if (key.empty() || !key_bytes.has_value()) {
std::cerr << "Parameter key is invalid: [" << key << "]\n";
std::cerr << "Use --key flag to specify the key in key-value dupsort table\n";
return -1;
}
auto timeout{absl::GetFlag(FLAGS_timeout)};
if (timeout < 0) {
std::cerr << "Parameter timeout is invalid: [" << timeout << "]\n";
std::cerr << "Use --timeout flag to specify the timeout in msecs for Erigon KV gRPC calls\n";
return -1;
}
return kv_seek_async(target, table_name, key_bytes.value(), timeout);
}
int kv_seek_both(int argc, char* argv[]) {
auto target{absl::GetFlag(FLAGS_target)};
if (target.empty() || target.find(":") == std::string::npos) {
std::cerr << "Parameter target is invalid: [" << target << "]\n";
std::cerr << "Use --target flag to specify the location of Erigon running instance\n";
return -1;
}
auto table_name{absl::GetFlag(FLAGS_table)};
if (table_name.empty()) {
std::cerr << "Parameter table is invalid: [" << table_name << "]\n";
std::cerr << "Use --table flag to specify the name of Erigon database table\n";
return -1;
}
auto key{absl::GetFlag(FLAGS_key)};
const auto key_bytes = silkworm::from_hex(key);
if (key.empty() || !key_bytes.has_value()) {
std::cerr << "Parameter key is invalid: [" << key << "]\n";
std::cerr << "Use --key flag to specify the key in key-value dupsort table\n";
return -1;
}
auto subkey{absl::GetFlag(FLAGS_subkey)};
const auto subkey_bytes = silkworm::from_hex(subkey);
if (subkey.empty() || !subkey_bytes.has_value()) {
std::cerr << "Parameter subkey is invalid: [" << subkey << "]\n";
std::cerr << "Use --subkey flag to specify the subkey in key-value dupsort table\n";
return -1;
}
return kv_seek_both(target, table_name, key_bytes.value(), subkey_bytes.value());
}
int kv_seek(int argc, char* argv[]) {
auto target{absl::GetFlag(FLAGS_target)};
if (target.empty() || target.find(":") == std::string::npos) {
std::cerr << "Parameter target is invalid: [" << target << "]\n";
std::cerr << "Use --target flag to specify the location of Erigon running instance\n";
return -1;
}
auto table_name{absl::GetFlag(FLAGS_table)};
if (table_name.empty()) {
std::cerr << "Parameter table is invalid: [" << table_name << "]\n";
std::cerr << "Use --table flag to specify the name of Erigon database table\n";
return -1;
}
auto key{absl::GetFlag(FLAGS_key)};
const auto key_bytes = silkworm::from_hex(key);
if (key.empty() || !key_bytes.has_value()) {
std::cerr << "Parameter key is invalid: [" << key << "]\n";
std::cerr << "Use --key flag to specify the key in key-value dupsort table\n";
return -1;
}
return kv_seek(target, table_name, key_bytes.value());
}
int main(int argc, char* argv[]) {
absl::SetProgramUsageMessage("Execute specified Silkrpc tool:\n"
"\tethbackend\t\t\tquery the Erigon/Silkworm ETHBACKEND remote interface\n"
"\tethbackend_async\t\tquery the Erigon/Silkworm ETHBACKEND remote interface\n"
"\tethbackend_coroutines\t\tquery the Erigon/Silkworm ETHBACKEND remote interface\n"
"\tkv_seek\t\t\t\tquery using SEEK the Erigon/Silkworm Key-Value (KV) remote interface to database\n"
"\tkv_seek_async\t\t\tquery using SEEK the Erigon/Silkworm Key-Value (KV) remote interface to database\n"
"\tkv_seek_async_callback\t\tquery using SEEK the Erigon/Silkworm Key-Value (KV) remote interface to database\n"
"\tkv_seek_async_coroutines\tquery using SEEK the Erigon/Silkworm Key-Value (KV) remote interface to database\n"
"\tkv_seek_both\t\t\tquery using SEEK_BOTH the Erigon/Silkworm Key-Value (KV) remote interface to database\n"
);
const auto positional_args = absl::ParseCommandLine(argc, argv);
if (positional_args.size() < 2) {
std::cerr << "No Silkrpc tool specified as first positional argument\n\n";
std::cerr << absl::ProgramUsageMessage();
return -1;
}
SILKRPC_LOG_VERBOSITY(absl::GetFlag(FLAGS_logLevel));
const std::string tool{positional_args[1]};
if (tool == "ethbackend_async") {
return ethbackend_async(argc, argv);
}
if (tool == "ethbackend_coroutines") {
return ethbackend_coroutines(argc, argv);
}
if (tool == "ethbackend") {
return ethbackend(argc, argv);
}
if (tool == "kv_seek_async_callback") {
return kv_seek_async_callback(argc, argv);
}
if (tool == "kv_seek_async_coroutines") {
return kv_seek_async_coroutines(argc, argv);
}
if (tool == "kv_seek_async") {
return kv_seek_async(argc, argv);
}
if (tool == "kv_seek_both") {
return kv_seek_both(argc, argv);
}
if (tool == "kv_seek") {
return kv_seek(argc, argv);
}
std::cerr << "Unknown tool " << tool << " specified as first argument\n\n";
std::cerr << absl::ProgramUsageMessage();
return -1;
}
| 41.513889 | 134 | 0.640683 | enriavil1 |
d49658b46836b6b2620117739b0a4e5e9eb6a2cb | 836 | cpp | C++ | tests/math_unit/math/rev/scal/fun/digamma_test.cpp | alashworth/stan-monorepo | 75596bc1f860ededd7b3e9ae9002aea97ee1cd46 | [
"BSD-3-Clause"
] | 1 | 2019-09-06T15:53:17.000Z | 2019-09-06T15:53:17.000Z | tests/math_unit/math/rev/scal/fun/digamma_test.cpp | alashworth/stan-monorepo | 75596bc1f860ededd7b3e9ae9002aea97ee1cd46 | [
"BSD-3-Clause"
] | 8 | 2019-01-17T18:51:16.000Z | 2019-01-17T18:51:39.000Z | tests/math_unit/math/rev/scal/fun/digamma_test.cpp | alashworth/stan-monorepo | 75596bc1f860ededd7b3e9ae9002aea97ee1cd46 | [
"BSD-3-Clause"
] | null | null | null | #include <stan/math/rev/scal.hpp>
#include <gtest/gtest.h>
#include <math/rev/scal/fun/nan_util.hpp>
#include <math/rev/scal/util.hpp>
#include <boost/math/special_functions/digamma.hpp>
#include <boost/math/special_functions/zeta.hpp>
TEST(AgradRev, digamma) {
AVAR a = 0.5;
AVAR f = digamma(a);
EXPECT_FLOAT_EQ(boost::math::digamma(0.5), f.val());
AVEC x = createAVEC(a);
VEC grad_f;
f.grad(x, grad_f);
EXPECT_FLOAT_EQ(4.9348022005446793094, grad_f[0]);
}
namespace {
struct digamma_fun {
template <typename T0>
inline T0 operator()(const T0& arg1) const {
return digamma(arg1);
}
};
} // namespace
TEST(AgradRev, digamma_NaN) {
digamma_fun digamma_;
test_nan(digamma_, false, true);
}
TEST(AgradRev, check_varis_on_stack_10) {
AVAR a = 0.5;
test::check_varis_on_stack(stan::math::digamma(a));
}
| 22.594595 | 54 | 0.704545 | alashworth |
d4982752bd910ed943446ff44ad77194d44a0566 | 208 | cpp | C++ | LeetCode/9.cpp | LauZyHou/- | 66c047fe68409c73a077eae561cf82b081cf8e45 | [
"MIT"
] | 7 | 2019-02-25T13:15:00.000Z | 2021-12-21T22:08:39.000Z | LeetCode/9.cpp | LauZyHou/- | 66c047fe68409c73a077eae561cf82b081cf8e45 | [
"MIT"
] | null | null | null | LeetCode/9.cpp | LauZyHou/- | 66c047fe68409c73a077eae561cf82b081cf8e45 | [
"MIT"
] | 1 | 2019-04-03T06:12:46.000Z | 2019-04-03T06:12:46.000Z | class Solution {
public:
bool isPalindrome(int x) {
string s = to_string(x);
int len = s.size();
for(int i=0;i<len/2;i++){
if(s[i]!=s[len-i-1])
return false;
}
return true;
}
}; | 17.333333 | 32 | 0.538462 | LauZyHou |
d49a88af357d8cbe7924edd00ab4b2f556ee786b | 2,238 | tcc | C++ | phpcxx/fcall.tcc | sjinks/php-cxx | c519f841c2d7122bcf02db7d43a109a6ec818e1d | [
"MIT"
] | 5 | 2017-02-26T23:55:20.000Z | 2019-10-12T04:04:38.000Z | phpcxx/fcall.tcc | sjinks/php-cxx | c519f841c2d7122bcf02db7d43a109a6ec818e1d | [
"MIT"
] | 25 | 2017-03-18T07:03:42.000Z | 2018-03-28T21:33:57.000Z | phpcxx/fcall.tcc | sjinks/php-cxx | c519f841c2d7122bcf02db7d43a109a6ec818e1d | [
"MIT"
] | 1 | 2017-03-18T07:27:25.000Z | 2017-03-18T07:27:25.000Z | #ifndef PHPCXX_FCALL_TCC
#define PHPCXX_FCALL_TCC
#ifndef PHPCXX_FCALL_H
#error "Please do not include this file directly, use fcall.h instead"
#endif
#include "array.h"
#include "value.h"
#include "bailoutrestorer.h"
namespace {
/**
* @internal
* @brief Helper function for codecov (`_zend_bailout` is for some reason not marked as `noreturn`)
* @param filename
* @param line
*/
[[noreturn]] static inline void bailout(const char* filename, long int line)
{
_zend_bailout(const_cast<char*>(filename), line);
ZEND_ASSUME(0);
}
}
namespace phpcxx {
template<typename... Params>
static Value call(const char* name, Params&&... p)
{
{
BailoutRestorer br;
JMP_BUF bailout;
FCall call(name);
EG(bailout) = &bailout;
if (EXPECTED(0 == SETJMP(bailout))) {
return call(std::forward<Params>(p)...);
}
}
bailout(__FILE__, __LINE__);
}
template<typename... Params>
static Value call(const Value& v, Params&&... p)
{
{
BailoutRestorer br;
JMP_BUF bailout;
FCall call(v.pzval());
EG(bailout) = &bailout;
if (EXPECTED(0 == SETJMP(bailout))) {
return call(std::forward<Params>(p)...);
}
}
bailout(__FILE__, __LINE__);
}
/**
* @brief Constructs `zval` from `phpcxx::Value`
* @param[in] v `phpcxx::Value`
* @return Pointer to `zval`
*/
template<> [[gnu::returns_nonnull]] inline zval* FCall::paramHelper(phpcxx::Value&& v, zval&) { return v.pzval(); }
/**
* @brief Constructs `zval` from `phpcxx::Array`
* @param[in] v `phpcxx::Array`
* @return Pointer to `zval`
*/
template<> [[gnu::returns_nonnull]] inline zval* FCall::paramHelper(phpcxx::Array&& v, zval&) { return v.pzval(); }
template<typename... Params>
inline phpcxx::Value FCall::operator()(Params&&... p)
{
return this->call(IndicesFor<Params...>{}, std::forward<Params>(p)...);
}
template<typename ...Args, std::size_t ...Is>
inline Value FCall::call(indices<Is...>, Args&&... args)
{
zval zparams[sizeof...(args) ? sizeof...(args) : sizeof...(args) + 1] = { *FCall::paramHelper(std::move(args), zparams[Is])... };
return this->operator()(sizeof...(args), zparams);
}
}
#endif /* PHPCXX_FCALL_TCC */
| 24.064516 | 133 | 0.628686 | sjinks |
d49dad27fbea319edc48a645c96ae9e0fae77241 | 2,839 | cpp | C++ | src/Game/main.cpp | Gegel85/THFgame | 89b2508ac8564274c26db0f45f7fab4876badb5d | [
"MIT"
] | null | null | null | src/Game/main.cpp | Gegel85/THFgame | 89b2508ac8564274c26db0f45f7fab4876badb5d | [
"MIT"
] | null | null | null | src/Game/main.cpp | Gegel85/THFgame | 89b2508ac8564274c26db0f45f7fab4876badb5d | [
"MIT"
] | 1 | 2019-11-18T22:05:10.000Z | 2019-11-18T22:05:10.000Z | #include "../Core/Resources/Game.hpp"
#include "../Core/Resources/Logger.hpp"
#include "../Core/Loading/Loader.hpp"
#include "../Core/Menus/MenuMgr.hpp"
#include "../Core/Exceptions.hpp"
#include "../Core/Utils/Utils.hpp"
#include "Menus/MainMenu.hpp"
#include "Menus/InGameMenu.hpp"
#include "Menus/InventoryMenu.hpp"
#ifdef _WIN32
#include <windows.h>
#include <direct.h>
#else
#include <unistd.h>
#endif
namespace TouhouFanGame
{
//! @brief The global logger
Logger logger{"./latest.log", Logger::LOG_DEBUG};
void setup(Game &game)
{
logger.debug("Opening main window");
game.resources.screen.reset(new Rendering::Screen{game.resources, "THFgame"});
game.state.menuMgr.addMenu<MainMenu>("main_menu", game.state.map, game.resources, game.state.hud);
game.state.menuMgr.addMenu<InGameMenu>("in_game", game, game.state.map, game.state.hud, *game.resources.screen);
game.state.menuMgr.addMenu<InventoryMenu>("inventory", game, game.state.map, game.state.hud, *game.resources.screen, game.resources.textures);
}
//! @brief The game loop
void gameLoop(Game &game)
{
sf::Event event;
game.state.menuMgr.changeMenu("main_menu");
while (game.resources.screen->isOpen()) {
game.resources.screen->clear();
while (game.resources.screen->pollEvent(event))
if (event.type == sf::Event::Closed)
game.resources.screen->close();
for (auto e = game.state.settings.input->pollEvent(); e; e = game.state.settings.input->pollEvent())
game.state.menuMgr.handleEvent(*e);
game.state.menuMgr.renderMenu();
game.resources.screen->display();
}
}
void run()
{
Game game;
//TODO: Add proper font loading.
#ifndef _DEBUG
try {
#endif
logger.info("Setting up...");
setup(game);
game.resources.font.loadFromFile("assets/arial.ttf");
game.resources.screen->setFont(game.resources.font);
logger.info("Loading assets...");
Loader::loadAssets(game);
logger.info("Starting game.");
gameLoop(game);
#ifndef _DEBUG
} catch (std::exception &e) {
logger.fatal(getLastExceptionName() + ": " + e.what());
Utils::dispMsg(
"Fatal Error",
"An unrecoverable error occurred\n\n" +
getLastExceptionName() + ":\n" + e.what() + "\n\n"
"Click OK to close the application",
MB_ICONERROR
);
throw;
}
#endif
logger.info("Goodbye !");
}
}
int main(int, char **argv)
{
std::string progPath = argv[0];
size_t occurence =
#ifdef _WIN32
progPath.find_last_of('\\');
#else
progPath.find_last_of('/');
#endif
if (occurence != std::string::npos)
chdir(progPath.substr(0, occurence).c_str());
else
TouhouFanGame::logger.warn("Cannot find program path from argv (" + progPath + ")");
#ifndef _DEBUG
try {
#endif
TouhouFanGame::run();
#ifndef _DEBUG
} catch (std::exception &) {
return EXIT_FAILURE;
}
#endif
return EXIT_SUCCESS;
}
| 24.474138 | 144 | 0.682987 | Gegel85 |
d49f7b41346bf9acb7b3d683c824f176ca38aca6 | 1,481 | cpp | C++ | set1/repeat_key_xor_test.cpp | guzhoucan/cryptopals | a45280158867a86b5d8c61bf7194277d05abdf14 | [
"MIT"
] | 1 | 2020-08-07T22:38:27.000Z | 2020-08-07T22:38:27.000Z | set1/repeat_key_xor_test.cpp | guzhoucan/cryptopals | a45280158867a86b5d8c61bf7194277d05abdf14 | [
"MIT"
] | null | null | null | set1/repeat_key_xor_test.cpp | guzhoucan/cryptopals | a45280158867a86b5d8c61bf7194277d05abdf14 | [
"MIT"
] | null | null | null | #include "repeat_key_xor.h"
#include <fstream>
#include "absl/strings/escaping.h"
#include "gtest/gtest.h"
namespace cryptopals {
namespace {
TEST(RepeatKeyXorTest, RepeatKeyXorEncode) {
std::string key = "ICE";
std::string plaintext =
"Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a "
"cymbal";
std::string ciphertext = RepeatKeyXorEncode(plaintext, key);
EXPECT_EQ(
"0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765"
"272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27"
"282f",
absl::BytesToHexString(ciphertext));
}
TEST(RepeatKeyXorTest, GetHammingDistance) {
std::string str1 = "this is a test";
std::string str2 = "wokka wokka!!!";
EXPECT_EQ(37, GetHammingDistance(str1, str2));
}
TEST(RepeatKeyXorTest, BreakRepeatKeyXor) {
std::ifstream file("break_repeat_key_xor.txt",
std::ios::in | std::ios::binary);
ASSERT_TRUE(file.is_open());
std::stringstream ss;
ss << file.rdbuf();
std::string ciphertext_base64 = ss.str();
file.close();
std::string ciphertext;
ASSERT_TRUE(absl::Base64Unescape(ciphertext_base64, &ciphertext));
BreakRepeatKeyXorOutput output = BreakRepeatKeyXor(ciphertext);
EXPECT_EQ("I'm back and I'm ringin' the bell ",
output.plaintext.substr(0, output.plaintext.find('\n')));
EXPECT_EQ("Terminator X: Bring the noise", output.key);
}
} // namespace
} // namespace cryptopals | 30.854167 | 80 | 0.713032 | guzhoucan |
d4a03b833995edadf3870c0ab6fb12ddb9534388 | 1,151 | hpp | C++ | src/Logic/JFIFRewriter.hpp | vividos/RemotePhotoTool | d17ae2abbda531acbd0ec8e90ddc4856c4fdfa00 | [
"BSD-2-Clause"
] | 16 | 2015-03-26T02:32:43.000Z | 2021-10-18T16:34:31.000Z | src/Logic/JFIFRewriter.hpp | vividos/RemotePhotoTool | d17ae2abbda531acbd0ec8e90ddc4856c4fdfa00 | [
"BSD-2-Clause"
] | 7 | 2019-02-21T06:07:09.000Z | 2022-01-01T10:00:50.000Z | src/Logic/JFIFRewriter.hpp | vividos/RemotePhotoTool | d17ae2abbda531acbd0ec8e90ddc4856c4fdfa00 | [
"BSD-2-Clause"
] | 6 | 2019-05-07T09:21:15.000Z | 2021-09-01T06:36:24.000Z | //
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2018 Michael Fink
//
/// \file JFIFRewriter.hpp JFIF (JPEG File Interchange Format) rewriter
//
#pragma once
// includes
#include <ulib/stream/IStream.hpp>
/// \brief JFIF rewriter
/// Loads JFIF data stream (used internally by JPEG images) and calls OnBlock() when a new block
/// arrives. Derived classes can then choose to re-write that block, e.g. EXIF data.
class JFIFRewriter
{
public:
/// ctor
JFIFRewriter(Stream::IStream& streamIn, Stream::IStream& streamOut)
:m_streamIn(streamIn), m_streamOut(streamOut)
{
}
/// starts rewriting process
void Start();
/// JFIF block marker
enum T_JFIFBlockMarker
{
SOI = 0xd8,
EOI = 0xd9,
APP0 = 0xe0,
APP1 = 0xe1, ///< Exif data is store in this block
DQT = 0xdb,
SOF0 = 0xc0,
DHT = 0xc4,
SOS = 0xda,
};
protected:
/// called when the next JFIF block is starting
virtual void OnBlock(BYTE marker, WORD length);
protected:
Stream::IStream& m_streamIn; ///< input stream
Stream::IStream& m_streamOut; ///< output stream
};
| 23.979167 | 96 | 0.658558 | vividos |
d4a0b39ea7a1e18149b9e420fe6231854b636669 | 8,625 | cpp | C++ | examples/ota-provider-app/ota-provider-common/OTAProviderExample.cpp | jimlyall-q/connectedhomeip | e4d15a802e663f1f2ed7b8205f027d30e447eb0e | [
"Apache-2.0"
] | 19 | 2021-02-17T12:31:28.000Z | 2022-03-24T09:15:43.000Z | examples/ota-provider-app/ota-provider-common/OTAProviderExample.cpp | jimlyall-q/connectedhomeip | e4d15a802e663f1f2ed7b8205f027d30e447eb0e | [
"Apache-2.0"
] | 18 | 2021-06-01T20:01:19.000Z | 2022-03-11T09:43:52.000Z | examples/ota-provider-app/ota-provider-common/OTAProviderExample.cpp | jimlyall-q/connectedhomeip | e4d15a802e663f1f2ed7b8205f027d30e447eb0e | [
"Apache-2.0"
] | 14 | 2020-12-14T11:05:45.000Z | 2022-03-29T08:42:30.000Z | /*
*
* Copyright (c) 2021 Project CHIP Authors
* All rights reserved.
*
* 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 <ota-provider-common/OTAProviderExample.h>
#include <app-common/zap-generated/cluster-id.h>
#include <app-common/zap-generated/command-id.h>
#include <app/CommandPathParams.h>
#include <app/clusters/ota-provider/ota-provider-delegate.h>
#include <app/util/af.h>
#include <lib/core/CHIPTLV.h>
#include <lib/support/CHIPMemString.h>
#include <lib/support/RandUtils.h>
#include <protocols/secure_channel/PASESession.h> // For chip::kTestDeviceNodeId
#include <string.h>
using chip::ByteSpan;
using chip::Span;
using chip::app::CommandPathFlags;
using chip::app::CommandPathParams;
using chip::app::clusters::OTAProviderDelegate;
using chip::TLV::ContextTag;
using chip::TLV::TLVWriter;
constexpr uint8_t kUpdateTokenLen = 32; // must be between 8 and 32
constexpr uint8_t kUpdateTokenStrLen = kUpdateTokenLen * 2 + 1; // Hex string needs 2 hex chars for every byte
constexpr size_t kUriMaxLen = 256;
void GetUpdateTokenString(const chip::ByteSpan & token, char * buf, size_t bufSize)
{
const uint8_t * tokenData = static_cast<const uint8_t *>(token.data());
size_t minLength = chip::min(token.size(), bufSize);
for (size_t i = 0; i < (minLength / 2) - 1; ++i)
{
snprintf(&buf[i * 2], bufSize, "%02X", tokenData[i]);
}
}
void GenerateUpdateToken(uint8_t * buf, size_t bufSize)
{
for (size_t i = 0; i < bufSize; ++i)
{
buf[i] = chip::GetRandU8();
}
}
bool GenerateBdxUri(const Span<char> & fileDesignator, Span<char> outUri, size_t availableSize)
{
static constexpr char bdxPrefix[] = "bdx://";
chip::NodeId nodeId = chip::kTestDeviceNodeId; // TODO: read this dynamically
size_t nodeIdHexStrLen = sizeof(nodeId) * 2;
size_t expectedLength = strlen(bdxPrefix) + nodeIdHexStrLen + fileDesignator.size();
if (expectedLength >= availableSize)
{
return false;
}
size_t written = static_cast<size_t>(snprintf(outUri.data(), availableSize, "%s" ChipLogFormatX64 "%s", bdxPrefix,
ChipLogValueX64(nodeId), fileDesignator.data()));
return expectedLength == written;
}
OTAProviderExample::OTAProviderExample()
{
memset(mOTAFilePath, 0, kFilepathBufLen);
}
void OTAProviderExample::SetOTAFilePath(const char * path)
{
if (path != nullptr)
{
chip::Platform::CopyString(mOTAFilePath, path);
}
else
{
memset(mOTAFilePath, 0, kFilepathBufLen);
}
}
EmberAfStatus OTAProviderExample::HandleQueryImage(chip::app::CommandHandler * commandObj, uint16_t vendorId, uint16_t productId,
uint16_t imageType, uint16_t hardwareVersion, uint32_t currentVersion,
uint8_t protocolsSupported, const chip::Span<const char> & location,
bool clientCanConsent, const chip::ByteSpan & metadataForServer)
{
// TODO: add confiuration for returning BUSY status
EmberAfOTAQueryStatus queryStatus =
(strlen(mOTAFilePath) ? EMBER_ZCL_OTA_QUERY_STATUS_UPDATE_AVAILABLE : EMBER_ZCL_OTA_QUERY_STATUS_NOT_AVAILABLE);
uint32_t delayedActionTimeSec = 0;
uint32_t softwareVersion = currentVersion + 1; // This implementation will always indicate that an update is available
// (if the user provides a file).
bool userConsentNeeded = false;
uint8_t updateToken[kUpdateTokenLen] = { 0 };
char strBuf[kUpdateTokenStrLen] = { 0 };
char uriBuf[kUriMaxLen] = { 0 };
GenerateUpdateToken(updateToken, kUpdateTokenLen);
GetUpdateTokenString(ByteSpan(updateToken), strBuf, kUpdateTokenStrLen);
ChipLogDetail(SoftwareUpdate, "generated updateToken: %s", strBuf);
if (strlen(mOTAFilePath))
{
// Only doing BDX transport for now
GenerateBdxUri(Span<char>(mOTAFilePath, strlen(mOTAFilePath)), Span<char>(uriBuf, 0), kUriMaxLen);
ChipLogDetail(SoftwareUpdate, "generated URI: %s", uriBuf);
}
CommandPathParams cmdParams = { emberAfCurrentEndpoint(), 0 /* mGroupId */, ZCL_OTA_PROVIDER_CLUSTER_ID,
ZCL_QUERY_IMAGE_RESPONSE_COMMAND_ID, (CommandPathFlags::kEndpointIdValid) };
TLVWriter * writer = nullptr;
uint8_t tagNum = 0;
VerifyOrReturnError((commandObj->PrepareCommand(cmdParams) == CHIP_NO_ERROR), EMBER_ZCL_STATUS_FAILURE);
VerifyOrReturnError((writer = commandObj->GetCommandDataElementTLVWriter()) != nullptr, EMBER_ZCL_STATUS_FAILURE);
VerifyOrReturnError(writer->Put(ContextTag(tagNum++), queryStatus) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE);
VerifyOrReturnError(writer->Put(ContextTag(tagNum++), delayedActionTimeSec) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE);
VerifyOrReturnError(writer->PutString(ContextTag(tagNum++), uriBuf) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE);
VerifyOrReturnError(writer->Put(ContextTag(tagNum++), softwareVersion) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE);
VerifyOrReturnError(writer->PutBytes(ContextTag(tagNum++), updateToken, kUpdateTokenLen) == CHIP_NO_ERROR,
EMBER_ZCL_STATUS_FAILURE);
VerifyOrReturnError(writer->Put(ContextTag(tagNum++), userConsentNeeded) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE);
VerifyOrReturnError(writer->PutBytes(ContextTag(tagNum++), updateToken, kUpdateTokenLen) == CHIP_NO_ERROR,
EMBER_ZCL_STATUS_FAILURE); // metadata
VerifyOrReturnError((commandObj->FinishCommand() == CHIP_NO_ERROR), EMBER_ZCL_STATUS_FAILURE);
return EMBER_ZCL_STATUS_SUCCESS;
}
EmberAfStatus OTAProviderExample::HandleApplyUpdateRequest(chip::app::CommandHandler * commandObj,
const chip::ByteSpan & updateToken, uint32_t newVersion)
{
// TODO: handle multiple transfers by tracking updateTokens
// TODO: add configuration for sending different updateAction and delayedActionTime values
EmberAfOTAApplyUpdateAction updateAction = EMBER_ZCL_OTA_APPLY_UPDATE_ACTION_PROCEED; // For now, just allow any update request
uint32_t delayedActionTimeSec = 0;
char tokenBuf[kUpdateTokenStrLen] = { 0 };
GetUpdateTokenString(updateToken, tokenBuf, kUpdateTokenStrLen);
ChipLogDetail(SoftwareUpdate, "%s: token: %s, version: %" PRIu32, __FUNCTION__, tokenBuf, newVersion);
VerifyOrReturnError(commandObj != nullptr, EMBER_ZCL_STATUS_INVALID_VALUE);
CommandPathParams cmdParams = { emberAfCurrentEndpoint(), 0 /* mGroupId */, ZCL_OTA_PROVIDER_CLUSTER_ID,
ZCL_APPLY_UPDATE_REQUEST_RESPONSE_COMMAND_ID, (CommandPathFlags::kEndpointIdValid) };
TLVWriter * writer = nullptr;
VerifyOrReturnError((commandObj->PrepareCommand(cmdParams) == CHIP_NO_ERROR), EMBER_ZCL_STATUS_FAILURE);
VerifyOrReturnError((writer = commandObj->GetCommandDataElementTLVWriter()) != nullptr, EMBER_ZCL_STATUS_FAILURE);
VerifyOrReturnError(writer->Put(ContextTag(0), updateAction) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE);
VerifyOrReturnError(writer->Put(ContextTag(1), delayedActionTimeSec) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE);
VerifyOrReturnError((commandObj->FinishCommand() == CHIP_NO_ERROR), EMBER_ZCL_STATUS_FAILURE);
return EMBER_ZCL_STATUS_SUCCESS;
}
EmberAfStatus OTAProviderExample::HandleNotifyUpdateApplied(const chip::ByteSpan & updateToken, uint32_t currentVersion)
{
char tokenBuf[kUpdateTokenStrLen] = { 0 };
GetUpdateTokenString(updateToken, tokenBuf, kUpdateTokenStrLen);
ChipLogDetail(SoftwareUpdate, "%s: token: %s, version: %" PRIu32, __FUNCTION__, tokenBuf, currentVersion);
emberAfSendImmediateDefaultResponse(EMBER_ZCL_STATUS_SUCCESS);
return EMBER_ZCL_STATUS_SUCCESS;
}
| 46.621622 | 131 | 0.69971 | jimlyall-q |
d4a57b90242ad005cd0d4e131c51c569828f1b18 | 1,155 | cpp | C++ | 01-list/LinkList/LinkListTest.cpp | lcl0512/cs_kaoyan | 4ff5aa32fc7c91bea29504664e5498f166bc5e4d | [
"MIT"
] | 3 | 2021-03-31T08:22:16.000Z | 2021-07-12T01:25:46.000Z | 01-list/LinkList/LinkListTest.cpp | lcl0512/cs_kaoyan | 4ff5aa32fc7c91bea29504664e5498f166bc5e4d | [
"MIT"
] | null | null | null | 01-list/LinkList/LinkListTest.cpp | lcl0512/cs_kaoyan | 4ff5aa32fc7c91bea29504664e5498f166bc5e4d | [
"MIT"
] | null | null | null | #include "LinkList.h"
#include <cstdio>
int main()
{
LinkList L1,L2;
List_HeadInsert(L1);
printf("-------头插法-------\n");
Print_LinkList(L1);
printf("\n");
List_TrailInsert(L2);
printf("-------尾插法-------\n");
Print_LinkList(L2);
printf("\n");
/*按序号查找结点值*/
LNode* p = GetElem(L1, 4);
printf("第%d个结点是%d\n", 4, p->data);
/*按值查找结点 */
ElemType e;
p = LocateElem(L1, 4);
printf("查找结点是%d\n", p->data);
printf("\n-------原数据-------\n");
Print_LinkList(L2);
printf("\n");
/*向一个结点后插入结点*/
Insert(L2, 4, 99);
printf("-------向第4个结点后插入99-------\n");
Print_LinkList(L2);
printf("\n");
/*向一个结点前插入结点*/
Insert_Prev(L2, 7, 77);
printf("-------向第7个结点前插入77-------\n");
Print_LinkList(L2);
printf("\n");
/*按序号删除结点,e接收删除结点的值*/
Delete_Elem(L2, 7, e);
printf("-------删除第7个结点%d-------\n",e);
Print_LinkList(L2);
printf("\n");
/*按值删除结点*/
Delete_ElemByValue(L2, 3);
printf("-------删除第3个结点-------\n");
Print_LinkList(L2);
printf("\n");
/*求表长*/
int len = Length(L2);
printf("表长:%d\n", len);
return 0;
}
| 20.625 | 42 | 0.49697 | lcl0512 |
d4a81fdf75a61d38c73dcd454e601354f1b4ac0e | 461 | cpp | C++ | sqrt.cpp | LiFengcheng01/CPP-Homework | 192766b689996b166a394ceb4e9b256fa39e54e0 | [
"Apache-2.0"
] | 1 | 2018-10-12T05:00:45.000Z | 2018-10-12T05:00:45.000Z | sqrt.cpp | LiFengcheng01/CPP-Homework | 192766b689996b166a394ceb4e9b256fa39e54e0 | [
"Apache-2.0"
] | null | null | null | sqrt.cpp | LiFengcheng01/CPP-Homework | 192766b689996b166a394ceb4e9b256fa39e54e0 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <cmath>
using namespace std;
int int_sqrt(int x);
int Mypow(int di,int mi);
int main()
{
int i;
for(i=0;i<=100;i++)
cout<<i<<" "<<int_sqrt(i)<<endl;
system("pause");
return 0;
}
int int_sqrt(int x)
{
int i;
for(i=0;;i++)
{
if(x>=Mypow(i,2)&&x<Mypow(i+1,2))
break;
}
return i;
}
int Mypow(int di,int mi)
{
int i,tmp=1;
for(i=0;i<mi;i++)
tmp*=di;
return tmp;
}
| 14.40625 | 39 | 0.518438 | LiFengcheng01 |
d4aa0ce1738e379af3688b811645da90f4788173 | 12,682 | hpp | C++ | sdk/core/azure-core/inc/azure/core/http/http.hpp | ahsonkhan/azure-sdk-for-cpp | ae612c5db562bb2176bdbc3cc1550a2ed835d553 | [
"MIT"
] | null | null | null | sdk/core/azure-core/inc/azure/core/http/http.hpp | ahsonkhan/azure-sdk-for-cpp | ae612c5db562bb2176bdbc3cc1550a2ed835d553 | [
"MIT"
] | null | null | null | sdk/core/azure-core/inc/azure/core/http/http.hpp | ahsonkhan/azure-sdk-for-cpp | ae612c5db562bb2176bdbc3cc1550a2ed835d553 | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation. All rights reserved.
// SPDX-License-Identifier: MIT
/**
* @file
* @brief HTTP request and response functionality.
*/
#pragma once
#include "azure/core/case_insensitive_containers.hpp"
#include "azure/core/dll_import_export.hpp"
#include "azure/core/exception.hpp"
#include "azure/core/http/http_status_code.hpp"
#include "azure/core/http/raw_response.hpp"
#include "azure/core/internal/contract.hpp"
#include "azure/core/io/body_stream.hpp"
#include "azure/core/nullable.hpp"
#include "azure/core/url.hpp"
#include <algorithm>
#include <cstdint>
#include <functional>
#include <map>
#include <memory>
#include <stdexcept>
#include <string>
#include <unordered_set>
#include <vector>
#if defined(TESTING_BUILD)
// Define the class used from tests to validate retry enabled
namespace Azure { namespace Core { namespace Test {
class TestHttp_getters_Test;
class TestHttp_query_parameter_Test;
class TestHttp_RequestStartTry_Test;
class TestURL_getters_Test;
class TestURL_query_parameter_Test;
class TransportAdapter_headWithStream_Test;
class TransportAdapter_putWithStream_Test;
class TransportAdapter_deleteRequestWithStream_Test;
class TransportAdapter_patchWithStream_Test;
class TransportAdapter_putWithStreamOnFail_Test;
class TransportAdapter_SizePutFromFile_Test;
class TransportAdapter_SizePutFromFileDefault_Test;
class TransportAdapter_SizePutFromFileBiggerPage_Test;
}}} // namespace Azure::Core::Test
#endif
namespace Azure { namespace Core { namespace Http {
/********************* Exceptions **********************/
/**
* @brief An error while sending the HTTP request with the transport adapter.
*/
class TransportException final : public Azure::Core::RequestFailedException {
public:
/**
* @brief Constructs `%TransportException` with a \p message string.
*
* @remark The transport policy will throw this error whenever the transport adapter fail to
* perform a request.
*
* @param whatArg The explanatory string.
*/
explicit TransportException(std::string const& whatArg)
: Azure::Core::RequestFailedException(whatArg)
{
}
};
/**
* @brief The range of bytes within an HTTP resource.
*
* @note Starts at an `Offset` and ends at `Offset + Length - 1` inclusively.
*/
struct HttpRange final
{
/**
* @brief The starting point of the HTTP Range.
*
*/
int64_t Offset = 0;
/**
* @brief The size of the HTTP Range.
*
*/
Azure::Nullable<int64_t> Length;
};
/**
* @brief The method to be performed on the resource identified by the Request.
*/
class HttpMethod final {
public:
/**
* @brief Constructs `%HttpMethod` from string.
*
* @note Won't check if \p value is a known HttpMethod defined as per any RFC.
*
* @param value A given string to represent the `%HttpMethod`.
*/
explicit HttpMethod(std::string value) : m_value(std::move(value)) {}
/**
* @brief Compares two instances of `%HttpMethod` for equality.
*
* @param other Some `%HttpMethod` instance to compare with.
* @return `true` if instances are equal; otherwise, `false`.
*/
bool operator==(const HttpMethod& other) const { return m_value == other.m_value; }
/**
* @brief Compares two instances of `%HttpMethod` for equality.
*
* @param other Some `%HttpMethod` instance to compare with.
* @return `false` if instances are equal; otherwise, `true`.
*/
bool operator!=(const HttpMethod& other) const { return !(*this == other); }
/**
* @brief Returns the `%HttpMethod` represented as a string.
*/
const std::string& ToString() const { return m_value; }
/**
* @brief The representation of a `GET` HTTP method based on [RFC 7231]
* (https://datatracker.ietf.org/doc/html/rfc7231#section-4.3.1).
*/
AZ_CORE_DLLEXPORT const static HttpMethod Get;
/**
* @brief The representation of a `HEAD` HTTP method based on [RFC 7231]
* (https://datatracker.ietf.org/doc/html/rfc7231#section-4.3.2).
*/
AZ_CORE_DLLEXPORT const static HttpMethod Head;
/**
* @brief The representation of a `POST` HTTP method based on [RFC 7231]
* (https://datatracker.ietf.org/doc/html/rfc7231#section-4.3.3).
*/
AZ_CORE_DLLEXPORT const static HttpMethod Post;
/**
* @brief The representation of a `PUT` HTTP method based on [RFC 7231]
* (https://datatracker.ietf.org/doc/html/rfc7231#section-4.3.4).
*/
AZ_CORE_DLLEXPORT const static HttpMethod Put;
/**
* @brief The representation of a `DELETE` HTTP method based on [RFC 7231]
* (https://datatracker.ietf.org/doc/html/rfc7231#section-4.3.5).
*/
AZ_CORE_DLLEXPORT const static HttpMethod Delete;
/**
* @brief The representation of a `PATCH` HTTP method based on [RFC 5789]
* (https://datatracker.ietf.org/doc/html/rfc5789).
*/
AZ_CORE_DLLEXPORT const static HttpMethod Patch;
private:
std::string m_value;
}; // extensible enum HttpMethod
namespace Policies { namespace _internal {
class RetryPolicy;
}} // namespace Policies::_internal
/**
* @brief A request message from a client to a server.
*
* @details Includes, within the first line of the message, the HttpMethod to be applied to the
* resource, the URL of the resource, and the protocol version in use.
*/
class Request final {
friend class Azure::Core::Http::Policies::_internal::RetryPolicy;
#if defined(TESTING_BUILD)
// make tests classes friends to validate set Retry
friend class Azure::Core::Test::TestHttp_getters_Test;
friend class Azure::Core::Test::TestHttp_query_parameter_Test;
friend class Azure::Core::Test::TestHttp_RequestStartTry_Test;
friend class Azure::Core::Test::TestURL_getters_Test;
friend class Azure::Core::Test::TestURL_query_parameter_Test;
// make tests classes friends to validate private Request ctor that takes both stream and bool
friend class Azure::Core::Test::TransportAdapter_headWithStream_Test;
friend class Azure::Core::Test::TransportAdapter_putWithStream_Test;
friend class Azure::Core::Test::TransportAdapter_deleteRequestWithStream_Test;
friend class Azure::Core::Test::TransportAdapter_patchWithStream_Test;
friend class Azure::Core::Test::TransportAdapter_putWithStreamOnFail_Test;
friend class Azure::Core::Test::TransportAdapter_SizePutFromFile_Test;
friend class Azure::Core::Test::TransportAdapter_SizePutFromFileDefault_Test;
friend class Azure::Core::Test::TransportAdapter_SizePutFromFileBiggerPage_Test;
#endif
private:
HttpMethod m_method;
Url m_url;
CaseInsensitiveMap m_headers;
CaseInsensitiveMap m_retryHeaders;
Azure::Core::IO::BodyStream* m_bodyStream;
// flag to know where to insert header
bool m_retryModeEnabled{false};
bool m_shouldBufferResponse{true};
// Expected to be called by a Retry policy to reset all headers set after this function was
// previously called
void StartTry();
/**
* @brief Construct an #Azure::Core::Http::Request.
*
* @param httpMethod HttpMethod.
* @param url %Request URL.
* @param bodyStream #Azure::Core::IO::BodyStream.
* @param shouldBufferResponse A boolean value indicating whether the returned response should
* be buffered or returned as a body stream instead.
*/
explicit Request(
HttpMethod httpMethod,
Url url,
Azure::Core::IO::BodyStream* bodyStream,
bool shouldBufferResponse)
: m_method(std::move(httpMethod)), m_url(std::move(url)), m_bodyStream(bodyStream),
m_retryModeEnabled(false), m_shouldBufferResponse(shouldBufferResponse)
{
AZURE_ASSERT_MSG(bodyStream, "The bodyStream pointer cannot be null.");
}
public:
/**
* @brief Constructs a `%Request`.
*
* @param httpMethod HTTP method.
* @param url %Request URL.
* @param bodyStream #Azure::Core::IO::BodyStream.
*/
explicit Request(HttpMethod httpMethod, Url url, Azure::Core::IO::BodyStream* bodyStream)
: Request(httpMethod, std::move(url), bodyStream, true)
{
}
/**
* @brief Constructs a `%Request`.
*
* @param httpMethod HTTP method.
* @param url %Request URL.
* @param shouldBufferResponse A boolean value indicating whether the returned response should
* be buffered or returned as a body stream instead.
*/
explicit Request(HttpMethod httpMethod, Url url, bool shouldBufferResponse);
/**
* @brief Constructs a `%Request`.
*
* @param httpMethod HTTP method.
* @param url %Request URL.
*/
explicit Request(HttpMethod httpMethod, Url url);
/**
* @brief Set an HTTP header to the #Azure::Core::Http::Request.
*
* @remark If the header key does not exists, it is added.
*
*
* @param name The name for the header to be set or added.
* @param value The value for the header to be set or added.
*
* @throw if \p name is an invalid header key.
*/
void SetHeader(std::string const& name, std::string const& value);
/**
* @brief Remove an HTTP header.
*
* @param name HTTP header name.
*/
void RemoveHeader(std::string const& name);
// Methods used by transport layer (and logger) to send request
/**
* @brief Get HttpMethod.
*
*/
HttpMethod GetMethod() const;
/**
* @brief Get HTTP headers.
*
*/
CaseInsensitiveMap GetHeaders() const;
/**
* @brief Get HTTP body as #Azure::Core::IO::BodyStream.
*
*/
Azure::Core::IO::BodyStream* GetBodyStream() { return this->m_bodyStream; }
/**
* @brief A value indicating whether the returned raw response for this request will be buffered
* within a memory buffer or if it will be returned as a body stream instead.
*/
bool ShouldBufferResponse() { return this->m_shouldBufferResponse; }
/**
* @brief Get URL.
*
*/
Url& GetUrl() { return this->m_url; }
/**
* @brief Get URL.
*
*/
Url const& GetUrl() const { return this->m_url; }
};
namespace _detail {
struct RawResponseHelpers final
{
/**
* @brief Insert a header into \p headers checking that \p headerName does not contain invalid
* characters.
*
* @param headers The headers map where to insert header.
* @param headerName The header name for the header to be inserted.
* @param headerValue The header value for the header to be inserted.
*
* @throw if \p headerName is invalid.
*/
static void InsertHeaderWithValidation(
CaseInsensitiveMap& headers,
std::string const& headerName,
std::string const& headerValue);
static void inline SetHeader(
Azure::Core::Http::RawResponse& response,
uint8_t const* const first,
uint8_t const* const last)
{
// get name and value from header
auto start = first;
auto end = std::find(start, last, ':');
if (end == last)
{
throw std::invalid_argument("Invalid header. No delimiter ':' found.");
}
// Always toLower() headers
auto headerName
= Azure::Core::_internal::StringExtensions::ToLower(std::string(start, end));
start = end + 1; // start value
while (start < last && (*start == ' ' || *start == '\t'))
{
++start;
}
end = std::find(start, last, '\r');
auto headerValue = std::string(start, end); // remove \r
response.SetHeader(headerName, headerValue);
}
};
} // namespace _detail
namespace _internal {
struct HttpShared final
{
AZ_CORE_DLLEXPORT static char const ContentType[];
AZ_CORE_DLLEXPORT static char const ApplicationJson[];
AZ_CORE_DLLEXPORT static char const Accept[];
AZ_CORE_DLLEXPORT static char const MsRequestId[];
AZ_CORE_DLLEXPORT static char const MsClientRequestId[];
static inline std::string GetHeaderOrEmptyString(
Azure::Core::CaseInsensitiveMap const& headers,
std::string const& headerName)
{
auto header = headers.find(headerName);
if (header != headers.end())
{
return header->second; // second is the header value.
}
return {}; // empty string
}
};
} // namespace _internal
}}} // namespace Azure::Core::Http
| 32.025253 | 100 | 0.6607 | ahsonkhan |
d4ab86cf288932c410245fa10b850737c2b5514f | 635 | cpp | C++ | kernel/src/syscall/task.cpp | unixpickle/alux | 662c656775f8bae3e043f6a8e78982e9ca8e48e7 | [
"BSD-2-Clause"
] | 11 | 2015-04-25T20:44:17.000Z | 2020-04-07T08:53:30.000Z | kernel/src/syscall/task.cpp | unixpickle/alux | 662c656775f8bae3e043f6a8e78982e9ca8e48e7 | [
"BSD-2-Clause"
] | null | null | null | kernel/src/syscall/task.cpp | unixpickle/alux | 662c656775f8bae3e043f6a8e78982e9ca8e48e7 | [
"BSD-2-Clause"
] | 4 | 2015-09-09T14:21:40.000Z | 2021-06-07T18:19:34.000Z | #include "task.hpp"
#include "../tasks/hold-scope.hpp"
#include <anarch/critical>
namespace Alux {
void ExitSyscall(anarch::SyscallArgs & args) {
bool aborted = args.PopBool();
HoldScope scope;
scope.ExitTask(aborted ? Task::KillReasonAbort : Task::KillReasonNormal);
}
anarch::SyscallRet GetPidSyscall() {
AssertCritical();
Task & t = Thread::GetCurrent()->GetTask();
return anarch::SyscallRet::Integer32((uint32_t)t.GetIdentifier());
}
anarch::SyscallRet GetUidSyscall() {
AssertCritical();
Task & t = Thread::GetCurrent()->GetTask();
return anarch::SyscallRet::Integer32((uint32_t)t.GetUserIdentifier());
}
}
| 24.423077 | 75 | 0.716535 | unixpickle |
d4b0bab70e7733bfaad73c2d425ee6c49a6c298f | 4,308 | cc | C++ | lib-opencc-android/src/main/jni/OpenCC/deps/google-benchmark/test/donotoptimize_assembly_test.cc | huxiaomao/android-opencc | a251591316323151a97d977c39c85e0571c60971 | [
"MIT"
] | 13,885 | 2018-08-03T17:46:24.000Z | 2022-03-31T14:26:19.000Z | lib-opencc-android/src/main/jni/OpenCC/deps/google-benchmark/test/donotoptimize_assembly_test.cc | huxiaomao/android-opencc | a251591316323151a97d977c39c85e0571c60971 | [
"MIT"
] | 11,789 | 2015-01-05T04:50:15.000Z | 2022-03-31T23:39:19.000Z | lib-opencc-android/src/main/jni/OpenCC/deps/google-benchmark/test/donotoptimize_assembly_test.cc | huxiaomao/android-opencc | a251591316323151a97d977c39c85e0571c60971 | [
"MIT"
] | 2,543 | 2015-01-01T11:18:36.000Z | 2022-03-22T21:32:36.000Z | #include <benchmark/benchmark.h>
#ifdef __clang__
#pragma clang diagnostic ignored "-Wreturn-type"
#endif
extern "C" {
extern int ExternInt;
extern int ExternInt2;
extern int ExternInt3;
inline int Add42(int x) { return x + 42; }
struct NotTriviallyCopyable {
NotTriviallyCopyable();
explicit NotTriviallyCopyable(int x) : value(x) {}
NotTriviallyCopyable(NotTriviallyCopyable const&);
int value;
};
struct Large {
int value;
int data[2];
};
}
// CHECK-LABEL: test_with_rvalue:
extern "C" void test_with_rvalue() {
benchmark::DoNotOptimize(Add42(0));
// CHECK: movl $42, %eax
// CHECK: ret
}
// CHECK-LABEL: test_with_large_rvalue:
extern "C" void test_with_large_rvalue() {
benchmark::DoNotOptimize(Large{ExternInt, {ExternInt, ExternInt}});
// CHECK: ExternInt(%rip)
// CHECK: movl %eax, -{{[0-9]+}}(%[[REG:[a-z]+]]
// CHECK: movl %eax, -{{[0-9]+}}(%[[REG]])
// CHECK: movl %eax, -{{[0-9]+}}(%[[REG]])
// CHECK: ret
}
// CHECK-LABEL: test_with_non_trivial_rvalue:
extern "C" void test_with_non_trivial_rvalue() {
benchmark::DoNotOptimize(NotTriviallyCopyable(ExternInt));
// CHECK: mov{{l|q}} ExternInt(%rip)
// CHECK: ret
}
// CHECK-LABEL: test_with_lvalue:
extern "C" void test_with_lvalue() {
int x = 101;
benchmark::DoNotOptimize(x);
// CHECK-GNU: movl $101, %eax
// CHECK-CLANG: movl $101, -{{[0-9]+}}(%[[REG:[a-z]+]])
// CHECK: ret
}
// CHECK-LABEL: test_with_large_lvalue:
extern "C" void test_with_large_lvalue() {
Large L{ExternInt, {ExternInt, ExternInt}};
benchmark::DoNotOptimize(L);
// CHECK: ExternInt(%rip)
// CHECK: movl %eax, -{{[0-9]+}}(%[[REG:[a-z]+]])
// CHECK: movl %eax, -{{[0-9]+}}(%[[REG]])
// CHECK: movl %eax, -{{[0-9]+}}(%[[REG]])
// CHECK: ret
}
// CHECK-LABEL: test_with_non_trivial_lvalue:
extern "C" void test_with_non_trivial_lvalue() {
NotTriviallyCopyable NTC(ExternInt);
benchmark::DoNotOptimize(NTC);
// CHECK: ExternInt(%rip)
// CHECK: movl %eax, -{{[0-9]+}}(%[[REG:[a-z]+]])
// CHECK: ret
}
// CHECK-LABEL: test_with_const_lvalue:
extern "C" void test_with_const_lvalue() {
const int x = 123;
benchmark::DoNotOptimize(x);
// CHECK: movl $123, %eax
// CHECK: ret
}
// CHECK-LABEL: test_with_large_const_lvalue:
extern "C" void test_with_large_const_lvalue() {
const Large L{ExternInt, {ExternInt, ExternInt}};
benchmark::DoNotOptimize(L);
// CHECK: ExternInt(%rip)
// CHECK: movl %eax, -{{[0-9]+}}(%[[REG:[a-z]+]])
// CHECK: movl %eax, -{{[0-9]+}}(%[[REG]])
// CHECK: movl %eax, -{{[0-9]+}}(%[[REG]])
// CHECK: ret
}
// CHECK-LABEL: test_with_non_trivial_const_lvalue:
extern "C" void test_with_non_trivial_const_lvalue() {
const NotTriviallyCopyable Obj(ExternInt);
benchmark::DoNotOptimize(Obj);
// CHECK: mov{{q|l}} ExternInt(%rip)
// CHECK: ret
}
// CHECK-LABEL: test_div_by_two:
extern "C" int test_div_by_two(int input) {
int divisor = 2;
benchmark::DoNotOptimize(divisor);
return input / divisor;
// CHECK: movl $2, [[DEST:.*]]
// CHECK: idivl [[DEST]]
// CHECK: ret
}
// CHECK-LABEL: test_inc_integer:
extern "C" int test_inc_integer() {
int x = 0;
for (int i=0; i < 5; ++i)
benchmark::DoNotOptimize(++x);
// CHECK: movl $1, [[DEST:.*]]
// CHECK: {{(addl \$1,|incl)}} [[DEST]]
// CHECK: {{(addl \$1,|incl)}} [[DEST]]
// CHECK: {{(addl \$1,|incl)}} [[DEST]]
// CHECK: {{(addl \$1,|incl)}} [[DEST]]
// CHECK-CLANG: movl [[DEST]], %eax
// CHECK: ret
return x;
}
// CHECK-LABEL: test_pointer_rvalue
extern "C" void test_pointer_rvalue() {
// CHECK: movl $42, [[DEST:.*]]
// CHECK: leaq [[DEST]], %rax
// CHECK-CLANG: movq %rax, -{{[0-9]+}}(%[[REG:[a-z]+]])
// CHECK: ret
int x = 42;
benchmark::DoNotOptimize(&x);
}
// CHECK-LABEL: test_pointer_const_lvalue:
extern "C" void test_pointer_const_lvalue() {
// CHECK: movl $42, [[DEST:.*]]
// CHECK: leaq [[DEST]], %rax
// CHECK-CLANG: movq %rax, -{{[0-9]+}}(%[[REG:[a-z]+]])
// CHECK: ret
int x = 42;
int * const xp = &x;
benchmark::DoNotOptimize(xp);
}
// CHECK-LABEL: test_pointer_lvalue:
extern "C" void test_pointer_lvalue() {
// CHECK: movl $42, [[DEST:.*]]
// CHECK: leaq [[DEST]], %rax
// CHECK-CLANG: movq %rax, -{{[0-9]+}}(%[[REG:[a-z+]+]])
// CHECK: ret
int x = 42;
int *xp = &x;
benchmark::DoNotOptimize(xp);
}
| 26.268293 | 69 | 0.620938 | huxiaomao |
d4b2857d7e43f3df5940f9ce8957ab4b55689a01 | 8,497 | cpp | C++ | thrift/test/UnionFieldRefTest.cpp | sakibguy/fbthrift | 8123a9192519072e119ac9817c6b59a35b98b81c | [
"Apache-2.0"
] | 2,112 | 2015-01-02T11:34:27.000Z | 2022-03-31T16:30:42.000Z | thrift/test/UnionFieldRefTest.cpp | sakibguy/fbthrift | 8123a9192519072e119ac9817c6b59a35b98b81c | [
"Apache-2.0"
] | 372 | 2015-01-05T10:40:09.000Z | 2022-03-31T20:45:11.000Z | thrift/test/UnionFieldRefTest.cpp | sakibguy/fbthrift | 8123a9192519072e119ac9817c6b59a35b98b81c | [
"Apache-2.0"
] | 582 | 2015-01-03T01:51:56.000Z | 2022-03-31T02:01:09.000Z | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 <folly/portability/GTest.h>
#include <thrift/lib/cpp2/BadFieldAccess.h>
#include <thrift/test/gen-cpp2/UnionFieldRef_types.h>
using namespace std;
namespace apache {
namespace thrift {
namespace test {
TEST(UnionFieldTest, basic) {
Basic a;
EXPECT_EQ(a.getType(), Basic::__EMPTY__);
EXPECT_FALSE(a.int64_ref());
EXPECT_THROW(a.int64_ref().value(), bad_field_access);
EXPECT_FALSE(a.list_i32_ref());
EXPECT_THROW(a.list_i32_ref().value(), bad_field_access);
EXPECT_FALSE(a.str_ref());
EXPECT_THROW(a.str_ref().value(), bad_field_access);
const int64_t int64 = 42LL << 42;
a.int64_ref() = int64;
EXPECT_EQ(a.getType(), Basic::int64);
EXPECT_TRUE(a.int64_ref());
EXPECT_EQ(a.int64_ref().value(), int64);
EXPECT_FALSE(a.list_i32_ref());
EXPECT_THROW(a.list_i32_ref().value(), bad_field_access);
EXPECT_FALSE(a.str_ref());
EXPECT_THROW(a.str_ref().value(), bad_field_access);
const vector<int32_t> list_i32 = {3, 1, 2};
a.list_i32_ref() = list_i32;
EXPECT_EQ(a.getType(), Basic::list_i32);
EXPECT_FALSE(a.int64_ref());
EXPECT_THROW(a.int64_ref().value(), bad_field_access);
EXPECT_TRUE(a.list_i32_ref());
EXPECT_EQ(a.list_i32_ref().value(), list_i32);
EXPECT_FALSE(a.str_ref());
EXPECT_THROW(a.str_ref().value(), bad_field_access);
const string str = "foo";
a.str_ref() = str;
EXPECT_EQ(a.getType(), Basic::str);
EXPECT_FALSE(a.int64_ref());
EXPECT_THROW(a.int64_ref().value(), bad_field_access);
EXPECT_FALSE(a.list_i32_ref());
EXPECT_THROW(a.list_i32_ref().value(), bad_field_access);
EXPECT_TRUE(a.str_ref());
EXPECT_EQ(a.str_ref().value(), str);
}
TEST(UnionFieldTest, operator_deref) {
Basic a;
EXPECT_THROW(*a.int64_ref(), bad_field_access);
EXPECT_THROW(*a.str_ref(), bad_field_access);
a.int64_ref() = 42;
EXPECT_EQ(*a.int64_ref(), 42);
EXPECT_THROW(*a.str_ref(), bad_field_access);
a.str_ref() = "foo";
EXPECT_EQ(*a.str_ref(), "foo");
EXPECT_THROW(*a.int64_ref(), bad_field_access);
}
TEST(UnionFieldTest, operator_assign) {
Basic a;
a.int64_ref() = 4;
a.list_i32_ref() = {1, 2};
// `folly::StringPiece` has explicit support for explicit conversion to
// `std::string`-like types, make sure that keeps working here.
folly::StringPiece lvalue = "lvalue";
a.str_ref() = lvalue;
a.str_ref() = folly::StringPiece("xvalue");
}
TEST(UnionFieldTest, duplicate_type) {
DuplicateType a;
EXPECT_EQ(a.getType(), DuplicateType::__EMPTY__);
EXPECT_FALSE(a.str1_ref());
EXPECT_THROW(a.str1_ref().value(), bad_field_access);
EXPECT_FALSE(a.list_i32_ref());
EXPECT_THROW(a.list_i32_ref().value(), bad_field_access);
EXPECT_FALSE(a.str2_ref());
EXPECT_THROW(a.str2_ref().value(), bad_field_access);
a.str1_ref() = string(1000, '1');
EXPECT_EQ(a.getType(), DuplicateType::str1);
EXPECT_TRUE(a.str1_ref());
EXPECT_EQ(a.str1_ref().value(), string(1000, '1'));
EXPECT_FALSE(a.list_i32_ref());
EXPECT_THROW(a.list_i32_ref().value(), bad_field_access);
EXPECT_FALSE(a.str2_ref());
EXPECT_THROW(a.str2_ref().value(), bad_field_access);
a.list_i32_ref() = vector<int32_t>(1000, 2);
EXPECT_EQ(a.getType(), DuplicateType::list_i32);
EXPECT_FALSE(a.str1_ref());
EXPECT_THROW(a.str1_ref().value(), bad_field_access);
EXPECT_TRUE(a.list_i32_ref());
EXPECT_EQ(a.list_i32_ref().value(), vector<int32_t>(1000, 2));
EXPECT_FALSE(a.str2_ref());
EXPECT_THROW(a.str2_ref().value(), bad_field_access);
a.str2_ref() = string(1000, '3');
EXPECT_EQ(a.getType(), DuplicateType::str2);
EXPECT_FALSE(a.str1_ref());
EXPECT_THROW(a.str1_ref().value(), bad_field_access);
EXPECT_FALSE(a.list_i32_ref());
EXPECT_THROW(a.list_i32_ref().value(), bad_field_access);
EXPECT_TRUE(a.str2_ref());
EXPECT_EQ(a.str2_ref().value(), string(1000, '3'));
a.str1_ref() = string(1000, '4');
EXPECT_EQ(a.getType(), DuplicateType::str1);
EXPECT_TRUE(a.str1_ref());
EXPECT_EQ(a.str1_ref().value(), string(1000, '4'));
EXPECT_FALSE(a.list_i32_ref());
EXPECT_THROW(a.list_i32_ref().value(), bad_field_access);
EXPECT_FALSE(a.str2_ref());
EXPECT_THROW(a.str2_ref().value(), bad_field_access);
a.str1_ref() = string(1000, '5');
EXPECT_EQ(a.getType(), DuplicateType::str1);
EXPECT_TRUE(a.str1_ref());
EXPECT_EQ(a.str1_ref().value(), string(1000, '5'));
EXPECT_FALSE(a.list_i32_ref());
EXPECT_THROW(a.list_i32_ref().value(), bad_field_access);
EXPECT_FALSE(a.str2_ref());
EXPECT_THROW(a.str2_ref().value(), bad_field_access);
}
TEST(UnionFieldTest, const_union) {
{
const Basic a;
EXPECT_EQ(a.getType(), Basic::__EMPTY__);
EXPECT_FALSE(a.int64_ref());
EXPECT_THROW(a.int64_ref().value(), bad_field_access);
EXPECT_FALSE(a.list_i32_ref());
EXPECT_THROW(a.list_i32_ref().value(), bad_field_access);
EXPECT_FALSE(a.str_ref());
EXPECT_THROW(a.str_ref().value(), bad_field_access);
}
{
Basic b;
const string str = "foo";
b.str_ref() = str;
const Basic& a = b;
EXPECT_EQ(a.getType(), Basic::str);
EXPECT_FALSE(a.int64_ref());
EXPECT_THROW(a.int64_ref().value(), bad_field_access);
EXPECT_FALSE(a.list_i32_ref());
EXPECT_THROW(a.list_i32_ref().value(), bad_field_access);
EXPECT_TRUE(a.str_ref());
EXPECT_EQ(a.str_ref().value(), str);
}
}
TEST(UnionFieldTest, emplace) {
DuplicateType a;
EXPECT_EQ(a.str1_ref().emplace(5, '0'), "00000");
EXPECT_EQ(*a.str1_ref(), "00000");
EXPECT_TRUE(a.str1_ref().has_value());
EXPECT_EQ(a.str2_ref().emplace({'1', '2', '3', '4', '5'}), "12345");
EXPECT_EQ(*a.str2_ref(), "12345");
EXPECT_TRUE(a.str2_ref().has_value());
const vector<int32_t> list_i32 = {3, 1, 2};
EXPECT_EQ(a.list_i32_ref().emplace(list_i32), list_i32);
EXPECT_EQ(*a.list_i32_ref(), list_i32);
EXPECT_TRUE(a.list_i32_ref().has_value());
}
TEST(UnionFieldTest, ensure) {
Basic a;
EXPECT_FALSE(a.str_ref());
EXPECT_EQ(a.str_ref().ensure(), "");
EXPECT_TRUE(a.str_ref());
EXPECT_EQ(a.str_ref().emplace("123"), "123");
EXPECT_EQ(a.str_ref().ensure(), "123");
EXPECT_EQ(*a.str_ref(), "123");
EXPECT_EQ(a.int64_ref().ensure(), 0);
EXPECT_FALSE(a.str_ref());
}
TEST(UnionFieldTest, member_of_pointer_operator) {
Basic a;
EXPECT_THROW(a.list_i32_ref()->push_back(3), bad_field_access);
a.list_i32_ref().emplace({1, 2});
a.list_i32_ref()->push_back(3);
EXPECT_EQ(a.list_i32_ref(), (vector<int32_t>{1, 2, 3}));
}
TEST(UnionFieldTest, comparison) {
auto test = [](auto i) {
Basic a;
auto ref = a.int64_ref();
ref = i;
EXPECT_LE(ref, i + 1);
EXPECT_LE(ref, i);
EXPECT_LE(i, ref);
EXPECT_LE(i - 1, ref);
EXPECT_LT(ref, i + 1);
EXPECT_LT(i - 1, ref);
EXPECT_GT(ref, i - 1);
EXPECT_GT(i + 1, ref);
EXPECT_GE(ref, i - 1);
EXPECT_GE(ref, i);
EXPECT_GE(i, ref);
EXPECT_GE(i + 1, ref);
EXPECT_EQ(ref, i);
EXPECT_EQ(i, ref);
EXPECT_NE(ref, i - 1);
EXPECT_NE(i - 1, ref);
};
{
SCOPED_TRACE("same type");
test(int64_t(10));
}
{
SCOPED_TRACE("different type");
test('a');
}
}
TEST(UnionFieldTest, field_ref_api) {
Basic a;
a.str_ref() = "foo";
EXPECT_EQ(*a.str_ref(), "foo");
EXPECT_EQ(*as_const(a).str_ref(), "foo");
EXPECT_EQ(*move(a).str_ref(), "foo");
EXPECT_EQ(*move(as_const(a)).str_ref(), "foo");
}
TEST(UnionFieldTest, TreeNode) {
TreeNode root;
root.nodes_ref().emplace(2);
(*root.nodes_ref())[0].data_ref() = 10;
(*root.nodes_ref())[1].data_ref() = 20;
EXPECT_EQ(root.nodes_ref()->size(), 2);
EXPECT_EQ((*root.nodes_ref())[0].data_ref(), 10);
EXPECT_EQ((*root.nodes_ref())[1].data_ref(), 20);
EXPECT_THROW(*root.data_ref(), bad_field_access);
EXPECT_THROW(*(*root.nodes_ref())[0].nodes_ref(), bad_field_access);
EXPECT_THROW(*(*root.nodes_ref())[1].nodes_ref(), bad_field_access);
}
} // namespace test
} // namespace thrift
} // namespace apache
| 30.238434 | 75 | 0.679887 | sakibguy |
d4b3374b4b1df7c566c469a3bdc0f1e5d48352cc | 1,336 | cpp | C++ | src/cmd_context/tactic_manager.cpp | jar-ben/z3 | 7baa4f88b0cb4458461596d147e1f71853d77126 | [
"MIT"
] | 7,746 | 2015-03-26T18:59:33.000Z | 2022-03-31T15:34:48.000Z | src/cmd_context/tactic_manager.cpp | jar-ben/z3 | 7baa4f88b0cb4458461596d147e1f71853d77126 | [
"MIT"
] | 5,162 | 2015-03-27T01:12:48.000Z | 2022-03-31T14:56:16.000Z | src/cmd_context/tactic_manager.cpp | jar-ben/z3 | 7baa4f88b0cb4458461596d147e1f71853d77126 | [
"MIT"
] | 1,529 | 2015-03-26T18:45:30.000Z | 2022-03-31T15:35:16.000Z | /*++
Copyright (c) 2012 Microsoft Corporation
Module Name:
tactic_manager.cpp
Abstract:
Collection of tactics & probes
Author:
Leonardo (leonardo) 2012-03-06
Notes:
--*/
#include "cmd_context/tactic_manager.h"
tactic_manager::~tactic_manager() {
finalize_tactic_cmds();
finalize_probes();
}
void tactic_manager::insert(tactic_cmd * c) {
symbol const & s = c->get_name();
SASSERT(!m_name2tactic.contains(s));
m_name2tactic.insert(s, c);
m_tactics.push_back(c);
}
void tactic_manager::insert(probe_info * p) {
symbol const & s = p->get_name();
SASSERT(!m_name2probe.contains(s));
m_name2probe.insert(s, p);
m_probes.push_back(p);
}
tactic_cmd * tactic_manager::find_tactic_cmd(symbol const & s) const {
tactic_cmd * c = nullptr;
m_name2tactic.find(s, c);
return c;
}
probe_info * tactic_manager::find_probe(symbol const & s) const {
probe_info * p = nullptr;
m_name2probe.find(s, p);
return p;
}
void tactic_manager::finalize_tactic_cmds() {
std::for_each(m_tactics.begin(), m_tactics.end(), delete_proc<tactic_cmd>());
m_tactics.reset();
m_name2tactic.reset();
}
void tactic_manager::finalize_probes() {
std::for_each(m_probes.begin(), m_probes.end(), delete_proc<probe_info>());
m_probes.reset();
m_name2probe.reset();
}
| 21.206349 | 81 | 0.683383 | jar-ben |
d4b5aeb0f9810540c1045c1d3ba442176dab49a7 | 1,549 | cpp | C++ | _investigacion/contests/un_marzo/prime_gap.cpp | civilian/competitive_programing | a6ae7ad0db84240667c1dd6231c51c586ba040c7 | [
"MIT"
] | 1 | 2016-02-11T21:28:22.000Z | 2016-02-11T21:28:22.000Z | _investigacion/contests/un_marzo/prime_gap.cpp | civilian/competitive_programing | a6ae7ad0db84240667c1dd6231c51c586ba040c7 | [
"MIT"
] | null | null | null | _investigacion/contests/un_marzo/prime_gap.cpp | civilian/competitive_programing | a6ae7ad0db84240667c1dd6231c51c586ba040c7 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <cctype>
#include <cassert>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <list>
#include <set>
#include <map>
#include <bitset>
#include <algorithm>
#include <numeric>
#include <complex>
#define D(x) cerr << #x << " = " << (x) << endl;
#define REP(i,a,n) for(int i=(a); i<(int)(n); i++)
#define FOREACH(it,v) for(__typeof((v).begin()) it=(v).begin(); it!=(v).end(); ++it)
#define ALL(v) (v).begin(), (v).end()
using namespace std;
typedef long long int64;
const int INF = (int)(1e9);
const int64 INFLL = (int64)(1e18);
const double EPS = 1e-13;
long long sieve_size;
bitset<2000010> bs;
vector<int> primes;
void sieve(long long upperbound) {
sieve_size = upperbound+1;
bs.set();
bs[0] = bs[1] = 0;
for(long long i = 2; i <= sieve_size; i++) if(bs[i]) {
for(long long j = i*i; j <= sieve_size; j+=i)
bs[j] = 0;
primes.push_back((int)i);
}
}
int main() {
#ifdef LOCAL
freopen("inputs/prime_gap.in", "r", stdin);
freopen("outputs/prime_gap.out", "w", stdout);
#else
ios_base::sync_with_stdio(false);
#endif
sieve(1500000);
int k;
while(cin >> k) {
if(k == 0) break;
int i = int(upper_bound(primes.begin(), primes.end(), k) - primes.begin()) - 1;
int j = int(lower_bound(primes.begin(), primes.end(), k) - primes.begin());
cout << (primes[j] - primes[i]) << endl;
}
return 0;
}
| 21.219178 | 84 | 0.621691 | civilian |
d4b604ba4e9830111aac0f0aa9f91986efd8a541 | 2,005 | cpp | C++ | AtCoder/E_CoinsRespawn.cpp | davimedio01/competitive-programming | e2a90f0183c11a90a50738a9a690efe03773d43f | [
"MIT"
] | 2 | 2020-09-10T15:48:02.000Z | 2020-09-12T00:05:35.000Z | AtCoder/E_CoinsRespawn.cpp | davimedio01/competitive-programming | e2a90f0183c11a90a50738a9a690efe03773d43f | [
"MIT"
] | null | null | null | AtCoder/E_CoinsRespawn.cpp | davimedio01/competitive-programming | e2a90f0183c11a90a50738a9a690efe03773d43f | [
"MIT"
] | 2 | 2020-09-09T17:01:05.000Z | 2020-09-09T17:02:27.000Z | #include <bits/stdc++.h>
using namespace std;
int N, M, P;
vector<tuple<int, int, long long>> grafo;
long long resp;
void BellmanFord(int inicio)
{
vector<long long> distancia(N + 1, LONG_LONG_MAX);
distancia[inicio] = 0;
//Verifica o looping negativo (não há máximo)
vector<bool> verifica(N + 1, false);
verifica[N] = true;
int primeiro, segundo;
long long moedas;
//Verifica o máximo possível, exceto os casos de looping negativo
for (int i = 1; i < N; i++)
{
for (int j = 0; j < M; j++)
{
tie(primeiro, segundo, moedas) = grafo[j];
if (distancia[primeiro] != LONG_LONG_MAX &&
distancia[primeiro] + moedas < distancia[segundo])
{
distancia[segundo] = distancia[primeiro] + moedas;
}
//Salvando o vértice percorrido
if(verifica[segundo] == true)
{
verifica[primeiro] = true;
}
}
}
//Salvando a resposta máxima atual
resp = max((long long)0, -distancia[N]);
//Percorrendo o grafo e verificando se há o looping negativo
for(int i = 0; i < M; i++)
{
tie(primeiro, segundo, moedas) = grafo[i];
if (distancia[primeiro] != LONG_LONG_MAX &&
distancia[primeiro] + moedas < distancia[segundo] &&
verifica[segundo] == true)
{
//Looping negativo = impossível
resp = -1;
break;
}
}
}
int main()
{
cin >> N >> M >> P;
for (int i = 0; i < M; i++)
{
int primeiro, segundo;
long long moedas;
cin >> primeiro >> segundo >> moedas;
grafo.push_back({primeiro, segundo, P - moedas});
}
BellmanFord(1);
cout << resp << endl;
return 0;
} | 25.0625 | 71 | 0.4798 | davimedio01 |
d4b7acfb32f080d3f7986adf3300da9d34419eb3 | 12,490 | cpp | C++ | Backends/Graphics4/OpenGL/Sources/Kore/RenderTargetImpl.cpp | varomix/Kore | fca273e3d865898e87bebd9ee58b13635bcdfd5c | [
"Zlib"
] | null | null | null | Backends/Graphics4/OpenGL/Sources/Kore/RenderTargetImpl.cpp | varomix/Kore | fca273e3d865898e87bebd9ee58b13635bcdfd5c | [
"Zlib"
] | null | null | null | Backends/Graphics4/OpenGL/Sources/Kore/RenderTargetImpl.cpp | varomix/Kore | fca273e3d865898e87bebd9ee58b13635bcdfd5c | [
"Zlib"
] | null | null | null | #include "pch.h"
#include "RenderTargetImpl.h"
#include "ogl.h"
#include <Kore/Graphics4/Graphics.h>
#include <Kore/Log.h>
#include <Kore/System.h>
#ifdef KORE_ANDROID
#include <GLContext.h>
#endif
using namespace Kore;
#ifndef GL_RGBA16F_EXT
#define GL_RGBA16F_EXT 0x881A
#endif
#ifndef GL_RGBA32F_EXT
#define GL_RGBA32F_EXT 0x8814
#endif
#ifndef GL_R16F_EXT
#define GL_R16F_EXT 0x822D
#endif
#ifndef GL_R32F_EXT
#define GL_R32F_EXT 0x822E
#endif
#ifndef GL_HALF_FLOAT
#define GL_HALF_FLOAT 0x140B
#endif
#ifndef GL_RED
#define GL_RED GL_LUMINANCE
#endif
namespace {
int pow(int pow) {
int ret = 1;
for (int i = 0; i < pow; ++i) ret *= 2;
return ret;
}
int getPower2(int i) {
for (int power = 0;; ++power)
if (pow(power) >= i) return pow(power);
}
bool nonPow2RenderTargetsSupported() {
#ifdef KORE_OPENGL_ES
#ifdef KORE_ANDROID
if (ndk_helper::GLContext::GetInstance()->GetGLVersion() >= 3.0)
return true;
else
return false;
#else
return true;
#endif
#else
return true;
#endif
}
}
void RenderTargetImpl::setupDepthStencil(GLenum texType, int depthBufferBits, int stencilBufferBits, int width, int height) {
if (depthBufferBits > 0 && stencilBufferBits > 0) {
_hasDepth = true;
#if defined(KORE_OPENGL_ES) && !defined(KORE_PI) && !defined(KORE_HTML5)
GLenum internalFormat = GL_DEPTH24_STENCIL8_OES;
#elif defined(KORE_OPENGL_ES)
GLenum internalFormat = NULL;
#else
GLenum internalFormat;
if (depthBufferBits == 24)
internalFormat = GL_DEPTH24_STENCIL8;
else
internalFormat = GL_DEPTH32F_STENCIL8;
#endif
// Renderbuffer
// glGenRenderbuffers(1, &_depthRenderbuffer);
// glCheckErrors();
// glBindRenderbuffer(GL_RENDERBUFFER, _depthRenderbuffer);
// glCheckErrors();
// glRenderbufferStorage(GL_RENDERBUFFER, internalFormat, width, height);
// glCheckErrors();
// #ifdef KORE_OPENGL_ES
// glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _depthRenderbuffer);
// glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, _depthRenderbuffer);
// #else
// glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, _depthRenderbuffer);
// #endif
// glCheckErrors();
// Texture
glGenTextures(1, &_depthTexture);
glCheckErrors();
glBindTexture(texType, _depthTexture);
glCheckErrors();
glTexImage2D(texType, 0, internalFormat, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, 0);
glCheckErrors();
glTexParameteri(texType, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(texType, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(texType, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(texType, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glCheckErrors();
glBindFramebuffer(GL_FRAMEBUFFER, _framebuffer);
glCheckErrors();
#ifdef KORE_OPENGL_ES
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, texType, _depthTexture, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, texType, _depthTexture, 0);
#else
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, texType, _depthTexture, 0);
#endif
glCheckErrors();
}
else if (depthBufferBits > 0) {
_hasDepth = true;
// Renderbuffer
// glGenRenderbuffers(1, &_depthRenderbuffer);
// glCheckErrors();
// glBindRenderbuffer(GL_RENDERBUFFER, _depthRenderbuffer);
// glCheckErrors();
// glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, width, height);
// glCheckErrors();
// glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _depthRenderbuffer);
// glCheckErrors();
// Texture
glGenTextures(1, &_depthTexture);
glCheckErrors();
glBindTexture(texType, _depthTexture);
glCheckErrors();
GLint format = depthBufferBits == 16 ? GL_DEPTH_COMPONENT16 : GL_DEPTH_COMPONENT;
glTexImage2D(texType, 0, format, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, 0);
glCheckErrors();
glTexParameteri(texType, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(texType, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(texType, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(texType, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glCheckErrors();
glBindFramebuffer(GL_FRAMEBUFFER, _framebuffer);
glCheckErrors();
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, texType, _depthTexture, 0);
glCheckErrors();
}
}
Graphics4::RenderTarget::RenderTarget(int width, int height, int depthBufferBits, bool antialiasing, RenderTargetFormat format, int stencilBufferBits,
int contextId)
: width(width), height(height), isCubeMap(false), isDepthAttachment(false) {
_hasDepth = false;
if (nonPow2RenderTargetsSupported()) {
texWidth = width;
texHeight = height;
}
else {
texWidth = getPower2(width);
texHeight = getPower2(height);
}
this->format = (int)format;
this->contextId = contextId;
// (DK) required on windows/gl
Kore::System::makeCurrent(contextId);
glGenTextures(1, &_texture);
glCheckErrors();
glBindTexture(GL_TEXTURE_2D, _texture);
glCheckErrors();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glCheckErrors();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glCheckErrors();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glCheckErrors();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glCheckErrors();
switch (format) {
case Target128BitFloat:
#ifdef KORE_OPENGL_ES
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F_EXT, texWidth, texHeight, 0, GL_RGBA, GL_FLOAT, 0);
#else
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, texWidth, texHeight, 0, GL_RGBA, GL_FLOAT, 0);
#endif
break;
case Target64BitFloat:
#ifdef KORE_OPENGL_ES
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_EXT, texWidth, texHeight, 0, GL_RGBA, GL_HALF_FLOAT, 0);
#else
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, texWidth, texHeight, 0, GL_RGBA, GL_HALF_FLOAT, 0);
#endif
break;
case Target16BitDepth:
#ifdef KORE_OPENGL_ES
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
#endif
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, texWidth, texHeight, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, 0);
break;
case Target8BitRed:
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, texWidth, texHeight, 0, GL_RED, GL_UNSIGNED_BYTE, 0);
break;
case Target16BitRedFloat:
glTexImage2D(GL_TEXTURE_2D, 0, GL_R16F_EXT, texWidth, texHeight, 0, GL_RED, GL_HALF_FLOAT, 0);
break;
case Target32BitRedFloat:
glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F_EXT, texWidth, texHeight, 0, GL_RED, GL_FLOAT, 0);
break;
case Target32Bit:
default:
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texWidth, texHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
}
glCheckErrors();
glGenFramebuffers(1, &_framebuffer);
glCheckErrors();
glBindFramebuffer(GL_FRAMEBUFFER, _framebuffer);
glCheckErrors();
setupDepthStencil(GL_TEXTURE_2D, depthBufferBits, stencilBufferBits, texWidth, texHeight);
if (format == Target16BitDepth) {
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, _texture, 0);
#ifndef KORE_OPENGL_ES
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);
#endif
}
else {
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _texture, 0);
}
glCheckErrors();
// GLenum drawBuffers[1] = { GL_COLOR_ATTACHMENT0 };
// glDrawBuffers(1, drawBuffers);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glCheckErrors();
glBindTexture(GL_TEXTURE_2D, 0);
glCheckErrors();
}
Graphics4::RenderTarget::RenderTarget(int cubeMapSize, int depthBufferBits, bool antialiasing, RenderTargetFormat format, int stencilBufferBits, int contextId)
: width(cubeMapSize), height(cubeMapSize), isCubeMap(true), isDepthAttachment(false) {
_hasDepth = false;
if (nonPow2RenderTargetsSupported()) {
texWidth = width;
texHeight = height;
}
else {
texWidth = getPower2(width);
texHeight = getPower2(height);
}
this->format = (int)format;
this->contextId = contextId;
// (DK) required on windows/gl
Kore::System::makeCurrent(contextId);
glGenTextures(1, &_texture);
glCheckErrors();
glBindTexture(GL_TEXTURE_CUBE_MAP, _texture);
glCheckErrors();
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glCheckErrors();
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glCheckErrors();
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glCheckErrors();
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glCheckErrors();
switch (format) {
case Target128BitFloat:
#ifdef KORE_OPENGL_ES
for (int i = 0; i < 6; i++) glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA32F_EXT, texWidth, texHeight, 0, GL_RGBA, GL_FLOAT, 0);
#else
for (int i = 0; i < 6; i++) glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA32F, texWidth, texHeight, 0, GL_RGBA, GL_FLOAT, 0);
#endif
break;
case Target64BitFloat:
#ifdef KORE_OPENGL_ES
for (int i = 0; i < 6; i++) glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA16F_EXT, texWidth, texHeight, 0, GL_RGBA, GL_HALF_FLOAT, 0);
#else
for (int i = 0; i < 6; i++) glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA16F, texWidth, texHeight, 0, GL_RGBA, GL_HALF_FLOAT, 0);
#endif
break;
case Target16BitDepth:
#ifdef KORE_OPENGL_ES
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
#endif
for (int i = 0; i < 6; i++)
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_DEPTH_COMPONENT16, texWidth, texHeight, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, 0);
break;
case Target32Bit:
default:
for (int i = 0; i < 6; i++) glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA, texWidth, texHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
}
glCheckErrors();
glGenFramebuffers(1, &_framebuffer);
glCheckErrors();
glBindFramebuffer(GL_FRAMEBUFFER, _framebuffer);
glCheckErrors();
setupDepthStencil(GL_TEXTURE_CUBE_MAP, depthBufferBits, stencilBufferBits, texWidth, texHeight);
if (format == Target16BitDepth) {
isDepthAttachment = true;
#ifndef KORE_OPENGL_ES
glDrawBuffer(GL_NONE);
glCheckErrors();
glReadBuffer(GL_NONE);
glCheckErrors();
#endif
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glCheckErrors();
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
glCheckErrors();
}
Graphics4::RenderTarget::~RenderTarget() {
{
GLuint textures[] = {_texture};
glDeleteTextures(1, textures);
}
if (_hasDepth) {
GLuint textures[] = {_depthTexture};
glDeleteTextures(1, textures);
}
GLuint framebuffers[] = {_framebuffer};
glDeleteFramebuffers(1, framebuffers);
}
void Graphics4::RenderTarget::useColorAsTexture(TextureUnit unit) {
glActiveTexture(GL_TEXTURE0 + unit.unit);
glCheckErrors();
glBindTexture(isCubeMap ? GL_TEXTURE_CUBE_MAP : GL_TEXTURE_2D, _texture);
glCheckErrors();
}
void Graphics4::RenderTarget::useDepthAsTexture(TextureUnit unit) {
glActiveTexture(GL_TEXTURE0 + unit.unit);
glCheckErrors();
glBindTexture(isCubeMap ? GL_TEXTURE_CUBE_MAP : GL_TEXTURE_2D, _depthTexture);
glCheckErrors();
}
void Graphics4::RenderTarget::setDepthStencilFrom(RenderTarget* source) {
glBindFramebuffer(GL_FRAMEBUFFER, _framebuffer);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, isCubeMap ? GL_TEXTURE_CUBE_MAP : GL_TEXTURE_2D, source->_depthTexture, 0);
}
void Graphics4::RenderTarget::getPixels(u8* data) {
glBindFramebuffer(GL_FRAMEBUFFER, _framebuffer);
switch ((RenderTargetFormat)format) {
case Target128BitFloat:
glReadPixels(0, 0, texWidth, texHeight, GL_RGBA, GL_FLOAT, data);
break;
case Target64BitFloat:
glReadPixels(0, 0, texWidth, texHeight, GL_RGBA, GL_HALF_FLOAT, data);
break;
case Target8BitRed:
glReadPixels(0, 0, texWidth, texHeight, GL_RED, GL_UNSIGNED_BYTE, data);
break;
case Target16BitRedFloat:
glReadPixels(0, 0, texWidth, texHeight, GL_RED, GL_HALF_FLOAT, data);
break;
case Target32BitRedFloat:
glReadPixels(0, 0, texWidth, texHeight, GL_RED, GL_FLOAT, data);
break;
case Target32Bit:
default:
glReadPixels(0, 0, texWidth, texHeight, GL_RGBA, GL_UNSIGNED_BYTE, data);
}
}
void Graphics4::RenderTarget::generateMipmaps(int levels) {
glBindTexture(GL_TEXTURE_2D, _texture);
glCheckErrors();
glGenerateMipmap(GL_TEXTURE_2D);
glCheckErrors();
}
| 31.700508 | 159 | 0.766453 | varomix |
d4b9a9a7f341c505aef9f2b9e908a91ef4a6d1b8 | 473 | cpp | C++ | firmware/examples/Delay/source/main.cpp | znic1967/Khalils-Kids | 4e8d744837c1ba63adf3ec3ec317a40860b463aa | [
"Apache-2.0"
] | null | null | null | firmware/examples/Delay/source/main.cpp | znic1967/Khalils-Kids | 4e8d744837c1ba63adf3ec3ec317a40860b463aa | [
"Apache-2.0"
] | null | null | null | firmware/examples/Delay/source/main.cpp | znic1967/Khalils-Kids | 4e8d744837c1ba63adf3ec3ec317a40860b463aa | [
"Apache-2.0"
] | null | null | null | #include <inttypes.h>
#include <cstdint>
#include "utility/log.hpp"
#include "utility/time.hpp"
int main(void)
{
LOG_INFO("Delay Application Starting...");
LOG_INFO(
"This example merely prints a statement every second using the delay "
"function.");
uint32_t counter = 0;
while (true)
{
LOG_INFO("[%lu] Hello, World! (milliseconds = %lu)", counter++,
static_cast<uint32_t>(Milliseconds()));
Delay(1000);
}
return 0;
}
| 19.708333 | 76 | 0.634249 | znic1967 |
d4c55a7e113d024fbee6fc0f65a32863cc3dac2a | 268 | cpp | C++ | chapter_8/section_x/q_4/main.cpp | martindes01/learncpp | 50c500b0cf03c9520eab0a6bdeb4556da7d13bbf | [
"MIT"
] | 4 | 2020-08-03T15:00:00.000Z | 2022-01-08T20:22:55.000Z | chapter_8/section_x/q_4/main.cpp | martindes01/learncpp | 50c500b0cf03c9520eab0a6bdeb4556da7d13bbf | [
"MIT"
] | null | null | null | chapter_8/section_x/q_4/main.cpp | martindes01/learncpp | 50c500b0cf03c9520eab0a6bdeb4556da7d13bbf | [
"MIT"
] | null | null | null | #include "deck.h"
#include "game.h"
#include <iostream>
int main()
{
// create and shuffle deck
game::Deck deck{ };
deck.shuffle();
// play a single game of blackjack
std::cout << (game::playBlackjack(deck) ? "You win!\n" : "You lose!\n");
return 0;
}
| 15.764706 | 74 | 0.615672 | martindes01 |
d4cb4d5e46c607312b1d1c274f5280a31eb5ad58 | 2,145 | hpp | C++ | tiffconvert/Font.hpp | Imagine-Programming/tiffconvert | 1eba05f3f876ac669d28ab9309326376bef61ef1 | [
"MIT"
] | null | null | null | tiffconvert/Font.hpp | Imagine-Programming/tiffconvert | 1eba05f3f876ac669d28ab9309326376bef61ef1 | [
"MIT"
] | 3 | 2021-02-15T08:10:59.000Z | 2021-03-13T10:52:47.000Z | tiffconvert/Font.hpp | Imagine-Programming/tiffconvert | 1eba05f3f876ac669d28ab9309326376bef61ef1 | [
"MIT"
] | null | null | null | #pragma once
#ifndef libtiffconvert_font_h
#define libtiffconvert_font_h
#include "libtiffconvert.h"
#include <string>
#include <cstdint>
#include <Windows.h>
namespace TiffConvert {
/// <summary>
/// Flags that specify how a font should be loaded.
/// </summary>
enum FontConfig : uint32_t {
FONT_BOLD = (1 << 0),
FONT_ITALIC = (1 << 1),
FONT_UNDERLINE = (1 << 2),
FONT_STRIKEOUT = (1 << 3),
FONT_ANTIALIAS = (1 << 4)
};
/// <summary>
/// Font describes a font that is loaded through libtiffconvert.
/// </summary>
class Font {
private:
const font_handle* m_Font = nullptr;
public:
/// <summary>
/// Convert a LOGFONTA descriptor to usable flags.
/// </summary>
/// <param name="descriptor">The LOGFONTA instance.</param>
/// <param name="hq">Whether or not anti-aliasing should be applied to the font.</param>
/// <returns>Combined flags.</returns>
static uint32_t FlagsFromLogFont(const LOGFONTA& descriptor, bool hq = true);
/// <summary>
/// Construct a new font by name, height and flags.
/// </summary>
/// <param name="name">Font family name.</param>
/// <param name="height">Font height, in points.</param>
/// <param name="flags">Font style flags.</param>
Font(const std::string& name, uint32_t height, uint32_t flags = 0);
/// <summary>
/// Construct a new font by name, height and flags.
/// </summary>
/// <param name="name">Font family name.</param>
/// <param name="height">Font height, in points.</param>
/// <param name="flags">Font style flags.</param>
Font(const std::wstring& name, uint32_t height, uint32_t flags = 0);
/// <summary>
/// Construct a new font from LOGFONTA descriptor.
/// </summary>
/// <param name="descriptor">The LOGFONTA instance.</param>
Font(const LOGFONTA& descriptor);
/// <summary>
/// The destructor frees the internal font.
/// </summary>
~Font();
/// <summary>
/// Get a const pointer to the internal font object.
/// </summary>
/// <returns>A const pointer to the internal font object.</returns>
const font_handle* get() const noexcept;
};
}
#endif | 28.986486 | 91 | 0.644755 | Imagine-Programming |
d4cec0522b84a09c904aa4bb7f30637fcf727dac | 3,702 | cpp | C++ | libs/multi_array/test/storage_order.cpp | zyiacas/boost-doc-zh | 689e5a3a0a4dbead1a960f7b039e3decda54aa2c | [
"BSL-1.0"
] | 198 | 2015-01-13T05:47:18.000Z | 2022-03-09T04:46:46.000Z | libs/multi_array/test/storage_order.cpp | sdfict/boost-doc-zh | 689e5a3a0a4dbead1a960f7b039e3decda54aa2c | [
"BSL-1.0"
] | 9 | 2015-01-28T16:33:19.000Z | 2020-04-12T23:03:28.000Z | libs/multi_array/test/storage_order.cpp | sdfict/boost-doc-zh | 689e5a3a0a4dbead1a960f7b039e3decda54aa2c | [
"BSL-1.0"
] | 139 | 2015-01-15T20:09:31.000Z | 2022-01-31T15:21:16.000Z | // Copyright 2002 The Trustees of Indiana University.
// Use, modification and distribution is subject to 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)
// Boost.MultiArray Library
// Authors: Ronald Garcia
// Jeremy Siek
// Andrew Lumsdaine
// See http://www.boost.org/libs/multi_array for documentation.
//
// storage_order.cpp - testing storage_order-isms.
//
#include "boost/multi_array.hpp"
#include "boost/test/minimal.hpp"
#include "boost/array.hpp"
int
test_main(int,char*[])
{
const int ndims=3;
int data_row[] = {
0,1,2,3,
4,5,6,7,
8,9,10,11,
12,13,14,15,
16,17,18,19,
20,21,22,23
};
int data_col[] = {
0,12,
4,16,
8,20,
1,13,
5,17,
9,21,
2,14,
6,18,
10,22,
3,15,
7,19,
11,23
};
const int num_elements = 24;
// fortran storage order
{
typedef boost::multi_array<int,ndims> array;
array::extent_gen extents;
array A(extents[2][3][4],boost::fortran_storage_order());
A.assign(data_col,data_col+num_elements);
int* num = data_row;
for (array::index i = 0; i != 2; ++i)
for (array::index j = 0; j != 3; ++j)
for (array::index k = 0; k != 4; ++k)
BOOST_CHECK(A[i][j][k] == *num++);
}
// Mimic fortran_storage_order using
// general_storage_order data placement
{
typedef boost::general_storage_order<ndims> storage;
typedef boost::multi_array<int,ndims> array;
array::size_type ordering[] = {0,1,2};
bool ascending[] = {true,true,true};
array::extent_gen extents;
array A(extents[2][3][4], storage(ordering,ascending));
A.assign(data_col,data_col+num_elements);
int* num = data_row;
for (array::index i = 0; i != 2; ++i)
for (array::index j = 0; j != 3; ++j)
for (array::index k = 0; k != 4; ++k)
BOOST_CHECK(A[i][j][k] == *num++);
}
// general_storage_order with arbitrary storage order
{
typedef boost::general_storage_order<ndims> storage;
typedef boost::multi_array<int,ndims> array;
array::size_type ordering[] = {2,0,1};
bool ascending[] = {true,true,true};
array::extent_gen extents;
array A(extents[2][3][4], storage(ordering,ascending));
int data_arb[] = {
0,1,2,3,
12,13,14,15,
4,5,6,7,
16,17,18,19,
8,9,10,11,
20,21,22,23
};
A.assign(data_arb,data_arb+num_elements);
int* num = data_row;
for (array::index i = 0; i != 2; ++i)
for (array::index j = 0; j != 3; ++j)
for (array::index k = 0; k != 4; ++k)
BOOST_CHECK(A[i][j][k] == *num++);
}
// general_storage_order with descending dimensions.
{
const int ndims=3;
typedef boost::general_storage_order<ndims> storage;
typedef boost::multi_array<int,ndims> array;
array::size_type ordering[] = {2,0,1};
bool ascending[] = {false,true,true};
array::extent_gen extents;
array A(extents[2][3][4], storage(ordering,ascending));
int data_arb[] = {
12,13,14,15,
0,1,2,3,
16,17,18,19,
4,5,6,7,
20,21,22,23,
8,9,10,11
};
A.assign(data_arb,data_arb+num_elements);
int* num = data_row;
for (array::index i = 0; i != 2; ++i)
for (array::index j = 0; j != 3; ++j)
for (array::index k = 0; k != 4; ++k)
BOOST_CHECK(A[i][j][k] == *num++);
}
return boost::exit_success;
}
| 23.1375 | 75 | 0.551053 | zyiacas |
d4d0b9fee2d7ed1f42eb4d27c4fcd094a91bfb9b | 519 | cpp | C++ | Qt-Tetris-cmake/GUI/ResetButton.cpp | Life4gal/CPP-EASY-PROJECT | 4bf66284b4990e6d7b3ab74ce15fe72fb52b5a41 | [
"MIT"
] | null | null | null | Qt-Tetris-cmake/GUI/ResetButton.cpp | Life4gal/CPP-EASY-PROJECT | 4bf66284b4990e6d7b3ab74ce15fe72fb52b5a41 | [
"MIT"
] | null | null | null | Qt-Tetris-cmake/GUI/ResetButton.cpp | Life4gal/CPP-EASY-PROJECT | 4bf66284b4990e6d7b3ab74ce15fe72fb52b5a41 | [
"MIT"
] | null | null | null | #include "ResetButton.h"
using namespace GUI;
ResetButton::ResetButton(QWidget *parent)
: QLabel(parent)
{
setAttribute(Qt::WA_StyledBackground, true);
setProperty("class", "ResetButton");
setText("Try again!");
setAlignment(Qt::AlignCenter);
setStyleSheet(".ResetButton { background-color: rgb(143,122,102); border-radius: 10px; font: bold; color: white; }");
}
void ResetButton::mousePressEvent(QMouseEvent *event)
{
emit clicked();
//QLabel::mousePressEvent(event);
}
| 24.714286 | 121 | 0.684008 | Life4gal |
d4d5327d65ef40c29aae7e101fbddffeef313076 | 2,560 | cpp | C++ | Leetcode/0355. Design Twitter/0355.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | Leetcode/0355. Design Twitter/0355.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | Leetcode/0355. Design Twitter/0355.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | struct Tweet {
int id;
int time;
Tweet* next = nullptr;
Tweet(int id, int time) : id(id), time(time) {}
};
struct User {
int id;
unordered_set<int> followeeIds;
Tweet* tweetHead = nullptr;
User() {}
User(int id) : id(id) {
follow(id); // follow himself
}
void follow(int followeeId) {
followeeIds.insert(followeeId);
}
void unfollow(int followeeId) {
followeeIds.erase(followeeId);
}
void post(int tweetId, int time) {
Tweet* oldTweetHead = tweetHead;
tweetHead = new Tweet(tweetId, time);
tweetHead->next = oldTweetHead;
}
};
class Twitter {
public:
/** Compose a new tweet. */
void postTweet(int userId, int tweetId) {
if (!users.count(userId))
users[userId] = User(userId);
users[userId].post(tweetId, time++);
}
/**
* Retrieve the 10 most recent tweet ids in the user's news feed. Each item in
* the news feed must be posted by users who the user followed or by the user
* herself. Tweets must be ordered from most recent to least recent.
*/
vector<int> getNewsFeed(int userId) {
if (!users.count(userId))
return {};
vector<int> newsFeed;
auto compare = [](const Tweet* a, const Tweet* b) {
return a->time < b->time;
};
priority_queue<Tweet*, vector<Tweet*>, decltype(compare)> maxHeap(compare);
for (const int followeeId : users[userId].followeeIds) {
Tweet* tweetHead = users[followeeId].tweetHead;
if (tweetHead)
maxHeap.push(tweetHead);
}
int count = 0;
while (!maxHeap.empty() && count++ < 10) {
Tweet* tweet = maxHeap.top();
maxHeap.pop();
newsFeed.push_back(tweet->id);
if (tweet->next)
maxHeap.push(tweet->next);
}
return newsFeed;
}
/**
* Follower follows a followee.
* If the operation is invalid, it should be a no-op.
*/
void follow(int followerId, int followeeId) {
if (followerId == followeeId)
return;
if (!users.count(followerId))
users[followerId] = User(followerId);
if (!users.count(followeeId))
users[followeeId] = User(followeeId);
users[followerId].follow(followeeId);
}
/**
* Follower unfollows a followee.
* If the operation is invalid, it should be a no-op.
*/
void unfollow(int followerId, int followeeId) {
if (followerId == followeeId)
return;
if (users.count(followerId) && users.count(followeeId))
users[followerId].unfollow(followeeId);
}
private:
int time = 0;
unordered_map<int, User> users; // {userId: User}
};
| 24.150943 | 80 | 0.629688 | Next-Gen-UI |
d4d6c86fbc8fe8dc720abba88f7ddf72d7917792 | 7,897 | cpp | C++ | all/native/renderers/NMLModelRenderer.cpp | mostafa-j13/mobile-sdk | 60d51e4d37c7fb9558b1310345083c7f7d6b79e7 | [
"BSD-3-Clause"
] | null | null | null | all/native/renderers/NMLModelRenderer.cpp | mostafa-j13/mobile-sdk | 60d51e4d37c7fb9558b1310345083c7f7d6b79e7 | [
"BSD-3-Clause"
] | null | null | null | all/native/renderers/NMLModelRenderer.cpp | mostafa-j13/mobile-sdk | 60d51e4d37c7fb9558b1310345083c7f7d6b79e7 | [
"BSD-3-Clause"
] | null | null | null | #include "NMLModelRenderer.h"
#include "components/ThreadWorker.h"
#include "datasources/VectorDataSource.h"
#include "graphics/Shader.h"
#include "graphics/ShaderManager.h"
#include "graphics/ViewState.h"
#include "graphics/utils/GLContext.h"
#include "layers/VectorLayer.h"
#include "projections/Projection.h"
#include "renderers/MapRenderer.h"
#include "renderers/components/RayIntersectedElement.h"
#include "utils/Log.h"
#include <nml/GLModel.h>
#include <nml/GLTexture.h>
#include <nml/GLResourceManager.h>
namespace {
struct GLResourceDeleter : carto::ThreadWorker {
GLResourceDeleter(std::shared_ptr<carto::nml::GLResourceManager> glResourceManager) : _glResourceManager(std::move(glResourceManager)) { }
virtual void operator () () {
_glResourceManager->deleteAll();
}
private:
std::shared_ptr<carto::nml::GLResourceManager> _glResourceManager;
};
}
namespace carto {
NMLModelRenderer::NMLModelRenderer() :
_glResourceManager(),
_glModelMap(),
_elements(),
_tempElements(),
_mapRenderer(),
_options(),
_mutex()
{
}
NMLModelRenderer::~NMLModelRenderer() {
if (_glResourceManager) {
if (auto mapRenderer = _mapRenderer.lock()) {
mapRenderer->addRenderThreadCallback(std::make_shared<GLResourceDeleter>(_glResourceManager));
}
}
}
void NMLModelRenderer::addElement(const std::shared_ptr<NMLModel>& element) {
_tempElements.push_back(element);
}
void NMLModelRenderer::refreshElements() {
std::lock_guard<std::mutex> lock(_mutex);
_elements.clear();
_elements.swap(_tempElements);
}
void NMLModelRenderer::updateElement(const std::shared_ptr<NMLModel>& element) {
std::lock_guard<std::mutex> lock(_mutex);
if (std::find(_elements.begin(), _elements.end(), element) == _elements.end()) {
_elements.push_back(element);
}
}
void NMLModelRenderer::removeElement(const std::shared_ptr<NMLModel>& element) {
std::lock_guard<std::mutex> lock(_mutex);
_elements.erase(std::remove(_elements.begin(), _elements.end(), element), _elements.end());
}
void NMLModelRenderer::setMapRenderer(const std::weak_ptr<MapRenderer>& mapRenderer) {
std::lock_guard<std::mutex> lock(_mutex);
_mapRenderer = mapRenderer;
}
void NMLModelRenderer::setOptions(const std::weak_ptr<Options>& options) {
std::lock_guard<std::mutex> lock(_mutex);
_options = options;
}
void NMLModelRenderer::offsetLayerHorizontally(double offset) {
std::lock_guard<std::mutex> lock(_mutex);
for (const std::shared_ptr<NMLModel>& element : _elements) {
element->getDrawData()->offsetHorizontally(offset);
}
}
void NMLModelRenderer::onSurfaceCreated(const std::shared_ptr<ShaderManager>& shaderManager, const std::shared_ptr<TextureManager>& textureManager) {
_glResourceManager = std::make_shared<nml::GLResourceManager>();
_glModelMap.clear();
nml::GLTexture::registerGLExtensions();
}
bool NMLModelRenderer::onDrawFrame(float deltaSeconds, const ViewState& viewState) {
std::lock_guard<std::mutex> lock(_mutex);
std::shared_ptr<Options> options = _options.lock();
if (!options) {
return false;
}
// Set expected GL state
glDepthMask(GL_TRUE);
glEnable(GL_DEPTH_TEST);
// Calculate lighting state
Color ambientColor = options->getAmbientLightColor();
cglib::vec4<float> ambientLightColor = cglib::vec4<float>(ambientColor.getR(), ambientColor.getG(), ambientColor.getB(), ambientColor.getA()) * (1.0f / 255.0f);
Color mainColor = options->getMainLightColor();
cglib::vec4<float> mainLightColor = cglib::vec4<float>(mainColor.getR(), mainColor.getG(), mainColor.getB(), mainColor.getA()) * (1.0f / 255.0f);
MapVec mainDir = options->getMainLightDirection();
cglib::vec3<float> mainLightDir = cglib::unit(cglib::vec3<float>::convert(cglib::transform_vector(cglib::vec3<double>(mainDir.getX(), mainDir.getY(), mainDir.getZ()), viewState.getModelviewMat())));
// Draw models
cglib::mat4x4<float> projMat = cglib::mat4x4<float>::convert(viewState.getProjectionMat());
for (const std::shared_ptr<NMLModel>& element : _elements) {
const NMLModelDrawData& drawData = *element->getDrawData();
std::shared_ptr<nml::Model> sourceModel = drawData.getSourceModel();
std::shared_ptr<nml::GLModel> glModel = _glModelMap[sourceModel];
if (!glModel) {
glModel = std::make_shared<nml::GLModel>(*sourceModel);
glModel->create(*_glResourceManager);
_glModelMap[sourceModel] = glModel;
}
cglib::mat4x4<float> mvMat = cglib::mat4x4<float>::convert(viewState.getModelviewMat() * drawData.getLocalMat());
nml::RenderState renderState(projMat, mvMat, ambientLightColor, mainLightColor, -mainLightDir);
glModel->draw(*_glResourceManager, renderState);
}
// Remove stale models
for (auto it = _glModelMap.begin(); it != _glModelMap.end(); ) {
if (it->first.expired()) {
it = _glModelMap.erase(it);
} else {
it++;
}
}
// Dispose unused models
_glResourceManager->deleteUnused();
// Restore expected GL state
glDepthMask(GL_TRUE);
glDisable(GL_DEPTH_TEST);
glActiveTexture(GL_TEXTURE0);
GLContext::CheckGLError("NMLModelRenderer::onDrawFrame");
return false;
}
void NMLModelRenderer::onSurfaceDestroyed() {
_glResourceManager.reset();
_glModelMap.clear();
}
void NMLModelRenderer::calculateRayIntersectedElements(const std::shared_ptr<VectorLayer>& layer, const cglib::ray3<double>& ray, const ViewState& viewState, std::vector<RayIntersectedElement>& results) const {
std::lock_guard<std::mutex> lock(_mutex);
for (const std::shared_ptr<NMLModel>& element : _elements) {
const NMLModelDrawData& drawData = *element->getDrawData();
std::shared_ptr<nml::Model> sourceModel = drawData.getSourceModel();
auto modelIt = _glModelMap.find(sourceModel);
if (modelIt == _glModelMap.end()) {
continue;
}
std::shared_ptr<nml::GLModel> glModel = modelIt->second;
cglib::mat4x4<double> modelMat = drawData.getLocalMat();
cglib::mat4x4<double> invModelMat = cglib::inverse(modelMat);
cglib::ray3<double> rayModel = cglib::transform_ray(ray, invModelMat);
cglib::bbox3<double> modelBounds = cglib::bbox3<double>::convert(glModel->getBounds());
if (!cglib::intersect_bbox(modelBounds, rayModel)) {
continue;
}
std::vector<nml::RayIntersection> intersections;
glModel->calculateRayIntersections(rayModel, intersections);
for (std::size_t i = 0; i < intersections.size(); i++) {
cglib::vec3<double> pos = cglib::transform_point(intersections[i].pos, modelMat);
MapPos clickPos(pos(0), pos(1), pos(2));
MapPos projectedClickPos = layer->getDataSource()->getProjection()->fromInternal(clickPos);
int priority = static_cast<int>(results.size());
results.push_back(RayIntersectedElement(std::static_pointer_cast<VectorElement>(element), layer, projectedClickPos, projectedClickPos, priority, true));
}
}
}
}
| 39.288557 | 214 | 0.635431 | mostafa-j13 |
d4d79367344f71a353f13de4f5760670a4a04c53 | 490 | hpp | C++ | include/depthai-shared/pipeline/NodeConnectionSchema.hpp | kamleshbhalui/depthai-shared | 28da84fc8a81b8d692d801924598ce9cb34ac761 | [
"MIT"
] | null | null | null | include/depthai-shared/pipeline/NodeConnectionSchema.hpp | kamleshbhalui/depthai-shared | 28da84fc8a81b8d692d801924598ce9cb34ac761 | [
"MIT"
] | null | null | null | include/depthai-shared/pipeline/NodeConnectionSchema.hpp | kamleshbhalui/depthai-shared | 28da84fc8a81b8d692d801924598ce9cb34ac761 | [
"MIT"
] | null | null | null | #pragma once
#include "depthai-shared/utility/Serialization.hpp"
namespace dai {
/**
* Specifies a connection between nodes IOs
*/
struct NodeConnectionSchema {
int64_t node1Id = -1;
std::string node1OutputGroup;
std::string node1Output;
int64_t node2Id = -1;
std::string node2InputGroup;
std::string node2Input;
};
DEPTHAI_SERIALIZE_EXT(NodeConnectionSchema, node1Id, node1OutputGroup, node1Output, node2Id, node2InputGroup, node2Input);
} // namespace dai
| 22.272727 | 122 | 0.740816 | kamleshbhalui |
d4d91b4b152a3967a3741925b6f9fb3e2e869c9a | 466 | cpp | C++ | contributors/nikolai_chernyshov/logger.cpp | AxoyTO/TheGraph | 4ced7206847f5bb22bd25a48ff09247c5b1218ef | [
"MIT"
] | 1 | 2022-02-07T15:52:51.000Z | 2022-02-07T15:52:51.000Z | contributors/nikolai_chernyshov/logger.cpp | AxoyTO/TheGraph | 4ced7206847f5bb22bd25a48ff09247c5b1218ef | [
"MIT"
] | null | null | null | contributors/nikolai_chernyshov/logger.cpp | AxoyTO/TheGraph | 4ced7206847f5bb22bd25a48ff09247c5b1218ef | [
"MIT"
] | 2 | 2022-02-07T15:53:00.000Z | 2022-02-12T13:31:36.000Z | #include "logger.hpp"
#include <iostream>
#include "config.hpp"
namespace uni_course_cpp {
void Logger::log(const std::string& string) {
std::cout << string;
file_stream_ << string;
}
Logger::~Logger() {
if (file_stream_.is_open())
file_stream_.close();
}
Logger::Logger() : file_stream_(std::ofstream(config::log_file_path())) {
if (!file_stream_.is_open())
throw std::runtime_error("Can't create file stream");
}
} // namespace uni_course_cpp
| 21.181818 | 73 | 0.693133 | AxoyTO |
d4d989943cc7f3ea91b3aa28139e790d5e4b652d | 1,219 | hpp | C++ | source/graphs/depth_first_search.hpp | pawel-kieliszczyk/algorithms | 0703ec99ce9fb215709b56fb0eefbdd576c71ed2 | [
"MIT"
] | null | null | null | source/graphs/depth_first_search.hpp | pawel-kieliszczyk/algorithms | 0703ec99ce9fb215709b56fb0eefbdd576c71ed2 | [
"MIT"
] | null | null | null | source/graphs/depth_first_search.hpp | pawel-kieliszczyk/algorithms | 0703ec99ce9fb215709b56fb0eefbdd576c71ed2 | [
"MIT"
] | null | null | null | #ifndef PK_GRAPHS_DEPTHFIRSTSEARCH_HPP
#define PK_GRAPHS_DEPTHFIRSTSEARCH_HPP
#include "stack.hpp"
#include "vector.hpp"
namespace pk
{
namespace graphs
{
class depth_first_search
{
public:
template<
class graph_type,
class visitor_type>
static void run(
const graph_type& g,
const int starting_vertex_id,
visitor_type& visitor)
{
pk::stack<int, graph_type::max_num_of_edges> s;
pk::vector<bool, graph_type::max_num_of_vertices> visited(false, g.get_num_of_vertices());
s.push(starting_vertex_id);
while(!s.empty())
{
const int v = s.top();
s.pop();
if(visited[v])
continue;
visitor.visit(v);
visited[v] = true;
const typename graph_type::adjacency_list& adj_v = g.get_adjacency_list(v);
for(int i = adj_v.size() - 1; i >= 0; --i)
{
const int u = adj_v[i].to;
if(visited[u])
continue;
s.push(u);
}
}
}
};
} // namespace graphs
} // namespace pk
#endif // PK_GRAPHS_DEPTHFIRSTSEARCH_HPP
| 19.66129 | 98 | 0.541427 | pawel-kieliszczyk |
d4d98ae4a5a7b0a378fc0783f1409b9d0246eed3 | 1,547 | hpp | C++ | include/help_line.hpp | matt-harvey/swx | e7b10fe7d4bf0bd6581ceada53ad14b08bc1d852 | [
"Apache-2.0"
] | 7 | 2017-10-08T08:08:25.000Z | 2020-04-27T09:25:00.000Z | include/help_line.hpp | matt-harvey/swx | e7b10fe7d4bf0bd6581ceada53ad14b08bc1d852 | [
"Apache-2.0"
] | null | null | null | include/help_line.hpp | matt-harvey/swx | e7b10fe7d4bf0bd6581ceada53ad14b08bc1d852 | [
"Apache-2.0"
] | 1 | 2020-04-27T09:24:42.000Z | 2020-04-27T09:24:42.000Z | /*
* Copyright 2014 Matthew Harvey
*
* 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.
*/
#ifndef GUARD_help_line_hpp_07384218837779118
#define GUARD_help_line_hpp_07384218837779118
#include <string>
namespace swx
{
/**
* Represents a line of help information for presentation to user,
* describing a particular string of arguments that might be passed to
* a command or command option, together with a description of how the
* command or option is used in conjunction with that string of arguments.
*/
class HelpLine
{
// special member functions
public:
HelpLine
( std::string const& p_usage_descriptor,
std::string const& p_args_descriptor = std::string()
);
HelpLine(char const* p_usage_descriptor);
// accessors
public:
std::string usage_descriptor() const;
std::string args_descriptor() const;
// data members
private:
std::string m_usage_descriptor;
std::string m_args_descriptor;
}; // class HelpLine
} // namespace swx
#endif // GUARD_help_line_hpp_07384218837779118
| 27.140351 | 75 | 0.740142 | matt-harvey |
d4da5e2271d4defc822bb600d756a6ff27a0535e | 214 | hpp | C++ | include/transactions/entities/BillGates.hpp | perriera/blockchain | 2c89ecc110dcc9c042bdb919c7cf3017a43d4ce8 | [
"MIT"
] | null | null | null | include/transactions/entities/BillGates.hpp | perriera/blockchain | 2c89ecc110dcc9c042bdb919c7cf3017a43d4ce8 | [
"MIT"
] | null | null | null | include/transactions/entities/BillGates.hpp | perriera/blockchain | 2c89ecc110dcc9c042bdb919c7cf3017a43d4ce8 | [
"MIT"
] | null | null | null | #ifndef _BILLGATES_HPP
#define _BILLGATES_HPP
#include <iostream>
#include "../../../extra/include/Definitions.hpp"
#include "../Entity.hpp"
class BillGates extends Entity {
public:
};
#endif // _BILLGATES_HPP
| 15.285714 | 49 | 0.728972 | perriera |
d4dc6e15a639a65d420fa629c3ea962a0daa2b07 | 5,268 | hpp | C++ | src/sdglib/readers/FileReader.hpp | KatOfCats/sdg | 1916e5c86dd88e601ab7476f38daef2bd3b3b6fc | [
"MIT"
] | null | null | null | src/sdglib/readers/FileReader.hpp | KatOfCats/sdg | 1916e5c86dd88e601ab7476f38daef2bd3b3b6fc | [
"MIT"
] | null | null | null | src/sdglib/readers/FileReader.hpp | KatOfCats/sdg | 1916e5c86dd88e601ab7476f38daef2bd3b3b6fc | [
"MIT"
] | null | null | null | //
// Created by Luis Yanes (EI) on 15/09/2017.
//
#ifndef SEQSORTER_FILEREADER_H
#define SEQSORTER_FILEREADER_H
#include <cstring>
#include <fstream>
#include <iostream>
#include <fcntl.h>
#include <sdglib/readers/Common.hpp>
#include <sdglib/utilities/OutputLog.hpp>
#include "kseq.hpp"
struct FastxReaderParams {
uint32_t min_length=0;
};
struct FastaRecord {
int32_t id;
std::string name,seq;
};
template<typename FileRecord>
class FastaReader {
public:
/**
* @brief
* Initialises the FastaReader, opens the file based on the format and instantiates a reader (plain, gzip or bzip2)
* @param params
* Parameters for filtering the records (i.e. min_size, max_size)
* @param filepath
* Relative or absolute path to the file that is going to be read.
*/
explicit FastaReader(FastxReaderParams params, const std::string &filepath) : params(params), numRecords(0) {
sdglib::OutputLog(sdglib::LogLevels::INFO) << "Opening: " << filepath << "\n";
gz_file = gzopen(filepath.c_str(), "r");
if (gz_file == Z_NULL || gz_file == NULL) {
sdglib::OutputLog(sdglib::LogLevels::WARN) << "Error opening FASTA " << filepath << ": " << std::strerror(errno) << std::endl;
throw std::runtime_error("Error opening " + filepath + ": " + std::strerror(errno));
}
ks = new kstream<gzFile, FunctorZlib>(gz_file, gzr);
}
~FastaReader() {
delete ks;
gzclose(gz_file);
}
/**
* @brief
* Calls the file reader and places the fields from the file onto the FileRecord, the ID is set to the
* number of records seen so far.
* @param rec
* Input/Output parameter where the file fields will be stored.
* @return
* Whether the function will generate another object or not
*/
bool next_record(FileRecord& rec) {
int l;
do {
l=(ks -> readFasta(seq));
std::swap(rec.seq, seq.seq);
std::swap(rec.name, seq.name);
rec.id = numRecords;
numRecords++;
stats.totalLength+=rec.seq.size();
} while(rec.seq.size() < params.min_length && l >= 0);
stats.filteredRecords++;
stats.filteredLength+=rec.seq.size();
return (l >= 0);
}
ReaderStats getSummaryStatistics() {
stats.totalRecords = numRecords;
return stats;
}
private:
kstream<gzFile, FunctorZlib> *ks;
kstream<BZFILE, FunctorBZlib2> *bzKS;
kseq seq;
uint32_t numRecords = 0;
gzFile gz_file;
BZFILE * bz_File{};
int fq_File{};
FunctorZlib gzr;
FunctorRead rr;
FastxReaderParams params;
ReaderStats stats;
};
struct FastqRecord{
int64_t id;
std::string name, comment, seq, qual;
};
template<typename FileRecord>
class FastqReader {
public:
/**
* @brief
* Initialises the FastaReader, opens the file based on the format and instantiates a reader (plain, gzip or bzip2)
* @param params
* Parameters for filtering the records (i.e. min_size, max_size)
* @param filepath
* Relative or absolute path to the file that is going to be read.
*/
explicit FastqReader(FastxReaderParams params, const std::string &filepath) : params(params), numRecords(0),eof_flag(false) {
sdglib::OutputLog() << "Opening: " << filepath << "\n";
gz_file = gzopen(filepath.c_str(), "r");
if (gz_file == Z_NULL) {
std::cout << "Error opening FASTQ " << filepath << ": " << std::strerror(errno) << std::endl;
throw std::runtime_error("Error opening " + filepath + ": " + std::strerror(errno));
}
ks = new kstream<gzFile, FunctorZlib>(gz_file, gzr);
}
/**
* @brief
* Calls the file reader and places the fields from the file onto the FileRecord, the ID is set to the
* number of records seen so far.
* @param rec
* Input/Output parameter where the file fields will be stored.
* @return
* Whether the function will generate another object or not
*/
bool next_record(FileRecord& rec) {
int l;
if ( eof_flag) return false;
{
do {
l = (ks->readFastq(seq));
std::swap(rec.seq, seq.seq);
std::swap(rec.qual, seq.qual);
std::swap(rec.name, seq.name);
std::swap(rec.comment, seq.comment);
rec.id = numRecords;
numRecords++;
stats.totalLength += rec.seq.size();
} while (rec.seq.size() < params.min_length && l >= 0);
}
if (l<0) eof_flag=true;
else {
stats.filteredRecords++;
stats.filteredLength += rec.seq.size();
}
return (l >= 0);
}
ReaderStats getSummaryStatistics() {
stats.totalRecords=numRecords;
return stats;
}
~FastqReader() {
gzclose(gz_file);
delete ks;
}
private:
kstream<gzFile, FunctorZlib> *ks;
kseq seq;
uint64_t numRecords=0;
gzFile gz_file;
BZFILE * bz_File{};
int fq_File{};
FunctorZlib gzr;
FastxReaderParams params;
ReaderStats stats;
bool eof_flag;
};
#endif //SEQSORTER_FILEREADER_H
| 29.931818 | 138 | 0.598899 | KatOfCats |
d4deb6b981b269ca0640f61198ac0b4a875d4c86 | 491 | cpp | C++ | components/scene_graph/tests/serialization/scene_context3.cpp | untgames/funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 7 | 2016-03-30T17:00:39.000Z | 2017-03-27T16:04:04.000Z | components/scene_graph/tests/serialization/scene_context3.cpp | untgames/Funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 4 | 2017-11-21T11:25:49.000Z | 2018-09-20T17:59:27.000Z | components/scene_graph/tests/serialization/scene_context3.cpp | untgames/Funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 4 | 2016-11-29T15:18:40.000Z | 2017-03-27T16:04:08.000Z | #include "shared.h"
bool check_exception (const char* message)
{
printf ("check_exception(%s)\n", message);
return true;
}
int main ()
{
printf ("Results of scene_context3_test:\n");
try
{
SceneContext context;
context.RegisterErrorHandler ("error:*", &check_exception);
printf ("check: %d\n", context.FilterError ("error: my error"));
}
catch (std::exception& e)
{
printf ("%s\n", e.what ());
}
return 0;
}
| 16.931034 | 69 | 0.572301 | untgames |
d4dff52a394af88ac0a4c7adf5509891fdc9bf38 | 1,761 | cpp | C++ | LeetCode/617. Merge Two Binary Trees.cpp | shamiul94/Problem-Solving-Online-Judges | 0387ccd02cc692c70429b4683311070dc9d69b28 | [
"MIT"
] | 2 | 2019-11-10T18:42:11.000Z | 2020-07-04T07:05:22.000Z | LeetCode/617. Merge Two Binary Trees.cpp | shamiul94/Problem-Solving-Online-Judges | 0387ccd02cc692c70429b4683311070dc9d69b28 | [
"MIT"
] | null | null | null | LeetCode/617. Merge Two Binary Trees.cpp | shamiul94/Problem-Solving-Online-Judges | 0387ccd02cc692c70429b4683311070dc9d69b28 | [
"MIT"
] | 1 | 2019-11-04T11:05:17.000Z | 2019-11-04T11:05:17.000Z | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// my original solution
// 96%, 80%
class Solution1 {
public:
TreeNode *mergeTrees(TreeNode *t1, TreeNode *t2) {
if (t1 == 0 && t2 == 0) {
return 0;
} else if (t1 != 0 && t2 != 0) {
int newVal;
newVal = t1->val + t2->val;
t1->val = newVal;
t1->left = mergeTrees(t1->left, t2->left);
t1->right = mergeTrees(t1->right, t2->right);
return t1;
} else if (t1 != 0 && t2 == 0) {
return t1;
} else if (t1 == 0 && t2 != 0) {
return t2;
}
return 0;
}
};
//////////////////
// my original solution
// 96%, 80%
class Solution2 {
public:
TreeNode *mergeTrees(TreeNode *t1, TreeNode *t2) {
if (t1 == 0 && t2 == 0) {
return 0;
} else if (t1 != 0 && t2 != 0) {
int newVal;
newVal = t1->val + t2->val;
t1->val = newVal;
t1->left = mergeTrees(t1->left, t2->left);
t1->right = mergeTrees(t1->right, t2->right);
return t1;
} else if (t1 != 0) {
return t1;
} else {
return t2;
}
return 0;
}
};
////////////////////
// 99%, 40%
class Solution3 {
public:
TreeNode *mergeTrees(TreeNode *t1, TreeNode *t2) {
if (!t1 || !t2) return t1 ? t1 : t2;
TreeNode *node = new TreeNode(t1->val + t2->val);
node->left = mergeTrees(t1->left, t2->left);
node->right = mergeTrees(t1->right, t2->right);
return node;
}
}; | 23.797297 | 59 | 0.451448 | shamiul94 |
d4e1aecf20faef926ca29686f1962cabc17116de | 5,299 | cpp | C++ | ReferenceDesign/SampleQTHMI/SDLApps/Templates/ChoiceSet/test/ChoiceSetTest.cpp | zenghuan1/HMI_SDK_LIB | d0d03af04abe07f5ca087cabcbb1e4f4858f266a | [
"BSD-3-Clause"
] | 8 | 2019-01-04T10:08:39.000Z | 2021-12-13T16:34:08.000Z | ReferenceDesign/SampleQTHMI/SDLApps/Templates/ChoiceSet/test/ChoiceSetTest.cpp | zenghuan1/HMI_SDK_LIB | d0d03af04abe07f5ca087cabcbb1e4f4858f266a | [
"BSD-3-Clause"
] | 33 | 2017-07-27T09:51:59.000Z | 2018-07-13T09:45:52.000Z | ReferenceDesign/SampleQTHMI/SDLApps/Templates/ChoiceSet/test/ChoiceSetTest.cpp | JH-G/HMI_SDK_LIB | caa4eac66d1f3b76349ef5d6ca5cf7dd69fcd760 | [
"BSD-3-Clause"
] | 12 | 2017-07-28T02:54:53.000Z | 2022-02-20T15:48:24.000Z | #include "ChoiceSetTest.h"
using namespace test;
using namespace hmi_sdk;
using namespace rpc_test;
CChoiceSetTest::CChoiceSetTest()
{
}
void CChoiceSetTest::SetUpTestCase()
{
}
void CChoiceSetTest::TearDownTestCase()
{
}
void CChoiceSetTest::SetUp()
{
}
void CChoiceSetTest::TearDown()
{
}
TEST_F(CChoiceSetTest,OnVRPerformInteraction_Success)
{
AppListMock appListMock;
AppDataMock appDataMock;
appListMock.DelegateGetActiveApp();
EXPECT_CALL(appListMock,getActiveApp()).WillRepeatedly(Return(&appDataMock));
EXPECT_CALL(appDataMock,OnPerformInteraction(PERFORMINTERACTION_TIMEOUT, 0, true));
EXPECT_CALL(appDataMock,OnPerformInteraction(PERFORMINTERACTION_TIMEOUT, 0, false));
CChoiceSet choiceSet(&appListMock);
choiceSet.OnTimeOut();
}
TEST_F(CChoiceSetTest,OnPerformInteraction_Success)
{
AppListMock appListMock;
AppDataMock appDataMock;
appListMock.DelegateGetActiveApp();
EXPECT_CALL(appListMock,getActiveApp()).WillRepeatedly(Return(&appDataMock));
EXPECT_CALL(appDataMock,OnPerformInteraction(PERFORMINTERACTION_TIMEOUT, 0, true));
EXPECT_CALL(appDataMock,OnPerformInteraction(PERFORMINTERACTION_TIMEOUT, 0, false));
CChoiceSet choiceSet(&appListMock);
choiceSet.OnTimeOut();
}
TEST_F(CChoiceSetTest,OnPerformInteraction_OnListItemClicked_Success)
{
AppListMock appListMock;
AppDataMock appDataMock;
appListMock.DelegateGetActiveApp();
EXPECT_CALL(appListMock,getActiveApp()).WillRepeatedly(Return(&appDataMock));
EXPECT_CALL(appDataMock,OnPerformInteraction(PERFORMINTERACTION_CHOICE, 0, _)).Times(AtLeast(1));
CChoiceSet choiceSet(&appListMock);
choiceSet.OnListItemClicked(0);
}
TEST_F(CChoiceSetTest,OnPerformInteraction_OnChoiceVRClicked_Success)
{
AppListMock appListMock;
AppDataMock appDataMock;
appListMock.DelegateGetActiveApp();
EXPECT_CALL(appListMock,getActiveApp()).WillRepeatedly(Return(&appDataMock));
EXPECT_CALL(appDataMock,OnPerformInteraction(PERFORMINTERACTION_TIMEOUT, 0, _)).Times(AtLeast(1));
CChoiceSet choiceSet(&appListMock);
choiceSet.OnChoiceVRClicked();
}
TEST_F(CChoiceSetTest,OnPerformInteraction_OnReturnBtnClicked_Success)
{
AppListMock appListMock;
AppDataMock appDataMock;
appListMock.DelegateGetActiveApp();
EXPECT_CALL(appListMock,getActiveApp()).WillRepeatedly(Return(&appDataMock));
EXPECT_CALL(appDataMock,OnPerformInteraction(RESULT_ABORTED, 0, _)).Times(AtLeast(1));
CChoiceSet choiceSet(&appListMock);
choiceSet.OnReturnBtnClicked();
}
TEST_F(CChoiceSetTest,getInteractionJson_Success)
{
AppListMock appListMock;
UIInterfaceMock uiManagerMock;
Json::Value obj;
Json::Value appList_;
Json::Value eleArr_;
Json::Value element1;
Json::Value element2;
element1["appName"] = "Music1";
element1["appID"] = 3;
element1["icon"] = "";
element2["appName"] = "Music2";
element2["appID"] = 4;
element2["icon"] = "";
eleArr_.append(element1);
eleArr_.append(element2);
appList_["applications"] = eleArr_;
obj["id"] = 64;
obj["jsonrpc"] = "2.0";
obj["method"] = "BasicCommunication.UpdateAppList";
obj["params"] = appList_;
appListMock.DelegateOnRequest(obj);
appListMock.DelegateSetUIManager(&uiManagerMock);
EXPECT_CALL(appListMock,onRequest(obj)).Times(AtLeast(1));
EXPECT_CALL(appListMock,setUIManager(&uiManagerMock));
EXPECT_CALL(uiManagerMock,onAppShow(ID_APPLINK)).Times(AtLeast(1));
appListMock.setUIManager(&uiManagerMock);
appListMock.onRequest(obj);
appListMock.DelegateGetActiveApp();
EXPECT_CALL(appListMock,getActiveApp());
EXPECT_FALSE(appListMock.getActiveApp());
Json::Value appObj;
Json::Value appId;
appObj["method"] = "BasicCommunication.ActivateApp";
appId["appID"] = 3;
appObj["id"] = 64;
appObj["jsonrpc"] = "2.0";
appObj["params"] = appId;
appListMock.DelegateOnRequest(appObj);
EXPECT_CALL(appListMock,onRequest(appObj)).Times(AtLeast(1));
appListMock.onRequest(appObj);
EXPECT_CALL(appListMock,getActiveApp()).Times(AtLeast(1));
EXPECT_TRUE(appListMock.getActiveApp());
Json::Value InteractionObj;
Json::Value choiceSet;
Json::Value params;
Json::Value initialText;
initialText["fieldName"] = "initialInteractionText";
initialText["fieldText"] = "1111111";
for (int i = 0; i< 10;++i)
{
Json::Value choiceSetEle;
choiceSetEle["choiceID"] = i+1;
choiceSetEle["menuName"] = QString(("MenuName" + QString::number(i+1))).toStdString();
choiceSet.append(choiceSetEle);
}
params["appID"] = 3;
params["choiceSet"] = choiceSet;
params["initialText"] = initialText;
InteractionObj["method"] = "UI.PerformInteraction";
InteractionObj["id"] = 127;
InteractionObj["jsonrpc"] = "2.0";
InteractionObj["params"] = params;
appListMock.DelegateOnRequest(InteractionObj);
EXPECT_CALL(appListMock,onRequest(InteractionObj)).Times(AtLeast(1));
appListMock.onRequest(InteractionObj);
EXPECT_EQ(3,appListMock.getActiveApp()->getInteractionJson()["Choiceset"]["params"]["appID"].asInt());
// CChoiceSet* cChoiceSet = new CChoiceSet(&appListMock);
// cChoiceSet->show();
}
| 27.743455 | 106 | 0.727873 | zenghuan1 |
d4e2dd83c76f0b0a14894f820e24dfbe83c08613 | 5,574 | cpp | C++ | src/bitwise-cpp/main_unopt.cpp | rogerdahl/cuda-bitwise | 4fc1576ecafc6521cc02b5ffd5a1ae7e6feb1ea0 | [
"MIT"
] | null | null | null | src/bitwise-cpp/main_unopt.cpp | rogerdahl/cuda-bitwise | 4fc1576ecafc6521cc02b5ffd5a1ae7e6feb1ea0 | [
"MIT"
] | 1 | 2018-02-22T02:14:41.000Z | 2018-02-22T04:07:37.000Z | src/bitwise-cpp/main_unopt.cpp | rogerdahl/cuda-bitwise | 4fc1576ecafc6521cc02b5ffd5a1ae7e6feb1ea0 | [
"MIT"
] | null | null | null | // Style: http://geosoft.no/development/cppstyle.html
#include <chrono>
#include <iostream>
#include <stack>
#include <vector>
#include <cppformat/format.h>
#include "int_types.h"
using namespace std;
using namespace fmt;
// The first version of this program would take 2500 hours to run. This was reduced to 250 hours by changing the stack
// type from std::stack to std::vector and clearing and reusing the std::vector for each program evaluation. The
// std::stack could not be cleared and therefore had to be recreated for each program evaluation.
enum Operation {
LD_A, LD_B, LD_C, LD_D, AND, OR, XOR, NOT, ENUM_END
};
const vector<string> opStrVec = {"v1", "v2", "v3", "v4", "and", "or", "xor", "not", "ENUM_END"};
typedef vector<Operation> OperationVec;
typedef vector<u16> U16Stack;
typedef std::chrono::high_resolution_clock Time;
typedef std::chrono::duration<float> Fsec;
void nextProgram(OperationVec& program);
bool evalProgram(u16& truthTable, const OperationVec& program);
bool evalOperation(U16Stack& s, Operation operation);
u16 pop(U16Stack& s);
string serializeProgram(const OperationVec& program);
int main() {
const u32 nSearchLevels = 15;
const u64 nTotalPossiblePrograms = pow(static_cast<int>(ENUM_END), nSearchLevels);
const u32 nPossibleTruthTables = 1 << 16;
// 1 << 16 to cover the full search space. Lower values for testing and benchmarking.
const u32 nSearchTruthTables = 1 << 16;
print("Total possible programs: {}\n", nTotalPossiblePrograms);
u32 nFoundTruthTables = 0;
u64 nProgramsEvaluated = 0;
u64 nValidPrograms = 0;
OperationVec program = {LD_A};
vector<OperationVec> foundOperationVec(nPossibleTruthTables);
auto startTime = Time::now();
while (nFoundTruthTables < nSearchTruthTables) {
u16 truthTable;
bool isValidProgram = evalProgram(truthTable, program);
if (isValidProgram) {
++nValidPrograms;
if (!foundOperationVec[truthTable].size()) {
foundOperationVec[truthTable] = program;
++nFoundTruthTables;
}
}
++nProgramsEvaluated;
if (!(nProgramsEvaluated & 0xffffff) || nFoundTruthTables == nSearchTruthTables) {
Fsec elapsedSec = Time::now() - startTime;
print("\nTotal time: {:.2f}s\n", elapsedSec.count());
print("Hours until done: {:.2f}\n", static_cast<float>(nTotalPossiblePrograms) / nProgramsEvaluated * elapsedSec.count() / 60.0f / 60.0f);
print("Programs evaluated: {} ({:f}%)\n", nProgramsEvaluated, static_cast<float>(nProgramsEvaluated) / nTotalPossiblePrograms * 100.0f);
print("Programs evaluated per second: {:d}\n", static_cast<int>(nProgramsEvaluated / elapsedSec.count()));
print("Valid programs: {} ({:.2f}%)\n", nValidPrograms, static_cast<float>(nValidPrograms) / nProgramsEvaluated * 100.0f);
print("Found truth tables: {} ({:.2f}%)\n", nFoundTruthTables, static_cast<float>(nFoundTruthTables) / nSearchTruthTables * 100.0f);
print("Last evaluated: {} ({} ops)\n", serializeProgram(program), program.size());
}
nextProgram(program);
}
return 0;
}
void nextProgram(OperationVec& program) {
auto nOperations = program.size();
for (u32 i = 0; i < nOperations; ++i) {
program[i] = static_cast<Operation>(static_cast<int>(program[i]) + 1);
if (program[i] != ENUM_END) {
break;
}
program[i] = LD_A;
if (i == nOperations - 1) {
program.push_back(LD_A);
}
}
}
// Find the truth table for a given program.
// Return true for valid programs. For a program to be valid, it must not cause a stack underflow during evaluation
// and must leave exactly one value on the stack when completed.
bool evalProgram(u16& truthTable, const OperationVec& program) {
static U16Stack s;
s.clear();
for (auto operation : program) {
bool stackIsValid = evalOperation(s, operation);
if (!stackIsValid) {
return false;
}
}
if (s.size() != 1) {
return false;
}
truthTable = s.back();
return true;
}
bool evalOperation(U16Stack& s, Operation operation) {
switch (operation) {
case LD_A:
s.push_back(0b0000000011111111);
break;
case LD_B:
s.push_back(0b0000111100001111);
break;
case LD_C:
s.push_back(0b0011001100110011);
break;
case LD_D:
s.push_back(0b0101010101010101);
break;
case AND:
if (s.size() < 2) return false;
s.push_back(pop(s) & pop(s));
break;
case OR:
if (s.size() < 2) return false;
s.push_back(pop(s) | pop(s));
break;
case XOR:
if (s.size() < 2) return false;
s.push_back(pop(s) ^ pop(s));
break;
case NOT:
if (!s.size()) return false;
s.push_back(~pop(s));
break;
case ENUM_END:
assert(false);
}
return true;
}
u16 pop(U16Stack& s) {
u16 v = s.back();
s.pop_back();
return v;
}
string serializeProgram(const OperationVec& program)
{
string s;
for (auto operation : program) {
s += format("{} ", opStrVec[static_cast<int>(operation)]);
}
return s;
}
u64 pow(u32 base, u32 exp)
{
u64 r = base;
for (u32 i = 0; i < exp; ++i) {
r *= base;
}
return r;
}
| 32.034483 | 150 | 0.61446 | rogerdahl |
d4e7f73096ec165db0e99002e18f0747627aea84 | 15,597 | cc | C++ | src/driver/tcp/TcpConnection.cc | lsgw/longd | 31caabd42a47c05857ae98716ef877052092aabe | [
"MIT"
] | null | null | null | src/driver/tcp/TcpConnection.cc | lsgw/longd | 31caabd42a47c05857ae98716ef877052092aabe | [
"MIT"
] | null | null | null | src/driver/tcp/TcpConnection.cc | lsgw/longd | 31caabd42a47c05857ae98716ef877052092aabe | [
"MIT"
] | null | null | null | #include "driver.h"
#include "Buffer.h"
#include "sockets.h"
#include "tcp.h"
#include <strings.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
class TcpConnnection : public driver<TcpConnnection> {
public:
void init(PortPtr port, MessagePtr& message) override
{
assert(message->type == MSG_TYPE_TCP);
time_t now = 0;
char timebuf[32];
struct tm tm;
now = time(NULL);
localtime_r(&now, &tm);
// gmtime_r(&now, &tm);
strftime(timebuf, sizeof timebuf, "%Y.%m.%d-%H:%M:%S", &tm);
start_ = timebuf;
state_ = kConnecting;
TcpPacket* packet = static_cast<TcpPacket*>(message->data);
assert(packet->type == TcpPacket::kShift);
assert(packet->shift.fd > 0);
fd_ = packet->shift.fd;
state_ = kConnected;
PortCtl(port, port->id(), 0, port->owner());
// printf("TcpConnnection id=%d init fd = %d\n", port->id(), packet->shift.fd);
}
void release(PortPtr port, MessagePtr& message) override
{
port->channel(fd_)->disableAll()->update();
sockets::close(fd_);
state_ = kDisconnected;
// printf("TcpConnnection id=%d release fd = %d\n", port->id(), fd_);
}
bool receive(PortPtr port, MessagePtr& message) override
{
if (message->type == MSG_TYPE_TCP) {
TcpPacket* packet = static_cast<TcpPacket*>(message->data);
switch (packet->type) {
case TcpPacket::kRead:
return recv(port, message->source, packet->session, packet->read.nbyte);
case TcpPacket::kWrite:
return send(port, packet);
case TcpPacket::kClose:
return close(port, message->source, packet->id);
case TcpPacket::kShutdown:
return shutdown(port, message->source, packet->id);
case TcpPacket::kOpts:
return setopts(port, packet);
case TcpPacket::kLowWaterMark:
return lowWaterMark(port, packet->lowWaterMark.on, packet->lowWaterMark.value);
case TcpPacket::kHighWaterMark:
return highWaterMark(port, packet->highWaterMark.on, packet->highWaterMark.value);
case TcpPacket::kInfo:
return getinfo(port, message->source, packet->session);
default:
return true;
}
} else if (message->type == MSG_TYPE_EVENT) {
Event* event = static_cast<Event*>(message->data);
switch (event->type) {
case Event::kRead:
return handleIoReadEvent(port, event->fd);
case Event::kWrite:
return handleIoWriteEvent(port, event->fd);
case Event::kError:
return true;
default:
return true;
}
} else {
assert(false);
return true;
}
}
bool setopts(PortPtr port, TcpPacket* packet)
{
// printf("port->id() = %d, setopts\n", port->id());
if (packet->opts.optsbits & 0B00000001) {
// printf("port->id() = %d, opts.reuseaddr = %d\n", port->id(), packet->opts.reuseaddr);
reuseaddr_ = packet->opts.reuseaddr;
}
if (packet->opts.optsbits & 0B00000010) {
// printf("port->id() = %d, opts.reuseport = %d\n", port->id(), packet->opts.reuseport);
reuseport_ = packet->opts.reuseport;
}
if (packet->opts.optsbits & 0B00000100) {
// printf("port->id() = %d, opts.keepalive = %d\n", port->id(), packet->opts.keepalive);
keepalive_ = packet->opts.keepalive;
sockets::setKeepAlive(fd_, keepalive_);
}
if (packet->opts.optsbits & 0B00001000) {
// printf("port->id() = %d, opts.nodelay = %d\n", port->id(), packet->opts.nodelay);
nodelay_ = packet->opts.nodelay;
sockets::setTcpNoDelay(fd_, nodelay_);
}
if (packet->opts.optsbits & 0B00010000) {
// printf("port->id() = %d, opts.active = %d\n", port->id(), packet->opts.active);
active_ = packet->opts.active;
}
if (packet->opts.optsbits & 0B00100000) {
// printf("port->id() = %d, opts.owner = %d\n", port->id(), packet->opts.owner);
if (port->owner() != packet->opts.owner) {
PortCtl(port, port->id(), port->owner(), packet->opts.owner);
port->setOwner(packet->opts.owner);
}
}
if (packet->opts.optsbits & 0B01000000) {
// printf("port->id() = %d, opts.read = %d\n", port->id(), packet->opts.read);
read_ = packet->opts.read;
if (read_) {
port->channel(fd_)->enableReading()->update();
} else {
port->channel(fd_)->disableReading()->update();
}
}
return true;
}
bool handleIoReadEvent(PortPtr port, int fd)
{
assert(fd_ == fd);
int savedErrno = 0;
ssize_t n = inputBuffer_.readFd(fd, &savedErrno);
if (n > 0) {
readCount_ += n;
}
// printf("port->id() = %d, new message = %zd, active = %d, fd = %d, \n", port->id(), n, active_, fd_);
if (active_) {
if (n > 0) {
TcpPacket* packet = (TcpPacket*)malloc(sizeof(TcpPacket) + n);
packet->type = TcpPacket::kRead;
packet->id = port->id();
packet->session = 0;
packet->read.nbyte = n;
memcpy(packet->read.data, inputBuffer_.peek(), n);
inputBuffer_.retrieve(n);
auto msg = port->makeMessage();
msg->type = MSG_TYPE_TCP;
msg->data = packet;
msg->size = sizeof(TcpPacket) + n;
port->send(port->owner(), msg);
return true;
} else if (n == 0) {
if (state_ == kDisconnecting) {
port->channel(fd_)->disableReading()->update();
close(port, port->owner(), port->id());
} else {
TcpPacket* packet = (TcpPacket*)malloc(sizeof(TcpPacket));
packet->type = TcpPacket::kRead;
packet->id = port->id();
packet->session = 0;
packet->read.nbyte = 0;
auto msg = port->makeMessage();
msg->type = MSG_TYPE_TCP;
msg->data = packet;
msg->size = sizeof(TcpPacket);
port->send(port->owner(), msg);
port->channel(fd_)->disableReading()->update();
state_ = kDisconnecting;
}
return true;
} else {
char t_errnobuf[512] = {'\0'};
strerror_r(savedErrno, t_errnobuf, sizeof t_errnobuf);
fprintf(stderr, "port->id() = %d, fd = %d read error=%s\n", port->id(), fd, t_errnobuf);
return true;
}
} else {
if (n > 0) {
if (inputBuffer_.readableBytes() >= highWaterMark_) {
port->channel(fd_)->disableReading()->update();
}
} else if (n == 0) {
if (state_ == kDisconnecting) {
port->channel(fd_)->disableReading()->update();
close(port, port->owner(), port->id());
} else {
port->channel(fd_)->disableReading()->update();
state_ = kDisconnecting;
}
}
}
return true;
}
bool handleIoWriteEvent(PortPtr port, int fd)
{
// static uint32_t i = 0;
// i++;
assert(fd_ == fd);
if (port->channel(fd_)->isWriting()) {
ssize_t n = sockets::write(fd_, outputBuffer_.peek(), outputBuffer_.readableBytes());
// if (i < 5) {
// printf("port->id() = %d, total = %zd, write = %zd, i = %d\n", port->id(), outputBuffer_.readableBytes(), n, i);
// }
if (n > 0) {
writeCount_ += n;
outputBuffer_.retrieve(n);
// 低水位回调
if (outputBuffer_.readableBytes() <= lowWaterMark_ && lowWaterMarkResponse_ && state_ == kConnected) {
TcpPacket* packet = (TcpPacket*)malloc(sizeof(TcpPacket));
packet->type = TcpPacket::kLowWaterMark;
packet->id = port->id();
packet->session = 0;
packet->lowWaterMark.on = true;
packet->lowWaterMark.value = outputBuffer_.readableBytes();
auto msg = port->makeMessage();
msg->type = MSG_TYPE_TCP;
msg->data = packet;
msg->size = sizeof(TcpPacket);
port->send(port->owner(), msg);
}
if (outputBuffer_.readableBytes() == 0) {
port->channel(fd_)->disableWriting()->update();
if (state_ == kDisconnecting) {
// close(port, port->owner(), port->id());
sockets::shutdownWrite(fd_);
}
}
} else {
char t_errnobuf[512] = {'\0'};
strerror_r(errno, t_errnobuf, sizeof t_errnobuf);
// fprintf(stderr, "port->id() = %d, fd = %d, errno = %d, write error = %s\n", port->id(), fd, errno, t_errnobuf);
port->channel(fd_)->disableWriting()->update();
// if (state_ == kDisconnecting)
// {
// sockets::shutdownWrite(connfd_);
// }
}
} else {
//LOG_TRACE << "Connection fd = " << channel_->fd() << " is down, no more writing";
}
return true;
}
bool send(PortPtr port, TcpPacket* packet)
{
// printf("port->id() = %d, send total message = %d\n", port->id(), cmd->towrite.nbyte);
const void* data = static_cast<const void*>(packet->write.data);
size_t len = packet->write.nbyte;
ssize_t nwrote = 0;
size_t remaining = len;
bool faultError = false;
if (state_ != kConnected) {
return true;
}
// if no thing in output queue, try writing directly
if (!port->channel(fd_)->isWriting() && outputBuffer_.readableBytes() == 0) {
nwrote = sockets::write(fd_, data, len);
if (nwrote >= 0) {
writeCount_ += nwrote;
remaining = len - nwrote;
// 低水位回调
if (remaining <= lowWaterMark_ && lowWaterMarkResponse_) {
TcpPacket* packet = (TcpPacket*)malloc(sizeof(TcpPacket));
packet->type = TcpPacket::kLowWaterMark;
packet->id = port->id();
packet->session = 0;
packet->lowWaterMark.on = true;
packet->lowWaterMark.value = remaining;
auto msg = port->makeMessage();
msg->type = MSG_TYPE_TCP;
msg->data = packet;
msg->size = sizeof(TcpPacket);
port->send(port->owner(), msg);
}
} else { // nwrote < 0
nwrote = 0;
if (errno != EWOULDBLOCK) {
if (errno == EPIPE || errno == ECONNRESET) { // FIXME: any others?
faultError = true;
}
}
}
}
assert(remaining <= len);
if (!faultError && remaining > 0) {
size_t oldLen = outputBuffer_.readableBytes();
// 高水位回调
if (oldLen + remaining >= highWaterMark_ && oldLen < highWaterMark_ && highWaterMarkResponse_) {
TcpPacket* packet = (TcpPacket*)malloc(sizeof(TcpPacket));
packet->type = TcpPacket::kHighWaterMark;
packet->id = port->id();
packet->session = 0;
packet->highWaterMark.on = true;
packet->highWaterMark.value = oldLen + remaining;
auto msg = port->makeMessage();
msg->type = MSG_TYPE_TCP;
msg->data = packet;
msg->size = sizeof(TcpPacket);
port->send(port->owner(), msg);
}
outputBuffer_.append(static_cast<const char*>(data)+nwrote, remaining);
if (!port->channel(fd_)->isWriting()) {
// printf("port->id() = %d, enableWriting\n", port->id());
port->channel(fd_)->enableWriting()->update();
}
}
// printf("port->id() = %d, send save message = %zd\n", port->id(), outputBuffer_.readableBytes());
return true;
}
bool recv(PortPtr port, uint32_t source, uint32_t session, int nbyte)
{
size_t size = static_cast<size_t>(nbyte);
assert(port->owner() == source);
assert(state_ == kConnected || state_ == kDisconnecting);
// printf("port->id() = %d, total = %zu, read msg start size = %d\n", port->id(), inputBuffer_.readableBytes(), size);
if (state_ == kDisconnecting && inputBuffer_.readableBytes() == 0) {
// printf("port->id() = %d, read msg 0, close connection\n", port->id());
TcpPacket* packet = (TcpPacket*)malloc(sizeof(TcpPacket));
packet->type = TcpPacket::kRead;
packet->id = port->id();
packet->session = session;
packet->read.nbyte = 0;
auto msg = port->makeMessage();
msg->type = MSG_TYPE_TCP;
msg->data = packet;
msg->size = sizeof(TcpPacket);
port->send(source, msg);
return true;
}
if (state_ == kDisconnecting && inputBuffer_.readableBytes() <= size) {
// printf("port->id() = %d, read all msg, close connection\n", port->id());
int n = inputBuffer_.readableBytes();
TcpPacket* packet = (TcpPacket*)malloc(sizeof(TcpPacket) + n);
packet->type = TcpPacket::kRead;
packet->id = port->id();
packet->session = session;
packet->read.nbyte = n;
memcpy(packet->read.data, inputBuffer_.peek(), n);
inputBuffer_.retrieve(n);
auto msg = port->makeMessage();
msg->type = MSG_TYPE_TCP;
msg->data = packet;
msg->size = sizeof(TcpPacket) + n;
port->send(source, msg);
return true;
}
if (state_ == kConnected && read_ && inputBuffer_.readableBytes() <= size && !port->channel(fd_)->isReading()) {
port->channel(fd_)->enableReading()->update();
return false;
}
if (inputBuffer_.readableBytes() == 0) {
return false;
}
if (inputBuffer_.readableBytes() < size) {
return false;
}
int n = size>0? size : inputBuffer_.readableBytes();
TcpPacket* packet = (TcpPacket*)malloc(sizeof(TcpPacket) + n);
packet->type = TcpPacket::kRead;
packet->id = port->id();
packet->session = session;
packet->read.nbyte = n;
memcpy(packet->read.data, inputBuffer_.peek(), n);
inputBuffer_.retrieve(n);
auto msg = port->makeMessage();
msg->type = MSG_TYPE_TCP;
msg->data = packet;
msg->size = sizeof(TcpPacket) + n;
port->send(source, msg);
// printf("port->id() = %d, read msg size %d [ok]\n", port->id(), n);
return true;
}
bool shutdown(PortPtr port, uint32_t source, uint32_t id)
{
// printf("port->id() = %d, shutdown\n", port->id());
assert(port->owner() == source);
assert(port->id() == id);
if (state_ == kConnected || state_ == kDisconnecting) {
// printf("shutdown to close1\n");
if (state_ == kDisconnecting) {
close(port, port->owner(), port->id());
return true;
}
if (!port->channel(fd_)->isWriting()) {
// printf("shutdown to close2\n");
// close(port, port->owner(), port->id());
sockets::shutdownWrite(fd_);
state_ = kDisconnecting;
return true;
}
}
return true;
}
bool close(PortPtr port, uint32_t source, uint32_t id)
{
// printf("port->id() = %d, close\n", port->id());
assert(port->owner() == source);
assert(port->id() == id);
assert(state_ == kConnected || state_ == kDisconnecting);
PortCtl(port, port->id(), port->owner(), 0);
// we don't close fd, leave it to dtor, so we can find leaks easily.
port->exit();
return true;
}
bool lowWaterMark(PortPtr port, bool on, uint64_t value)
{
lowWaterMarkResponse_ = on;
lowWaterMark_ = value;
return true;
}
bool highWaterMark(PortPtr port, bool on, uint64_t value)
{
highWaterMarkResponse_ = on;
highWaterMark_ = value;
return true;
}
bool getinfo(PortPtr port, uint32_t source, uint32_t session)
{
struct sockaddr_in6 addr6 = sockets::getPeerAddr(fd_);
struct sockaddr* addr = (struct sockaddr*)&addr6;
TcpPacket* packet = (TcpPacket*)malloc(sizeof(TcpPacket));
memset(packet, 0, sizeof(TcpPacket));
packet->type = TcpPacket::kInfo;
packet->id = port->id();
packet->session = session;
sockets::toIp(packet->info.ip, 64, addr);
packet->info.port = sockets::toPort(addr);
packet->info.ipv6 = addr->sa_family == AF_INET6;
memcpy(packet->info.start, start_.data(), start_.size());
packet->info.owner = port->owner();
packet->info.readCount = readCount_;
packet->info.readBuff = inputBuffer_.readableBytes();
packet->info.writeCount = writeCount_;
packet->info.writeBuff = outputBuffer_.readableBytes();
auto msg = port->makeMessage();
msg->type = MSG_TYPE_TCP;
msg->data = packet;
msg->size = sizeof(TcpPacket);
port->send(source, msg);
return true;
}
private:
enum State {kConnecting, kConnected, kDisconnecting, kDisconnected};
State state_;
int fd_ = 0;
Buffer inputBuffer_;
Buffer outputBuffer_;
// 高低水位回调设置
bool lowWaterMarkResponse_ = false;
bool highWaterMarkResponse_ = false;
uint64_t lowWaterMark_ = 0;
uint64_t highWaterMark_ = 1024*1024*1024;
bool reuseaddr_ = false;
bool reuseport_ = false;
bool keepalive_ = false;
bool nodelay_ = false;
bool active_ = false;
bool read_ = false;
std::string start_;
uint32_t readCount_ = 0;
uint32_t writeCount_ = 0;
};
reg(TcpConnnection)
| 31.509091 | 120 | 0.623838 | lsgw |
d4e812eef103969aebf1cacaaa70cb49ecaaf4be | 534 | cpp | C++ | path_planning/a_star/main.cpp | EatAllBugs/cpp_robotics | f0ee1b936f8f3d40ec78c30846cd1fbdf72ef27c | [
"MIT"
] | 1 | 2022-01-23T13:17:28.000Z | 2022-01-23T13:17:28.000Z | path_planning/a_star/main.cpp | yinflight/cpp_robotics | f0ee1b936f8f3d40ec78c30846cd1fbdf72ef27c | [
"MIT"
] | null | null | null | path_planning/a_star/main.cpp | yinflight/cpp_robotics | f0ee1b936f8f3d40ec78c30846cd1fbdf72ef27c | [
"MIT"
] | 1 | 2022-01-23T13:17:16.000Z | 2022-01-23T13:17:16.000Z | #include <iostream>
#include "a_star.hpp"
using namespace cpp_robotics::path_planning;
int main() {
std::cout << "Hello, World!" << std::endl;
//! load map data
cv::Mat map_data = cv::imread("../maps/map2.png", CV_8UC1);
if (map_data.empty()) {
std::cerr << "load map image fail." << std::endl;
return -1;
}
//! a_star
std::cout << map_data.size() << std::endl;
a_star::Astar astar(a_star::Heuristic::euclidean, true);
astar.init(map_data);
auto path = astar.findPath({25,25}, {480, 480});
return 0;
} | 25.428571 | 61 | 0.625468 | EatAllBugs |
d4e918042e1f759e3b539c2da88ba2899876459b | 797 | cpp | C++ | 20. valid-parentheses.cpp | dipta007/leetcode-solutions-dipta007 | 0454ad24ce686a37fab8025c75efb7d857985f29 | [
"MIT"
] | null | null | null | 20. valid-parentheses.cpp | dipta007/leetcode-solutions-dipta007 | 0454ad24ce686a37fab8025c75efb7d857985f29 | [
"MIT"
] | null | null | null | 20. valid-parentheses.cpp | dipta007/leetcode-solutions-dipta007 | 0454ad24ce686a37fab8025c75efb7d857985f29 | [
"MIT"
] | null | null | null | class Solution {
public:
bool isValid(string s) {
stack <char> st;
int flg = 1;
for(int i=0; i<s.size(); i++)
{
if(s[i]=='(' || s[i]=='{' || s[i]=='[')
st.push(s[i]);
else
{
if(st.size()==0)
{
flg = 0;
break;
}
char ch = st.top();
st.pop();
cout << ch << endl;
if(ch=='(' && s[i]==')') ;
else if(ch=='{' && s[i]=='}') ;
else if(ch=='[' && s[i]==']') ;
else flg = 0;
}
cout << flg << endl;
}
if(st.size()) flg = 0;
return flg;
}
}; | 24.151515 | 51 | 0.250941 | dipta007 |
d4efde9b136113af189a2a5097ff79e210b5f240 | 872 | cc | C++ | zircon/system/ulib/lockdep/lock_dep.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 5 | 2022-01-10T20:22:17.000Z | 2022-01-21T20:14:17.000Z | zircon/system/ulib/lockdep/lock_dep.cc | PlugFox/fuchsia | 39afe5230d41628b3c736a6e384393df954968c8 | [
"BSD-2-Clause"
] | 2 | 2021-09-19T21:55:09.000Z | 2021-12-19T03:34:53.000Z | zircon/system/ulib/lockdep/lock_dep.cc | PlugFox/fuchsia | 39afe5230d41628b3c736a6e384393df954968c8 | [
"BSD-2-Clause"
] | 1 | 2021-08-23T11:33:57.000Z | 2021-08-23T11:33:57.000Z | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Default weak implementation of integration routines appropriate for
// userspace. The kernel has its own versions of these symbols that
// override this implementation.
//
#include <zircon/compiler.h>
#include <lockdep/lockdep.h>
namespace lockdep {
// Default implementation of the runtime functions supporting the thread-local
// ThreadLockState. These MUST be overridden in environments that do not support
// the C++ thread_local TLS mechanism.
__WEAK ThreadLockState* SystemGetThreadLockState(LockFlags lock_flags) {
thread_local ThreadLockState thread_lock_state{};
return &thread_lock_state;
}
__WEAK void SystemInitThreadLockState(ThreadLockState* state) {}
} // namespace lockdep
| 30.068966 | 80 | 0.78555 | allansrc |
d4f027e29b231c1032a15d9481272ce7db913a8a | 791 | cpp | C++ | LeetCode/ThousandOne/0287-find_duplicated_num.cpp | Ginkgo-Biloba/Cpp-Repo1-VS | 231c68a055e6bf69a3f7c224e7c0182b67ce5b67 | [
"Apache-2.0"
] | null | null | null | LeetCode/ThousandOne/0287-find_duplicated_num.cpp | Ginkgo-Biloba/Cpp-Repo1-VS | 231c68a055e6bf69a3f7c224e7c0182b67ce5b67 | [
"Apache-2.0"
] | null | null | null | LeetCode/ThousandOne/0287-find_duplicated_num.cpp | Ginkgo-Biloba/Cpp-Repo1-VS | 231c68a055e6bf69a3f7c224e7c0182b67ce5b67 | [
"Apache-2.0"
] | null | null | null | #include "leetcode.hpp"
/* 287. 寻找重复数
给定一个包含 n + 1 个整数的数组 nums,其数字都在 1 到 n 之间(包括 1 和 n),可知至少存在一个重复的整数。
假设只有一个重复的整数,找出这个重复的数。
示例 1:
输入: [1,3,4,2,2]
输出: 2
示例 2:
输入: [3,1,3,4,2]
输出: 3
说明:
不能更改原数组(假设数组是只读的)。
只能使用额外的 O(1) 的空间。
时间复杂度小于 O(n^2) 。
数组中只有一个重复的数字,但它可能不止重复出现一次。
*/
int findDuplicate(vector<int>& A)
{
int len = static_cast<int>(A.size());
for (int i = 0; i < len;)
{
if (A[i] == i + 1)
++i;
else
{
if (A[A[i] - 1] != A[i])
std::swap(A[A[i] - 1], A[i]);
else
return A[i];
}
}
return 0;
}
int main()
{
vector<int>
a = { 1, 3, 4, 2, 2 },
b = { 3, 1, 3, 4, 2 },
c = { 1, 1, 2 },
d = { 3, 3, 3, 3 };
OutExpr(findDuplicate(a), "%d");
OutExpr(findDuplicate(b), "%d");
OutExpr(findDuplicate(c), "%d");
OutExpr(findDuplicate(d), "%d");
}
| 14.125 | 64 | 0.529709 | Ginkgo-Biloba |
d4f1e66d9a1adde53e06f995979180dcd749f5d0 | 2,467 | cpp | C++ | firmware/main/TimeService.cpp | opiopan/elflet | 78a8a38f552d12d812f50d6b13b4db6110020211 | [
"Apache-2.0"
] | 6 | 2019-01-09T15:01:32.000Z | 2020-12-30T20:39:02.000Z | firmware/main/TimeService.cpp | opiopan/elflet | 78a8a38f552d12d812f50d6b13b4db6110020211 | [
"Apache-2.0"
] | 1 | 2019-04-08T02:56:27.000Z | 2019-04-22T06:31:43.000Z | firmware/main/TimeService.cpp | opiopan/elflet | 78a8a38f552d12d812f50d6b13b4db6110020211 | [
"Apache-2.0"
] | 2 | 2020-12-30T20:39:07.000Z | 2021-09-27T19:23:29.000Z | #include <esp_log.h>
#include <esp_system.h>
#include <string.h>
#include <GeneralUtils.h>
#include <Task.h>
#include <freertos/event_groups.h>
#include "Mutex.h"
#include "Config.h"
#include "TimeObj.h"
#include "SensorService.h"
#include "TimeService.h"
#include "Stat.h"
#include "WatchDog.h"
#include "boardconfig.h"
#include "sdkconfig.h"
static const char tag[] = "TimeService";
class TimeTask;
static TimeTask* task;
//----------------------------------------------------------------------
// SNTP time adjustment task
//----------------------------------------------------------------------
class TimeTask : public Task {
protected:
static const int EV_WAKE_SERVER = 1;
EventGroupHandle_t events;
public:
TimeTask();
virtual ~TimeTask();
void enable();
protected:
void run(void *data) override;
};
TimeTask::TimeTask(){
events = xEventGroupCreate();
}
TimeTask::~TimeTask(){
}
void TimeTask::enable(){
xEventGroupSetBits(events, EV_WAKE_SERVER);
}
void TimeTask::run(void *data){
ESP_LOGI(tag, "timezone set to: %s", elfletConfig->getTimezone());
Time::setTZ(elfletConfig->getTimezone());
xEventGroupWaitBits(events, EV_WAKE_SERVER,
pdTRUE, pdFALSE,
portMAX_DELAY);
bool first = true;
while (true){
if (Time::shouldAdjust(elfletConfig->getWakeupCause() != WC_NOTSLEEP)){
ESP_LOGI(tag, "start SNTP & wait for finish adjustment");
Time::startSNTP();
if (!Time::waitForFinishAdjustment(3)){
ESP_LOGE(tag, "fail to adjust time by SNTP");
}
Time now;
ESP_LOGI(tag, "adjusted time: %s",
now.format(Time::SIMPLE_DATETIME));
if (baseStat.boottime < 60 * 60 * 24 * 365){
baseStat.boottime = now.getTime();
}
updateWatchDog();
}
if (first){
first = false;
enableSensorCapturing();
}
vTaskDelay(60 * 60 * 1000 / portTICK_PERIOD_MS);
}
}
//----------------------------------------------------------------------
// module interface
//----------------------------------------------------------------------
bool startTimeService(){
if (!task){
task = new TimeTask;
task->setStackSize(2048);
task->start();
}
return true;
}
void notifySMTPserverAccesivility(){
task->enable();
}
| 23.951456 | 79 | 0.528172 | opiopan |
d4f2f70717ce542d8b524f37266924a3ed61637b | 19,726 | cpp | C++ | Backends/Graphics5/Vulkan/Sources/Kore/PipelineState5Impl.cpp | hyperluminality/Kinc | f1802becc92e9a9eaa2e13b205d6a18eb58359a3 | [
"Zlib"
] | null | null | null | Backends/Graphics5/Vulkan/Sources/Kore/PipelineState5Impl.cpp | hyperluminality/Kinc | f1802becc92e9a9eaa2e13b205d6a18eb58359a3 | [
"Zlib"
] | null | null | null | Backends/Graphics5/Vulkan/Sources/Kore/PipelineState5Impl.cpp | hyperluminality/Kinc | f1802becc92e9a9eaa2e13b205d6a18eb58359a3 | [
"Zlib"
] | null | null | null | #include "pch.h"
#include "Vulkan.h"
#include <kinc/graphics5/shader.h>
#include <kinc/graphics5/pipeline.h>
#include <assert.h>
#include <malloc.h>
#include <map>
#include <string>
#include <string.h>
extern VkDevice device;
extern VkRenderPass render_pass;
extern VkDescriptorSet desc_set;
bool memory_type_from_properties(uint32_t typeBits, VkFlags requirements_mask, uint32_t* typeIndex);
void createDescriptorLayout(PipelineState5Impl* pipeline);
kinc_g5_pipeline_t *currentPipeline = NULL;
static bool has_number(kinc_internal_named_number *named_numbers, const char *name) {
for (int i = 0; i < KINC_INTERNAL_NAMED_NUMBER_COUNT; ++i) {
if (strcmp(named_numbers[i].name, name) == 0) {
return true;
}
}
return false;
}
static uint32_t find_number(kinc_internal_named_number *named_numbers, const char *name) {
for (int i = 0; i < KINC_INTERNAL_NAMED_NUMBER_COUNT; ++i) {
if (strcmp(named_numbers[i].name, name) == 0) {
return named_numbers[i].number;
}
}
return 0;
}
static void set_number(kinc_internal_named_number *named_numbers, const char *name, uint32_t number) {
for (int i = 0; i < KINC_INTERNAL_NAMED_NUMBER_COUNT; ++i) {
if (strcmp(named_numbers[i].name, name) == 0) {
named_numbers[i].number = number;
return;
}
}
for (int i = 0; i < KINC_INTERNAL_NAMED_NUMBER_COUNT; ++i) {
if (named_numbers[i].name[0] == 0) {
strcpy(named_numbers[i].name, name);
named_numbers[i].number = number;
return;
}
}
assert(false);
}
namespace {
void parseShader(kinc_g5_shader_t *shader, kinc_internal_named_number *locations, kinc_internal_named_number *textureBindings,
kinc_internal_named_number *uniformOffsets) {
memset(locations, 0, sizeof(kinc_internal_named_number) * KINC_INTERNAL_NAMED_NUMBER_COUNT);
memset(textureBindings, 0, sizeof(kinc_internal_named_number) * KINC_INTERNAL_NAMED_NUMBER_COUNT);
memset(uniformOffsets, 0, sizeof(kinc_internal_named_number) * KINC_INTERNAL_NAMED_NUMBER_COUNT);
uint32_t *spirv = (uint32_t *)shader->impl.source;
int spirvsize = shader->impl.length / 4;
int index = 0;
unsigned magicNumber = spirv[index++];
unsigned version = spirv[index++];
unsigned generator = spirv[index++];
unsigned bound = spirv[index++];
index++;
std::map<uint32_t, std::string> names;
std::map<uint32_t, std::string> memberNames;
std::map<uint32_t, uint32_t> locs;
std::map<uint32_t, uint32_t> bindings;
std::map<uint32_t, uint32_t> offsets;
while (index < spirvsize) {
int wordCount = spirv[index] >> 16;
uint32_t opcode = spirv[index] & 0xffff;
uint32_t *operands = wordCount > 1 ? &spirv[index + 1] : nullptr;
uint32_t length = wordCount - 1;
switch (opcode) {
case 5: { // OpName
uint32_t id = operands[0];
char* string = (char*)&operands[1];
names[id] = string;
break;
}
case 6: { // OpMemberName
uint32_t type = operands[0];
if (names[type] == "_k_global_uniform_buffer_type") {
uint32_t member = operands[1];
char* string = (char*)&operands[2];
memberNames[member] = string;
}
break;
}
case 71: { // OpDecorate
uint32_t id = operands[0];
uint32_t decoration = operands[1];
if (decoration == 30) { // location
uint32_t location = operands[2];
locs[id] = location;
}
if (decoration == 33) { // binding
uint32_t binding = operands[2];
bindings[id] = binding;
}
break;
}
case 72: { // OpMemberDecorate
uint32_t type = operands[0];
if (names[type] == "_k_global_uniform_buffer_type") {
uint32_t member = operands[1];
uint32_t decoration = operands[2];
if (decoration == 35) { // offset
uint32_t offset = operands[3];
offsets[member] = offset;
}
}
}
}
index += wordCount;
}
for (std::map<uint32_t, uint32_t>::iterator it = locs.begin(); it != locs.end(); ++it) {
set_number(locations, names[it->first].c_str(), it->second);
}
for (std::map<uint32_t, uint32_t>::iterator it = bindings.begin(); it != bindings.end(); ++it) {
set_number(textureBindings, names[it->first].c_str(), it->second);
}
for (std::map<uint32_t, uint32_t>::iterator it = offsets.begin(); it != offsets.end(); ++it) {
set_number(uniformOffsets, memberNames[it->first].c_str(), it->second);
}
}
VkShaderModule demo_prepare_shader_module(const void* code, size_t size) {
VkShaderModuleCreateInfo moduleCreateInfo;
VkShaderModule module;
VkResult err;
moduleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
moduleCreateInfo.pNext = NULL;
moduleCreateInfo.codeSize = size;
moduleCreateInfo.pCode = (const uint32_t*)code;
moduleCreateInfo.flags = 0;
err = vkCreateShaderModule(device, &moduleCreateInfo, NULL, &module);
assert(!err);
return module;
}
VkShaderModule demo_prepare_vs(VkShaderModule& vert_shader_module, kinc_g5_shader_t *vertexShader) {
vert_shader_module = demo_prepare_shader_module(vertexShader->impl.source, vertexShader->impl.length);
return vert_shader_module;
}
VkShaderModule demo_prepare_fs(VkShaderModule& frag_shader_module, kinc_g5_shader_t *fragmentShader) {
frag_shader_module = demo_prepare_shader_module(fragmentShader->impl.source, fragmentShader->impl.length);
return frag_shader_module;
}
}
void kinc_g5_pipeline_init(kinc_g5_pipeline_t *pipeline) {
pipeline->vertexShader = nullptr;
pipeline->fragmentShader = nullptr;
pipeline->geometryShader = nullptr;
pipeline->tessellationEvaluationShader = nullptr;
pipeline->tessellationControlShader = nullptr;
createDescriptorLayout(&pipeline->impl);
Kore::Vulkan::createDescriptorSet(&pipeline->impl, nullptr, nullptr, desc_set);
}
void kinc_g5_pipeline_destroy(kinc_g5_pipeline_t *pipeline) {}
kinc_g5_constant_location_t kinc_g5_pipeline_get_constant_location(kinc_g5_pipeline_t *pipeline, const char *name) {
kinc_g5_constant_location_t location;
location.impl.vertexOffset = -1;
location.impl.fragmentOffset = -1;
if (has_number(pipeline->impl.vertexOffsets, name)) {
location.impl.vertexOffset = find_number(pipeline->impl.vertexOffsets, name);
}
if (has_number(pipeline->impl.fragmentOffsets, name)) {
location.impl.fragmentOffset = find_number(pipeline->impl.fragmentOffsets, name);
}
return location;
}
kinc_g5_texture_unit_t kinc_g5_pipeline_get_texture_unit(kinc_g5_pipeline_t *pipeline, const char *name) {
kinc_g5_texture_unit_t unit;
unit.impl.binding = find_number(pipeline->impl.textureBindings, name);
return unit;
}
void kinc_g5_pipeline_compile(kinc_g5_pipeline_t *pipeline) {
parseShader(pipeline->vertexShader, pipeline->impl.vertexLocations, pipeline->impl.textureBindings, pipeline->impl.vertexOffsets);
parseShader(pipeline->fragmentShader, pipeline->impl.fragmentLocations, pipeline->impl.textureBindings, pipeline->impl.fragmentOffsets);
//
VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = {};
pPipelineLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pPipelineLayoutCreateInfo.pNext = NULL;
pPipelineLayoutCreateInfo.setLayoutCount = 1;
pPipelineLayoutCreateInfo.pSetLayouts = &pipeline->impl.desc_layout;
VkResult err = vkCreatePipelineLayout(device, &pPipelineLayoutCreateInfo, NULL, &pipeline->impl.pipeline_layout);
assert(!err);
//
VkGraphicsPipelineCreateInfo pipeline_info = {};
VkPipelineCacheCreateInfo pipelineCache_info = {};
VkPipelineInputAssemblyStateCreateInfo ia = {};
VkPipelineRasterizationStateCreateInfo rs = {};
VkPipelineColorBlendStateCreateInfo cb = {};
VkPipelineDepthStencilStateCreateInfo ds = {};
VkPipelineViewportStateCreateInfo vp = {};
VkPipelineMultisampleStateCreateInfo ms = {};
VkDynamicState dynamicStateEnables[VK_DYNAMIC_STATE_RANGE_SIZE];
VkPipelineDynamicStateCreateInfo dynamicState = {};
memset(dynamicStateEnables, 0, sizeof dynamicStateEnables);
memset(&dynamicState, 0, sizeof dynamicState);
dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
dynamicState.pDynamicStates = dynamicStateEnables;
memset(&pipeline_info, 0, sizeof(pipeline_info));
pipeline_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipeline_info.layout = pipeline->impl.pipeline_layout;
uint32_t stride = 0;
for (int i = 0; i < pipeline->inputLayout[0]->size; ++i) {
kinc_g5_vertex_element_t element = pipeline->inputLayout[0]->elements[i];
switch (element.data) {
case KINC_G4_VERTEX_DATA_COLOR:
stride += 1 * 4;
break;
case KINC_G4_VERTEX_DATA_FLOAT1:
stride += 1 * 4;
break;
case KINC_G4_VERTEX_DATA_FLOAT2:
stride += 2 * 4;
break;
case KINC_G4_VERTEX_DATA_FLOAT3:
stride += 3 * 4;
break;
case KINC_G4_VERTEX_DATA_FLOAT4:
stride += 4 * 4;
break;
case KINC_G4_VERTEX_DATA_FLOAT4X4:
stride += 4 * 4 * 4;
break;
}
}
VkVertexInputBindingDescription vi_bindings[1];
#ifdef KORE_WINDOWS
VkVertexInputAttributeDescription* vi_attrs = (VkVertexInputAttributeDescription*)alloca(sizeof(VkVertexInputAttributeDescription) * pipeline->inputLayout[0]->size);
#else
VkVertexInputAttributeDescription vi_attrs[pipeline->inputLayout[0]->size];
#endif
VkPipelineVertexInputStateCreateInfo vi = {};
vi.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
vi.pNext = NULL;
vi.vertexBindingDescriptionCount = 1;
vi.pVertexBindingDescriptions = vi_bindings;
vi.vertexAttributeDescriptionCount = pipeline->inputLayout[0]->size;
vi.pVertexAttributeDescriptions = vi_attrs;
vi_bindings[0].binding = 0;
vi_bindings[0].stride = stride;
vi_bindings[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
uint32_t offset = 0;
for (int i = 0; i < pipeline->inputLayout[0]->size; ++i) {
kinc_g5_vertex_element_t element = pipeline->inputLayout[0]->elements[i];
switch (element.data) {
case KINC_G4_VERTEX_DATA_COLOR:
vi_attrs[i].binding = 0;
vi_attrs[i].location = find_number(pipeline->impl.vertexLocations, element.name);
vi_attrs[i].format = VK_FORMAT_R32_UINT;
vi_attrs[i].offset = offset;
offset += 1 * 4;
break;
case KINC_G4_VERTEX_DATA_FLOAT1:
vi_attrs[i].binding = 0;
vi_attrs[i].location = find_number(pipeline->impl.vertexLocations, element.name);
vi_attrs[i].format = VK_FORMAT_R32_SFLOAT;
vi_attrs[i].offset = offset;
offset += 1 * 4;
break;
case KINC_G4_VERTEX_DATA_FLOAT2:
vi_attrs[i].binding = 0;
vi_attrs[i].location = find_number(pipeline->impl.vertexLocations, element.name);
vi_attrs[i].format = VK_FORMAT_R32G32_SFLOAT;
vi_attrs[i].offset = offset;
offset += 2 * 4;
break;
case KINC_G4_VERTEX_DATA_FLOAT3:
vi_attrs[i].binding = 0;
vi_attrs[i].location = find_number(pipeline->impl.vertexLocations, element.name);
vi_attrs[i].format = VK_FORMAT_R32G32B32_SFLOAT;
vi_attrs[i].offset = offset;
offset += 3 * 4;
break;
case KINC_G4_VERTEX_DATA_FLOAT4:
vi_attrs[i].binding = 0;
vi_attrs[i].location = find_number(pipeline->impl.vertexLocations, element.name);
vi_attrs[i].format = VK_FORMAT_R32G32B32A32_SFLOAT;
vi_attrs[i].offset = offset;
offset += 4 * 4;
break;
case KINC_G4_VERTEX_DATA_FLOAT4X4:
vi_attrs[i].binding = 0;
vi_attrs[i].location = find_number(pipeline->impl.vertexLocations, element.name);
vi_attrs[i].format = VK_FORMAT_R32G32B32A32_SFLOAT; // TODO
vi_attrs[i].offset = offset;
offset += 4 * 4 * 4;
break;
}
}
memset(&ia, 0, sizeof(ia));
ia.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
memset(&rs, 0, sizeof(rs));
rs.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rs.polygonMode = VK_POLYGON_MODE_FILL;
rs.cullMode = VK_CULL_MODE_NONE;
rs.frontFace = VK_FRONT_FACE_CLOCKWISE;
rs.depthClampEnable = VK_FALSE;
rs.rasterizerDiscardEnable = VK_FALSE;
rs.depthBiasEnable = VK_FALSE;
rs.lineWidth = 1.0f;
memset(&cb, 0, sizeof(cb));
cb.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
VkPipelineColorBlendAttachmentState att_state[1];
memset(att_state, 0, sizeof(att_state));
att_state[0].colorWriteMask = 0xf;
att_state[0].blendEnable = VK_FALSE;
cb.attachmentCount = 1;
cb.pAttachments = att_state;
memset(&vp, 0, sizeof(vp));
vp.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
vp.viewportCount = 1;
dynamicStateEnables[dynamicState.dynamicStateCount++] = VK_DYNAMIC_STATE_VIEWPORT;
vp.scissorCount = 1;
dynamicStateEnables[dynamicState.dynamicStateCount++] = VK_DYNAMIC_STATE_SCISSOR;
memset(&ds, 0, sizeof(ds));
ds.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
ds.depthTestEnable = VK_FALSE;
ds.depthWriteEnable = VK_FALSE;
ds.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL;
ds.depthBoundsTestEnable = VK_FALSE;
ds.back.failOp = VK_STENCIL_OP_KEEP;
ds.back.passOp = VK_STENCIL_OP_KEEP;
ds.back.compareOp = VK_COMPARE_OP_ALWAYS;
ds.stencilTestEnable = VK_FALSE;
ds.front = ds.back;
memset(&ms, 0, sizeof(ms));
ms.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
ms.pSampleMask = nullptr;
ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
pipeline_info.stageCount = 2;
VkPipelineShaderStageCreateInfo shaderStages[2];
memset(&shaderStages, 0, 2 * sizeof(VkPipelineShaderStageCreateInfo));
shaderStages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
shaderStages[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
shaderStages[0].module = demo_prepare_vs(pipeline->impl.vert_shader_module, pipeline->vertexShader);
shaderStages[0].pName = "main";
shaderStages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
shaderStages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
shaderStages[1].module = demo_prepare_fs(pipeline->impl.frag_shader_module, pipeline->fragmentShader);
shaderStages[1].pName = "main";
pipeline_info.pVertexInputState = &vi;
pipeline_info.pInputAssemblyState = &ia;
pipeline_info.pRasterizationState = &rs;
pipeline_info.pColorBlendState = &cb;
pipeline_info.pMultisampleState = &ms;
pipeline_info.pViewportState = &vp;
pipeline_info.pDepthStencilState = &ds;
pipeline_info.pStages = shaderStages;
pipeline_info.renderPass = render_pass;
pipeline_info.pDynamicState = &dynamicState;
memset(&pipelineCache_info, 0, sizeof(pipelineCache_info));
pipelineCache_info.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
err = vkCreatePipelineCache(device, &pipelineCache_info, nullptr, &pipeline->impl.pipelineCache);
assert(!err);
err = vkCreateGraphicsPipelines(device, pipeline->impl.pipelineCache, 1, &pipeline_info, nullptr, &pipeline->impl.pipeline);
assert(!err);
vkDestroyPipelineCache(device, pipeline->impl.pipelineCache, nullptr);
vkDestroyShaderModule(device, pipeline->impl.frag_shader_module, nullptr);
vkDestroyShaderModule(device, pipeline->impl.vert_shader_module, nullptr);
}
extern VkDescriptorPool desc_pool;
void createDescriptorLayout(PipelineState5Impl* pipeline) {
VkDescriptorSetLayoutBinding layoutBindings[8];
memset(layoutBindings, 0, sizeof(layoutBindings));
layoutBindings[0].binding = 0;
layoutBindings[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
layoutBindings[0].descriptorCount = 1;
layoutBindings[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
layoutBindings[0].pImmutableSamplers = nullptr;
layoutBindings[1].binding = 1;
layoutBindings[1].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
layoutBindings[1].descriptorCount = 1;
layoutBindings[1].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
layoutBindings[1].pImmutableSamplers = nullptr;
for (int i = 2; i < 8; ++i) {
layoutBindings[i].binding = i;
layoutBindings[i].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
layoutBindings[i].descriptorCount = 1;
layoutBindings[i].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
layoutBindings[i].pImmutableSamplers = nullptr;
}
VkDescriptorSetLayoutCreateInfo descriptor_layout = {};
descriptor_layout.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
descriptor_layout.pNext = NULL;
descriptor_layout.bindingCount = 8;
descriptor_layout.pBindings = layoutBindings;
VkResult err = vkCreateDescriptorSetLayout(device, &descriptor_layout, NULL, &pipeline->desc_layout);
assert(!err);
VkDescriptorPoolSize typeCounts[8];
memset(typeCounts, 0, sizeof(typeCounts));
typeCounts[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
typeCounts[0].descriptorCount = 1;
typeCounts[1].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
typeCounts[1].descriptorCount = 1;
for (int i = 2; i < 8; ++i) {
typeCounts[i].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
typeCounts[i].descriptorCount = 1;
}
VkDescriptorPoolCreateInfo descriptor_pool = {};
descriptor_pool.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
descriptor_pool.pNext = NULL;
descriptor_pool.maxSets = 128;
descriptor_pool.poolSizeCount = 8;
descriptor_pool.pPoolSizes = typeCounts;
err = vkCreateDescriptorPool(device, &descriptor_pool, NULL, &desc_pool);
assert(!err);
}
void Kore::Vulkan::createDescriptorSet(struct PipelineState5Impl_s *pipeline, kinc_g5_texture_t *texture, kinc_g5_render_target_t *renderTarget,
VkDescriptorSet &desc_set) {
// VkDescriptorImageInfo tex_descs[DEMO_TEXTURE_COUNT];
VkDescriptorBufferInfo buffer_descs[2];
VkDescriptorSetAllocateInfo alloc_info = {};
alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
alloc_info.pNext = NULL;
alloc_info.descriptorPool = desc_pool;
alloc_info.descriptorSetCount = 1;
alloc_info.pSetLayouts = &pipeline->desc_layout;
VkResult err = vkAllocateDescriptorSets(device, &alloc_info, &desc_set);
assert(!err);
memset(&buffer_descs, 0, sizeof(buffer_descs));
if (vertexUniformBuffer != nullptr) {
buffer_descs[0].buffer = *vertexUniformBuffer;
}
buffer_descs[0].offset = 0;
buffer_descs[0].range = 256 * sizeof(float);
if (fragmentUniformBuffer != nullptr) {
buffer_descs[1].buffer = *fragmentUniformBuffer;
}
buffer_descs[1].offset = 0;
buffer_descs[1].range = 256 * sizeof(float);
VkDescriptorImageInfo tex_desc;
memset(&tex_desc, 0, sizeof(tex_desc));
if (texture != nullptr) {
tex_desc.sampler = texture->impl.texture.sampler;
tex_desc.imageView = texture->impl.texture.view;
}
if (renderTarget != nullptr) {
tex_desc.sampler = renderTarget->impl.sampler;
tex_desc.imageView = renderTarget->impl.destView;
}
tex_desc.imageLayout = VK_IMAGE_LAYOUT_GENERAL;
VkWriteDescriptorSet writes[8];
memset(writes, 0, sizeof(writes));
writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
writes[0].dstSet = desc_set;
writes[0].dstBinding = 0;
writes[0].descriptorCount = 1;
writes[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
writes[0].pBufferInfo = &buffer_descs[0];
writes[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
writes[1].dstSet = desc_set;
writes[1].dstBinding = 1;
writes[1].descriptorCount = 1;
writes[1].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
writes[1].pBufferInfo = &buffer_descs[1];
for (int i = 2; i < 8; ++i) {
writes[i].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
writes[i].dstSet = desc_set;
writes[i].dstBinding = i;
writes[i].descriptorCount = 1;
writes[i].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
writes[i].pImageInfo = &tex_desc;
}
if (texture != nullptr || renderTarget != nullptr) {
if (vertexUniformBuffer != nullptr && fragmentUniformBuffer != nullptr) {
vkUpdateDescriptorSets(device, 3, writes, 0, nullptr);
}
else {
vkUpdateDescriptorSets(device, 1, writes + 2, 0, nullptr);
}
}
else {
if (vertexUniformBuffer != nullptr && fragmentUniformBuffer != nullptr) {
vkUpdateDescriptorSets(device, 2, writes, 0, nullptr);
}
}
}
| 34.913274 | 166 | 0.759302 | hyperluminality |
d4f4cbcd7969a06acff1d1c8ab2470fb19d63bc9 | 4,297 | cpp | C++ | src/object.cpp | ghewgill/neon-lang | e9bd686a6c566dc6e40f2816cab34c24725847c7 | [
"MIT"
] | 74 | 2016-01-18T12:20:53.000Z | 2022-01-16T10:26:29.000Z | src/object.cpp | ghewgill/neon-lang | e9bd686a6c566dc6e40f2816cab34c24725847c7 | [
"MIT"
] | 197 | 2015-01-02T03:50:59.000Z | 2022-01-24T05:40:39.000Z | src/object.cpp | ghewgill/neon-lang | e9bd686a6c566dc6e40f2816cab34c24725847c7 | [
"MIT"
] | 2 | 2015-04-01T03:54:19.000Z | 2021-11-29T08:27:12.000Z | #include "object.h"
#include <iso646.h>
#include "rtl_exec.h"
#include "intrinsic.h"
bool ObjectString::invokeMethod(const utf8string &name, const std::vector<std::shared_ptr<Object>> &args, std::shared_ptr<Object> &result) const
{
std::string method = name.str();
if (method == "length") {
if (args.size() != 0) {
throw RtlException(rtl::ne_global::Exception_DynamicConversionException, utf8string("invalid number of arguments to length() (expected 0)"));
}
result = std::shared_ptr<Object> { new ObjectNumber(number_from_uint64(s.length())) };
return true;
}
throw RtlException(rtl::ne_global::Exception_DynamicConversionException, utf8string("string object does not support this method"));
}
utf8string ObjectString::toLiteralString() const
{
return rtl::ne_string::quoted(s);
}
bool ObjectArray::invokeMethod(const utf8string &name, const std::vector<std::shared_ptr<Object>> &args, std::shared_ptr<Object> &result) const
{
std::string method = name.str();
if (method == "size") {
if (args.size() != 0) {
throw RtlException(rtl::ne_global::Exception_DynamicConversionException, utf8string("invalid number of arguments to size() (expected 0)"));
}
result = std::shared_ptr<Object> { new ObjectNumber(number_from_uint64(a.size())) };
return true;
}
throw RtlException(rtl::ne_global::Exception_DynamicConversionException, utf8string("array object does not support this method"));
}
bool ObjectArray::subscript(std::shared_ptr<Object> index, std::shared_ptr<Object> &r) const
{
Number i;
if (not index->getNumber(i)) {
throw RtlException(rtl::ne_global::Exception_DynamicConversionException, utf8string("to Number"));
}
uint64_t ii = number_to_uint64(i);
if (ii >= a.size()) {
throw RtlException(rtl::ne_global::Exception_ArrayIndexException, utf8string(number_to_string(i)));
}
r = a.at(ii);
return true;
}
utf8string ObjectArray::toString() const
{
utf8string r {"["};
bool first = true;
for (auto x: a) {
if (not first) {
r.append(", ");
} else {
first = false;
}
r.append(x != nullptr ? x->toLiteralString() : utf8string("null"));
}
r.append("]");
return r;
}
bool ObjectDictionary::invokeMethod(const utf8string &name, const std::vector<std::shared_ptr<Object>> &args, std::shared_ptr<Object> &result) const
{
std::string method = name.str();
if (method == "keys") {
if (args.size() != 0) {
throw RtlException(rtl::ne_global::Exception_DynamicConversionException, utf8string("invalid number of arguments to keys() (expected 0)"));
}
std::vector<std::shared_ptr<Object>> keys;
for (auto &x: d) {
keys.push_back(std::shared_ptr<Object> { new ObjectString(x.first) });
}
result = std::shared_ptr<Object> { new ObjectArray(keys) };
return true;
}
if (method == "size") {
if (args.size() != 0) {
throw RtlException(rtl::ne_global::Exception_DynamicConversionException, utf8string("invalid number of arguments to size() (expected 0)"));
}
result = std::shared_ptr<Object> { new ObjectNumber(number_from_uint64(d.size())) };
return true;
}
throw RtlException(rtl::ne_global::Exception_DynamicConversionException, utf8string("dictionary object does not support this method"));
}
bool ObjectDictionary::subscript(std::shared_ptr<Object> index, std::shared_ptr<Object> &r) const
{
utf8string i;
if (not index->getString(i)) {
throw RtlException(rtl::ne_global::Exception_DynamicConversionException, utf8string("to String"));
}
auto e = d.find(i);
if (e == d.end()) {
return false;
}
r = e->second;
return true;
}
utf8string ObjectDictionary::toString() const
{
utf8string r {"{"};
bool first = true;
for (auto x: d) {
if (not first) {
r.append(", ");
} else {
first = false;
}
r.append(rtl::ne_string::quoted(x.first));
r.append(": ");
r.append(x.second != nullptr ? x.second->toLiteralString() : utf8string("null"));
}
r.append("}");
return r;
}
| 34.653226 | 153 | 0.633698 | ghewgill |
d4f9674fffe5843af74927bd7aa16b04bacf6351 | 947 | cpp | C++ | C++/Core/stb_image.cpp | Ninjacoderhsi/ps3-emu-for-android | cc20876f56cf7d1d66be0f85d7f160acd574a97d | [
"Apache-2.0"
] | 1 | 2021-11-06T12:08:57.000Z | 2021-11-06T12:08:57.000Z | C++/Core/stb_image.cpp | Ninjacoderhsi/ps3-emu-for-android | cc20876f56cf7d1d66be0f85d7f160acd574a97d | [
"Apache-2.0"
] | null | null | null | C++/Core/stb_image.cpp | Ninjacoderhsi/ps3-emu-for-android | cc20876f56cf7d1d66be0f85d7f160acd574a97d | [
"Apache-2.0"
] | null | null | null | #include "stdafx.h"
// Defines STB_IMAGE_IMPLEMENTATION *once* for stb_image.h includes (Should this be placed somewhere else?)
#define STB_IMAGE_IMPLEMENTATION
// Sneak in truetype as well.
#define STB_TRUETYPE_IMPLEMENTATION
// This header generates lots of errors, so we ignore those (not rpcs3 code)
#ifdef _MSC_VER
#pragma warning(push, 0)
#include <stb_image.h>
#include <stb_truetype.h>
#pragma warning(pop)
#else
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wall"
#pragma GCC diagnostic ignored "-Wextra"
#pragma GCC diagnostic ignored "-Wold-style-cast"
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#pragma GCC diagnostic ignored "-Wcast-qual"
#ifndef __clang__
#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
#pragma GCC diagnostic ignored "-Wduplicated-branches"
#endif
#pragma GCC diagnostic ignored "-Wsign-compare"
#include <stb_image.h>
#include <stb_truetype.h>
#pragma GCC diagnostic pop
#endif
| 31.566667 | 107 | 0.786695 | Ninjacoderhsi |
d4fb32a3368516c4389196164784c0c4f0f1a07e | 2,481 | cc | C++ | parallel_clustering/clustering/util/dynamic_weight_threshold.cc | gunpowder78/google-research | d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5 | [
"Apache-2.0"
] | 1 | 2022-03-19T04:26:12.000Z | 2022-03-19T04:26:12.000Z | parallel_clustering/clustering/util/dynamic_weight_threshold.cc | gunpowder78/google-research | d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5 | [
"Apache-2.0"
] | null | null | null | parallel_clustering/clustering/util/dynamic_weight_threshold.cc | gunpowder78/google-research | d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5 | [
"Apache-2.0"
] | 1 | 2022-03-30T07:20:29.000Z | 2022-03-30T07:20:29.000Z | // Copyright 2022 The Google Research 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 "clustering/util/dynamic_weight_threshold.h"
#include <cmath>
#include "clustering/util/dynamic_weight_threshold.pb.h"
#include "absl/status/status.h"
namespace research_graph {
absl::StatusOr<double> DynamicWeightThreshold(
const DynamicWeightThresholdConfig& config, int num_iterations,
int iteration) {
if (num_iterations < 1)
return absl::InvalidArgumentError("num_iterations must be >= 1");
if (iteration < 0 || iteration >= num_iterations)
return absl::InvalidArgumentError(
"iteration must be between 0 and num_iterations-1 inclusive.");
if (num_iterations == 1) {
if (config.upper_bound() != config.lower_bound()) {
return absl::InvalidArgumentError(
"If num_iterations=1, upper and lower bounds must match.");
}
return config.upper_bound();
}
const double upper_bound = config.upper_bound();
const double lower_bound = config.lower_bound();
double dynamic_threshold;
switch (config.weight_decay_function()) {
case DynamicWeightThresholdConfig::LINEAR_DECAY:
dynamic_threshold =
upper_bound -
((upper_bound - lower_bound) / (num_iterations - 1)) * iteration;
return dynamic_threshold;
case DynamicWeightThresholdConfig::EXPONENTIAL_DECAY:
if (lower_bound <= 0 || upper_bound <= 0)
return absl::InvalidArgumentError(
"lower and upper bounds need to positive, if EXPONENTIAL_DECAY is "
"used");
dynamic_threshold =
upper_bound * std::pow(lower_bound / upper_bound,
static_cast<double>(iteration) /
static_cast<double>(num_iterations - 1));
return dynamic_threshold;
default:
return absl::InvalidArgumentError(
"Unsupported weight decay function provided");
}
}
} // namespace research_graph
| 36.485294 | 79 | 0.693672 | gunpowder78 |
d4fdbce446a6b7ad858c4027acf861aa891d4bfb | 2,449 | cpp | C++ | lib/bmm_lib.cpp | pkarakal/sparse-boolean-matrix-multiplication | 3384bf2dd2b86537177c1e91540ce2c77e95c785 | [
"MIT"
] | null | null | null | lib/bmm_lib.cpp | pkarakal/sparse-boolean-matrix-multiplication | 3384bf2dd2b86537177c1e91540ce2c77e95c785 | [
"MIT"
] | 1 | 2021-10-10T21:16:26.000Z | 2021-10-10T21:16:26.000Z | lib/bmm_lib.cpp | pkarakal/sparse-boolean-matrix-multiplication | 3384bf2dd2b86537177c1e91540ce2c77e95c785 | [
"MIT"
] | null | null | null | #include "bmm_lib.h"
namespace po = boost::program_options;
template<class T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
copy(v.begin(), v.end(), std::ostream_iterator<T>(os, " "));
return os;
}
void bmm_lib::parse_cli(int nargs, char** args,
std::vector<std::string>& paths) {
po::options_description desc("Allowed options");
desc.add_options()("help", "produce help message")(
"path,p", po::value<std::vector<std::string>>(), "input path to file");
po::variables_map vm;
po::store(po::parse_command_line(nargs, args, desc), vm);
po::notify(vm);
if (vm.count("help")) {
std::cout << desc << std::endl;
return;
}
paths = vm.count("path") ? vm["path"].as<std::vector<std::string>>()
: std::vector<std::string>();
}
#ifdef USE_MMIO_MATRICES
void bmm_lib::read_matrix(FILE* f, std::vector<uint32_t>& I,
std::vector<uint32_t>& J, std::vector<uint32_t>& val) {
MM_typecode matcode;
int M, N, nnz;
uint32_t i;
if (mm_read_banner(f, &matcode) != 0) {
printf("Could not process Matrix Market banner.\n");
exit(1);
}
/* This is how one can screen matrix types if their application */
/* only supports a subset of the Matrix Market data types. */
if (mm_is_complex(matcode) && mm_is_matrix(matcode) &&
mm_is_sparse(matcode)) {
printf("Sorry, this application does not support ");
printf("Market Market type: [%s]\n", mm_typecode_to_str(matcode));
exit(1);
}
/* find out size of sparse matrix .... */
if (mm_read_mtx_crd_size(f, &M, &N, &nnz) != 0)
exit(1);
I = std::vector<uint32_t>(nnz);
J = std::vector<uint32_t>(nnz);
val = std::vector<uint32_t>(nnz);
/* NOTE: when reading in doubles, ANSI C requires the use of the "l" */
/* specifier as in "%lg", "%lf", "%le", otherwise errors will occur */
/* (ANSI C X3.159-1989, Sec. 4.9.6.2, p. 136 lines 13-15) */
/* Replace missing val column with 1s and change the fscanf to match pattern
* matrices*/
if (!mm_is_pattern(matcode)) {
for (i = 0; i < nnz; i++) {
fscanf(f, "%d %d %lg\n", &I[i], &J[i], &val[i]);
I[i]--; /* adjust from 1-based to 0-based */
J[i]--;
}
} else {
for (i = 0; i < nnz; i++) {
fscanf(f, "%d %d\n", &I[i], &J[i]);
val[i] = 1;
I[i]--; /* adjust from 1-based to 0-based */
J[i]--;
}
}
if (f != stdin)
fclose(f);
if (M != N) {
printf("COO matrix' columns and rows are not the same");
}
}
#endif | 28.811765 | 78 | 0.604737 | pkarakal |
be025071df5eb19bb70f7c95c89c893d6bbd04e7 | 5,309 | hpp | C++ | deps/boost/include/boost/geometry/formulas/meridian_direct.hpp | kindlychung/mediasoup-sfu-cpp | f69d2f48f7edbf4f0c57244280a47bea985f39cf | [
"Apache-2.0"
] | 995 | 2018-06-22T10:39:18.000Z | 2022-03-25T01:22:14.000Z | deps/boost/include/boost/geometry/formulas/meridian_direct.hpp | kindlychung/mediasoup-sfu-cpp | f69d2f48f7edbf4f0c57244280a47bea985f39cf | [
"Apache-2.0"
] | 32 | 2018-06-23T14:19:37.000Z | 2022-03-29T10:20:37.000Z | deps/boost/include/boost/geometry/formulas/meridian_direct.hpp | kindlychung/mediasoup-sfu-cpp | f69d2f48f7edbf4f0c57244280a47bea985f39cf | [
"Apache-2.0"
] | 172 | 2018-06-22T11:12:00.000Z | 2022-03-29T07:44:33.000Z | // Boost.Geometry
// Copyright (c) 2018 Oracle and/or its affiliates.
// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
// Use, modification and distribution is subject to 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)
#ifndef BOOST_GEOMETRY_FORMULAS_MERIDIAN_DIRECT_HPP
#define BOOST_GEOMETRY_FORMULAS_MERIDIAN_DIRECT_HPP
#include <boost/math/constants/constants.hpp>
#include <boost/geometry/core/radius.hpp>
#include <boost/geometry/formulas/differential_quantities.hpp>
#include <boost/geometry/formulas/flattening.hpp>
#include <boost/geometry/formulas/meridian_inverse.hpp>
#include <boost/geometry/formulas/quarter_meridian.hpp>
#include <boost/geometry/formulas/result_direct.hpp>
#include <boost/geometry/util/condition.hpp>
#include <boost/geometry/util/math.hpp>
namespace boost { namespace geometry { namespace formula
{
/*!
\brief Compute the direct geodesic problem on a meridian
*/
template <
typename CT,
bool EnableCoordinates = true,
bool EnableReverseAzimuth = false,
bool EnableReducedLength = false,
bool EnableGeodesicScale = false,
unsigned int Order = 4
>
class meridian_direct
{
static const bool CalcQuantities = EnableReducedLength || EnableGeodesicScale;
static const bool CalcRevAzimuth = EnableReverseAzimuth || CalcQuantities;
static const bool CalcCoordinates = EnableCoordinates || CalcRevAzimuth;
public:
typedef result_direct<CT> result_type;
template <typename T, typename Dist, typename Spheroid>
static inline result_type apply(T const& lo1,
T const& la1,
Dist const& distance,
bool north,
Spheroid const& spheroid)
{
result_type result;
CT const half_pi = math::half_pi<CT>();
CT const pi = math::pi<CT>();
CT const one_and_a_half_pi = pi + half_pi;
CT const c0 = 0;
CT azimuth = north ? c0 : pi;
if (BOOST_GEOMETRY_CONDITION(CalcCoordinates))
{
CT s0 = meridian_inverse<CT, Order>::apply(la1, spheroid);
int signed_distance = north ? distance : -distance;
result.lon2 = lo1;
result.lat2 = apply(s0 + signed_distance, spheroid);
}
if (BOOST_GEOMETRY_CONDITION(CalcRevAzimuth))
{
result.reverse_azimuth = azimuth;
if (result.lat2 > half_pi &&
result.lat2 < one_and_a_half_pi)
{
result.reverse_azimuth = pi;
}
else if (result.lat2 < -half_pi &&
result.lat2 > -one_and_a_half_pi)
{
result.reverse_azimuth = c0;
}
}
if (BOOST_GEOMETRY_CONDITION(CalcQuantities))
{
CT const b = CT(get_radius<2>(spheroid));
CT const f = formula::flattening<CT>(spheroid);
boost::geometry::math::normalize_spheroidal_coordinates
<
boost::geometry::radian,
double
>(result.lon2, result.lat2);
typedef differential_quantities
<
CT,
EnableReducedLength,
EnableGeodesicScale,
Order
> quantities;
quantities::apply(lo1, la1, result.lon2, result.lat2,
azimuth, result.reverse_azimuth,
b, f,
result.reduced_length, result.geodesic_scale);
}
return result;
}
// https://en.wikipedia.org/wiki/Meridian_arc#The_inverse_meridian_problem_for_the_ellipsoid
// latitudes are assumed to be in radians and in [-pi/2,pi/2]
template <typename T, typename Spheroid>
static CT apply(T m, Spheroid const& spheroid)
{
CT const f = formula::flattening<CT>(spheroid);
CT n = f / (CT(2) - f);
CT mp = formula::quarter_meridian<CT>(spheroid);
CT mu = geometry::math::pi<CT>()/CT(2) * m / mp;
if (Order == 0)
{
return mu;
}
CT H2 = 1.5 * n;
if (Order == 1)
{
return mu + H2 * sin(2*mu);
}
CT n2 = n * n;
CT H4 = 1.3125 * n2;
if (Order == 2)
{
return mu + H2 * sin(2*mu) + H4 * sin(4*mu);
}
CT n3 = n2 * n;
H2 -= 0.84375 * n3;
CT H6 = 1.572916667 * n3;
if (Order == 3)
{
return mu + H2 * sin(2*mu) + H4 * sin(4*mu) + H6 * sin(6*mu);
}
CT n4 = n2 * n2;
H4 -= 1.71875 * n4;
CT H8 = 2.142578125 * n4;
// Order 4 or higher
return mu + H2 * sin(2*mu) + H4 * sin(4*mu) + H6 * sin(6*mu) + H8 * sin(8*mu);
}
};
}}} // namespace boost::geometry::formula
#endif // BOOST_GEOMETRY_FORMULAS_MERIDIAN_DIRECT_HPP
| 31.046784 | 97 | 0.556602 | kindlychung |
be02da1e4682e055e9bd49fd7c5f526f8bf1be96 | 2,031 | cpp | C++ | src/Graphics/Camera.cpp | khskarl/tori | 52e07e7b8bdbab7b46c4565a6be9353c0ce59422 | [
"MIT"
] | 2 | 2018-07-05T23:50:20.000Z | 2020-02-07T12:34:05.000Z | src/Graphics/Camera.cpp | khskarl/tori | 52e07e7b8bdbab7b46c4565a6be9353c0ce59422 | [
"MIT"
] | null | null | null | src/Graphics/Camera.cpp | khskarl/tori | 52e07e7b8bdbab7b46c4565a6be9353c0ce59422 | [
"MIT"
] | null | null | null | #include "Camera.hpp"
#include <glm/gtx/rotate_vector.hpp>
#include <glm/gtc/matrix_transform.hpp>
Camera::Camera () {
this->BuildProjectionMatrix();
}
Camera::Camera (const glm::vec3 pos, const glm::vec3 direction, const float width, const float height) {
m_position = pos;
m_direction = direction;
m_width = width;
m_height = height;
this->BuildProjectionMatrix();
}
void Camera::BuildProjectionMatrix () {
mProjectionMatrix = glm::perspective(glm::radians(m_fov),
GetAspectRatio(),
m_nearPlane,
m_farPlane);
}
glm::mat4 const Camera::GetViewMatrix () {
return glm::lookAt(m_position, m_position + m_direction, m_up);
}
glm::mat4 const& Camera::GetProjectionMatrix () {
return mProjectionMatrix;
}
glm::vec3 const& Camera::GetPosition () {
return m_position;
}
glm::vec3 const& Camera::GetDirection () {
return m_direction;
}
glm::vec3 const& Camera::GetUp () {
return m_up;
}
glm::vec3 const Camera::GetRight () {
return glm::normalize(glm::cross(m_direction, m_up));
}
float const Camera::GetAspectRatio () {
return m_width / m_height;
}
void Camera::MoveForward (const float amount) {
m_position += m_direction * amount;
}
void Camera::MoveRight (const float amount) {
m_position += GetRight() * amount;
}
void Camera::RotatePitch (const float amount) {
m_pitch += amount;
if (m_pitch > 90.f) m_pitch = 90.f - 0.001f;
if (m_pitch < -90.f) m_pitch = -90.f + 0.001f;
RecomputeDirection();
}
void Camera::RotateYaw (const float amount) {
m_yaw += amount;
if (m_yaw > 360.0f) m_yaw = 0.0f;
if (m_yaw < 0.0f) m_yaw = 360.0f;
RecomputeDirection();
}
void Camera::RecomputeDirection () {
float pitch = glm::radians(m_pitch);
float yaw = glm::radians(m_yaw);
m_direction = (glm::vec3(glm::cos(pitch) * glm::cos(yaw),
glm::sin(pitch),
glm::cos(pitch) * glm::sin(yaw)));
m_direction = glm::normalize(m_direction);\
}
| 24.178571 | 104 | 0.641556 | khskarl |
be066596eff08a474ecdb5dcd894bb7059ccebf7 | 2,428 | cc | C++ | src/generate_A440.cc | mpoullet/audio-tools | b7cb54ec16f2845830ab6168d8e6992124c98a75 | [
"MIT"
] | null | null | null | src/generate_A440.cc | mpoullet/audio-tools | b7cb54ec16f2845830ab6168d8e6992124c98a75 | [
"MIT"
] | null | null | null | src/generate_A440.cc | mpoullet/audio-tools | b7cb54ec16f2845830ab6168d8e6992124c98a75 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <cmath>
#include <iostream>
#include <numeric>
#include <vector>
#include <sndfile.hh>
int main ()
{
const auto pi{3.14159265358979323846264338};
const auto freq{440.0};
const auto duration{1.0};
const auto samplerate{48000};
const auto sample_duration{1.0 / samplerate};
const int sample_count = samplerate * std::round (duration);
std::cout << "duration=" << duration << "\n";
std::cout << "samplerate=" << samplerate << "\n";
std::cout << "sample_count=" << sample_count << "\n";
std::cout << "sample_duration=" << sample_duration << "\n";
std::cout << "freq=" << freq;
std::cout << std::endl;
std::vector<double> buffer (sample_count);
std::iota (std::begin (buffer), std::end (buffer), 0);
std::transform (std::begin (buffer), std::end (buffer), std::begin (buffer),
[&](auto k) { return sin (freq * 2 * k * pi / samplerate); });
std::string filename_prefix = "sine_" + std::to_string (freq) + "_" + std::to_string (samplerate);
SndfileHandle sndfilehandle_pcm32 (filename_prefix + "_pcm32.wav",
SFM_WRITE,
(SF_FORMAT_WAV | SF_FORMAT_PCM_32), 1, samplerate);
SndfileHandle sndfilehandle_pcm24 (filename_prefix + "_pcm24.wav",
SFM_WRITE,
(SF_FORMAT_WAV | SF_FORMAT_PCM_24), 1, samplerate);
SndfileHandle sndfilehandle_pcm16 (filename_prefix + "_pcm16.wav",
SFM_WRITE,
(SF_FORMAT_WAV | SF_FORMAT_PCM_16), 1, samplerate);
SndfileHandle sndfilehandle_pcmf (filename_prefix + "_float.wav",
SFM_WRITE,
(SF_FORMAT_WAV | SF_FORMAT_FLOAT), 1, samplerate);
SndfileHandle sndfilehandle_pcmd (filename_prefix + "_double.wav",
SFM_WRITE,
(SF_FORMAT_WAV | SF_FORMAT_DOUBLE), 1, samplerate);
sndfilehandle_pcm32.write (buffer.data (), buffer.size ());
sndfilehandle_pcm24.write (buffer.data (), buffer.size ());
sndfilehandle_pcm16.write (buffer.data (), buffer.size ());
sndfilehandle_pcmf.write (buffer.data (), buffer.size ());
sndfilehandle_pcmd.write (buffer.data (), buffer.size ());
}
| 45.811321 | 102 | 0.570016 | mpoullet |
be0680ddc3b048ce58713361bf085c95624875ae | 2,402 | cpp | C++ | spawner.cpp | darkoppressor/huberts-island-adventure-mouse-o-war | 9ff8d9e2c2b388bf762a0e463238794fb0233df8 | [
"MIT"
] | null | null | null | spawner.cpp | darkoppressor/huberts-island-adventure-mouse-o-war | 9ff8d9e2c2b388bf762a0e463238794fb0233df8 | [
"MIT"
] | null | null | null | spawner.cpp | darkoppressor/huberts-island-adventure-mouse-o-war | 9ff8d9e2c2b388bf762a0e463238794fb0233df8 | [
"MIT"
] | null | null | null | /* Copyright (c) 2012-2013 Cheese and Bacon Games, LLC */
/* See the file docs/COPYING.txt for copying permission. */
#include "spawner.h"
#include "world.h"
#include "collision.h"
using namespace std;
Spawner::Spawner(short get_spawner_type,short get_type,double get_x,double get_y,bool get_disallow_doubles,bool get_items_stay){
spawner_type=get_spawner_type;
type=get_type;
x=get_x;
y=get_y;
disallow_doubles=get_disallow_doubles;
items_stay=get_items_stay;
}
bool Spawner::allow_spawn(){
if(disallow_doubles){
bool allow=true;
if(spawner_type==SPAWN_ITEM){
for(int i=0;i<vector_items.size();i++){
if(vector_items[i].exists && type==vector_items[i].type &&
collision_check(x,y,ITEM_W,ITEM_H,vector_items[i].x,vector_items[i].y,vector_items[i].w,vector_items[i].h)){
allow=false;
break;
}
}
}
else if(spawner_type==SPAWN_NPC){
for(int i=0;i<vector_npcs.size();i++){
if(vector_npcs[i].exists && type==vector_npcs[i].type &&
collision_check(x,y,ITEM_W,ITEM_H,vector_npcs[i].x,vector_npcs[i].y,vector_npcs[i].w,vector_npcs[i].h)){
allow=false;
break;
}
}
}
return allow;
}
else{
return true;
}
}
void Spawner::spawn_object(short object_type){
if(spawner_type==object_type){
if(object_type==SPAWN_ITEM){
if(fabs(x-player.cam_focused_x())>=SPAWN_RANGE || fabs(y-player.cam_focused_y())>=SPAWN_RANGE){
if(random_range(0,99)<level.survival_spawn_items_chance()){
if(allow_spawn()){
vector_items.push_back(Item(x,y,!items_stay,type,0,false));
}
}
}
}
else if(object_type==SPAWN_NPC){
if(fabs(x-player.cam_focused_x())>=SPAWN_RANGE || fabs(y-player.cam_focused_y())>=SPAWN_RANGE){
if(random_range(0,99)<level.survival_spawn_npcs_chance()){
if(allow_spawn()){
vector_npcs.push_back(Npc(x,y,type,false));
vector_npcs[vector_npcs.size()-1].ethereal_to_npcs=true;
}
}
}
}
}
}
| 33.361111 | 128 | 0.556203 | darkoppressor |
be07628f4cf1c892299c014a9e0346b5e18eb045 | 2,661 | cpp | C++ | outputDialogs/signaldata.cpp | kerdemdemir/sharpEar | 6193fad5a776b246caed72d89009d64afc1db5a0 | [
"BSD-4-Clause"
] | 5 | 2016-04-27T08:01:06.000Z | 2021-12-21T07:07:14.000Z | outputDialogs/signaldata.cpp | kerdemdemir/sharpEar | 6193fad5a776b246caed72d89009d64afc1db5a0 | [
"BSD-4-Clause"
] | 3 | 2016-04-27T08:02:17.000Z | 2017-04-18T18:46:40.000Z | outputDialogs/signaldata.cpp | kerdemdemir/sharpEar | 6193fad5a776b246caed72d89009d64afc1db5a0 | [
"BSD-4-Clause"
] | null | null | null | #include "signaldata.h"
#include <qvector.h>
#include <qmutex.h>
#include <qreadwritelock.h>
class SignalData::PrivateData
{
public:
PrivateData():
boundingRect( 1.0, 1.0, -2.0, -2.0 ) // invalid
{
values.reserve( 1000 );
}
inline void append( const QPointF &sample )
{
values.append( sample );
// adjust the bounding rectangle
if ( boundingRect.width() < 0 || boundingRect.height() < 0 )
{
boundingRect.setRect( sample.x(), sample.y(), 0.0, 0.0 );
}
else
{
boundingRect.setRight( sample.x() );
if ( sample.y() > boundingRect.bottom() )
boundingRect.setBottom( sample.y() );
if ( sample.y() < boundingRect.top() )
boundingRect.setTop( sample.y() );
}
}
QReadWriteLock lock;
QVector<QPointF> values;
QRectF boundingRect;
QMutex mutex; // protecting pendingValues
QVector<QPointF> pendingValues;
};
SignalData::SignalData()
{
elapsedDataSize = 0;
d_data = new PrivateData();
}
SignalData::~SignalData()
{
delete d_data;
}
int SignalData::size() const
{
return d_data->values.size();
}
QPointF SignalData::value( int index ) const
{
return d_data->values[index];
}
QRectF SignalData::boundingRect() const
{
return d_data->boundingRect;
}
void SignalData::lock()
{
d_data->lock.lockForRead();
}
void SignalData::unlock()
{
d_data->lock.unlock();
}
void SignalData::append( const QPointF &sample )
{
d_data->mutex.lock();
d_data->pendingValues += sample;
elapsedDataSize++;
const bool isLocked = d_data->lock.tryLockForWrite();
if ( isLocked )
{
const int numValues = d_data->pendingValues.size();
const QPointF *pendingValues = d_data->pendingValues.data();
for ( int i = 0; i < numValues; i++ )
d_data->append( pendingValues[i] );
d_data->pendingValues.clear();
d_data->lock.unlock();
}
d_data->mutex.unlock();
}
void SignalData::clearStaleValues( double limit )
{
d_data->lock.lockForWrite();
d_data->boundingRect = QRectF( 1.0, 1.0, -2.0, -2.0 ); // invalid
const QVector<QPointF> values = d_data->values;
d_data->values.clear();
d_data->values.reserve( values.size() );
int index;
for ( index = values.size() - 1; index >= 0; index-- )
{
if ( values[index].x() < limit )
break;
}
if ( index > 0 )
d_data->append( values[index++] );
while ( index < values.size() - 1 )
d_data->append( values[index++] );
d_data->lock.unlock();
}
| 20.469231 | 69 | 0.585118 | kerdemdemir |
be08114dfb3bf0b9017071cc557cbd331a3a6b43 | 7,445 | cpp | C++ | src/crypto/scrypt/crypto_scrypt_smix_sse2.cpp | orobio/gulden-official | a329faf163b15eabc7ff1d9f07ea87f66df8d27d | [
"MIT"
] | 158 | 2016-01-08T10:38:37.000Z | 2022-02-01T06:28:05.000Z | src/crypto/scrypt/crypto_scrypt_smix_sse2.cpp | orobio/gulden-official | a329faf163b15eabc7ff1d9f07ea87f66df8d27d | [
"MIT"
] | 196 | 2015-11-19T10:59:24.000Z | 2021-10-07T14:52:13.000Z | src/crypto/scrypt/crypto_scrypt_smix_sse2.cpp | orobio/gulden-official | a329faf163b15eabc7ff1d9f07ea87f66df8d27d | [
"MIT"
] | 71 | 2016-06-25T23:29:04.000Z | 2022-03-14T10:57:19.000Z | // -
// Copyright 2009 Colin Percival
// 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.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
//
// The code in this file is taken from a file which was originally written by Colin Percival as part of the Tarsnap
// online backup system.
// -
//
// File contains modifications by: The Gulden developers
// All modifications:
// Copyright (c) 2019 The Gulden developers
// Authored by: Malcolm MacLeod (mmacleod@gmx.com)
// Distributed under the GULDEN software license, see the accompanying
// file COPYING in the root of this repository
#if defined(USE_SSE2)
#include <emmintrin.h>
#include <stdint.h>
#include "sysendian.h"
#include "crypto_scrypt_smix_sse2.h"
static void blkcpy(void*, const void*, size_t);
static void blkxor(void*, const void*, size_t);
static void salsa20_8(__m128i*);
static void blockmix_salsa8(const __m128i*, __m128i*, __m128i*, size_t);
static uint64_t integerify(const void*, size_t);
static void blkcpy(void* dest, const void* src, size_t len)
{
__m128i* D = dest;
const __m128i* S = src;
size_t L = len / 16;
size_t i;
for (i = 0; i < L; i++)
{
D[i] = S[i];
}
}
static void blkxor(void* dest, const void* src, size_t len)
{
__m128i* D = dest;
const __m128i* S = src;
size_t L = len / 16;
size_t i;
for (i = 0; i < L; i++)
{
D[i] = _mm_xor_si128(D[i], S[i]);
}
}
/* salsa20_8(B):
* Apply the salsa20/8 core to the provided block.
*/
static void salsa20_8(__m128i B[4])
{
__m128i X0, X1, X2, X3;
__m128i T;
size_t i;
X0 = B[0];
X1 = B[1];
X2 = B[2];
X3 = B[3];
for (i = 0; i < 8; i += 2)
{
// Operate on "columns".
T = _mm_add_epi32(X0, X3);
X1 = _mm_xor_si128(X1, _mm_slli_epi32(T, 7));
X1 = _mm_xor_si128(X1, _mm_srli_epi32(T, 25));
T = _mm_add_epi32(X1, X0);
X2 = _mm_xor_si128(X2, _mm_slli_epi32(T, 9));
X2 = _mm_xor_si128(X2, _mm_srli_epi32(T, 23));
T = _mm_add_epi32(X2, X1);
X3 = _mm_xor_si128(X3, _mm_slli_epi32(T, 13));
X3 = _mm_xor_si128(X3, _mm_srli_epi32(T, 19));
T = _mm_add_epi32(X3, X2);
X0 = _mm_xor_si128(X0, _mm_slli_epi32(T, 18));
X0 = _mm_xor_si128(X0, _mm_srli_epi32(T, 14));
// Rearrange data.
X1 = _mm_shuffle_epi32(X1, 0x93);
X2 = _mm_shuffle_epi32(X2, 0x4E);
X3 = _mm_shuffle_epi32(X3, 0x39);
// Operate on "rows".
T = _mm_add_epi32(X0, X1);
X3 = _mm_xor_si128(X3, _mm_slli_epi32(T, 7));
X3 = _mm_xor_si128(X3, _mm_srli_epi32(T, 25));
T = _mm_add_epi32(X3, X0);
X2 = _mm_xor_si128(X2, _mm_slli_epi32(T, 9));
X2 = _mm_xor_si128(X2, _mm_srli_epi32(T, 23));
T = _mm_add_epi32(X2, X3);
X1 = _mm_xor_si128(X1, _mm_slli_epi32(T, 13));
X1 = _mm_xor_si128(X1, _mm_srli_epi32(T, 19));
T = _mm_add_epi32(X1, X2);
X0 = _mm_xor_si128(X0, _mm_slli_epi32(T, 18));
X0 = _mm_xor_si128(X0, _mm_srli_epi32(T, 14));
// Rearrange data.
X1 = _mm_shuffle_epi32(X1, 0x39);
X2 = _mm_shuffle_epi32(X2, 0x4E);
X3 = _mm_shuffle_epi32(X3, 0x93);
}
B[0] = _mm_add_epi32(B[0], X0);
B[1] = _mm_add_epi32(B[1], X1);
B[2] = _mm_add_epi32(B[2], X2);
B[3] = _mm_add_epi32(B[3], X3);
}
/* blockmix_salsa8(Bin, Bout, X, r):
* Compute Bout = BlockMix_{salsa20/8, r}(Bin). The input Bin must be 128r
* bytes in length; the output Bout must also be the same size. The
* temporary space X must be 64 bytes.
*/
static void blockmix_salsa8(const __m128i* Bin, __m128i* Bout, __m128i* X, size_t r)
{
size_t i;
// 1: X <-- B_{2r - 1}
blkcpy(X, &Bin[8 * r - 4], 64);
// 2: for i = 0 to 2r - 1 do
for (i = 0; i < r; i++) {
// 3: X <-- H(X \xor B_i)
blkxor(X, &Bin[i * 8], 64);
salsa20_8(X);
// 4: Y_i <-- X
// 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1})
blkcpy(&Bout[i * 4], X, 64);
/* 3: X <-- H(X \xor B_i) */
blkxor(X, &Bin[i * 8 + 4], 64);
salsa20_8(X);
// 4: Y_i <-- X
// 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1})
blkcpy(&Bout[(r + i) * 4], X, 64);
}
}
/* integerify(B, r):
* Return the result of parsing B_{2r-1} as a little-endian integer.
* Note that B's layout is permuted compared to the generic implementation.
*/
static uint64_t integerify(const void* B, size_t r)
{
const uint32_t* X = (const void*)((uintptr_t)(B) + (2 * r - 1) * 64);
return (((uint64_t)(X[13]) << 32) + X[0]);
}
void crypto_scrypt_smix_sse2(uint8_t * B, size_t r, uint64_t N, void * V, void * XY)
{
__m128i* X = XY;
__m128i* Y = (void*)((uintptr_t)(XY) + 128 * r);
__m128i* Z = (void*)((uintptr_t)(XY) + 256 * r);
uint32_t* X32 = (void*)X;
uint64_t i, j;
size_t k;
// 1: X <-- B
for (k = 0; k < 2 * r; k++)
{
for (i = 0; i < 16; i++)
{
X32[k * 16 + i] = le32dec(&B[(k * 16 + (i * 5 % 16)) * 4]);
}
}
// 2: for i = 0 to N - 1 do
for (i = 0; i < N; i += 2)
{
// 3: V_i <-- X
blkcpy((void*)((uintptr_t)(V) + i * 128 * r), X, 128 * r);
// 4: X <-- H(X)
blockmix_salsa8(X, Y, Z, r);
// 3: V_i <-- X
blkcpy((void*)((uintptr_t)(V) + (i + 1) * 128 * r), Y, 128 * r);
// 4: X <-- H(X)
blockmix_salsa8(Y, X, Z, r);
}
// 6: for i = 0 to N - 1 do
for (i = 0; i < N; i += 2)
{
// 7: j <-- Integerify(X) mod N
j = integerify(X, r) & (N - 1);
// 8: X <-- H(X \xor V_j)
blkxor(X, (void*)((uintptr_t)(V) + j * 128 * r), 128 * r);
blockmix_salsa8(X, Y, Z, r);
// 7: j <-- Integerify(X) mod N
j = integerify(Y, r) & (N - 1);
// 8: X <-- H(X \xor V_j)
blkxor(Y, (void *)((uintptr_t)(V) + j * 128 * r), 128 * r);
blockmix_salsa8(Y, X, Z, r);
}
// 10: B' <-- X
for (k = 0; k < 2 * r; k++)
{
for (i = 0; i < 16; i++)
{
le32enc(&B[(k * 16 + (i * 5 % 16)) * 4], X32[k * 16 + i]);
}
}
}
#endif /* CPUSUPPORT_X86_SSE2 */
| 30.387755 | 115 | 0.570047 | orobio |
be089947172f9410e10fb07cb376d3c43383fa65 | 5,762 | hpp | C++ | code/path_marker.hpp | LoginLEE/HKUST-COMP2012h-2D-Shooting-Game | d03812a4a8cba8d31873157d71818b8c67d495fd | [
"MIT"
] | null | null | null | code/path_marker.hpp | LoginLEE/HKUST-COMP2012h-2D-Shooting-Game | d03812a4a8cba8d31873157d71818b8c67d495fd | [
"MIT"
] | null | null | null | code/path_marker.hpp | LoginLEE/HKUST-COMP2012h-2D-Shooting-Game | d03812a4a8cba8d31873157d71818b8c67d495fd | [
"MIT"
] | null | null | null | #pragma once
#include <SFML/Graphics.hpp>
#include "global_defines.hpp"
#include "game_entity.hpp"
#include "collision_box.hpp"
#include "textured_block.hpp"
class Enemy;
/**
* @brief Class for Enemy Path Markers
*
* This class represents a invisible Entity that guides the Enemy and controls their pathing around the level
*/
class PathMarker : public GameEntity {
public:
/**
* @brief Movement Direction for the Enemy
*/
enum Direction {
EnemyPathIdle,
EnemyPathLeft,
EnemyPathRight,
EnemyPathJumpLeft,
EnemyPathJumpRight,
};
private:
/**
* @brief The movement direction that this path marker will tell an Enemy to follow
*/
Direction pathDir = Direction::EnemyPathRight;
/**
* @brief Speed of the path that the enemy should take
*/
float speed = 1.0f;
/**
* @brief Should the enemy shoot while following this path?
*/
bool shoot = true;
/**
* @brief CollisionBox of this Path Marker
*/
CollisionBox collisionBox;
/**
* @brief Create a new Path Marker with a certain generation code at the default position
*
* @param _manager The global GameManager pointer
* @param[in] generationCode The generation code
* @param parent The parent GameEntity node
*/
PathMarker(GameManager *_manager, int generationCode, GameEntity *parent)
: PathMarker(_manager, generationCode, parent, 0, 0) {}
/**
* @brief Create a new Path Marker with a certain generation code at the given position
*
* @param _manager The global GameManager pointer
* @param[in] generationCode The generation code
* @param parent The parent GameEntity node
* @param[in] x x coordinate
* @param[in] y y coordinate
*/
PathMarker(GameManager *_manager, int generationCode, GameEntity *parent, float x, float y)
: PathMarker(_manager, generationCode, parent, sf::Vector2f(x, y)) {}
/**
* @brief Create a new Path Marker with a certain generation code at the given position
*
* @param _manager The global GameManager pointer
* @param[in] generationCode The generation code
* @param parent The parent GameEntity node
* @param[in] pos The position
*/
PathMarker(GameManager *_manager, int generationCode, GameEntity *parent, sf::Vector2f pos)
: GameEntity(_manager, parent) {
pathDir = static_cast<Direction>(generationCode % 5);
setPosition(pos);
setSize(sf::Vector2f(BLOCK_SIZE*0.5f, BLOCK_SIZE));
switch (pathDir) {
case EnemyPathIdle:
setSize(sf::Vector2f(BLOCK_SIZE, BLOCK_SIZE));
break;
case EnemyPathLeft:
case EnemyPathJumpLeft:
setPosition(pos + sf::Vector2f(BLOCK_SIZE*0.25f, 0));
break;
case EnemyPathRight:
case EnemyPathJumpRight:
setPosition(pos - sf::Vector2f(BLOCK_SIZE*0.25f, 0));
break;
}
collisionBox = CollisionBox(getTotalPosition(), getSize());
}
public:
/**
* @brief Static function for creating Path Markers from Map file codes
*
* Used to allow for the possibility of generating subclasses of Path Markers in the future
*
* @param _manager The global GameManager pointer
* @param[in] generationCode The generation code
* @param parent The parent GameEntity node
* @param[in] x The X coordinate
* @param[in] y The Y coordinate
*
* @return The created Path Marker
*/
static PathMarker* create(GameManager *_manager, int generationCode, GameEntity *parent, float x, float y) {
return new PathMarker(_manager, generationCode, parent, x, y); //may return sub classes in the future
}
/**
* @brief Gets the collision box.
*
* @return The collision box.
*/
CollisionBox getCollisionBox() const {return collisionBox;}
/**
* @brief Is the given Enemy Entity stepping in this Path Marker?
*
* @param[in] enemy The enemy
*
* @return True if Enemy's feet is inside this collision box
*/
bool steppingIn(const Enemy* enemy) const;
/**
* @brief Gets the path direction
*/
Direction getPathDir() const {return pathDir;};
/**
* @brief Gets the speed.
*/
float getSpeed() const {return speed;};
/**
* @brief Should enemy shoot?
*
* @return { description_of_the_return_value }
*/
float shouldShoot() const {return shoot;};
/**
* @brief Draw Collision Box and Arrows for Debugging
*
* @param renderer The Render Target to Draw to
*/
virtual void draw(sf::RenderTarget &renderer) const override {
if (DISPLAY_DEBUGGING_STUFF) {
collisionBox.draw(renderer);
if (pathDir == EnemyPathIdle) return;
sf::ConvexShape arrow;
arrow.setPointCount(3);
switch (pathDir) {
case EnemyPathLeft:
arrow.setPoint(0, sf::Vector2f(getSize().x, 0));
arrow.setPoint(1, sf::Vector2f(0, getSize().y/2));
arrow.setPoint(2, sf::Vector2f(getSize().x, getSize().y));
break;
case EnemyPathRight:
arrow.setPoint(0, sf::Vector2f(0, 0));
arrow.setPoint(1, sf::Vector2f(0, getSize().y));
arrow.setPoint(2, sf::Vector2f(getSize().x, getSize().y/2));
break;
case EnemyPathJumpLeft:
arrow.setPoint(0, sf::Vector2f(0, 0));
arrow.setPoint(1, sf::Vector2f(0, getSize().y/2));
arrow.setPoint(2, sf::Vector2f(getSize().x, 0));
break;
case EnemyPathJumpRight:
arrow.setPoint(0, sf::Vector2f(0, 0));
arrow.setPoint(1, sf::Vector2f(getSize().x, getSize().y/2));
arrow.setPoint(2, sf::Vector2f(getSize().x, 0));
break;
case EnemyPathIdle:
break;
}
arrow.setFillColor(sf::Color::Green);
arrow.setPosition(getTotalPosition());
arrow.setOrigin(getSize()/2.0f);
renderer.draw(arrow);
}
}
}; | 29.548718 | 109 | 0.660708 | LoginLEE |
be0bab1063aa9afa00fc47702ebc5681dae32f10 | 129 | hpp | C++ | Blob_Lib/Include/glm/detail/type_float.hpp | antholuo/Blob_Traffic | 5d6acf88044e9abc63c0ff356714179eaa4b75bf | [
"MIT"
] | null | null | null | Blob_Lib/Include/glm/detail/type_float.hpp | antholuo/Blob_Traffic | 5d6acf88044e9abc63c0ff356714179eaa4b75bf | [
"MIT"
] | null | null | null | Blob_Lib/Include/glm/detail/type_float.hpp | antholuo/Blob_Traffic | 5d6acf88044e9abc63c0ff356714179eaa4b75bf | [
"MIT"
] | null | null | null | version https://git-lfs.github.com/spec/v1
oid sha256:a62772f6d894faf1b10bfe5468fe32accdfecae65e88b1d03150d1f60896ad1d
size 1642
| 32.25 | 75 | 0.883721 | antholuo |
be0bcd0be50d923bb67c41601580f594205e393a | 1,665 | cpp | C++ | aws-cpp-sdk-codecommit/source/model/ListAssociatedApprovalRuleTemplatesForRepositoryResult.cpp | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2021-12-06T20:36:35.000Z | 2021-12-06T20:36:35.000Z | aws-cpp-sdk-codecommit/source/model/ListAssociatedApprovalRuleTemplatesForRepositoryResult.cpp | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-codecommit/source/model/ListAssociatedApprovalRuleTemplatesForRepositoryResult.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2022-03-23T15:17:18.000Z | 2022-03-23T15:17:18.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/codecommit/model/ListAssociatedApprovalRuleTemplatesForRepositoryResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::CodeCommit::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
ListAssociatedApprovalRuleTemplatesForRepositoryResult::ListAssociatedApprovalRuleTemplatesForRepositoryResult()
{
}
ListAssociatedApprovalRuleTemplatesForRepositoryResult::ListAssociatedApprovalRuleTemplatesForRepositoryResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
ListAssociatedApprovalRuleTemplatesForRepositoryResult& ListAssociatedApprovalRuleTemplatesForRepositoryResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("approvalRuleTemplateNames"))
{
Array<JsonView> approvalRuleTemplateNamesJsonList = jsonValue.GetArray("approvalRuleTemplateNames");
for(unsigned approvalRuleTemplateNamesIndex = 0; approvalRuleTemplateNamesIndex < approvalRuleTemplateNamesJsonList.GetLength(); ++approvalRuleTemplateNamesIndex)
{
m_approvalRuleTemplateNames.push_back(approvalRuleTemplateNamesJsonList[approvalRuleTemplateNamesIndex].AsString());
}
}
if(jsonValue.ValueExists("nextToken"))
{
m_nextToken = jsonValue.GetString("nextToken");
}
return *this;
}
| 33.3 | 176 | 0.810811 | lintonv |
be13231a3b636e9dcc87646a88cf80a8fa8dc09b | 1,942 | cpp | C++ | Source/VoxelEditor/Private/EdMode/VoxelEdModeToolkit.cpp | ADMTec/VoxelPlugin | db3c94fd8140d27671b9e80f09c47b28d02a6096 | [
"MIT"
] | 998 | 2018-03-20T06:46:08.000Z | 2022-03-31T11:45:38.000Z | Source/VoxelEditor/Private/EdMode/VoxelEdModeToolkit.cpp | B0B-100/VoxelPlugin | cd331027eff6bee027101af355408c165d07d1b8 | [
"MIT"
] | 408 | 2018-03-19T20:43:19.000Z | 2022-03-10T23:02:25.000Z | Source/VoxelEditor/Private/EdMode/VoxelEdModeToolkit.cpp | B0B-100/VoxelPlugin | cd331027eff6bee027101af355408c165d07d1b8 | [
"MIT"
] | 205 | 2018-03-19T12:14:19.000Z | 2022-03-30T16:29:42.000Z | // Copyright 2021 Phyronnaz
#include "VoxelEdModeToolkit.h"
#include "VoxelEdMode.h"
#include "VoxelEditorToolsPanel.h"
#include "EditorModeManager.h"
void FVoxelEdModeToolkit::Init(const TSharedPtr<IToolkitHost>& InitToolkitHost)
{
FModeToolkit::Init(InitToolkitHost);
}
FName FVoxelEdModeToolkit::GetToolkitFName() const
{
return FName("VoxelEdMode");
}
FText FVoxelEdModeToolkit::GetBaseToolkitName() const
{
return VOXEL_LOCTEXT("VoxelEdMode Tool");
}
class FEdMode* FVoxelEdModeToolkit::GetEditorMode() const
{
return GLevelEditorModeTools().GetActiveMode(FEdModeVoxel::EM_Voxel);
}
TSharedPtr<SWidget> FVoxelEdModeToolkit::GetInlineContent() const
{
return GetPanel().GetWidget();
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void FVoxelEdModeToolkit::GetToolPaletteNames(TArray<FName>& InPaletteName) const
{
InPaletteName = { STATIC_FNAME("Main") };
}
void FVoxelEdModeToolkit::BuildToolPalette(FName PaletteName, FToolBarBuilder& ToolBarBuilder)
{
GetPanel().CustomizeToolbar(ToolBarBuilder);
}
void FVoxelEdModeToolkit::OnToolPaletteChanged(FName PaletteName)
{
}
FText FVoxelEdModeToolkit::GetActiveToolDisplayName() const
{
return {};
}
FText FVoxelEdModeToolkit::GetActiveToolMessage() const
{
return {};
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
FVoxelEditorToolsPanel& FVoxelEdModeToolkit::GetPanel() const
{
FEdModeVoxel* VoxelEdMode = static_cast<FEdModeVoxel*>(GetEditorMode());
check(VoxelEdMode);
return VoxelEdMode->GetPanel();
} | 27.742857 | 95 | 0.569516 | ADMTec |
be142be23774b71c652228c325e18379295532cc | 15,173 | cpp | C++ | src/HighGoal/HighGoal.cpp | team3130/Harriet | 5fc9ecfe7c94b954e2f5ea21df056fe35a3fcb34 | [
"Apache-2.0"
] | 2 | 2017-06-20T15:15:27.000Z | 2017-09-05T02:04:33.000Z | src/HighGoal/HighGoal.cpp | team3130/Harriet | 5fc9ecfe7c94b954e2f5ea21df056fe35a3fcb34 | [
"Apache-2.0"
] | null | null | null | src/HighGoal/HighGoal.cpp | team3130/Harriet | 5fc9ecfe7c94b954e2f5ea21df056fe35a3fcb34 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <memory>
#include <chrono>
#include <thread>
#include <ctime>
#include "networktables/NetworkTable.h"
#include "opencv2/opencv.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/cudaarithm.hpp"
#include "opencv2/cudaimgproc.hpp"
#include "opencv2/cudafilters.hpp"
static const cv::Size frameSize(1280, 720);
static const double MIN_AREA = 0.0002 * frameSize.height * frameSize.width;
static const double BOILER_TAPE_RATIO = 2.5;
static const double BOILER_TAPE_RATIO2 = BOILER_TAPE_RATIO/2;
static const char* default_intrinsic_file = "jetson-camera-720.yml";
static const double CAMERA_GOAL_HEIGHT = 69; //!<- Tower height is 97" and the camera is 19" above the floor
static const double CAMERA_ZERO_DIST = 130; //!<- Tower height is 97" and the camera is 12" above the floor
#ifdef XGUI_ENABLED
#include "opencv2/highgui.hpp"
static const cv::Size displaySize(640, 360);
static const double displayRatio = double(displaySize.height) / frameSize.height;
static const char* detection_window = "Object Detection";
#endif
struct RingRelation {
double rating;
std::vector<cv::Point> *my_cont;
std::vector<cv::Point> *other_cont;
cv::RotatedRect my_rect;
cv::RotatedRect other_rect;
double rate2rings(const RingRelation &other)
{
double rate = 0;
rate += fabs(my_rect.angle)/90.0; // angle is in (-90,+90), 90 is the best
rate += 1.0 - fabs(BOILER_TAPE_RATIO - my_rect.size.height/my_rect.size.width);
rate += 1.0 - fabs((my_rect.center.x-other_rect.center.x) / (my_rect.center.y-other_rect.center.y));
rate += 1.0 - fabs(BOILER_TAPE_RATIO2 - my_rect.size.height / norm(my_rect.center-other_rect.center));
return rate;
};
RingRelation(std::vector<cv::Point> *cont, cv::RotatedRect rect, const std::vector<RingRelation> &chain)
: rating(0), my_cont(cont), my_rect(rect), other_cont(cont), other_rect(rect)
{
for(auto&& other : chain) {
double temp = rate2rings(other);
if(temp > rating) {
rating = temp;
other_rect = other.my_rect;
other_cont = other.my_cont;
}
}
};
// This comparison operator is for sort. Reversed for descending order.
bool operator<(RingRelation &other) { return rating > other.rating; };
};
void CheezyInRange(
cv::cuda::GpuMat src,
cv::Vec3i BlobLower,
cv::Vec3i BlobUpper,
cv::cuda::GpuMat dst,
cv::cuda::Stream stream = cv::cuda::Stream::Null()) {
cv::cuda::GpuMat channels[3];
cv::cuda::split(src, channels, stream);
//threshold, reset to zero everything that is above the upper limit
cv::cuda::threshold(channels[0], channels[0], BlobUpper[0], 255, cv::THRESH_TOZERO_INV, stream);
cv::cuda::threshold(channels[1], channels[1], BlobUpper[1], 255, cv::THRESH_TOZERO_INV, stream);
cv::cuda::threshold(channels[2], channels[2], BlobUpper[2], 255, cv::THRESH_TOZERO_INV, stream);
//threshold, reset to zero what is below the lower limit, otherwise to 255
cv::cuda::threshold(channels[0], channels[0], BlobLower[0], 255, cv::THRESH_BINARY, stream);
cv::cuda::threshold(channels[1], channels[1], BlobLower[1], 255, cv::THRESH_BINARY, stream);
cv::cuda::threshold(channels[2], channels[2], BlobLower[2], 255, cv::THRESH_BINARY, stream);
//combine all three channels and collapse them into one B/W image (to channels[0])
cv::cuda::bitwise_and(channels[0], channels[1], channels[0], cv::noArray(), stream);
cv::cuda::bitwise_and(channels[0], channels[2], dst, cv::noArray(), stream);
}
void righten(cv::RotatedRect &rectangle)
{
if (rectangle.size.height < rectangle.size.width) {
std::swap(rectangle.size.height, rectangle.size.width);
rectangle.angle += 90.0;
}
rectangle.angle = fmod(rectangle.angle, 180.0);
if (rectangle.angle > 90.0) rectangle.angle -= 180;
if (rectangle.angle < -90.0) rectangle.angle += 180;
}
bool readIntrinsics(const char *filename, cv::Mat &intrinsic, cv::Mat &distortion)
{
cv::FileStorage fs( filename, cv::FileStorage::READ );
if( !fs.isOpened() )
{
std::cerr << "Error: Couldn't open intrinsic parameters file "
<< filename << std::endl;
return false;
}
fs["camera_matrix"] >> intrinsic;
fs["distortion_coefficients"] >> distortion;
if( intrinsic.empty() || distortion.empty() )
{
std::cerr << "Error: Couldn't load intrinsic parameters from "
<< filename << std::endl;
return false;
}
fs.release();
return true;
}
cv::Point2d intersect(cv::Point2d pivot, cv::Matx22d rotation, cv::Point one, cv::Point two)
{
cv::Point2d ret(-1,-1);
cv::Point2d one_f(one), two_f(two);
cv::Vec2d one_v = rotation * (one_f - pivot);
cv::Vec2d two_v = rotation * (two_f - pivot);
if(one_v[0] > 0 and two_v[0] > 0) return ret;
if(one_v[0] < 0 and two_v[0] < 0) return ret;
if(one_v[0] == 0) return one_f;
if(two_v[0] == 0) return two_f;
double y0 = two_v[1] - two_v[0] * (one_v[1]-two_v[1])/(one_v[0]-two_v[0]);
ret = rotation.t() * cv::Point2d(0, y0) + pivot;
return ret;
}
bool compPoints(const cv::Point2d a, const cv::Point2d b) { return (a.y < b.y); }
void FindMidPoints(std::vector<cv::Point> *upCont, std::vector<cv::Point> *dnCont, std::vector<cv::Point2d> &imagePoints)
{
std::vector<cv::Point> new_points = *upCont;
new_points.reserve(upCont->size()+dnCont->size());
for(size_t i=0; i<dnCont->size(); ++i) new_points.push_back((*dnCont)[i]);
cv::RotatedRect big = cv::minAreaRect(new_points);
if(fabs(big.angle) > 45 and fabs(big.angle) < 135) {
std::swap(big.size.height, big.size.width);
big.angle = fmod(big.angle+90.0, 180.0);
if (big.angle > 90.0) big.angle -= 180;
if (big.angle < -90.0) big.angle += 180;
}
double cosT = cos(CV_PI*big.angle/180.0);
double sinT = -sin(CV_PI*big.angle/180.0); // RotatedRect::angle is clockwise, so negative
cv::Matx22d rmat(cosT, -sinT, sinT, cosT);
std::vector<cv::Point2d> pointsUp;
for(size_t i = 0; i < upCont->size(); ++i) {
cv::Point2d point = intersect(big.center, rmat, (*upCont)[i], (*upCont)[(i+1)%upCont->size()]);
if(point != cv::Point2d(-1,-1)) pointsUp.push_back(point);
}
if(pointsUp.size() > 1) {
std::sort(pointsUp.begin(), pointsUp.end(), compPoints);
imagePoints.push_back(pointsUp.front());
imagePoints.push_back(pointsUp.back());
}
std::vector<cv::Point2d> pointsDn;
for(size_t i = 0; i < dnCont->size(); ++i) {
cv::Point2d point = intersect(big.center, rmat, (*dnCont)[i], (*dnCont)[(i+1)%dnCont->size()]);
if(point != cv::Point2d(-1,-1)) pointsDn.push_back(point);
}
if(pointsDn.size() > 1) {
std::sort(pointsDn.begin(), pointsDn.end(), compPoints);
imagePoints.push_back(pointsDn.front());
imagePoints.push_back(pointsDn.back());
}
}
int main(int argc, const char** argv)
{
const char* intrinsic_file = default_intrinsic_file;
if(argc > 1) intrinsic_file = argv[1];
cv::Mat intrinsic, distortion;
if(!readIntrinsics(intrinsic_file, intrinsic, distortion)) return -1;
NetworkTable::SetClientMode();
NetworkTable::SetTeam(3130);
std::shared_ptr<NetworkTable> table = NetworkTable::GetTable("/Jetson");
std::shared_ptr<NetworkTable> preferences = NetworkTable::GetTable("/Preferences");
cv::Mat frame, filtered, display;
cv::cuda::GpuMat gpuC, gpu1, gpu2;
static cv::Vec3i BlobLower(66, 200, 30);
static cv::Vec3i BlobUpper(94, 255, 255);
static int dispMode = 2; // 0: none, 1: bw, 2: color
cv::Vec3d camera_offset(-7.0, -4.0, -12);
static std::vector<cv::Point3d> realPoints;
realPoints.push_back(cv::Point3d(0,-4, 0));
realPoints.push_back(cv::Point3d(0, 0, 0.3));
realPoints.push_back(cv::Point3d(0, 4, 0.3));
realPoints.push_back(cv::Point3d(0, 6, 0));
cv::VideoCapture capture;
for(;;) {
std::ostringstream capturePipe;
capturePipe << "nvcamerasrc ! video/x-raw(memory:NVMM)"
<< ", width=(int)" << frameSize.width
<< ", height=(int)" << frameSize.height
<< ", format=(string)I420, framerate=(fraction)30/1 ! "
<< "nvvidconv flip-method=2 ! video/x-raw, format=(string)BGRx ! "
<< "videoconvert ! video/x-raw, format=(string)BGR ! appsink";
// if(!capture.open(capturePipe.str())) {
capture.open(0);
capture.set(cv::CAP_PROP_FRAME_WIDTH, frameSize.width);
capture.set(cv::CAP_PROP_FRAME_HEIGHT, frameSize.height);
capture.set(cv::CAP_PROP_FPS, 7.5);
capture.set(cv::CAP_PROP_AUTO_EXPOSURE, 0.25); // Magic! 0.25 means manual exposure, 0.75 = auto
capture.set(cv::CAP_PROP_EXPOSURE, 0);
capture.set(cv::CAP_PROP_BRIGHTNESS, 0.5);
capture.set(cv::CAP_PROP_CONTRAST, 0.5);
capture.set(cv::CAP_PROP_SATURATION, 0.5);
std::cerr << "Resolution: "<< capture.get(cv::CAP_PROP_FRAME_WIDTH)
<< "x" << capture.get(cv::CAP_PROP_FRAME_HEIGHT)
<< " FPS: " << capture.get(cv::CAP_PROP_FPS)
<< std::endl;
// }
if(capture.isOpened()) break;
std::cerr << "Couldn't connect to camera" << std::endl;
}
#ifdef XGUI_ENABLED
cv::namedWindow(detection_window, cv::WINDOW_NORMAL);
cv::createTrackbar("Lo H",detection_window, &BlobLower[0], 255);
cv::createTrackbar("Hi H",detection_window, &BlobUpper[0], 255);
cv::createTrackbar("Lo S",detection_window, &BlobLower[1], 255);
cv::createTrackbar("Hi S",detection_window, &BlobUpper[1], 255);
cv::createTrackbar("Lo V",detection_window, &BlobLower[2], 255);
cv::createTrackbar("Hi V",detection_window, &BlobUpper[2], 255);
#endif
int elemSize(5);
cv::Mat element = getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(elemSize+1,elemSize+1));
cv::Ptr<cv::cuda::Filter> erode = cv::cuda::createMorphologyFilter(cv::MORPH_ERODE, gpu1.type(), element);
cv::Ptr<cv::cuda::Filter> dilate = cv::cuda::createMorphologyFilter(cv::MORPH_DILATE, gpu1.type(), element);
gpu1.create(frameSize, CV_8UC1);
gpu2.create(frameSize, CV_8UC1);
cv::cuda::Stream cudastream;
for(;;) {
capture >> frame;
if (frame.empty()) {
std::cerr << " Error reading from camera, empty frame." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2));
continue;
}
std::vector<long int> timer_values;
std::vector<std::string> timer_names;
timer_names.push_back("start"); timer_values.push_back(cv::getTickCount());
gpuC.upload(frame);
timer_names.push_back("uploaded"); timer_values.push_back(cv::getTickCount());
cv::cuda::cvtColor(gpuC, gpuC, CV_BGR2HSV, 0, cudastream);
CheezyInRange(gpuC, BlobLower, BlobUpper, gpu1, cudastream);
erode->apply(gpu1, gpu2, cudastream);
dilate->apply(gpu2, gpu1, cudastream);
timer_names.push_back("cuda sched"); timer_values.push_back(cv::getTickCount());
cudastream.waitForCompletion();
timer_names.push_back("cuda done"); timer_values.push_back(cv::getTickCount());
gpu1.download(filtered);
#ifdef XGUI_ENABLED
switch(dispMode) {
case 1:
cv::resize(filtered, display, displaySize);
break;
case 2:
cv::resize(frame, display, displaySize);
break;
}
#endif
std::vector<std::vector<cv::Point>> contours;
cv::findContours(filtered, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);
std::vector<RingRelation> graph;
for (auto&& cont : contours)
{
cv::RotatedRect rect = cv::minAreaRect(cont);
double area = rect.size.height * rect.size.width;
if (area < MIN_AREA) continue;
righten(rect);
if (fabs(rect.angle) < 45) continue;
graph.push_back(RingRelation(&cont, rect, graph));
}
std::sort(graph.begin(), graph.end());
if (graph.size() > 1) {
double distance, yaw;
#ifdef XGUI_ENABLED
cv::Point dispTarget(displaySize.width/2,displaySize.height*0.9);
#endif
std::vector<cv::Point2d> imagePoints;
if (graph[0].my_rect.center.y < graph[1].my_rect.center.y) {
FindMidPoints(graph[0].my_cont, graph[1].my_cont, imagePoints);
}
else {
FindMidPoints(graph[1].my_cont, graph[0].my_cont, imagePoints);
}
cv::Vec3d rvec, tvec;
if(imagePoints.size() == 4) {
std::vector<cv::Point2d> undistortedPoints;
cv::undistortPoints(imagePoints, undistortedPoints, intrinsic, distortion, cv::noArray(), intrinsic);
double cam_tilt = preferences->GetNumber("Front Camera Tilt", 40);
cv::Vec3d cam_offset(-18, 0, -18);
double cam_cos = cos(CV_PI*cam_tilt/180.0);
double dee = cv::norm(undistortedPoints[0] - undistortedPoints[3]);
distance = cam_cos * intrinsic.at<double>(1,1) * fabs(realPoints[3].y-realPoints[0].y) / dee;
double m_zenith = intrinsic.at<double>(0,0) * preferences->GetNumber("CameraZeroDist", CAMERA_ZERO_DIST) / preferences->GetNumber("CameraHeight", CAMERA_GOAL_HEIGHT);
double m_horizon = intrinsic.at<double>(0,0) * preferences->GetNumber("CameraHeight", CAMERA_GOAL_HEIGHT) / preferences->GetNumber("CameraZeroDist", CAMERA_ZERO_DIST);
double m_flat = sqrt(intrinsic.at<double>(0,0)*intrinsic.at<double>(0,0) + m_horizon*m_horizon);
// dX is the offset of the target from the focal center to the right
float dX = undistortedPoints[0].x - intrinsic.at<double>(0,2);
// dY is the distance from the zenith to the target on the image
float dY = m_zenith + undistortedPoints[0].y - intrinsic.at<double>(1,2);
// The real azimuth to the target is on the horizon, so scale it accordingly
float azimuth = dX * ((m_zenith + m_horizon) / dY);
// Vehicle's yaw is negative arc tangent from the current heading to the target
yaw = -atan2(azimuth, m_flat);
table->PutNumber("Boiler Distance", distance);
table->PutNumber("Boiler Yaw", yaw);
}
timer_names.push_back("calcs done"); timer_values.push_back(cv::getTickCount());
#ifdef XGUI_ENABLED
if (dispMode == 2) {
if(imagePoints.size() == 4) {
cv::circle(display, imagePoints[0]*displayRatio, 8, cv::Scalar( 0, 0,200), 1);
cv::circle(display, imagePoints[1]*displayRatio, 8, cv::Scalar( 0,200,200), 1);
cv::circle(display, imagePoints[2]*displayRatio, 8, cv::Scalar( 0,200, 0), 1);
cv::circle(display, imagePoints[3]*displayRatio, 8, cv::Scalar(200, 0, 0), 1);
}
cv::line(display,
dispTarget,
cv::Point(displaySize.width/2,displaySize.height*0.9),
cv::Scalar(0,255,255));
std::ostringstream oss;
oss << "Yaw: " << yaw << " Tvec: " << imagePoints;
cv::putText(display, oss.str(), cv::Point(20,20), 0, 0.33, cv::Scalar(0,200,200));
std::ostringstream oss1;
oss1 << "Distance: " << distance;
cv::putText(display, oss1.str(), cv::Point(20,40), 0, 0.33, cv::Scalar(0,200,200));
}
#endif
}
#ifdef XGUI_ENABLED
if (dispMode > 0) {
for(size_t i=1; i < timer_values.size(); ++i) {
long int val = timer_values[i] - timer_values[0];
std::ostringstream osst;
osst << timer_names[i] << ": " << val / cv::getTickFrequency();
cv::putText(display, osst.str(), cv::Point(20,40+20*i), 0, 0.33, cv::Scalar(0,200,200));
}
cv::imshow(detection_window, display);
}
int key = cv::waitKey(20);
if ((key & 255) == 27) break;
if ((key & 255) == 32) {
if(++dispMode > 2) dispMode =0;
}
if ((key & 255) == 's') cv::waitKey(0);
#endif
}
return 0;
}
| 39.513021 | 172 | 0.667831 | team3130 |
be157d8576d9ca5d82098886d9298f0c468cfbd9 | 1,553 | cpp | C++ | IntervalsList.cpp | alechh/test-opencv | ab82723e4f9dda88a63add60d5f28dda5a22bc73 | [
"Apache-2.0"
] | 1 | 2022-03-24T08:05:22.000Z | 2022-03-24T08:05:22.000Z | IntervalsList.cpp | alechh/test-opencv | ab82723e4f9dda88a63add60d5f28dda5a22bc73 | [
"Apache-2.0"
] | null | null | null | IntervalsList.cpp | alechh/test-opencv | ab82723e4f9dda88a63add60d5f28dda5a22bc73 | [
"Apache-2.0"
] | null | null | null | #include "IntervalsList.h"
#include <iostream>
/**
* Default constructor
*/
IntervalsList::IntervalsList()
{
head = nullptr;
tail = nullptr;
next = nullptr;
}
/**
* Destructor
*/
IntervalsList::~IntervalsList()
{
while (head != nullptr)
{
Interval* oldHead = head;
head = head->next;
delete oldHead;
}
}
/**
* Add interval to the list
* @param begin -- x coordinate of the begin of the new interval
* @param end -- x coordinate of the end of the new interval
* @param y_coordinate -- y coordinate of the new interval
* @param color -- the color of the cluster that the interval belongs to
*/
void IntervalsList::addInterval(int begin, int end, int y_coordinate, cv::Vec3b color)
{
if (head == nullptr)
{
head = new Interval(begin, end, y_coordinate, color);
tail = head;
return;
}
tail->next = new Interval(begin, end, y_coordinate, color);
tail = tail->next;
}
/**
* Add interval to the list
* @param newInterval -- Pointer to the interval
*/
void IntervalsList::addInterval(Interval *newInterval)
{
if (head == nullptr)
{
head = newInterval;
tail = head;
return;
}
tail->next = newInterval;
tail = tail->next;
}
/**
* Length of the list
* @return
*/
int IntervalsList::getLength()
{
if (this->head == nullptr)
{
return 0;
}
int res = 1;
Interval *temp = head;
while (temp->next != nullptr)
{
res++;
temp = temp->next;
}
return res;
}
| 19.17284 | 86 | 0.59369 | alechh |
be15ae8b056357a1e3842f6e767273f5e01852bd | 4,342 | hpp | C++ | nucleo-g431-akashi04-i2s/Core/Inc/murasaki_platform.hpp | suikan4github/murasaki_samples_audio | 30ce5bc821e529e3415c7983ed435dbacc9b1126 | [
"MIT"
] | 12 | 2019-02-24T05:22:37.000Z | 2021-10-01T05:56:59.000Z | nucleo-g431-akashi04-i2s/Core/Inc/murasaki_platform.hpp | suikan4github/murasaki_samples_audio | 30ce5bc821e529e3415c7983ed435dbacc9b1126 | [
"MIT"
] | 122 | 2019-02-23T13:51:42.000Z | 2021-11-13T01:24:34.000Z | nucleo-l412-64/Inc/murasaki_platform.hpp | suikan4github/murasaki_samples | f339c1bf555035f4416797e3938fbe25cc82414c | [
"MIT"
] | 3 | 2019-02-24T16:38:25.000Z | 2022-03-22T15:25:09.000Z | /**
* @file murasaki_platform.hpp
*
* @date 2017/11/12
* @author Seiichi "Suikan" Horie
* @brief An interface for the applicaiton from murasaki library to main.c
* @details
* The resources below are impremented in the murasaki_platform.cpp and serve as glue to the main.c.
*/
#ifndef MURASAKI_PLATFORM_HPP_
#define MURASAKI_PLATFORM_HPP_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
// Murasaki platform control
/**
* @brief Initialize the platform variables.
* @ingroup MURASAKI_PLATFORM_GROUP
* @details
* The murasaki::platform variable is an interface between the application program and HAL / RTOS.
* To use it correctly, the initialization is needed before any activity of murasaki client.
*
* @code
* void StartDefaultTask(void const * argument)
* {
* InitPlatform();
* ExecPlatform();
* }
* @endcode
*
* This function have to be invoked from the StartDefaultTask() of the main.c only once
* to initialize the platform variable.
*
*/
void InitPlatform();
/**
* @brief The body of the real application.
* @ingroup MURASAKI_PLATFORM_GROUP
* @details
* The body function of the murasaki application. Usually this function is called from
* the StartDefaultTask() of the main.c.
*
* This function is invoked only once, and never return. See @ref InitPlatform() as calling sample.
*
* By default, it toggles LED as sample program.
* This function can be customized freely.
*/
void ExecPlatform();
/**
* @brief Hook for the assert_failure() in main.c
* @ingroup MURASAKI_PLATFORM_GROUP
* @param file Name of the source file where assertion happen
* @param line Number of the line where assertion happen
* @details
* This routine provides a custom hook for the assertion inside STM32Cube HAL.
* All assertion raised in HAL will be redirected here.
*
* @code
* void assert_failed(uint8_t* file, uint32_t line)
* {
* CustomAssertFailed(file, line);
* }
* @endcode
* By default, this routine output a message with location informaiton
* to the debugger console.
*/
void CustomAssertFailed(uint8_t* file, uint32_t line);
/**
* @brief Hook for the default exception handler. Never return.
* @ingroup MURASAKI_PLATFORM_GROUP
* @details
* An entry of the exception. Especialy for the Hard Fault exception.
* In this function, the Stack pointer just before exception is retrieved
* and pass as the first parameter of the PrintFaultResult().
*
* Note : To print the correct information, this function have to be
* Jumped in from the exception entry without any data push to the stack.
* To avoid the pushing extra data to stack or making stack frame,
* Compile the program without debug information and with certain
* optimization leve, when you investigate the Hard Fault.
*
* For example, the start up code for the Nucleo-L152RE is startup_stml152xe.s.
* This file is generated by CubeIDE. This file has default handler as like this:
*
* @code
* .section .text.Default_Handler,"ax",%progbits
* Default_Handler:
* Infinite_Loop:
* b Infinite_Loop
* @endcode
*
* This code can be modified to call CustomDefaultHanler as like this :
* @code
* .global CustomDefaultHandler
* .section .text.Default_Handler,"ax",%progbits
* Default_Handler:
* bl CustomDefaultHandler
* Infinite_Loop:
* b Infinite_Loop
* @endcode
*
* While it is declared as function prototype, the CustomDefaultHandler is just a label.
* Do not call from user application.
*/
void CustomDefaultHandler();
/**
* @brief Printing out the context information.
* @param stack_pointer retrieved stack pointer before interrupt / exception.
* @details
* Do not call from application. This is murasaki_internal_only.
*
*/
void PrintFaultResult(unsigned int * stack_pointer);
/**
* @brief StackOverflow hook for FreeRTOS
* @param xTask Task ID which causes stack overflow.
* @param pcTaskName Name of the task which cuases stack overflow.
* @fn vApplicationStackOverflowHook
* @ingroup MURASAKI_PLATFORM_GROUP
*
* @details
* This function will be called from FreeRTOS when some task causes overflow.
* See TaskStrategy::getStackMinHeadroom() for details.
*
* Because this function prototype is declared by system,
* we don't have prototype in the murasaki_platform.hpp.
*/
#ifdef __cplusplus
}
#endif
#endif /* MURASAKI_PLATFORM_HPP_ */
| 30.363636 | 100 | 0.739982 | suikan4github |
be16f13425dc340b268540882541197a0db249a2 | 343 | cpp | C++ | src/filter_cells.cpp | LTLA/diet.scran | c274bf058e10c174a06a409af50fcad225d40f0d | [
"MIT"
] | null | null | null | src/filter_cells.cpp | LTLA/diet.scran | c274bf058e10c174a06a409af50fcad225d40f0d | [
"MIT"
] | null | null | null | src/filter_cells.cpp | LTLA/diet.scran | c274bf058e10c174a06a409af50fcad225d40f0d | [
"MIT"
] | null | null | null | #include "tatamize.h"
#include "scran/quality_control/FilterCells.hpp"
#include "Rcpp.h"
//[[Rcpp::export(rng=false)]]
SEXP filter_cells(SEXP x, Rcpp::LogicalVector discard) {
scran::FilterCells qc;
auto y = qc.run(extract_NumericMatrix_shared(x), static_cast<const int*>(discard.begin()));
return new_MatrixChan(std::move(y));
}
| 31.181818 | 95 | 0.723032 | LTLA |
be18722437b404c2701a0321ff7f681cac1ac88a | 1,777 | cpp | C++ | Prim's_Algorithm _for_MST.cpp | taareek/c-plus-plus | b9d04f710e9b2e65786618f8bbced4a56c149444 | [
"Unlicense"
] | null | null | null | Prim's_Algorithm _for_MST.cpp | taareek/c-plus-plus | b9d04f710e9b2e65786618f8bbced4a56c149444 | [
"Unlicense"
] | null | null | null | Prim's_Algorithm _for_MST.cpp | taareek/c-plus-plus | b9d04f710e9b2e65786618f8bbced4a56c149444 | [
"Unlicense"
] | null | null | null | #include<iostream>
#include<cstdlib>
#define a 9
using namespace std;
struct prims
{
int cost;
int parent;
bool visited;
};
void printGraph(int graph[a][a]){
for(int i=0; i<a; i++){
for(int j=0; j<a; j++){
cout<<graph[i][j]<<" ";
}
cout<<endl;
}
}
int find_min(struct prims arr[a]){
int least, index;
for(int i=0; i<a; i++){
if(arr[i].visited==false && arr[i].cost<least){
least= arr[i].cost;
index= i;
}
}
return index;
}
void prims_mst(int graph[a][a], struct prims arr[a]){
for(int m=0; m<a-1; m++){
int k= find_min(arr);
arr[k].visited= true;
for(int n=0; n<a; n++){
if(arr[n].visited!=true && graph[k][n]<arr[n].cost){
arr[n].parent= k;
arr[n].cost= graph[k][n];
}
}
}
for(int i=0; i<a; i++){
cout<<arr[i].parent<<"-> ";
}
}
int main(){
//Graph
int graph[a][a]= {
{ 0,4,0,0,0,0,0,8,0},
{ 4,0,8,0,0,0,0,11,0},
{ 0,8,0,7,0,4,0,2,0},
{ 0,0,7,0,9,14,0,0,0},
{ 0,0,0,9,0,10,0,0,0},
{ 0,0,4,14,10,0,2,0,0},
{ 0,0,0,0,0,2,0,1,6},
{ 8,11,0,0,0,0,1,0,7},
{ 0,0,2,0,0,0,6,7,0},
};
//Label Array
struct prims arr[a];
int INFINITY, m;
for(int i=0; i<a; i++){
arr[i].cost= INFINITY;
arr[i].parent= -1;
arr[i].visited= false;
}
int start;
//cout<<"Enter the node from which you want to start(0-8): ";
//cin>>start;
arr[0].cost=0;
//printGraph(graph);
cout<<endl;
prims_mst(graph, arr);
}
| 20.662791 | 66 | 0.420934 | taareek |
be1aa88cce90ce63ac8cd0d78f3045ee6dd9cdf8 | 12,230 | hpp | C++ | framework/areg/base/RuntimeClassID.hpp | Ali-Nasrolahi/areg-sdk | 4fbc2f2644220196004a31672a697a864755f0b6 | [
"Apache-2.0"
] | 70 | 2021-07-20T11:26:16.000Z | 2022-03-27T11:17:43.000Z | framework/areg/base/RuntimeClassID.hpp | Ali-Nasrolahi/areg-sdk | 4fbc2f2644220196004a31672a697a864755f0b6 | [
"Apache-2.0"
] | 32 | 2021-07-31T05:20:44.000Z | 2022-03-20T10:11:52.000Z | framework/areg/base/RuntimeClassID.hpp | Ali-Nasrolahi/areg-sdk | 4fbc2f2644220196004a31672a697a864755f0b6 | [
"Apache-2.0"
] | 40 | 2021-11-02T09:45:38.000Z | 2022-03-27T11:17:46.000Z | #pragma once
/************************************************************************
* This file is part of the AREG SDK core engine.
* AREG SDK is dual-licensed under Free open source (Apache version 2.0
* License) and Commercial (with various pricing models) licenses, depending
* on the nature of the project (commercial, research, academic or free).
* You should have received a copy of the AREG SDK license description in LICENSE.txt.
* If not, please contact to info[at]aregtech.com
*
* \copyright (c) 2017-2021 Aregtech UG. All rights reserved.
* \file areg/base/RuntimeClassID.hpp
* \ingroup AREG SDK, Asynchronous Event Generator Software Development Kit
* \author Artak Avetyan
* \brief AREG Platform, Runtime Class ID
* This class contains information of Runtime Class ID.
* Every Runtime Class contains class ID value to identify and
* cast instances of Runtime Object.
* As an ID of Runtime class used class name.
*
************************************************************************/
/************************************************************************
* Include files.
************************************************************************/
#include "areg/base/GEGlobal.h"
#include "areg/base/String.hpp"
#include <utility>
//////////////////////////////////////////////////////////////////////////
// RuntimeClassID class declaration
//////////////////////////////////////////////////////////////////////////
/**
* \brief Runtime Class ID is used in all objects derived from
* Runtime Objects. It contains the class ID, so that during
* runtime can check and cast the instance of Runtime Object.
* In particular, Runtime Object and Runtime Class ID are used
* in Threads, Events and other objects to check the instance
* of object during runtime.
*
* \see RuntimeObject
**/
class AREG_API RuntimeClassID
{
/************************************************************************
* friend classes to access default constructor.
************************************************************************/
/**
* \brief Declare friend classes to access private default constructor
* required to initialize runtime class ID in hash map blocks.
**/
template < typename KEY, typename VALUE, typename KEY_TYPE, typename VALUE_TYPE, class Implement >
friend class TEHashMap;
template <typename RESOURCE_KEY, typename RESOURCE_OBJECT, class HashMap, class Implement>
friend class TEResourceMap;
//////////////////////////////////////////////////////////////////////////
// Static members
//////////////////////////////////////////////////////////////////////////
public:
/**
* \brief Static function to create empty Runtime Class ID object.
* By default, the class ID value is BAD_CLASS_ID.
* Change the value after creating class ID object.
**/
static inline RuntimeClassID createEmptyClassID( void );
//////////////////////////////////////////////////////////////////////////
// Constructors / Destructor
//////////////////////////////////////////////////////////////////////////
public:
/**
* \brief Initialization constructor.
* This constructor is initializing the name Runtime Class ID
* \param className The name of Runtime Class ID
**/
explicit RuntimeClassID( const char * className );
/**
* \brief Copy constructor.
* \param src The source to copy data.
**/
RuntimeClassID( const RuntimeClassID & src );
/**
* \brief Move constructor.
* \param src The source to move data.
**/
RuntimeClassID( RuntimeClassID && src ) noexcept;
/**
* \brief Destructor
**/
~RuntimeClassID( void ) = default;
//////////////////////////////////////////////////////////////////////////
// Operators
//////////////////////////////////////////////////////////////////////////
public:
/************************************************************************/
// friend global operators
/************************************************************************/
/**
* \brief Compares null-terminated string with Runtime Class ID name.
* \param lhs Left-Hand Operand, string to compare.
* \param rhs Right-Hand Operand, Runtime Class ID to compare the name.
* \return Returns true if string is equal to Runtime Class ID.
**/
friend inline bool operator == ( const char * lhs, const RuntimeClassID & rhs );
/**
* \brief Compare null-terminated string with Runtime Class ID name.
* \param lhs Left-Hand Operand, string to compare.
* \param rhs Right-Hand Operand, Runtime Class to compare the name.
* \return Returns true if string is not equal to Runtime Class ID.
**/
friend inline bool operator != ( const char * lhs, const RuntimeClassID & rhs );
/**
* \brief Compares number with Runtime Class ID calculated number.
* \param lhs Left-Hand Operand, number to compare.
* \param rhs Right-Hand Operand, Runtime Class ID to compare the calculated number.
* \return Returns true if number is equal to Runtime Class ID.
**/
friend inline bool operator == ( unsigned int lhs, const RuntimeClassID & rhs );
/**
* \brief Compares number with Runtime Class ID calculated number.
* \param lhs Left-Hand Operand, number to compare.
* \param rhs Right-Hand Operand, Runtime Class ID to compare the calculated number.
* \return Returns true if number is not equal to Runtime Class ID.
**/
friend inline bool operator != ( unsigned int lhs, const RuntimeClassID & rhs );
/************************************************************************/
// class members operators
/************************************************************************/
/**
* \brief Assigning operator. Copies Runtime Class ID name from given Runtime Class ID source
* \param src The source of Runtime Class ID to copy.
* \return Returns Runtime Class ID object.
**/
inline RuntimeClassID & operator = ( const RuntimeClassID & src );
/**
* \brief Move operator. Moves Runtime Class ID name from given Runtime Class ID source.
* \param src The source of Runtime Class ID to move.
* \return Returns Runtime Class ID object.
**/
inline RuntimeClassID & operator = ( RuntimeClassID && src ) noexcept;
/**
* \brief Assigning operator. Copies Runtime Class ID name from given string buffer source
* \param src The source of string buffer to copy.
* \return Returns Runtime Class ID object.
**/
inline RuntimeClassID & operator = ( const char * src );
/**
* \brief Assigning operator. Copies Runtime Class ID name from given string source
* \param src The source of string to copy.
* \return Returns Runtime Class ID object.
**/
inline RuntimeClassID & operator = ( const String & src );
/**
* \brief Comparing operator. Compares 2 Runtime Class ID objects.
* \param other The Runtime Class ID object to compare
* \return Returns true if 2 instance of Runtime Class ID have same Class ID value.
**/
inline bool operator == ( const RuntimeClassID & other ) const;
/**
* \brief Comparing operator. Compares Runtime Class ID and string.
* \param other The null-terminated string to compare
* \return Returns true if Runtime Class ID value is equal to null-terminated string.
**/
inline bool operator == ( const char * other ) const;
/**
* \brief Comparing operator. Compares 2 Runtime Class ID objects.
* \param other The Runtime Class ID object to compare
* \return Returns true if 2 instance of Runtime Class ID have different Class ID values.
**/
inline bool operator != ( const RuntimeClassID & other ) const;
/**
* \brief Comparing operator. Compares Runtime Class ID and string.
* \param other The null-terminated string to compare
* \return Returns true if Runtime Class ID value is not equal to given null-terminated string.
**/
inline bool operator != (const char * other) const;
/**
* \brief Operator to convert the value or Runtime Class ID to unsigned integer value.
* Used to calculate hash value in hash map
**/
inline explicit operator unsigned int ( void ) const;
//////////////////////////////////////////////////////////////////////////
// Attributes
//////////////////////////////////////////////////////////////////////////
/**
* \brief Returns true if the value of Runtime Class ID is not equal to RuntimeClassID::BAD_CLASS_ID.
**/
inline bool isValid( void ) const;
/**
* \brief Returns the name of Runtime Class ID.
**/
inline const char * getName( void ) const;
/**
* \brief Sets the name of Runtime Class ID.
**/
void setName( const char * className );
/**
* \brief Returns calculated number of runtime class.
**/
inline unsigned getMagic( void ) const;
//////////////////////////////////////////////////////////////////////////
// Hidden methods
//////////////////////////////////////////////////////////////////////////
private:
/**
* \brief Default constructor. Private. Will create BAD_CLASS_ID
* object.
**/
RuntimeClassID( void );
//////////////////////////////////////////////////////////////////////////
// Member variables
//////////////////////////////////////////////////////////////////////////
private:
/**
* \brief Runtime Class ID value.
**/
String mClassName;
/**
* \brief The calculated number of runtime class.
**/
unsigned int mMagicNum;
};
//////////////////////////////////////////////////////////////////////////
// RuntimeClassID class inline function implementation
//////////////////////////////////////////////////////////////////////////
inline RuntimeClassID RuntimeClassID::createEmptyClassID( void )
{
return RuntimeClassID();
}
inline RuntimeClassID & RuntimeClassID::operator = ( const RuntimeClassID & src )
{
this->mClassName= src.mClassName;
this->mMagicNum = src.mMagicNum;
return (*this);
}
inline RuntimeClassID & RuntimeClassID::operator = ( RuntimeClassID && src ) noexcept
{
this->mClassName= std::move(src.mClassName);
this->mMagicNum = src.mMagicNum;
return (*this);
}
inline RuntimeClassID & RuntimeClassID::operator = ( const char * src )
{
setName(src);
return (*this);
}
inline RuntimeClassID & RuntimeClassID::operator = ( const String & src )
{
setName(src);
return (*this);
}
inline bool RuntimeClassID::operator == ( const RuntimeClassID & other ) const
{
return (mMagicNum == other.mMagicNum);
}
inline bool RuntimeClassID::operator == ( const char * other ) const
{
return mClassName == other;
}
inline bool RuntimeClassID::operator != ( const RuntimeClassID & other ) const
{
return (mMagicNum != other.mMagicNum);
}
inline bool RuntimeClassID::operator != ( const char* other ) const
{
return mClassName != other;
}
inline RuntimeClassID::operator unsigned int ( void ) const
{
return mMagicNum;
}
inline bool RuntimeClassID::isValid( void ) const
{
return (mMagicNum != NEMath::CHECKSUM_IGNORE);
}
inline const char* RuntimeClassID::getName( void ) const
{
return mClassName.getString();
}
inline unsigned RuntimeClassID::getMagic(void) const
{
return mMagicNum;
}
inline bool operator == ( const char * lhs, const RuntimeClassID & rhs )
{
return rhs.mClassName == lhs;
}
inline bool operator != ( const char* lhs, const RuntimeClassID & rhs )
{
return rhs.mClassName != lhs;
}
inline bool operator == ( unsigned int lhs, const RuntimeClassID & rhs )
{
return rhs.mMagicNum == lhs;
}
inline bool operator != ( unsigned int lhs, const RuntimeClassID & rhs )
{
return rhs.mMagicNum != lhs;
}
| 35.865103 | 107 | 0.553802 | Ali-Nasrolahi |
be1bb2e706b7d4485d8d48b4f2d049421bf5275b | 6,764 | cc | C++ | chrome/browser/component_updater/component_patcher_operation_browsertest.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/component_updater/component_patcher_operation_browsertest.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/component_updater/component_patcher_operation_browsertest.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/base_paths.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/files/file.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/task/post_task.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "build/build_config.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "components/services/patch/content/patch_service.h"
#include "components/services/patch/public/cpp/patch.h"
#include "components/update_client/component_patcher_operation.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "courgette/courgette.h"
#include "courgette/third_party/bsdiff/bsdiff.h"
namespace {
constexpr base::TaskTraits kThreadPoolTaskTraits = {
base::MayBlock(), base::TaskPriority::BEST_EFFORT,
base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN};
} // namespace
class PatchTest : public InProcessBrowserTest {
public:
PatchTest() {
EXPECT_TRUE(installed_dir_.CreateUniqueTempDir());
EXPECT_TRUE(input_dir_.CreateUniqueTempDir());
EXPECT_TRUE(unpack_dir_.CreateUniqueTempDir());
}
static base::FilePath TestFile(const char* name) {
base::FilePath path;
base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
return path.AppendASCII("components")
.AppendASCII("test")
.AppendASCII("data")
.AppendASCII("update_client")
.AppendASCII(name);
}
base::FilePath InputFilePath(const char* name) {
base::FilePath path = installed_dir_.GetPath().AppendASCII(name);
base::RunLoop run_loop;
base::ThreadPool::PostTaskAndReply(
FROM_HERE, kThreadPoolTaskTraits,
base::BindOnce(&PatchTest::CopyFile, TestFile(name), path),
run_loop.QuitClosure());
run_loop.Run();
return path;
}
base::FilePath PatchFilePath(const char* name) {
base::FilePath path = input_dir_.GetPath().AppendASCII(name);
base::RunLoop run_loop;
base::ThreadPool::PostTaskAndReply(
FROM_HERE, kThreadPoolTaskTraits,
base::BindOnce(&PatchTest::CopyFile, TestFile(name), path),
run_loop.QuitClosure());
run_loop.Run();
return path;
}
base::FilePath OutputFilePath(const char* name) {
return unpack_dir_.GetPath().AppendASCII(name);
}
base::FilePath InvalidPath(const char* name) {
return input_dir_.GetPath().AppendASCII("nonexistent").AppendASCII(name);
}
void RunPatchTest(const std::string& operation,
const base::FilePath& input,
const base::FilePath& patch,
const base::FilePath& output,
int expected_result) {
base::RunLoop run_loop;
quit_closure_ = run_loop.QuitClosure();
done_called_ = false;
base::ThreadPool::CreateSequencedTaskRunner(kThreadPoolTaskTraits)
->PostTask(FROM_HERE,
base::BindOnce(&PatchTest::PatchAsyncSequencedTaskRunner,
base::Unretained(this), operation, input,
patch, output, expected_result));
run_loop.Run();
EXPECT_TRUE(done_called_);
}
private:
void PatchAsyncSequencedTaskRunner(
const std::string& operation,
const base::FilePath& input,
const base::FilePath& patch,
const base::FilePath& output,
int expected_result) {
patch::Patch(patch::LaunchFilePatcher(), operation, input, patch, output,
base::BindOnce(&PatchTest::PatchDone, base::Unretained(this),
expected_result));
}
void PatchDone(int expected, int result) {
EXPECT_EQ(expected, result);
done_called_ = true;
base::CreateSingleThreadTaskRunner({content::BrowserThread::UI})
->PostTask(FROM_HERE, std::move(quit_closure_));
}
static void CopyFile(const base::FilePath& source,
const base::FilePath& target) {
EXPECT_TRUE(base::CopyFile(source, target));
}
base::ScopedTempDir installed_dir_;
base::ScopedTempDir input_dir_;
base::ScopedTempDir unpack_dir_;
base::OnceClosure quit_closure_;
bool done_called_;
DISALLOW_COPY_AND_ASSIGN(PatchTest);
};
IN_PROC_BROWSER_TEST_F(PatchTest, CheckBsdiffOperation) {
constexpr int kExpectedResult = bsdiff::OK;
base::FilePath input_file = InputFilePath("binary_input.bin");
base::FilePath patch_file = PatchFilePath("binary_bsdiff_patch.bin");
base::FilePath output_file = OutputFilePath("output.bin");
RunPatchTest(update_client::kBsdiff, input_file, patch_file, output_file,
kExpectedResult);
EXPECT_TRUE(base::ContentsEqual(TestFile("binary_output.bin"), output_file));
}
IN_PROC_BROWSER_TEST_F(PatchTest, CheckCourgetteOperation) {
constexpr int kExpectedResult = courgette::C_OK;
base::FilePath input_file = InputFilePath("binary_input.bin");
base::FilePath patch_file = PatchFilePath("binary_courgette_patch.bin");
base::FilePath output_file = OutputFilePath("output.bin");
RunPatchTest(update_client::kCourgette, input_file, patch_file, output_file,
kExpectedResult);
EXPECT_TRUE(base::ContentsEqual(TestFile("binary_output.bin"), output_file));
}
IN_PROC_BROWSER_TEST_F(PatchTest, InvalidInputFile) {
constexpr int kInvalidInputFile = -1;
base::FilePath invalid = InvalidPath("binary_input.bin");
base::FilePath patch_file = PatchFilePath("binary_courgette_patch.bin");
base::FilePath output_file = OutputFilePath("output.bin");
RunPatchTest(update_client::kCourgette, invalid, patch_file, output_file,
kInvalidInputFile);
}
IN_PROC_BROWSER_TEST_F(PatchTest, InvalidPatchFile) {
constexpr int kInvalidPatchFile = -1;
base::FilePath input_file = InputFilePath("binary_input.bin");
base::FilePath invalid = InvalidPath("binary_courgette_patch.bin");
base::FilePath output_file = OutputFilePath("output.bin");
RunPatchTest(update_client::kCourgette, input_file, invalid, output_file,
kInvalidPatchFile);
}
IN_PROC_BROWSER_TEST_F(PatchTest, InvalidOutputFile) {
constexpr int kInvalidOutputFile = -1;
base::FilePath input_file = InputFilePath("binary_input.bin");
base::FilePath patch_file = PatchFilePath("binary_courgette_patch.bin");
base::FilePath invalid = InvalidPath("output.bin");
RunPatchTest(update_client::kCourgette, input_file, patch_file, invalid,
kInvalidOutputFile);
}
| 34.161616 | 79 | 0.714666 | sarang-apps |
be1ec1f0e46485e8f7775cc784e8d2d64e8b2c98 | 1,200 | cpp | C++ | RLSimion/CNTKWrapper/InputData.cpp | xcillero001/SimionZoo | b343b08f3356e1aa230d4132b0abb58aac4c5e98 | [
"MIT"
] | 1 | 2019-02-21T10:40:28.000Z | 2019-02-21T10:40:28.000Z | RLSimion/CNTKWrapper/InputData.cpp | JosuGom3z/SimionZoo | b343b08f3356e1aa230d4132b0abb58aac4c5e98 | [
"MIT"
] | null | null | null | RLSimion/CNTKWrapper/InputData.cpp | JosuGom3z/SimionZoo | b343b08f3356e1aa230d4132b0abb58aac4c5e98 | [
"MIT"
] | null | null | null | #include "InputData.h"
#include "xmltags.h"
#include "ParameterValues.h"
#include "CNTKWrapperInternals.h"
#include "Exceptions.h"
InputData::InputData(tinyxml2::XMLElement * pParentNode)
{
m_id = pParentNode->Attribute(XML_ATTRIBUTE_Id);
if (m_id.empty())
throw ProblemParserElementNotFound(XML_ATTRIBUTE_Id);
m_name = pParentNode->Attribute(XML_ATTRIBUTE_Name);
if (m_name.empty())
m_name = "InputData";
tinyxml2::XMLElement* pNode = pParentNode->FirstChildElement(XML_TAG_Shape);
if (pNode == nullptr)
throw ProblemParserElementNotFound(XML_TAG_Shape);
m_pShape = CIntTuple::getInstance(pNode);
}
InputData::InputData(string id, CNTK::Variable pInputVariable)
{
m_id = id;
m_inputVariable = pInputVariable;
}
InputData::~InputData()
{
}
InputData * InputData::getInstance(tinyxml2::XMLElement * pNode)
{
if (!strcmp(pNode->Name(), XML_TAG_InputData))
return new InputData(pNode);
return nullptr;
}
NDShape InputData::getNDShape()
{
return m_pShape->getNDShape();
}
void InputData::createInputVariable()
{
m_isInitialized = true;
m_inputVariable = CNTK::InputVariable(m_pShape->getNDShape(), CNTK::DataType::Double, CNTKWrapper::Internal::string2wstring(m_id));
}
| 22.222222 | 132 | 0.758333 | xcillero001 |
be2028dd6194d28f16be8bda33256e006569f045 | 14,138 | cpp | C++ | private/src/diagnostic/IasDiagnosticStream.cpp | juimonen/SmartXbar | 033f521a5dba5bce5e097df9c98af5b2cc2636dd | [
"BSD-3-Clause"
] | 5 | 2018-11-05T07:37:58.000Z | 2022-03-04T06:40:09.000Z | private/src/diagnostic/IasDiagnosticStream.cpp | juimonen/SmartXbar | 033f521a5dba5bce5e097df9c98af5b2cc2636dd | [
"BSD-3-Clause"
] | null | null | null | private/src/diagnostic/IasDiagnosticStream.cpp | juimonen/SmartXbar | 033f521a5dba5bce5e097df9c98af5b2cc2636dd | [
"BSD-3-Clause"
] | 7 | 2018-12-04T07:32:19.000Z | 2021-02-17T11:28:28.000Z | /*
* Copyright (C) 2018 Intel Corporation.All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
/**
* File: IasDiagnosticStream.cpp
*/
#include <assert.h>
#include <ctime>
#include <cstdio>
#include <algorithm>
#include <chrono>
#include "diagnostic/IasDiagnosticStream.hpp"
#include "diagnostic/IasDiagnosticLogWriter.hpp"
namespace IasAudio {
#define TMP_PATH "/tmp/"
static const std::string cClassName = "IasDiagnosticStream::";
#define LOG_PREFIX cClassName + __func__ + "(" + std::to_string(__LINE__) + "):"
#define LOG_DEVICE "device=" + mParams.deviceName + ":"
#define LOG_STATE "[" + toString(mStreamState) + "]"
IasDiagnosticStream::IasDiagnosticStream(const struct IasParams& params, IasDiagnosticLogWriter& logWriter)
:mLog(IasAudioLogging::registerDltContext("AHD", "ALSA Handler"))
,mLogThread(IasAudioLogging::registerDltContext("AHDD", "ALSA Handler Diagnostic File Operations Thread"))
,mParams(params)
,mPeriodCounter(0)
,mMaxCounter(0)
,mTmpFile()
,mTmpFileName()
,mTmpFileNameFull()
,mStreamState(eIasStreamStateIdle)
,mStreamStateMutex()
,mFileOpen()
,mFileClose()
,mCondWaitForStart()
,mMutexWaitForStart()
,mStreamStarted(false)
,mErrorCounter(0)
,mLogWriter(logWriter)
,mFileIdx(0)
{
if (mParams.periodTime == 0)
{
// Set default to 5333us
mParams.periodTime = 5333;
}
std::uint32_t bytesPerSecond = cBytesPerPeriod * 1000 * 1000 / mParams.periodTime;
std::uint32_t bytesPerHour = bytesPerSecond * 60 * 60;
mMaxCounter = bytesPerHour / cBytesPerPeriod;
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_DEVICE, "Maximum bytes recorded per hour=", bytesPerHour, "maximum counter=", mMaxCounter);
}
IasDiagnosticStream::~IasDiagnosticStream()
{
changeState(IasTriggerStateChange::eIasStop);
isStopped(); // this call really waits until the stream is stopped and the file is closed
if (mFileOpen.joinable())
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, "File open thread will be joined now");
mFileOpen.join();
}
if (mFileClose.joinable())
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, "File close thread will be joined now");
mFileClose.join();
}
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX);
}
void IasDiagnosticStream::writeAlsaHandlerData(std::uint64_t timestampDeviceBuffer, std::uint64_t numTransmittedFramesDevice, std::uint64_t timestampAsrcBuffer, std::uint64_t numTransmittedFramesAsrc, std::uint32_t asrcBufferNumFramesAvailable, std::uint32_t numTotalFrames, std::float_t ratioAdaptive)
{
if (mStreamState != eIasStreamStateStarted)
{
DLT_LOG_CXX(*mLog, DLT_LOG_VERBOSE, LOG_PREFIX, LOG_STATE, "Stream not started yet");
return;
}
DLT_LOG_CXX(*mLog, DLT_LOG_VERBOSE, LOG_PREFIX, "Writing data to file, period #", mPeriodCounter);
char tmpBuffer[cBytesPerPeriod];
std::uint64_t* ptr_ui64 = reinterpret_cast<std::uint64_t*>(tmpBuffer);
*ptr_ui64++ = timestampDeviceBuffer;
*ptr_ui64++ = numTransmittedFramesDevice;
*ptr_ui64++ = timestampAsrcBuffer;
*ptr_ui64++ = numTransmittedFramesAsrc;
std::uint32_t* ptr_ui32 = reinterpret_cast<std::uint32_t*>(ptr_ui64);
*ptr_ui32++ = asrcBufferNumFramesAvailable;
*ptr_ui32++ = numTotalFrames;
std::float_t* ptr_float = reinterpret_cast<std::float_t*>(ptr_ui32);
*ptr_float = ratioAdaptive;
mTmpFile.write(tmpBuffer, cBytesPerPeriod);
++mPeriodCounter;
if (mPeriodCounter > mMaxCounter)
{
mPeriodCounter = 0;
changeState(eIasStop);
}
}
IasDiagnosticStream::IasResult IasDiagnosticStream::startStream()
{
IasStreamState newState = changeState(eIasStart);
if ((newState == eIasStreamStateOpening) || (newState == eIasStreamStatePendingOpen))
{
return IasResult::eIasOk;
}
else
{
return IasResult::eIasFailed;
}
}
IasDiagnosticStream::IasResult IasDiagnosticStream::stopStream()
{
IasStreamState newState = changeState(eIasStop);
if ((newState == eIasStreamStateClosing) || (newState == eIasStreamStatePendingClose))
{
return IasResult::eIasOk;
}
else
{
return IasResult::eIasFailed;
}
}
IasDiagnosticStream::IasStreamState IasDiagnosticStream::changeState(IasTriggerStateChange trigger)
{
std::lock_guard<std::mutex> lock(mStreamStateMutex);
switch (mStreamState)
{
case eIasStreamStateIdle:
if (trigger == IasTriggerStateChange::eIasStart)
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Trigger=", toString(trigger), ". New state=", toString(eIasStreamStateOpening));
mStreamState = eIasStreamStateOpening;
if (mFileOpen.joinable())
{
mFileOpen.join();
}
mFileOpen = std::thread(&IasDiagnosticStream::openFile, this);
}
else
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Ignoring trigger", toString(trigger));
}
break;
case eIasStreamStateStarted:
if (trigger == IasTriggerStateChange::eIasStop)
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Trigger=", toString(trigger), ". New state=", toString(eIasStreamStateClosing));
mStreamState = eIasStreamStateClosing;
if (mFileClose.joinable())
{
mFileClose.join();
}
mFileClose = std::thread(&IasDiagnosticStream::closeFile, this);
}
else
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Ignoring trigger", toString(trigger));
}
break;
case eIasStreamStateOpening:
if (trigger == IasTriggerStateChange::eIasOpeningFinished)
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Trigger=", toString(trigger), ". New state=", toString(eIasStreamStateStarted));
mStreamState = eIasStreamStateStarted;
{
std::lock_guard<std::mutex> lk(mMutexWaitForStart);
mStreamStarted = true;
}
mCondWaitForStart.notify_one();
}
else if (trigger == IasTriggerStateChange::eIasStop)
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Trigger=", toString(trigger), ". New state=", toString(eIasStreamStatePendingClose));
mStreamState = eIasStreamStatePendingClose;
}
else
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Ignoring trigger", toString(trigger));
}
break;
case eIasStreamStatePendingClose:
if (trigger == IasTriggerStateChange::eIasOpeningFinished)
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Trigger=", toString(trigger), ". New state=", toString(eIasStreamStateClosing));
mStreamState = eIasStreamStateClosing;
{
std::lock_guard<std::mutex> lk(mMutexWaitForStart);
mStreamStarted = true;
}
mCondWaitForStart.notify_one();
if (mFileClose.joinable())
{
mFileClose.join();
}
mFileClose = std::thread(&IasDiagnosticStream::closeFile, this);
}
else
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Ignoring trigger", toString(trigger));
}
break;
case eIasStreamStateClosing:
if (trigger == IasTriggerStateChange::eIasClosingFinished)
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Trigger=", toString(trigger), ". New state=", toString(eIasStreamStateIdle));
mStreamState = eIasStreamStateIdle;
{
std::lock_guard<std::mutex> lk(mMutexWaitForStart);
mStreamStarted = false;
}
mCondWaitForStart.notify_one();
}
else if (trigger == IasTriggerStateChange::eIasStart)
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Trigger=", toString(trigger), ". New state=", toString(eIasStreamStatePendingOpen));
mStreamState = eIasStreamStatePendingOpen;
}
else
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Ignoring trigger", toString(trigger));
}
break;
case eIasStreamStatePendingOpen:
if (trigger == IasTriggerStateChange::eIasClosingFinished)
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Trigger=", toString(trigger), ". New state=", toString(eIasStreamStateOpening));
mStreamState = eIasStreamStateOpening;
{
std::lock_guard<std::mutex> lk(mMutexWaitForStart);
mStreamStarted = false;
}
mCondWaitForStart.notify_one();
if (mFileOpen.joinable())
{
mFileOpen.join();
}
mFileOpen = std::thread(&IasDiagnosticStream::openFile, this);
}
else if (trigger == IasTriggerStateChange::eIasStop)
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Trigger=", toString(trigger), ". New state=", toString(eIasStreamStatePendingClose));
mStreamState = eIasStreamStatePendingClose;
}
else
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Ignoring trigger", toString(trigger));
}
break;
}
return mStreamState;
}
void IasDiagnosticStream::openFile()
{
if (mTmpFile.is_open() == false)
{
std::time_t t = std::time(nullptr);
std::tm* tm = std::localtime(&t);
char currentTime[20] = {'\0'};
if (tm != nullptr)
{
std::strftime(currentTime, sizeof(currentTime), "%T", tm);
}
mTmpFileName = std::string(currentTime) + "_" + mParams.deviceName + "_asrc_diag_" + std::to_string(mFileIdx) + ".bin";
mFileIdx++;
// Replace all commas with underscore to have a cleaner filename
std::replace(mTmpFileName.begin(), mTmpFileName.end(), ',', '_');
mTmpFileNameFull = std::string(TMP_PATH) + mTmpFileName;
DLT_LOG_CXX(*mLogThread, DLT_LOG_INFO, LOG_PREFIX, "Opening tmp file", mTmpFileNameFull, "for writing diagnostic log");
mTmpFile.open(mTmpFileNameFull, std::ios::binary|std::ios::out|std::ios::trunc);
mErrorCounter = 0;
}
changeState(eIasOpeningFinished);
}
void IasDiagnosticStream::closeFile()
{
if (mTmpFile.is_open())
{
std::uint32_t fileSize = static_cast<std::uint32_t>(mTmpFile.tellp());
DLT_LOG_CXX(*mLogThread, DLT_LOG_INFO, LOG_PREFIX, mTmpFileNameFull, "file size=", fileSize);
mTmpFile.close();
}
DLT_LOG_CXX(*mLogThread, DLT_LOG_INFO, LOG_PREFIX, "Closing file", mTmpFileNameFull, "finished");
bool writeToLog = false;
if (mParams.copyTo.compare("log") == 0)
{
writeToLog = true;
}
if (mErrorCounter >= mParams.errorThreshold)
{
if (writeToLog)
{
mLogWriter.addFile(mTmpFileNameFull);
}
else
{
copyFile();
}
}
else
{
std::remove(mTmpFileNameFull.c_str());
DLT_LOG_CXX(*mLogThread, DLT_LOG_INFO, LOG_PREFIX, "Removed", mTmpFileNameFull);
}
mErrorCounter = 0;
changeState(eIasClosingFinished);
}
void IasDiagnosticStream::copyFile()
{
std::ofstream dstFile;
std::ifstream srcFile;
std::string dstFileName = mParams.copyTo;
if (dstFileName.back() != '/')
{
dstFileName.append("/");
}
dstFileName += mTmpFileName;
DLT_LOG_CXX(*mLogThread, DLT_LOG_INFO, LOG_PREFIX, "Copying from", mTmpFileNameFull, "to", dstFileName);
dstFile.open(dstFileName, std::ios::binary|std::ios::out|std::ios::trunc);
if (dstFile.is_open())
{
srcFile.open(mTmpFileNameFull, std::ios::binary);
dstFile<<srcFile.rdbuf();
srcFile.close();
dstFile.close();
DLT_LOG_CXX(*mLogThread, DLT_LOG_INFO, LOG_PREFIX, "Copying from", mTmpFileNameFull, "to", dstFileName, "finished successfully.");
}
else
{
DLT_LOG_CXX(*mLogThread, DLT_LOG_ERROR, LOG_PREFIX, "Destination file", dstFileName, "couldn't be created");
}
std::remove(mTmpFileNameFull.c_str());
DLT_LOG_CXX(*mLogThread, DLT_LOG_INFO, LOG_PREFIX, "Removed", mTmpFileNameFull);
}
bool IasDiagnosticStream::isStarted()
{
std::unique_lock<std::mutex> lk(mMutexWaitForStart);
bool status = mCondWaitForStart.wait_for(lk, std::chrono::seconds(1), [this] { return mStreamStarted == true; });
if (status == true)
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, "Stream is started");
}
else
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, "Stream is not started after timeout of 1s");
}
return status;
}
bool IasDiagnosticStream::isStopped()
{
std::unique_lock<std::mutex> lk(mMutexWaitForStart);
bool status = mCondWaitForStart.wait_for(lk, std::chrono::seconds(1), [this] { return mStreamStarted == false; });
if (status == true)
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, "Stream is stopped");
}
else
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, "Stream is not stopped after timeout of 1s");
}
return status;
}
void IasDiagnosticStream::errorOccurred()
{
++mErrorCounter;
}
#define STRING_RETURN_CASE(name) case name: return std::string(#name); break
#define DEFAULT_STRING(name) default: return std::string(name)
std::string IasDiagnosticStream::toString(const IasStreamState& streamState)
{
switch(streamState)
{
STRING_RETURN_CASE(IasDiagnosticStream::IasStreamState::eIasStreamStateIdle);
STRING_RETURN_CASE(IasDiagnosticStream::IasStreamState::eIasStreamStateStarted);
STRING_RETURN_CASE(IasDiagnosticStream::IasStreamState::eIasStreamStateOpening);
STRING_RETURN_CASE(IasDiagnosticStream::IasStreamState::eIasStreamStateClosing);
STRING_RETURN_CASE(IasDiagnosticStream::IasStreamState::eIasStreamStatePendingClose);
STRING_RETURN_CASE(IasDiagnosticStream::IasStreamState::eIasStreamStatePendingOpen);
DEFAULT_STRING("Invalid IasStreamState => " + std::to_string(streamState));
}
}
std::string IasDiagnosticStream::toString(const IasTriggerStateChange& trigger)
{
switch(trigger)
{
STRING_RETURN_CASE(IasDiagnosticStream::IasTriggerStateChange::eIasStart);
STRING_RETURN_CASE(IasDiagnosticStream::IasTriggerStateChange::eIasStop);
STRING_RETURN_CASE(IasDiagnosticStream::IasTriggerStateChange::eIasOpeningFinished);
STRING_RETURN_CASE(IasDiagnosticStream::IasTriggerStateChange::eIasClosingFinished);
DEFAULT_STRING("Invalid IasTriggerStateChange => " + std::to_string(trigger));
}
}
} /* namespace IasAudio */
| 33.742243 | 302 | 0.698331 | juimonen |
be252a88b5fdcdffbe0c7deef9a4179ac1b916d9 | 1,874 | cpp | C++ | 算法学习/第三章 分治法/00004H_选择最大最小元素/code.cpp | gaowanlu/LearnAlgorithm_2021 | 7e8f50d98a04a5820147d3cc1c2e84ccf9f0cb7e | [
"MIT"
] | 1 | 2021-01-16T04:13:12.000Z | 2021-01-16T04:13:12.000Z | 算法学习/第三章 分治法/00004H_选择最大最小元素/code.cpp | gaowanlu/LearnAlgorithm_2021 | 7e8f50d98a04a5820147d3cc1c2e84ccf9f0cb7e | [
"MIT"
] | null | null | null | 算法学习/第三章 分治法/00004H_选择最大最小元素/code.cpp | gaowanlu/LearnAlgorithm_2021 | 7e8f50d98a04a5820147d3cc1c2e84ccf9f0cb7e | [
"MIT"
] | null | null | null | /*
在第一章中,我们用迭代枚举求解了,寻找最大最小元素
学了分治思想算法,我们能否利用分治的思想
来解决,在数字序列中寻找 最大元素 与 最小元素呢
let's we get start
算法步骤
1 2 3 4 5
分为两部分
1 2 3 4 5
min=1 max=2 3 4 5
min=3 max=3 min=4 max=5
min=3 max=5
min=1 max=2 min=3 max=5
result=> min=1 max=5
*/
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int MAX=100;
int list[MAX];
//分治算法之寻找最大和最小元素
void FindMaxMin(int *list,int s,int e,int *maxmin){
if(e-s<=1){//两个元素时
if(list[e]>list[s]){
maxmin[0]=list[e];
maxmin[1]=list[s];
}else{
maxmin[0]=list[e];
maxmin[1]=list[s];
}
return;
}else{
/*从中间分开,left right 分为两部分
寻找两边的最小元素 与 最大元素
经过比较再选出整体的最大元素与最小元素
*/
int mid=(s+e)/2;
int leftmaxmin[2];
int rightmaxmin[2];
FindMaxMin(list,s,mid,leftmaxmin);
FindMaxMin(list,mid+1,e,rightmaxmin);
//比较选出最大值
if(leftmaxmin[0]<rightmaxmin[0]){
maxmin[0]=rightmaxmin[0];
}else{
maxmin[0]=leftmaxmin[0];
}
//比较选出最小值
if(leftmaxmin[1]<rightmaxmin[1]){
maxmin[1]=leftmaxmin[1];
}else{
maxmin[1]=rightmaxmin[1];
}
}
}
int main(void){
memset(list,0,sizeof(list));
int maxmin[2];
int n;
cout<<"请输入元素个数n\n";
cin>>n;
cout<<"n="<<n<<endl;
cout<<"请输入元素\n";
for(int i=0;i<n;i++){
scanf("%d",&list[i]);
}
cout<<"over input list\n";
cout<<"list[]={";
for(int i=0;i<n;i++){
cout<<list[i]<<" ";
if(i!=n-1){
cout<<",";
}
}
cout<<"}\n";
FindMaxMin(list,0,n-1,maxmin);
cout<<"max="<<maxmin[0]<<" min="<<maxmin[1]<<endl;
return 0;
}
| 22.309524 | 54 | 0.478655 | gaowanlu |
be25620a6c09d51fbd97664e0d6e263b4fb04e7f | 130 | cpp | C++ | src/modules/vmount/vmount.cpp | Diksha-agg/Firmware_val | 1efc1ba06997d19df3ed9bd927cfb24401b0fe03 | [
"BSD-3-Clause"
] | null | null | null | src/modules/vmount/vmount.cpp | Diksha-agg/Firmware_val | 1efc1ba06997d19df3ed9bd927cfb24401b0fe03 | [
"BSD-3-Clause"
] | null | null | null | src/modules/vmount/vmount.cpp | Diksha-agg/Firmware_val | 1efc1ba06997d19df3ed9bd927cfb24401b0fe03 | [
"BSD-3-Clause"
] | null | null | null | version https://git-lfs.github.com/spec/v1
oid sha256:c3585e2db12c3926546d8188a694cd568aa96746e1589110d909fb4649296d1f
size 18247
| 32.5 | 75 | 0.884615 | Diksha-agg |
be2927dafaa6379e3f2fe1a3f64700e9781ce4ed | 981 | cpp | C++ | examples/gpds/main.cpp | Tectu/cpp-properties | b56a5ae13a21a3d8569cce9290d8d8befae15f3f | [
"MIT"
] | 9 | 2021-01-08T11:44:14.000Z | 2021-09-05T13:48:35.000Z | examples/gpds/main.cpp | Tectu/cpp-properties | b56a5ae13a21a3d8569cce9290d8d8befae15f3f | [
"MIT"
] | 4 | 2021-01-07T22:32:41.000Z | 2021-09-14T20:08:04.000Z | examples/gpds/main.cpp | Tectu/cpp-properties | b56a5ae13a21a3d8569cce9290d8d8befae15f3f | [
"MIT"
] | 1 | 2021-03-04T06:28:20.000Z | 2021-03-04T06:28:20.000Z | #include <iostream>
#include <gpds/container.hpp>
#include <gpds/archiver_xml.hpp>
#include "cppproperties/properties.hpp"
#include "cppproperties/archiver_gpds.hpp"
struct shape :
tct::properties::properties
{
MAKE_PROPERTY(locked, bool);
MAKE_PROPERTY(x, int);
MAKE_PROPERTY(y, int);
MAKE_PROPERTY(name, std::string);
};
int main()
{
shape s;
s.locked = false;
s.x = 24;
s.y = 48;
s.name = "My Shape";
s.set_attribute("foobar", "zbar");
s.name.set_attribute("name-attr", "test1234");
tct::properties::archiver_gpds ar;
const gpds::container& c = ar.save(s);
std::stringstream ss;
gpds::archiver_xml gpds_ar;
gpds_ar.save(ss, c, "properties");
gpds::container gpds_c;
gpds_ar.load(ss, gpds_c, "properties");
shape s2;
ar.load(s2, gpds_c);
std::cout << s2.locked << "\n";
std::cout << s2.x << "\n";
std::cout << s2.y << "\n";
std::cout << s2.name << "\n";
return 0;
}
| 20.87234 | 50 | 0.610601 | Tectu |
be2c2fafa2b3aed8c193c6c1bf55d2fdb5f05f13 | 965 | cpp | C++ | Medium/19_Remove_Nth_Node_From_End_of_List.cpp | Napolean28/leet | 80854c24a9549cc665bddc8e87489bd4b550a00d | [
"MIT"
] | 1 | 2019-12-24T19:41:34.000Z | 2019-12-24T19:41:34.000Z | Medium/19_Remove_Nth_Node_From_End_of_List.cpp | Napolean28/leet | 80854c24a9549cc665bddc8e87489bd4b550a00d | [
"MIT"
] | null | null | null | Medium/19_Remove_Nth_Node_From_End_of_List.cpp | Napolean28/leet | 80854c24a9549cc665bddc8e87489bd4b550a00d | [
"MIT"
] | 1 | 2019-12-23T10:20:00.000Z | 2019-12-23T10:20:00.000Z | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int getLen(ListNode* head){
int len = 0;
while(head != NULL){
len++;
head = head->next;
}
return len;
}
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(head == NULL) return head;
int len = getLen(head);
n = len - n + 1;
int cur_node_id = 0;
ListNode* head_keep;
head_keep = head;
if(n == 1){
head = head->next;
return head;
}
while(head_keep != NULL){
cur_node_id++;
if(cur_node_id + 1 == n){
head_keep->next = head_keep->next->next;
break;
}
head_keep = head_keep->next;
}
return head;
}
}; | 22.44186 | 56 | 0.448705 | Napolean28 |
be2e6b23a9304f8649854777c544bf9a789b482d | 63,382 | cpp | C++ | libpdgl/rift/OculusSDK/Samples/OculusWorldDemo/OculusWorldDemo.cpp | cr88192/bgbtech_engine | 03869a92fbf3197dd176d311f3b917f4f4e88d1a | [
"MIT"
] | 1 | 2019-07-02T22:53:52.000Z | 2019-07-02T22:53:52.000Z | libpdgl/rift/OculusSDK/Samples/OculusWorldDemo/OculusWorldDemo.cpp | cr88192/bgbtech_engine | 03869a92fbf3197dd176d311f3b917f4f4e88d1a | [
"MIT"
] | 5 | 2015-11-17T05:45:50.000Z | 2015-11-26T18:36:51.000Z | libpdgl/rift/OculusSDK/Samples/OculusWorldDemo/OculusWorldDemo.cpp | cr88192/bgbtech_engine | 03869a92fbf3197dd176d311f3b917f4f4e88d1a | [
"MIT"
] | null | null | null | /************************************************************************************
Filename : OculusWorldDemo.cpp
Content : First-person view test application for Oculus Rift
Created : October 4, 2012
Authors : Michael Antonov, Andrew Reisse, Steve LaValle
Peter Hoff, Dan Goodman, Bryan Croteau
Copyright : Copyright 2012 Oculus VR, Inc. All Rights reserved.
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 "OVR.h"
#include "../CommonSrc/Platform/Platform_Default.h"
#include "../CommonSrc/Render/Render_Device.h"
#include "../CommonSrc/Render/Render_XmlSceneLoader.h"
#include "../CommonSrc/Render/Render_FontEmbed_DejaVu48.h"
#include "../CommonSrc/Platform/Gamepad.h"
#include <Kernel/OVR_SysFile.h>
#include <Kernel/OVR_Log.h>
#include <Kernel/OVR_Timer.h>
#include "Player.h"
// Filename to be loaded by default, searching specified paths.
#define WORLDDEMO_ASSET_FILE "Tuscany.xml"
#define WORLDDEMO_ASSET_PATH1 "Assets/Tuscany/"
#define WORLDDEMO_ASSET_PATH2 "../Assets/Tuscany/"
// This path allows the shortcut to work.
#define WORLDDEMO_ASSET_PATH3 "Samples/OculusWorldDemo/Assets/Tuscany/"
using namespace OVR;
using namespace OVR::Platform;
using namespace OVR::Render;
//-------------------------------------------------------------------------------------
// ***** OculusWorldDemo Description
// This app renders a simple flat-shaded room allowing the user to move along the
// floor and look around with an HMD, mouse and keyboard. The following keys work:
//
// 'W', 'S', 'A', 'D' and Arrow Keys - Move forward, back; strafe left/right.
// F1 - No stereo, no distortion.
// F2 - Stereo, no distortion.
// F3 - Stereo and distortion.
// F4 - Toggle MSAA.
// F9 - Cycle through fullscreen and windowed modes. Necessary for previewing content with Rift.
//
// Important Oculus-specific logic can be found at following locations:
//
// OculusWorldDemoApp::OnStartup - This function will initialize OVR::DeviceManager and HMD,
// creating SensorDevice and attaching it to SensorFusion.
// This needs to be done before obtaining sensor data.
//
// OculusWorldDemoApp::OnIdle - Here we poll SensorFusion for orientation, apply it
// to the scene and handle movement.
// Stereo rendering is also done here, by delegating to
// to Render function for each eye.
//
//-------------------------------------------------------------------------------------
// ***** OculusWorldDemo Application class
// An instance of this class is created on application startup (main/WinMain).
// It then works as follows:
// - Graphics and HMD setup is done OculusWorldDemoApp::OnStartup(). This function
// also creates the room model from Slab declarations.
// - Per-frame processing is done in OnIdle(). This function processes
// sensor and movement input and then renders the frame.
// - Additional input processing is done in OnMouse, OnKey.
class OculusWorldDemoApp : public Application, public MessageHandler
{
public:
OculusWorldDemoApp();
~OculusWorldDemoApp();
virtual int OnStartup(int argc, const char** argv);
virtual void OnIdle();
virtual void OnMouseMove(int x, int y, int modifiers);
virtual void OnKey(OVR::KeyCode key, int chr, bool down, int modifiers);
virtual void OnResize(int width, int height);
virtual void OnMessage(const Message& msg);
void Render(const StereoEyeParams& stereo);
// Sets temporarily displayed message for adjustments
void SetAdjustMessage(const char* format, ...);
// Overrides current timeout, in seconds (not the future default value);
// intended to be called right after SetAdjustMessage.
void SetAdjustMessageTimeout(float timeout);
// Stereo setting adjustment functions.
// Called with deltaTime when relevant key is held.
void AdjustFov(float dt);
void AdjustAspect(float dt);
void AdjustIPD(float dt);
void AdjustEyeHeight(float dt);
void AdjustMotionPrediction(float dt);
void AdjustDistortion(float dt, int kIndex, const char* label);
void AdjustDistortionK0(float dt) { AdjustDistortion(dt, 0, "K0"); }
void AdjustDistortionK1(float dt) { AdjustDistortion(dt, 1, "K1"); }
void AdjustDistortionK2(float dt) { AdjustDistortion(dt, 2, "K2"); }
void AdjustDistortionK3(float dt) { AdjustDistortion(dt, 3, "K3"); }
// Adds room model to scene.
void PopulateScene(const char* fileName);
void PopulatePreloadScene();
void ClearScene();
// Magnetometer calibration procedure
void UpdateManualMagCalibration();
protected:
RenderDevice* pRender;
RendererParams RenderParams;
int Width, Height;
int Screen;
int FirstScreenInCycle;
// Magnetometer calibration and yaw correction
Util::MagCalibration MagCal;
bool MagAwaitingForwardLook;
// *** Oculus HMD Variables
Ptr<DeviceManager> pManager;
Ptr<SensorDevice> pSensor;
Ptr<HMDDevice> pHMD;
Ptr<Profile> pUserProfile;
SensorFusion SFusion;
HMDInfo TheHMDInfo;
Ptr<LatencyTestDevice> pLatencyTester;
Util::LatencyTest LatencyUtil;
double LastUpdate;
int FPS;
int FrameCounter;
double NextFPSUpdate;
Array<Ptr<CollisionModel> > CollisionModels;
Array<Ptr<CollisionModel> > GroundCollisionModels;
// Loading process displays screenshot in first frame
// and then proceeds to load until finished.
enum LoadingStateType
{
LoadingState_Frame0,
LoadingState_DoLoad,
LoadingState_Finished
};
// Player
Player ThePlayer;
Matrix4f View;
Scene MainScene;
Scene LoadingScene;
Scene GridScene;
Scene YawMarkGreenScene;
Scene YawMarkRedScene;
Scene YawLinesScene;
LoadingStateType LoadingState;
Ptr<ShaderFill> LitSolid, LitTextures[4];
// Stereo view parameters.
StereoConfig SConfig;
PostProcessType PostProcess;
// LOD
String MainFilePath;
Array<String> LODFilePaths;
int ConsecutiveLowFPSFrames;
int CurrentLODFileIndex;
float DistortionK0;
float DistortionK1;
float DistortionK2;
float DistortionK3;
String AdjustMessage;
double AdjustMessageTimeout;
// Saved distortion state.
float SavedK0, SavedK1, SavedK2, SavedK3;
float SavedESD, SavedAspect, SavedEyeDistance;
// Allows toggling color around distortion.
Color DistortionClearColor;
// Stereo settings adjustment state.
typedef void (OculusWorldDemoApp::*AdjustFuncType)(float);
bool ShiftDown;
AdjustFuncType pAdjustFunc;
float AdjustDirection;
enum SceneRenderMode
{
Scene_World,
Scene_Grid,
Scene_Both,
Scene_YawView
};
SceneRenderMode SceneMode;
enum TextScreen
{
Text_None,
Text_Orientation,
Text_Config,
Text_Help,
Text_Count
};
TextScreen TextScreen;
struct DeviceStatusNotificationDesc
{
DeviceHandle Handle;
MessageType Action;
DeviceStatusNotificationDesc():Action(Message_None) {}
DeviceStatusNotificationDesc(MessageType mt, const DeviceHandle& dev)
: Handle(dev), Action(mt) {}
};
Array<DeviceStatusNotificationDesc> DeviceStatusNotificationsQueue;
Model* CreateModel(Vector3f pos, struct SlabModel* sm);
Model* CreateBoundingModel(CollisionModel &cm);
void PopulateLODFileNames();
void DropLOD();
void RaiseLOD();
void CycleDisplay();
void GamepadStateChanged(const GamepadState& pad);
// Variable used by UpdateManualCalibration
Anglef FirstMagYaw;
int ManualMagCalStage;
int ManualMagFailures;
};
//-------------------------------------------------------------------------------------
OculusWorldDemoApp::OculusWorldDemoApp()
: pRender(0),
LastUpdate(0),
LoadingState(LoadingState_Frame0),
// Initial location
SConfig(),
PostProcess(PostProcess_Distortion),
DistortionClearColor(0, 0, 0),
ShiftDown(false),
pAdjustFunc(0),
AdjustDirection(1.0f),
SceneMode(Scene_World),
TextScreen(Text_None)
{
Width = 1280;
Height = 800;
Screen = 0;
FirstScreenInCycle = 0;
FPS = 0;
FrameCounter = 0;
NextFPSUpdate = 0;
ConsecutiveLowFPSFrames = 0;
CurrentLODFileIndex = 0;
AdjustMessageTimeout = 0;
}
OculusWorldDemoApp::~OculusWorldDemoApp()
{
RemoveHandlerFromDevices();
if(DejaVu.fill)
{
DejaVu.fill->Release();
}
pLatencyTester.Clear();
pSensor.Clear();
pHMD.Clear();
CollisionModels.ClearAndRelease();
GroundCollisionModels.ClearAndRelease();
}
int OculusWorldDemoApp::OnStartup(int argc, const char** argv)
{
// *** Oculus HMD & Sensor Initialization
// Create DeviceManager and first available HMDDevice from it.
// Sensor object is created from the HMD, to ensure that it is on the
// correct device.
pManager = *DeviceManager::Create();
// We'll handle it's messages in this case.
pManager->SetMessageHandler(this);
pHMD = *pManager->EnumerateDevices<HMDDevice>().CreateDevice();
if (pHMD)
{
pSensor = *pHMD->GetSensor();
// This will initialize HMDInfo with information about configured IPD,
// screen size and other variables needed for correct projection.
// We pass HMD DisplayDeviceName into the renderer to select the
// correct monitor in full-screen mode.
if(pHMD->GetDeviceInfo(&TheHMDInfo))
{
//RenderParams.MonitorName = hmd.DisplayDeviceName;
SConfig.SetHMDInfo(TheHMDInfo);
}
// Retrieve relevant profile settings.
pUserProfile = pHMD->GetProfile();
if (pUserProfile)
{
ThePlayer.EyeHeight = pUserProfile->GetEyeHeight();
ThePlayer.EyePos.y = ThePlayer.EyeHeight;
}
}
else
{
// If we didn't detect an HMD, try to create the sensor directly.
// This is useful for debugging sensor interaction; it is not needed in
// a shipping app.
pSensor = *pManager->EnumerateDevices<SensorDevice>().CreateDevice();
}
// Create the Latency Tester device and assign it to the LatencyTesterUtil object.
pLatencyTester = *pManager->EnumerateDevices<LatencyTestDevice>().CreateDevice();
if (pLatencyTester)
{
LatencyUtil.SetDevice(pLatencyTester);
}
// Make the user aware which devices are present.
if(pHMD == NULL && pSensor == NULL)
{
SetAdjustMessage("---------------------------------\nNO HMD DETECTED\nNO SENSOR DETECTED\n---------------------------------");
}
else if(pHMD == NULL)
{
SetAdjustMessage("----------------------------\nNO HMD DETECTED\n----------------------------");
}
else if(pSensor == NULL)
{
SetAdjustMessage("---------------------------------\nNO SENSOR DETECTED\n---------------------------------");
}
else
{
SetAdjustMessage("--------------------------------------------\n"
"Press F9 for Full-Screen on Rift\n"
"--------------------------------------------");
}
// First message should be extra-long.
SetAdjustMessageTimeout(10.0f);
if(TheHMDInfo.HResolution > 0)
{
Width = TheHMDInfo.HResolution;
Height = TheHMDInfo.VResolution;
}
if(!pPlatform->SetupWindow(Width, Height))
{
return 1;
}
String Title = "Oculus World Demo";
if(TheHMDInfo.ProductName[0])
{
Title += " : ";
Title += TheHMDInfo.ProductName;
}
pPlatform->SetWindowTitle(Title);
// Report relative mouse motion in OnMouseMove
pPlatform->SetMouseMode(Mouse_Relative);
if(pSensor)
{
// We need to attach sensor to SensorFusion object for it to receive
// body frame messages and update orientation. SFusion.GetOrientation()
// is used in OnIdle() to orient the view.
SFusion.AttachToSensor(pSensor);
SFusion.SetDelegateMessageHandler(this);
SFusion.SetPredictionEnabled(true);
}
// *** Initialize Rendering
const char* graphics = "d3d11";
// Select renderer based on command line arguments.
for(int i = 1; i < argc; i++)
{
if(!strcmp(argv[i], "-r") && i < argc - 1)
{
graphics = argv[i + 1];
}
else if(!strcmp(argv[i], "-fs"))
{
RenderParams.Fullscreen = true;
}
}
// Enable multi-sampling by default.
RenderParams.Multisample = 4;
pRender = pPlatform->SetupGraphics(OVR_DEFAULT_RENDER_DEVICE_SET,
graphics, RenderParams);
// *** Configure Stereo settings.
SConfig.SetFullViewport(Viewport(0, 0, Width, Height));
SConfig.SetStereoMode(Stereo_LeftRight_Multipass);
// Configure proper Distortion Fit.
// For 7" screen, fit to touch left side of the view, leaving a bit of
// invisible screen on the top (saves on rendering cost).
// For smaller screens (5.5"), fit to the top.
if (TheHMDInfo.HScreenSize > 0.0f)
{
if (TheHMDInfo.HScreenSize > 0.140f) // 7"
SConfig.SetDistortionFitPointVP(-1.0f, 0.0f);
else
SConfig.SetDistortionFitPointVP(0.0f, 1.0f);
}
pRender->SetSceneRenderScale(SConfig.GetDistortionScale());
//pRender->SetSceneRenderScale(1.0f);
SConfig.Set2DAreaFov(DegreeToRad(85.0f));
// *** Identify Scene File & Prepare for Loading
// This creates lights and models.
if (argc == 2)
{
MainFilePath = argv[1];
PopulateLODFileNames();
}
else
{
fprintf(stderr, "Usage: OculusWorldDemo [input XML]\n");
MainFilePath = WORLDDEMO_ASSET_FILE;
}
// Try to modify path for correctness in case specified file is not found.
if (!SysFile(MainFilePath).IsValid())
{
String prefixPath1(pPlatform->GetContentDirectory() + "/" + WORLDDEMO_ASSET_PATH1),
prefixPath2(WORLDDEMO_ASSET_PATH2),
prefixPath3(WORLDDEMO_ASSET_PATH3);
if (SysFile(prefixPath1 + MainFilePath).IsValid())
MainFilePath = prefixPath1 + MainFilePath;
else if (SysFile(prefixPath2 + MainFilePath).IsValid())
MainFilePath = prefixPath2 + MainFilePath;
else if (SysFile(prefixPath3 + MainFilePath).IsValid())
MainFilePath = prefixPath3 + MainFilePath;
}
PopulatePreloadScene();
LastUpdate = pPlatform->GetAppTime();
//pPlatform->PlayMusicFile(L"Loop.wav");
return 0;
}
void OculusWorldDemoApp::OnMessage(const Message& msg)
{
if (msg.Type == Message_DeviceAdded || msg.Type == Message_DeviceRemoved)
{
if (msg.pDevice == pManager)
{
const MessageDeviceStatus& statusMsg =
static_cast<const MessageDeviceStatus&>(msg);
{ // limit the scope of the lock
Lock::Locker lock(pManager->GetHandlerLock());
DeviceStatusNotificationsQueue.PushBack(
DeviceStatusNotificationDesc(statusMsg.Type, statusMsg.Handle));
}
switch (statusMsg.Type)
{
case OVR::Message_DeviceAdded:
LogText("DeviceManager reported device added.\n");
break;
case OVR::Message_DeviceRemoved:
LogText("DeviceManager reported device removed.\n");
break;
default: OVR_ASSERT(0); // unexpected type
}
}
}
}
void OculusWorldDemoApp::OnResize(int width, int height)
{
Width = width;
Height = height;
SConfig.SetFullViewport(Viewport(0, 0, Width, Height));
}
void OculusWorldDemoApp::OnMouseMove(int x, int y, int modifiers)
{
if(modifiers & Mod_MouseRelative)
{
// Get Delta
int dx = x, dy = y;
const float maxPitch = ((3.1415f / 2) * 0.98f);
// Apply to rotation. Subtract for right body frame rotation,
// since yaw rotation is positive CCW when looking down on XZ plane.
ThePlayer.EyeYaw -= (Sensitivity * dx) / 360.0f;
if(!pSensor)
{
ThePlayer.EyePitch -= (Sensitivity * dy) / 360.0f;
if(ThePlayer.EyePitch > maxPitch)
{
ThePlayer.EyePitch = maxPitch;
}
if(ThePlayer.EyePitch < -maxPitch)
{
ThePlayer.EyePitch = -maxPitch;
}
}
}
}
void OculusWorldDemoApp::OnKey(OVR::KeyCode key, int chr, bool down, int modifiers)
{
OVR_UNUSED(chr);
switch(key)
{
case Key_Q:
if (down && (modifiers & Mod_Control))
{
pPlatform->Exit(0);
}
break;
// Handle player movement keys.
// We just update movement state here, while the actual translation is done in OnIdle()
// based on time.
case Key_W:
ThePlayer.MoveForward = down ? (ThePlayer.MoveForward | 1) : (ThePlayer.MoveForward & ~1);
break;
case Key_S:
ThePlayer.MoveBack = down ? (ThePlayer.MoveBack | 1) : (ThePlayer.MoveBack & ~1);
break;
case Key_A:
ThePlayer.MoveLeft = down ? (ThePlayer.MoveLeft | 1) : (ThePlayer.MoveLeft & ~1);
break;
case Key_D:
ThePlayer.MoveRight = down ? (ThePlayer.MoveRight | 1) : (ThePlayer.MoveRight & ~1);
break;
case Key_Up:
ThePlayer.MoveForward = down ? (ThePlayer.MoveForward | 2) : (ThePlayer.MoveForward & ~2);
break;
case Key_Down:
ThePlayer.MoveBack = down ? (ThePlayer.MoveBack | 2) : (ThePlayer.MoveBack & ~2);
break;
case Key_Left:
ThePlayer.MoveLeft = down ? (ThePlayer.MoveLeft | 2) : (ThePlayer.MoveLeft & ~2);
break;
case Key_Right:
ThePlayer.MoveRight = down ? (ThePlayer.MoveRight | 2) : (ThePlayer.MoveRight & ~2);
break;
case Key_Minus:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustEyeHeight : 0;
AdjustDirection = -1;
break;
case Key_Equal:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustEyeHeight : 0;
AdjustDirection = 1;
break;
case Key_B:
if (down)
{
if(SConfig.GetDistortionScale() == 1.0f)
{
if(SConfig.GetHMDInfo().HScreenSize > 0.140f) // 7"
{
SConfig.SetDistortionFitPointVP(-1.0f, 0.0f);
}
else
{
SConfig.SetDistortionFitPointVP(0.0f, 1.0f);
}
}
else
{
// No fitting; scale == 1.0.
SConfig.SetDistortionFitPointVP(0, 0);
}
}
break;
// Support toggling background color for distortion so that we can see
// the effect on the periphery.
case Key_V:
if (down)
{
if(DistortionClearColor.B == 0)
{
DistortionClearColor = Color(0, 128, 255);
}
else
{
DistortionClearColor = Color(0, 0, 0);
}
pRender->SetDistortionClearColor(DistortionClearColor);
}
break;
case Key_F1:
SConfig.SetStereoMode(Stereo_None);
PostProcess = PostProcess_None;
SetAdjustMessage("StereoMode: None");
break;
case Key_F2:
SConfig.SetStereoMode(Stereo_LeftRight_Multipass);
PostProcess = PostProcess_None;
SetAdjustMessage("StereoMode: Stereo + No Distortion");
break;
case Key_F3:
SConfig.SetStereoMode(Stereo_LeftRight_Multipass);
PostProcess = PostProcess_Distortion;
SetAdjustMessage("StereoMode: Stereo + Distortion");
break;
case Key_R:
SFusion.Reset();
if (MagCal.IsAutoCalibrating() || MagCal.IsManuallyCalibrating())
MagCal.AbortCalibration();
SetAdjustMessage("Sensor Fusion Reset");
break;
case Key_Space:
if (!down)
{
TextScreen = (enum TextScreen)((TextScreen + 1) % Text_Count);
}
break;
case Key_F4:
if (!down)
{
RenderParams = pRender->GetParams();
RenderParams.Multisample = RenderParams.Multisample > 1 ? 1 : 4;
pRender->SetParams(RenderParams);
if(RenderParams.Multisample > 1)
{
SetAdjustMessage("Multisampling On");
}
else
{
SetAdjustMessage("Multisampling Off");
}
}
break;
case Key_F9:
#ifndef OVR_OS_LINUX // On Linux F9 does the same as F11.
if (!down)
{
CycleDisplay();
}
break;
#endif
#ifdef OVR_OS_MAC
case Key_F10: // F11 is reserved on Mac
#else
case Key_F11:
#endif
if (!down)
{
RenderParams = pRender->GetParams();
RenderParams.Display = DisplayId(SConfig.GetHMDInfo().DisplayDeviceName,SConfig.GetHMDInfo().DisplayId);
pRender->SetParams(RenderParams);
pPlatform->SetMouseMode(Mouse_Normal);
pPlatform->SetFullscreen(RenderParams, pRender->IsFullscreen() ? Display_Window : Display_FakeFullscreen);
pPlatform->SetMouseMode(Mouse_Relative); // Avoid mode world rotation jump.
// If using an HMD, enable post-process (for distortion) and stereo.
if(RenderParams.IsDisplaySet() && pRender->IsFullscreen())
{
SConfig.SetStereoMode(Stereo_LeftRight_Multipass);
PostProcess = PostProcess_Distortion;
}
}
break;
case Key_Escape:
if(!down)
{
if (MagCal.IsAutoCalibrating() || MagCal.IsManuallyCalibrating())
{
MagCal.AbortCalibration();
SetAdjustMessage("Aborting Magnetometer Calibration");
}
else
{
// switch to primary screen windowed mode
pPlatform->SetFullscreen(RenderParams, Display_Window);
RenderParams.Display = pPlatform->GetDisplay(0);
pRender->SetParams(RenderParams);
Screen = 0;
}
}
break;
// Stereo adjustments.
case Key_BracketLeft:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustFov : 0;
AdjustDirection = 1;
break;
case Key_BracketRight:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustFov : 0;
AdjustDirection = -1;
break;
case Key_Insert:
case Key_Num0:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustIPD : 0;
AdjustDirection = 1;
break;
case Key_Delete:
case Key_Num9:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustIPD : 0;
AdjustDirection = -1;
break;
case Key_PageUp:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustAspect : 0;
AdjustDirection = 1;
break;
case Key_PageDown:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustAspect : 0;
AdjustDirection = -1;
break;
// Distortion correction adjustments
case Key_H:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK0 : NULL;
AdjustDirection = -1;
break;
case Key_Y:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK0 : NULL;
AdjustDirection = 1;
break;
case Key_J:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK1 : NULL;
AdjustDirection = -1;
break;
case Key_U:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK1 : NULL;
AdjustDirection = 1;
break;
case Key_K:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK2 : NULL;
AdjustDirection = -1;
break;
case Key_I:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK2 : NULL;
AdjustDirection = 1;
break;
case Key_L:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK3 : NULL;
AdjustDirection = -1;
break;
case Key_O:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK3 : NULL;
AdjustDirection = 1;
break;
case Key_Tab:
if (down)
{
float t0 = SConfig.GetDistortionK(0),
t1 = SConfig.GetDistortionK(1),
t2 = SConfig.GetDistortionK(2),
t3 = SConfig.GetDistortionK(3);
float tESD = SConfig.GetEyeToScreenDistance(),
taspect = SConfig.GetAspectMultiplier(),
tipd = SConfig.GetIPD();
if(SavedK0 > 0.0f)
{
SConfig.SetDistortionK(0, SavedK0);
SConfig.SetDistortionK(1, SavedK1);
SConfig.SetDistortionK(2, SavedK2);
SConfig.SetDistortionK(3, SavedK3);
SConfig.SetEyeToScreenDistance(SavedESD);
SConfig.SetAspectMultiplier(SavedAspect);
SConfig.SetIPD(SavedEyeDistance);
if ( ShiftDown )
{
// Swap saved and current values. Good for doing direct comparisons.
SetAdjustMessage("Swapped current and saved. New settings:\n"
"ESD:\t120 %.3f\t350 Eye:\t490 %.3f\n"
"K0: \t120 %.4f\t350 K2: \t490 %.4f\n"
"K1: \t120 %.4f\t350 K3: \t490 %.4f\n",
SavedESD, SavedEyeDistance,
SavedK0, SavedK2,
SavedK1, SavedK3);
SavedK0 = t0;
SavedK1 = t1;
SavedK2 = t2;
SavedK3 = t3;
SavedESD = tESD;
SavedAspect = taspect;
SavedEyeDistance = tipd;
}
else
{
SetAdjustMessage("Restored:\n"
"ESD:\t120 %.3f\t350 Eye:\t490 %.3f\n"
"K0: \t120 %.4f\t350 K2: \t490 %.4f\n"
"K1: \t120 %.4f\t350 K3: \t490 %.4f\n",
SavedESD, SavedEyeDistance,
SavedK0, SavedK2,
SavedK1, SavedK3);
}
}
else
{
SetAdjustMessage("Setting Saved");
SavedK0 = t0;
SavedK1 = t1;
SavedK2 = t2;
SavedK3 = t3;
SavedESD = tESD;
SavedAspect = taspect;
SavedEyeDistance = tipd;
}
}
break;
case Key_G:
if (down)
{
if(SceneMode == Scene_World)
{
SceneMode = Scene_Grid;
SetAdjustMessage("Grid Only");
}
else if(SceneMode == Scene_Grid)
{
SceneMode = Scene_Both;
SetAdjustMessage("Grid Overlay");
}
else if(SceneMode == Scene_Both)
{
SceneMode = Scene_World;
SetAdjustMessage("Grid Off");
}
}
break;
// Holding down Shift key accelerates adjustment velocity.
case Key_Shift:
ShiftDown = down;
break;
// Reset the camera position in case we get stuck
case Key_T:
ThePlayer.EyePos = Vector3f(10.0f, 1.6f, 10.0f);
break;
case Key_F5:
if (!down)
{
UPInt numNodes = MainScene.Models.GetSize();
for(UPInt i = 0; i < numNodes; i++)
{
Ptr<OVR::Render::Model> nodePtr = MainScene.Models[i];
Render::Model* pNode = nodePtr.GetPtr();
if(pNode->IsCollisionModel)
{
pNode->Visible = !pNode->Visible;
}
}
}
break;
case Key_N:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustMotionPrediction : NULL;
AdjustDirection = -1;
break;
case Key_M:
pAdjustFunc = down ? &OculusWorldDemoApp::AdjustMotionPrediction : NULL;
AdjustDirection = 1;
break;
/*
case Key_N:
RaiseLOD();
break;
case Key_M:
DropLOD();
break;
*/
// Start calibrating magnetometer
case Key_Z:
if (down)
{
ManualMagCalStage = 0;
if (MagCal.IsManuallyCalibrating())
MagAwaitingForwardLook = false;
else
{
MagCal.BeginManualCalibration(SFusion);
MagAwaitingForwardLook = true;
}
}
break;
case Key_X:
if (down)
{
MagCal.BeginAutoCalibration(SFusion);
SetAdjustMessage("Starting Auto Mag Calibration");
}
break;
// Show view of yaw angles (for mag calibration/analysis)
case Key_F6:
if (down)
{
if (SceneMode != Scene_YawView)
{
SceneMode = Scene_YawView;
SetAdjustMessage("Magnetometer Yaw Angle Marks");
}
else
{
SceneMode = Scene_World;
SetAdjustMessage("Magnetometer Marks Off");
}
}
break;
case Key_C:
if (down)
{
// Toggle chromatic aberration correction on/off.
RenderDevice::PostProcessShader shader = pRender->GetPostProcessShader();
if (shader == RenderDevice::PostProcessShader_Distortion)
{
pRender->SetPostProcessShader(RenderDevice::PostProcessShader_DistortionAndChromAb);
SetAdjustMessage("Chromatic Aberration Correction On");
}
else if (shader == RenderDevice::PostProcessShader_DistortionAndChromAb)
{
pRender->SetPostProcessShader(RenderDevice::PostProcessShader_Distortion);
SetAdjustMessage("Chromatic Aberration Correction Off");
}
else
OVR_ASSERT(false);
}
break;
case Key_P:
if (down)
{
// Toggle motion prediction.
if (SFusion.IsPredictionEnabled())
{
SFusion.SetPredictionEnabled(false);
SetAdjustMessage("Motion Prediction Off");
}
else
{
SFusion.SetPredictionEnabled(true);
SetAdjustMessage("Motion Prediction On");
}
}
break;
default:
break;
}
}
void OculusWorldDemoApp::OnIdle()
{
double curtime = pPlatform->GetAppTime();
float dt = float(curtime - LastUpdate);
LastUpdate = curtime;
// Update gamepad.
GamepadState gamepadState;
if (GetPlatformCore()->GetGamepadManager()->GetGamepadState(0, &gamepadState))
{
GamepadStateChanged(gamepadState);
}
if (LoadingState == LoadingState_DoLoad)
{
PopulateScene(MainFilePath.ToCStr());
LoadingState = LoadingState_Finished;
return;
}
// Check if any new devices were connected.
{
bool queueIsEmpty = false;
while (!queueIsEmpty)
{
DeviceStatusNotificationDesc desc;
{
Lock::Locker lock(pManager->GetHandlerLock());
if (DeviceStatusNotificationsQueue.GetSize() == 0)
break;
desc = DeviceStatusNotificationsQueue.Front();
// We can't call Clear under the lock since this may introduce a dead lock:
// this thread is locked by HandlerLock and the Clear might cause
// call of Device->Release, which will use Manager->DeviceLock. The bkg
// thread is most likely locked by opposite way:
// Manager->DeviceLock ==> HandlerLock, therefore - a dead lock.
// So, just grab the first element, save a copy of it and remove
// the element (Device->Release won't be called since we made a copy).
DeviceStatusNotificationsQueue.RemoveAt(0);
queueIsEmpty = (DeviceStatusNotificationsQueue.GetSize() == 0);
}
bool wasAlreadyCreated = desc.Handle.IsCreated();
if (desc.Action == Message_DeviceAdded)
{
switch(desc.Handle.GetType())
{
case Device_Sensor:
if (desc.Handle.IsAvailable() && !desc.Handle.IsCreated())
{
if (!pSensor)
{
pSensor = *desc.Handle.CreateDeviceTyped<SensorDevice>();
SFusion.AttachToSensor(pSensor);
SetAdjustMessage("---------------------------\n"
"SENSOR connected\n"
"---------------------------");
}
else if (!wasAlreadyCreated)
{
LogText("A new SENSOR has been detected, but it is not currently used.");
}
}
break;
case Device_LatencyTester:
if (desc.Handle.IsAvailable() && !desc.Handle.IsCreated())
{
if (!pLatencyTester)
{
pLatencyTester = *desc.Handle.CreateDeviceTyped<LatencyTestDevice>();
LatencyUtil.SetDevice(pLatencyTester);
if (!wasAlreadyCreated)
SetAdjustMessage("----------------------------------------\n"
"LATENCY TESTER connected\n"
"----------------------------------------");
}
}
break;
case Device_HMD:
{
OVR::HMDInfo info;
desc.Handle.GetDeviceInfo(&info);
// if strlen(info.DisplayDeviceName) == 0 then
// this HMD is 'fake' (created using sensor).
if (strlen(info.DisplayDeviceName) > 0 && (!pHMD || !info.IsSameDisplay(TheHMDInfo)))
{
SetAdjustMessage("------------------------\n"
"HMD connected\n"
"------------------------");
if (!pHMD || !desc.Handle.IsDevice(pHMD))
pHMD = *desc.Handle.CreateDeviceTyped<HMDDevice>();
// update stereo config with new HMDInfo
if (pHMD && pHMD->GetDeviceInfo(&TheHMDInfo))
{
//RenderParams.MonitorName = hmd.DisplayDeviceName;
SConfig.SetHMDInfo(TheHMDInfo);
}
LogText("HMD device added.\n");
}
break;
}
default:;
}
}
else if (desc.Action == Message_DeviceRemoved)
{
if (desc.Handle.IsDevice(pSensor))
{
LogText("Sensor reported device removed.\n");
SFusion.AttachToSensor(NULL);
pSensor.Clear();
SetAdjustMessage("-------------------------------\n"
"SENSOR disconnected.\n"
"-------------------------------");
}
else if (desc.Handle.IsDevice(pLatencyTester))
{
LogText("Latency Tester reported device removed.\n");
LatencyUtil.SetDevice(NULL);
pLatencyTester.Clear();
SetAdjustMessage("---------------------------------------------\n"
"LATENCY SENSOR disconnected.\n"
"---------------------------------------------");
}
else if (desc.Handle.IsDevice(pHMD))
{
if (pHMD && !pHMD->IsDisconnected())
{
SetAdjustMessage("---------------------------\n"
"HMD disconnected\n"
"---------------------------");
// Disconnect HMD. pSensor is used to restore 'fake' HMD device
// (can be NULL).
pHMD = pHMD->Disconnect(pSensor);
// This will initialize TheHMDInfo with information about configured IPD,
// screen size and other variables needed for correct projection.
// We pass HMD DisplayDeviceName into the renderer to select the
// correct monitor in full-screen mode.
if (pHMD && pHMD->GetDeviceInfo(&TheHMDInfo))
{
//RenderParams.MonitorName = hmd.DisplayDeviceName;
SConfig.SetHMDInfo(TheHMDInfo);
}
LogText("HMD device removed.\n");
}
}
}
else
OVR_ASSERT(0); // unexpected action
}
}
// If one of Stereo setting adjustment keys is pressed, adjust related state.
if (pAdjustFunc)
{
(this->*pAdjustFunc)(dt * AdjustDirection * (ShiftDown ? 5.0f : 1.0f));
}
// Process latency tester results.
const char* results = LatencyUtil.GetResultsString();
if (results != NULL)
{
LogText("LATENCY TESTER: %s\n", results);
}
// Have to place this as close as possible to where the HMD orientation is read.
LatencyUtil.ProcessInputs();
// Magnetometer calibration procedure
if (MagCal.IsManuallyCalibrating())
UpdateManualMagCalibration();
if (MagCal.IsAutoCalibrating())
{
MagCal.UpdateAutoCalibration(SFusion);
int n = MagCal.NumberOfSamples();
if (n == 1)
SetAdjustMessage(" Magnetometer Calibration Has 1 Sample \n %d Remaining - Please Keep Looking Around ",4-n);
else if (n < 4)
SetAdjustMessage(" Magnetometer Calibration Has %d Samples \n %d Remaining - Please Keep Looking Around ",n,4-n);
if (MagCal.IsCalibrated())
{
SFusion.SetYawCorrectionEnabled(true);
Vector3f mc = MagCal.GetMagCenter();
SetAdjustMessage(" Magnetometer Calibration Complete \nCenter: %f %f %f",mc.x,mc.y,mc.z);
}
}
// Handle Sensor motion.
// We extract Yaw, Pitch, Roll instead of directly using the orientation
// to allow "additional" yaw manipulation with mouse/controller.
if(pSensor)
{
Quatf hmdOrient = SFusion.GetPredictedOrientation();
float yaw = 0.0f;
hmdOrient.GetEulerAngles<Axis_Y, Axis_X, Axis_Z>(&yaw, &ThePlayer.EyePitch, &ThePlayer.EyeRoll);
ThePlayer.EyeYaw += (yaw - ThePlayer.LastSensorYaw);
ThePlayer.LastSensorYaw = yaw;
// NOTE: We can get a matrix from orientation as follows:
// Matrix4f hmdMat(hmdOrient);
// Test logic - assign quaternion result directly to view:
// Quatf hmdOrient = SFusion.GetOrientation();
// View = Matrix4f(hmdOrient.Inverted()) * Matrix4f::Translation(-EyePos);
}
if(curtime >= NextFPSUpdate)
{
NextFPSUpdate = curtime + 1.0;
FPS = FrameCounter;
FrameCounter = 0;
}
FrameCounter++;
if(FPS < 40)
{
ConsecutiveLowFPSFrames++;
}
else
{
ConsecutiveLowFPSFrames = 0;
}
if(ConsecutiveLowFPSFrames > 200)
{
DropLOD();
ConsecutiveLowFPSFrames = 0;
}
ThePlayer.EyeYaw -= ThePlayer.GamepadRotate.x * dt;
ThePlayer.HandleCollision(dt, &CollisionModels, &GroundCollisionModels, ShiftDown);
if(!pSensor)
{
ThePlayer.EyePitch -= ThePlayer.GamepadRotate.y * dt;
const float maxPitch = ((3.1415f / 2) * 0.98f);
if(ThePlayer.EyePitch > maxPitch)
{
ThePlayer.EyePitch = maxPitch;
}
if(ThePlayer.EyePitch < -maxPitch)
{
ThePlayer.EyePitch = -maxPitch;
}
}
// Rotate and position View Camera, using YawPitchRoll in BodyFrame coordinates.
//
Matrix4f rollPitchYaw = Matrix4f::RotationY(ThePlayer.EyeYaw) * Matrix4f::RotationX(ThePlayer.EyePitch) *
Matrix4f::RotationZ(ThePlayer.EyeRoll);
Vector3f up = rollPitchYaw.Transform(UpVector);
Vector3f forward = rollPitchYaw.Transform(ForwardVector);
// Minimal head modeling; should be moved as an option to SensorFusion.
float headBaseToEyeHeight = 0.15f; // Vertical height of eye from base of head
float headBaseToEyeProtrusion = 0.09f; // Distance forward of eye from base of head
Vector3f eyeCenterInHeadFrame(0.0f, headBaseToEyeHeight, -headBaseToEyeProtrusion);
Vector3f shiftedEyePos = ThePlayer.EyePos + rollPitchYaw.Transform(eyeCenterInHeadFrame);
shiftedEyePos.y -= eyeCenterInHeadFrame.y; // Bring the head back down to original height
View = Matrix4f::LookAtRH(shiftedEyePos, shiftedEyePos + forward, up);
// Transformation without head modeling.
// View = Matrix4f::LookAtRH(EyePos, EyePos + forward, up);
// This is an alternative to LookAtRH:
// Here we transpose the rotation matrix to get its inverse.
// View = (Matrix4f::RotationY(EyeYaw) * Matrix4f::RotationX(EyePitch) *
// Matrix4f::RotationZ(EyeRoll)).Transposed() *
// Matrix4f::Translation(-EyePos);
switch(SConfig.GetStereoMode())
{
case Stereo_None:
Render(SConfig.GetEyeRenderParams(StereoEye_Center));
break;
case Stereo_LeftRight_Multipass:
//case Stereo_LeftDouble_Multipass:
Render(SConfig.GetEyeRenderParams(StereoEye_Left));
Render(SConfig.GetEyeRenderParams(StereoEye_Right));
break;
}
pRender->Present();
// Force GPU to flush the scene, resulting in the lowest possible latency.
pRender->ForceFlushGPU();
}
void OculusWorldDemoApp::UpdateManualMagCalibration()
{
float tyaw, pitch, roll;
Anglef yaw;
Quatf hmdOrient = SFusion.GetOrientation();
hmdOrient.GetEulerAngles<Axis_Y, Axis_X, Axis_Z>(&tyaw, &pitch, &roll);
Vector3f mag = SFusion.GetMagnetometer();
float dtr = Math<float>::DegreeToRadFactor;
yaw.Set(tyaw); // Using Angle class to handle angle wraparound arithmetic
const int timeout = 100;
switch(ManualMagCalStage)
{
case 0:
if (MagAwaitingForwardLook)
SetAdjustMessage("Magnetometer Calibration\n** Step 1: Please Look Forward **\n** and Press Z When Ready **");
else
if (fabs(pitch) < 10.0f*dtr)
{
MagCal.InsertIfAcceptable(hmdOrient, mag);
FirstMagYaw = yaw;
MagAwaitingForwardLook = false;
if (MagCal.NumberOfSamples() == 1)
{
ManualMagCalStage = 1;
ManualMagFailures = 0;
}
}
else
MagAwaitingForwardLook = true;
break;
case 1:
SetAdjustMessage("Magnetometer Calibration\n** Step 2: Please Look Up **");
yaw -= FirstMagYaw;
if ((pitch > 50.0f*dtr) && (yaw.Abs() < 20.0f*dtr))
{
MagCal.InsertIfAcceptable(hmdOrient, mag);
ManualMagFailures++;
if ((MagCal.NumberOfSamples() == 2)||(ManualMagFailures > timeout))
{
ManualMagCalStage = 2;
ManualMagFailures = 0;
}
}
break;
case 2:
SetAdjustMessage("Magnetometer Calibration\n** Step 3: Please Look Left **");
yaw -= FirstMagYaw;
if (yaw.Get() > 60.0f*dtr)
{
MagCal.InsertIfAcceptable(hmdOrient, mag);
ManualMagFailures++;
if ((MagCal.NumberOfSamples() == 3)||(ManualMagFailures > timeout))
{
ManualMagCalStage = 3;
ManualMagFailures = 0;
}
}
break;
case 3:
SetAdjustMessage("Magnetometer Calibration\n** Step 4: Please Look Right **");
yaw -= FirstMagYaw;
if (yaw.Get() < -60.0f*dtr)
{
MagCal.InsertIfAcceptable(hmdOrient, mag);
ManualMagFailures++;
if (MagCal.NumberOfSamples() == 4)
ManualMagCalStage = 6;
else
{
if (ManualMagFailures > timeout)
{
ManualMagCalStage = 4;
ManualMagFailures = 0;
}
}
}
break;
case 4:
SetAdjustMessage("Magnetometer Calibration\n** Step 5: Please Look Upper Right **");
yaw -= FirstMagYaw;
if ((yaw.Get() < -50.0f*dtr) && (pitch > 40.0f*dtr))
{
MagCal.InsertIfAcceptable(hmdOrient, mag);
if (MagCal.NumberOfSamples() == 4)
ManualMagCalStage = 6;
else
{
if (ManualMagFailures > timeout)
{
ManualMagCalStage = 5;
ManualMagFailures = 0;
}
else
ManualMagFailures++;
}
}
break;
case 5:
SetAdjustMessage("Calibration Failed\n** Try Again From Another Location **");
MagCal.AbortCalibration();
break;
case 6:
if (!MagCal.IsCalibrated())
{
MagCal.SetCalibration(SFusion);
SFusion.SetYawCorrectionEnabled(true);
Vector3f mc = MagCal.GetMagCenter();
SetAdjustMessage(" Magnetometer Calibration and Activation \nCenter: %f %f %f",
mc.x,mc.y,mc.z);
}
}
}
static const char* HelpText =
"F1 \t100 NoStereo \t420 Z \t520 Manual Mag Calib\n"
"F2 \t100 Stereo \t420 X \t520 Auto Mag Calib\n"
"F3 \t100 StereoHMD \t420 ; \t520 Mag Set Ref Point\n"
"F4 \t100 MSAA \t420 F6 \t520 Mag Info\n"
"F9 \t100 FullScreen \t420 R \t520 Reset SensorFusion\n"
"F11 \t100 Fast FullScreen \t500 - + \t660 Adj EyeHeight\n"
"C \t100 Chromatic Ab \t500 [ ] \t660 Adj FOV\n"
"P \t100 Motion Pred \t500 Shift \t660 Adj Faster\n"
"N/M \t180 Adj Motion Pred\n"
"( / ) \t180 Adj EyeDistance"
;
enum DrawTextCenterType
{
DrawText_NoCenter= 0,
DrawText_VCenter = 0x1,
DrawText_HCenter = 0x2,
DrawText_Center = DrawText_VCenter | DrawText_HCenter
};
static void DrawTextBox(RenderDevice* prender, float x, float y,
float textSize, const char* text,
DrawTextCenterType centerType = DrawText_NoCenter)
{
float ssize[2] = {0.0f, 0.0f};
prender->MeasureText(&DejaVu, text, textSize, ssize);
// Treat 0 a VCenter.
if (centerType & DrawText_HCenter)
{
x = -ssize[0]/2;
}
if (centerType & DrawText_VCenter)
{
y = -ssize[1]/2;
}
prender->FillRect(x-0.02f, y-0.02f, x+ssize[0]+0.02f, y+ssize[1]+0.02f, Color(40,40,100,210));
prender->RenderText(&DejaVu, text, x, y, textSize, Color(255,255,0,210));
}
void OculusWorldDemoApp::Render(const StereoEyeParams& stereo)
{
pRender->BeginScene(PostProcess);
// *** 3D - Configures Viewport/Projection and Render
pRender->ApplyStereoParams(stereo);
pRender->Clear();
pRender->SetDepthMode(true, true);
if (SceneMode != Scene_Grid)
{
MainScene.Render(pRender, stereo.ViewAdjust * View);
}
if (SceneMode == Scene_YawView)
{
Matrix4f calView = Matrix4f();
float viewYaw = -ThePlayer.LastSensorYaw + SFusion.GetMagRefYaw();
calView.M[0][0] = calView.M[2][2] = cos(viewYaw);
calView.M[0][2] = sin(viewYaw);
calView.M[2][0] = -sin(viewYaw);
//LogText("yaw: %f\n",SFusion.GetMagRefYaw());
if (SFusion.IsYawCorrectionInProgress())
YawMarkGreenScene.Render(pRender, stereo.ViewAdjust);
else
YawMarkRedScene.Render(pRender, stereo.ViewAdjust);
if (fabs(ThePlayer.EyePitch) < Math<float>::Pi * 0.33)
YawLinesScene.Render(pRender, stereo.ViewAdjust * calView);
}
// *** 2D Text & Grid - Configure Orthographic rendering.
// Render UI in 2D orthographic coordinate system that maps [-1,1] range
// to a readable FOV area centered at your eye and properly adjusted.
pRender->ApplyStereoParams2D(stereo);
pRender->SetDepthMode(false, false);
float unitPixel = SConfig.Get2DUnitPixel();
float textHeight= unitPixel * 22;
if ((SceneMode == Scene_Grid)||(SceneMode == Scene_Both))
{ // Draw grid two pixels thick.
GridScene.Render(pRender, Matrix4f());
GridScene.Render(pRender, Matrix4f::Translation(unitPixel,unitPixel,0));
}
// Display Loading screen-shot in frame 0.
if (LoadingState != LoadingState_Finished)
{
LoadingScene.Render(pRender, Matrix4f());
String loadMessage = String("Loading ") + MainFilePath;
DrawTextBox(pRender, 0.0f, 0.25f, textHeight, loadMessage.ToCStr(), DrawText_HCenter);
LoadingState = LoadingState_DoLoad;
}
if(!AdjustMessage.IsEmpty() && AdjustMessageTimeout > pPlatform->GetAppTime())
{
DrawTextBox(pRender,0.0f,0.4f, textHeight, AdjustMessage.ToCStr(), DrawText_HCenter);
}
switch(TextScreen)
{
case Text_Orientation:
{
char buf[256], gpustat[256];
OVR_sprintf(buf, sizeof(buf),
" Yaw:%4.0f Pitch:%4.0f Roll:%4.0f \n"
" FPS: %d Frame: %d \n Pos: %3.2f, %3.2f, %3.2f \n"
" EyeHeight: %3.2f",
RadToDegree(ThePlayer.EyeYaw), RadToDegree(ThePlayer.EyePitch), RadToDegree(ThePlayer.EyeRoll),
FPS, FrameCounter, ThePlayer.EyePos.x, ThePlayer.EyePos.y, ThePlayer.EyePos.z, ThePlayer.EyePos.y);
size_t texMemInMB = pRender->GetTotalTextureMemoryUsage() / 1058576;
if (texMemInMB)
{
OVR_sprintf(gpustat, sizeof(gpustat), "\n GPU Tex: %u MB", texMemInMB);
OVR_strcat(buf, sizeof(buf), gpustat);
}
DrawTextBox(pRender, 0.0f, -0.15f, textHeight, buf, DrawText_HCenter);
}
break;
case Text_Config:
{
char textBuff[2048];
OVR_sprintf(textBuff, sizeof(textBuff),
"Fov\t300 %9.4f\n"
"EyeDistance\t300 %9.4f\n"
"DistortionK0\t300 %9.4f\n"
"DistortionK1\t300 %9.4f\n"
"DistortionK2\t300 %9.4f\n"
"DistortionK3\t300 %9.4f\n"
"TexScale\t300 %9.4f",
SConfig.GetYFOVDegrees(),
SConfig.GetIPD(),
SConfig.GetDistortionK(0),
SConfig.GetDistortionK(1),
SConfig.GetDistortionK(2),
SConfig.GetDistortionK(3),
SConfig.GetDistortionScale());
DrawTextBox(pRender, 0.0f, 0.0f, textHeight, textBuff, DrawText_Center);
}
break;
case Text_Help:
DrawTextBox(pRender, 0.0f, -0.1f, textHeight, HelpText, DrawText_Center);
default:
break;
}
// Display colored quad if we're doing a latency test.
Color colorToDisplay;
if (LatencyUtil.DisplayScreenColor(colorToDisplay))
{
pRender->FillRect(-0.4f, -0.4f, 0.4f, 0.4f, colorToDisplay);
}
pRender->FinishScene();
}
// Sets temporarily displayed message for adjustments
void OculusWorldDemoApp::SetAdjustMessage(const char* format, ...)
{
Lock::Locker lock(pManager->GetHandlerLock());
char textBuff[2048];
va_list argList;
va_start(argList, format);
OVR_vsprintf(textBuff, sizeof(textBuff), format, argList);
va_end(argList);
// Message will time out in 4 seconds.
AdjustMessage = textBuff;
AdjustMessageTimeout = pPlatform->GetAppTime() + 4.0f;
}
void OculusWorldDemoApp::SetAdjustMessageTimeout(float timeout)
{
AdjustMessageTimeout = pPlatform->GetAppTime() + timeout;
}
// ***** View Control Adjustments
void OculusWorldDemoApp::AdjustFov(float dt)
{
float esd = SConfig.GetEyeToScreenDistance() + 0.01f * dt;
SConfig.SetEyeToScreenDistance(esd);
SetAdjustMessage("ESD:%6.3f FOV: %6.3f", esd, SConfig.GetYFOVDegrees());
}
void OculusWorldDemoApp::AdjustAspect(float dt)
{
float rawAspect = SConfig.GetAspect() / SConfig.GetAspectMultiplier();
float newAspect = SConfig.GetAspect() + 0.01f * dt;
SConfig.SetAspectMultiplier(newAspect / rawAspect);
SetAdjustMessage("Aspect: %6.3f", newAspect);
}
void OculusWorldDemoApp::AdjustDistortion(float dt, int kIndex, const char* label)
{
SConfig.SetDistortionK(kIndex, SConfig.GetDistortionK(kIndex) + 0.03f * dt);
SetAdjustMessage("%s: %6.4f", label, SConfig.GetDistortionK(kIndex));
}
void OculusWorldDemoApp::AdjustIPD(float dt)
{
SConfig.SetIPD(SConfig.GetIPD() + 0.025f * dt);
SetAdjustMessage("EyeDistance: %6.4f", SConfig.GetIPD());
}
void OculusWorldDemoApp::AdjustEyeHeight(float dt)
{
float dist = 0.5f * dt;
ThePlayer.EyeHeight += dist;
ThePlayer.EyePos.y += dist;
SetAdjustMessage("EyeHeight: %4.2f", ThePlayer.EyeHeight);
}
void OculusWorldDemoApp::AdjustMotionPrediction(float dt)
{
float motionPred = SFusion.GetPredictionDelta() + 0.01f * dt;
if (motionPred < 0.0f)
{
motionPred = 0.0f;
}
SFusion.SetPrediction(motionPred);
SetAdjustMessage("MotionPrediction: %6.3fs", motionPred);
}
// Loads the scene data
void OculusWorldDemoApp::PopulateScene(const char *fileName)
{
XmlHandler xmlHandler;
if(!xmlHandler.ReadFile(fileName, pRender, &MainScene, &CollisionModels, &GroundCollisionModels))
{
SetAdjustMessage("---------------------------------\nFILE LOAD FAILED\n---------------------------------");
SetAdjustMessageTimeout(10.0f);
}
MainScene.SetAmbient(Vector4f(1.0f, 1.0f, 1.0f, 1.0f));
// Distortion debug grid (brought up by 'G' key).
Ptr<Model> gridModel = *Model::CreateGrid(Vector3f(0,0,0), Vector3f(1.0f/10, 0,0), Vector3f(0,1.0f/10,0),
10, 10, 5,
Color(0, 255, 0, 255), Color(255, 50, 50, 255) );
GridScene.World.Add(gridModel);
// Yaw angle marker and lines (brought up by ';' key).
float shifty = -0.5f;
Ptr<Model> yawMarkGreenModel = *Model::CreateBox(Color(0, 255, 0, 255), Vector3f(0.0f, shifty, -2.0f), Vector3f(0.05f, 0.05f, 0.05f));
YawMarkGreenScene.World.Add(yawMarkGreenModel);
Ptr<Model> yawMarkRedModel = *Model::CreateBox(Color(255, 0, 0, 255), Vector3f(0.0f, shifty, -2.0f), Vector3f(0.05f, 0.05f, 0.05f));
YawMarkRedScene.World.Add(yawMarkRedModel);
Ptr<Model> yawLinesModel = *new Model(Prim_Lines);
float r = 2.0f;
float theta0 = Math<float>::PiOver2;
float theta1 = 0.0f;
Color c = Color(255, 200, 200, 255);
for (int i = 0; i < 35; i++)
{
theta1 = theta0 + Math<float>::Pi / 18.0f;
yawLinesModel->AddLine(yawLinesModel->AddVertex(Vector3f(r*cos(theta0),shifty,-r*sin(theta0)),c),
yawLinesModel->AddVertex(Vector3f(r*cos(theta1),shifty,-r*sin(theta1)),c));
theta0 = theta1;
yawLinesModel->AddLine(yawLinesModel->AddVertex(Vector3f(r*cos(theta0),shifty,-r*sin(theta0)),c),
yawLinesModel->AddVertex(Vector3f(r*cos(theta0),shifty+0.1f,-r*sin(theta0)),c));
theta0 = theta1;
}
theta1 = theta0 + Math<float>::Pi / 18.0f;
yawLinesModel->AddLine(yawLinesModel->AddVertex(Vector3f(r*cos(theta0),shifty,-r*sin(theta0)),c),
yawLinesModel->AddVertex(Vector3f(r*cos(theta1),shifty,-r*sin(theta1)),c));
yawLinesModel->AddLine(yawLinesModel->AddVertex(Vector3f(0.0f,shifty+0.1f,-r),c),
yawLinesModel->AddVertex(Vector3f(r*sin(0.02f),shifty,-r*cos(0.02f)),c));
yawLinesModel->AddLine(yawLinesModel->AddVertex(Vector3f(0.0f,shifty+0.1f,-r),c),
yawLinesModel->AddVertex(Vector3f(r*sin(-0.02f),shifty,-r*cos(-0.02f)),c));
yawLinesModel->SetPosition(Vector3f(0.0f,0.0f,0.0f));
YawLinesScene.World.Add(yawLinesModel);
}
void OculusWorldDemoApp::PopulatePreloadScene()
{
// Load-screen screen shot image
String fileName = MainFilePath;
fileName.StripExtension();
Ptr<File> imageFile = *new SysFile(fileName + "_LoadScreen.tga");
Ptr<Texture> imageTex;
if (imageFile->IsValid())
imageTex = *LoadTextureTga(pRender, imageFile);
// Image is rendered as a single quad.
if (imageTex)
{
imageTex->SetSampleMode(Sample_Anisotropic|Sample_Repeat);
Ptr<Model> m = *new Model(Prim_Triangles);
m->AddVertex(-0.5f, 0.5f, 0.0f, Color(255,255,255,255), 0.0f, 0.0f);
m->AddVertex( 0.5f, 0.5f, 0.0f, Color(255,255,255,255), 1.0f, 0.0f);
m->AddVertex( 0.5f, -0.5f, 0.0f, Color(255,255,255,255), 1.0f, 1.0f);
m->AddVertex(-0.5f, -0.5f, 0.0f, Color(255,255,255,255), 0.0f, 1.0f);
m->AddTriangle(2,1,0);
m->AddTriangle(0,3,2);
Ptr<ShaderFill> fill = *new ShaderFill(*pRender->CreateShaderSet());
fill->GetShaders()->SetShader(pRender->LoadBuiltinShader(Shader_Vertex, VShader_MVP));
fill->GetShaders()->SetShader(pRender->LoadBuiltinShader(Shader_Fragment, FShader_Texture));
fill->SetTexture(0, imageTex);
m->Fill = fill;
LoadingScene.World.Add(m);
}
}
void OculusWorldDemoApp::ClearScene()
{
MainScene.Clear();
GridScene.Clear();
YawMarkGreenScene.Clear();
YawMarkRedScene.Clear();
YawLinesScene.Clear();
}
void OculusWorldDemoApp::PopulateLODFileNames()
{
//OVR::String mainFilePath = MainFilePath;
LODFilePaths.PushBack(MainFilePath);
int LODIndex = 1;
SPInt pos = strcspn(MainFilePath.ToCStr(), ".");
SPInt len = strlen(MainFilePath.ToCStr());
SPInt diff = len - pos;
if (diff == 0)
return;
while(true)
{
char pathWithoutExt[250];
char buffer[250];
for(SPInt i = 0; i < pos; ++i)
{
pathWithoutExt[i] = MainFilePath[(int)i];
}
pathWithoutExt[pos] = '\0';
OVR_sprintf(buffer, sizeof(buffer), "%s%i.xml", pathWithoutExt, LODIndex);
FILE* fp = 0;
#if defined(_MSC_VER) && (_MSC_VER >= 1400 )
errno_t err = fopen_s(&fp, buffer, "rb");
if(!fp || err)
{
#else
fp = fopen(buffer, "rb");
if(!fp)
{
#endif
break;
}
fclose(fp);
OVR::String result = buffer;
LODFilePaths.PushBack(result);
LODIndex++;
}
}
void OculusWorldDemoApp::DropLOD()
{
if(CurrentLODFileIndex < (int)(LODFilePaths.GetSize() - 1))
{
ClearScene();
CurrentLODFileIndex++;
PopulateScene(LODFilePaths[CurrentLODFileIndex].ToCStr());
}
}
void OculusWorldDemoApp::RaiseLOD()
{
if(CurrentLODFileIndex > 0)
{
ClearScene();
CurrentLODFileIndex--;
PopulateScene(LODFilePaths[CurrentLODFileIndex].ToCStr());
}
}
//-----------------------------------------------------------------------------
void OculusWorldDemoApp::CycleDisplay()
{
int screenCount = pPlatform->GetDisplayCount();
// If Windowed, switch to the HMD screen first in Full-Screen Mode.
// If already Full-Screen, cycle to next screen until we reach FirstScreenInCycle.
if (pRender->IsFullscreen())
{
// Right now, we always need to restore window before going to next screen.
pPlatform->SetFullscreen(RenderParams, Display_Window);
Screen++;
if (Screen == screenCount)
Screen = 0;
RenderParams.Display = pPlatform->GetDisplay(Screen);
if (Screen != FirstScreenInCycle)
{
pRender->SetParams(RenderParams);
pPlatform->SetFullscreen(RenderParams, Display_Fullscreen);
}
}
else
{
// Try to find HMD Screen, making it the first screen in full-screen Cycle.
FirstScreenInCycle = 0;
if (pHMD)
{
DisplayId HMD (SConfig.GetHMDInfo().DisplayDeviceName, SConfig.GetHMDInfo().DisplayId);
for (int i = 0; i< screenCount; i++)
{
if (pPlatform->GetDisplay(i) == HMD)
{
FirstScreenInCycle = i;
break;
}
}
}
// Switch full-screen on the HMD.
Screen = FirstScreenInCycle;
RenderParams.Display = pPlatform->GetDisplay(Screen);
pRender->SetParams(RenderParams);
pPlatform->SetFullscreen(RenderParams, Display_Fullscreen);
}
}
void OculusWorldDemoApp::GamepadStateChanged(const GamepadState& pad)
{
ThePlayer.GamepadMove = Vector3f(pad.LX * pad.LX * (pad.LX > 0 ? 1 : -1),
0,
pad.LY * pad.LY * (pad.LY > 0 ? -1 : 1));
ThePlayer.GamepadRotate = Vector3f(2 * pad.RX, -2 * pad.RY, 0);
}
//-------------------------------------------------------------------------------------
OVR_PLATFORM_APP(OculusWorldDemoApp);
| 32.959958 | 138 | 0.565176 | cr88192 |
be3001675b70a04f35feab7ee872b2a8bbfadc18 | 7,011 | cpp | C++ | src/core/postprocessing/backbuffer_resolver.cpp | SleepKiller/swbfii-shaderpatch | b49ce3349d4dd09b19237ff4766652166ba1ffd4 | [
"MIT"
] | 5 | 2018-03-02T04:02:39.000Z | 2018-08-07T19:36:50.000Z | src/core/postprocessing/backbuffer_resolver.cpp | SleepKiller/swbfii-shaderpatch | b49ce3349d4dd09b19237ff4766652166ba1ffd4 | [
"MIT"
] | 27 | 2018-03-10T20:37:38.000Z | 2018-10-08T11:10:34.000Z | src/core/postprocessing/backbuffer_resolver.cpp | SleepKiller/swbfii-shaderpatch | b49ce3349d4dd09b19237ff4766652166ba1ffd4 | [
"MIT"
] | null | null | null |
#include "backbuffer_resolver.hpp"
#include "../d3d11_helpers.hpp"
#include <DirectXTex.h>
namespace sp::core::postprocessing {
Backbuffer_resolver::Backbuffer_resolver(Com_ptr<ID3D11Device5> device,
shader::Database& shaders)
: _resolve_vs{std::get<0>(
shaders.vertex("late_backbuffer_resolve"sv).entrypoint("main_vs"sv))},
_resolve_ps{shaders.pixel("late_backbuffer_resolve"sv).entrypoint("main_ps"sv)},
_resolve_ps_x2{
shaders.pixel("late_backbuffer_resolve"sv).entrypoint("main_x2_ps"sv)},
_resolve_ps_x4{
shaders.pixel("late_backbuffer_resolve"sv).entrypoint("main_x4_ps"sv)},
_resolve_ps_x8{
shaders.pixel("late_backbuffer_resolve"sv).entrypoint("main_x8_ps"sv)},
_resolve_ps_linear{
shaders.pixel("late_backbuffer_resolve"sv).entrypoint("main_linear_ps"sv)},
_resolve_ps_linear_x2{
shaders.pixel("late_backbuffer_resolve"sv).entrypoint("main_linear_x2_ps"sv)},
_resolve_ps_linear_x4{
shaders.pixel("late_backbuffer_resolve"sv).entrypoint("main_linear_x4_ps"sv)},
_resolve_ps_linear_x8{
shaders.pixel("late_backbuffer_resolve"sv).entrypoint("main_linear_x8_ps"sv)},
_resolve_cb{
create_dynamic_constant_buffer(*device, sizeof(std::array<std::uint32_t, 4>))}
{
}
void Backbuffer_resolver::apply(ID3D11DeviceContext1& dc, const Input input,
const Flags flags, Swapchain& swapchain,
const Interfaces interfaces) noexcept
{
if (DirectX::MakeTypeless(input.format) == DirectX::MakeTypeless(Swapchain::format)) {
apply_matching_format(dc, input, flags, swapchain, interfaces);
}
else {
apply_mismatch_format(dc, input, flags, swapchain, interfaces);
}
}
void Backbuffer_resolver::apply_matching_format(ID3D11DeviceContext1& dc,
const Input& input, const Flags flags,
Swapchain& swapchain,
const Interfaces& interfaces) noexcept
{
const bool msaa_input = input.sample_count > 1;
const bool want_post_aa = flags.use_cmma2;
// Fast Path for MSAA only.
if (msaa_input && !want_post_aa) {
dc.ResolveSubresource(swapchain.texture(), 0, &input.texture, 0, input.format);
return;
}
if (flags.use_cmma2) {
interfaces.cmaa2.apply(dc, interfaces.profiler,
{.input = input.srv,
.output = *input.uav,
.width = input.width,
.height = input.height});
}
dc.CopyResource(swapchain.texture(), &input.texture);
}
void Backbuffer_resolver::apply_mismatch_format(ID3D11DeviceContext1& dc,
const Input& input, const Flags flags,
Swapchain& swapchain,
const Interfaces& interfaces) noexcept
{
[[maybe_unused]] const bool msaa_input = input.sample_count > 1;
const bool want_post_aa = flags.use_cmma2;
// Fast Path for no post AA.
if (!want_post_aa) {
resolve_input(dc, input, flags, interfaces, *swapchain.rtv());
return;
}
if (flags.use_cmma2) {
auto cmma_target = interfaces.rt_allocator.allocate(
{.format = DXGI_FORMAT_R8G8B8A8_TYPELESS,
.width = input.width,
.height = input.height,
.bind_flags = effects::rendertarget_bind_srv_rtv_uav,
.srv_format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB,
.rtv_format = DXGI_FORMAT_R8G8B8A8_UNORM,
.uav_format = DXGI_FORMAT_R8G8B8A8_UNORM});
resolve_input(dc, input, flags, interfaces, *cmma_target.rtv());
interfaces.cmaa2.apply(dc, interfaces.profiler,
{.input = *cmma_target.srv(),
.output = *cmma_target.uav(),
.width = input.width,
.height = input.height});
dc.CopyResource(swapchain.texture(), &cmma_target.texture());
return;
}
log_and_terminate("Failed to resolve backbuffer! This should never happen.");
}
void Backbuffer_resolver::resolve_input(ID3D11DeviceContext1& dc,
const Input& input, const Flags flags,
const Interfaces& interfaces,
ID3D11RenderTargetView& target) noexcept
{
effects::Profile profile{interfaces.profiler, dc, "Backbuffer Resolve"};
dc.ClearState();
dc.IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
dc.VSSetShader(_resolve_vs.get(), nullptr, 0);
const D3D11_VIEWPORT viewport{.TopLeftX = 0.0f,
.TopLeftY = 0.0f,
.Width = static_cast<float>(input.width),
.Height = static_cast<float>(input.height),
.MinDepth = 0.0f,
.MaxDepth = 1.0f};
dc.RSSetViewports(1, &viewport);
auto* const rtv = ⌖
dc.OMSetRenderTargets(1, &rtv, nullptr);
const std::array srvs{&input.srv, get_blue_noise_texture(interfaces)};
dc.PSSetShaderResources(0, srvs.size(), srvs.data());
const std::array<std::uint32_t, 4> randomness{_resolve_rand_dist(_resolve_xorshift),
_resolve_rand_dist(_resolve_xorshift)};
update_dynamic_buffer(dc, *_resolve_cb, randomness);
auto* const cb = _resolve_cb.get();
dc.PSSetConstantBuffers(0, 1, &cb);
dc.PSSetShader(get_resolve_pixel_shader(input, flags), nullptr, 0);
dc.Draw(3, 0);
}
auto Backbuffer_resolver::get_blue_noise_texture(const Interfaces& interfaces) noexcept
-> ID3D11ShaderResourceView*
{
if (_blue_noise_srvs[0] == nullptr) {
for (int i = 0; i < 64; ++i) {
_blue_noise_srvs[i] = interfaces.resources.at_if(
"_SP_BUILTIN_blue_noise_rgb_"s + std::to_string(i));
}
}
return _blue_noise_srvs[_resolve_rand_dist(_resolve_xorshift)].get();
}
auto Backbuffer_resolver::get_resolve_pixel_shader(const Input& input,
const Flags flags) noexcept
-> ID3D11PixelShader*
{
if (flags.linear_input) {
switch (input.sample_count) {
case 1:
return _resolve_ps_linear.get();
case 2:
return _resolve_ps_linear_x2.get();
case 4:
return _resolve_ps_linear_x4.get();
case 8:
return _resolve_ps_linear_x8.get();
}
}
switch (input.sample_count) {
case 1:
return _resolve_ps.get();
case 2:
return _resolve_ps_x2.get();
case 4:
return _resolve_ps_x4.get();
case 8:
return _resolve_ps_x8.get();
default:
log_and_terminate("Unsupported sample count!");
}
}
} | 36.326425 | 89 | 0.607046 | SleepKiller |
be336e816c8b899a7c976e3e9a0ac37c4b723b66 | 4,465 | cpp | C++ | armm/STM32/src/hwi2cslave_stm32_v1.cpp | Bergi84/vihal | 7c139b544bb5ed5a27088bbb6b993f061e055ce8 | [
"BSD-2-Clause"
] | 13 | 2018-02-26T14:56:02.000Z | 2022-03-31T06:01:56.000Z | armm/STM32/src/hwi2cslave_stm32_v1.cpp | Bergi84/vihal | 7c139b544bb5ed5a27088bbb6b993f061e055ce8 | [
"BSD-2-Clause"
] | 2 | 2022-03-12T10:18:07.000Z | 2022-03-14T20:06:26.000Z | armm/STM32/src/hwi2cslave_stm32_v1.cpp | Bergi84/vihal | 7c139b544bb5ed5a27088bbb6b993f061e055ce8 | [
"BSD-2-Clause"
] | 3 | 2020-11-04T09:15:01.000Z | 2021-07-06T09:42:00.000Z | /* -----------------------------------------------------------------------------
* This file is a part of the NVCM project: https://github.com/nvitya/nvcm
* Copyright (c) 2018 Viktor Nagy, nvitya
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from
* the use of this software. Permission is granted to anyone to use this
* software for any purpose, including commercial applications, and to alter
* it and redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software in
* a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
* --------------------------------------------------------------------------- */
/*
* file: hwi2cslave_stm32_v1.cpp
* brief: STM32 I2C / TWI Slave for F1, F4
* version: 1.00
* date: 2020-03-06
* authors: nvitya
*/
#include "platform.h"
#include "hwpins.h"
#include "hwi2cslave.h"
#include "stm32_utils.h"
#include "traces.h"
#if I2C_HW_VER == 1
// v1 (STM32F1xx, STM32F4xx): different register names and defines
bool THwI2cSlave_stm32::InitHw(int adevnum)
{
unsigned tmp;
uint8_t busid = STM32_BUSID_APB1;
initialized = false;
devnum = adevnum;
regs = nullptr;
if (false)
{
}
#ifdef I2C1
else if (1 == devnum)
{
regs = I2C1;
RCC->APB1ENR |= RCC_APB1ENR_I2C1EN;
}
#endif
#ifdef I2C2
else if (2 == devnum)
{
regs = I2C2;
RCC->APB1ENR |= RCC_APB1ENR_I2C2EN;
}
#endif
#ifdef I2C3
else if (3 == devnum)
{
regs = I2C3;
RCC->APB1ENR |= RCC_APB1ENR_I2C3EN;
}
#endif
if (!regs)
{
return false;
}
// disable for setup
regs->CR1 &= ~I2C_CR1_PE;
regs->CR1 |= I2C_CR1_SWRST;
regs->CR1 &= ~I2C_CR1_SWRST;
unsigned cr1 = 0; // use the default settings, keep disabled
regs->CR1 = cr1;
// setup address
// this device does not support address mask
regs->OAR1 = ((address & 0x7F) << 1);
unsigned periphclock = stm32_bus_speed(busid);
// CR2
tmp = 0
| (0 << 12) // LAST: 1 = Last transfer on DMA EOT
| (0 << 11) // DMAEN: 1 = enable DMA
| (1 << 10) // ITBUFEN: 1 = enable data interrupt
| (1 << 9) // ITEVTEN: 1 = enable event interrupt
| (1 << 8) // ITERREN: 1 = enable error interrupt
| ((periphclock / 1000000) << 0) // set clock speed in MHz
;
regs->CR2 = tmp;
cr1 |= 0
| I2C_CR1_ACK // ACKnowledge must be enabled, otherwise even the own address won't be handled
| I2C_CR1_PE // Enable
;
regs->CR1 = cr1;
initialized = true;
return true;
}
// runstate:
// 0: idle
// 1: receive data
// 5: transmit data
void THwI2cSlave_stm32::HandleIrq()
{
uint32_t sr1 = regs->SR1;
uint32_t sr2 = regs->SR2;
// warning, the sequence above clears some of the status bits
//TRACE("[I2C IRQ %04X %04X]\r\n", sr1, sr2);
// check errors
if (sr1 & 0xFF00)
{
if (sr1 & I2C_SR1_AF) // ACK Failure ?
{
// this is normal
regs->SR1 = ~I2C_SR1_AF; // clear AF error
}
else
{
//TRACE("I2C errors: %04X\r\n", sr1);
regs->SR1 = ~(sr1 & 0xFF00); // clear errors
}
}
// check events
if (sr1 & I2C_SR1_ADDR) // address matched, after start / restart
{
if (sr2 & I2C_SR2_TRA)
{
istx = true;
runstate = 5; // go to transfer data
}
else
{
istx = false;
runstate = 1; // go to receive data
}
OnAddressRw(address); // there is no other info on this chip, use own address
}
if (sr1 & I2C_SR1_RXNE)
{
uint8_t d = regs->DR;
if (1 == runstate)
{
OnByteReceived(d);
}
else
{
// unexpected byte
}
}
if (sr1 & I2C_SR1_TXE)
{
if (5 == runstate)
{
uint8_t d = OnTransmitRequest();
regs->DR = d;
}
else
{
// force stop, releases the data lines
regs->CR1 |= I2C_CR1_STOP; // this must be done here for the proper STOP
}
}
// check stop
if (sr1 & I2C_SR1_STOPF)
{
//TRACE(" STOP DETECTED.\r\n");
// the CR1 must be written in order to clear this flag
runstate = 0;
uint32_t cr1 = regs->CR1;
cr1 &= ~I2C_CR1_STOP;
regs->CR1 = cr1;
}
if (sr2) // to keep sr2 if unused
{
}
}
#endif
| 20.864486 | 97 | 0.618365 | Bergi84 |
be33f928b091cb9843bd6739b8f6114c9175140f | 591 | cpp | C++ | test/language/enumeration_types/cpp/EnumDefinedByConstantTest.cpp | dkBrazz/zserio | 29dd8145b7d851fac682d3afe991185ea2eac318 | [
"BSD-3-Clause"
] | 86 | 2018-09-06T09:30:53.000Z | 2022-03-27T01:12:36.000Z | test/language/enumeration_types/cpp/EnumDefinedByConstantTest.cpp | dkBrazz/zserio | 29dd8145b7d851fac682d3afe991185ea2eac318 | [
"BSD-3-Clause"
] | 362 | 2018-09-04T20:21:24.000Z | 2022-03-30T15:14:38.000Z | test/language/enumeration_types/cpp/EnumDefinedByConstantTest.cpp | dkBrazz/zserio | 29dd8145b7d851fac682d3afe991185ea2eac318 | [
"BSD-3-Clause"
] | 20 | 2018-09-10T15:59:02.000Z | 2021-12-01T15:38:22.000Z | #include "gtest/gtest.h"
#include "enumeration_types/enum_defined_by_constant/Colors.h"
#include "enumeration_types/enum_defined_by_constant/WHITE_COLOR.h"
namespace enumeration_types
{
namespace enum_defined_by_constant
{
class EnumDefinedByConstant : public ::testing::Test
{
};
TEST_F(EnumDefinedByConstant, lightColor)
{
ASSERT_EQ(1, WHITE_COLOR);
ASSERT_EQ(WHITE_COLOR, zserio::enumToValue(Colors::WHITE));
ASSERT_EQ(zserio::enumToValue(Colors::WHITE) + 1, zserio::enumToValue(Colors::BLACK));
}
} // namespace enum_defined_by_constant
} // namespace enumeration_types
| 24.625 | 90 | 0.788494 | dkBrazz |
be341e8d65a3a103c2400bd43d9009349a22888d | 6,052 | hxx | C++ | Common/OpenCL/Filters/itkGPUTranslationTransformBase.hxx | squll1peter/elastix | e58c831a91df6233605f96ad060119439756ca90 | [
"Apache-2.0"
] | 1 | 2020-11-12T12:17:02.000Z | 2020-11-12T12:17:02.000Z | Common/OpenCL/Filters/itkGPUTranslationTransformBase.hxx | squll1peter/elastix | e58c831a91df6233605f96ad060119439756ca90 | [
"Apache-2.0"
] | null | null | null | Common/OpenCL/Filters/itkGPUTranslationTransformBase.hxx | squll1peter/elastix | e58c831a91df6233605f96ad060119439756ca90 | [
"Apache-2.0"
] | 1 | 2021-01-16T08:59:39.000Z | 2021-01-16T08:59:39.000Z | /*=========================================================================
*
* Copyright UMC Utrecht and contributors
*
* 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.txt
*
* 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.
*
*=========================================================================*/
#ifndef __itkGPUTranslationTransformBase_hxx
#define __itkGPUTranslationTransformBase_hxx
#include "itkGPUTranslationTransformBase.h"
#include <iomanip>
// begin of ITKGPUTranslationTransformBase namespace
namespace ITKGPUTranslationTransformBase
{
typedef struct
{
cl_float offset;
} GPUTranslationTransformBase1D;
typedef struct
{
cl_float2 offset;
} GPUTranslationTransformBase2D;
typedef struct
{
cl_float3 offset;
} GPUTranslationTransformBase3D;
//------------------------------------------------------------------------------
template< unsigned int ImageDimension >
struct SpaceDimensionToType {};
//----------------------------------------------------------------------------
// Offset
template< typename TScalarType, unsigned int SpaceDimension >
void
SetOffset1( const itk::Vector< TScalarType, SpaceDimension > &,
cl_float &, SpaceDimensionToType< SpaceDimension > )
{}
template< typename TScalarType, unsigned int SpaceDimension >
void
SetOffset2( const itk::Vector< TScalarType, SpaceDimension > &,
cl_float2 &, SpaceDimensionToType< SpaceDimension > )
{}
template< typename TScalarType, unsigned int SpaceDimension >
void
SetOffset3( const itk::Vector< TScalarType, SpaceDimension > &,
cl_float4 &, SpaceDimensionToType< SpaceDimension > )
{}
template< typename TScalarType >
void
SetOffset1( const itk::Vector< TScalarType, 1 > & offset,
cl_float & ocloffset, SpaceDimensionToType< 1 > )
{
ocloffset = offset[ 0 ];
}
template< typename TScalarType >
void
SetOffset2( const itk::Vector< TScalarType, 2 > & offset,
cl_float2 & ocloffset, SpaceDimensionToType< 2 > )
{
unsigned int id = 0;
for( unsigned int i = 0; i < 2; i++ )
{
ocloffset.s[ id++ ] = offset[ i ];
}
}
template< typename TScalarType >
void
SetOffset3( const itk::Vector< TScalarType, 3 > & offset,
cl_float4 & ocloffset, SpaceDimensionToType< 3 > )
{
unsigned int id = 0;
for( unsigned int i = 0; i < 3; i++ )
{
ocloffset.s[ id++ ] = offset[ i ];
}
ocloffset.s[ 3 ] = 0.0;
}
} // end of ITKGPUTranslationTransformBase namespace
//------------------------------------------------------------------------------
namespace itk
{
template< typename TScalarType, unsigned int NDimensions >
GPUTranslationTransformBase< TScalarType, NDimensions >
::GPUTranslationTransformBase()
{
// Add GPUTranslationTransformBase source
const std::string sourcePath(
GPUTranslationTransformBaseKernel::GetOpenCLSource() );
m_Sources.push_back( sourcePath );
this->m_ParametersDataManager->Initialize();
this->m_ParametersDataManager->SetBufferFlag( CL_MEM_READ_ONLY );
using namespace ITKGPUTranslationTransformBase;
const unsigned int Dimension = SpaceDimension;
switch( Dimension )
{
case 1:
this->m_ParametersDataManager->SetBufferSize( sizeof( GPUTranslationTransformBase1D ) );
break;
case 2:
this->m_ParametersDataManager->SetBufferSize( sizeof( GPUTranslationTransformBase2D ) );
break;
case 3:
this->m_ParametersDataManager->SetBufferSize( sizeof( GPUTranslationTransformBase3D ) );
break;
default:
break;
}
this->m_ParametersDataManager->Allocate();
} // end Constructor
//------------------------------------------------------------------------------
template< typename TScalarType, unsigned int NDimensions >
GPUDataManager::Pointer
GPUTranslationTransformBase< TScalarType, NDimensions >
::GetParametersDataManager( void ) const
{
using namespace ITKGPUTranslationTransformBase;
const SpaceDimensionToType< SpaceDimension > dim = {};
const unsigned int Dimension = SpaceDimension;
switch( Dimension )
{
case 1:
{
GPUTranslationTransformBase1D translationBase;
SetOffset1< ScalarType >( GetCPUOffset(), translationBase.offset, dim );
this->m_ParametersDataManager->SetCPUBufferPointer( &translationBase );
}
break;
case 2:
{
GPUTranslationTransformBase2D translationBase;
SetOffset2< ScalarType >( GetCPUOffset(), translationBase.offset, dim );
this->m_ParametersDataManager->SetCPUBufferPointer( &translationBase );
}
break;
case 3:
{
GPUTranslationTransformBase3D translationBase;
SetOffset3< ScalarType >( GetCPUOffset(), translationBase.offset, dim );
this->m_ParametersDataManager->SetCPUBufferPointer( &translationBase );
}
break;
default:
break;
}
this->m_ParametersDataManager->SetGPUDirtyFlag( true );
this->m_ParametersDataManager->UpdateGPUBuffer();
return this->m_ParametersDataManager;
} // end GetParametersDataManager()
//------------------------------------------------------------------------------
template< typename TScalarType, unsigned int NDimensions >
bool
GPUTranslationTransformBase< TScalarType, NDimensions >
::GetSourceCode( std::string & source ) const
{
if( this->m_Sources.size() == 0 )
{
return false;
}
// Create the final source code
std::ostringstream sources;
// Add other sources
for( std::size_t i = 0; i < this->m_Sources.size(); i++ )
{
sources << this->m_Sources[ i ] << std::endl;
}
source = sources.str();
return true;
} // end GetSourceCode()
} // end namespace itk
#endif /* __itkGPUTranslationTransformBase_hxx */
| 28.413146 | 94 | 0.660278 | squll1peter |
be393597aafda60712bc16de7518b01a798ee7c3 | 449 | hpp | C++ | iOS/G3MiOSSDK/Commons/Rendererers/VisibleSectorListener.hpp | restjohn/g3m | 608657fd6f0e2898bd963d15136ff085b499e97e | [
"BSD-2-Clause"
] | 1 | 2016-08-23T10:29:44.000Z | 2016-08-23T10:29:44.000Z | iOS/G3MiOSSDK/Commons/Rendererers/VisibleSectorListener.hpp | restjohn/g3m | 608657fd6f0e2898bd963d15136ff085b499e97e | [
"BSD-2-Clause"
] | null | null | null | iOS/G3MiOSSDK/Commons/Rendererers/VisibleSectorListener.hpp | restjohn/g3m | 608657fd6f0e2898bd963d15136ff085b499e97e | [
"BSD-2-Clause"
] | null | null | null | //
// VisibleSectorListener.hpp
// G3MiOSSDK
//
// Created by Diego Gomez Deck on 1/17/13.
//
//
#ifndef __G3MiOSSDK__VisibleSectorListener__
#define __G3MiOSSDK__VisibleSectorListener__
#include "Sector.hpp"
class VisibleSectorListener {
public:
virtual ~VisibleSectorListener() {
}
virtual void onVisibleSectorChange(const Sector& visibleSector,
const Geodetic3D& cameraPosition) = 0;
};
#endif
| 17.96 | 75 | 0.699332 | restjohn |
be3944e34edde676ff4d93b9d326f3e846e7198f | 5,877 | cpp | C++ | src/globalsearch/http/httprequestmanager.cpp | lilithean/XtalOpt | 9ebc125e6014b27e72a04fb62c8820c7b9670c61 | [
"BSD-3-Clause"
] | 23 | 2017-09-01T04:35:02.000Z | 2022-01-16T13:51:17.000Z | src/globalsearch/http/httprequestmanager.cpp | lilithean/XtalOpt | 9ebc125e6014b27e72a04fb62c8820c7b9670c61 | [
"BSD-3-Clause"
] | 20 | 2017-08-29T15:29:46.000Z | 2022-01-20T09:10:59.000Z | src/globalsearch/http/httprequestmanager.cpp | lilithean/XtalOpt | 9ebc125e6014b27e72a04fb62c8820c7b9670c61 | [
"BSD-3-Clause"
] | 21 | 2017-06-15T03:11:34.000Z | 2022-02-28T05:20:44.000Z | /**********************************************************************
HttpRequestManager - Submit http 'get' and 'post' requests with a
QNetworkAccessManager and receive the results
Copyright (C) 2017-2018 by Patrick Avery
This source code is released under the New BSD License, (the "License").
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 "httprequestmanager.h"
#include <QDebug>
#include <QNetworkRequest>
HttpRequestManager::HttpRequestManager(
const std::shared_ptr<QNetworkAccessManager>& networkManager, QObject* parent)
: QObject(parent), m_networkManager(networkManager), m_requestCounter(0)
{
// This is done so that handleGet and handlePost are always ran in the
// main thread
connect(this, &HttpRequestManager::signalGet, this,
&HttpRequestManager::handleGet);
connect(this, &HttpRequestManager::signalPost, this,
&HttpRequestManager::handlePost);
}
size_t HttpRequestManager::sendGet(QUrl url)
{
std::unique_lock<std::mutex> lock(m_mutex);
QNetworkRequest request(url);
emit signalGet(request, m_requestCounter);
return m_requestCounter++;
}
size_t HttpRequestManager::sendPost(QUrl url, const QByteArray& data)
{
std::unique_lock<std::mutex> lock(m_mutex);
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader,
"application/x-www-form-urlencoded");
emit signalPost(request, data, m_requestCounter);
return m_requestCounter++;
}
bool HttpRequestManager::containsData(size_t i) const
{
std::unique_lock<std::mutex> lock(m_mutex);
return m_receivedReplies.find(i) != m_receivedReplies.end();
}
const QByteArray& HttpRequestManager::data(size_t i) const
{
std::unique_lock<std::mutex> lock(m_mutex);
static const QByteArray empty = "";
if (m_receivedReplies.find(i) == m_receivedReplies.end())
return empty;
return m_receivedReplies.at(i);
}
void HttpRequestManager::handleGet(QNetworkRequest request, size_t requestId)
{
std::unique_lock<std::mutex> lock(m_mutex);
QNetworkReply* reply = m_networkManager->get(request);
connect(reply, (void (QNetworkReply::*)(QNetworkReply::NetworkError))(
&QNetworkReply::error),
this, &HttpRequestManager::handleError);
connect(reply, &QNetworkReply::finished, this,
&HttpRequestManager::handleFinished);
m_pendingReplies[requestId] = reply;
}
void HttpRequestManager::handlePost(QNetworkRequest request, QByteArray data,
size_t requestId)
{
std::unique_lock<std::mutex> lock(m_mutex);
QNetworkReply* reply = m_networkManager->post(request, data);
connect(reply, (void (QNetworkReply::*)(QNetworkReply::NetworkError))(
&QNetworkReply::error),
this, &HttpRequestManager::handleError);
connect(reply, &QNetworkReply::finished, this,
&HttpRequestManager::handleFinished);
m_pendingReplies[requestId] = reply;
}
void HttpRequestManager::handleError(QNetworkReply::NetworkError ec)
{
std::unique_lock<std::mutex> lock(m_mutex);
// Make sure the sender is a QNetworkReply
QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
if (!reply) {
qDebug() << "Error in" << __FUNCTION__ << ": sender() is not a"
<< "QNetworkReply!";
return;
}
// Make sure this HttpRequestManager owns this reply
auto it =
std::find_if(m_pendingReplies.begin(), m_pendingReplies.end(),
[reply](const std::pair<size_t, QNetworkReply*>& item) {
return reply == item.second;
});
// If not, print an error and return
if (it == m_pendingReplies.end()) {
qDebug() << "Error in" << __FUNCTION__ << ": sender() is not owned by"
<< "this HttpRequestManager instance!";
return;
}
size_t receivedInd = it->first;
// Print a message for some of the more common errors
if (ec == QNetworkReply::ConnectionRefusedError)
qDebug() << "QNetworkReply received an error: connection refused";
else if (ec == QNetworkReply::RemoteHostClosedError)
qDebug() << "QNetworkReply received an error: remote host closed";
else if (ec == QNetworkReply::HostNotFoundError)
qDebug() << "QNetworkReply received an error: host not found";
else if (ec == QNetworkReply::TimeoutError)
qDebug() << "QNetworkReply received an error: timeout";
else
qDebug() << "QNetworkReply received error code:" << ec;
m_receivedReplies[receivedInd] = reply->readAll();
m_pendingReplies.erase(receivedInd);
reply->deleteLater();
// Emit a signal
emit received(receivedInd);
}
void HttpRequestManager::handleFinished()
{
std::unique_lock<std::mutex> lock(m_mutex);
// Make sure the sender is a QNetworkReply
QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
if (!reply) {
qDebug() << "Error in" << __FUNCTION__ << ": sender() is not a"
<< "QNetworkReply!";
return;
}
// Make sure this HttpRequestManager owns this reply
auto it =
std::find_if(m_pendingReplies.begin(), m_pendingReplies.end(),
[reply](const std::pair<size_t, QNetworkReply*>& item) {
return reply == item.second;
});
// If not, just return
if (it == m_pendingReplies.end())
return;
size_t receivedInd = it->first;
m_receivedReplies[receivedInd] = reply->readAll();
m_pendingReplies.erase(receivedInd);
reply->deleteLater();
// Emit a signal
emit received(receivedInd);
}
| 30.931579 | 80 | 0.674153 | lilithean |
be3a0c39567c62c15320c7468a85fb540c600e45 | 2,056 | cpp | C++ | WiXCustomActions/CustomAction.cpp | droobah/privacyidea-credential-provider | 275ce8ba8852716eeadc67d264802d697d46816a | [
"Apache-2.0"
] | null | null | null | WiXCustomActions/CustomAction.cpp | droobah/privacyidea-credential-provider | 275ce8ba8852716eeadc67d264802d697d46816a | [
"Apache-2.0"
] | null | null | null | WiXCustomActions/CustomAction.cpp | droobah/privacyidea-credential-provider | 275ce8ba8852716eeadc67d264802d697d46816a | [
"Apache-2.0"
] | null | null | null | /* * * * * * * * * * * * * * * * * * * * *
**
** Copyright 2012 Dominik Pretzsch
**
** 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 "stdafx.h"
UINT __stdcall SanitizeDwordFromRegistry(MSIHANDLE hInstall)
{
HRESULT hr = S_OK;
UINT er = ERROR_SUCCESS;
hr = WcaInitialize(hInstall, "SanitizeDword");
ExitOnFailure(hr, "Failed to initialize");
WcaLog(LOGMSG_STANDARD, "Initialized.");
///
wchar_t cPropertyName[MAX_PATH];
wchar_t cPropertyValue[MAX_PATH];
DWORD dwMaxLen = MAX_PATH;
// TODO: Support multiple properties (separated by comma)
MsiGetProperty(hInstall, L"SANITIZE_DWORD", cPropertyName, &dwMaxLen);
MsiGetProperty(hInstall, cPropertyName, cPropertyValue, &dwMaxLen);
if (cPropertyValue[0] == '#')
{
WcaLog(LOGMSG_STANDARD, "Property %s needs sanitation...", cPropertyName);
for (unsigned int i = 1; i < dwMaxLen; i++)
{
cPropertyValue[i - 1] = cPropertyValue[i];
cPropertyValue[i] = NULL;
}
WcaLog(LOGMSG_STANDARD, "Sanitation done.");
}
MsiSetProperty(hInstall, cPropertyName, cPropertyValue);
///
LExit:
er = SUCCEEDED(hr) ? ERROR_SUCCESS : ERROR_INSTALL_FAILURE;
return WcaFinalize(er);
}
// DllMain - Initialize and cleanup WiX custom action utils.
extern "C" BOOL WINAPI DllMain(
__in HINSTANCE hInst,
__in ULONG ulReason,
__in LPVOID
)
{
switch (ulReason)
{
case DLL_PROCESS_ATTACH:
WcaGlobalInitialize(hInst);
break;
case DLL_PROCESS_DETACH:
WcaGlobalFinalize();
break;
}
return TRUE;
}
| 25.7 | 78 | 0.693093 | droobah |
be3d407877150ee39192f8a603838808f55b3bec | 1,558 | cpp | C++ | test/windows_on_apc_known.cpp | lanza/coroutine | c90caab988f96997f5bc1bd6f1958b80524fa14a | [
"CC-BY-4.0"
] | 368 | 2018-11-22T22:57:04.000Z | 2022-03-31T04:04:54.000Z | test/windows_on_apc_known.cpp | lanza/coroutine | c90caab988f96997f5bc1bd6f1958b80524fa14a | [
"CC-BY-4.0"
] | 35 | 2018-11-09T04:38:20.000Z | 2022-01-27T01:10:02.000Z | test/windows_on_apc_known.cpp | lanza/coroutine | c90caab988f96997f5bc1bd6f1958b80524fa14a | [
"CC-BY-4.0"
] | 29 | 2018-12-26T14:03:47.000Z | 2022-02-11T17:36:55.000Z | /**
* @author github.com/luncliff (luncliff@gmail.com)
*/
#undef NDEBUG
#include <atomic>
#include <cassert>
#include <iostream>
#include <gsl/gsl>
#include <coroutine/return.h>
#include <coroutine/windows.h>
using namespace std;
using namespace coro;
auto procedure_call_on_known_thread(HANDLE thread, HANDLE event) -> frame_t {
co_await continue_on_apc{thread};
if (SetEvent(event) == FALSE)
cerr << system_category().message(GetLastError()) << endl;
}
DWORD WINAPI wait_in_sleep(LPVOID) {
SleepEx(1000, true);
return GetLastError();
}
int main(int, char*[]) {
HANDLE event = CreateEvent(nullptr, false, false, nullptr);
assert(event != INVALID_HANDLE_VALUE);
auto on_return_1 = gsl::finally([event]() { CloseHandle(event); });
DWORD worker_id{};
HANDLE worker = CreateThread(nullptr, 0, //
wait_in_sleep, nullptr, 0, &worker_id);
assert(worker != 0);
auto on_return_2 = gsl::finally([worker]() { CloseHandle(worker); });
SleepEx(500, true);
procedure_call_on_known_thread(worker, event);
HANDLE handles[2] = {event, worker};
auto ec = WaitForMultipleObjectsEx(2, handles, TRUE, INFINITE, true);
// expect the wait is cancelled by APC (WAIT_IO_COMPLETION)
assert(ec == WAIT_OBJECT_0 || ec == WAIT_IO_COMPLETION);
DWORD retcode{};
GetExitCodeThread(worker, &retcode);
// we used QueueUserAPC so the return can be 'elapsed' milliseconds
// allow zero for the timeout
assert(retcode >= 0);
return EXIT_SUCCESS;
}
| 28.851852 | 77 | 0.673941 | lanza |
be3deb80e8531487df0b431d675cadcadfb98212 | 3,633 | hpp | C++ | Periapsis/src/game/main_window.hpp | kulibali/periapsis | 8a8588caff526d3b17604c96338145329be160b8 | [
"MIT"
] | null | null | null | Periapsis/src/game/main_window.hpp | kulibali/periapsis | 8a8588caff526d3b17604c96338145329be160b8 | [
"MIT"
] | null | null | null | Periapsis/src/game/main_window.hpp | kulibali/periapsis | 8a8588caff526d3b17604c96338145329be160b8 | [
"MIT"
] | null | null | null | #ifndef PERIAPSIS_MAIN_WINDOW_H
#define PERIAPSIS_MAIN_WINDOW_H
//
// $Id$
//
// Copyright (c) 2008, The Periapsis Project. 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 The Periapsis Project 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.
//
#include "data/singleton.hpp"
#include "data/string.hpp"
#include "data/config.hpp"
#include "framework/widget.hpp"
namespace gsgl
{
namespace framework
{
class textbox;
class button;
class tabbox;
}
}
namespace periapsis
{
class periapsis_app;
class simulation_tab;
class settings_tab;
class load_scenery_thread;
class main_window
: public gsgl::framework::widget, public gsgl::data::singleton<main_window>
{
gsgl::framework::textbox *title_box, *status_bar;
gsgl::framework::button *quit_button;
gsgl::framework::tabbox *tab_box;
simulation_tab *sim_tab;
settings_tab *set_tab;
bool need_to_load_scenery;
load_scenery_thread *loading_thread;
public:
main_window(gsgl::platform::display & screen, const gsgl::string & title, const int x, const int y);
virtual ~main_window();
//
void set_status(const gsgl::string & message);
//
virtual void draw();
//
static gsgl::data::config_variable<int> WIDTH;
static gsgl::data::config_variable<int> HEIGHT;
static gsgl::data::config_variable<gsgl::platform::color> FOREGROUND;
static gsgl::data::config_variable<gsgl::platform::color> BACKGROUND;
static gsgl::data::config_variable<gsgl::string> FONT_FACE;
static gsgl::data::config_variable<int> FONT_SIZE;
static gsgl::data::config_variable<int> TITLE_BOX_HEIGHT;
static gsgl::data::config_variable<int> STATUS_BAR_HEIGHT;
static gsgl::data::config_variable<int> TAB_BOX_SPACE;
static gsgl::data::config_variable<int> QUIT_BUTTON_WIDTH;
}; // class main_window
} // namespace periapsis
#endif
| 35.271845 | 109 | 0.674649 | kulibali |
be3e65e07c3fcb64b7a52b965e48bccb6d9f8577 | 340 | cpp | C++ | src/patternMatchValidator/AnyPatternMatchValidator.cpp | sroehling/ChartPatternRecognitionLib | d9bd25c0fc5a8942bb98c74c42ab52db80f680c1 | [
"MIT"
] | 9 | 2019-07-15T19:10:07.000Z | 2021-12-14T12:16:18.000Z | src/patternMatchValidator/AnyPatternMatchValidator.cpp | sroehling/ChartPatternRecognitionLib | d9bd25c0fc5a8942bb98c74c42ab52db80f680c1 | [
"MIT"
] | null | null | null | src/patternMatchValidator/AnyPatternMatchValidator.cpp | sroehling/ChartPatternRecognitionLib | d9bd25c0fc5a8942bb98c74c42ab52db80f680c1 | [
"MIT"
] | 2 | 2020-05-23T03:25:25.000Z | 2021-11-19T16:41:44.000Z | /*
* AnyPatternMatchValidator.cpp
*
* Created on: Jun 18, 2014
* Author: sroehling
*/
#include <AnyPatternMatchValidator.h>
AnyPatternMatchValidator::AnyPatternMatchValidator() {
}
bool AnyPatternMatchValidator::validPattern(const PatternMatch &)
{
return true;
}
AnyPatternMatchValidator::~AnyPatternMatchValidator() {
}
| 15.454545 | 65 | 0.75 | sroehling |
be41f1e87de4fe59078b694951cb90900698e62d | 826 | cpp | C++ | src/gamelib/components/CollisionComponent.cpp | mall0c/GameLib | df4116b53c39be7b178dd87f7eb0fe32a94d00d3 | [
"MIT"
] | 1 | 2020-02-17T09:53:36.000Z | 2020-02-17T09:53:36.000Z | src/gamelib/components/CollisionComponent.cpp | mall0c/GameLib | df4116b53c39be7b178dd87f7eb0fe32a94d00d3 | [
"MIT"
] | null | null | null | src/gamelib/components/CollisionComponent.cpp | mall0c/GameLib | df4116b53c39be7b178dd87f7eb0fe32a94d00d3 | [
"MIT"
] | null | null | null | #include "gamelib/components/CollisionComponent.hpp"
#include "gamelib/core/geometry/CollisionSystem.hpp"
namespace gamelib
{
CollisionComponent::CollisionComponent()
{
_props.registerProperty("flags", flags, 0, num_colflags, str_colflags);
}
CollisionComponent::~CollisionComponent()
{
quit();
}
bool CollisionComponent::_init()
{
auto sys = getSubsystem<CollisionSystem>();
if (!sys)
return false;
sys->add(this);
return true;
}
void CollisionComponent::_quit()
{
getSubsystem<CollisionSystem>()->remove(this);
}
Transformable* CollisionComponent::getTransform()
{
return this;
}
const Transformable* CollisionComponent::getTransform() const
{
return this;
}
}
| 20.146341 | 79 | 0.623487 | mall0c |
be42554cbc4e5b35acaf0ad990cbef4e0da7c9dd | 514 | cpp | C++ | tableinfo.cpp | santomet/JustOneMoreBeerPlease | af22e68ea2a964b7b9d70d43b81f708df9446a9b | [
"WTFPL"
] | null | null | null | tableinfo.cpp | santomet/JustOneMoreBeerPlease | af22e68ea2a964b7b9d70d43b81f708df9446a9b | [
"WTFPL"
] | null | null | null | tableinfo.cpp | santomet/JustOneMoreBeerPlease | af22e68ea2a964b7b9d70d43b81f708df9446a9b | [
"WTFPL"
] | 1 | 2019-06-15T20:01:47.000Z | 2019-06-15T20:01:47.000Z | #include "tableinfo.h"
TableInfo::TableInfo(QObject *parent) : QObject(parent)
{
}
QString TableInfo::name()
{
return mName;
}
int TableInfo::id()
{
return mId;
}
bool TableInfo::isWaitingOrder()
{
return waitingOrder;
}
void TableInfo::setName(const QString &name)
{
mName = name;
emit nameChanged();
}
void TableInfo::setWaitingOrder(bool waiting)
{
waitingOrder = waiting;
emit isWaitingOrderChanged();
}
void TableInfo::setId(int id)
{
mId = id;
emit idChanged();
}
| 12.85 | 55 | 0.669261 | santomet |
be45a5d04efd03001b7ea061367aba467b00b7ba | 349 | cpp | C++ | library/succinct/main.cpp | bluedawnstar/algorithm_library | 4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6 | [
"Unlicense"
] | 40 | 2017-11-26T05:29:18.000Z | 2020-11-13T00:29:26.000Z | library/succinct/main.cpp | bluedawnstar/algorithm_library | 4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6 | [
"Unlicense"
] | 101 | 2019-02-09T06:06:09.000Z | 2021-12-25T16:55:37.000Z | library/succinct/main.cpp | bluedawnstar/algorithm_library | 4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6 | [
"Unlicense"
] | 6 | 2017-01-03T14:17:58.000Z | 2021-01-22T10:37:04.000Z | #include <iostream>
using namespace std;
#define TEST(ModuleName) extern void test##ModuleName(void); \
test##ModuleName()
int main(void) {
TEST(BitVectorRank);
TEST(WaveletTree);
TEST(WaveletTreeBitVector);
TEST(WaveletMatrix);
TEST(WaveletMatrixArray);
TEST(WaveletMatrixArrayIndirect);
}
| 21.8125 | 65 | 0.659026 | bluedawnstar |
be46616bf23901fa75ab08931a99583b1bce52bd | 530 | hpp | C++ | unit_tests/classgenerator.hpp | julienlopez/CppDependencyAnalyzer | d29065e7988ef7f553785ce7cb8bf2bb03097c66 | [
"MIT"
] | null | null | null | unit_tests/classgenerator.hpp | julienlopez/CppDependencyAnalyzer | d29065e7988ef7f553785ce7cb8bf2bb03097c66 | [
"MIT"
] | 7 | 2019-12-10T12:59:20.000Z | 2020-07-01T14:13:44.000Z | unit_tests/classgenerator.hpp | julienlopez/CppDependencyAnalyzer | d29065e7988ef7f553785ce7cb8bf2bb03097c66 | [
"MIT"
] | null | null | null | #pragma once
#include "class.hpp"
namespace Testing
{
class ClassGenerator
{
public:
explicit ClassGenerator(std::wstring class_name = L"A", std::wstring header_file_name = L"a.hpp");
~ClassGenerator() = default;
operator Cda::ClassFiles() const;
ClassGenerator& addLine(std::wstring line);
private:
const std::wstring m_class_name;
const std::wstring m_header_file_name;
std::wstring m_content;
};
std::vector<Cda::File::Line> linesFromString(const std::wstring& str);
} // namespace Testing
| 18.928571 | 102 | 0.713208 | julienlopez |
be4723f5197a44609d384533bee263f0f7a7494d | 4,825 | cpp | C++ | demo/sdk_demo_v2/SETTINGS_virtualBG_workflow.cpp | j421037/zoom | 3ba230a3ace50b7b8d722550eb320011a374f90d | [
"RSA-MD"
] | null | null | null | demo/sdk_demo_v2/SETTINGS_virtualBG_workflow.cpp | j421037/zoom | 3ba230a3ace50b7b8d722550eb320011a374f90d | [
"RSA-MD"
] | null | null | null | demo/sdk_demo_v2/SETTINGS_virtualBG_workflow.cpp | j421037/zoom | 3ba230a3ace50b7b8d722550eb320011a374f90d | [
"RSA-MD"
] | 3 | 2020-11-04T08:51:33.000Z | 2020-11-06T04:49:07.000Z | #include "stdafx.h"
#include "SETTINGS_virtualBG_workflow.h"
CSDKVirtualBGSettingsWorkFlow::CSDKVirtualBGSettingsWorkFlow()
{
m_pSettingService = NULL;
m_pVBGSettingContext = NULL;
m_pVideoSettingsContext = NULL;
m_pTestVideoDeviceHelper = NULL;
Init();
}
CSDKVirtualBGSettingsWorkFlow::~CSDKVirtualBGSettingsWorkFlow()
{
m_pSettingService = NULL;
m_pVBGSettingContext = NULL;
m_pTestVideoDeviceHelper = NULL;
m_pVideoSettingsContext = NULL;
}
ZOOM_SDK_NAMESPACE::SDKError CSDKVirtualBGSettingsWorkFlow::Init()
{
if(NULL == m_pSettingService)
{
m_pSettingService = SDKInterfaceWrap::GetInst().GetSettingService();
}
if(m_pSettingService)
{
m_pVBGSettingContext = m_pSettingService->GetVirtualBGSettings();
m_pVideoSettingsContext = m_pSettingService->GetVideoSettings();
}
if(NULL == m_pVBGSettingContext)
{
return ZOOM_SDK_NAMESPACE::SDKERR_UNINITIALIZE;
}
if(m_pVideoSettingsContext)
{
m_pTestVideoDeviceHelper = m_pVideoSettingsContext->GetTestVideoDeviceHelper();
if(m_pTestVideoDeviceHelper)
{
ZOOM_SDK_NAMESPACE::SDKError err = ZOOM_SDK_NAMESPACE::SDKERR_SUCCESS;
err = m_pTestVideoDeviceHelper->SetEvent(this);
return err;
}
}
return ZOOM_SDK_NAMESPACE::SDKERR_SUCCESS;
}
bool CSDKVirtualBGSettingsWorkFlow::IsSupportVirtualBG()
{
if(m_pVBGSettingContext)
return m_pVBGSettingContext->IsSupportVirtualBG();
return false;
}
bool CSDKVirtualBGSettingsWorkFlow::IsSupportSmartVirtualBG()
{
if(m_pVBGSettingContext)
return m_pVBGSettingContext->IsSupportSmartVirtualBG();
return false;
}
bool CSDKVirtualBGSettingsWorkFlow::IsUsingGreenScreenOn()
{
if(m_pVBGSettingContext)
return m_pVBGSettingContext->IsUsingGreenScreenOn ();
return false;
}
DWORD CSDKVirtualBGSettingsWorkFlow::GetBGReplaceColor()
{
if(m_pVBGSettingContext)
return m_pVBGSettingContext->GetBGReplaceColor();
return 0;
}
ZOOM_SDK_NAMESPACE::SDKError CSDKVirtualBGSettingsWorkFlow::SetUsingGreenScreen(bool bUse)
{
if(m_pVBGSettingContext)
{
ZOOM_SDK_NAMESPACE::SDKError err = ZOOM_SDK_NAMESPACE::SDKERR_SUCCESS;
err = m_pVBGSettingContext->SetUsingGreenScreen(bUse);
return err;
}
return ZOOM_SDK_NAMESPACE::SDKERR_UNINITIALIZE;
}
ZOOM_SDK_NAMESPACE::SDKError CSDKVirtualBGSettingsWorkFlow::AddBGImage(const wchar_t* file_path)
{
if(m_pVBGSettingContext)
{
ZOOM_SDK_NAMESPACE::SDKError err = ZOOM_SDK_NAMESPACE::SDKERR_SUCCESS;
err = m_pVBGSettingContext->AddBGImage(file_path);
return err;
}
return ZOOM_SDK_NAMESPACE::SDKERR_UNINITIALIZE;
}
ZOOM_SDK_NAMESPACE::SDKError CSDKVirtualBGSettingsWorkFlow::RemoveBGImage(ZOOM_SDK_NAMESPACE::IVirtualBGImageInfo* pRemoveImage)
{
if(m_pVBGSettingContext)
{
ZOOM_SDK_NAMESPACE::SDKError err = ZOOM_SDK_NAMESPACE::SDKERR_SUCCESS;
err = m_pVBGSettingContext->RemoveBGImage(pRemoveImage);
return err;
}
return ZOOM_SDK_NAMESPACE::SDKERR_UNINITIALIZE;
}
ZOOM_SDK_NAMESPACE::IList<ZOOM_SDK_NAMESPACE::IVirtualBGImageInfo* >* CSDKVirtualBGSettingsWorkFlow::GetBGImageList()
{
if(m_pVBGSettingContext)
{
return m_pVBGSettingContext->GetBGImageList();
}
return NULL;
}
ZOOM_SDK_NAMESPACE::SDKError CSDKVirtualBGSettingsWorkFlow::UseBGImage(ZOOM_SDK_NAMESPACE::IVirtualBGImageInfo* pImage)
{
if(m_pVBGSettingContext)
{
ZOOM_SDK_NAMESPACE::SDKError err = ZOOM_SDK_NAMESPACE::SDKERR_SUCCESS;
err = m_pVBGSettingContext->UseBGImage(pImage);
return err;
}
return ZOOM_SDK_NAMESPACE::SDKERR_UNINITIALIZE;
}
ZOOM_SDK_NAMESPACE::SDKError CSDKVirtualBGSettingsWorkFlow::BeginSelectReplaceVBColor()
{
if(m_pVBGSettingContext)
{
ZOOM_SDK_NAMESPACE::SDKError err = ZOOM_SDK_NAMESPACE::SDKERR_SUCCESS;
err = m_pVBGSettingContext->BeginSelectReplaceVBColor();
return err;
}
return ZOOM_SDK_NAMESPACE::SDKERR_UNINITIALIZE;
}
ZOOM_SDK_NAMESPACE::SDKError CSDKVirtualBGSettingsWorkFlow::SetVideoPreviewParentWnd(HWND hParentWnd, RECT rc /* = _SDK_TEST_VIDEO_INIT_RECT */)
{
if(m_pTestVideoDeviceHelper)
{
ZOOM_SDK_NAMESPACE::SDKError err = ZOOM_SDK_NAMESPACE::SDKERR_SUCCESS;
err = m_pTestVideoDeviceHelper->SetVideoPreviewParentWnd(hParentWnd,rc);
return err;
}
return ZOOM_SDK_NAMESPACE::SDKERR_UNINITIALIZE;
}
ZOOM_SDK_NAMESPACE::SDKError CSDKVirtualBGSettingsWorkFlow::TestVideoStartPreview(const wchar_t* deviceID /* = NULL */)
{
if(m_pTestVideoDeviceHelper)
{
ZOOM_SDK_NAMESPACE::SDKError err = ZOOM_SDK_NAMESPACE::SDKERR_SUCCESS;
err = m_pTestVideoDeviceHelper->TestVideoStartPreview(deviceID);
return err;
}
return ZOOM_SDK_NAMESPACE::SDKERR_UNINITIALIZE;
}
ZOOM_SDK_NAMESPACE::SDKError CSDKVirtualBGSettingsWorkFlow::TestVideoStopPreview()
{
if(m_pTestVideoDeviceHelper)
{
ZOOM_SDK_NAMESPACE::SDKError err = ZOOM_SDK_NAMESPACE::SDKERR_SUCCESS;
err = m_pTestVideoDeviceHelper->TestVideoStopPreview();
return err;
}
return ZOOM_SDK_NAMESPACE::SDKERR_UNINITIALIZE;
}
| 28.382353 | 144 | 0.813886 | j421037 |
be47515f112bca48f2482eaa5053e10ae7164f0a | 18,152 | cpp | C++ | external/vulkancts/modules/vulkan/memory_model/vktMemoryModelSharedLayoutCase.cpp | iabernikhin/VK-GL-CTS | a3338eb2ded98b5befda64f9325db0d219095a00 | [
"Apache-2.0"
] | 354 | 2017-01-24T17:12:38.000Z | 2022-03-30T07:40:19.000Z | external/vulkancts/modules/vulkan/memory_model/vktMemoryModelSharedLayoutCase.cpp | iabernikhin/VK-GL-CTS | a3338eb2ded98b5befda64f9325db0d219095a00 | [
"Apache-2.0"
] | 275 | 2017-01-24T20:10:36.000Z | 2022-03-24T16:24:50.000Z | external/vulkancts/modules/vulkan/memory_model/vktMemoryModelSharedLayoutCase.cpp | iabernikhin/VK-GL-CTS | a3338eb2ded98b5befda64f9325db0d219095a00 | [
"Apache-2.0"
] | 190 | 2017-01-24T18:02:04.000Z | 2022-03-27T13:11:23.000Z | /*------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2021 The Khronos Group Inc.
* Copyright (c) 2021 Google LLC.
*
* 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.
*
*//*!
* \file
* \brief Shared memory layout test case.
*//*--------------------------------------------------------------------*/
#include <vkDefs.hpp>
#include "deRandom.hpp"
#include "gluContextInfo.hpp"
#include "gluVarTypeUtil.hpp"
#include "tcuTestLog.hpp"
#include "vkBuilderUtil.hpp"
#include "vkMemUtil.hpp"
#include "vkQueryUtil.hpp"
#include "vkRefUtil.hpp"
#include "vkRef.hpp"
#include "vkTypeUtil.hpp"
#include "vkCmdUtil.hpp"
#include "vktMemoryModelSharedLayoutCase.hpp"
#include "util/vktTypeComparisonUtil.hpp"
namespace vkt
{
namespace MemoryModel
{
using tcu::TestLog;
using std::string;
using std::vector;
using glu::VarType;
using glu::StructMember;
namespace
{
void computeReferenceLayout (const VarType& type, vector<SharedStructVarEntry>& entries)
{
if (type.isBasicType())
entries.push_back(SharedStructVarEntry(type.getBasicType(), 1));
else if (type.isArrayType())
{
const VarType &elemType = type.getElementType();
// Array of scalars, vectors or matrices.
if (elemType.isBasicType())
entries.push_back(SharedStructVarEntry(elemType.getBasicType(), type.getArraySize()));
else
{
DE_ASSERT(elemType.isStructType() || elemType.isArrayType());
for (int i = 0; i < type.getArraySize(); i++)
computeReferenceLayout(type.getElementType(), entries);
}
}
else
{
DE_ASSERT(type.isStructType());
for (const auto& member : *type.getStructPtr())
computeReferenceLayout(member.getType(), entries);
}
}
void computeReferenceLayout (SharedStructVar& var)
{
// Top-level arrays need special care.
if (var.type.isArrayType())
computeReferenceLayout(var.type.getElementType(), var.entries);
else
computeReferenceLayout(var.type, var.entries);
}
void generateValue (const SharedStructVarEntry& entry, de::Random& rnd, vector<string>& values)
{
const glu::DataType scalarType = glu::getDataTypeScalarType(entry.type);
const int scalarSize = glu::getDataTypeScalarSize(entry.type);
const int arraySize = entry.arraySize;
const bool isMatrix = glu::isDataTypeMatrix(entry.type);
const int numVecs = isMatrix ? glu::getDataTypeMatrixNumColumns(entry.type) : 1;
const int vecSize = scalarSize / numVecs;
DE_ASSERT(scalarSize % numVecs == 0);
DE_ASSERT(arraySize >= 0);
string generatedValue;
for (int elemNdx = 0; elemNdx < arraySize; elemNdx++)
{
for (int vecNdx = 0; vecNdx < numVecs; vecNdx++)
{
for (int compNdx = 0; compNdx < vecSize; compNdx++)
{
switch (scalarType)
{
case glu::TYPE_INT:
case glu::TYPE_INT8:
case glu::TYPE_INT16:
// Fall through. This fits into all the types above.
generatedValue = de::toString(rnd.getInt(-9, 9));
break;
case glu::TYPE_UINT:
case glu::TYPE_UINT8:
case glu::TYPE_UINT16:
// Fall through. This fits into all the types above.
generatedValue = de::toString(rnd.getInt(0, 9)).append("u");
break;
case glu::TYPE_FLOAT:
case glu::TYPE_FLOAT16:
// Fall through. This fits into all the types above.
generatedValue = de::floatToString(static_cast<float>(rnd.getInt(-9, 9)), 1);
break;
case glu::TYPE_BOOL:
generatedValue = rnd.getBool() ? "true" : "false";
break;
default:
DE_ASSERT(false);
}
values.push_back(generatedValue);
}
}
}
}
string getStructMemberName (const SharedStructVar& var, const glu::TypeComponentVector& accessPath)
{
std::ostringstream name;
name << "." << var.name;
for (auto pathComp = accessPath.begin(); pathComp != accessPath.end(); pathComp++)
{
if (pathComp->type == glu::VarTypeComponent::STRUCT_MEMBER)
{
const VarType curType = glu::getVarType(var.type, accessPath.begin(), pathComp);
const glu::StructType *structPtr = curType.getStructPtr();
name << "." << structPtr->getMember(pathComp->index).getName();
}
else if (pathComp->type == glu::VarTypeComponent::ARRAY_ELEMENT)
name << "[" << pathComp->index << "]";
else
DE_ASSERT(false);
}
return name.str();
}
} // anonymous
NamedStructSP ShaderInterface::allocStruct (const string& name)
{
m_structs.emplace_back(new glu::StructType(name.c_str()));
return m_structs.back();
}
SharedStruct& ShaderInterface::allocSharedObject (const string& name, const string& instanceName)
{
m_sharedMemoryObjects.emplace_back(name, instanceName);
return m_sharedMemoryObjects.back();
}
void generateCompareFuncs (std::ostream &str, const ShaderInterface &interface)
{
std::set<glu::DataType> types;
std::set<glu::DataType> compareFuncs;
// Collect unique basic types.
for (const auto& sharedObj : interface.getSharedObjects())
for (const auto& var : sharedObj)
vkt::typecomputil::collectUniqueBasicTypes(types, var.type);
// Set of compare functions required.
for (const auto& type : types)
vkt::typecomputil::getCompareDependencies(compareFuncs, type);
for (int type = 0; type < glu::TYPE_LAST; ++type)
if (compareFuncs.find(glu::DataType(type)) != compareFuncs.end())
str << vkt::typecomputil::getCompareFuncForType(glu::DataType(type));
}
void generateSharedMemoryWrites (std::ostream &src, const SharedStruct &object,
const SharedStructVar &var, const glu::SubTypeAccess &accessPath,
vector<string>::const_iterator &valueIter, bool compare)
{
const VarType curType = accessPath.getType();
if (curType.isArrayType())
{
const int arraySize = curType.getArraySize();
for (int i = 0; i < arraySize; i++)
generateSharedMemoryWrites(src, object, var, accessPath.element(i), valueIter, compare);
}
else if (curType.isStructType())
{
const int numMembers = curType.getStructPtr()->getNumMembers();
for (int i = 0; i < numMembers; i++)
generateSharedMemoryWrites(src, object, var, accessPath.member(i), valueIter, compare);
}
else
{
DE_ASSERT(curType.isBasicType());
const glu::DataType basicType = curType.getBasicType();
const string typeName = glu::getDataTypeName(basicType);
const string sharedObjectVarName = object.getInstanceName();
const string structMember = getStructMemberName(var, accessPath.getPath());
const glu::DataType promoteType = vkt::typecomputil::getPromoteType(basicType);
int numElements = glu::getDataTypeScalarSize(basicType);
if (glu::isDataTypeMatrix(basicType))
numElements = glu::getDataTypeMatrixNumColumns(basicType) * glu::getDataTypeMatrixNumRows(basicType);
if (compare)
{
src << "\t" << "allOk" << " = " << "allOk" << " && compare_" << typeName << "(";
// Comparison functions use 32-bit values. Convert 8/16-bit scalar and vector types if necessary.
// E.g. uint8_t becomes int.
if (basicType != promoteType || numElements > 1)
src << glu::getDataTypeName(promoteType) << "(";
}
else
{
src << "\t" << sharedObjectVarName << structMember << " = " << "";
// If multiple literals or a 8/16-bit literal is assigned, the variable must be
// initialized with the constructor.
if (basicType != promoteType || numElements > 1)
src << glu::getDataTypeName(basicType) << "(";
}
for (int i = 0; i < numElements; i++)
src << (i != 0 ? ", " : "") << *valueIter++;
if (basicType != promoteType)
src << ")";
else if (numElements > 1)
src << ")";
// Write the variable in the shared memory as the next argument for the comparison function.
// Initialize it as a new 32-bit variable in the case it's a 8-bit or a 16-bit variable.
if (compare)
{
if (basicType != promoteType)
src << ", " << glu::getDataTypeName(promoteType) << "(" << sharedObjectVarName
<< structMember
<< "))";
else
src << ", " << sharedObjectVarName << structMember << ")";
}
src << ";\n";
}
}
string generateComputeShader (ShaderInterface &interface)
{
std::ostringstream src;
src << "#version 450\n";
if (interface.is16BitTypesEnabled())
src << "#extension GL_EXT_shader_explicit_arithmetic_types : enable\n";
if (interface.is8BitTypesEnabled())
src << "#extension GL_EXT_shader_explicit_arithmetic_types_int8 : enable\n";
src << "layout(local_size_x = 1) in;\n";
src << "\n";
src << "layout(std140, binding = 0) buffer block { highp uint passed; };\n";
// Output definitions for the struct fields of the shared memory objects.
std::vector<NamedStructSP>& namedStructs = interface.getStructs();
for (const auto& s: namedStructs)
src << glu::declare(s.get()) << ";\n";
// Output definitions for the shared memory structs.
for (auto& sharedObj : interface.getSharedObjects())
{
src << "struct " << sharedObj.getName() << " {\n";
for (auto& var : sharedObj)
src << "\t" << glu::declare(var.type, var.name, 1) << ";\n";
src << "};\n";
}
// Comparison utilities.
src << "\n";
generateCompareFuncs(src, interface);
src << "\n";
for (auto& sharedObj : interface.getSharedObjects())
src << "shared " << sharedObj.getName() << " " << sharedObj.getInstanceName() << ";\n";
src << "\n";
src << "void main (void) {\n";
for (auto& sharedObj : interface.getSharedObjects())
{
for (const auto& var : sharedObj)
{
vector<string>::const_iterator valueIter = var.entryValues.begin();
generateSharedMemoryWrites(src, sharedObj, var, glu::SubTypeAccess(var.type), valueIter, false);
}
}
src << "\n";
src << "\tbarrier();\n";
src << "\tmemoryBarrier();\n";
src << "\tbool allOk = true;\n";
for (auto& sharedObj : interface.getSharedObjects())
{
for (const auto& var : sharedObj)
{
vector<string>::const_iterator valueIter = var.entryValues.begin();
generateSharedMemoryWrites(src, sharedObj, var, glu::SubTypeAccess(var.type), valueIter, true);
}
}
src << "\tif (allOk)\n"
<< "\t\tpassed++;\n"
<< "\n";
src << "}\n";
return src.str();
}
void SharedLayoutCase::checkSupport(Context& context) const
{
if ((m_interface.is16BitTypesEnabled() || m_interface.is8BitTypesEnabled())
&& !context.isDeviceFunctionalitySupported("VK_KHR_shader_float16_int8"))
TCU_THROW(NotSupportedError, "VK_KHR_shader_float16_int8 extension for 16-/8-bit types not supported");
const vk::VkPhysicalDeviceVulkan12Features features = context.getDeviceVulkan12Features();
if (m_interface.is16BitTypesEnabled() && !features.shaderFloat16)
TCU_THROW(NotSupportedError, "16-bit types not supported");
if (m_interface.is8BitTypesEnabled() && !features.shaderInt8)
TCU_THROW(NotSupportedError, "8-bit types not supported");
}
tcu::TestStatus SharedLayoutCaseInstance::iterate (void)
{
const vk::DeviceInterface &vk = m_context.getDeviceInterface();
const vk::VkDevice device = m_context.getDevice();
const vk::VkQueue queue = m_context.getUniversalQueue();
const deUint32 queueFamilyIndex = m_context.getUniversalQueueFamilyIndex();
const deUint32 bufferSize = 4;
// Create descriptor set
const vk::VkBufferCreateInfo params =
{
vk::VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, // sType
DE_NULL, // pNext
0u, // flags
bufferSize, // size
vk::VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, // usage
vk::VK_SHARING_MODE_EXCLUSIVE, // sharingMode
1u, // queueFamilyCount
&queueFamilyIndex // pQueueFamilyIndices
};
vk::Move<vk::VkBuffer> buffer (vk::createBuffer(vk, device, ¶ms));
de::MovePtr<vk::Allocation> bufferAlloc (vk::bindBuffer (m_context.getDeviceInterface(), m_context.getDevice(),
m_context.getDefaultAllocator(), *buffer, vk::MemoryRequirement::HostVisible));
deMemset(bufferAlloc->getHostPtr(), 0, bufferSize);
flushMappedMemoryRange(vk, device, bufferAlloc->getMemory(), bufferAlloc->getOffset(), bufferSize);
vk::DescriptorSetLayoutBuilder setLayoutBuilder;
vk::DescriptorPoolBuilder poolBuilder;
setLayoutBuilder.addSingleBinding(vk::VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, vk::VK_SHADER_STAGE_COMPUTE_BIT);
poolBuilder.addType(vk::VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, deUint32(1));
const vk::Unique<vk::VkDescriptorSetLayout> descriptorSetLayout (setLayoutBuilder.build(vk, device));
const vk::Unique<vk::VkDescriptorPool> descriptorPool (poolBuilder.build(vk, device,
vk::VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, 1u));
const vk::VkDescriptorSetAllocateInfo allocInfo =
{
vk::VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
*descriptorPool, // VkDescriptorPool descriptorPool;
1u, // deUint32 descriptorSetCount;
&descriptorSetLayout.get(), // const VkDescriptorSetLayout *pSetLayouts;
};
const vk::Unique<vk::VkDescriptorSet> descriptorSet (allocateDescriptorSet(vk, device, &allocInfo));
const vk::VkDescriptorBufferInfo descriptorInfo = makeDescriptorBufferInfo(*buffer, 0ull, bufferSize);
vk::DescriptorSetUpdateBuilder setUpdateBuilder;
std::vector<vk::VkDescriptorBufferInfo> descriptors;
setUpdateBuilder.writeSingle(*descriptorSet, vk::DescriptorSetUpdateBuilder::Location::binding(0u),
vk::VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, &descriptorInfo);
setUpdateBuilder.update(vk, device);
const vk::VkPipelineLayoutCreateInfo pipelineLayoutParams =
{
vk::VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(vk::VkPipelineLayoutCreateFlags) 0, // VkPipelineLayoutCreateFlags flags;
1u, // deUint32 descriptorSetCount;
&*descriptorSetLayout, // const VkDescriptorSetLayout* pSetLayouts;
0u, // deUint32 pushConstantRangeCount;
DE_NULL // const VkPushConstantRange* pPushConstantRanges;
};
vk::Move<vk::VkPipelineLayout> pipelineLayout (createPipelineLayout(vk, device, &pipelineLayoutParams));
vk::Move<vk::VkShaderModule> shaderModule (createShaderModule(vk, device, m_context.getBinaryCollection().get("compute"), 0));
const vk::VkPipelineShaderStageCreateInfo pipelineShaderStageParams =
{
vk::VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(vk::VkPipelineShaderStageCreateFlags) 0, // VkPipelineShaderStageCreateFlags flags;
vk::VK_SHADER_STAGE_COMPUTE_BIT, // VkShaderStage stage;
*shaderModule, // VkShaderModule module;
"main", // const char* pName;
DE_NULL, // const VkSpecializationInfo* pSpecializationInfo;
};
const vk::VkComputePipelineCreateInfo pipelineCreateInfo =
{
vk::VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
0, // VkPipelineCreateFlags flags;
pipelineShaderStageParams, // VkPipelineShaderStageCreateInfo stage;
*pipelineLayout, // VkPipelineLayout layout;
DE_NULL, // VkPipeline basePipelineHandle;
0, // deInt32 basePipelineIndex;
};
vk::Move<vk::VkPipeline> pipeline (createComputePipeline(vk, device, DE_NULL, &pipelineCreateInfo));
vk::Move<vk::VkCommandPool> cmdPool (createCommandPool(vk, device, vk::VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, queueFamilyIndex));
vk::Move<vk::VkCommandBuffer> cmdBuffer (allocateCommandBuffer(vk, device, *cmdPool, vk::VK_COMMAND_BUFFER_LEVEL_PRIMARY));
beginCommandBuffer(vk, *cmdBuffer, 0u);
vk.cmdBindPipeline(*cmdBuffer, vk::VK_PIPELINE_BIND_POINT_COMPUTE, *pipeline);
vk.cmdBindDescriptorSets(*cmdBuffer, vk::VK_PIPELINE_BIND_POINT_COMPUTE, *pipelineLayout,
0u, 1u, &descriptorSet.get(), 0u, DE_NULL);
vk.cmdDispatch(*cmdBuffer, 1, 1, 1);
endCommandBuffer(vk, *cmdBuffer);
submitCommandsAndWait(vk, device, queue, cmdBuffer.get());
// Read back passed data
bool counterOk;
const int refCount = 1;
int resCount = 0;
invalidateAlloc(vk, device, *bufferAlloc);
resCount = *(static_cast<const int *>(bufferAlloc->getHostPtr()));
counterOk = (refCount == resCount);
if (!counterOk)
m_context.getTestContext().getLog() << TestLog::Message << "Error: passed = " << resCount
<< ", expected " << refCount << TestLog::EndMessage;
// Validate result
if (counterOk)
return tcu::TestStatus::pass("Counter value OK");
return tcu::TestStatus::fail("Counter value incorrect");
}
void SharedLayoutCase::initPrograms (vk::SourceCollections &programCollection) const
{
DE_ASSERT(!m_computeShaderSrc.empty());
programCollection.glslSources.add("compute") << glu::ComputeSource(m_computeShaderSrc);
}
TestInstance* SharedLayoutCase::createInstance (Context &context) const
{
return new SharedLayoutCaseInstance(context);
}
void SharedLayoutCase::delayedInit (void)
{
for (auto& sharedObj : m_interface.getSharedObjects())
for (auto &var : sharedObj)
computeReferenceLayout(var);
deUint32 seed = deStringHash(getName()) ^ 0xad2f7214;
de::Random rnd (seed);
for (auto& sharedObj : m_interface.getSharedObjects())
for (auto &var : sharedObj)
for (int i = 0; i < var.topLevelArraySize; i++)
for (auto &entry : var.entries)
generateValue(entry, rnd, var.entryValues);
m_computeShaderSrc = generateComputeShader(m_interface);
}
} // MemoryModel
} // vkt
| 34.707457 | 149 | 0.687032 | iabernikhin |
be487eca0271cd5326b4063632b42274629692ef | 1,363 | hpp | C++ | source/URI/Query.hpp | kurocha/uri | b920d01de5323126eaf539d4217d357b47fde64e | [
"Unlicense",
"MIT"
] | 2 | 2018-07-06T19:43:16.000Z | 2018-07-06T19:44:46.000Z | source/URI/Query.hpp | kurocha/uri | b920d01de5323126eaf539d4217d357b47fde64e | [
"Unlicense",
"MIT"
] | null | null | null | source/URI/Query.hpp | kurocha/uri | b920d01de5323126eaf539d4217d357b47fde64e | [
"Unlicense",
"MIT"
] | null | null | null | //
// Query.hpp
// File file is part of the "URI" project and released under the MIT License.
//
// Created by Samuel Williams on 17/7/2017.
// Copyright, 2017, by Samuel Williams. All rights reserved.
//
#pragma once
#include "Encoding.hpp"
#include <string>
#include <map>
namespace URI
{
/// Assumes application/x-www-form-urlencoded.
struct Query
{
std::string value;
Query() {}
template <typename ValueT>
Query(const ValueT & value_) : value(value_) {}
template <typename IteratorT>
Query(IteratorT begin, IteratorT end) : Query(Encoding::encode_query(begin, end)) {}
bool empty () const noexcept {return value.empty();}
explicit operator bool() const noexcept {return !empty();}
std::multimap<std::string, std::string> to_map() const;
Query operator+(const Query & other);
bool operator==(const Query & other) const {return value == other.value;}
bool operator!=(const Query & other) const {return value != other.value;}
bool operator<(const Query & other) const {return value < other.value;}
bool operator<=(const Query & other) const {return value <= other.value;}
bool operator>(const Query & other) const {return value > other.value;}
bool operator>=(const Query & other) const {return value >= other.value;}
};
std::ostream & operator<<(std::ostream & output, const Query & query);
}
| 28.395833 | 86 | 0.685253 | kurocha |
be4a2a539596993af1f41b575016539abd897ef6 | 1,109 | hpp | C++ | icarus/socketsfunc.hpp | Jusot/icarus | 1b908b0d7ff03d6ee088c94730acfef36101ef32 | [
"MIT"
] | 4 | 2019-04-01T10:49:54.000Z | 2020-12-24T11:46:45.000Z | icarus/socketsfunc.hpp | Jusot/Icarus | 1b908b0d7ff03d6ee088c94730acfef36101ef32 | [
"MIT"
] | null | null | null | icarus/socketsfunc.hpp | Jusot/Icarus | 1b908b0d7ff03d6ee088c94730acfef36101ef32 | [
"MIT"
] | 1 | 2019-04-04T02:36:29.000Z | 2019-04-04T02:36:29.000Z | #ifndef ICARUS_SOCKHELPER_HPP
#define ICARUS_SOCKHELPER_HPP
#include <cstdint>
#include <sys/uio.h>
namespace icarus
{
namespace sockets
{
int create_nonblocking_or_die();
int connect(int sockfd, const struct sockaddr* addr);
void bind_or_die(int sockfd, const struct sockaddr* addr);
void listen_or_die(int sockfd);
int accept(int sockfd, struct sockaddr_in* addr);
void close(int sockfd);
void shutdown_write(int sockfd);
void set_non_block_and_close_on_exec(int sockfd);
uint64_t host_to_network64(uint64_t hosst64);
uint32_t host_to_network32(uint32_t host32);
uint16_t host_to_network16(uint16_t host16);
uint64_t network_to_host64(uint64_t net64);
uint32_t network_to_host32(uint32_t net32);
uint16_t network_to_host16(uint16_t net16);
ssize_t write(int fd, const void *buf, size_t count);
ssize_t readv(int sockfd, const struct iovec *iov, int iovcnt);
int get_socket_error(int sockfd);
struct sockaddr_in get_local_addr(int sockfd);
struct sockaddr_in get_peer_addr(int sockfd);
bool is_self_connect(int sockfd);
} // namespace sockets
} // namespace icarus
#endif // ICARUS_SOCKHELPER_HPP
| 25.790698 | 63 | 0.808837 | Jusot |
be5105142969bbb610f8de19362de4913e4e2930 | 4,986 | cpp | C++ | Aula 4/a4ex1.cpp | LuisEduardoR/SCC0210-Advanced-Algorithms | 714670e87b56fcfe6f850d826a5cdd38ec7e0603 | [
"MIT"
] | null | null | null | Aula 4/a4ex1.cpp | LuisEduardoR/SCC0210-Advanced-Algorithms | 714670e87b56fcfe6f850d826a5cdd38ec7e0603 | [
"MIT"
] | null | null | null | Aula 4/a4ex1.cpp | LuisEduardoR/SCC0210-Advanced-Algorithms | 714670e87b56fcfe6f850d826a5cdd38ec7e0603 | [
"MIT"
] | null | null | null | /*
In this problem we will be considering a game played with four wheels. Digits ranging from 0 to 9
are printed consecutively (clockwise) on the periphery of each wheel. The topmost digits of the wheels
form a four-digit integer. For example, in the following figure the wheels form the integer 8056. Each
wheel has two buttons associated with it. Pressing the button marked with a left arrow rotates the
wheel one digit in the clockwise direction and pressing the one marked with the right arrow rotates it
by one digit in the opposite direction.
The game starts with an initial configuration of the wheels. Say, in the initial configuration the
topmost digits form the integer S1S2S3S4. You will be given some (say, n) forbidden configurations
Fi1 Fi2 Fi3 Fi4
(1 ≤ i ≤ n) and a target configuration T1T2T3T4. Your job will be to write a program that
can calculate the minimum number of button presses required to transform the initial configuration to
the target configuration by never passing through a forbidden one.
Input:
The first line of the input contains an integer N giving the number of test cases to follow.
The first line of each test case contains the initial configuration of the wheels specified by 4 digits.
Two consecutive digits are separated by a space. The next line contains the target configuration. The
third line contains an integer n giving the number of forbidden configurations. Each of the following n
lines contains a forbidden configuration. There is a blank line between two consecutive input sets.
Output:
For each test case in the input print a line containing the minimum number of button presses required.
If the target configuration is not reachable then print ‘-1’.
Sample Input:
2
8 0 5 6
6 5 0 8
5
8 0 5 7
8 0 4 7
5 5 0 8
7 5 0 8
6 4 0 8
0 0 0 0
5 3 1 7
8
0 0 0 1
0 0 0 9
0 0 1 0
0 0 9 0
0 1 0 0
0 9 0 0
1 0 0 0
9 0 0 0
Sample Output:
14
-1
*/
#include <iostream>
#include <vector>
#include <set>
#include <queue>
#include <string>
using namespace std;
int start, target;
set<int> forbs;
vector<int> vet[10000];
int to_number(int* arr) {
return (arr[0] * 1000) + (arr[1] * 100) + (arr[2] * 10) + arr[3];
}
bool is_forbs(int v) {
if(forbs.find(v) != forbs.end())
return true;
return false;
}
void build_graph() {
int v;
string buf;
for(int i = 0; i < 10000; i++) {
//x--- +
buf = to_string(i);
buf[0]++;
if(buf[0] == ':') buf[0] = '0';
v = stoi(buf);
if(!is_forbs(v))
vet[i].push_back(v);
//x--- -
buf = to_string(i);
buf[0]--;
if(buf[0] == '/') buf[0] = '9';
v = stoi(buf);
if(!is_forbs(v))
vet[i].push_back(v);
//-x-- +
buf = to_string(i);
buf[1]++;
if(buf[1] == ':') buf[1] = '0';
v = stoi(buf);
if(!is_forbs(v))
vet[i].push_back(v);
//-x-- -
buf = to_string(i);
buf[1]--;
if(buf[1] == '/') buf[1] = '9';
v = stoi(buf);
if(!is_forbs(v))
vet[i].push_back(v);
//--x- +
buf = to_string(i);
buf[2]++;
if(buf[2] == ':') buf[2] = '0';
v = stoi(buf);
if(!is_forbs(v))
vet[i].push_back(v);
//--x- -
buf = to_string(i);
buf[2]--;
if(buf[2] == '/') buf[2] = '9';
v = stoi(buf);
if(!is_forbs(v))
vet[i].push_back(v);
//---x +
buf = to_string(i);
buf[3]++;
if(buf[3] == ':') buf[3] = '0';
v = stoi(buf);
if(!is_forbs(v))
vet[i].push_back(v);
//---x -
buf = to_string(i);
buf[3]--;
if(buf[3] == '/') buf[3] = '9';
v = stoi(buf);
if(!is_forbs(v))
vet[i].push_back(v);
}
}
int bfs() {
int vis[10000];
for(int i = 0; i < 10000; i++) {
vis[i] = -1;
}
queue<int> q;
q.push(start);
vis[start] = 0;
int u, v;
while(!q.empty()){
u = q.front();
q.pop();
for(size_t i = 0; i < vet[u].size(); i++) {
v = vet[u][i];
if(vis[v] == -1) {
vis[v] = vis[u] + 1;
q.push(v);
}
}
}
return vis[target];
}
int main(void) {
int n;
cin >> n;
for(int i = 0; i < n; i++) {
int temp[4];
cin >> temp[0] >> temp[1] >> temp[2] >> temp[3];
start = to_number(temp);
cin >> temp[0] >> temp[1] >> temp[2] >> temp[3];
target = to_number(temp);
int f;
cin >> f;
for(int j = 0; j < f; j++) {
cin >> temp[0] >> temp[1] >> temp[2] >> temp[3];
int fbr = to_number(temp);
forbs.insert(fbr);
}
for(int k = 0; k < 10000; k++)
vet[k].clear();
build_graph();
cout << bfs() << endl;
}
} | 21.678261 | 104 | 0.529884 | LuisEduardoR |
be56e60561f98ff854f29f7a4636fda78b0f6ce8 | 647 | hpp | C++ | src/Cell.hpp | JaroslawWiosna/nonogram-solver | 5d6f9eec5b56700e2930478e67bc99b7b8951664 | [
"MIT"
] | null | null | null | src/Cell.hpp | JaroslawWiosna/nonogram-solver | 5d6f9eec5b56700e2930478e67bc99b7b8951664 | [
"MIT"
] | null | null | null | src/Cell.hpp | JaroslawWiosna/nonogram-solver | 5d6f9eec5b56700e2930478e67bc99b7b8951664 | [
"MIT"
] | null | null | null | #pragma once
#include <array>
#include <cassert>
#include <functional>
#include <iostream>
#include <memory>
#include <vector>
enum class Cell_type {
unfilled = -1,
empty,
one,
};
struct Cell {
Cell_type type = Cell_type::unfilled;
void print() const {
switch (type) {
case Cell_type::unfilled: {
std::cout << "-";
return;
}
case Cell_type::empty: {
std::cout << "x";
return;
}
case Cell_type::one: {
std::cout << "1";
return;
}
}
}
};
| 18.485714 | 41 | 0.446677 | JaroslawWiosna |
be57434d352eadefc22396c8caa40c1f7027e55d | 807 | cc | C++ | src/.unfinished/_89-gray-code.cc | q191201771/yoko_leetcode | a29b163169f409856e9c9808890bcb25ca976f78 | [
"MIT"
] | 2 | 2018-07-28T06:11:30.000Z | 2019-01-15T15:16:54.000Z | src/.unfinished/_89-gray-code.cc | q191201771/yoko_leetcode | a29b163169f409856e9c9808890bcb25ca976f78 | [
"MIT"
] | null | null | null | src/.unfinished/_89-gray-code.cc | q191201771/yoko_leetcode | a29b163169f409856e9c9808890bcb25ca976f78 | [
"MIT"
] | null | null | null | The gray code is a binary numeral system where two successive values differ in only one bit.
Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A
gray code sequence must begin with 0.
Example 1:
Input: 2
Output: [0,1,3,2]
Explanation:
00 - 0
01 - 1
11 - 3
10 - 2
For a given n, a gray code sequence may not be uniquely defined.
For example, [0,2,3,1] is also a valid gray code sequence.
00 - 0
10 - 2
11 - 3
01 - 1
Example 2:
Input: 0
Output: [0]
Explanation: We define the gray code sequence to begin with 0.
A gray code sequence of n has size = 2n, which for n = 0 the size is 20 = 1.
Therefore, for n = 0 the gray code sequence is [0].
class Solution {
public:
vector<int> grayCode(int n) {
}
};
| 20.692308 | 116 | 0.677819 | q191201771 |
be586aef943398347d424720037eeb46d868e3a7 | 632 | cpp | C++ | FlightComputerV2/src/Mount.cpp | jowallace1/FlightComputerV2 | b8ea60bd370243ef05611267cba214bf72c34f9b | [
"MIT"
] | null | null | null | FlightComputerV2/src/Mount.cpp | jowallace1/FlightComputerV2 | b8ea60bd370243ef05611267cba214bf72c34f9b | [
"MIT"
] | null | null | null | FlightComputerV2/src/Mount.cpp | jowallace1/FlightComputerV2 | b8ea60bd370243ef05611267cba214bf72c34f9b | [
"MIT"
] | null | null | null | #include "Mount.h"
Mount::Mount(double yawRatio, unsigned int yawOffset, unsigned int yawPin, double pitchRatio, unsigned int pitchOffset, unsigned int pitchPin)
: yawRatio(yawRatio), pitchRatio(pitchRatio)
{
yawServo.offset = yawOffset;
yawServo.pin = yawPin;
pitchServo.offset = pitchOffset;
pitchServo.pin = pitchPin;
}
void Mount::attach()
{
yawServo.attach();
pitchServo.attach();
}
void Mount::detach()
{
yawServo.detach();
pitchServo.detach();
}
Pair Mount::getState()
{
Pair temp;
temp.yaw = yawServo.readAngle();
temp.pitch = pitchServo.readAngle();
return temp;
} | 19.151515 | 142 | 0.683544 | jowallace1 |
be58abfad3ffe9229687fbb04fe0b7dae8b45799 | 511 | cpp | C++ | Basic/Calculate Nth Fibonacci Number/SolutionByRamneek.cpp | Mdanish777/Programmers-Community | b5ca9582fc1cd4337baa7077ff62130a1052583f | [
"MIT"
] | 261 | 2019-09-30T19:47:29.000Z | 2022-03-29T18:20:07.000Z | Basic/Calculate Nth Fibonacci Number/SolutionByRamneek.cpp | Mdanish777/Programmers-Community | b5ca9582fc1cd4337baa7077ff62130a1052583f | [
"MIT"
] | 647 | 2019-10-01T16:51:29.000Z | 2021-12-16T20:39:44.000Z | Basic/Calculate Nth Fibonacci Number/SolutionByRamneek.cpp | Mdanish777/Programmers-Community | b5ca9582fc1cd4337baa7077ff62130a1052583f | [
"MIT"
] | 383 | 2019-09-30T19:32:07.000Z | 2022-03-24T16:18:26.000Z | #include <iostream>
using namespace std;
int fibonacci(int x)
{
int a, b, c, i;
a = 0;
b = 1;
if (x == 1) {
return 0;
}
else if (x == 2) {
return 1;
}
else {
for (i = 3; i <= x; i++) {
c = a + b;
a = b;
b = c;
}
return c;
}
}
int main()
{
int n;
cout << "Enter the value of n\n";
cin >> n;
cout << n << "th Number in Fibonacci Series :- " << fibonacci(n);
return 0;
}
| 12.166667 | 69 | 0.379648 | Mdanish777 |
be6002255810de8e91e64153bd1592890cfe773b | 1,815 | cpp | C++ | code_reading/oceanbase-master/deps/oblib/src/lib/ob_name_id_def.cpp | wangcy6/weekly_read | 3a8837ee9cd957787ee1785e4066dd623e02e13a | [
"Apache-2.0"
] | null | null | null | code_reading/oceanbase-master/deps/oblib/src/lib/ob_name_id_def.cpp | wangcy6/weekly_read | 3a8837ee9cd957787ee1785e4066dd623e02e13a | [
"Apache-2.0"
] | null | null | null | code_reading/oceanbase-master/deps/oblib/src/lib/ob_name_id_def.cpp | wangcy6/weekly_read | 3a8837ee9cd957787ee1785e4066dd623e02e13a | [
"Apache-2.0"
] | 1 | 2020-10-18T12:59:31.000Z | 2020-10-18T12:59:31.000Z | /**
* Copyright (c) 2021 OceanBase
* OceanBase CE is licensed under Mulan PubL v2.
* You can use this software according to the terms and conditions of the Mulan PubL v2.
* You may obtain a copy of Mulan PubL v2 at:
* http://license.coscl.org.cn/MulanPubL-2.0
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PubL v2 for more details.
*/
#include "lib/ob_name_id_def.h"
#include <stdlib.h>
#include <string.h>
namespace oceanbase {
namespace name {
static const char* ID_NAMES[NAME_COUNT + 1];
static const char* ID_DESCRIPTIONS[NAME_COUNT + 1];
struct RuntimeIdNameMapInit {
RuntimeIdNameMapInit()
{
#define DEF_NAME(name_sym, description) ID_NAMES[name_sym] = #name_sym;
#define DEF_NAME_PAIR(name_sym, description) \
DEF_NAME(name_sym##_begin, description " begin") \
DEF_NAME(name_sym##_end, description " end")
#include "ob_name_id_def.h"
#undef DEF_NAME
#undef DEF_NAME_PAIR
#define DEF_NAME(name_sym, description) ID_DESCRIPTIONS[name_sym] = description;
#define DEF_NAME_PAIR(name_sym, description) \
DEF_NAME(name_sym##_begin, description " begin") \
DEF_NAME(name_sym##_end, description " end")
#include "ob_name_id_def.h"
#undef DEF_NAME
#undef DEF_NAME_PAIR
}
};
static RuntimeIdNameMapInit INIT;
const char* get_name(int32_t id)
{
const char* ret = NULL;
if (id < NAME_COUNT && id >= 0) {
ret = oceanbase::name::ID_NAMES[id];
}
return ret;
}
const char* get_description(int32_t id)
{
const char* ret = NULL;
if (id < NAME_COUNT && id >= 0) {
ret = oceanbase::name::ID_DESCRIPTIONS[id];
}
return ret;
}
} // namespace name
} // end namespace oceanbase
| 29.274194 | 88 | 0.720661 | wangcy6 |
41534a336201e5b58c51aa778b08dc92074aa99a | 21,709 | cpp | C++ | bindings/cpp/opencv_4/superres.cpp | bamorim/opencv-rust | d83ac457cea9540f2d535bc6158e1910ba887eea | [
"MIT"
] | null | null | null | bindings/cpp/opencv_4/superres.cpp | bamorim/opencv-rust | d83ac457cea9540f2d535bc6158e1910ba887eea | [
"MIT"
] | null | null | null | bindings/cpp/opencv_4/superres.cpp | bamorim/opencv-rust | d83ac457cea9540f2d535bc6158e1910ba887eea | [
"MIT"
] | null | null | null | #include "common.hpp"
#include <opencv2/superres.hpp>
#include "superres_types.hpp"
extern "C" {
Result<cv::Ptr<cv::superres::FrameSource>*> cv_superres_createFrameSource_Camera_int(int deviceId) {
try {
cv::Ptr<cv::superres::FrameSource> ret = cv::superres::createFrameSource_Camera(deviceId);
return Ok(new cv::Ptr<cv::superres::FrameSource>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::FrameSource>*>))
}
Result<cv::Ptr<cv::superres::FrameSource>*> cv_superres_createFrameSource_Empty() {
try {
cv::Ptr<cv::superres::FrameSource> ret = cv::superres::createFrameSource_Empty();
return Ok(new cv::Ptr<cv::superres::FrameSource>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::FrameSource>*>))
}
Result<cv::Ptr<cv::superres::FrameSource>*> cv_superres_createFrameSource_Video_CUDA_const_StringR(const char* fileName) {
try {
cv::Ptr<cv::superres::FrameSource> ret = cv::superres::createFrameSource_Video_CUDA(std::string(fileName));
return Ok(new cv::Ptr<cv::superres::FrameSource>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::FrameSource>*>))
}
Result<cv::Ptr<cv::superres::FrameSource>*> cv_superres_createFrameSource_Video_const_StringR(const char* fileName) {
try {
cv::Ptr<cv::superres::FrameSource> ret = cv::superres::createFrameSource_Video(std::string(fileName));
return Ok(new cv::Ptr<cv::superres::FrameSource>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::FrameSource>*>))
}
Result<cv::Ptr<cv::superres::BroxOpticalFlow>*> cv_superres_createOptFlow_Brox_CUDA() {
try {
cv::Ptr<cv::superres::BroxOpticalFlow> ret = cv::superres::createOptFlow_Brox_CUDA();
return Ok(new cv::Ptr<cv::superres::BroxOpticalFlow>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::BroxOpticalFlow>*>))
}
Result<cv::Ptr<cv::superres::DualTVL1OpticalFlow>*> cv_superres_createOptFlow_DualTVL1() {
try {
cv::Ptr<cv::superres::DualTVL1OpticalFlow> ret = cv::superres::createOptFlow_DualTVL1();
return Ok(new cv::Ptr<cv::superres::DualTVL1OpticalFlow>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::DualTVL1OpticalFlow>*>))
}
Result<cv::Ptr<cv::superres::DualTVL1OpticalFlow>*> cv_superres_createOptFlow_DualTVL1_CUDA() {
try {
cv::Ptr<cv::superres::DualTVL1OpticalFlow> ret = cv::superres::createOptFlow_DualTVL1_CUDA();
return Ok(new cv::Ptr<cv::superres::DualTVL1OpticalFlow>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::DualTVL1OpticalFlow>*>))
}
Result<cv::Ptr<cv::superres::FarnebackOpticalFlow>*> cv_superres_createOptFlow_Farneback() {
try {
cv::Ptr<cv::superres::FarnebackOpticalFlow> ret = cv::superres::createOptFlow_Farneback();
return Ok(new cv::Ptr<cv::superres::FarnebackOpticalFlow>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::FarnebackOpticalFlow>*>))
}
Result<cv::Ptr<cv::superres::FarnebackOpticalFlow>*> cv_superres_createOptFlow_Farneback_CUDA() {
try {
cv::Ptr<cv::superres::FarnebackOpticalFlow> ret = cv::superres::createOptFlow_Farneback_CUDA();
return Ok(new cv::Ptr<cv::superres::FarnebackOpticalFlow>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::FarnebackOpticalFlow>*>))
}
Result<cv::Ptr<cv::superres::PyrLKOpticalFlow>*> cv_superres_createOptFlow_PyrLK_CUDA() {
try {
cv::Ptr<cv::superres::PyrLKOpticalFlow> ret = cv::superres::createOptFlow_PyrLK_CUDA();
return Ok(new cv::Ptr<cv::superres::PyrLKOpticalFlow>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::PyrLKOpticalFlow>*>))
}
Result<cv::Ptr<cv::superres::SuperResolution>*> cv_superres_createSuperResolution_BTVL1() {
try {
cv::Ptr<cv::superres::SuperResolution> ret = cv::superres::createSuperResolution_BTVL1();
return Ok(new cv::Ptr<cv::superres::SuperResolution>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::SuperResolution>*>))
}
Result<cv::Ptr<cv::superres::SuperResolution>*> cv_superres_createSuperResolution_BTVL1_CUDA() {
try {
cv::Ptr<cv::superres::SuperResolution> ret = cv::superres::createSuperResolution_BTVL1_CUDA();
return Ok(new cv::Ptr<cv::superres::SuperResolution>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::SuperResolution>*>))
}
Result<double> cv_superres_BroxOpticalFlow_getAlpha_const(const cv::superres::BroxOpticalFlow* instance) {
try {
double ret = instance->getAlpha();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_BroxOpticalFlow_setAlpha_double(cv::superres::BroxOpticalFlow* instance, double val) {
try {
instance->setAlpha(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_BroxOpticalFlow_getGamma_const(const cv::superres::BroxOpticalFlow* instance) {
try {
double ret = instance->getGamma();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_BroxOpticalFlow_setGamma_double(cv::superres::BroxOpticalFlow* instance, double val) {
try {
instance->setGamma(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_BroxOpticalFlow_getScaleFactor_const(const cv::superres::BroxOpticalFlow* instance) {
try {
double ret = instance->getScaleFactor();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_BroxOpticalFlow_setScaleFactor_double(cv::superres::BroxOpticalFlow* instance, double val) {
try {
instance->setScaleFactor(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_BroxOpticalFlow_getInnerIterations_const(const cv::superres::BroxOpticalFlow* instance) {
try {
int ret = instance->getInnerIterations();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_BroxOpticalFlow_setInnerIterations_int(cv::superres::BroxOpticalFlow* instance, int val) {
try {
instance->setInnerIterations(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_BroxOpticalFlow_getOuterIterations_const(const cv::superres::BroxOpticalFlow* instance) {
try {
int ret = instance->getOuterIterations();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_BroxOpticalFlow_setOuterIterations_int(cv::superres::BroxOpticalFlow* instance, int val) {
try {
instance->setOuterIterations(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_BroxOpticalFlow_getSolverIterations_const(const cv::superres::BroxOpticalFlow* instance) {
try {
int ret = instance->getSolverIterations();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_BroxOpticalFlow_setSolverIterations_int(cv::superres::BroxOpticalFlow* instance, int val) {
try {
instance->setSolverIterations(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result_void cv_superres_DenseOpticalFlowExt_calc_const__InputArrayR_const__InputArrayR_const__OutputArrayR_const__OutputArrayR(cv::superres::DenseOpticalFlowExt* instance, const cv::_InputArray* frame0, const cv::_InputArray* frame1, const cv::_OutputArray* flow1, const cv::_OutputArray* flow2) {
try {
instance->calc(*frame0, *frame1, *flow1, *flow2);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result_void cv_superres_DenseOpticalFlowExt_collectGarbage(cv::superres::DenseOpticalFlowExt* instance) {
try {
instance->collectGarbage();
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_DualTVL1OpticalFlow_getTau_const(const cv::superres::DualTVL1OpticalFlow* instance) {
try {
double ret = instance->getTau();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_DualTVL1OpticalFlow_setTau_double(cv::superres::DualTVL1OpticalFlow* instance, double val) {
try {
instance->setTau(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_DualTVL1OpticalFlow_getLambda_const(const cv::superres::DualTVL1OpticalFlow* instance) {
try {
double ret = instance->getLambda();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_DualTVL1OpticalFlow_setLambda_double(cv::superres::DualTVL1OpticalFlow* instance, double val) {
try {
instance->setLambda(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_DualTVL1OpticalFlow_getTheta_const(const cv::superres::DualTVL1OpticalFlow* instance) {
try {
double ret = instance->getTheta();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_DualTVL1OpticalFlow_setTheta_double(cv::superres::DualTVL1OpticalFlow* instance, double val) {
try {
instance->setTheta(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_DualTVL1OpticalFlow_getScalesNumber_const(const cv::superres::DualTVL1OpticalFlow* instance) {
try {
int ret = instance->getScalesNumber();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_DualTVL1OpticalFlow_setScalesNumber_int(cv::superres::DualTVL1OpticalFlow* instance, int val) {
try {
instance->setScalesNumber(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_DualTVL1OpticalFlow_getWarpingsNumber_const(const cv::superres::DualTVL1OpticalFlow* instance) {
try {
int ret = instance->getWarpingsNumber();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_DualTVL1OpticalFlow_setWarpingsNumber_int(cv::superres::DualTVL1OpticalFlow* instance, int val) {
try {
instance->setWarpingsNumber(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_DualTVL1OpticalFlow_getEpsilon_const(const cv::superres::DualTVL1OpticalFlow* instance) {
try {
double ret = instance->getEpsilon();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_DualTVL1OpticalFlow_setEpsilon_double(cv::superres::DualTVL1OpticalFlow* instance, double val) {
try {
instance->setEpsilon(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_DualTVL1OpticalFlow_getIterations_const(const cv::superres::DualTVL1OpticalFlow* instance) {
try {
int ret = instance->getIterations();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_DualTVL1OpticalFlow_setIterations_int(cv::superres::DualTVL1OpticalFlow* instance, int val) {
try {
instance->setIterations(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<bool> cv_superres_DualTVL1OpticalFlow_getUseInitialFlow_const(const cv::superres::DualTVL1OpticalFlow* instance) {
try {
bool ret = instance->getUseInitialFlow();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<bool>))
}
Result_void cv_superres_DualTVL1OpticalFlow_setUseInitialFlow_bool(cv::superres::DualTVL1OpticalFlow* instance, bool val) {
try {
instance->setUseInitialFlow(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_FarnebackOpticalFlow_getPyrScale_const(const cv::superres::FarnebackOpticalFlow* instance) {
try {
double ret = instance->getPyrScale();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_FarnebackOpticalFlow_setPyrScale_double(cv::superres::FarnebackOpticalFlow* instance, double val) {
try {
instance->setPyrScale(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_FarnebackOpticalFlow_getLevelsNumber_const(const cv::superres::FarnebackOpticalFlow* instance) {
try {
int ret = instance->getLevelsNumber();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_FarnebackOpticalFlow_setLevelsNumber_int(cv::superres::FarnebackOpticalFlow* instance, int val) {
try {
instance->setLevelsNumber(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_FarnebackOpticalFlow_getWindowSize_const(const cv::superres::FarnebackOpticalFlow* instance) {
try {
int ret = instance->getWindowSize();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_FarnebackOpticalFlow_setWindowSize_int(cv::superres::FarnebackOpticalFlow* instance, int val) {
try {
instance->setWindowSize(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_FarnebackOpticalFlow_getIterations_const(const cv::superres::FarnebackOpticalFlow* instance) {
try {
int ret = instance->getIterations();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_FarnebackOpticalFlow_setIterations_int(cv::superres::FarnebackOpticalFlow* instance, int val) {
try {
instance->setIterations(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_FarnebackOpticalFlow_getPolyN_const(const cv::superres::FarnebackOpticalFlow* instance) {
try {
int ret = instance->getPolyN();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_FarnebackOpticalFlow_setPolyN_int(cv::superres::FarnebackOpticalFlow* instance, int val) {
try {
instance->setPolyN(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_FarnebackOpticalFlow_getPolySigma_const(const cv::superres::FarnebackOpticalFlow* instance) {
try {
double ret = instance->getPolySigma();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_FarnebackOpticalFlow_setPolySigma_double(cv::superres::FarnebackOpticalFlow* instance, double val) {
try {
instance->setPolySigma(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_FarnebackOpticalFlow_getFlags_const(const cv::superres::FarnebackOpticalFlow* instance) {
try {
int ret = instance->getFlags();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_FarnebackOpticalFlow_setFlags_int(cv::superres::FarnebackOpticalFlow* instance, int val) {
try {
instance->setFlags(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result_void cv_superres_FrameSource_nextFrame_const__OutputArrayR(cv::superres::FrameSource* instance, const cv::_OutputArray* frame) {
try {
instance->nextFrame(*frame);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result_void cv_superres_FrameSource_reset(cv::superres::FrameSource* instance) {
try {
instance->reset();
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_PyrLKOpticalFlow_getWindowSize_const(const cv::superres::PyrLKOpticalFlow* instance) {
try {
int ret = instance->getWindowSize();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_PyrLKOpticalFlow_setWindowSize_int(cv::superres::PyrLKOpticalFlow* instance, int val) {
try {
instance->setWindowSize(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_PyrLKOpticalFlow_getMaxLevel_const(const cv::superres::PyrLKOpticalFlow* instance) {
try {
int ret = instance->getMaxLevel();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_PyrLKOpticalFlow_setMaxLevel_int(cv::superres::PyrLKOpticalFlow* instance, int val) {
try {
instance->setMaxLevel(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_PyrLKOpticalFlow_getIterations_const(const cv::superres::PyrLKOpticalFlow* instance) {
try {
int ret = instance->getIterations();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_PyrLKOpticalFlow_setIterations_int(cv::superres::PyrLKOpticalFlow* instance, int val) {
try {
instance->setIterations(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result_void cv_superres_SuperResolution_setInput_const_Ptr_FrameSource_R(cv::superres::SuperResolution* instance, const cv::Ptr<cv::superres::FrameSource>* frameSource) {
try {
instance->setInput(*frameSource);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result_void cv_superres_SuperResolution_nextFrame_const__OutputArrayR(cv::superres::SuperResolution* instance, const cv::_OutputArray* frame) {
try {
instance->nextFrame(*frame);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result_void cv_superres_SuperResolution_reset(cv::superres::SuperResolution* instance) {
try {
instance->reset();
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result_void cv_superres_SuperResolution_collectGarbage(cv::superres::SuperResolution* instance) {
try {
instance->collectGarbage();
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_SuperResolution_getScale_const(const cv::superres::SuperResolution* instance) {
try {
int ret = instance->getScale();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_SuperResolution_setScale_int(cv::superres::SuperResolution* instance, int val) {
try {
instance->setScale(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_SuperResolution_getIterations_const(const cv::superres::SuperResolution* instance) {
try {
int ret = instance->getIterations();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_SuperResolution_setIterations_int(cv::superres::SuperResolution* instance, int val) {
try {
instance->setIterations(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_SuperResolution_getTau_const(const cv::superres::SuperResolution* instance) {
try {
double ret = instance->getTau();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_SuperResolution_setTau_double(cv::superres::SuperResolution* instance, double val) {
try {
instance->setTau(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_SuperResolution_getLambda_const(const cv::superres::SuperResolution* instance) {
try {
double ret = instance->getLambda();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_SuperResolution_setLambda_double(cv::superres::SuperResolution* instance, double val) {
try {
instance->setLambda(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_SuperResolution_getAlpha_const(const cv::superres::SuperResolution* instance) {
try {
double ret = instance->getAlpha();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_SuperResolution_setAlpha_double(cv::superres::SuperResolution* instance, double val) {
try {
instance->setAlpha(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_SuperResolution_getKernelSize_const(const cv::superres::SuperResolution* instance) {
try {
int ret = instance->getKernelSize();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_SuperResolution_setKernelSize_int(cv::superres::SuperResolution* instance, int val) {
try {
instance->setKernelSize(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_SuperResolution_getBlurKernelSize_const(const cv::superres::SuperResolution* instance) {
try {
int ret = instance->getBlurKernelSize();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_SuperResolution_setBlurKernelSize_int(cv::superres::SuperResolution* instance, int val) {
try {
instance->setBlurKernelSize(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_SuperResolution_getBlurSigma_const(const cv::superres::SuperResolution* instance) {
try {
double ret = instance->getBlurSigma();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_SuperResolution_setBlurSigma_double(cv::superres::SuperResolution* instance, double val) {
try {
instance->setBlurSigma(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_SuperResolution_getTemporalAreaRadius_const(const cv::superres::SuperResolution* instance) {
try {
int ret = instance->getTemporalAreaRadius();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_SuperResolution_setTemporalAreaRadius_int(cv::superres::SuperResolution* instance, int val) {
try {
instance->setTemporalAreaRadius(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<cv::Ptr<cv::superres::DenseOpticalFlowExt>*> cv_superres_SuperResolution_getOpticalFlow_const(const cv::superres::SuperResolution* instance) {
try {
cv::Ptr<cv::superres::DenseOpticalFlowExt> ret = instance->getOpticalFlow();
return Ok(new cv::Ptr<cv::superres::DenseOpticalFlowExt>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::DenseOpticalFlowExt>*>))
}
Result_void cv_superres_SuperResolution_setOpticalFlow_const_Ptr_DenseOpticalFlowExt_R(cv::superres::SuperResolution* instance, const cv::Ptr<cv::superres::DenseOpticalFlowExt>* val) {
try {
instance->setOpticalFlow(*val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
}
| 34.845907 | 298 | 0.752591 | bamorim |