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
3e0932793cd541b17d107d1d47c468a3170b96e2
1,517
cpp
C++
client/UDPClient.cpp
connest/BerkeleySockets
e3facc13150409483ab91ec373609715ac832602
[ "MIT" ]
null
null
null
client/UDPClient.cpp
connest/BerkeleySockets
e3facc13150409483ab91ec373609715ac832602
[ "MIT" ]
null
null
null
client/UDPClient.cpp
connest/BerkeleySockets
e3facc13150409483ab91ec373609715ac832602
[ "MIT" ]
null
null
null
#include "UDPClient.h" #include <iostream> #include <arpa/inet.h> #include <unistd.h> #include <cstring> UDPClient::UDPClient(const std::string &address, short port) : IClient(address, port) { memset(&server_address, 0, sizeof(server_address)); server_address.sin_family = AF_INET; server_address.sin_port = htons(port); } UDPClient::~UDPClient() { std::cout << "Close the UDP client..." <<std::endl; if(sockfd > 0) close(sockfd); } int UDPClient::init() { int res = getBindAddress(); if(res) return -1; res = bindSocket(); if(res) return -2; return 0; } int UDPClient::recv(char *buffer, int maxlength) { int length = recvfrom(sockfd, buffer, maxlength, 0, NULL, NULL); if(length < 0) { std::cerr<<"Read error"<<std::endl; return -1; } buffer[length] = 0; return length; } int UDPClient::send(const std::string &request) { return sendto(sockfd, request.data(), request.length(), 0, (struct sockaddr*)&server_address, sizeof(server_address)); } int UDPClient::getBindAddress() { int res = inet_pton(AF_INET, address.data(), &server_address.sin_addr); if(res <= 0) { std::cerr<<"inet_pton error occured" <<std::endl; return -1; } return 0; } int UDPClient::bindSocket() { sockfd = socket(PF_INET, SOCK_DGRAM, 0); if (sockfd < 0) { std::cerr<<"Error : Could not create socket" <<std::endl; return -1; } return 0; }
19.960526
77
0.607119
connest
3e09e4dd05661b82fafb4fc33c6a746ea5544951
310
cpp
C++
src/xray/shader_compiler/sources/shader_compiler_library_linkage.cpp
ixray-team/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
3
2021-10-30T09:36:14.000Z
2022-03-26T17:00:06.000Z
src/xray/shader_compiler/sources/shader_compiler_library_linkage.cpp
acidicMercury8/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
null
null
null
src/xray/shader_compiler/sources/shader_compiler_library_linkage.cpp
acidicMercury8/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:08.000Z
2022-03-26T17:00:08.000Z
//////////////////////////////////////////////////////////////////////////// // Created : 18.05.2010 // Author : Armen Abroyan // Copyright (C) GSC Game World - 2010 //////////////////////////////////////////////////////////////////////////// #include "pch.h" #include <xray/core/library_linkage.h>
34.444444
77
0.325806
ixray-team
3e0b7f9e60c94d9507bd52cf0afd05ba81479e02
201
hpp
C++
unicode_back/character_categories/punctuation_dash.hpp
do-m-en/random_regex_string
7ded2dcf7c03122a68e66b5db6f94403e8c9c690
[ "BSL-1.0" ]
null
null
null
unicode_back/character_categories/punctuation_dash.hpp
do-m-en/random_regex_string
7ded2dcf7c03122a68e66b5db6f94403e8c9c690
[ "BSL-1.0" ]
null
null
null
unicode_back/character_categories/punctuation_dash.hpp
do-m-en/random_regex_string
7ded2dcf7c03122a68e66b5db6f94403e8c9c690
[ "BSL-1.0" ]
null
null
null
#ifndef UNICODE_PUNCTUATION_DASH_HPP_INCLUDED #define UNICODE_PUNCTUATION_DASH_HPP_INCLUDED namespace unicode { // Pd class punctuation_dash { }; } #endif // UNICODE_PUNCTUATION_DASH_HPP_INCLUDED
13.4
47
0.830846
do-m-en
3e0debffd5950077536d0e6189e7c788e3474386
15,480
hpp
C++
include/hlsv/hlsv_reflect.hpp
mossseank/HLSV
5725b842ec629536a4156321ac27c926ad063590
[ "MIT" ]
null
null
null
include/hlsv/hlsv_reflect.hpp
mossseank/HLSV
5725b842ec629536a4156321ac27c926ad063590
[ "MIT" ]
null
null
null
include/hlsv/hlsv_reflect.hpp
mossseank/HLSV
5725b842ec629536a4156321ac27c926ad063590
[ "MIT" ]
null
null
null
/* * The HLSV project and all associated files and assets, including this file, are licensed under the MIT license, the * text of which can be found in the LICENSE file at the root of this project, and is available online at * (https://opensource.org/licenses/MIT). In the event of redistribution of this code, this header, or the text of * the license itself, must not be removed from the source files or assets in which they appear. * Copyright (c) 2019 Sean Moss [moss.seank@gmail.com] */ // This file declares the public reflection API functionality #pragma once #include "hlsv.hpp" #include <vector> /* Import/Export Macros */ #if !defined(HLSV_STATIC) # if defined(HLSV_COMPILER_MSVC) # if defined(_HLSV_BUILD) # define _EXPORT __declspec(dllexport) # else # define _EXPORT __declspec(dllimport) # endif // defined(_HLSV_BUILD) # else # define _EXPORT __attribute__((__visibility__("default"))) # endif // defined(HLSV_COMPILER_MSVC) #else # define _EXPORT #endif // !defined(HLSV_STATIC) namespace hlsv { // The types of shaders enum class ShaderType : uint8 { Graphics = 0 // The shader operates in the graphics pipeline }; // enum class ShaderType // Shader stages (as a bitset of flags), contains flags for all shader types, but the types shouldn't be mixed enum class ShaderStages : uint8 { None = 0x00, // Represents a bitset of no stages /// Graphics Stages Vertex = 0x01, // The vertex stage for graphics shaders TessControl = 0x02, // The tessellation control stage for graphics shaders TessEval = 0x04, // The tessellation evaluation stage for graphics shaders Geometry = 0x08, // The geometry stage for graphics shaders Fragment = 0x10, // The fragment stage for graphics shaders MinGraphics = 0x11, // A bitset representing the minimal set of stages required for a "complete" graphics shader AllGraphics = 0x1F // A bitset representing all graphics shader stages }; // enum class ShaderStages /* ShaderStages Operators */ inline ShaderStages operator | (ShaderStages l, ShaderStages r) { return (ShaderStages)((uint8)l | (uint8)r); } inline ShaderStages& operator |= (ShaderStages& l, ShaderStages r) { l = l | r; return l; } inline ShaderStages operator ^ (ShaderStages l, ShaderStages r) { return (ShaderStages)((uint8)l & ~(uint8)r); } inline ShaderStages& operator ^= (ShaderStages& l, ShaderStages r) { l = l ^ r; return l; } inline bool operator & (ShaderStages l, ShaderStages r) { return (ShaderStages)((uint8)l & (uint8)r) == r; } // Represents a record about a specific primitive HLSV type struct _EXPORT HLSVType final { public: // A listing of the primitive types enum PrimType : uint8 { Void = 0, // The special "nothing" type, only valid as a function return type (void) Error = 255, // A value used internally to represent a type error, this value will not appear in valid shaders /// Scalar/Vector Value Types Bool = 1, // A scalar boolean value (bool) Bool2 = 2, // A 2-component boolean vector (bvec2) Bool3 = 3, // A 3-component boolean vector (bvec3) Bool4 = 4, // A 4-component boolean vector (bvec4) Int = 5, // A scalar 32-bit signed integer value (int) Int2 = 6, // A 2-component 32-bit signed integer vector (ivec2) Int3 = 7, // A 3-component 32-bit signed integer vector (ivec3) Int4 = 8, // A 4-component 32-bit signed integer vector (ivec4) UInt = 9, // A scalar 32-bit unsigned integer value (uint) UInt2 = 10, // A 2-component 32-bit unsigned integer vector (uvec2) UInt3 = 11, // A 3-component 32-bit unsigned integer vector (uvec3) UInt4 = 12, // A 4-component 32-bit unsigned integer vector (uvec4) Float = 13, // A scalar 32-bit floating point value (float) Float2 = 14, // A 2-component 32-bit floating point vector (vec2) Float3 = 15, // A 3-component 32-bit floating point vector (vec3) Float4 = 16, // A 4-component 32-bit floating point vector (vec4) /// Matrix Value Types Mat2 = 150, // A square 2x2 matrix of 32-bit floating point values (mat2) Mat3 = 151, // A square 3x3 matrix of 32-bit floating point values (mat3) Mat4 = 152, // A square 4x4 matrix of 32-bit floating point values (mat4) /// Handle Types Tex1D = 200, // A 1-dimensional combined image/sampler (tex1D) Tex2D = 201, // A 2-dimensional combined image/sampler (tex2D) Tex3D = 202, // A 3-dimensional combined image/sampler (tex3D) TexCube = 203, // A cube-map combined image/sampler (texCube) Tex1DArray = 204, // An array of 1-dimensional combined image/samplers (tex1DArray) Tex2DArray = 205, // An array of 2-dimensional combined image/samplers (tex2DArray) Image1D = 206, // A 1-dimensional non-sampled storage image (image1D) Image2D = 207, // A 2-dimensional non-sampled storage image (image2D) Image3D = 208, // A 3-dimensional non-sampled storage image (image3D) Image1DArray = 209, // An array of 1-dimensional non-sampled storage images (image1DArray) Image2DArray = 210, // An array of 2-dimensional non-sampled storage images (image2DArray) SubpassInput = 211, // A texture resource that is being used as a subpass input within a renderpass }; private: static const PrimType VECTOR_TYPE_START = Bool; static const PrimType VECTOR_TYPE_END = Float4; static const PrimType MATRIX_TYPE_START = Mat2; static const PrimType MATRIX_TYPE_END = Mat4; static const PrimType HANDLE_TYPE_START = Tex1D; static const PrimType HANDLE_TYPE_END = SubpassInput; static const PrimType TEXTURE_TYPE_START = Tex1D; static const PrimType TEXTURE_TYPE_END = Tex2DArray; static const PrimType IMAGE_TYPE_START = Image1D; static const PrimType IMAGE_TYPE_END = Image2DArray; public: PrimType type; // The base primitive type bool is_array; // If the type is an array uint8 count; // The number of elements in the type, will be 1 for non-arrays, and the array size for array types union { uint8 subpass_input_index; // The index of the subpass input resource PrimType image_format; // The texel format of the storage image } extra; // Contains extra information about the type, the members will be valid only for certain types // IMPORTANT: THIS VALUE SHOULD NOT BE LARGER THAN A BYTE, OR ELSE BINARY REFLECTION WILL BREAK public: HLSVType() : type{ Void }, is_array{ false }, count{ 1 }, extra{ 0 } { } HLSVType(PrimType type) : type{ type }, is_array{ false }, count{ 1 }, extra{ 0 } { } HLSVType(PrimType type, uint8 array_size) : type{ type }, is_array{ true }, count{ array_size }, extra{ 0 } { } HLSVType(PrimType type, PrimType fmt) : type{ type }, is_array{ false }, count{ 1 }, extra{ fmt } { } HLSVType& operator = (PrimType type) { this->type = type; is_array = false; count = 1; extra = { 0 }; return *this; } inline bool is_error() const { return type == Error; } // Gets if the type represents a type error inline bool is_value_type() const { return IsValueType(type); } inline bool is_scalar_type() const { return IsScalarType(type); } inline bool is_vector_type() const { return IsVectorType(type); } inline bool is_matrix_type() const { return IsMatrixType(type); } inline bool is_handle_type() const { return IsHandleType(type); } inline bool is_texture_type() const { return IsTextureType(type); } inline bool is_image_type() const { return IsImageType(type); } inline uint8 get_component_count() const { return GetComponentCount(type); } inline PrimType get_component_type() const { return GetComponentType(type); } inline string get_type_str() const { return GetTypeStr(type); } inline uint32 get_slot_size() const { return GetSlotSize(*this); } inline bool is_integer_type() const { return IsIntegerType(type); } inline bool is_floating_point_type() const { return IsFloatingPointType(type); } inline bool is_boolean_type() const { return IsBooleanType(type); } inline static bool IsValueType(enum PrimType t) { return (t >= VECTOR_TYPE_START && t <= VECTOR_TYPE_END) || (t >= MATRIX_TYPE_START && t <= MATRIX_TYPE_END); } inline static bool IsScalarType(enum PrimType t) { return (t >= VECTOR_TYPE_START && t <= VECTOR_TYPE_END) && ((t % 4) == 1); } inline static bool IsVectorType(enum PrimType t) { return (t >= VECTOR_TYPE_START && t <= VECTOR_TYPE_END) && ((t % 4) != 1); } inline static bool IsMatrixType(enum PrimType t) { return (t >= MATRIX_TYPE_START && t <= MATRIX_TYPE_END); } inline static bool IsHandleType(enum PrimType t) { return (t >= HANDLE_TYPE_START && t <= HANDLE_TYPE_END); } inline static bool IsTextureType(enum PrimType t) { return (t >= TEXTURE_TYPE_START && t <= TEXTURE_TYPE_END); } inline static bool IsImageType(enum PrimType t) { return (t >= IMAGE_TYPE_START && t <= IMAGE_TYPE_END); } inline static uint8 GetComponentCount(enum PrimType t) { if (IsHandleType(t)) return 1u; if (IsMatrixType(t)) return (t == Mat2) ? 4u : (t == Mat3) ? 9u : 16u; return (((t - 1) % 4) + 1); } static PrimType GetComponentType(enum PrimType type); static string GetTypeStr(enum PrimType t); static uint32 GetSlotSize(HLSVType type); inline static bool IsIntegerType(enum PrimType t) { auto gc = GetComponentType(t); return IsValueType(t) && (gc != Float) && (gc != Bool); } inline static bool IsFloatingPointType(enum PrimType t) { return IsValueType(t) && (GetComponentType(t) == Float); } inline static bool IsBooleanType(enum PrimType t) { return IsValueType(t) && (GetComponentType(t) == Bool); } inline static PrimType GetMostPromotedType(enum PrimType l, enum PrimType r) { auto lc = GetComponentType(l); auto rc = GetComponentType(r); return lc > rc ? lc : rc; } inline static PrimType MakeVectorType(enum PrimType comp, uint8 count) { return (PrimType)(comp + (count - 1)); } }; // struct HLSVType /* HLSVType Operators */ inline bool operator == (HLSVType l, HLSVType r) { return l.type == r.type && l.is_array == r.is_array && l.count == r.count && l.extra.subpass_input_index == r.extra.subpass_input_index; } inline bool operator != (HLSVType l, HLSVType r) { return l.type != r.type || l.is_array != r.is_array || l.count != r.count || l.extra.subpass_input_index != r.extra.subpass_input_index; } inline bool operator == (HLSVType l, enum HLSVType::PrimType r) { return l.type == r; } inline bool operator != (HLSVType l, enum HLSVType::PrimType r) { return l.type != r; } // Contains information about a vertex attribute in a shader struct _EXPORT Attribute final { string name; // The attribute name HLSVType type; // The attribute type information uint8 location; // The binding location of the attribute uint8 slot_count; // The number of binding slots taken by the attribute Attribute(const string& name, HLSVType type, uint8 l, uint8 sc) : name{ name }, type{ type }, location{ l }, slot_count{ sc } { } }; // struct Attribute // Contains information about a fragment output in a shader struct _EXPORT Output final { string name; // The output name HLSVType type; // The output type information uint8 location; // The binding slot for the output Output(const string& name, HLSVType type, uint8 l) : name{ name }, type{ type }, location{ l } { } }; // struct Output // Contains information about a shader uniform struct _EXPORT Uniform final { string name; HLSVType type; uint8 set; uint8 binding; struct { uint8 index; // The index of the uniform block that this uniform belongs to, if applicable uint16 offset; // The offset of the uniform within its block, in bytes uint16 size; // The size of the uniform within its block, in bytes } block; // Contains block information, only valid for value-type uniforms inside of blocks Uniform(const string& name, HLSVType type, uint8 s, uint8 b, uint8 bl, uint16 o, uint16 sz) : name{ name }, type{ type }, set{ s }, binding{ b }, block{ bl, o, sz } { } }; // struct Uniform // Contains information about a shader uniform block struct _EXPORT UniformBlock final { uint8 set; uint8 binding; uint16 size; // Total size of the block in bytes bool packed; // If the members in the block are tightly packed std::vector<uint8> members; // The indices into the reflection uniforms array for the members of this block UniformBlock(uint8 s, uint8 b) : set{ s }, binding{ b }, size{ 0 }, packed{ false }, members{ } { } }; // struct UniformBlock // Contains information about a push constant struct _EXPORT PushConstant final { string name; HLSVType type; uint16 offset; uint16 size; PushConstant(const string& name, HLSVType type, uint16 o, uint16 s) : name{ name }, type{ type }, offset{ o }, size{ s } { } }; // struct PushConstant // Contains information about a specialization constant struct _EXPORT SpecConstant final { string name; HLSVType type; uint8 index; uint16 size; union { float f; // The default floating point value int32 si; // The default signed integer value uint32 ui; // The default unsigned integer value } default_value; // The default value for the spec constant SpecConstant(const string& name, HLSVType type, uint8 i, uint16 s) : name{ name }, type{ type }, index{ i }, size{ s }, default_value{ 0u } { } }; // struct SpecConstant // The core reflection type that contains all reflection information about an HSLV shader class _EXPORT ReflectionInfo final { public: uint32 tool_version; // The version of the compiler that compiled the shader uint32 shader_version; // The minimum feature version specified by the shader ShaderType shader_type; // The type of the shader ShaderStages stages; // The stages that are present in the shader std::vector<Attribute> attributes; // The vertex attributes for the shader std::vector<Output> outputs; // The fragment outputs for the shader std::vector<Uniform> uniforms; // The uniforms for the shader std::vector<UniformBlock> blocks; // The uniform blocks for the shader std::vector<PushConstant> push_constants; // The push constants for the shader std::vector<SpecConstant> spec_constants; // The specialization constants for the shader bool push_constants_packed; // If the push constants are tightly packed uint16 push_constants_size; // The total size of the push constant block, in bytes public: ReflectionInfo(ShaderType type, uint32 tv, uint32 sv); ~ReflectionInfo(); // Sorts the member vectors by binding location, info objects generated by the API will be pre-sorted void sort(); inline bool is_graphics() const { return shader_type == ShaderType::Graphics; } inline bool has_push_constants() const { return push_constants.size() > 0; } // Gets the highest binding slot that is occupied by the vertex attributes of the shader uint32 get_highest_attr_slot() const; // Gets the uniform at the given set and binding, or nullptr if there is not one const Uniform* get_uniform_at(uint32 set, uint32 binding) const; // Gets the subpass input for the given index, or nullptr if there is not one const Uniform* get_subpass_input(uint32 index) const; }; // class ReflectionInfo } // namespace hlsv // Cleanup the non-public macros #undef _EXPORT
43
138
0.702261
mossseank
3e0ee372b42dce7b782e0dd26d2b41ea9ff64021
10,726
cxx
C++
drivers/storage/volsnap/vss/modules/coord/src/reg_util.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
drivers/storage/volsnap/vss/modules/coord/src/reg_util.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
drivers/storage/volsnap/vss/modules/coord/src/reg_util.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1999 Microsoft Corporation Abstract: @doc @module reg_util.cxx | Implementation of the Registry-related functions @end Author: Adi Oltean [aoltean] 09/27/1999 TBD: Add comments. Revision History: Name Date Comments aoltean 09/27/1999 Created --*/ ///////////////////////////////////////////////////////////////////////////// // Includes #include "stdafx.hxx" #include "resource.h" #include "vssmsg.h" #include "vs_inc.hxx" // Generated file from Coord.IDL #include "vs_idl.hxx" #include "svc.hxx" #include "copy.hxx" #include "pointer.hxx" #include "enum.hxx" #include "provmgr.hxx" #include "reg_util.hxx" //////////////////////////////////////////////////////////////////////// // Standard foo for file name aliasing. This code block must be after // all includes of VSS header files. // #ifdef VSS_FILE_ALIAS #undef VSS_FILE_ALIAS #endif #define VSS_FILE_ALIAS "CORREGUC" // //////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // CVssCoordinator private methods void RecursiveDeleteKey( IN CVssFunctionTracer& ft, IN HKEY hParentKey, IN LPCWSTR wszName ) /*++ Routine Description: Deletes recursively a registry key. Arguments: IN CVssFunctionTracer& ft, // function tracer of the caller IN HKEY hParentKey, // handle to an ancestor key (like HKEY_LOCAL_MACHINE) IN LPCWSTR wszName // The key path from ancestor Remarks: Calls RecursiveDeleteSubkeys() who also calls this function --*/ { HKEY hKey; WCHAR wszFunctionName[] = L"RecursiveDeleteKey"; BS_ASSERT(ft.hr == S_OK); BS_ASSERT(hParentKey); BS_ASSERT(wszName && wszName[0] != L'\0'); // Open the key LONG lRes = ::RegOpenKeyExW( hParentKey, // IN HKEY hKey, wszName, // IN LPCWSTR lpSubKey, 0, // IN DWORD ulOptions, KEY_ALL_ACCESS, // IN REGSAM samDesired, &hKey // OUT PHKEY phkResult ); if (lRes != ERROR_SUCCESS) { if (ft.hr == S_OK) // Remember only first error ft.hr = lRes; ft.LogGenericWarning(VSSDBG_COORD, L"RegOpenKeyExW(0x%08lx,%s,...) == 0x%08lx", hParentKey, wszName, lRes); ft.Trace( VSSDBG_COORD, L"%s: Error on opening (enumerated) key with name %s. lRes == 0x%08lx", wszFunctionName, wszName, lRes ); return; } BS_ASSERT(hKey); // Recursive delete the subkeys RecursiveDeleteSubkeys( ft, hKey ); // Close the key lRes = ::RegCloseKey( hKey ); if (lRes != ERROR_SUCCESS) { if (ft.hr == S_OK) // Remember only first error ft.hr = lRes; ft.Trace( VSSDBG_COORD, L"%s: Error on closing key with name %s. lRes == 0x%08lx", wszFunctionName, wszName, lRes ); } // Delete the key lRes = ::RegDeleteKeyW( hParentKey, wszName ); switch( lRes ) { case ERROR_SUCCESS: break; case ERROR_FILE_NOT_FOUND: default: if (ft.hr == S_OK) // Remember only first error ft.hr = lRes; ft.LogGenericWarning(VSSDBG_COORD, L"RegDeleteKeyW(0x%08lx,%s) == 0x%08lx", hParentKey, wszName, lRes); ft.Trace( VSSDBG_COORD, L"%s: Error on deleting key with name %s. lRes == 0x%08lx", wszFunctionName, wszName, lRes ); } } void RecursiveDeleteSubkeys( IN CVssFunctionTracer& ft, IN HKEY hKey ) /*++ Routine Description: Deletes recursively all subkeys under a registry key. Arguments: IN CVssFunctionTracer& ft, // function tracer of the caller IN HKEY hKey, // handle to the current key Remarks: Calls RecursiveDeleteKey() for all subkeys, who also calls this function --*/ { WCHAR wszFunctionName[] = L"RecursiveDeleteSubkeys"; WCHAR wszSubKeyName[_MAX_KEYNAME_LEN]; FILETIME time; BS_ASSERT(ft.hr == S_OK); BS_ASSERT(hKey); // Enumerate all subkeys while (true) { // Fill wszSubKeyName with the name of the subkey DWORD dwSize = sizeof(wszSubKeyName)/sizeof(wszSubKeyName[0]); LONG lRes = ::RegEnumKeyExW( hKey, // IN HKEY hKey, 0, // IN DWORD dwIndex, wszSubKeyName, // OUT LPWSTR lpName, &dwSize, // IN OUT LPDWORD lpcbName, NULL, // IN LPDWORD lpReserved, NULL, // IN OUT LPWSTR lpClass, NULL, // IN OUT LPDWORD lpcbClass, &time); // OUT PFILETIME lpftLastWriteTime switch(lRes) { case ERROR_SUCCESS: BS_ASSERT(dwSize != 0); RecursiveDeleteKey( ft, hKey, wszSubKeyName ); break; // Go to Next key default: if (ft.hr == S_OK) // Remember only first error ft.hr = lRes; ft.LogGenericWarning(VSSDBG_COORD, L"RegEnumKeyExW(0x%08lx,%s,...) == 0x%08lx", hKey, wszSubKeyName, lRes); ft.Trace( VSSDBG_COORD, L"%s: Error on iteration. 0x%08lx", wszFunctionName, lRes ); case ERROR_NO_MORE_ITEMS: return; // End of iteration } } } void QueryStringValue( IN CVssFunctionTracer& ft, IN HKEY hKey, IN LPCWSTR wszKeyName, IN LPCWSTR wszValueName, IN DWORD dwValueSize, OUT LPCWSTR wszValue ) /*++ Routine Description: Get the content of a (named) value of a registry key. Intended to be called from CVssCoordinator methods. Throw some HRESULTS on error Arguments: IN CVssFunctionTracer& ft, IN HKEY hKey, // handle to the registry key IN LPCWSTR wszKeyName, // the name of the key (used only in tracing) IN LPCWSTR wszValueName, // the name of the value. Empty string for default key value. IN DWORD dwValueSize, // the size of the value buffer, in WCHARs OUT LPCWSTR wszValue // The content of that value. // The buffer must be already allocated and must have at // least dwValueSize WCHARs Remarks: The code throws an error if value name length is greater than dwValueSize-1 Throws: E_OUTOFMEMORY E_UNEXPECTED - on registry errors. An error log entry is added describing the error. --*/ { WCHAR wszFunctionName[] = L"QueryStringValue"; ft.hr = S_OK; BS_ASSERT( hKey ); BS_ASSERT( wszKeyName != NULL && wszKeyName[0] != L'\0' ); BS_ASSERT( wszValueName != NULL ); // wszValueName can be L"" BS_ASSERT( dwValueSize != 0 ); BS_ASSERT( wszValue ); ::ZeroMemory( (void*)wszValue, dwValueSize * sizeof(WCHAR) ); // Get the string content of the named key value DWORD dwType; DWORD dwDataSize = dwValueSize * sizeof(WCHAR); LPBYTE pbData = (LPBYTE)wszValue; LONG lRes = ::RegQueryValueExW ( hKey, // IN HKEY hKey, wszValueName, // IN LPCWSTR lpValueName, NULL, // IN LPDWORD lpReserved, &dwType, // OUT LPDWORD lpType, pbData, // IN OUT LPBYTE lpData, &dwDataSize // IN OUT LPDWORD lpcbData ); if ( lRes != ERROR_SUCCESS ) ft.TranslateGenericError(VSSDBG_COORD, HRESULT_FROM_WIN32(lRes), L"RegQueryValueExW(%s,%s,...)", wszKeyName, wszValueName ); // Unexpected key type if ( dwType != REG_SZ ) { ft.LogError(VSS_ERROR_WRONG_REGISTRY_TYPE_VALUE, VSSDBG_COORD << (INT)dwType << (INT)REG_SZ << wszValueName << wszKeyName ); ft.Throw( VSSDBG_COORD, E_UNEXPECTED, L"%s: The value %s in the key with name %s has not a REG_SZ type. dwType == 0x%08lx", wszFunctionName, wszValueName, wszKeyName, dwType ); } } void QueryDWORDValue( IN CVssFunctionTracer& ft, IN HKEY hKey, IN LPCWSTR wszKeyName, IN LPCWSTR wszValueName, OUT PDWORD pdwValue ) /*++ Routine Description: Get the content of a (named) value of a registry key. Intended to be called from CVssCoordinator methods. Throw some HRESULTS on error Arguments: IN CVssFunctionTracer& ft, IN HKEY hKey, // handle to the registry key IN LPCWSTR wszKeyName, // the name of the key (used only in tracing) IN LPCWSTR wszValueName, // the name of the value. Empty string for default key value. OUT PDWORD pdwValue // The content of that DWORD value. Remarks: The code throws an error if value name length is greater than dwValueSize-1 Throws: E_OUTOFMEMORY E_UNEXPECTED - on registry errors. An error log entry is added describing the error. --*/ { WCHAR wszFunctionName[] = L"QueryDWORDValue"; ft.hr = S_OK; BS_ASSERT( hKey ); BS_ASSERT( wszKeyName != NULL && wszKeyName[0] != L'\0' ); BS_ASSERT( wszValueName != NULL ); // wszValueName can be L"" BS_ASSERT( pdwValue ); (*pdwValue)=0; // Get the string content of the named key value DWORD dwType = REG_NONE; // Prefix bug 192471, still doesn't handle throw inside called functions well. DWORD dwDataSize = sizeof(DWORD); LPBYTE pbData = (LPBYTE)pdwValue; LONG lRes = ::RegQueryValueExW ( hKey, // IN HKEY hKey, wszValueName, // IN LPCWSTR lpValueName, NULL, // IN LPDWORD lpReserved, &dwType, // OUT LPDWORD lpType, pbData, // IN OUT LPBYTE lpData, &dwDataSize // IN OUT LPDWORD lpcbData ); if ( lRes != ERROR_SUCCESS ) ft.TranslateGenericError(VSSDBG_COORD, HRESULT_FROM_WIN32(lRes), L"RegQueryValueExW(%s,%s,...)", wszKeyName, wszValueName ); // Unexpected key type if ( dwType != REG_DWORD ) { ft.LogError(VSS_ERROR_WRONG_REGISTRY_TYPE_VALUE, VSSDBG_COORD << (INT)dwType << (INT)REG_DWORD << wszValueName << wszKeyName ); ft.Throw( VSSDBG_COORD, E_UNEXPECTED, L"%s: The value %s in the key with name %s has not a REG_DWORD type. dwType == 0x%08lx", wszFunctionName, wszValueName, wszKeyName, dwType ); } }
29.629834
114
0.571415
npocmaka
3e137481138fdf09e3991cecdf367f1246be62c3
1,225
cpp
C++
tests/Droplet_tests.cpp
padinadrian/droplet
921415b5fed5a19fa5d7131a79713c2e574ca0d6
[ "Apache-2.0" ]
null
null
null
tests/Droplet_tests.cpp
padinadrian/droplet
921415b5fed5a19fa5d7131a79713c2e574ca0d6
[ "Apache-2.0" ]
null
null
null
tests/Droplet_tests.cpp
padinadrian/droplet
921415b5fed5a19fa5d7131a79713c2e574ca0d6
[ "Apache-2.0" ]
null
null
null
/** * Author: Adrian Padin (padin.adrian@gmail.com) * Date: 2020/03/16 */ /* ===== Includes ===== */ #include <gtest/gtest.h> extern "C" { #include "Droplet.h" #include "BackgroundMap.h" #include "data/maps/droplet_level1_bg.c" } /* ===== Tests ===== */ TEST(Position, DropletCheckMovement) { // Initialize map BackgroundMap level1_map; level1_map.map_data = DropletBackgroundLevel1; level1_map.width = DropletBackgroundLevel1Width; level1_map.height = DropletBackgroundLevel1Height; // Droplet starting point on grid Position droplet_grid_pos = {1, 10}; // Droplet can move right, but not up, down, or left EXPECT_TRUE( DropletCheckMovement( J_RIGHT, &droplet_grid_pos, &level1_map ) ); EXPECT_FALSE( DropletCheckMovement( J_UP, &droplet_grid_pos, &level1_map ) ); EXPECT_FALSE( DropletCheckMovement( J_DOWN, &droplet_grid_pos, &level1_map ) ); EXPECT_FALSE( DropletCheckMovement( J_LEFT, &droplet_grid_pos, &level1_map ) ); }
21.12069
56
0.568163
padinadrian
3e1527f339c5acd7412cd6a7a35cb08a7ecef28a
3,959
cpp
C++
UI/GameHUD/Widget/Widget_PlayerSlowMotion.cpp
Bornsoul/Revenger_JoyContinue
599716970ca87a493bf3a959b36de0b330b318f1
[ "MIT" ]
null
null
null
UI/GameHUD/Widget/Widget_PlayerSlowMotion.cpp
Bornsoul/Revenger_JoyContinue
599716970ca87a493bf3a959b36de0b330b318f1
[ "MIT" ]
null
null
null
UI/GameHUD/Widget/Widget_PlayerSlowMotion.cpp
Bornsoul/Revenger_JoyContinue
599716970ca87a493bf3a959b36de0b330b318f1
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "Widget_PlayerSlowMotion.h" #include "../../Core/WidgetAni_Mng.h" #include "Runtime/UMG/Public/Animation/WidgetAnimation.h" #include "Kismet/KismetMathLibrary.h" void UWidget_PlayerSlowMotion::NativeConstruct() { Super::NativeConstruct(); m_pGage = Cast<UImage>(GetWidgetFromName(TEXT("Gage"))); if (m_pGage == nullptr) { ULOG(TEXT("Error UProgressBar")); } m_pGageValueText = Cast<UTextBlock>(GetWidgetFromName(TEXT("GageValue"))); if (m_pGageValueText == nullptr) { ULOG(TEXT("Error UTextBlock")); } m_pWidgetAni = NewObject<UWidgetAni_Mng>(); if (m_pWidgetAni != nullptr) { m_pWidgetAni->Init(this); } else { ULOG(TEXT("WidgetAniMng is nullptr")); return; } m_pMaterialInstance = Cast<UMaterialInterface >(m_pGage->Brush.GetResourceObject()); if (m_pMaterialInstance == nullptr) { ULOG(TEXT("Error m_pMaterialInstance")); } else { m_pMaterialDynamic = UMaterialInstanceDynamic::Create(m_pMaterialInstance, nullptr); if (m_pMaterialDynamic == nullptr) { ULOG(TEXT("Error UMaterialInstanceDynamic")); } else { m_pGage->Brush.SetResourceObject(m_pMaterialDynamic); } } ChangeSlowState(static_cast<int32>(E_State_SlowTime::E_SLOW_NONE)); } void UWidget_PlayerSlowMotion::NativeTick(const FGeometry& MyGeometry, float InDeltaTime) { Super::NativeTick(MyGeometry, InDeltaTime); switch (m_eSlowState) { case static_cast<int32>(E_State_SlowTime::E_SLOW_NONE) : SlowTick_None(InDeltaTime); break; case static_cast<int32>(E_State_SlowTime::E_SLOW_START) : SlowTick_Start(InDeltaTime); break; case static_cast<int32>(E_State_SlowTime::E_SLOW_END) : SlowTick_End(InDeltaTime); break; } if ( m_fValue <= 0.0f ) m_bEmptySlow = true; else if ( m_fValue > 0.1f ) m_bEmptySlow = false; if (m_fCurrValue_Front <= 0.0f) m_fCurrValue_Front = 0.0f; m_fCurrValue_Front = FMath::FInterpTo(m_fCurrValue_Front, m_fPerValue, InDeltaTime, 7.0f); if (m_pGage != nullptr) m_pMaterialDynamic->SetScalarParameterValue(FName(TEXT("ProgressBar")), m_fCurrValue_Front); FString sText = FString::Printf(TEXT("%d%%"), static_cast<int32>(m_fPerValue*100));// FString::FromInt(sAA) + "%"; if ( m_pGageValueText != nullptr) m_pGageValueText->SetText(FText::FromString(sText)); } void UWidget_PlayerSlowMotion::SetInit(float fGage) { m_fPerValue = fGage; m_fValue = fGage; m_fCurrValue_Front = fGage; m_bUseSlow = false; m_bEmptySlow = false; GetRootWidget()->SetVisibility(ESlateVisibility::Hidden); } void UWidget_PlayerSlowMotion::SetShow(bool bShow) { if (bShow) { if (m_eSlowState == static_cast<int32>(E_State_SlowTime::E_SLOW_NONE)) m_pWidgetAni->SetPlayAnimation("SlowShow"); } else { m_pWidgetAni->SetPlayAnimation("SlowHide"); } } void UWidget_PlayerSlowMotion::SetPercent(float fValue) { if (m_fPerValue <= 0.0f) { m_fPerValue = 0.0f; } if (m_fPerValue >= 1.0f) { m_fPerValue = 1.0f; } m_fPerValue = fValue; } void UWidget_PlayerSlowMotion::ChangeSlowState(int32 eState) { if ( eState == static_cast<int32>(E_State_SlowTime::E_SLOW_START)) GetRootWidget()->SetVisibility(ESlateVisibility::Visible); m_eSlowState = eState; } void UWidget_PlayerSlowMotion::SlowTick_None(float fDeltaTime) { if (m_bUseSlow) { SetShow(false); m_bUseSlow = false; } m_fValue = 1.0f; SetPercent(m_fValue); } void UWidget_PlayerSlowMotion::SlowTick_Start(float fDeltaTime) { if (m_fValue <= 0.0f) { m_fValue = 0.0f; ChangeSlowState(static_cast<int32>(E_State_SlowTime::E_SLOW_END)); return; } m_bUseSlow = true; m_fValue -= m_fUseSpeed * fDeltaTime; SetPercent(m_fValue); } void UWidget_PlayerSlowMotion::SlowTick_End(float fDeltaTime) { if (m_fValue >= 1.0f) { m_fValue = 1.0f; ChangeSlowState(static_cast<int32>(E_State_SlowTime::E_SLOW_NONE)); return; } m_fValue += m_fFullSpeed * fDeltaTime; SetPercent(m_fValue); }
21.994444
115
0.735034
Bornsoul
3e1cd3e9a033fa1b10782747b2d1d830fd9ec04f
1,048
cpp
C++
Editor/Source/Misc/EditorSelection.cpp
jkorn2324/jkornEngine
5822f2a311ed62e6ca495919872f0f436d300733
[ "MIT" ]
null
null
null
Editor/Source/Misc/EditorSelection.cpp
jkorn2324/jkornEngine
5822f2a311ed62e6ca495919872f0f436d300733
[ "MIT" ]
null
null
null
Editor/Source/Misc/EditorSelection.cpp
jkorn2324/jkornEngine
5822f2a311ed62e6ca495919872f0f436d300733
[ "MIT" ]
null
null
null
#include "EditorPCH.h" #include "EditorSelection.h" #include "EditorCamera.h" namespace Editor { static Engine::Entity s_selectedEntity; static bool OnEntityCreated_EditorSelection(Engine::EntityCreatedEvent& event) { return true; } static bool OnEntityDestroyed_EditorSelection(Engine::EntityDestroyedEvent& event) { if (event.entity == s_selectedEntity) { s_selectedEntity = event.entity; } return true; } Engine::Entity EditorSelection::GetSelectedEntity() { return s_selectedEntity; } void EditorSelection::SetSelectedEntity(const Engine::Entity& entity) { s_selectedEntity = entity; } bool EditorSelection::HasSelectedEntity() { return s_selectedEntity.IsValid(); } void EditorSelection::OnEvent(Engine::Event& event) { Engine::EventDispatcher dispatcher(event); dispatcher.Invoke<Engine::EntityCreatedEvent>( BIND_STATIC_EVENT_FUNCTION(OnEntityCreated_EditorSelection)); dispatcher.Invoke<Engine::EntityDestroyedEvent>( BIND_STATIC_EVENT_FUNCTION(OnEntityDestroyed_EditorSelection)); } }
23.288889
83
0.77958
jkorn2324
3e1fa805fa276a6d1adb643d4e9f37eaa8a026bc
860
cpp
C++
vm/exceptions.cpp
aidaka/KayoVM
e86ddb705ebf798f7e9f04a41ab64ca63a7f13f6
[ "MIT" ]
1
2019-12-09T02:54:51.000Z
2019-12-09T02:54:51.000Z
vm/exceptions.cpp
aidaka/KayoVM
e86ddb705ebf798f7e9f04a41ab64ca63a7f13f6
[ "MIT" ]
null
null
null
vm/exceptions.cpp
aidaka/KayoVM
e86ddb705ebf798f7e9f04a41ab64ca63a7f13f6
[ "MIT" ]
null
null
null
/* * Author: kayo */ #include <cstdlib> #include "exceptions.h" #include "interpreter/interpreter.h" #include "rtda/heap/StringObject.h" #include "loader/bootstrap_class_loader.h" #include "rtda/ma/Class.h" #define EXCEPTION_EXIT (-1) [[noreturn]] void raiseException(const char *exceptionName, const char *msg) { assert(exceptionName != nullptr); Class *c = bootClassLoader->loadClass(exceptionName); c->clinit(); jref o = Object::newInst(c); if (msg == nullptr) { execJavaFunc(c->getConstructor("()V"), o); } else { execJavaFunc(c->getConstructor("(Ljava/lang/String;)V"), { (slot_t) o, (slot_t) StringObject::newInst(msg) }); } // public void printStackTrace() auto printStackTrace = c->lookupInstMethod("printStackTrace", "()V"); execJavaFunc(printStackTrace, o); exit(EXCEPTION_EXIT); }
26.060606
118
0.67093
aidaka
4a3d73bb232e353024018ef8732bf6854029ba90
3,565
cxx
C++
Wells/Widgets/qMRMLMarkupsWellWidget.cxx
tierra-colada/ColadaWells
3dbad8ac5a9acbf767a443eeb0d2698494bfb6e4
[ "MIT" ]
null
null
null
Wells/Widgets/qMRMLMarkupsWellWidget.cxx
tierra-colada/ColadaWells
3dbad8ac5a9acbf767a443eeb0d2698494bfb6e4
[ "MIT" ]
null
null
null
Wells/Widgets/qMRMLMarkupsWellWidget.cxx
tierra-colada/ColadaWells
3dbad8ac5a9acbf767a443eeb0d2698494bfb6e4
[ "MIT" ]
null
null
null
/*============================================================================== Copyright (c) The Intervention Centre Oslo University Hospital, Oslo, Norway. All Rights Reserved. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. 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. This file was originally developed by Rafael Palomar (The Intervention Centre, Oslo University Hospital) and was supported by The Research Council of Norway through the ALive project (grant nr. 311393). ==============================================================================*/ #include "qMRMLMarkupsWellWidget.h" #include "ui_qMRMLMarkupsWellWidget.h" // MRML Nodes includes #include "vtkMRMLMarkupsWellNode.h" // VTK includes #include <vtkWeakPointer.h> // -------------------------------------------------------------------------- class qMRMLMarkupsWellWidgetPrivate: public Ui_qMRMLMarkupsWellWidget { Q_DECLARE_PUBLIC(qMRMLMarkupsWellWidget); protected: qMRMLMarkupsWellWidget* const q_ptr; public: qMRMLMarkupsWellWidgetPrivate(qMRMLMarkupsWellWidget* object); void setupUi(qMRMLMarkupsWellWidget*); vtkWeakPointer<vtkMRMLMarkupsWellNode> MarkupsWellNode; }; // -------------------------------------------------------------------------- qMRMLMarkupsWellWidgetPrivate:: qMRMLMarkupsWellWidgetPrivate(qMRMLMarkupsWellWidget* object) : q_ptr(object) { } // -------------------------------------------------------------------------- void qMRMLMarkupsWellWidgetPrivate::setupUi(qMRMLMarkupsWellWidget* widget) { Q_Q(qMRMLMarkupsWellWidget); this->Ui_qMRMLMarkupsWellWidget::setupUi(widget); this->wellTestCollapsibleButton->setVisible(false); } // -------------------------------------------------------------------------- qMRMLMarkupsWellWidget:: qMRMLMarkupsWellWidget(QWidget *parent) : Superclass(parent), d_ptr(new qMRMLMarkupsWellWidgetPrivate(this)) { this->setup(); } // -------------------------------------------------------------------------- qMRMLMarkupsWellWidget::~qMRMLMarkupsWellWidget() = default; // -------------------------------------------------------------------------- void qMRMLMarkupsWellWidget::setup() { Q_D(qMRMLMarkupsWellWidget); d->setupUi(this); } // -------------------------------------------------------------------------- void qMRMLMarkupsWellWidget::updateWidgetFromMRML() { Q_D(qMRMLMarkupsWellWidget); if (!this->canManageMRMLMarkupsNode(d->MarkupsWellNode)) { d->wellTestCollapsibleButton->setVisible(false); return; } d->wellTestCollapsibleButton->setVisible(true); } //----------------------------------------------------------------------------- bool qMRMLMarkupsWellWidget::canManageMRMLMarkupsNode(vtkMRMLMarkupsNode *markupsNode) const { Q_D(const qMRMLMarkupsWellWidget); vtkMRMLMarkupsWellNode* wellNode= vtkMRMLMarkupsWellNode::SafeDownCast(markupsNode); if (!wellNode) { return false; } return true; } // -------------------------------------------------------------------------- void qMRMLMarkupsWellWidget::setMRMLMarkupsNode(vtkMRMLMarkupsNode* markupsNode) { Q_D(qMRMLMarkupsWellWidget); d->MarkupsWellNode = vtkMRMLMarkupsWellNode::SafeDownCast(markupsNode); this->setEnabled(markupsNode != nullptr); }
30.211864
92
0.597195
tierra-colada
4a419b245489a7a1facbb4189dfe76de15a0dfda
5,424
cpp
C++
Examples/SetVarDefExample.cpp
alwinw/Janus
d80ec94af69e17e41718b94eea91e5419e600da2
[ "MIT" ]
7
2020-04-07T20:05:03.000Z
2022-02-04T10:36:28.000Z
Examples/SetVarDefExample.cpp
alwinw/Janus
d80ec94af69e17e41718b94eea91e5419e600da2
[ "MIT" ]
null
null
null
Examples/SetVarDefExample.cpp
alwinw/Janus
d80ec94af69e17e41718b94eea91e5419e600da2
[ "MIT" ]
1
2022-02-12T10:17:51.000Z
2022-02-12T10:17:51.000Z
// // DST Janus Library (Janus DAVE-ML Interpreter Library) // // Defence Science and Technology (DST) Group // Department of Defence, Australia. // 506 Lorimer St // Fishermans Bend, VIC // AUSTRALIA, 3207 // // Copyright 2005-2019 Commonwealth of Australia // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, // merge, publish, distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be included in all copies // or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT // OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // #include <iostream> #include <Ute/aString.h> #include <Janus/Janus.h> using namespace std; using namespace janus; using namespace dstomath; using namespace dstoute; const aString XMLFile = "SetVarDefExample.xml"; void example00() { Janus janus( XMLFile); VariableDef& input00 = janus.getVariableDef( "input00"); const VariableDef& output00 = janus.getVariableDef( "output00"); input00.setValue( 15.0); cout << "Output value: " << output00.getValue() << " (expected: 19)" << endl; } void example01() { Janus janus( XMLFile); const VariableDef& incrementer = janus.getVariableDef( "incrementer"); const VariableDef& output01 = janus.getVariableDef( "output01"); incrementer.getValue(); // Compiles expression cout << "Output value: " << output01.getValue() << " (expected: 6)" << endl; incrementer.getValue(); cout << "Output value: " << output01.getValue() << " (expected: 9)" << endl; incrementer.getValue(); cout << "Output value: " << output01.getValue() << " (expected: 12)" << endl; } void example02() { Janus janus( XMLFile); VariableDef& input02 = janus.getVariableDef( "input02"); const VariableDef& output02 = janus.getVariableDef( "output02"); const VariableDef& function02 = janus.getVariableDef( "function02"); input02.setValue( 42.0); function02.getValue(); cout << "Output value: " << output02.getValue() << " (expected: 42)" << endl; } void example03() { Janus janus( XMLFile); VariableDef& input03 = janus.getVariableDef( "input03"); const VariableDef& output03_00 = janus.getVariableDef( "output03_00"); const VariableDef& function03 = janus.getVariableDef( "function03"); input03.setValue( 123.456); function03.getValue(); cout << "Output value: " << output03_00.getValue() << " (expected: 123.456)" << endl; } void example04() { Janus janus( XMLFile); const VariableDef& function04_00 = janus.getVariableDef( "function04_00"); const VariableDef& function04_01 = janus.getVariableDef( "function04_01"); cout << "Output value: " << function04_00.getValue() << " (expected: 56.78)" << endl; cout << "Output value: " << function04_01.getValue() << " (expected: 56.78)" << endl; } void example05() { Janus janus( XMLFile); const VariableDef& output05_00 = janus.getVariableDef( "output05_00"); const VariableDef& output05_01 = janus.getVariableDef( "output05_01"); cout << "Output value: " << output05_00.getValue() << " (expected: 0.0)" << endl; cout << "Output value: " << output05_01.getValue() << " (expected: 40.0)" << endl; } void example06() { Janus janus( XMLFile); const VariableDef& output06_00 = janus.getVariableDef( "output06_00"); const VariableDef& output06_01 = janus.getVariableDef( "output06_01"); const VariableDef& output06_02 = janus.getVariableDef( "output06_02"); const VariableDef& output06_03 = janus.getVariableDef( "output06_03"); const VariableDef& internal06_00 = janus.getVariableDef( "internal06_00"); const VariableDef& internal06_01 = janus.getVariableDef( "internal06_01"); const VariableDef& internal06_02 = janus.getVariableDef( "internal06_02"); const VariableDef& internal06_21 = janus.getVariableDef( "internal06_21"); cout << "Output value: " << output06_00.getValue() << " (expected: 2704.0)" << endl; cout << "Output value: " << internal06_00.getValue() << " (expected: 0.0)" << endl; cout << "Output value: " << output06_01.getValue() << " (expected: 52.0)" << endl; cout << "Output value: " << internal06_01.getValue() << " (expected: 0.0)" << endl; cout << "Output value: " << output06_02.getValue() << " (expected: 52.0)" << endl; cout << "Output value: " << internal06_02.getValue() << " (expected: 0.0)" << endl; cout << "Output value: " << output06_03.getValue() << " (expected: 231.0)" << endl; cout << "Output value: " << internal06_21.getValue() << " (expected: 0.0)" << endl; } int main( int, char **) { example00(); example01(); example02(); example03(); example04(); example05(); example06(); return 0; }
35.45098
91
0.688975
alwinw
4a439ca093c442481cfbaa4b81199266bc2a32d1
4,735
cpp
C++
booster/lib/shared_object/src/shared_object.cpp
gatehouse/cppcms
61da055ffeb349b4eda14bc9ac393af9ce842364
[ "MIT" ]
388
2017-03-01T07:39:21.000Z
2022-03-30T19:38:41.000Z
booster/lib/shared_object/src/shared_object.cpp
gatehouse/cppcms
61da055ffeb349b4eda14bc9ac393af9ce842364
[ "MIT" ]
81
2017-03-08T20:28:00.000Z
2022-01-23T08:19:31.000Z
booster/lib/shared_object/src/shared_object.cpp
gatehouse/cppcms
61da055ffeb349b4eda14bc9ac393af9ce842364
[ "MIT" ]
127
2017-03-05T21:53:40.000Z
2022-02-25T02:31:01.000Z
#define BOOSTER_SOURCE #include <booster/shared_object.h> #include <booster/backtrace.h> #include <booster/build_config.h> #include <booster/nowide/convert.h> #ifdef BOOSTER_WIN_NATIVE #include <windows.h> #include <booster/system_error.h> #else #include <dlfcn.h> #endif #include <iostream> namespace booster { #ifdef BOOSTER_WIN_NATIVE struct shared_object::data { HMODULE handle; data() : handle(0) {} ~data() { if(handle) FreeLibrary(handle); } }; shared_object::shared_object() : d(new data()) { } shared_object::~shared_object() { } shared_object::shared_object(std::string const &name,int) : d(new data()) { std::string err; if(!open(name,err)) { throw booster::runtime_error("booster::shared_object: failed to load shared library " + name +": " + err); } } shared_object::shared_object(std::string const &name) : d(new data()) { std::string err; if(!open(name,err)) { throw booster::runtime_error("booster::shared_object: failed to load shared library " + name +": " + err); } } void shared_object::close() { if(d->handle) { FreeLibrary(d->handle); d->handle = 0; } } bool shared_object::is_open() const { return d->handle != 0; } bool shared_object::open(std::string const &file_name,int) { return open(file_name); } bool shared_object::open(std::string const &file_name) { close(); d->handle = LoadLibraryW(booster::nowide::convert(file_name).c_str()); return d->handle != 0; } bool shared_object::open(std::string const &file_name,std::string &error_message,int) { return open(file_name,error_message); } bool shared_object::open(std::string const &file_name,std::string &error_message) { if(open(file_name)) return true; booster::system::error_code e(GetLastError(),booster::system::system_category); error_message = e.message(); return false; } void *shared_object::resolve_symbol(std::string const &name) const { if(!is_open()) throw booster::runtime_error("booster::shared_object::resolve_symbol: the shared_object is not open!"); return reinterpret_cast<void*>(GetProcAddress(d->handle,name.c_str())); } #else struct shared_object::data { void *handle; data() : handle(0) {} ~data() { if(handle) dlclose(handle); } }; shared_object::shared_object() : d(new data()) { } shared_object::~shared_object() { } shared_object::shared_object(std::string const &name,int flags) : d(new data()) { std::string err; if(!open(name,err,flags)) { throw booster::runtime_error("booster::shared_object: failed to load shared library " + name +": " + err); } } shared_object::shared_object(std::string const &name) : d(new data()) { std::string err; if(!open(name,err)) { throw booster::runtime_error("booster::shared_object: failed to load shared library " + name +": " + err); } } void shared_object::close() { if(d->handle) { dlclose(d->handle); d->handle = 0; } } bool shared_object::is_open() const { return d->handle != 0; } bool shared_object::open(std::string const &file_name) { return open(file_name,load_lazy); } bool shared_object::open(std::string const &file_name,int flags) { std::string msg; return open(file_name,msg,flags); } bool shared_object::open(std::string const &file_name,std::string &error_message) { return open(file_name,error_message,load_lazy); } bool shared_object::open(std::string const &file_name,std::string &error_message,int flags) { close(); int dlflags = 0; if(flags & load_lazy) dlflags |= RTLD_LAZY; if(flags & load_now) dlflags |= RTLD_NOW; if(flags & load_global) dlflags |= RTLD_GLOBAL; if(flags & load_local) dlflags |= RTLD_LOCAL; d->handle = dlopen(file_name.c_str(),dlflags); if(!d->handle) { error_message = dlerror(); return false; } return true; } void *shared_object::resolve_symbol(std::string const &name) const { if(!is_open()) throw booster::runtime_error("booster::shared_object::resolve_symbol: the shared_object is not open!"); return dlsym(d->handle,name.c_str()); } #endif #ifndef BOOSTER_LIBRARY_PREFIX #define BOOSTER_LIBRARY_PREFIX "" #endif std::string shared_object::name(std::string const &module) { return BOOSTER_LIBRARY_PREFIX + module + BOOSTER_LIBRARY_SUFFIX; } std::string shared_object::name(std::string const &module,std::string const &soversion) { #if defined __APPLE__ return BOOSTER_LIBRARY_PREFIX + module + "." + soversion + BOOSTER_LIBRARY_SUFFIX; #elif defined BOOSTER_WIN32 return BOOSTER_LIBRARY_PREFIX + module + "-" + soversion + BOOSTER_LIBRARY_SUFFIX; #else return BOOSTER_LIBRARY_PREFIX + module + BOOSTER_LIBRARY_SUFFIX + "." + soversion; #endif } } // booster
25.320856
109
0.692291
gatehouse
4a4471bdccd0f3b818af66840c59cf4a9dcd7661
2,679
hpp
C++
library/utility/byte.hpp
SJSURoboticsTeam/urc-control_systems-2020
35dff34c1bc0beecc94ad6b8f2d4b551969c6854
[ "Apache-2.0" ]
1
2020-02-22T20:26:41.000Z
2020-02-22T20:26:41.000Z
library/utility/byte.hpp
SJSURoboticsTeam/urc-control_systems-2020
35dff34c1bc0beecc94ad6b8f2d4b551969c6854
[ "Apache-2.0" ]
null
null
null
library/utility/byte.hpp
SJSURoboticsTeam/urc-control_systems-2020
35dff34c1bc0beecc94ad6b8f2d4b551969c6854
[ "Apache-2.0" ]
4
2019-10-17T03:42:03.000Z
2020-05-23T20:32:03.000Z
#pragma once #include <algorithm> #include <array> #include <bit> #include <climits> #include <cstdint> #include <span> namespace sjsu { template <typename T, size_t array_size = sizeof(T)> constexpr auto ToByteArray(std::endian endian, T value) { std::array<uint8_t, array_size> array = {}; static_assert(std::is_integral_v<T>, "Type T (the return type) must be intergal type."); if constexpr (std::is_integral_v<T>) { if (endian == std::endian::little) { for (size_t i = 0; i < array.size(); i++) { auto next_byte = value >> ((CHAR_BIT * i) & 0xFF); array.begin()[i] = static_cast<uint8_t>(next_byte); } } else { for (size_t i = 0; i < array.size(); i++) { auto next_byte = value >> ((CHAR_BIT * i) & 0xFF); array.rbegin()[i] = static_cast<uint8_t>(next_byte); } } } return array; } template <size_t N> constexpr auto ByteArrayToSpan(std::endian endian, const std::array<uint8_t, N> & bytes, size_t width) { if (endian == std::endian::big) { return std::span<const uint8_t>(&bytes.end()[-width], width); } else { return std::span<const uint8_t>(bytes.data(), width); } } template <typename T> constexpr auto ToInteger(std::endian endian, std::span<const uint8_t> array) { static_assert(std::is_integral_v<T>, "Type T (the return type) must be intergal type."); T value = 0; if constexpr (std::is_integral_v<T>) { size_t end = std::min(sizeof(T), array.size()); if (endian == std::endian::little) { for (size_t i = 0; i < end; i++) { auto or_value = static_cast<T>(array.begin()[i]) << (CHAR_BIT * i); value = static_cast<T>(value | or_value); } } else { for (size_t i = 0; i < end; i++) { auto or_value = static_cast<T>(array.rbegin()[i]) << (CHAR_BIT * i); value = static_cast<T>(value | or_value); } } } return value; } template <typename T, size_t N> constexpr auto ToIntegerArray(std::endian endian, std::span<const uint8_t> bytes) { static_assert(std::is_integral_v<T>, "Type T (the return type) must be intergal type."); std::array<T, N> value = { 0 }; std::span<const uint8_t> byte_span; if constexpr (std::is_integral_v<T>) { for (size_t i = 0; i < bytes.size(); i += sizeof(T)) { byte_span = bytes.subspan(i, sizeof(T)); value[i / sizeof(T)] = ToInteger<T>(endian, byte_span); } } return value; } } // namespace sjsu
25.273585
76
0.562897
SJSURoboticsTeam
4a4499dd57b31069a8775c28f34832d24a4d1c3a
12,270
cc
C++
src/test-string-view.cc
okuoku/wabt
3dc09d11ff4396c9a4cf903cae2ed6a88f5982b6
[ "Apache-2.0" ]
8,664
2016-01-13T17:33:19.000Z
2019-05-06T19:55:36.000Z
src/test-string-view.cc
okuoku/wabt
3dc09d11ff4396c9a4cf903cae2ed6a88f5982b6
[ "Apache-2.0" ]
5,058
2016-01-13T17:57:02.000Z
2019-05-04T15:41:54.000Z
src/test-string-view.cc
okuoku/wabt
3dc09d11ff4396c9a4cf903cae2ed6a88f5982b6
[ "Apache-2.0" ]
1,367
2016-01-13T17:54:57.000Z
2019-04-29T18:16:27.000Z
/* * Copyright 2017 WebAssembly Community Group participants * * 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 "gtest/gtest.h" #include "src/string-view.h" #include <cstring> #include <functional> using namespace wabt; namespace { void assert_string_view_eq(const char* s, string_view sv) { size_t len = std::strlen(s); ASSERT_EQ(len, sv.size()); for (size_t i = 0; i < len; ++i) { ASSERT_EQ(s[i], sv[i]); } } constexpr string_view::size_type npos = string_view::npos; } // end anonymous namespace TEST(string_view, default_constructor) { assert_string_view_eq("", string_view()); } TEST(string_view, copy_constructor) { string_view sv1("copy"); assert_string_view_eq("copy", string_view(sv1)); string_view sv2; assert_string_view_eq("", string_view(sv2)); } TEST(string_view, assignment_operator) { string_view sv1; sv1 = string_view("assign"); assert_string_view_eq("assign", sv1); string_view sv2; sv2 = string_view(); assert_string_view_eq("", sv2); } TEST(string_view, string_constructor) { assert_string_view_eq("", string_view(std::string())); assert_string_view_eq("string", string_view(std::string("string"))); } TEST(string_view, cstr_constructor) { assert_string_view_eq("", string_view("")); assert_string_view_eq("cstr", string_view("cstr")); } TEST(string_view, cstr_len_constructor) { assert_string_view_eq("", string_view("foo-bar-baz", 0)); assert_string_view_eq("foo", string_view("foo-bar-baz", 3)); assert_string_view_eq("foo-bar", string_view("foo-bar-baz", 7)); } TEST(string_view, begin_end) { string_view sv("012345"); char count = 0; for (auto iter = sv.begin(), end = sv.end(); iter != end; ++iter) { ASSERT_EQ('0' + count, *iter); ++count; } ASSERT_EQ(6, count); } TEST(string_view, cbegin_cend) { const string_view sv("012345"); char count = 0; for (auto iter = sv.cbegin(), end = sv.cend(); iter != end; ++iter) { ASSERT_EQ('0' + count, *iter); ++count; } ASSERT_EQ(6, count); } TEST(string_view, rbegin_rend) { string_view sv("012345"); char count = 0; for (auto iter = sv.rbegin(), end = sv.rend(); iter != end; ++iter) { ASSERT_EQ('5' - count, *iter); ++count; } ASSERT_EQ(6, count); } TEST(string_view, crbegin_crend) { const string_view sv("012345"); char count = 0; for (auto iter = sv.crbegin(), end = sv.crend(); iter != end; ++iter) { ASSERT_EQ('5' - count, *iter); ++count; } ASSERT_EQ(6, count); } TEST(string_view, size) { string_view sv1; ASSERT_EQ(0U, sv1.size()); string_view sv2(""); ASSERT_EQ(0U, sv2.size()); string_view sv3("hello"); ASSERT_EQ(5U, sv3.size()); } TEST(string_view, length) { string_view sv1; ASSERT_EQ(0U, sv1.length()); string_view sv2("hello"); ASSERT_EQ(5U, sv2.length()); } TEST(string_view, empty) { string_view sv1; ASSERT_TRUE(sv1.empty()); string_view sv2("bye"); ASSERT_FALSE(sv2.empty()); } TEST(string_view, operator_bracket) { string_view sv("words"); ASSERT_EQ('w', sv[0]); ASSERT_EQ('o', sv[1]); ASSERT_EQ('r', sv[2]); ASSERT_EQ('d', sv[3]); ASSERT_EQ('s', sv[4]); } TEST(string_view, at) { string_view sv("words"); ASSERT_EQ('w', sv.at(0)); ASSERT_EQ('o', sv.at(1)); ASSERT_EQ('r', sv.at(2)); ASSERT_EQ('d', sv.at(3)); ASSERT_EQ('s', sv.at(4)); } TEST(string_view, front) { string_view sv("words"); ASSERT_EQ('w', sv.front()); } TEST(string_view, back) { string_view sv("words"); ASSERT_EQ('s', sv.back()); } TEST(string_view, data) { const char* cstr = "words"; string_view sv(cstr); ASSERT_EQ(cstr, sv.data()); } TEST(string_view, remove_prefix) { string_view sv("words"); sv.remove_prefix(2); assert_string_view_eq("rds", sv); } TEST(string_view, remove_suffix) { string_view sv("words"); sv.remove_suffix(2); assert_string_view_eq("wor", sv); } TEST(string_view, swap) { string_view sv1("hello"); string_view sv2("bye"); sv1.swap(sv2); assert_string_view_eq("bye", sv1); assert_string_view_eq("hello", sv2); } TEST(string_view, operator_std_string) { string_view sv1("hi"); std::string s(sv1); ASSERT_EQ(2U, s.size()); ASSERT_EQ('h', s[0]); ASSERT_EQ('i', s[1]); } TEST(string_view, copy) { string_view sv("words"); char buffer[10] = {0}; sv.copy(buffer, 10, 2); ASSERT_EQ('r', buffer[0]); ASSERT_EQ('d', buffer[1]); ASSERT_EQ('s', buffer[2]); for (int i = 3; i < 10; ++i) { ASSERT_EQ(0, buffer[i]); } } TEST(string_view, substr) { string_view sv1("abcdefghij"); string_view sv2 = sv1.substr(2, 3); assert_string_view_eq("cde", sv2); } TEST(string_view, compare0) { ASSERT_TRUE(string_view("meat").compare(string_view("meet")) < 0); ASSERT_TRUE(string_view("rest").compare(string_view("rate")) > 0); ASSERT_TRUE(string_view("equal").compare(string_view("equal")) == 0); ASSERT_TRUE(string_view("star").compare(string_view("start")) < 0); ASSERT_TRUE(string_view("finished").compare(string_view("fin")) > 0); } TEST(string_view, compare1) { ASSERT_TRUE(string_view("abcdef").compare(2, 2, string_view("ca")) > 0); ASSERT_TRUE(string_view("abcdef").compare(2, 2, string_view("cd")) == 0); ASSERT_TRUE(string_view("abcdef").compare(2, 2, string_view("cz")) < 0); } TEST(string_view, compare2) { ASSERT_TRUE(string_view("abcdef").compare(2, 2, string_view("_ca__"), 1, 2) > 0); ASSERT_TRUE(string_view("abcdef").compare(2, 2, string_view("_cd__"), 1, 2) == 0); ASSERT_TRUE(string_view("abcdef").compare(2, 2, string_view("_cz__"), 1, 2) < 0); } TEST(string_view, compare3) { ASSERT_TRUE(string_view("abcdef").compare("aaaa") > 0); ASSERT_TRUE(string_view("abcdef").compare("abcdef") == 0); ASSERT_TRUE(string_view("abcdef").compare("zzzz") < 0); } TEST(string_view, compare4) { ASSERT_TRUE(string_view("abcdef").compare(2, 2, "ca") > 0); ASSERT_TRUE(string_view("abcdef").compare(2, 2, "cd") == 0); ASSERT_TRUE(string_view("abcdef").compare(2, 2, "cz") < 0); } TEST(string_view, compare5) { ASSERT_TRUE(string_view("abcdef").compare(2, 2, "ca____", 2) > 0); ASSERT_TRUE(string_view("abcdef").compare(2, 2, "cd___", 2) == 0); ASSERT_TRUE(string_view("abcdef").compare(2, 2, "cz__", 2) < 0); } TEST(string_view, find0) { ASSERT_EQ(0U, string_view("find fins").find(string_view("fin"))); ASSERT_EQ(5U, string_view("find fins").find(string_view("fin"), 1)); ASSERT_EQ(npos, string_view("find fins").find(string_view("fin"), 6)); } TEST(string_view, find1) { ASSERT_EQ(0U, string_view("012340123").find('0')); ASSERT_EQ(5U, string_view("012340123").find('0', 2)); ASSERT_EQ(npos, string_view("012340123").find('0', 6)); } TEST(string_view, find2) { ASSERT_EQ(1U, string_view("012340123").find("12345", 0, 2)); ASSERT_EQ(6U, string_view("012340123").find("12345", 3, 2)); ASSERT_EQ(npos, string_view("012340123").find("12345", 10, 2)); } TEST(string_view, find3) { ASSERT_EQ(1U, string_view("012340123").find("12")); ASSERT_EQ(6U, string_view("012340123").find("12", 2)); ASSERT_EQ(npos, string_view("012340123").find("12", 10)); } TEST(string_view, rfind0) { ASSERT_EQ(5U, string_view("find fins").rfind(string_view("fin"))); ASSERT_EQ(0U, string_view("find fins").rfind(string_view("fin"), 4)); ASSERT_EQ(npos, string_view("find fins").rfind(string_view("no"))); ASSERT_EQ(npos, string_view("foo").rfind(string_view("foobar"))); } TEST(string_view, rfind1) { ASSERT_EQ(5U, string_view("012340123").rfind('0')); ASSERT_EQ(0U, string_view("012340123").rfind('0', 2)); ASSERT_EQ(npos, string_view("012340123").rfind('9')); } TEST(string_view, rfind2) { ASSERT_EQ(6U, string_view("012340123").rfind("12345", npos, 2)); ASSERT_EQ(1U, string_view("012340123").rfind("12345", 4, 2)); ASSERT_EQ(npos, string_view("012340123").rfind("12345", npos, 5)); ASSERT_EQ(npos, string_view("012").rfind("12345", npos, 5)); } TEST(string_view, rfind3) { ASSERT_EQ(6U, string_view("012340123").rfind("12")); ASSERT_EQ(1U, string_view("012340123").rfind("12", 2)); ASSERT_EQ(npos, string_view("012340123").rfind("12", 0)); ASSERT_EQ(npos, string_view("012").rfind("12345")); } TEST(string_view, find_first_of0) { ASSERT_EQ(0U, string_view("0123abc").find_first_of(string_view("0a"))); ASSERT_EQ(4U, string_view("0123abc").find_first_of(string_view("0a"), 1)); ASSERT_EQ(npos, string_view("0123abc").find_first_of(string_view("xyz"))); } TEST(string_view, find_first_of1) { ASSERT_EQ(1U, string_view("ahellohi").find_first_of('h')); ASSERT_EQ(6U, string_view("ahellohi").find_first_of('h', 2)); ASSERT_EQ(npos, string_view("ahellohi").find_first_of('z', 2)); } TEST(string_view, find_first_of2) { ASSERT_EQ(0U, string_view("0123abc").find_first_of("0a1b", 0, 2)); ASSERT_EQ(4U, string_view("0123abc").find_first_of("0a1b", 1, 2)); ASSERT_EQ(npos, string_view("0123abc").find_first_of("0a1b", 5, 2)); } TEST(string_view, find_first_of3) { ASSERT_EQ(0U, string_view("0123abc").find_first_of("0a")); ASSERT_EQ(0U, string_view("0123abc").find_first_of("0a", 0)); ASSERT_EQ(4U, string_view("0123abc").find_first_of("0a", 1)); ASSERT_EQ(npos, string_view("0123abc").find_first_of("0a", 5)); } TEST(string_view, find_last_of0) { ASSERT_EQ(4U, string_view("0123abc").find_last_of(string_view("0a"))); ASSERT_EQ(0U, string_view("0123abc").find_last_of(string_view("0a"), 1)); ASSERT_EQ(npos, string_view("0123abc").find_last_of(string_view("xyz"))); } TEST(string_view, find_last_of1) { ASSERT_EQ(6U, string_view("ahellohi").find_last_of('h')); ASSERT_EQ(1U, string_view("ahellohi").find_last_of('h', 2)); ASSERT_EQ(npos, string_view("ahellohi").find_last_of('z', 2)); } TEST(string_view, find_last_of2) { ASSERT_EQ(4U, string_view("0123abc").find_last_of("0a1b", npos, 2)); ASSERT_EQ(0U, string_view("0123abc").find_last_of("0a1b", 1, 2)); ASSERT_EQ(npos, string_view("0123abc").find_last_of("a1b", 0, 2)); ASSERT_EQ(npos, string_view("0123abc").find_last_of("xyz", npos, 0)); } TEST(string_view, find_last_of3) { ASSERT_EQ(4U, string_view("0123abc").find_last_of("0a")); ASSERT_EQ(4U, string_view("0123abc").find_last_of("0a", npos)); ASSERT_EQ(0U, string_view("0123abc").find_last_of("0a", 1)); ASSERT_EQ(npos, string_view("0123abc").find_last_of("a1", 0)); } TEST(string_view, operator_equal) { ASSERT_TRUE(string_view("this") == string_view("this")); ASSERT_FALSE(string_view("this") == string_view("that")); } TEST(string_view, operator_not_equal) { ASSERT_FALSE(string_view("here") != string_view("here")); ASSERT_TRUE(string_view("here") != string_view("there")); } TEST(string_view, operator_less_than) { ASSERT_TRUE(string_view("abc") < string_view("xyz")); ASSERT_FALSE(string_view("later") < string_view("earlier")); ASSERT_FALSE(string_view("one") < string_view("one")); } TEST(string_view, operator_greater_than) { ASSERT_TRUE(string_view("much") > string_view("little")); ASSERT_FALSE(string_view("future") > string_view("past")); ASSERT_FALSE(string_view("now") > string_view("now")); } TEST(string_view, operator_less_than_or_equal) { ASSERT_TRUE(string_view("abc") <= string_view("xyz")); ASSERT_FALSE(string_view("later") <= string_view("earlier")); ASSERT_TRUE(string_view("one") <= string_view("one")); } TEST(string_view, operator_greater_than_or_equal) { ASSERT_TRUE(string_view("much") >= string_view("little")); ASSERT_FALSE(string_view("future") >= string_view("past")); ASSERT_TRUE(string_view("now") >= string_view("now")); } TEST(string_view, hash) { std::hash<string_view> hasher; ASSERT_NE(hasher(string_view("hello")), hasher(string_view("goodbye"))); ASSERT_EQ(hasher(string_view("same")), hasher(string_view("same"))); }
29.495192
80
0.681581
okuoku
4a4a4afebe687c634b224eb377b4ac969d84a9ed
1,065
cpp
C++
exploringBB/chp09/dcmotor/DCMotorApp.cpp
chaicko/ExploringBeagleBone
56528557e7d9a328602c65f1b2d837906cb08952
[ "Apache-2.0" ]
1
2019-05-28T18:38:29.000Z
2019-05-28T18:38:29.000Z
exploringBB/chp09/dcmotor/DCMotorApp.cpp
chaicko/ExploringBeagleBone
56528557e7d9a328602c65f1b2d837906cb08952
[ "Apache-2.0" ]
null
null
null
exploringBB/chp09/dcmotor/DCMotorApp.cpp
chaicko/ExploringBeagleBone
56528557e7d9a328602c65f1b2d837906cb08952
[ "Apache-2.0" ]
null
null
null
/* A DC Motor Example * Written by Derek Molloy for the book "Exploring BeagleBone: Tools and * Techniques for Building with Embedded Linux" by John Wiley & Sons, 2014 * ISBN 9781118935125. Please see the file README.md in the repository root * directory for copyright and GNU GPLv3 license information. */ #include <iostream> #include "motor/DCMotor.h" using namespace std; using namespace exploringBB; int main(){ cout << "Starting EBB DC Motor Example" << endl; DCMotor dcm(new PWM("pwm_test_P9_42.12"), 116); //will export GPIO116 dcm.setDirection(DCMotor::ANTICLOCKWISE); dcm.setSpeedPercent(50.0f); //make it clear that a float is passed dcm.go(); cout << "Rotating Anti-clockwise at 50% speed" << endl; usleep(5000000); //sleep for 5 seconds dcm.reverseDirection(); cout << "Rotating clockwise at 50% speed" << endl; usleep(5000000); dcm.setSpeedPercent(100.0f); cout << "Rotating clockwise at 100% speed" << endl; usleep(5000000); dcm.stop(); cout << "End of EBB DC Motor Example" << endl; }
36.724138
75
0.694836
chaicko
4a4e824e4424393ff50c0193a8823f86492c6e56
1,532
cpp
C++
Physx.NetCore/Source/VehicleDriveSimData.cpp
ronbrogan/Physx.NetCore
ac788494b6aefc4b6633c46e857f199e6ab0a47a
[ "MIT" ]
187
2015-01-02T15:58:10.000Z
2022-02-20T05:23:13.000Z
PhysX.Net-3.4/PhysX.Net-3/Source/VehicleDriveSimData.cpp
Golangltd/PhysX.Net
fb71e0422d441a16a05ed51348d8afb0328d4b90
[ "MIT" ]
37
2015-01-10T04:38:23.000Z
2022-03-18T00:52:27.000Z
PhysX.Net-3.4/PhysX.Net-3/Source/VehicleDriveSimData.cpp
Golangltd/PhysX.Net
fb71e0422d441a16a05ed51348d8afb0328d4b90
[ "MIT" ]
63
2015-01-11T12:12:44.000Z
2022-02-05T14:12:49.000Z
#include "StdAfx.h" #include "VehicleDriveSimData.h" #include "VehicleEngineData.h" #include "VehicleGearsData.h" #include "VehicleClutchData.h" #include "VehicleAutoBoxData.h" VehicleDriveSimData::VehicleDriveSimData() { _data = new PxVehicleDriveSimData(); } VehicleDriveSimData::VehicleDriveSimData(PxVehicleDriveSimData* data) { if (data == NULL) throw gcnew ArgumentNullException("data"); _data = data; } VehicleEngineData^ VehicleDriveSimData::GetEngineData() { return VehicleEngineData::ToManaged(_data->getEngineData()); } void VehicleDriveSimData::SetEngineData(VehicleEngineData^ engine) { _data->setEngineData(VehicleEngineData::ToUnmanaged(engine)); } VehicleClutchData^ VehicleDriveSimData::GetClutchData() { return VehicleClutchData::ToManaged(_data->getClutchData()); } void VehicleDriveSimData::SetClutchData(VehicleClutchData^ clutch) { _data->setClutchData(VehicleClutchData::ToUnmanaged(clutch)); } VehicleGearsData^ VehicleDriveSimData::GetGearsData() { return VehicleGearsData::ToManaged(_data->getGearsData()); } void VehicleDriveSimData::SetGearsData(VehicleGearsData^ gears) { _data->setGearsData(VehicleGearsData::ToUnmanaged(gears)); } VehicleAutoBoxData^ VehicleDriveSimData::GetAutoBoxData() { return VehicleAutoBoxData::ToManaged(_data->getAutoBoxData()); } void VehicleDriveSimData::SetAutoBoxData(VehicleAutoBoxData^ autobox) { _data->setAutoBoxData(VehicleAutoBoxData::ToUnmanaged(autobox)); } PxVehicleDriveSimData* VehicleDriveSimData::UnmanagedPointer::get() { return _data; }
25.966102
69
0.806136
ronbrogan
4a532efbc43a090eca996a4d7696171696919abc
1,194
cc
C++
lib/fibers/SFibersCalSim.cc
SiFi-CC/sifi-framework
8dba20dcc4dc8b25ca000d58e6eac27b2a94eb55
[ "MIT" ]
null
null
null
lib/fibers/SFibersCalSim.cc
SiFi-CC/sifi-framework
8dba20dcc4dc8b25ca000d58e6eac27b2a94eb55
[ "MIT" ]
3
2020-05-06T18:22:40.000Z
2020-05-26T14:00:23.000Z
lib/fibers/SFibersCalSim.cc
SiFi-CC/sifi-framework
8dba20dcc4dc8b25ca000d58e6eac27b2a94eb55
[ "MIT" ]
4
2021-02-11T10:44:29.000Z
2021-06-17T10:50:23.000Z
// @(#)lib/fibers:$Id$ // Author: Rafal Lalik 18/11/2017 /************************************************************************* * Copyright (C) 2017-2018, Rafał Lalik. * * All rights reserved. * * * * For the licensing terms see $SiFiSYS/LICENSE. * * For the list of contributors see $SiFiSYS/README/CREDITS. * *************************************************************************/ #include "SFibersCalSim.h" #include <cstdio> // for printf /** * \class SFibersCalSim \ingroup lib_fibers A container for Fibers Stack Calibrated simulation data */ /** * Clear object. * Parameter options are ignored, for ROOT compatibility. * * \param opt options */ void SFibersCalSim::Clear(Option_t* /*opt*/) { fGeantEloss = 0.0; fGeantPoint.Clear(); } /** * Print category. */ void SFibersCalSim::print() const { SFibersCal::print(); printf(" GEANT: position = %.2f,%.2f,%.2f Eloss = %.2f\n", fGeantPoint.X(), fGeantPoint.Y(), fGeantPoint.Z(), fGeantEloss); }
26.533333
98
0.468174
SiFi-CC
4a56d14d814c86a5b74dd454e0d13525b14a6213
475
cpp
C++
cppcode/cpp execise/day01/bool.cpp
jiedou/study
606676ebc3d1fb1a87de26b6609307d71dafec22
[ "Apache-2.0" ]
null
null
null
cppcode/cpp execise/day01/bool.cpp
jiedou/study
606676ebc3d1fb1a87de26b6609307d71dafec22
[ "Apache-2.0" ]
null
null
null
cppcode/cpp execise/day01/bool.cpp
jiedou/study
606676ebc3d1fb1a87de26b6609307d71dafec22
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; int main (void) <% bool b = true; cout << boolalpha << b << noboolalpha << ' ' << b << endl; b = false; cout << boolalpha << b << noboolalpha << ' ' << b << endl; cout << sizeof (bool) << endl; // b = 1234; // b = 1.23; // b = 'A'; // b = "Hello, World !"; // b = *("Hello, World !" + 14); // b = "Hello, World !"[14]; b = 14<:"Hello, World !":>; cout << boolalpha << b << endl; // a[b] <=> b[a] <=> *(a + b) return 0; %>
21.590909
38
0.48
jiedou
4a571ca06f16a0c1c3b327d6a193ad39b17b1a65
4,155
hpp
C++
include/Hord/Data/TableSchema.hpp
komiga/hord
32be8ffb11bd74959c5cd5254e36d87f224b6f60
[ "MIT" ]
null
null
null
include/Hord/Data/TableSchema.hpp
komiga/hord
32be8ffb11bd74959c5cd5254e36d87f224b6f60
[ "MIT" ]
null
null
null
include/Hord/Data/TableSchema.hpp
komiga/hord
32be8ffb11bd74959c5cd5254e36d87f224b6f60
[ "MIT" ]
null
null
null
/** @copyright MIT license; see @ref index or the accompanying LICENSE file. @file @brief TableSchema class. @ingroup data */ #pragma once #include <Hord/config.hpp> #include <Hord/aux.hpp> #include <Hord/String.hpp> #include <Hord/utility.hpp> #include <Hord/serialization.hpp> #include <Hord/Data/Defs.hpp> #include <duct/debug.hpp> namespace Hord { namespace Data { // Forward declarations class TableSchema; /** @addtogroup data @{ */ /** Table schema. */ class TableSchema { public: /** Column schema. */ struct Column { /** @name Properties */ /// @{ /** Index. This is only used when configuring a table. See @c Data::Table::configure(). */ unsigned index{~0u}; /** Type. */ Data::Type type{}; /** Name. */ String name{}; /// @} /** @name Special member functions */ /// @{ /** Destructor. */ ~Column() noexcept = default; /** Default constructor. */ Column() = default; /** Move constructor. */ Column(Column&&) = default; /** Copy constructor. */ Column(Column const&) = default; /** Move assignment operator. */ Column& operator=(Column&&) = default; /** Copy assignment operator. */ Column& operator=(Column const&) = default; /** Construct with name and type. */ Column( String name, Data::Type type ) noexcept : type(type) , name(std::move(name)) {} /** Construct with index, name, and type. */ Column( unsigned index, String name, Data::Type type ) noexcept : index(index) , type(type) , name(std::move(name)) {} /// @} /** @name Serialization */ /// @{ /** Serialize. @throws SerializerError{..} If a serialization operation failed. */ template<class Ser> ser_result_type serialize( ser_tag_serialize, Ser& ser ) { auto& self = const_safe<Ser>(*this); ser( self.type, Cacophony::make_string_cfg<std::uint8_t>(self.name) ); } /// @} }; /** Column vector type. */ using column_vector_type = aux::vector<Column>; private: HashValue m_hash{HASH_EMPTY}; column_vector_type m_columns{}; public: /** @name Special member functions */ /// @{ /** Destructor. */ ~TableSchema() noexcept = default; /** Default constructor. */ TableSchema() = default; /** Move constructor. */ TableSchema(TableSchema&&) = default; /** Copy constructor. */ TableSchema(TableSchema const&) = default; /** Move assignment operator. */ TableSchema& operator=(TableSchema&&) = default; /** Copy assignment operator. */ TableSchema& operator=(TableSchema const&) = default; /** Construct with column initializer list. @note Column indices are ~0u; they must be assigned manually if reconfiguring a table. */ TableSchema( std::initializer_list<Data::TableSchema::Column> const ilist ) noexcept; /// @} /** @name Properties */ /// @{ /** Get schema hash. */ HashValue hash() const noexcept { return m_hash; } /** Get columns (mutable). */ column_vector_type& columns() noexcept { return m_columns; } /** Get columns. */ column_vector_type const& columns() const noexcept { return m_columns; } /** Get number of columns. */ unsigned num_columns() const noexcept { return m_columns.size(); } /// @} /** @name Layout */ /// @{ /** Get a column by index. */ Data::TableSchema::Column const& column( unsigned const index ) const { return m_columns.at(index); } /** Update schema hash. @returns @c true if the hash changed. */ bool update() noexcept; /** Update schema hash. @returns @c true if a type or the number of columns changed. */ bool assign( Data::TableSchema const& schema ) noexcept; /// @} /** @name Serialization */ /// @{ /** Read from input serializer. @throws SerializerError{..} If a serialization operation failed. */ ser_result_type read( ser_tag_read, InputSerializer& ser ); /** Write to output serializer. @throws SerializerError{..} If a serialization operation failed. */ ser_result_type write( ser_tag_write, OutputSerializer& ser ) const; /// @} }; /** @} */ // end of doc-group data } // namespace Data } // namespace Hord
16.686747
72
0.635379
komiga
4a583509cdbfd5e612eabd578f3b25d0fd2e96a7
2,700
cc
C++
wrapper/lr_wrapper.cc
KaiminLai/tiny-machine-learning-system
e29625dfb513032b40712663b63f874e2ae6f924
[ "MIT" ]
1
2019-01-09T16:03:50.000Z
2019-01-09T16:03:50.000Z
wrapper/lr_wrapper.cc
KaiminLai/tiny-machine-learning-system
e29625dfb513032b40712663b63f874e2ae6f924
[ "MIT" ]
null
null
null
wrapper/lr_wrapper.cc
KaiminLai/tiny-machine-learning-system
e29625dfb513032b40712663b63f874e2ae6f924
[ "MIT" ]
null
null
null
#include <iostream> #include "../src/logistic_regression.h" #include <ctime> using namespace Eigen; using namespace std; void gen_random(char *s, int len) { srand(time(NULL)); static const char alphanum[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; for (int i = 0; i < len; ++i){ s[i] = alphanum[rand() % (sizeof(alphanum) - 1)]; } s[len] = 0; } extern "C" void lr_fit(double** features, int* labels, int row, int col, int max_iter, double alpha, double lambda, double tolerance, int seed, bool use_batch, int batch_size, int early_stopping_round, char* ret, double (*metric)(double* y, double* pred, int size)=Utils::accuracy){ MatrixXd X(row, col); VectorXd y(row); for(int i = 0; i < row; i++){ for(int j = 0; j < col; j++){ X(i,j) = features[i][j]; } y(i) = labels[i]; } // train the logistic regression model LogisticRegression clf = LogisticRegression(max_iter, alpha, lambda, tolerance, seed, use_batch); clf.fit(X, y, batch_size, early_stopping_round, metric); // save the model weights char* fmodel = new char[21]; gen_random(fmodel, 20); string model_path = "/tmp/"+string(fmodel); clf.saveWeights(model_path); strcpy(ret, model_path.c_str()); } extern "C" void lr_predict_prob(double** features, int row, int col, char* fmodel, double* ret){ LogisticRegression clf = LogisticRegression(); clf.loadWeights(fmodel); MatrixXd X(row, col); for(int i = 0; i < row; i++){ for(int j = 0; j < col; j++){ X(i,j) = features[i][j]; } } VectorXd pred = clf.predict_prob(X); for(int i = 0; i < row; i++){ ret[i] = pred(i); } } extern "C" void lr_predict(double** features, int row, int col, char* fmodel, int* ret){ double* prob = new double[row]; lr_predict_prob(features, row, col, fmodel, prob); for(int i = 0; i < row; i++){ ret[i] = prob[i]>0.5?1:0; } } int main(){ int row = 10, col = 2; double** features = new double *[row]; for(int i = 0; i < row; i++){ features[i] = new double[col]; } int* labels = new int[row]; double features_value[row*col] = {1.0,0.8,2.0,1.7,3.0,2.5,4.0,3.6,5.0,4.9,1.0,1.2,2.0,2.5,3.0,3.4,4.0,4.5,5.0,6.0}; int labels_value[row] = {0,0,0,0,0,1,1,1,1,1}; for(int i = 0; i < row; i++){ for(int j = 0; j < col; j++){ features[i][j] = features_value[i*col+j]; } labels[i] = labels_value[i]; } char* ret = new char[26]; lr_fit(features, labels, row, col, 200, 0.01, 0.0, 1e-7, 2018, false, 128, 100, ret); cout << ret << endl; int* pred = new int[row]; lr_predict(features, row, col, ret, pred); for(int i = 0; i < row; i++){ cout << pred[i] << ","; } }
29.347826
117
0.608148
KaiminLai
4a5d94a107e0cd2785d6c29bbd9f46ed9048cb34
5,044
cc
C++
src/object/file.cc
jcbaillie/urbi
fb17359b2838cdf8d3c0858abb141e167a9d4bdb
[ "BSD-3-Clause" ]
16
2016-05-10T05:50:58.000Z
2021-10-05T22:16:13.000Z
src/object/file.cc
jcbaillie/urbi
fb17359b2838cdf8d3c0858abb141e167a9d4bdb
[ "BSD-3-Clause" ]
7
2016-09-05T10:08:33.000Z
2019-02-13T10:51:07.000Z
src/object/file.cc
jcbaillie/urbi
fb17359b2838cdf8d3c0858abb141e167a9d4bdb
[ "BSD-3-Clause" ]
15
2015-01-28T20:27:02.000Z
2021-09-28T19:26:08.000Z
/* * Copyright (C) 2008-2012, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ #include <libport/cstdlib> #include <fstream> #include <libport/file-system.hh> #include <urbi/object/date.hh> #include <urbi/object/file.hh> #include <urbi/object/global.hh> #include <urbi/object/path.hh> #include <urbi/object/symbols.hh> #include <urbi/runner/raise.hh> namespace boostfs = boost::filesystem; namespace boost { namespace filesystem { typedef filesystem_error fserror; } } namespace urbi { namespace object { using boost::format; ATTRIBUTE_NORETURN static void raise_boost_fs_error(boostfs::fserror& e) { RAISE(libport::format_error(e)); } /*--------------. | C++ methods. | `--------------*/ File::value_type File::value_get() { return path_; } /*---------------------. | urbiscript methods. | `---------------------*/ // Construction File::File() : path_(new Path("/")) { proto_add(proto); } File::File(rFile model) : path_(model.get()->path_) { proto_add(model); } File::File(const std::string& value) : path_(new Path(value)) { proto_add(proto ? rObject(proto) : Object::proto); } OVERLOAD_TYPE(file_init_bouncer, 1, 1, Path, (void (File::*)(rPath)) &File::init, String, (void (File::*)(const std::string&)) &File::init); URBI_CXX_OBJECT_INIT(File) : path_(new Path("/")) { BIND(asList, as_list); BIND(asPath, as_path); BIND(asPrintable, as_printable); BIND(asString, as_string); BINDG(content); BIND(create); BIND(remove); BINDG(size); setSlot(SYMBOL(init), new Primitive(&file_init_bouncer)); } rFile File::create(rObject, const std::string& p) { libport::path path(p); if (path.exists()) path.remove(); if (!path.create()) FRAISE("cannot create file: %s: %s", path, strerror(errno)); return new File(p); } void File::remove() { path_->value_get().remove(); } rFloat File::size() const { try { return new Float(boostfs::file_size(boostfs::path(path_->as_string()))); } catch (boostfs::fserror& e) { raise_boost_fs_error(e); } } void File::init(rPath path) { path->check_file(); path_ = path; } void File::init(const std::string& path) { init(new Path(path)); } /*--------------. | Conversions. | `--------------*/ static bool split_point(const std::string& str, size_t& pos, size_t& size) { pos = std::string::npos; size_t where; #define SPLIT(Str) \ where = str.find(Str); \ if (where != std::string::npos && where < pos) \ { \ pos = where; \ size = sizeof(Str) - 1; \ } SPLIT("\n"); SPLIT("\r\n"); #undef SPLIT return pos != std::string::npos; } static void get_buf(std::istream& input, std::string& output) { char buf[BUFSIZ]; input.read(buf, sizeof buf); output += std::string(buf, input.gcount()); } rList File::as_list() const { std::ifstream s(path_->as_string().c_str()); if (!s.good()) FRAISE("file not readable: %s", as_string()); List::value_type res; std::string line; // Split in lines, 'Back in the stone age' version. while (!s.eof()) { get_buf(s, line); // Initialized because g++ warns that size may be used // uninitialized otherwise. size_t pos = std::string::npos; size_t size = 0; while (split_point(line, pos, size)) { res << new String(line.substr(0, pos)); line = line.substr(pos + size, std::string::npos); } } // Bad bad bad user! The file does not finish with a \n! Handle it // anyway ... if (!line.empty()) res << new String(line); return new List(res); } rPath File::as_path() const { return path_; } std::string File::as_string() const { return path_->as_string(); } std::string File::as_printable() const { return libport::format("File(\"%s\")", path_->as_string()); } rObject File::content() const { CAPTURE_GLOBAL(Binary); return Binary->call(SYMBOL(new), to_urbi(std::string()), to_urbi(libport::file_content(path_->as_string()))); } } }
22.026201
80
0.519033
jcbaillie
4a5f5d3d3d9b840114271eba76557a9bd0402d34
1,263
cpp
C++
logic/EnabledItemFilter.cpp
Heufneutje/MultiMC5
7d1dd2a32f95eacaaea7d808cd07faf99e425977
[ "Apache-2.0" ]
2
2016-03-29T07:43:32.000Z
2019-05-31T14:38:04.000Z
logic/EnabledItemFilter.cpp
Heufneutje/MultiMC5
7d1dd2a32f95eacaaea7d808cd07faf99e425977
[ "Apache-2.0" ]
null
null
null
logic/EnabledItemFilter.cpp
Heufneutje/MultiMC5
7d1dd2a32f95eacaaea7d808cd07faf99e425977
[ "Apache-2.0" ]
null
null
null
/* Copyright 2013-2014 MultiMC 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 * * 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 "EnabledItemFilter.h" EnabledItemFilter::EnabledItemFilter(QObject *parent) : QSortFilterProxyModel(parent) { } void EnabledItemFilter::setActive(bool active) { m_active = active; invalidateFilter(); } bool EnabledItemFilter::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const { if (!m_active) return true; QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent); if (sourceModel()->flags(index) & Qt::ItemIsEnabled) { return true; } return false; } bool EnabledItemFilter::lessThan(const QModelIndex &left, const QModelIndex &right) const { return QSortFilterProxyModel::lessThan(left, right); }
28.704545
94
0.756136
Heufneutje
4a60d8d84766f8bfad9320c6f021e7af991f235d
1,283
cc
C++
c/test2.cc
seckcoder/lang-learn
1e0d6f412bbd7f89b1af00293fd907ddb3c1b571
[ "Unlicense" ]
1
2017-10-14T04:23:45.000Z
2017-10-14T04:23:45.000Z
c/test2.cc
seckcoder/lang-learn
1e0d6f412bbd7f89b1af00293fd907ddb3c1b571
[ "Unlicense" ]
null
null
null
c/test2.cc
seckcoder/lang-learn
1e0d6f412bbd7f89b1af00293fd907ddb3c1b571
[ "Unlicense" ]
null
null
null
void add(Bignum *pa, Bignum *pb) { for(int i = 0; i < pa->len && i < pb->len; i++) { pa->arr[i] += pb->arr[i]; } } void copyBignum(Bignum *dest, Bignum *src) { dest->len = src->len; for(int i = 0; i < src->len; i++) { dest->arr[i] = src->arr[i]; } } Bignum res; initBignum(&res); for(int i = 1; i < n; i++) { Bignum tmp; copyBignum(&tmp, &res); mult10(&res); add(&res, &tmp); } struct Bignum { int len; int *arr; }; void initBignum(Bignum *pa) { pa->len = 1; pa->arr = (int*)malloc(M*sizeof(int)); pa->arr[0] = 1; } void freeBignum(Bignum *pa) { free(pa->arr); } Bignum res; initBignum(&res); void copyBignum(Bignum *dest, Bignum *src) { dest->len = src->len; for(int i = 0; i < src->len; i++) { dest->arr[i] = src->arr[i]; } } for(int i = 1; i < n; i++) { Bignum tmp; initBignum(tmp); copyBignum(&tmp, &res); mult10(&res); add(&res, &tmp); freeBignum(tmp); } freeBignum(res); struct Bignum { int len; int *arr; }; void initBignum(Bignum *pa) { pa->len = 1; pa->arr = (int*)malloc(M*sizeof(int)); pa->arr[0] = 1; } initBignum(a); Bignum res; for(int i = 1; i < n; i++) { Bignum new_a = mult10(&a); res = addBignum(a, new_a); freeBignum(new_a); freeBignum(a); a = res; } freeBignum(a);
14.918605
51
0.550273
seckcoder
4a6215f7c75deeee00ed31bae53170713730c627
691
cpp
C++
pgm15_04.cpp
neharkarvishal/Data-Structures-and-Algorithms-with-Object-Oriented-Design-Patterns-in-C-
c9a29d2dd43ad8561e828c25f98de6a8c8f2317a
[ "Unlicense" ]
1
2021-07-13T03:58:36.000Z
2021-07-13T03:58:36.000Z
pgm15_04.cpp
neharkarvishal/Data-Structures-and-Algorithms-with-Object-Oriented-Design-Patterns-in-C-
c9a29d2dd43ad8561e828c25f98de6a8c8f2317a
[ "Unlicense" ]
null
null
null
pgm15_04.cpp
neharkarvishal/Data-Structures-and-Algorithms-with-Object-Oriented-Design-Patterns-in-C-
c9a29d2dd43ad8561e828c25f98de6a8c8f2317a
[ "Unlicense" ]
null
null
null
// // This file contains the C++ code from Program 15.4 of // "Data Structures and Algorithms // with Object-Oriented Design Patterns in C++" // by Bruno R. Preiss. // // Copyright (c) 1998 by Bruno R. Preiss, P.Eng. All rights reserved. // // http://www.pads.uwaterloo.ca/Bruno.Preiss/books/opus4/programs/pgm15_04.cpp // template <class T> class StraightInsertionSorter : public InsertionSorter<T> { protected: void DoSort (Array<T>&); }; template <class T> void StraightInsertionSorter<T>::DoSort (Array<T>& array) { for (unsigned int i = 1; i < n; ++i) for (unsigned int j = i; j > 0 && array [j - 1U] > array [j]; --j) Swap (array [j], array [j - 1U]); }
26.576923
80
0.643994
neharkarvishal
4a6535087189ba4eb88e868f99c14a777eb2f38f
4,490
cpp
C++
oi/codevs/P3160/main.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
3
2018-08-30T09:43:20.000Z
2019-12-03T04:53:43.000Z
oi/codevs/P3160/main.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
null
null
null
oi/codevs/P3160/main.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
null
null
null
#include <cassert> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; #define NMAX 100000 #define SIGMA 28 #define EOFCHAR1 26 #define EOFCHAR2 27 class SuffixTree { public: SuffixTree() : size(0), root(new Node) {} void append(char c) { static Node *active = root; static char dir = -1; static int len = 0; static int cnt = 0; cnt++; Node *last = NULL; while (cnt) { if (cnt - 1 < len) { assert(active == root); len = cnt - 1; dir = len ? str[size - len + 1] : -1; } while (dir >= 0 && len >= length(active->trans[dir])) { len -= length(active->trans[dir]); active = active->trans[dir]->next; dir = len ? str[size - len + 1] : -1; } // while if ((dir < 0 && active->trans[c]) || (dir >= 0 && c == str[active->trans[dir]->left + len])) { if (dir < 0) dir = c; len++; if (last) last->suffix_link = active; break; } Node *x; if (dir < 0) { active->trans[c] = new Edge(size + 1, 0, new Node); x = active; } else { Edge *t = active->trans[dir]; x = new Node; x->trans[c] = new Edge(size + 1, 0, new Node); x->trans[str[t->left + len]] = new Edge(t->left + len, t->right, t->next); t->right = t->left + len - 1; t->next = x; } if (last) last->suffix_link = x; last = x; active = active->suffix_link ? active->suffix_link : root; cnt--; } // while str[++size] = c; if (c == EOFCHAR1) eof1 = size; else if (c == EOFCHAR2) eof2 = size; } void reset() { _reset(root); } void process_mask() { _process_mask(root); } int solve() { return _solve(root); } private: struct Node { struct Edge { Edge(int l, int r, Node *nxt) : left(l), right(r), next(nxt) {} int left; int right; Node *next; }; // struct Edge Node() : mask(0), depth(0), suffix_link(NULL) { memset(trans, 0, sizeof(trans)); } char mask; int depth; Node *suffix_link; Edge *trans[SIGMA]; }; // struct Node typedef Node::Edge Edge; int length(const Edge *e) { return e->right ? e->right - e->left + 1 : size - e->left + 1; } void _reset(Node *x) { for (char p = 0; p < SIGMA; p++) { if (x->trans[p]) { Edge *t = x->trans[p]; if (!t->right) t->right = size; _reset(t->next); } } // for } int _process_mask(Node *x) { for (char p = 0; p < SIGMA; p++) { Edge *t = x->trans[p]; if (t) { t->next->depth = x->depth + length(t); if (t->left <= eof1 && eof1 <= t->right) x->mask |= 1; if (t->left <= eof2 && eof2 <= t->right) x->mask |= 2; x->mask |= _process_mask(t->next); } } // for return x->mask; } int _solve(Node *x) { int answer = x->mask == 3 ? x->depth : 0; for (char p = 0; p < SIGMA; p++) { if (x->trans[p]) { answer = max(answer, _solve(x->trans[p]->next)); } } // for return answer; } int eof1, eof2; int size; char str[NMAX * 2 + 10]; Node *root; }; // class SuffixTree static char buf1[NMAX + 10]; static char buf2[NMAX + 10]; int main() { scanf("%s%s", buf1, buf2); SuffixTree *tree = new SuffixTree; for (size_t pos = 0; buf1[pos]; pos++) { tree->append(buf1[pos] - 'a'); } // for tree->append(EOFCHAR1); tree->reset(); for (size_t pos = 0; buf2[pos]; pos++) { tree->append(buf2[pos] - 'a'); } // for tree->append(EOFCHAR2); tree->reset(); tree->process_mask(); printf("%d\n", tree->solve()); return 0; } // function main
23.14433
75
0.417372
Riteme
4a6582e421a94644738cadd7e41a5ede344a106f
3,943
cpp
C++
source/core/render/glfw_windowBuilder.cpp
zeplaz/s_liz_rz
612ebd97be4d0624b967b1968c45f092ea1c8ddb
[ "MIT" ]
null
null
null
source/core/render/glfw_windowBuilder.cpp
zeplaz/s_liz_rz
612ebd97be4d0624b967b1968c45f092ea1c8ddb
[ "MIT" ]
null
null
null
source/core/render/glfw_windowBuilder.cpp
zeplaz/s_liz_rz
612ebd97be4d0624b967b1968c45f092ea1c8ddb
[ "MIT" ]
null
null
null
#include "glfw_windowBuilder.hpp" #include "../SL_ZER_namespace_def01.hpp" window_glfw::~window_glfw() { this->shutdown(); } ERRORCODE window_glfw::init() { ERRORCODE co = this->setup_context(); if(co != NO_ERROR) { #ifdef DEBUG_01 fmt::print("\n##->ERROR CODE create_window::{}\n", error_to_string(co)); #endif return co; } co = this->create_window(SL_ZER::DEFAULT_MAIN_VEWPORT_WIDTH,SL_ZER::DEFAULT_MAIN_VEWPORT_HIGHT,"MAIN_WIN GLFW_TITLE"); if(co != NO_ERROR) { #ifdef DEBUG_01 fmt::print("\n##->ERROR CODE create_window::{}\n", error_to_string(co)); #endif return co; } co = SL_ZER::glew_check(); #ifdef DEBUG_01 fmt::print("\n##->ERROR CODE create_window::{}\n", error_to_string(co)); #endif return co; } void window_glfw::shutdown() { if(gWindow != nullptr) glfwDestroyWindow(gWindow); #ifdef DEBUG_01 fmt::print("\nwindow flfw shutdown likly destutor? showdown\n"); #endif } ERRORCODE window_glfw::setup_context() { glfwSetErrorCallback(glfw_error_callback); glewExperimental = GL_TRUE; //launch gluitInit if (!glfwInit()) { fmt::print("\n##ERROR:::glfwinit faild :()\n"); return GWFLW_FAIL_INIT; } fmt::print("\nglfwInit compleated\n"); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR,4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR,5); #ifdef DEBUG_01 glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); #endif glfwWindowHint(GLFW_OPENGL_PROFILE,GLFW_OPENGL_CORE_PROFILE); return NO_ERROR; } ERRORCODE window_glfw::create_window(int width, int hight, std::string title) { gWindow = glfwCreateWindow(width,hight,title.c_str(), NULL, NULL); if (gWindow == NULL) { fmt::print("ERROR..glfwCreateWindow.window NULL\n"); return GWFLW_FAIL_CREATE; } #ifdef DEBUG_01 fmt::print("\nwindow created? compleated\n"); #endif glfwMakeContextCurrent(gWindow); glfwSwapInterval(1); // Enable vsync // this->set_windowSize_callback(); this->set_framebuffer_callback(); glfwSetInputMode(gWindow, GLFW_CURSOR, GLFW_CURSOR_DISABLED); return NO_ERROR; } void window_glfw::set_windowSize_callback() { glfwSetWindowSizeCallback(gWindow,[](GLFWwindow* window, int w, int h) { glfwMakeContextCurrent(window); glfwSetWindowSize(window, w, h); base_window::Resized = true; }); } void window_glfw::set_framebuffer_callback() { glfwSetFramebufferSizeCallback(gWindow,[](GLFWwindow* window, int w, int h) { glViewport(0, 0, w, h); base_window::Resized = true; } ); } void window_glfw::if_resized() { glfwGetWindowSize(gWindow, &frameportbuffer_width, &frameportbuffer_height); //glfwSetWindowAspectRatio(window, frameportbuffer_width, frameportbuffer_height); //m_m4Projection = glm::perspective(45.0f, float(frameportbuffer_width)/float(frameportbuffer_height), 0.1f, 1000.0f); base_window::Resized = false; } long double glfw_window_imp::get_window_time_seconds() { return glfwGetTime(); } void glfw_window_imp::render() { // int display_w, display_h; GLFWwindow* l_window = static_cast<GLFWwindow*> (window->window_hanlde()); if(glfwWindowShouldClose(l_window)) {window->shutdown_signa = true; return; } if(base_window::Resized == true) {window->if_resized();} glClearColor(SL_ZER::CLEAR_COLOUR_GLM.x * SL_ZER::CLEAR_COLOUR_GLM.w, SL_ZER::CLEAR_COLOUR_GLM.y * SL_ZER::CLEAR_COLOUR_GLM.w, SL_ZER::CLEAR_COLOUR_GLM.z * SL_ZER::CLEAR_COLOUR_GLM.w, SL_ZER::CLEAR_COLOUR_GLM.w); glClear(GL_COLOR_BUFFER_BIT); //CALL IMGUI SHDRAW HERE!!! // ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); ///// glfwSwapBuffers(l_window); } void glfw_window_imp::poll_events() { glfwPollEvents(); }
21.78453
120
0.676896
zeplaz
4a688579bfdf2b79e2c9facd2c3ccbb790338e94
4,722
cpp
C++
c/wikipedia/page_parse_dequeuer.cpp
mmonto7/small-world-graph
8ea1015c24065cb71875620b28c66ffb8348dcae
[ "MIT" ]
3
2016-05-31T07:23:27.000Z
2018-02-16T00:06:04.000Z
c/wikipedia/page_parse_dequeuer.cpp
mmonto7/small-world-graph
8ea1015c24065cb71875620b28c66ffb8348dcae
[ "MIT" ]
2
2020-08-31T20:51:20.000Z
2021-03-30T18:05:25.000Z
c/wikipedia/page_parse_dequeuer.cpp
mmonto7/small-world-graph
8ea1015c24065cb71875620b28c66ffb8348dcae
[ "MIT" ]
4
2015-01-17T07:31:25.000Z
2020-08-31T20:49:41.000Z
#define _FILE_OFFSET_BITS 64 #include <iostream> #include <fstream> #include <sstream> #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <vector> #include <list> #include "wikipedia_xml_parser.h" #include "wiki_parser.h" #include "wiki_title_validator.h" #include "s3_helper.h" #include <signal.h> #include "string_utils.h" #include "PageParseQueue.h" #include <protocol/TBinaryProtocol.h> #include <transport/TSocket.h> #include <transport/TTransportUtils.h> using namespace std; using namespace apache::thrift; using namespace apache::thrift::protocol; using namespace apache::thrift::transport; /* Globals */ shared_ptr<S3Helper> __s3; static size_t __total_pages = 0; static size_t __pages_imported = 0; static volatile sig_atomic_t gracefully_quit = 0; static void handle_sigint(int signal) { if (!gracefully_quit) { cout << "Sent Quit Signal" << endl; gracefully_quit = 1; } else { exit(0); } } static void handle_raw_page(const char* title, const char* text, const char* s3_bucket, const char* directory) { if (title && text) { stringstream output; string filename = string(title) + string(".html"); output << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"; output << "<html xmlns='http://www.w3.org/1999/xhtml'>\n\t<head>\n\t\t<meta http-equiv='content-type' content='text/html; charset=utf-8' />\n\t\t<title>" << title << "</title>\n\t</head>\n"; output << "\t<body onload=\"document.domain='cruxlux.com';if(parent&&parent!=self){parent.show_from_frame(document.title);}var s=document.createElement('script');s.src='http://assets.cruxlux.com/javascripts/dec.js';document.body.appendChild(s)\">"; char* transformed = wikitext_to_plaintext(text); if (transformed) { string result = replace_all(transformed,"\n","\n<p></p>"); output << result; output << "\n\t</body>\n</html>"; string str_output = output.str(); if (directory) { chdir(directory); ofstream file(filename.c_str()); if (file.is_open()) { file << result; file.close(); } } if (s3_bucket) { cout << "[P] " << filename << " -> " << s3_bucket << endl; __s3->put(s3_bucket,filename.c_str(),str_output.c_str(), str_output.size(), "text/html",true); } free(transformed); } } } int main(int argc,char** argv) { struct sigaction sig_pipe_action; memset(&sig_pipe_action,'\0',sizeof(sig_pipe_action)); sig_pipe_action.sa_handler = SIG_IGN; sigaction(SIGPIPE,&sig_pipe_action,NULL); signal(SIGINT,handle_sigint); char* host = (char*) "localhost"; int port = 10010; int c; char* s3_bucket = NULL; char* directory = NULL; while ((c = getopt(argc, argv, "h:ps:d:")) != -1) { switch (c) { case 'h': host = optarg; break; case 'p': port = atoi(optarg); if (port == 0) { cout << "Invalid port" << endl; exit(-1); } break; case 's': s3_bucket = optarg; break; case 'd': directory = optarg; break; } } shared_ptr<TSocket> socket(new TSocket(host,port)); socket->setConnTimeout(1000); socket->setRecvTimeout(1000); shared_ptr<TTransport> transport(new TBufferedTransport(socket)); shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport)); PageParseQueueClient client(protocol); __s3 = S3Helper::instance(); for(;;) { try { if (gracefully_quit == 1) { cout << "Gracefully Quitting" << endl; exit(0); } transport->open(); vector<RawPage> work_units; client.dequeue(work_units); transport->close(); if(work_units.size() > 0) { int dequeued_amount = work_units.size(); for(vector<RawPage>::const_iterator ii = work_units.begin(); ii != work_units.end(); ii++) { RawPage page = *ii; handle_raw_page(page.title.c_str(),page.content.c_str(),s3_bucket,directory); __pages_imported++; fprintf(stdout,"\rDequeued %d | Pages Imported: %9d ",(int) dequeued_amount, (int) __pages_imported); fflush(stdout); } } else { fprintf(stdout,"\rQueue is Empty"); fflush(stdout); sleep(10); } } catch (TException &tx) { transport->close(); printf("ERROR: %s\n", tx.what()); printf("Sleeping for 10s before retry\n"); sleep(10); } } fprintf(stdout,"\rPages Imported: %9d / %d",(int) __pages_imported, (int) __total_pages); fflush(stdout); cout << endl; return 0; }
28.618182
252
0.624947
mmonto7
4a6b66fb771ce459a760bdd25f427650e5893834
2,070
hpp
C++
include/fea/ui/sfmlinputbackend.hpp
CptAsgard/featherkit
84e7a119fcb84cd3a4d8ad9ba9b288abe5c56aa5
[ "Zlib" ]
22
2015-01-13T10:49:38.000Z
2020-12-23T15:25:59.000Z
include/fea/ui/sfmlinputbackend.hpp
CptAsgard/featherkit
84e7a119fcb84cd3a4d8ad9ba9b288abe5c56aa5
[ "Zlib" ]
27
2015-01-11T03:47:27.000Z
2015-12-10T17:52:17.000Z
include/fea/ui/sfmlinputbackend.hpp
CptAsgard/featherkit
84e7a119fcb84cd3a4d8ad9ba9b288abe5c56aa5
[ "Zlib" ]
7
2015-09-18T15:06:45.000Z
2020-02-19T15:12:34.000Z
#pragma once #include <fea/config.hpp> #include <fea/ui/inputbackend.hpp> #include <SFML/Window.hpp> namespace fea { class FEA_API SFMLInputBackend : public InputBackend { public: SFMLInputBackend(sf::Window& window); std::queue<Event> fetchEvents() override; bool isKeyPressed(Keyboard::Code code) override; bool isMouseButtonPressed(Mouse::Button b) override; Vec2I getMouseGlobalPosition() override; Vec2I getMouseWindowPosition() override; void setMouseGlobalPosition(int32_t x, int32_t y) override; void setMouseWindowPosition(int32_t x, int32_t y) override; bool isGamepadConnected(uint32_t id) override; uint32_t getGamepadButtonCount(uint32_t id) override; bool isGamepadButtonPressed(uint32_t id, uint32_t button) override; bool gamepadHasAxis(uint32_t id, Gamepad::Axis axis) override; float getGamepadAxisPosition(uint32_t id, Gamepad::Axis axis) override; void setGamepadThreshold(float threshold) override; void setKeyRepeatEnabled(bool enabled) override; private: Event closed(); Event resized(sf::Event& event); Event lostFocus(); Event gainedFocus(); Event textEntered(sf::Event& event); Event keyPressed(sf::Event& event); Event keyReleased(sf::Event& event); Event mouseWheelMoved(sf::Event& event); Event mouseButtonPressed(sf::Event& event); Event mouseButtonReleased(sf::Event& event); Event mouseMoved(sf::Event& event); Event mouseEntered(); Event mouseLeft(); Event gamepadButtonPressed(sf::Event& event); Event gamepadButtonReleased(sf::Event& event); Event gamepadMoved(sf::Event& event); Event gamepadConnected(sf::Event& event); Event gamepadDisconnected(sf::Event& event); sf::Window& mWindow; }; }
39.056604
83
0.629469
CptAsgard
4a6c3eb3722193437a81c9044d886a61a1116e10
16,798
cpp
C++
src/linalg/mat_arr_math.cpp
mirkoruether/ann-cpp
7b7aae3f59b0ab82b4a83c4705f7025077b8bfd5
[ "MIT" ]
null
null
null
src/linalg/mat_arr_math.cpp
mirkoruether/ann-cpp
7b7aae3f59b0ab82b4a83c4705f7025077b8bfd5
[ "MIT" ]
null
null
null
src/linalg/mat_arr_math.cpp
mirkoruether/ann-cpp
7b7aae3f59b0ab82b4a83c4705f7025077b8bfd5
[ "MIT" ]
null
null
null
#include "mat_arr_math.h" #include "mat_arr_math_t.h" using namespace linalg; namespace linalg { struct _mat_e_by_e_add_kernel { fpt operator()(fpt a, fpt b) const { return a + b; } }; mat_arr mat_element_wise_add(const mat_arr& A, const mat_arr& B, mat_arr* C, const mat_tr tr) { return mat_element_by_element_operation(A, B, C, _mat_e_by_e_add_kernel(), tr); } struct _mat_e_by_e_sub_kernel { fpt operator()(fpt a, fpt b) const { return a - b; } }; mat_arr mat_element_wise_sub(const mat_arr& A, const mat_arr& B, mat_arr* C, const mat_tr tr) { return mat_element_by_element_operation(A, B, C, _mat_e_by_e_sub_kernel(), tr); } struct _mat_e_by_e_mul_kernel { fpt operator()(fpt a, fpt b) const { return a * b; } }; mat_arr mat_element_wise_mul(const mat_arr& A, const mat_arr& B, mat_arr* C, const mat_tr tr) { return mat_element_by_element_operation(A, B, C, _mat_e_by_e_mul_kernel(), tr); } struct _mat_e_by_e_div_kernel { fpt operator()(fpt a, fpt b) const { return a / b; } }; mat_arr mat_element_wise_div(const mat_arr& A, const mat_arr& B, mat_arr* C, const mat_tr tr) { return mat_element_by_element_operation(A, B, C, _mat_e_by_e_div_kernel(), tr); } struct _mat_e_by_e_max_kernel { fpt operator()(fpt a, fpt b) const { return std::max(a, b); } }; mat_arr mat_element_wise_max(const mat_arr& A, const mat_arr& B, mat_arr* C, mat_tr tr) { return mat_element_by_element_operation(A, B, C, _mat_e_by_e_max_kernel(), tr); } struct _mat_e_by_e_min_kernel { fpt operator()(fpt a, fpt b) const { return std::min(a, b); } }; mat_arr mat_element_wise_min(const mat_arr& A, const mat_arr& B, mat_arr* C, mat_tr tr) { return mat_element_by_element_operation(A, B, C, _mat_e_by_e_min_kernel(), tr); } struct _mat_e_wise_add_kernel { fpt b; explicit _mat_e_wise_add_kernel(fpt b) : b(b) { } fpt operator()(fpt a) const { return a + b; } }; mat_arr mat_element_wise_add(const mat_arr& A, fpt b, mat_arr* C) { return mat_element_wise_operation(A, C, _mat_e_wise_add_kernel(b)); } mat_arr mat_element_wise_add(fpt a, const mat_arr& B, mat_arr* C) { return mat_element_wise_operation(B, C, _mat_e_wise_add_kernel(a)); } struct _mat_e_wise_sub_kernel { fpt b; explicit _mat_e_wise_sub_kernel(fpt b) : b(b) { } fpt operator()(fpt a) const { return a - b; } }; mat_arr mat_element_wise_sub(const mat_arr& A, fpt b, mat_arr* C) { return mat_element_wise_operation(A, C, _mat_e_wise_sub_kernel(b)); } struct _mat_e_wise_sub_kernel2 { fpt a; explicit _mat_e_wise_sub_kernel2(fpt a) : a(a) { } fpt operator()(fpt b) const { return a - b; } }; mat_arr mat_element_wise_sub(fpt a, const mat_arr& B, mat_arr* C) { return mat_element_wise_operation(B, C, _mat_e_wise_sub_kernel2(a)); } struct _mat_e_wise_mul_kernel { fpt b; explicit _mat_e_wise_mul_kernel(fpt b) : b(b) { } fpt operator()(fpt a) const { return a * b; } }; mat_arr mat_element_wise_mul(const mat_arr& A, fpt b, mat_arr* C) { return mat_element_wise_operation(A, C, _mat_e_wise_mul_kernel(b)); } mat_arr mat_element_wise_mul(fpt a, const mat_arr& B, mat_arr* C) { return mat_element_wise_operation(B, C, _mat_e_wise_mul_kernel(a)); } struct _mat_e_wise_div_kernel { fpt b; explicit _mat_e_wise_div_kernel(fpt b) : b(b) { } fpt operator()(fpt a) const { return a / b; } }; mat_arr mat_element_wise_div(const mat_arr& A, fpt b, mat_arr* C) { return mat_element_wise_operation(A, C, _mat_e_wise_div_kernel(b)); } struct _mat_e_wise_div_kernel2 { fpt a; explicit _mat_e_wise_div_kernel2(fpt a) : a(a) { } fpt operator()(fpt b) const { return a / b; } }; mat_arr mat_element_wise_div(fpt a, const mat_arr& B, mat_arr* C) { return mat_element_wise_operation(B, C, _mat_e_wise_div_kernel2(a)); } struct _mat_e_wise_max_kernel { fpt b; explicit _mat_e_wise_max_kernel(fpt b) : b(b) { } fpt operator()(fpt a) const { return std::max(a, b); } }; mat_arr mat_element_wise_max(const mat_arr& A, float b, mat_arr* C) { return mat_element_wise_operation(A, C, _mat_e_wise_max_kernel(b)); } mat_arr mat_element_wise_max(float a, const mat_arr& B, mat_arr* C) { return mat_element_wise_operation(B, C, _mat_e_wise_max_kernel(a)); } struct _mat_e_wise_min_kernel { fpt b; explicit _mat_e_wise_min_kernel(fpt b) : b(b) { } fpt operator()(fpt a) const { return std::min(a, b); } }; mat_arr mat_element_wise_min(const mat_arr& A, float b, mat_arr* C) { return mat_element_wise_operation(A, C, _mat_e_wise_min_kernel(b)); } mat_arr mat_element_wise_min(float a, const mat_arr& B, mat_arr* C) { return mat_element_wise_operation(B, C, _mat_e_wise_min_kernel(a)); } inline void __matrix_mul_size_check(const unsigned count_a, const unsigned rows_a, const unsigned cols_a, const unsigned count_b, const unsigned rows_b, const unsigned cols_b, const unsigned count_c, const unsigned rows_c, const unsigned cols_c) { if (count_a != 1 && count_b != 1 && count_a != count_b) { throw std::runtime_error("Wrong input array sizes"); } if (count_c != std::max(count_a, count_b)) { throw std::runtime_error("Wrong output array sizes"); } if (cols_a != rows_b) { throw std::runtime_error("A and B cannot be multiplied"); } if (rows_a != rows_c || cols_b != cols_c) { throw std::runtime_error("C has wrong size"); } } struct _mat_mul_case0_kernel { // Cache miss analysis: Inner Loop // A fixed, B row-wise, C row-wise void operator()(unsigned l, unsigned m, unsigned n, const fpt* a, const fpt* b, fpt* c) const { for (unsigned i = 0; i < l; i++) { const fpt* a_row = a + i * m; fpt* c_row = c + i * n; for (unsigned j = 0; j < m; j++) { const fpt a_val = a_row[j]; const fpt* b_row = b + j * n; for (unsigned k = 0; k < n; k++) { c_row[k] += a_val * b_row[k]; } } } }; }; struct _mat_mul_case1_kernel { // Cache miss analysis: Inner Loop // A fixed, B row-wise, C row-wise void operator()(unsigned l, unsigned m, unsigned n, const fpt* a, const fpt* b, fpt* c) const { for (unsigned j = 0; j < m; j++) { const fpt* a_row = a + j * l; const fpt* b_row = b + j * n; for (unsigned i = 0; i < l; i++) { const fpt a_val = a_row[i]; fpt* c_row = c + i * n; for (unsigned k = 0; k < n; k++) { c_row[k] += a_val * b_row[k]; } } } }; }; struct _mat_mul_case2_kernel { // Cache miss analysis: Inner Loop // A row-wise, B row-wise, C fixed void operator()(unsigned l, unsigned m, unsigned n, const fpt* a, const fpt* b, fpt* c) const { for (unsigned i = 0; i < l; i++) { const fpt* a_row = a + i * m; fpt* c_row = c + i * n; for (unsigned k = 0; k < n; k++) { const fpt* b_row = b + k * m; fpt c_val = c_row[k]; for (unsigned j = 0; j < m; j++) { c_val += a_row[j] * b_row[j]; } c_row[k] = c_val; } } }; }; struct _mat_mul_case3_kernel { // Cache miss analysis: Inner Loop // A row-wise, B fixed, C column-wise (many cache misses!) void operator()(unsigned l, unsigned m, unsigned n, const fpt* a, const fpt* b, fpt* c) const { for (unsigned k = 0; k < n; k++) { const fpt* b_row = b + k * m; for (unsigned j = 0; j < m; j++) { const fpt* a_row = a + j * l; const fpt b_val = b_row[j]; for (unsigned i = 0; i < l; i++) { c[i * n + k] += a_row[i] * b_val; } } } }; }; template <typename Case> void __mat_matrix_mul_add_launch(const mat_arr& A, const mat_arr& B, mat_arr* C, unsigned l, unsigned m, unsigned n, Case cs) { const unsigned count = C->count; const fpt* a_start = A.start(); const fpt* b_start = B.start(); fpt* c_start = C->start(); const bool a_is_array = A.count > 1; const bool b_is_array = B.count > 1; for (unsigned matNo = 0; matNo < count; matNo++) { const fpt* a = a_is_array ? a_start + (matNo * l * m) : a_start; const fpt* b = b_is_array ? b_start + (matNo * m * n) : b_start; fpt* c = c_start + (matNo * l * n); cs(l, m, n, a, b, c); } #ifdef MATARRMATH_CHECK_NAN if (!C->only_real()) { throw std::runtime_error("nan"); } #endif } void __mat_matrix_mul_add(const mat_arr& A, const mat_arr& B, mat_arr* C, const mat_tr tr) { const bool transpose_a = tr == transpose_A || tr == transpose_both; const bool transpose_b = tr == transpose_B || tr == transpose_both; __matrix_mul_size_check(A.count, transpose_a ? A.cols : A.rows, transpose_a ? A.rows : A.cols, B.count, transpose_b ? B.cols : B.rows, transpose_b ? B.rows : B.cols, C->count, C->rows, C->cols); if (A.start() == C->start() || B.start() == C->start()) { throw std::runtime_error("Matrix mul in place not possible"); } switch (tr) { case transpose_no: __mat_matrix_mul_add_launch(A, B, C, A.rows, A.cols, B.cols, _mat_mul_case0_kernel()); return; case transpose_A: __mat_matrix_mul_add_launch(A, B, C, A.cols, A.rows, B.cols, _mat_mul_case1_kernel()); return; case transpose_B: __mat_matrix_mul_add_launch(A, B, C, A.rows, A.cols, B.rows, _mat_mul_case2_kernel()); return; case transpose_both: __mat_matrix_mul_add_launch(A, B, C, A.cols, A.rows, B.rows, _mat_mul_case3_kernel()); return; } } void __mat_matrix_mul(const mat_arr& A, const mat_arr& B, mat_arr* C, const mat_tr tr) { mat_set_all(0, C); __mat_matrix_mul_add(A, B, C, tr); } mat_arr mat_matrix_mul_add(const mat_arr& A, const mat_arr& B, mat_arr* C, const mat_tr tr) { if (C == nullptr) { mat_arr tempC = mat_arr(std::max(A.count, B.count), (tr == transpose_A || tr == transpose_both) ? A.cols : A.rows, (tr == transpose_B || tr == transpose_both) ? B.rows : B.cols); __mat_matrix_mul_add(A, B, &tempC, tr); return tempC; } __mat_matrix_mul_add(A, B, C, tr); return *C; } mat_arr mat_matrix_mul(const mat_arr& A, const mat_arr& B, mat_arr* C, const mat_tr tr) { if (C == nullptr) { mat_arr tempC = mat_arr(std::max(A.count, B.count), (tr == transpose_A || tr == transpose_both) ? A.cols : A.rows, (tr == transpose_B || tr == transpose_both) ? B.rows : B.cols); __mat_matrix_mul(A, B, &tempC, tr); return tempC; } __mat_matrix_mul(A, B, C, tr); return *C; } void __transpose_size_check(const unsigned count_a, const unsigned rows_a, const unsigned cols_a, const unsigned count_c, const unsigned rows_c, const unsigned cols_c) { if (count_a != count_c) { throw std::runtime_error("Wrong array sizes"); } if (rows_a != cols_c || cols_a != rows_c) { throw std::runtime_error("Wrong matrix dimensions"); } } void __mat_transpose(const mat_arr& A, mat_arr* C) { __transpose_size_check(A.count, A.rows, A.cols, C->count, C->rows, C->cols); const fpt* a_start = A.start(); fpt* c_start = C->start(); const unsigned count = C->count; const unsigned rows = C->rows; const unsigned cols = C->cols; for (unsigned mat_no = 0; mat_no < count; mat_no++) { const unsigned offset = mat_no * rows * cols; const fpt* a = a_start + offset; fpt* c = c_start + offset; unsigned i_normal = 0; unsigned i_transposed = 0; for (unsigned i = 0; i < rows; ++i) { for (unsigned col = 0; col < cols; ++col) { c[i_normal] = a[i_transposed]; i_normal++; i_transposed += rows; } i_transposed -= (cols * rows - 1); } } } mat_arr mat_transpose(const mat_arr& A, mat_arr* C) { if (C == nullptr) { const unsigned n_rows = A.cols; const unsigned n_cols = A.rows; mat_arr tempC = mat_arr(A.count, n_rows, n_cols); __mat_transpose(A, C); return tempC; } __mat_transpose(A, C); return *C; } mat_arr mat_set_all(fpt val, mat_arr* C) { if (C == nullptr) { throw std::runtime_error("C is nullptr"); } const unsigned size = C->size(); fpt* c = C->start(); for (unsigned i = 0; i < size; i++) { c[i] = val; } return *C; } void __mat_concat_size_check(const std::vector<mat_arr>& mats, mat_arr* C) { const auto mats_count = static_cast<unsigned>(mats.size()); unsigned count_sum = 0; for (unsigned i = 0; i < mats_count; i++) { if (C->rows != mats[i].rows) { throw std::runtime_error("Row count does not fit"); } if (C->cols != mats[i].cols) { throw std::runtime_error("Column count does not fit"); } count_sum += mats[i].count; } if (C->count != count_sum) { throw std::runtime_error("Array sizes do not fit"); } } void __mat_concat_mats(const std::vector<mat_arr>& mats, mat_arr* C) { __mat_concat_size_check(mats, C); const auto mat_arr_count = static_cast<unsigned>(mats.size()); const unsigned row_col = C->rows * C->cols; fpt* c = C->start(); for (unsigned mat_arr_no = 0; mat_arr_no < mat_arr_count; mat_arr_no++) { const unsigned size = row_col * mats[mat_arr_no].count; const fpt* m = mats[mat_arr_no].start(); for (unsigned i = 0; i < size; i++) { *c = *m; c++; m++; } } } mat_arr mat_concat_mats(const std::vector<mat_arr>& mats, mat_arr* C) { if (C == nullptr) { unsigned count = 0; for (const auto& mat : mats) { count += mat.count; } mat_arr tempC = mat_arr(count, mats[0].rows, mats[0].cols); __mat_concat_mats(mats, &tempC); return tempC; } __mat_concat_mats(mats, C); return *C; } void __mat_select_mats_size_check(const mat_arr& A, const std::vector<unsigned>& indices, mat_arr* C) { if (C->rows != A.rows) { throw std::runtime_error("Row count does not fit"); } if (C->cols != A.cols) { throw std::runtime_error("Column count does not fit"); } if (static_cast<unsigned>(indices.size()) != C->count) { throw std::runtime_error("Array sizes do not fit"); } } void __mat_select_mats(const mat_arr& A, const std::vector<unsigned>& indices, mat_arr* C) { __mat_select_mats_size_check(A, indices, C); const auto mat_count = static_cast<unsigned>(indices.size()); const unsigned row_col = C->rows * C->cols; const fpt* a_start = A.start(); fpt* c_start = C->start(); for (unsigned mat_no = 0; mat_no < mat_count; mat_no++) { const fpt* a = a_start + indices[mat_no] * row_col; fpt* c = c_start + (mat_no * row_col); for (unsigned i = 0; i < row_col; i++) { c[i] = a[i]; } } } mat_arr mat_select_mats(const mat_arr& A, const std::vector<unsigned>& indices, mat_arr* C) { if (C == nullptr) { mat_arr tempC = mat_arr(static_cast<unsigned>(indices.size()), A.rows, A.cols); __mat_select_mats(A, indices, &tempC); return tempC; } __mat_select_mats(A, indices, C); return *C; } mat_arr mat_random_gaussian(fpt mean, fpt sigma, std::mt19937* rnd, mat_arr* C) { std::normal_distribution<fpt> distr(mean, sigma); return mat_element_wise_operation(*C, C, [&](fpt a) { return distr(*rnd); }); } mat_arr mat_copy(const mat_arr& A, mat_arr* C) { return mat_element_wise_operation(A, C, [](fpt a) { return a; }); } mat_arr mat_max(const mat_arr& A, mat_arr* C) { return mat_aggregate(A, C, -1.0f * std::numeric_limits<fpt>::infinity(), _mat_e_by_e_max_kernel()); } mat_arr mat_min(const mat_arr& A, mat_arr* C) { return mat_aggregate(A, C, std::numeric_limits<fpt>::infinity(), _mat_e_by_e_min_kernel()); } mat_arr mat_sum(const mat_arr& A, mat_arr* C) { return mat_aggregate(A, C, 0.0f, _mat_e_by_e_add_kernel()); } mat_arr mat_product(const mat_arr& A, mat_arr* C) { return mat_aggregate(A, C, 1.0f, _mat_e_by_e_mul_kernel()); } float mat_total_max(const mat_arr& A) { return mat_total_aggregate(A, -1.0f * std::numeric_limits<fpt>::infinity(), _mat_e_by_e_max_kernel()); } float mat_total_min(const mat_arr& A) { return mat_total_aggregate(A, std::numeric_limits<fpt>::infinity(), _mat_e_by_e_min_kernel()); } float mat_total_sum(const mat_arr& A) { return mat_total_aggregate(A, 0.0f, _mat_e_by_e_add_kernel()); } float mat_total_product(const mat_arr& A) { return mat_total_aggregate(A, 1.0f, _mat_e_by_e_mul_kernel()); } }
23.105915
106
0.624836
mirkoruether
4a70b65caf147a534596463ea67c3eb62d134bb2
3,573
cpp
C++
src/net/https/openssl_server.cpp
justinc1/IncludeOS
2ce07b04e7a35c8d96e773f041db32a4593ca3d0
[ "Apache-2.0" ]
null
null
null
src/net/https/openssl_server.cpp
justinc1/IncludeOS
2ce07b04e7a35c8d96e773f041db32a4593ca3d0
[ "Apache-2.0" ]
null
null
null
src/net/https/openssl_server.cpp
justinc1/IncludeOS
2ce07b04e7a35c8d96e773f041db32a4593ca3d0
[ "Apache-2.0" ]
null
null
null
#include <net/https/openssl_server.hpp> #include <net/openssl/init.hpp> #include <net/openssl/tls_stream.hpp> #include <memdisk> #define LOAD_FROM_MEMDISK namespace http { // https://gist.github.com/darrenjs/4645f115d10aa4b5cebf57483ec82eca inline void handle_error(const char* file, int lineno, const char* msg) { fprintf(stderr, "** %s:%i %s\n", file, lineno, msg); ERR_print_errors_fp(stderr); exit(1); } #define int_error(msg) handle_error(__FILE__, __LINE__, msg) static void tls_load_from_memory(SSL_CTX* ctx, fs::Buffer cert_buffer, fs::Buffer key_buffer) { auto* cbio = BIO_new_mem_buf(cert_buffer.data(), cert_buffer.size()); auto* cert = PEM_read_bio_X509(cbio, NULL, 0, NULL); assert(cert != NULL); SSL_CTX_use_certificate(ctx, cert); BIO_free(cbio); auto* kbio = BIO_new_mem_buf(key_buffer.data(), key_buffer.size()); auto* key = PEM_read_bio_RSAPrivateKey(kbio, NULL, 0, NULL); assert(key != NULL); SSL_CTX_use_RSAPrivateKey(ctx, key); BIO_free(kbio); } SSL_CTX* tls_init_server(const char* cert_file, const char* key_file) { /* create the SSL server context */ auto meth = TLSv1_1_method(); auto* ctx = SSL_CTX_new(meth); if (!ctx) throw std::runtime_error("SSL_CTX_new()"); int res = SSL_CTX_set_cipher_list(ctx, "AES256-SHA"); assert(res == 1); #ifdef LOAD_FROM_MEMDISK auto& filesys = fs::memdisk().fs(); // load CA certificate auto ca_cert_buffer = filesys.read_file(cert_file); // load CA private key auto ca_key_buffer = filesys.read_file(key_file); // use in SSL CTX tls_load_from_memory(ctx, ca_cert_buffer, ca_key_buffer); #else /* Load certificate and private key files, and check consistency */ int err; err = SSL_CTX_use_certificate_file(ctx, cert_file, SSL_FILETYPE_PEM); if (err != 1) int_error("SSL_CTX_use_certificate_file failed"); /* Indicate the key file to be used */ err = SSL_CTX_use_PrivateKey_file(ctx, key_file, SSL_FILETYPE_PEM); if (err != 1) int_error("SSL_CTX_use_PrivateKey_file failed"); #endif /* Make sure the key and certificate file match. */ if (SSL_CTX_check_private_key(ctx) != 1) int_error("SSL_CTX_check_private_key failed"); /* Recommended to avoid SSLv2 & SSLv3 */ SSL_CTX_set_options(ctx, SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3); int error = ERR_get_error(); if (error) { printf("Status: %s\n", ERR_error_string(error, nullptr)); } assert(error == SSL_ERROR_NONE); return ctx; } void OpenSSL_server::openssl_initialize(const std::string& certif, const std::string& key) { fs::memdisk().init_fs( [] (auto err, auto&) { assert(!err); }); /** INIT OPENSSL **/ openssl::init(); /** SETUP CUSTOM RNG **/ //openssl::setup_rng(); /** VERIFY RNG **/ openssl::verify_rng(); this->m_ctx = tls_init_server(certif.c_str(), key.c_str()); assert(ERR_get_error() == 0); } OpenSSL_server::~OpenSSL_server() { SSL_CTX_free((SSL_CTX*) this->m_ctx); } void OpenSSL_server::bind(const uint16_t port) { tcp_.listen(port, {this, &OpenSSL_server::on_connect}); INFO("HTTPS Server", "Listening on port %u", port); } void OpenSSL_server::on_connect(TCP_conn conn) { connect( std::make_unique<openssl::TLS_stream> ((SSL_CTX*) m_ctx, std::make_unique<net::tcp::Connection::Stream>(std::move(conn))) ); } } // http
30.801724
127
0.655751
justinc1
4a73474550dfb568e4ff71f431ce047fc4915952
6,976
cpp
C++
Libs/bullet/BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.cpp
stinvi/dava.engine
2b396ca49cdf10cdc98ad8a9ffcf7768a05e285e
[ "BSD-3-Clause" ]
26
2018-09-03T08:48:22.000Z
2022-02-14T05:14:50.000Z
Libs/bullet/BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.cpp
ANHELL-blitz/dava.engine
ed83624326f000866e29166c7f4cccfed1bb41d4
[ "BSD-3-Clause" ]
null
null
null
Libs/bullet/BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.cpp
ANHELL-blitz/dava.engine
ed83624326f000866e29166c7f4cccfed1bb41d4
[ "BSD-3-Clause" ]
45
2018-05-11T06:47:17.000Z
2022-02-03T11:30:55.000Z
/*================================================================================== Copyright (c) 2008, binaryzebra 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 binaryzebra 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 binaryzebra 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 binaryzebra 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. =====================================================================================*/ /* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org 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. */ #include "btScaledBvhTriangleMeshShape.h" btScaledBvhTriangleMeshShape::btScaledBvhTriangleMeshShape(btBvhTriangleMeshShape* childShape, const btVector3& localScaling) : m_localScaling(localScaling) , m_bvhTriMeshShape(childShape) { m_shapeType = SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE; } btScaledBvhTriangleMeshShape::~btScaledBvhTriangleMeshShape() { } class btScaledTriangleCallback : public btTriangleCallback { btTriangleCallback* m_originalCallback; btVector3 m_localScaling; public: btScaledTriangleCallback(btTriangleCallback* originalCallback, const btVector3& localScaling) : m_originalCallback(originalCallback) , m_localScaling(localScaling) { } virtual void processTriangle(btVector3* triangle, int partId, int triangleIndex) { btVector3 newTriangle[3]; newTriangle[0] = triangle[0] * m_localScaling; newTriangle[1] = triangle[1] * m_localScaling; newTriangle[2] = triangle[2] * m_localScaling; m_originalCallback->processTriangle(&newTriangle[0], partId, triangleIndex); } }; void btScaledBvhTriangleMeshShape::processAllTriangles(btTriangleCallback* callback, const btVector3& aabbMin, const btVector3& aabbMax) const { btScaledTriangleCallback scaledCallback(callback, m_localScaling); btVector3 invLocalScaling(1.f / m_localScaling.getX(), 1.f / m_localScaling.getY(), 1.f / m_localScaling.getZ()); btVector3 scaledAabbMin, scaledAabbMax; ///support negative scaling scaledAabbMin[0] = m_localScaling.getX() >= 0. ? aabbMin[0] * invLocalScaling[0] : aabbMax[0] * invLocalScaling[0]; scaledAabbMin[1] = m_localScaling.getY() >= 0. ? aabbMin[1] * invLocalScaling[1] : aabbMax[1] * invLocalScaling[1]; scaledAabbMin[2] = m_localScaling.getZ() >= 0. ? aabbMin[2] * invLocalScaling[2] : aabbMax[2] * invLocalScaling[2]; scaledAabbMin[3] = 0.f; scaledAabbMax[0] = m_localScaling.getX() <= 0. ? aabbMin[0] * invLocalScaling[0] : aabbMax[0] * invLocalScaling[0]; scaledAabbMax[1] = m_localScaling.getY() <= 0. ? aabbMin[1] * invLocalScaling[1] : aabbMax[1] * invLocalScaling[1]; scaledAabbMax[2] = m_localScaling.getZ() <= 0. ? aabbMin[2] * invLocalScaling[2] : aabbMax[2] * invLocalScaling[2]; scaledAabbMax[3] = 0.f; m_bvhTriMeshShape->processAllTriangles(&scaledCallback, scaledAabbMin, scaledAabbMax); } void btScaledBvhTriangleMeshShape::getAabb(const btTransform& trans, btVector3& aabbMin, btVector3& aabbMax) const { btVector3 localAabbMin = m_bvhTriMeshShape->getLocalAabbMin(); btVector3 localAabbMax = m_bvhTriMeshShape->getLocalAabbMax(); btVector3 tmpLocalAabbMin = localAabbMin * m_localScaling; btVector3 tmpLocalAabbMax = localAabbMax * m_localScaling; localAabbMin[0] = (m_localScaling.getX() >= 0.) ? tmpLocalAabbMin[0] : tmpLocalAabbMax[0]; localAabbMin[1] = (m_localScaling.getY() >= 0.) ? tmpLocalAabbMin[1] : tmpLocalAabbMax[1]; localAabbMin[2] = (m_localScaling.getZ() >= 0.) ? tmpLocalAabbMin[2] : tmpLocalAabbMax[2]; localAabbMax[0] = (m_localScaling.getX() <= 0.) ? tmpLocalAabbMin[0] : tmpLocalAabbMax[0]; localAabbMax[1] = (m_localScaling.getY() <= 0.) ? tmpLocalAabbMin[1] : tmpLocalAabbMax[1]; localAabbMax[2] = (m_localScaling.getZ() <= 0.) ? tmpLocalAabbMin[2] : tmpLocalAabbMax[2]; btVector3 localHalfExtents = btScalar(0.5) * (localAabbMax - localAabbMin); btScalar margin = m_bvhTriMeshShape->getMargin(); localHalfExtents += btVector3(margin, margin, margin); btVector3 localCenter = btScalar(0.5) * (localAabbMax + localAabbMin); btMatrix3x3 abs_b = trans.getBasis().absolute(); btVector3 center = trans(localCenter); btVector3 extent = btVector3(abs_b[0].dot(localHalfExtents), abs_b[1].dot(localHalfExtents), abs_b[2].dot(localHalfExtents)); aabbMin = center - extent; aabbMax = center + extent; } void btScaledBvhTriangleMeshShape::setLocalScaling(const btVector3& scaling) { m_localScaling = scaling; } const btVector3& btScaledBvhTriangleMeshShape::getLocalScaling() const { return m_localScaling; } void btScaledBvhTriangleMeshShape::calculateLocalInertia(btScalar mass, btVector3& inertia) const { ///don't make this a movable object! // btAssert(0); }
47.135135
243
0.724914
stinvi
4a73c220ee987a66d0220c899940fef195bbe26f
896
hpp
C++
stan/math/rev/fun/log1p_exp.hpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
null
null
null
stan/math/rev/fun/log1p_exp.hpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
null
null
null
stan/math/rev/fun/log1p_exp.hpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_MATH_REV_FUN_LOG1P_EXP_HPP #define STAN_MATH_REV_FUN_LOG1P_EXP_HPP #include <stan/math/rev/meta.hpp> #include <stan/math/rev/core.hpp> #include <stan/math/prim/fun/inv_logit.hpp> #include <stan/math/prim/fun/log1p_exp.hpp> namespace stan { namespace math { /** * Return the log of 1 plus the exponential of the specified * variable. * @tparam T Arithmetic or a type inheriting from `EigenBase`. * @param a The variable. */ template <typename T, require_stan_scalar_or_eigen_t<T>* = nullptr> inline auto log1p_exp(const var_value<T>& a) { auto precomp_inv_logit = to_arena(as_array_or_scalar(inv_logit(a.val()))); return make_callback_var( log1p_exp(a.val()), [a, precomp_inv_logit](auto& vi) mutable { as_array_or_scalar(a.adj()) += as_array_or_scalar(vi.adj()) * precomp_inv_logit; }); } } // namespace math } // namespace stan #endif
28.903226
76
0.722098
LaudateCorpus1
4a759bf0128590cc8ee8c0da81b80a79445de7d0
16,447
cpp
C++
src/plugins/dist_matrixops/dist_inverse_operation.cpp
kmoham6/phylanx
252fa5fbb84acaf6f999410e6823b9f8d6693213
[ "BSL-1.0" ]
null
null
null
src/plugins/dist_matrixops/dist_inverse_operation.cpp
kmoham6/phylanx
252fa5fbb84acaf6f999410e6823b9f8d6693213
[ "BSL-1.0" ]
null
null
null
src/plugins/dist_matrixops/dist_inverse_operation.cpp
kmoham6/phylanx
252fa5fbb84acaf6f999410e6823b9f8d6693213
[ "BSL-1.0" ]
1
2021-07-25T15:44:01.000Z
2021-07-25T15:44:01.000Z
// Copyright (c) 2020 Rory Hector // Copyright (c) 2018-2020 Hartmut Kaiser // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <phylanx/config.hpp> #include <phylanx/execution_tree/annotation.hpp> #include <phylanx/execution_tree/localities_annotation.hpp> #include <phylanx/execution_tree/locality_annotation.hpp> #include <phylanx/execution_tree/meta_annotation.hpp> #include <phylanx/execution_tree/primitives/node_data_helpers.hpp> #include <phylanx/execution_tree/tiling_annotations.hpp> #include <phylanx/ir/node_data.hpp> #include <phylanx/plugins/dist_matrixops/dist_inverse_operation.hpp> #include <phylanx/plugins/dist_matrixops/tile_calculation_helper.hpp> #include <phylanx/util/detail/bad_swap.hpp> #include <hpx/errors/throw_exception.hpp> #include <hpx/include/lcos.hpp> #include <hpx/include/naming.hpp> #include <hpx/include/util.hpp> #include <hpx/futures/future.hpp> #include <algorithm> #include <cmath> #include <cstddef> #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include <blaze/Math.h> #include <blaze_tensor/Math.h> #include <phylanx/util/distributed_matrix.hpp> namespace phylanx { namespace dist_matrixops { namespace primitives { constexpr char const* const help_string = R"( inverse_d(matrix) Args: blaze dynamic matrix Returns: the inverse of the matrix )"; execution_tree::match_pattern_type const dist_inverse::match_data = { hpx::make_tuple("inverse_d", std::vector<std::string>{R"( inverse_d( _1_matrix ))"}, &create_dist_inverse, &execution_tree::create_primitive<dist_inverse>, help_string)}; dist_inverse::dist_inverse( execution_tree::primitive_arguments_type&& operands, std::string const& name, std::string const& codename) : primitive_component_base(std::move(operands), name, codename) , transferred_bytes_(0) { } std::int64_t dist_inverse::get_transferred_bytes(bool reset) const { return hpx::util::get_and_reset_value(transferred_bytes_, reset); } // find the first column belonging to a locality std::size_t getStartCol(std::size_t id, std::size_t n, std::size_t numLocs) { std::size_t startCol = id * (n / numLocs) + ((id < n % numLocs) ? id : (n % numLocs)); return startCol; } // find the final column belonging to a locality std::size_t getEndCol(std::size_t id, std::size_t n, std::size_t numLocs) { std::size_t endCol; if (id == numLocs - 1) endCol = n; else endCol = getStartCol(id + 1, n, numLocs); return endCol; } // find the locality who holds a given column locally std::size_t findOwningLoc( std::size_t n, std::size_t numLocs, std::size_t col) { std::size_t id; if (col < (n % numLocs) * (n / numLocs + 1)) id = col / ((n / numLocs) + 1); else id = (n % numLocs) + ((col - (n % numLocs) * (n / numLocs + 1)) / (n / numLocs)); return id; } // This is where the computation of the inverse is performed. template <typename T> execution_tree::primitive_argument_type dist_inverse::distGaussInv( ir::node_data<T>&& arg, execution_tree::localities_information&& lhs_localities) const { if (lhs_localities.num_dimensions() != 2) { HPX_THROW_EXCEPTION(hpx::bad_parameter, "dist_inverse::distGaussInv", generate_error_message("the input must be a 2d matrix")); } std::size_t thisLocalityID = lhs_localities.locality_.locality_id_; std::size_t numLocalities = lhs_localities.locality_.num_localities_; util::distributed_matrix<T> lhs_data(lhs_localities.annotation_.name_, arg.matrix(), lhs_localities.locality_.num_localities_, lhs_localities.locality_.locality_id_, &transferred_bytes_); auto myMatrix = arg.matrix(); std::size_t numRows = myMatrix.rows(); std::size_t numCols = myMatrix.columns(); // Define some additional information on where // columns lie in the full input std::size_t startCol = thisLocalityID * (numRows / numLocalities) + ((thisLocalityID < (numRows % numLocalities)) ? thisLocalityID : (numRows % numLocalities)); std::size_t endCol = startCol + numCols - 1; // Definition of this loc's part of a nxn double row-major identity matrix blaze::DynamicMatrix<double> invMatrix = blaze::submatrix(blaze::IdentityMatrix<double>(numRows), 0, startCol, arg.matrix().rows(), arg.matrix().columns()); // Do gaussian elimination to get upper triangular // matrix with 1's across diagonal for (std::size_t current_row = 0; current_row != numRows; current_row++) { // Find the locality that owns the pivot element then get the pivot std::size_t ownid1 = findOwningLoc(numRows, numLocalities, current_row); std::size_t localIndexOffset = current_row - getStartCol(ownid1, numRows, numLocalities); auto pulledColumn = lhs_data .fetch(ownid1, current_row, localIndexOffset, numRows, localIndexOffset + 1) .get(); double pivot = pulledColumn(0, 0); if (numLocalities > 1) { hpx::lcos::barrier b2( "barrierb_" + lhs_localities.annotation_.name_, lhs_localities.locality_.num_localities_, lhs_localities.locality_.locality_id_); b2.wait(); } // Swaps current row with nearest subsequent row such that // after swapping A[current_row][current_row] != 0. if (pivot == 0) { bool rowFound = false; std::size_t checkOffset = 1; while (current_row + checkOffset != numRows && !rowFound) { pivot = pulledColumn(checkOffset, 0); if (pivot != 0) { std::size_t checkRow = (current_row + checkOffset) % numRows; for (std::size_t swapCol = 0; swapCol!=numCols; swapCol++) { auto temp = (*lhs_data)(current_row, swapCol); (*lhs_data)(current_row, swapCol) = (*lhs_data)(checkRow, swapCol); (*lhs_data)(checkRow, swapCol) = temp; auto invtemp = invMatrix(current_row, swapCol); invMatrix(current_row, swapCol) = invMatrix(checkRow, swapCol); invMatrix(checkRow, swapCol) = invtemp; } rowFound = true; } else checkOffset++; } // swap row with nearest subsequent row such that after // swapping A[i][i] != 0 // if fails, inverse does not exist if (!rowFound) { HPX_THROW_EXCEPTION(hpx::bad_parameter, "dist_inverse::distGaussInv", generate_error_message("inverse does not exist")); } current_row--; // After swapping, make sure to retry this row } else // the inversion has not already failed { for (std::size_t col = 0; col != numCols; col++) { (*lhs_data)(current_row, col) = (*lhs_data)(current_row, col) / pivot; invMatrix(current_row, col) = invMatrix(current_row, col) / pivot; } if (current_row < numRows - 1) { for (std::size_t nextRow = current_row + 1; nextRow != numRows; nextRow++) { // Find the locality that owns the pivot element // then get the pivot std::size_t ownid2 = findOwningLoc( numRows, numLocalities, current_row); std::size_t localIndexOffset2 = current_row - getStartCol(ownid2, numRows, numLocalities); auto pulledElement = lhs_data .fetch(ownid2, nextRow, localIndexOffset2, nextRow + 1, localIndexOffset2 + 1) .get(); double factor = pulledElement(0, 0); // Removing this barrier causes errors if (numLocalities > 1) { hpx::lcos::barrier b5("barriere_" + lhs_localities.annotation_.name_, lhs_localities.locality_.num_localities_, lhs_localities.locality_.locality_id_); b5.wait(); } for (std::size_t nextCol = 0; nextCol != numCols; nextCol++) { (*lhs_data)(nextRow, nextCol) = (*lhs_data)(nextRow, nextCol) - (factor * (*lhs_data)(current_row, nextCol)); invMatrix(nextRow, nextCol) = invMatrix(nextRow, nextCol) - (factor * invMatrix(current_row, nextCol)); } } } } } // Back substitution phase, going from bottom to top // in matrix zeroing out columns except diagonal for (std::size_t zeroCol = numRows - 1; zeroCol != 0; zeroCol--) { for (std::int64_t row = zeroCol - 1; row != -1; row--) { // Find the locality that owns the pivot element then get the pivot std::size_t ownid3 = findOwningLoc(numRows, numLocalities, zeroCol); std::size_t localIndexOffset3 = zeroCol - getStartCol(ownid3, numRows, numLocalities); auto pulledElement = lhs_data .fetch(ownid3, row, localIndexOffset3, row + 1, localIndexOffset3 + 1) .get(); double factor = pulledElement(0, 0); // Removing this barrier causes errors if (numLocalities > 1) { hpx::lcos::barrier b8( "barrierg_" + lhs_localities.annotation_.name_, lhs_localities.locality_.num_localities_, lhs_localities.locality_.locality_id_); b8.wait(); } for (std::size_t col = 0; col != numCols; col++) { myMatrix(row, col) = myMatrix(row, col) - (factor * myMatrix(zeroCol, col)); invMatrix(row, col) = invMatrix(row, col) - (factor * invMatrix(zeroCol, col)); } } } // Prepare the output execution_tree::primitive_argument_type result = execution_tree::primitive_argument_type{invMatrix}; execution_tree::annotation ann{ir::range("tile", ir::range("rows", static_cast<std::int64_t>(0), static_cast<std::int64_t>(numRows)), ir::range("columns", static_cast<std::int64_t>(startCol), static_cast<std::int64_t>(endCol+1)))}; // Generate new tiling annotation for the result vector execution_tree::tiling_information_2d tile_info( ann, name_, codename_); ++lhs_localities.annotation_.generation_; auto locality_ann = lhs_localities.locality_.as_annotation(); result.set_annotation( execution_tree::localities_annotation(locality_ann, tile_info.as_annotation(name_, codename_), lhs_localities.annotation_, name_, codename_), name_, codename_); return result; } // This is where the computation of the inverse should be performed. execution_tree::primitive_argument_type dist_inverse::distGaussInv( execution_tree::primitive_argument_type&& lhs) const { using namespace execution_tree; execution_tree::localities_information lhs_localities = extract_localities_information(lhs, name_, codename_); switch (extract_numeric_value_dimension(lhs, name_, codename_)) { case 2: // Do the inverse operation return distGaussInv( extract_numeric_value(std::move(lhs), name_, codename_), std::move(lhs_localities)); default: HPX_THROW_EXCEPTION(hpx::bad_parameter, " dist_inverse::distGaussInv", generate_error_message("left hand side operand has unsupported " "number of dimensions")); } } // Call the evaluation function hpx::future<execution_tree::primitive_argument_type> dist_inverse::eval( execution_tree::primitive_arguments_type const& operands, execution_tree::primitive_arguments_type const& args, execution_tree::eval_context ctx) const { using namespace execution_tree; // Check to make sure there is exactly one item to invert if (operands.size() != 1) { HPX_THROW_EXCEPTION(hpx::bad_parameter, "dist_inverse::eval", generate_error_message( "the gaussian inverse operation primitive requires" "exactly one operand")); } // Check if there are no valid operands if (!valid(operands[0])) { HPX_THROW_EXCEPTION(hpx::bad_parameter, "dist_inverse::eval", generate_error_message( "the gaussian_inverse_operation primitive requires that " "the arguments given by the operands array is valid")); } // Get a future to the result of the actual computation auto this_ = this->shared_from_this(); return hpx::dataflow(hpx::launch::sync, hpx::util::unwrapping( [this_ = std::move(this_)](primitive_arguments_type&& args) -> primitive_argument_type { return this_->distGaussInv(std::move(args[0])); }), execution_tree::primitives::detail::map_operands(operands, execution_tree::functional::value_operand{}, args, name_, codename_, std::move(ctx))); } }}}
41.743655
87
0.516021
kmoham6
4a764191c7adbcb8350eed177c1f465a50fd4279
6,780
cpp
C++
Tetris Source/BlockOverlay.cpp
mattacer/Tetris
2a553ec955d7742c9797504464f63af05e981663
[ "MIT" ]
null
null
null
Tetris Source/BlockOverlay.cpp
mattacer/Tetris
2a553ec955d7742c9797504464f63af05e981663
[ "MIT" ]
null
null
null
Tetris Source/BlockOverlay.cpp
mattacer/Tetris
2a553ec955d7742c9797504464f63af05e981663
[ "MIT" ]
1
2019-02-07T03:29:13.000Z
2019-02-07T03:29:13.000Z
/* BlockOverlay.cpp Defines the methods and members of the BlockOverlay class. */ #include "BlockOverlay.h" //Default BlockOverlay class constructor BlockOverlay::BlockOverlay(){ blocks = nullptr; blockCount = 0; this->clearGrid(); } //Constructor that accepts a pointer to a set of Block instances for initiation BlockOverlay::BlockOverlay(Block* newBlocks, int count){ blocks = new Block[count]; for (int i = 0; i < blockCount; i++){ blocks[i] = newBlocks[i]; } blockCount = count; this->updateGrid(); } //BlockOverlay Class Destructor BlockOverlay::~BlockOverlay(){ delete[] blocks; } //Draws the BlockOverlay instance by calling each Block instances draw method void BlockOverlay::draw(){ for (int i = 0; i < blockCount; i++){ blocks[i].draw(); } } //Deletes the block instances, sets the block count to zero, and calls the clearGrid method //To be called when a new game is started void BlockOverlay::clear(){ delete[] blocks; blocks = nullptr; blockCount = 0; this->clearGrid(); } //Adds the Block instances of a Tetrimino instance to the calling BlockOverlay instance void BlockOverlay::addTetriminoBlocks(Tetrimino* blockSource){ Block* tempBlocks = blocks; blocks = new Block[blockCount + blockSource->getBlockCount()]; for (int i = 0; i < blockCount; i++){ blocks[i] = tempBlocks[i]; } delete[] tempBlocks; for (int i = 0; i < blockSource->getBlockCount(); i++){ blocks[blockCount + i] = blockSource->getBlock(i); } blockCount = blockCount + blockSource->getBlockCount(); this->updateGrid(); } //Sets all boolean values in the grid array to false void BlockOverlay::clearGrid(){ for (int i = 0; i < BLOCKS_PER_GRID_WIDTH; i++){ for (int j = 0; j < BLOCKS_PER_GRID_HEIGHT; j++){ grid[i][j] = false; } } } //Iterates through all Block instances in the calling BlockOverlay instance, //setting their corresponding location in the grid array as true, when false //Returns false if two blocks have the same location //Returns true when blocks have unique locations bool BlockOverlay::updateGrid(){ this->clearGrid(); int indexX, indexY = 0; for (int i = 0; i < blockCount; i++){ indexX = blocks[i].getX() / BLOCK_LENGTH; indexY = blocks[i].getY() / BLOCK_LENGTH; if (grid[indexX][indexY] == false){ grid[indexX][indexY] = true; } else { return false; } } return true; } //Returns true when a complete horizontal line of blocks exists, otherwise returns false bool BlockOverlay::linesPresent(){ for (int i = BLOCKS_PER_GRID_HEIGHT - 1; i >= 0; i--){ for (int j = 0; j < BLOCKS_PER_GRID_WIDTH; j++){ if (grid[j][i] == false){ break; } if (j == BLOCKS_PER_GRID_WIDTH - 1 && grid[j][i] == true){ return true; } } } return false; } //Finds the lowest occuring line of blocks, then deletes blocks on that line //Moves blocks down once, if they are above that line void BlockOverlay::clearLowestLine(){ int lowestLine = 0; int indexX = 0; int indexY = 0; for (int i = BLOCKS_PER_GRID_HEIGHT - 1; i >= 0 && i >= lowestLine; i--){ for (int j = 0; j < BLOCKS_PER_GRID_WIDTH; j++){ if (grid[j][i] == false){ break; } if (j == BLOCKS_PER_GRID_WIDTH - 1 && grid[j][i] == true){ lowestLine = i; break; } } } Block* tempBlocks = blocks; blocks = new Block[blockCount - BLOCKS_PER_GRID_WIDTH]; int j = 0; for (int i = 0; i < blockCount; i++){ indexY = tempBlocks[i].getY() / BLOCK_LENGTH; if (indexY > lowestLine){ blocks[j] = tempBlocks[i]; j++; } else if (indexY < lowestLine){ tempBlocks[i].moveDown(); blocks[j] = tempBlocks[i]; j++; } } blockCount -= BLOCKS_PER_GRID_WIDTH; delete[] tempBlocks; this->updateGrid(); } //Tests whether a Tetrimino instance will go out of boundary or overlap the BlockOverlay blocks, if it is rotated //Returns true if a rotation will not cause the tetrimino to overlap or go out of bounds bool BlockOverlay::tetriminoCanRotate(Tetrimino* current){ Tetrimino* tempTetrimino = current->clone(); tempTetrimino->rotate(); if (withinBoundary(tempTetrimino)){ return !checkForOverlap(tempTetrimino); } else { return false; } } //Tests whether a Tetrimino instance will go out of boundary or overlap the BlockOverlay blocks, when moved left //Returns true if a left movement will not cause the tetrimino to overlap or go out of bounds bool BlockOverlay::tetriminoCanMoveLeft(Tetrimino* current){ Tetrimino* tempTetrimino = current->clone(); tempTetrimino->moveLeft(); if (withinBoundary(tempTetrimino)){ return !checkForOverlap(tempTetrimino); } else { return false; } } //Tests whether a Tetrimino instance will go out of boundary or overlap the BlockOverlay blocks, when moved right //Returns true if a right movement will not cause the tetrimino to overlap or go out of bounds bool BlockOverlay::tetriminoCanMoveRight(Tetrimino* current){ Tetrimino* tempTetrimino = current->clone(); tempTetrimino->moveRight(); if (withinBoundary(tempTetrimino)){ return !checkForOverlap(tempTetrimino); } else { return false; } } //Tests whether a Tetrimino instance will go out of boundary or overlap the BlockOverlay blocks, when moved down //Returns true if a downward movement will not cause the tetrimino to overlap or go out of bounds bool BlockOverlay::tetriminoCanMoveDown(Tetrimino* current){ Tetrimino* tempTetrimino = current->clone(); tempTetrimino->moveDown(); if (withinBoundary(tempTetrimino)){ return !checkForOverlap(tempTetrimino); } else { return false; } } //Tests a Tetrimino instance for Block instances that overlap the blocks of the BlockOverlay instance //Returns true if overlap occurs, otherwise returns false bool BlockOverlay::checkForOverlap(Tetrimino* tetrimino){ int x, y; for (int i = 0; i < tetrimino->getBlockCount(); i++){ x = tetrimino->getBlock(i).getX() / BLOCK_LENGTH; y = tetrimino->getBlock(i).getY() / BLOCK_LENGTH; if (grid[x][y] == true){ return true; } } return false; } //Tests whether a Tetrimino instance is within the play area boundaries //Returns false if a block is outside the boundaries, otherwise returns true bool BlockOverlay::withinBoundary(Tetrimino* tetrimino){ int x, y; for (int i = 0; i < tetrimino->getBlockCount(); i++){ x = tetrimino->getBlock(i).getX(); y = tetrimino->getBlock(i).getY(); if (!(x >= 0 && x <= BLOCK_GRID_WIDTH - BLOCK_LENGTH && y >= 0 && y <= HEIGHT - BLOCK_LENGTH)){ return false; } } return true; } int BlockOverlay::getBlockCount(){ return blockCount; } Block BlockOverlay::getBlock(int index){ return blocks[index]; }
30.403587
114
0.683628
mattacer
4a7a0371f8f2bc0e538528e06a14651e16ac9dcb
1,325
hpp
C++
include/daq_ni.hpp
gadzooks00/AbsoluteThreshold_AIMS-Fork-
aa26ae3af9b165b3d2c95e472c9a20faa302a0c2
[ "MIT" ]
null
null
null
include/daq_ni.hpp
gadzooks00/AbsoluteThreshold_AIMS-Fork-
aa26ae3af9b165b3d2c95e472c9a20faa302a0c2
[ "MIT" ]
null
null
null
include/daq_ni.hpp
gadzooks00/AbsoluteThreshold_AIMS-Fork-
aa26ae3af9b165b3d2c95e472c9a20faa302a0c2
[ "MIT" ]
null
null
null
/* File: daq_ni.cpp ________________________________ Author(s): Zane Zook (gadzooks@rice.edu) This file defines the DaqNI class which holds all the lower level commands sent to the National Instruments DAQ used for this experiment set. This specific version is customized to work with the two ATI sensors hooked up to the PCIe-6323 board connected to the two ATI Nano 25 sensors. Uses MEL's development ATIsensor class. */ #ifndef DAQNI #define DAQNI /*********************************************************** ******************** LIBRARY IMPORT ************************ ************************************************************/ // libraries for MEL #include <MEL/Logging/Csv.hpp> #include <MEL/Daq/Input.hpp> // C libraries #include "NIDAQmx.h" /*********************************************************** ****************** CLASS DECLARATION *********************** ************************************************************/ class DaqNI : public mel::AnalogInput, mel::NonCopyable { private: // member variables TaskHandle task_handle_; // creates a new task_handle_ signed long error_; signed long read_; char error_buffer_[2048] = { '\0' }; public: // constructor DaqNI(); ~DaqNI(); // DAQ update functions bool update(); bool update_channel(mel::uint32 channel_number); }; #endif DAQNI
27.604167
61
0.563019
gadzooks00
4a81b95fe28284ed008d5d7bf2e8f4bdcfc653f9
196
cc
C++
experimental/proto_test.cc
romange/beeri
60718d0f3133fffdf1500f8844852a79c91d8351
[ "BSD-2-Clause" ]
2
2015-01-07T06:34:25.000Z
2019-01-25T10:11:24.000Z
experimental/proto_test.cc
romange/beeri
60718d0f3133fffdf1500f8844852a79c91d8351
[ "BSD-2-Clause" ]
null
null
null
experimental/proto_test.cc
romange/beeri
60718d0f3133fffdf1500f8844852a79c91d8351
[ "BSD-2-Clause" ]
1
2019-01-25T10:11:28.000Z
2019-01-25T10:11:28.000Z
#include <gtest/gtest.h> #include "experimental/addressbook.pb.h" class ProtoTest : public testing::Test { }; TEST_F(ProtoTest, Basic) { tutorial::Person person; person.set_name("Roman"); }
17.818182
40
0.719388
romange
4a8a3115f5e63f4538f17364ef7d8aaef909b938
194
cpp
C++
Source/GCE/Game/Death/PawnDeathComponent.cpp
ssapo/GCE
ddb5dfa2472c2f4ba01bf81d4fac9a64ac861e9f
[ "MIT" ]
2
2019-07-28T13:30:14.000Z
2019-11-22T08:14:28.000Z
Source/GCE/Game/Death/PawnDeathComponent.cpp
ssapo/GCE
ddb5dfa2472c2f4ba01bf81d4fac9a64ac861e9f
[ "MIT" ]
null
null
null
Source/GCE/Game/Death/PawnDeathComponent.cpp
ssapo/GCE
ddb5dfa2472c2f4ba01bf81d4fac9a64ac861e9f
[ "MIT" ]
1
2019-07-07T13:39:08.000Z
2019-07-07T13:39:08.000Z
// Fill out your copyright notice in the Description page of Project Settings. #include "PawnDeathComponent.h" UPawnDeathComponent::UPawnDeathComponent() { ChessClass = EChessClass::Pawn; }
19.4
78
0.783505
ssapo
4a8a994a09e35902ff3645293eab9b0ea6cede65
535
cpp
C++
C++/Clase 8/Clase8.1.cpp
Rofernweh/UDPpl
da448091396b3f567f83e2964e8db97f6b8382bc
[ "MIT" ]
null
null
null
C++/Clase 8/Clase8.1.cpp
Rofernweh/UDPpl
da448091396b3f567f83e2964e8db97f6b8382bc
[ "MIT" ]
1
2021-06-29T05:16:19.000Z
2021-06-29T05:16:19.000Z
C++/Clase 8/Clase8.1.cpp
Rofernweh/UDPpl
da448091396b3f567f83e2964e8db97f6b8382bc
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> using namespace std; /*Se deja caer un objeto. Se pide al usuario un entero n,donde n es la cantidad de segundos que el usuario desea medir. Imprimir en pantalla cuanto ha caído el objeto en cada segundo menor a n. */ int main () { float n; float distancia; cout << "Ingrese el tiempo que desea medir en segundos: \n"; cin >> n; for(i=0; i<=n;i++) { distancia= 0.5*9.8*(pow(n,n)); cout << "En el segundo\t" << i << " se recorrieron " << distancia << " metros."; } }
28.157895
95
0.635514
Rofernweh
4a8bc14b35942e5905161e0890643f8a0fc2439f
8,323
inl
C++
include/volt/math/vec3.inl
voltengine/volt
fbefe2e0a8e461b6130ffe926870c4848bd6e7d1
[ "MIT" ]
null
null
null
include/volt/math/vec3.inl
voltengine/volt
fbefe2e0a8e461b6130ffe926870c4848bd6e7d1
[ "MIT" ]
null
null
null
include/volt/math/vec3.inl
voltengine/volt
fbefe2e0a8e461b6130ffe926870c4848bd6e7d1
[ "MIT" ]
null
null
null
#include "../util/util.hpp" namespace volt::math { template<scalar T> const vec3<T> vec3<T>::zero(0); template<scalar T> const vec3<T> vec3<T>::one(1); template<scalar T> const vec3<T> vec3<T>::left(-1, 0, 0); template<scalar T> const vec3<T> vec3<T>::right(1, 0, 0); template<scalar T> const vec3<T> vec3<T>::down(0, -1, 0); template<scalar T> const vec3<T> vec3<T>::up(0, 1, 0); template<scalar T> const vec3<T> vec3<T>::forward(0, 0, -1); template<scalar T> const vec3<T> vec3<T>::backward(0, 0, 1); template<scalar T> constexpr vec3<T>::vec3() : vec3(0) {} template<scalar T> constexpr vec3<T>::vec3(T all) : x(all), y(all), z(all) {} template<scalar T> constexpr vec3<T>::vec3(T x, T y, T z) : x(x), y(y), z(z) {} template<scalar T> template<scalar U> constexpr vec3<T>::vec3(const vec3<U> &other) : x(other.x), y(other.y), z(other.z) {} template<scalar T> template<scalar U> constexpr vec3<T>::vec3(const vec2<U> &other, float z) : x(other.x), y(other.y), z(z) {} #pragma region Operators template<scalar T> template<scalar U> vec3<T>::operator vec2<U>() const { return vec2<U>(x, y); } template<scalar U> std::ostream &operator<<(std::ostream &lhs, const vec3<U> &rhs) { return lhs << '[' << util::to_string(rhs.x) << ", " << util::to_string(rhs.y) << ", " << util::to_string(rhs.z) << ']'; } template<scalar T> T &vec3<T>::operator[](size_t index) { return data[index]; } template<scalar T> const T &vec3<T>::operator[](size_t index) const { return data[index]; } template<scalar T> vec3<T> vec3<T>::operator-() const { return vec3<T>(-x, -y, -z); } template<boolean U> vec3<bool> operator!(const vec3<U> &vec) { return vec3<bool>(!vec.x, !vec.y, !vec.z); } template<scalar T> template<scalar U> vec3<bool> vec3<T>::operator==(const vec3<U> &rhs) const { return vec3<bool>(x == rhs.x, y == rhs.y, z == rhs.z); } template<scalar T> template<scalar U> vec3<bool> vec3<T>::operator!=(const vec3<U> &rhs) const { return vec3<bool>(x != rhs.x, y != rhs.y, z != rhs.z); } template<scalar T> template<scalar U> vec3<bool> vec3<T>::operator<=(const vec3<U> &rhs) const { return vec3<bool>(x <= rhs.x, y <= rhs.y, z <= rhs.z); } template<scalar T> template<scalar U> vec3<bool> vec3<T>::operator>=(const vec3<U> &rhs) const { return vec3<bool>(x >= rhs.x, y >= rhs.y, z >= rhs.z); } template<scalar T> template<scalar U> vec3<bool> vec3<T>::operator<(const vec3<U> &rhs) const { return vec3<bool>(x < rhs.x, y < rhs.y, z < rhs.z); } template<scalar T> template<scalar U> vec3<bool> vec3<T>::operator>(const vec3<U> &rhs) const { return vec3<bool>(x > rhs.x, y > rhs.y, z > rhs.z); } // Vector + Vector template<scalar T> template<scalar U, scalar Ret> vec3<Ret> vec3<T>::operator+(const vec3<U> &rhs) const { return vec3<Ret>(x + rhs.x, y + rhs.y, z + rhs.z); } template<scalar T> template<scalar U, scalar Ret> vec3<Ret> vec3<T>::operator-(const vec3<U> &rhs) const { return vec3<Ret>(x - rhs.x, y - rhs.y, z - rhs.z); } template<scalar T> template<scalar U, scalar Ret> vec3<Ret> vec3<T>::operator*(const vec3<U> &rhs) const { return vec3<Ret>(x * rhs.x, y * rhs.y, z * rhs.z); } template<scalar T> template<scalar U, scalar Ret> vec3<Ret> vec3<T>::operator/(const vec3<U> &rhs) const { return vec3<Ret>(x / rhs.x, y / rhs.y, z / rhs.z); } template<scalar T> template<scalar U> vec3<T> &vec3<T>::operator+=(const vec3<U> &rhs) { return *this = *this + rhs; } template<scalar T> template<scalar U> vec3<T> &vec3<T>::operator-=(const vec3<U> &rhs) { return *this = *this - rhs; } template<scalar T> template<scalar U> vec3<T> &vec3<T>::operator*=(const vec3<U> &rhs) { return *this = *this * rhs; } template<scalar T> template<scalar U> vec3<T> &vec3<T>::operator/=(const vec3<U> &rhs) { return *this = *this / rhs; } // Vector + Scalar template<scalar T> template<scalar U, scalar Ret> vec3<Ret> vec3<T>::operator*(U rhs) const { return vec3<Ret>(x * rhs, y * rhs, z * rhs); } template<scalar T> template<scalar U, scalar Ret> vec3<Ret> vec3<T>::operator/(U rhs) const { return vec3<Ret>(x / rhs, y / rhs, z / rhs); } template<scalar T> template<scalar U> vec3<T> &vec3<T>::operator*=(U rhs) { return *this = *this * rhs; } template<scalar T> template<scalar U> vec3<T> &vec3<T>::operator/=(U rhs) { return *this = *this / rhs; } // Scalar + Vector template<scalar L, scalar R, scalar Ret = std::common_type_t<L, R>> vec3<Ret> operator*(L lhs, const vec3<R> &rhs) { return vec3<Ret>(lhs * rhs.x, lhs * rhs.y, lhs * rhs.z); } #pragma endregion template<boolean T> bool all(const vec3<T> &vec) { return vec.x && vec.y && vec.z; } template<boolean T> bool any(const vec3<T> &vec) { return vec.x || vec.y || vec.z; } template<scalar L, scalar R, scalar Ret> vec3<Ret> cross(const vec3<L> &lhs, const vec3<R> &rhs) { return vec3<Ret>( (lhs.y * rhs.z) - (lhs.z * rhs.y), (lhs.z * rhs.x) - (lhs.x * rhs.z), (lhs.x * rhs.y) - (lhs.y * rhs.x) ); } template<scalar A, scalar B, floating_point Ret> Ret distance(const vec3<A> &a, const vec3<B> &b) { return length(a - b); } template<scalar A, scalar B, scalar Ret> Ret dot(const vec3<A> &a, const vec3<B> &b) { return a.x * b.x + a.y * b.y + a.z * b.z; } template<scalar T, scalar Epsilon> bool is_normalized(const vec3<T> &vec, Epsilon epsilon) { return is_approx(dot(vec, vec), 1, epsilon); } template<floating_point T> T length(const vec3<T> &vec) { return sqrt(dot(vec, vec)); } template<floating_point T> vec3<T> normalize(const vec3<T> &vec) { return vec * (1 / length(vec)); } template<floating_point To, floating_point From, scalar Ret> vec3<Ret> proj(const vec3<To> &to, const vec3<From> &from) { return (dot(to, from) / dot(to, to)) * to; } template<scalar Incident, scalar Normal, scalar Ret> vec3<Ret> reflect(const vec3<Incident> &incident, const vec3<Normal> &normal) { return incident - 2 * dot(normal, incident) * normal; } template<scalar Incident, scalar Normal, scalar IorRatio, scalar Ret> vec3<Ret> refract(const vec3<Incident> &incident, const vec3<Normal> &normal, IorRatio ior_ratio) { Ret cos_theta = dot(incident, normal); Ret k = 1 - ior_ratio * ior_ratio * (1 - cos_theta * cos_theta); if (k < 0) return vec3<Ret>::zero; return ior_ratio * incident - (ior_ratio * cos_theta + sqrt(k)) * normal; } #pragma region Component-Wise Math Wrappers template<scalar X> vec3<X> abs(const vec3<X> &x) { return vec3<X>(abs(x.x), abs(x.y), abs(x.z)); } template<floating_point X> vec3<X> fract(const vec3<X> &x) { return vec3<X>(fract(x.x), fract(x.y), fract(x.z)); } template<scalar From, scalar To, scalar Weight, scalar Ret> vec3<Ret> lerp(const vec3<From> &from, const vec3<To> &to, const vec3<Weight> &weight) { return vec3<Ret>( lerp(from.x, to.x, weight.x), lerp(from.y, to.y, weight.y), lerp(from.z, to.z, weight.z)); } template<scalar A, scalar B, scalar Ret> vec3<Ret> max(const vec3<A> &a, const vec3<B> &b) { return vec3<Ret>( max(a.x, b.x), max(a.y, b.y), max(a.z, b.z)); } template<scalar A, scalar B, scalar... Others, scalar Ret> vec3<Ret> max(const vec3<A> &a, const vec3<B> &b, const vec3<Others> &...others) { return max(max(a, b), others...); } template<scalar A, scalar B, scalar Ret> vec3<Ret> min(const vec3<A> &a, const vec3<B> &b) { return vec3<Ret>( min(a.x, b.x), min(a.y, b.y), min(a.z, b.z)); } template<scalar A, scalar B, scalar... Others, scalar Ret> vec3<Ret> min(const vec3<A> &a, const vec3<B> &b, const vec3<Others> &...others) { return min(min(a, b), others...); } template<scalar X, scalar Y, scalar Ret> vec3<Ret> mod(const vec3<X> &x, const vec3<Y> &y) { return vec3<Ret>( mod(x.x, y.x), mod(x.y, y.y), mod(x.z, y.z)); } template<scalar X, scalar Power, scalar Ret> vec3<Ret> pow(const vec3<X> &x, const vec3<Power> &power) { return vec3<Ret>( math::pow(x.x, power.x), math::pow(x.y, power.y), math::pow(x.z, power.z)); } template<scalar X> vec3<X> saturate(const vec3<X> &x) { return vec3<X>( saturate(x.x), saturate(x.y), saturate(x.z)); } #pragma endregion } namespace std { template<volt::math::scalar T> std::size_t hash<volt::math::vec3<T>>::operator()(volt::math::vec3<T> vec) const { return (static_cast<size_t>(vec.x) * 859433 ^ static_cast<size_t>(vec.y)) * 19937 ^ static_cast<size_t>(vec.z); } }
23.055402
88
0.641115
voltengine
4a905e489392eb0b97fbfd773b15341812e1a028
305
hpp
C++
tests/regex/regex_full.hpp
olegpublicprofile/stdfwd
19671bcc8e53bd4c008f07656eaf25a22495e093
[ "MIT" ]
11
2021-03-15T07:06:21.000Z
2021-09-27T13:54:25.000Z
tests/regex/regex_full.hpp
olegpublicprofile/stdfwd
19671bcc8e53bd4c008f07656eaf25a22495e093
[ "MIT" ]
null
null
null
tests/regex/regex_full.hpp
olegpublicprofile/stdfwd
19671bcc8e53bd4c008f07656eaf25a22495e093
[ "MIT" ]
1
2021-06-24T10:46:46.000Z
2021-06-24T10:46:46.000Z
#pragma once //------------------------------------------------------------------------------ namespace regex_tests { //------------------------------------------------------------------------------ void run_full(); //------------------------------------------------------------------------------ }
21.785714
80
0.137705
olegpublicprofile
4a916439eaae0711688369191b735ef4483c6e05
82,405
cpp
C++
sdl1/goonies/GO_character.cpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
sdl1/goonies/GO_character.cpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
sdl1/goonies/GO_character.cpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
#ifdef KITSCHY_DEBUG_MEMORY #include "debug_memorymanager.h" #endif #ifdef _WIN32 #include "windows.h" #endif #include "math.h" #include "stdlib.h" #include "string.h" #include "GL/gl.h" #include "GL/glu.h" #include "SDL.h" #include "SDL_image.h" #include "SDL_mixer.h" #include "List.h" #include "auxiliar.h" #include "2DCMC.h" #include "Symbol.h" #include "GLTile.h" #include "keyboardstate.h" #include "VirtualController.h" #include "GLTManager.h" #include "SoundManager.h" #include "SFXManager.h" #include "GObject.h" #include "GO_character.h" #include "GO_enemy.h" #include "GO_skulldoor.h" #include "GO_item.h" #include "GO_bridge.h" #include "GMap.h" #include "TheGooniesCtnt.h" #include "GObjectCreator.h" // #include "debug.h" extern int difficulty; extern int score; GO_character::GO_character(int x, int y, int sfx_volume, int facing) : GObject(x, y, sfx_volume) { m_class = new Symbol(character_symbol); if (facing == 0) m_state = CSTATE_STANDING_LEFT; else m_state = CSTATE_STANDING_RIGHT; m_last_state = m_state; m_state_cycle = 0; m_punch_cycle = 0; m_step_cycle = 0; m_layer = 2; m_walking_channel = -1; m_climbing_channel = -1; m_facebefore_vine = 0; m_requested_room = false; m_requested_room_x = 0; m_requested_room_y = 0; m_requested_room_door = 0; m_player_hit_counter = 0; m_walking_speed = PLAYER_SPEED; m_energy = 64; m_experience = 0; m_key = false; m_goonies_rescued = 0; for (int i = 0; i < 7; ++i) m_rescued_goonies[i] = false; m_last_pick = 0; m_last_hit = 0; m_last_hit_by = 0; m_camefrom = 0; m_turning_counter = 0; // item variables: m_yellowhelmet_status = m_yellowhelmet_timer = 0; m_greycoat_status = m_greycoat_timer = 0; m_yellowcoat_timer = 0; m_hammer_status = 0; m_greenbook_status = 0; m_redbook_status = 0; m_lightbluebook_status = 0; m_bluebook_status = m_bluebook_timer = 0; m_greencoat_timer = 0; m_whitebook_status = 0; m_yellowshield_status = m_yellowshield_timer = 0; m_lightbluecoat_timer = 0; m_whiteshield_status = m_whiteshield_timer = 0; m_lightbluehelmet_status = m_lightbluehelmet_timer = 0; m_yellowbook_status = m_yellowbook_timer = 0; m_purpleshield_status = m_purpleshield_timer = 0; m_clock_timer = 0; m_bluebadbook_nghosts = 0; } GO_character::~GO_character() { if (m_last_pick != 0) delete m_last_pick; if (m_last_hit != 0) delete m_last_hit; if (m_last_hit_by != 0) delete m_last_hit_by; if (m_camefrom != 0) delete m_camefrom; } bool GO_character::cycle(VirtualController *v, GMap *map, int layer, TheGoonies *game, GLTManager *GLTM, SFXManager *SFXM) { int salute = (m_state_cycle % 615); m_previous_state = m_state; if (m_last_tile_used == 0) m_last_tile_used = GLTM->get ("ob_character-l1"); // reset the variables for script conditions: m_last_state = m_state; if (m_last_pick != 0) delete m_last_pick; m_last_pick = 0; if (m_last_hit != 0) delete m_last_hit; m_last_hit = 0; if (m_last_hit_by != 0) delete m_last_hit_by; m_last_hit_by = 0; #ifdef __DEBUG_MESSAGES output_debug_message("Character, %i (%f,%f)\n", m_state, m_x, m_y); #endif if (player_has("GO_shoes")) { m_walking_speed = PLAYER_SPEED * 1.25f; } else { m_walking_speed = PLAYER_SPEED; } switch (m_state) { case CSTATE_STANDING_LEFT: case CSTATE_STANDING_RIGHT: m_state_cycle++; if (v->m_joystick[VC_UP] && !v->m_old_joystick[VC_UP]) { GObject *o; o = map->collision_with_object(this, GLTM, rope_symbol); if (o != 0) { // climb a rope! if (m_state == CSTATE_STANDING_LEFT) m_facebefore_vine = 0; else m_facebefore_vine = 1; m_state = CSTATE_CLIMBING_UP; m_x = o->get_x() + 10; } else { // check for skulldoors: GO_skulldoor *sd = (GO_skulldoor *)map->collision_with_object(this, GLTM, skulldoor_symbol); if (sd != 0) { // Room change request: if (sd->get_destination_x() != -1 || m_goonies_rescued >= 7) { m_requested_room_x = sd->get_destination_x(); m_requested_room_y = sd->get_destination_y(); m_requested_room_door = sd->get_destination_door(); m_state = CSTATE_ENTERING_DOOR; m_state_cycle = 0; m_x = sd->get_x()-4; m_y = sd->get_y()+16; } } else { SFXM->SFX_play("sfx/player_jump", m_sfx_volume, get_player_angle(), get_player_distance()); if (m_state == CSTATE_STANDING_LEFT) { m_state = CSTATE_JUMPING_LEFT; m_state_cycle = 0; } else { m_state = CSTATE_JUMPING_RIGHT; m_state_cycle = 0; } } } } else { if (v->m_joystick[VC_LEFT]) { m_state_cycle = 0; m_state = CSTATE_WALKING_LEFT; } if (v->m_joystick[VC_RIGHT]) { m_state_cycle = 0; m_state = CSTATE_WALKING_RIGHT; } // down an rope: if (v->m_joystick[VC_DOWN] && !v->m_old_joystick[VC_DOWN]) { m_y += 50; GObject *o; o = map->collision_with_object(this, GLTM, rope_symbol); if (o != 0) { set_layer(3, map); if (m_state == CSTATE_STANDING_LEFT) m_facebefore_vine = 0; else m_facebefore_vine = 1; m_state = CSTATE_CLIMBING_DOWN; m_x = o->get_x() + 10; m_y -= 28; } else { m_y -= 50; } } // punch: if (v->m_button[0] && !v->m_old_button[0]) { int e_gained = 0; int points_gained = 0; if (m_state == CSTATE_STANDING_LEFT || m_state == CSTATE_WALKING_LEFT) { m_state = CSTATE_PUNCH_LEFT; m_punch_cycle = 0; GO_enemy *e = (GO_enemy *)map->collision_with_object(GLTM->get ("ob_character-punch-mask-l"), (int)m_x, (int)m_y, GLTM, enemy_symbol); if (e != 0 && e->player_hit(&e_gained, &points_gained)) { if (m_last_hit != 0) delete m_last_hit; m_last_hit = new Symbol(e->get_class()); SFXM->SFX_play("sfx/player_hit_enemy", m_sfx_volume, get_player_angle(), get_player_distance()); m_experience += e_gained; inc_score(points_gained); } else { SFXM->SFX_play("sfx/player_attack", m_sfx_volume, get_player_angle(), get_player_distance()); } } else { m_state = CSTATE_PUNCH_RIGHT; m_punch_cycle = 0; GO_enemy *e = (GO_enemy *)map->collision_with_object(GLTM->get ("ob_character-punch-mask-r"), (int)m_x, (int)m_y, GLTM, enemy_symbol); if (e != 0 && e->player_hit(&e_gained, &points_gained)) { if (m_last_hit != 0) delete m_last_hit; m_last_hit = new Symbol(e->get_class()); SFXM->SFX_play("sfx/player_hit_enemy", m_sfx_volume, get_player_angle(), get_player_distance()); m_experience += e_gained; inc_score(points_gained); } else { SFXM->SFX_play("sfx/player_attack", m_sfx_volume, get_player_angle(), get_player_distance()); } } } } // salute; wink sfx if (salute == 250 || salute == 260 || salute == 270) { SFXM->SFX_play("sfx/player_wink", m_sfx_volume, get_player_angle(), get_player_distance()); // salute; foot tap } else if (salute == 510 || salute == 530 || salute == 550) { SFXM->SFX_play("sfx/player_foottap", m_sfx_volume, get_player_angle(), get_player_distance()); // salute; knock on monitor } else if (salute == 580 || salute == 590 || salute == 600) { SFXM->SFX_play("sfx/player_knock", m_sfx_volume, get_player_angle(), get_player_distance()); } // test for fall: if (m_state != CSTATE_ENTERING_DOOR) { m_y+=2.0f; if (!map->collision_with_background(this, GLTM)) { GObject *go = map->collision_with_object(this, GLTM, bridge_symbol); if (go == 0) { if (m_state == CSTATE_STANDING_LEFT) m_state = CSTATE_FALLING_LEFT; else m_state = CSTATE_FALLING_RIGHT; m_state_cycle = 0; } } m_y-=2.0f; } break; case CSTATE_WALKING_LEFT: m_state_cycle++; m_x -= m_walking_speed; if (v->m_joystick[VC_UP] && !v->m_old_joystick[VC_UP]) { GObject *o; o = map->collision_with_object(this, GLTM, rope_symbol); if (o != 0) { // climb a rope! m_facebefore_vine = 0; m_state = CSTATE_CLIMBING_UP; m_x = o->get_x() + 10; } else { // check for skulldoors: GO_skulldoor *sd = (GO_skulldoor *)map->collision_with_object(this, GLTM, skulldoor_symbol); if (sd != 0) { // Room change request: if (sd->get_destination_x() != -1 || m_goonies_rescued >= 7) { m_requested_room_x = sd->get_destination_x(); m_requested_room_y = sd->get_destination_y(); m_requested_room_door = sd->get_destination_door(); m_state = CSTATE_ENTERING_DOOR; m_state_cycle = 0; m_x = sd->get_x()-4; m_y = sd->get_y()+16; } } else { SFXM->SFX_play("sfx/player_jump", m_sfx_volume, get_player_angle(), get_player_distance()); m_state = CSTATE_JUMPING_LEFT_LEFT; m_state_cycle = 0; } } } else { if (!v->m_joystick[VC_LEFT]) { m_state_cycle = 0; m_state = CSTATE_STANDING_LEFT; } if (v->m_joystick[VC_RIGHT] && !v->m_old_joystick[VC_RIGHT]) { m_state_cycle = 0; m_state = CSTATE_WALKING_RIGHT; } // down an rope: if (v->m_joystick[VC_DOWN] && !v->m_old_joystick[VC_DOWN]) { m_y += 50; GObject *o; o = map->collision_with_object(this, GLTM, rope_symbol); if (o != 0) { set_layer(3, map); m_facebefore_vine = 0; m_state = CSTATE_CLIMBING_DOWN; m_x = o->get_x() + 10; m_y -= 28; } else { m_y -= 50; } } // punch: if (v->m_button[0] && !v->m_old_button[0]) { int e_gained = 0; int points_gained = 0; if (m_state == CSTATE_STANDING_LEFT || m_state == CSTATE_WALKING_LEFT) { m_state = CSTATE_PUNCH_LEFT; m_punch_cycle = 0; GO_enemy *e = (GO_enemy *)map->collision_with_object(GLTM->get ("ob_character-punch-mask-l"), (int)m_x, (int)m_y, GLTM, enemy_symbol); if (e != 0 && e->player_hit(&e_gained, &points_gained)) { if (m_last_hit != 0) delete m_last_hit; m_last_hit = new Symbol(e->get_class()); SFXM->SFX_play("sfx/player_hit_enemy", m_sfx_volume, get_player_angle(), get_player_distance()); m_experience += e_gained; inc_score(points_gained); } else { SFXM->SFX_play("sfx/player_attack", m_sfx_volume, get_player_angle(), get_player_distance()); } } else { m_state = CSTATE_PUNCH_RIGHT; m_punch_cycle = 0; GO_enemy *e = (GO_enemy *)map->collision_with_object(GLTM->get ("ob_character-punch-mask-r"), (int)m_x, (int)m_y, GLTM, enemy_symbol); if (e != 0 && e->player_hit(&e_gained, &points_gained)) { if (m_last_hit != 0) delete m_last_hit; m_last_hit = new Symbol(e->get_class()); SFXM->SFX_play("sfx/player_hit_enemy", m_sfx_volume, get_player_angle(), get_player_distance()); m_experience += e_gained; inc_score(points_gained); } else { SFXM->SFX_play("sfx/player_attack", m_sfx_volume, get_player_angle(), get_player_distance()); } } } } // test for fall: if (m_state != CSTATE_ENTERING_DOOR) { m_y+=2.0f; if (!map->collision_with_background(this, GLTM)) { GObject *go = map->collision_with_object(this, GLTM, bridge_symbol); if (go == 0) { m_state = CSTATE_FALLING_LEFT; m_state_cycle = 0; } } m_y-=2.0f; } break; case CSTATE_WALKING_RIGHT: m_state_cycle++; m_x += m_walking_speed; if (v->m_joystick[VC_UP] && !v->m_old_joystick[VC_UP]) { GObject *o; o = map->collision_with_object(this, GLTM, rope_symbol); if (o != 0) { // climb a rope! m_facebefore_vine = 1; m_state = CSTATE_CLIMBING_UP; m_x = o->get_x() + 10; } else { // check for skulldoors: GO_skulldoor *sd = (GO_skulldoor *)map->collision_with_object(this, GLTM, skulldoor_symbol); if (sd != 0) { // Room change request: if (sd->get_destination_x() != -1 || m_goonies_rescued >= 7) { m_requested_room_x = sd->get_destination_x(); m_requested_room_y = sd->get_destination_y(); m_requested_room_door = sd->get_destination_door(); m_state = CSTATE_ENTERING_DOOR; m_state_cycle = 0; m_x = sd->get_x()-4; m_y = sd->get_y()+16; } } else { SFXM->SFX_play("sfx/player_jump", m_sfx_volume, get_player_angle(), get_player_distance()); m_state = CSTATE_JUMPING_RIGHT_RIGHT; m_state_cycle = 0; } } } else { if (v->m_joystick[VC_LEFT] && !v->m_old_joystick[VC_LEFT]) { m_state_cycle = 0; m_state = CSTATE_WALKING_LEFT; } if (!v->m_joystick[VC_RIGHT]) { m_state_cycle = 0; m_state = CSTATE_STANDING_RIGHT; } // down an rope: if (v->m_joystick[VC_DOWN] && !v->m_old_joystick[VC_DOWN]) { m_y += 50; GObject *o; o = map->collision_with_object(this, GLTM, rope_symbol); if (o != 0) { set_layer(3, map); m_facebefore_vine = 1; m_state = CSTATE_CLIMBING_DOWN; m_x = o->get_x() + 10; m_y -= 28; } else { m_y -= 50; } } // punch: if (v->m_button[0] && !v->m_old_button[0]) { int e_gained = 0; int points_gained = 0; if (m_state == CSTATE_STANDING_LEFT || m_state == CSTATE_WALKING_LEFT) { m_state = CSTATE_PUNCH_LEFT; m_punch_cycle = 0; GO_enemy *e = (GO_enemy *)map->collision_with_object(GLTM->get ("ob_character-punch-mask-l"), (int)m_x, (int)m_y, GLTM, enemy_symbol); if (e != 0 && e->player_hit(&e_gained, &points_gained)) { if (m_last_hit != 0) delete m_last_hit; m_last_hit = new Symbol(e->get_class()); SFXM->SFX_play("sfx/player_hit_enemy", m_sfx_volume, get_player_angle(), get_player_distance()); m_experience += e_gained; inc_score(points_gained); } else { SFXM->SFX_play("sfx/player_attack", m_sfx_volume, get_player_angle(), get_player_distance()); } } else { m_state = CSTATE_PUNCH_RIGHT; m_punch_cycle = 0; GO_enemy *e = (GO_enemy *)map->collision_with_object(GLTM->get ("ob_character-punch-mask-r"), (int)m_x, (int)m_y, GLTM, enemy_symbol); if (e != 0 && e->player_hit(&e_gained, &points_gained)) { if (m_last_hit != 0) delete m_last_hit; m_last_hit = new Symbol(e->get_class()); SFXM->SFX_play("sfx/player_hit_enemy", m_sfx_volume, get_player_angle(), get_player_distance()); m_experience += e_gained; inc_score(points_gained); } else { SFXM->SFX_play("sfx/player_attack", m_sfx_volume, get_player_angle(), get_player_distance()); } } } } // test for fall: if (m_state != CSTATE_ENTERING_DOOR) { m_y+=2.0f; if (!map->collision_with_background(this, GLTM)) { GObject *go = map->collision_with_object(this, GLTM, bridge_symbol); if (go == 0) { m_state = CSTATE_FALLING_RIGHT; m_state_cycle = 0; } } m_y-=2.0f; } break; case CSTATE_FALLING_LEFT: { int i, j = 1; if (m_state_cycle > 4) j++; if (m_state_cycle > 12) j++; if (m_state_cycle > 20) j++; for (i = 0;i < j;i++) { m_y++; if (map->collision_with_background(this, GLTM)) { m_state = CSTATE_STANDING_LEFT; m_state_cycle = 0; m_y--; SFXM->SFX_play("sfx/player_land", m_sfx_volume, get_player_angle(), get_player_distance()); } else { GObject *go = map->collision_with_object(this, GLTM, bridge_symbol); if (go != 0) { m_state = CSTATE_STANDING_LEFT; m_state_cycle = 0; m_y--; } } } m_state_cycle++; } break; case CSTATE_FALLING_RIGHT: { int i, j = 1; if (m_state_cycle > 4) j++; if (m_state_cycle > 12) j++; if (m_state_cycle > 20) j++; for (i = 0;i < j;i++) { m_y++; if (map->collision_with_background(this, GLTM)) { m_state = CSTATE_STANDING_RIGHT; m_state_cycle = 0; m_y--; SFXM->SFX_play("sfx/player_land", m_sfx_volume, get_player_angle(), get_player_distance()); } else { GObject *go = map->collision_with_object(this, GLTM, bridge_symbol); if (go != 0) { m_state = CSTATE_STANDING_RIGHT; m_state_cycle = 0; m_y--; } } } m_state_cycle++; } break; case CSTATE_PUNCH_LEFT: m_punch_cycle++; if (m_punch_cycle >= 8) { m_state = CSTATE_STANDING_LEFT; m_state_cycle = 0; } break; case CSTATE_PUNCH_RIGHT: m_punch_cycle++; if (m_punch_cycle >= 8) { m_state = CSTATE_STANDING_RIGHT; m_state_cycle = 0; } break; case CSTATE_JUMPING_LEFT: case CSTATE_JUMPING_RIGHT: case CSTATE_JUMPING_LEFT_LEFT: case CSTATE_JUMPING_RIGHT_RIGHT: { int i, y_move = 3; if (m_state_cycle < 39) y_move = 2; if (m_state_cycle < 33) y_move = 1; if (m_state_cycle < 27) y_move = 0; if (m_state_cycle < 21) y_move = -1; if (m_state_cycle < 15) y_move = -2; if (m_state_cycle < 9) y_move = -3; if (m_state_cycle < 4) y_move = -4; if (y_move > 0) { for (i = 0;i < y_move;i++) { m_y++; if (map->collision_with_background(this, 0, 1, GLTM)) { SFXM->SFX_play("sfx/player_land", m_sfx_volume, get_player_angle(), get_player_distance()); if (m_state == CSTATE_JUMPING_LEFT || m_state == CSTATE_JUMPING_LEFT_LEFT) { m_state = CSTATE_STANDING_LEFT; y_move = 0; } if (m_state == CSTATE_JUMPING_RIGHT || m_state == CSTATE_JUMPING_RIGHT_RIGHT) { m_state = CSTATE_STANDING_RIGHT; y_move = 0; } m_state_cycle = 0; } else { if (map->collision_with_object(this, GLTM, bridge_symbol) != 0) { // SFXM->SFX_play("sfx/player_walk_bridge1", m_sfx_volume, get_player_angle(), get_player_distance()); if (m_state == CSTATE_JUMPING_LEFT || m_state == CSTATE_JUMPING_LEFT_LEFT) { m_state = CSTATE_STANDING_LEFT; y_move = 0; } if (m_state == CSTATE_JUMPING_RIGHT || m_state == CSTATE_JUMPING_RIGHT_RIGHT) { m_state = CSTATE_STANDING_RIGHT; y_move = 0; } m_state_cycle = 0; } } } } if (y_move < 0) { y_move = -y_move; for (i = 0;i < y_move;i++) { m_y--; if (map->collision_with_background(this, GLTM)) { m_y++; m_state_cycle = 22; } else { if (map->collision_with_object(this, GLTM, bridge_symbol) != 0) { m_y++; m_state_cycle = 22; } } } } if (m_state == CSTATE_JUMPING_LEFT_LEFT) { m_x -= (m_walking_speed * 1.25f); if (map->collision_with_background(this, GLTM)) { m_x += (m_walking_speed * 1.25f); if (m_state_cycle > 25) m_state = CSTATE_JUMPING_LEFT; } // if else { if (map->collision_with_object(this, GLTM, bridge_symbol) != 0) { m_x += (m_walking_speed * 1.25f); if (m_state_cycle > 25) m_state = CSTATE_JUMPING_LEFT; } } } // if if (m_state == CSTATE_JUMPING_RIGHT_RIGHT) { m_x += (m_walking_speed * 1.25f); if (map->collision_with_background(this, GLTM)) { m_x -= (m_walking_speed * 1.25f); if (m_state_cycle > 25) m_state = CSTATE_JUMPING_RIGHT; } else { if (map->collision_with_object(this, GLTM, bridge_symbol) != 0) { m_x -= (m_walking_speed * 1.25f); if (m_state_cycle > 25) m_state = CSTATE_JUMPING_RIGHT; } } } { // punch: if (v->m_button[0] && !v->m_old_button[0]) { int e_gained = 0; int points_gained = 0; if (m_state == CSTATE_JUMPING_LEFT || m_state == CSTATE_JUMPING_LEFT_LEFT) { GO_enemy *e = (GO_enemy *)map->collision_with_object(GLTM->get ("ob_character-punchjump-mask-l"), (int)m_x, (int)m_y, GLTM, enemy_symbol); if (e != 0 && e->player_hit(&e_gained, &points_gained)) { if (m_last_hit != 0) delete m_last_hit; m_last_hit = new Symbol(e->get_class()); SFXM->SFX_play("sfx/player_hit_enemy", m_sfx_volume, get_player_angle(), get_player_distance()); m_experience += e_gained; inc_score(points_gained); } else { SFXM->SFX_play("sfx/player_attack", m_sfx_volume, get_player_angle(), get_player_distance()); } } else { GO_enemy *e = (GO_enemy *)map->collision_with_object(GLTM->get ("ob_character-punchjump-mask-r"), (int)m_x, (int)m_y, GLTM, enemy_symbol); if (e != 0 && e->player_hit(&e_gained, &points_gained)) { if (m_last_hit != 0) delete m_last_hit; m_last_hit = new Symbol(e->get_class()); SFXM->SFX_play("sfx/player_hit_enemy", m_sfx_volume, get_player_angle(), get_player_distance()); m_experience += e_gained; inc_score(points_gained); } else { SFXM->SFX_play("sfx/player_attack", m_sfx_volume, get_player_angle(), get_player_distance()); } } m_punch_cycle = 0; if (m_state == CSTATE_JUMPING_LEFT) m_state = CSTATE_JUMPPUNCH_LEFT; if (m_state == CSTATE_JUMPING_RIGHT) m_state = CSTATE_JUMPPUNCH_RIGHT; if (m_state == CSTATE_JUMPING_LEFT_LEFT) m_state = CSTATE_JUMPPUNCH_LEFT_LEFT; if (m_state == CSTATE_JUMPING_RIGHT_RIGHT) m_state = CSTATE_JUMPPUNCH_RIGHT_RIGHT; } } m_state_cycle++; } break; case CSTATE_JUMPPUNCH_LEFT: case CSTATE_JUMPPUNCH_RIGHT: case CSTATE_JUMPPUNCH_LEFT_LEFT: case CSTATE_JUMPPUNCH_RIGHT_RIGHT: { int i, y_move = 3; if (m_state_cycle < 39) y_move = 2; if (m_state_cycle < 33) y_move = 1; if (m_state_cycle < 27) y_move = 0; if (m_state_cycle < 21) y_move = -1; if (m_state_cycle < 15) y_move = -2; if (m_state_cycle < 9) y_move = -3; if (m_state_cycle < 4) y_move = -4; if (m_state == CSTATE_JUMPPUNCH_LEFT_LEFT) { m_x -= (m_walking_speed * 1.25f); if (map->collision_with_background(this, GLTM)) { m_x += (m_walking_speed * 1.25f); if (m_state_cycle > 25) m_state = CSTATE_JUMPPUNCH_LEFT; } else { if (map->collision_with_object(this, GLTM, bridge_symbol) != 0) { m_x += (m_walking_speed * 1.25f); if (m_state_cycle > 25) m_state = CSTATE_JUMPPUNCH_LEFT; } } } if (m_state == CSTATE_JUMPPUNCH_RIGHT_RIGHT) { m_x += (m_walking_speed * 1.25f); if (map->collision_with_background(this, GLTM)) { m_x -= (m_walking_speed * 1.25f); if (m_state_cycle > 25) m_state = CSTATE_JUMPPUNCH_RIGHT; } else { if (map->collision_with_object(this, GLTM, bridge_symbol) != 0) { m_x -= (m_walking_speed * 1.25f); if (m_state_cycle > 25) m_state = CSTATE_JUMPPUNCH_RIGHT; } } } if (y_move > 0) { for (i = 0;i < y_move;i++) { m_y++; if (map->collision_with_background(this, 0, 1, GLTM)) { SFXM->SFX_play("sfx/player_land", m_sfx_volume, get_player_angle(), get_player_distance()); if (m_state == CSTATE_JUMPPUNCH_LEFT || m_state == CSTATE_JUMPPUNCH_LEFT_LEFT) { m_state = CSTATE_STANDING_LEFT; y_move = 0; } if (m_state == CSTATE_JUMPPUNCH_RIGHT || m_state == CSTATE_JUMPPUNCH_RIGHT_RIGHT) { m_state = CSTATE_STANDING_RIGHT; y_move = 0; } m_state_cycle = 0; } else { if (map->collision_with_object(this, GLTM, bridge_symbol) != 0) { SFXM->SFX_play("sfx/player_land", m_sfx_volume, get_player_angle(), get_player_distance()); if (m_state == CSTATE_JUMPPUNCH_LEFT || m_state == CSTATE_JUMPPUNCH_LEFT_LEFT) { m_state = CSTATE_STANDING_LEFT; y_move = 0; } if (m_state == CSTATE_JUMPPUNCH_RIGHT || m_state == CSTATE_JUMPPUNCH_RIGHT_RIGHT) { m_state = CSTATE_STANDING_RIGHT; y_move = 0; } m_state_cycle = 0; } } } } if (y_move < 0) { y_move = -y_move; for (i = 0;i < y_move;i++) { m_y--; if (map->collision_with_background(this, GLTM)) { m_y++; m_state_cycle = 22; } else { if (map->collision_with_object(this, GLTM, bridge_symbol) != 0) { m_y++; m_state_cycle = 22; } } } } m_state_cycle++; m_punch_cycle++; if (m_punch_cycle >= 8) { if (m_state == CSTATE_JUMPPUNCH_LEFT) m_state = CSTATE_JUMPING_LEFT; if (m_state == CSTATE_JUMPPUNCH_RIGHT) m_state = CSTATE_JUMPING_RIGHT; if (m_state == CSTATE_JUMPPUNCH_LEFT_LEFT) m_state = CSTATE_JUMPING_LEFT_LEFT; if (m_state == CSTATE_JUMPPUNCH_RIGHT_RIGHT) m_state = CSTATE_JUMPING_RIGHT_RIGHT; } } break; case CSTATE_CLIMBING_UP: set_layer(3, map); m_y -= PLAYER_CLIMBING_SPEED; // test if end of rope: if (m_y > 8) { m_y -= 8; if (!map->collision_with_object(this, GLTM, rope_symbol)) { set_layer(2, map); if (m_facebefore_vine == 0) m_state = CSTATE_STANDING_LEFT; else m_state = CSTATE_STANDING_RIGHT; m_state_cycle = 0; do { m_y -= PLAYER_CLIMBING_SPEED; } while (m_y >= 0 && map->collision_with_background(this, GLTM)); } else { m_y += 8; } // check for reaching a platform: if (m_state == CSTATE_CLIMBING_UP && !map->collision_with_background(this, GLTM) && map->collision_with_background(this, 0, 1, GLTM)) { set_layer(2, map); if (m_facebefore_vine == 0) m_state = CSTATE_STANDING_LEFT; else m_state = CSTATE_STANDING_RIGHT; m_state_cycle = 0; } } m_state_cycle++; if (!v->m_joystick[VC_UP]) { m_state = CSTATE_CLIMBING; } if (v->m_joystick[VC_DOWN] && !v->m_old_joystick[VC_DOWN]) { m_state = CSTATE_CLIMBING_DOWN; } break; case CSTATE_CLIMBING: set_layer(3, map); if (v->m_joystick[VC_UP]) { m_state = CSTATE_CLIMBING_UP; } if (v->m_joystick[VC_DOWN]) { m_state = CSTATE_CLIMBING_DOWN; } break; case CSTATE_CLIMBING_DOWN: set_layer(3, map); m_y += PLAYER_CLIMBING_SPEED; if (map->collision_with_background(this, GLTM)) { m_y -= PLAYER_CLIMBING_SPEED; if (!map->collision_with_background(this, GLTM) || !map->collision_with_object(this, GLTM, rope_symbol)) { set_layer(2, map); if (m_facebefore_vine == 0) m_state = CSTATE_STANDING_LEFT; else m_state = CSTATE_STANDING_RIGHT; m_state_cycle = 0; } else { m_y += PLAYER_CLIMBING_SPEED; } } m_state_cycle++; if (!v->m_joystick[VC_DOWN]) { m_state = CSTATE_CLIMBING; } if (v->m_joystick[VC_UP] && !v->m_old_joystick[VC_UP]) { m_state = CSTATE_CLIMBING_UP; } break; case CSTATE_ENTERING_DOOR: if (m_state_cycle == 0) SFXM->SFX_play("sfx/skulldoor_warp", m_sfx_volume); m_state_cycle++; if (m_state_cycle > 50) { m_requested_room = true; m_state = CSTATE_STANDING_RIGHT; } break; case CSTATE_DYING: m_state_cycle++; if (m_state_cycle / 8 == 5) SFXM->SFX_play("sfx/player_land", m_sfx_volume, get_player_angle(), get_player_distance()); if (m_state_cycle > 100) m_state = CSTATE_DEAD; break; case CSTATE_DEAD: break; } // continuous SFX: switch (m_state) { case CSTATE_STANDING_LEFT: case CSTATE_STANDING_RIGHT: case CSTATE_JUMPING_LEFT: case CSTATE_JUMPING_RIGHT: case CSTATE_JUMPING_LEFT_LEFT: case CSTATE_JUMPING_RIGHT_RIGHT: case CSTATE_FALLING_LEFT: case CSTATE_FALLING_RIGHT: case CSTATE_PUNCH_LEFT: case CSTATE_PUNCH_RIGHT: case CSTATE_JUMPPUNCH_LEFT: case CSTATE_JUMPPUNCH_RIGHT: case CSTATE_JUMPPUNCH_LEFT_LEFT: case CSTATE_JUMPPUNCH_RIGHT_RIGHT: case CSTATE_CLIMBING: if (m_walking_channel != -1) { Mix_HaltChannel(m_walking_channel); m_walking_channel = -1; } if (m_climbing_channel != -1) { Mix_HaltChannel(m_climbing_channel); m_climbing_channel = -1; } break; case CSTATE_WALKING_LEFT: case CSTATE_WALKING_RIGHT: if (m_climbing_channel != -1) { Mix_HaltChannel(m_climbing_channel); m_climbing_channel = -1; } // time playing of sfx to step animation if (m_state_cycle % 16 == 0) { bool walk_on_bridge = ((map->collision_with_object(this, 0, 2, GLTM, bridge_symbol)!=0) ? true : false); if (m_walking_channel != -1) { if (m_step_cycle == 1) { if (walk_on_bridge) SFXM->SFX_play_channel("sfx/player_walk_bridge1", m_walking_channel, get_player_angle(), get_player_distance(), m_sfx_volume); else SFXM->SFX_play_channel("sfx/player_walk1", m_walking_channel, get_player_angle(), get_player_distance(), m_sfx_volume); m_step_cycle = 0; } else { if (walk_on_bridge) SFXM->SFX_play_channel("sfx/player_walk_bridge2", m_walking_channel, get_player_angle(), get_player_distance(), m_sfx_volume); else SFXM->SFX_play_channel("sfx/player_walk2", m_walking_channel, get_player_angle(), get_player_distance(), m_sfx_volume); m_step_cycle = 1; } Mix_SetPosition(m_walking_channel, get_player_angle(), get_player_distance()); } else { if (walk_on_bridge) m_walking_channel = SFXM->SFX_play("sfx/player_walk_bridge1", m_sfx_volume); else m_walking_channel = SFXM->SFX_play("sfx/player_walk1", m_sfx_volume); m_step_cycle = 1; } } break; case CSTATE_CLIMBING_UP: case CSTATE_CLIMBING_DOWN: if (m_walking_channel != -1) { Mix_HaltChannel(m_walking_channel); m_walking_channel = -1; } if (m_climbing_channel != -1) { Mix_SetPosition(m_climbing_channel, get_player_angle(), get_player_distance()); } if (m_climbing_channel == -1) { m_climbing_channel = SFXM->SFX_play_continuous("sfx/player_climb", m_sfx_volume, get_player_angle(), get_player_distance(),this); } break; } if (m_layer != 3 && map->collision_with_background(this, GLTM)) { int i, j; bool found = false; #ifdef __DEBUG_MESSAGES output_debug_message("GO_character: finding a proper position from %i,%i\n",int(m_x),int(m_y)); #endif for (i = 1;i < 5 && !found;i++) { for (j = 0;j <= i && !found;j++) { if (!found && !map->collision_with_background(this, j, i - j, GLTM)) { m_x += j; m_y += i - j; found = true; } if (!found && (i - j) != 0) { if (!map->collision_with_background(this, j, -(i - j), GLTM)) { m_x += j; m_y += -(i - j); found = true; } } if (!found && j != 0) { if (!map->collision_with_background(this, -j, i - j, GLTM)) { m_x += -j; m_y += i - j; found = true; } } if (!found && j != 0 && (i - j) != 0) { if (!map->collision_with_background(this, -j, -(i - j), GLTM)) { m_x += -j; m_y += -(i - j); found = true; } } } } #ifdef __DEBUG_MESSAGES if (found) output_debug_message("GO_character: found proper position: %i,%i\n",int(m_x),int(m_y)); #endif if (!found && m_player_hit_counter == 0) { m_energy = 0; m_player_hit_counter = 64; SFXM->SFX_play("sfx/player_dead", m_sfx_volume, get_player_angle(), get_player_distance()); } } // check for keys: if (!m_key) { GObject *o = map->collision_with_object(this, GLTM, key_symbol); if (o != 0) { if (o->get_state() == 0) { SFXM->SFX_play("sfx/player_pickup_key", m_sfx_volume, get_player_angle(), get_player_distance()); o->set_state(1); m_key = true; inc_score(200); if (m_last_pick != 0) delete m_last_pick; m_last_pick = new Symbol(key_symbol); } } } // check for coins: { GObject *o = map->collision_with_object(this, GLTM, coin_symbol); if (o != 0) { if (o->get_state() == 0) { SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance()); o->set_state(2); inc_score(500); if (m_last_pick != 0) delete m_last_pick; m_last_pick = new Symbol("coin_symbol"); } } } // check for other items: { GO_item *o = (GO_item *)map->collision_with_object(this, GLTM, item_symbol); if (o != 0) { if (o->get_state() == 0) { o->set_state(1); if (m_last_pick != 0) delete m_last_pick; m_last_pick = new Symbol(item_symbol); // Pick up the object: update the internal status: switch (o->get_type()) { case 0: SFXM->SFX_play("sfx/rescue_goonie", m_sfx_volume); m_goonies_rescued++; inc_score(2000); break; case 1: SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance()); m_energy += 6; if (m_energy > PLAYER_MAX_ENERGY) m_energy = PLAYER_MAX_ENERGY; break; case 2: m_items.Add(new Symbol("GO_yellowhelmet")); m_yellowhelmet_status = 5; m_yellowhelmet_timer = 0; m_last_pick = new Symbol("GO_yellowhelmet"); SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance()); inc_score(1000); break; case 3: m_items.Add(new Symbol("GO_shoes")); if (m_last_pick != 0) delete m_last_pick; m_last_pick = new Symbol("GO_shoes"); SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance()); inc_score(1000); break; case 4: m_items.Add(new Symbol("GO_greycoat")); m_greycoat_status = 5; m_greycoat_timer = 0; m_last_pick = new Symbol("GO_greycoat"); SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance()); inc_score(1000); break; case 5: m_items.Add(new Symbol("GO_yellowcoat")); if (m_last_pick != 0) delete m_last_pick; m_last_pick = new Symbol("GO_yellowcoat"); SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance()); inc_score(1000); m_yellowcoat_timer = 500; break; case 6: m_items.Add(new Symbol("GO_hammer")); m_hammer_status = 30; // each time a drop falls, this is decremented once, and every time it becomes // an odd number, the drop is converted into a coin if (m_last_pick != 0) delete m_last_pick; m_last_pick = new Symbol("GO_hammer"); SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance()); inc_score(1000); break; case 7: // energy increasing bag m_energy += 8; if (m_energy >= PLAYER_MAX_ENERGY) m_energy = PLAYER_MAX_ENERGY; break; case 8: m_items.Add(new Symbol("GO_lamp")); if (m_last_pick != 0) delete m_last_pick; m_last_pick = new Symbol("GO_lamp"); SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance()); inc_score(1000); break; case 9: m_items.Add(new Symbol("GO_greenbook")); m_greenbook_status = 5; m_last_pick = new Symbol("GO_greenbook"); SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance()); inc_score(1000); break; case 10: m_items.Add(new Symbol("GO_redbook")); m_redbook_status = 4; m_last_pick = new Symbol("GO_redbook"); SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance()); inc_score(1000); break; case 11: m_items.Add(new Symbol("GO_lightbluebook")); m_lightbluebook_status = 5; m_last_pick = new Symbol("GO_lightbluebook"); SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance()); inc_score(1000); break; case 12: m_items.Add(new Symbol("GO_bluebook")); m_bluebook_status = 5; m_last_pick = new Symbol("GO_bluebook"); SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance()); inc_score(1000); break; case 13: m_items.Add(new Symbol("GO_greencoat")); m_greencoat_timer = 500; m_last_pick = new Symbol("GO_greencoat"); SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance()); inc_score(1000); break; case 14: m_items.Add(new Symbol("GO_whitebook")); m_whitebook_status = 5; m_last_pick = new Symbol("GO_whitebook"); SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance()); inc_score(1000); break; case 15: m_items.Add(new Symbol("GO_yellowshield")); m_yellowshield_status = 5; m_last_pick = new Symbol("GO_yellowshield"); SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance()); inc_score(1000); break; case 16: m_experience++; SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance()); break; case 17: m_items.Add(new Symbol("GO_lightbluecoat")); m_lightbluecoat_timer = 500; m_last_pick = new Symbol("GO_lightbluecoat"); SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance()); inc_score(1000); break; case 18: m_items.Add(new Symbol("GO_whiteshield")); m_yellowshield_status = 5; m_last_pick = new Symbol("GO_whiteshield"); SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance()); inc_score(1000); break; case 19: m_items.Add(new Symbol("GO_redbadbook")); m_last_pick = new Symbol("GO_redbadbook"); SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance()); inc_score(1000); break; case 20: m_items.Add(new Symbol("GO_purplebook")); m_last_pick = new Symbol("GO_purplebook"); SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance()); inc_score(1000); break; case 21: m_items.Add(new Symbol("GO_lightbluehelmet")); m_lightbluehelmet_status = 5; m_last_pick = new Symbol("GO_lightbluehelmet"); SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance()); inc_score(1000); break; case 22: m_items.Add(new Symbol("GO_yellowbook")); m_yellowbook_status = 5; m_last_pick = new Symbol("GO_yellowbook"); SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance()); inc_score(1000); break; case 23: m_items.Add(new Symbol("GO_purplebadbook")); m_last_pick = new Symbol("GO_purplebadbook"); SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance()); inc_score(1000); break; case 24: m_items.Add(new Symbol("GO_purpleshield")); m_purpleshield_status = 5; m_last_pick = new Symbol("GO_purpleshield"); SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance()); inc_score(1000); break; case 25: m_items.Add(new Symbol("GO_clock")); m_clock_timer = 1500; m_last_pick = new Symbol("GO_clock"); SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance()); inc_score(1000); break; case 26: m_items.Add(new Symbol("GO_bluebadbook")); m_bluebadbook_nghosts = 2; m_last_pick = new Symbol("GO_bluebadbook"); SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance()); inc_score(1000); break; case 27: SFXM->SFX_play("sfx/rescue_goonie", m_sfx_volume); if (!m_rescued_goonies[0]) { m_rescued_goonies[0] = true; m_goonies_rescued++; } inc_score(2000); break; case 28: SFXM->SFX_play("sfx/rescue_goonie", m_sfx_volume); if (!m_rescued_goonies[1]) { m_rescued_goonies[1] = true; m_goonies_rescued++; } inc_score(2000); break; case 29: SFXM->SFX_play("sfx/rescue_goonie", m_sfx_volume); if (!m_rescued_goonies[2]) { m_rescued_goonies[2] = true; m_goonies_rescued++; } inc_score(2000); break; case 30: SFXM->SFX_play("sfx/rescue_goonie", m_sfx_volume); if (!m_rescued_goonies[3]) { m_rescued_goonies[3] = true; m_goonies_rescued++; } inc_score(2000); break; case 31: SFXM->SFX_play("sfx/rescue_goonie", m_sfx_volume); if (!m_rescued_goonies[4]) { m_rescued_goonies[4] = true; m_goonies_rescued++; } inc_score(2000); break; case 32: SFXM->SFX_play("sfx/rescue_goonie", m_sfx_volume); if (!m_rescued_goonies[5]) { m_rescued_goonies[5] = true; m_goonies_rescued++; } inc_score(2000); break; case 33: SFXM->SFX_play("sfx/rescue_goonie", m_sfx_volume); if (!m_rescued_goonies[6]) { m_rescued_goonies[6] = true; m_goonies_rescued++; } inc_score(2000); break; default: SFXM->SFX_play("sfx/player_pickup_item", m_sfx_volume, get_player_angle(), get_player_distance()); break; } } } } // check for enemies: if (m_player_hit_counter > 0) { m_player_hit_counter--; } else { if (m_state != CSTATE_ENTERING_DOOR && !m_requested_room) { bool saved = false; int energy_taken = 0; GO_enemy *e = (GO_enemy *)map->collision_with_object(this, GLTM, "GO_enemy"); if (e != 0) energy_taken = (int)(e->enemy_hit() * difficulty / 100); if (energy_taken != 0) { if (e->get_class()->cmp(bat_symbol)) SFXM->SFX_play("sfx/bat_attack", m_sfx_volume, get_angle(map), get_distance(map)); if (e->get_class()->cmp(fallingrock_symbol)) { if (player_has("GO_yellowhelmet") && (m_yellowhelmet_status > 0 || m_yellowhelmet_timer > 0)) { if (m_yellowhelmet_timer == 0) { m_yellowhelmet_timer = 32; m_yellowhelmet_status--; } saved = true; } } if (e->get_class()->cmp(bullet_symbol)) { if (player_has("GO_yellowshield") && (m_yellowshield_status > 0 || m_yellowshield_timer > 0)) { if (m_yellowshield_timer == 0) { m_yellowshield_timer = 32; m_yellowshield_status--; } saved = true; } } if (e->get_class()->cmp(musicalnote_symbol)) { if (player_has("GO_whiteshield") && (m_whiteshield_status > 0 || m_whiteshield_timer > 0)) { if (m_whiteshield_timer == 0) { m_whiteshield_timer = 32; m_whiteshield_status--; } saved = true; } } if (e->get_class()->cmp(bone_symbol)) { if (player_has("GO_purpleshield") && (m_purpleshield_status > 0 || m_purpleshield_timer > 0)) { if (m_purpleshield_timer == 0) { m_purpleshield_timer = 32; m_purpleshield_status--; } saved = true; } } if (e->get_class()->cmp(drop_symbol)) { if (player_has("GO_greycoat") && (m_greycoat_status > 0 || m_greycoat_timer > 0)) { if (m_greycoat_timer == 0) { m_greycoat_timer = 32; m_greycoat_status--; } saved = true; } } if (e->is_a(skull_symbol)) { int exp; int score; if (player_has("GO_greenbook") && m_greenbook_status > 0) { m_greenbook_status--; e->player_hit(&exp, &score); m_experience += exp; saved = true; } if (!saved) { if (player_has("GO_bluebook") && (m_bluebook_status > 0 || m_bluebook_timer > 0)) { if (m_bluebook_timer == 0) { m_bluebook_timer = 32; m_bluebook_status--; } saved = true; } } } if (e->get_class()->cmp(bat_symbol)) { int exp; int score; if (player_has("GO_lightbluebook") && m_lightbluebook_status > 0) { m_lightbluebook_status--; e->player_hit(&exp, &score); m_experience += exp; saved = true; } if (!saved) { if (player_has("GO_lightbluehelmet") && (m_lightbluehelmet_status > 0 || m_lightbluehelmet_timer > 0)) { if (m_lightbluehelmet_timer == 0) { m_lightbluehelmet_timer = 32; m_lightbluehelmet_status--; } saved = true; } } } if (e->get_class()->cmp(skeleton_symbol)) { int exp; int score; if (player_has("GO_whitebook") && m_whitebook_status > 0) { m_whitebook_status--; e->player_hit(&exp, &score); m_experience += exp; saved = true; } if (!saved) { if (player_has("GO_yellowbook") && (m_yellowbook_status > 0 || m_yellowbook_timer > 0)) { if (m_yellowbook_timer == 0) { m_yellowbook_timer = 32; m_yellowbook_status--; } saved = true; } } } if (e->get_class()->cmp(pipe_water_symbol)) { if (player_has("GO_yellowcoat") && m_yellowcoat_timer > 0) { saved = true; m_yellowcoat_timer--; } } if (e->get_class()->cmp(flame_symbol)) { if (player_has("GO_greencoat") && m_greencoat_timer > 0) { saved = true; m_greencoat_timer--; } } if (e->get_class()->cmp(fallingwater_symbol)) { if (player_has("GO_lightbluecoat") && m_lightbluecoat_timer > 0) { saved = true; m_lightbluecoat_timer--; } } if (m_last_hit_by != 0) delete m_last_hit_by; m_last_hit_by = new Symbol(e->get_class()); if (!saved) { m_energy -= energy_taken; m_player_hit_counter = 64; if (e->is_a(fallingwater_symbol)) m_player_hit_counter = 8; if (e->is_a(flame_symbol)) m_player_hit_counter = 8; if (e->is_a(pipe_water_symbol)) m_player_hit_counter = 8; if (m_energy > 0) SFXM->SFX_play("sfx/player_hit", m_sfx_volume, get_player_angle(), get_player_distance()); else SFXM->SFX_play("sfx/player_dead", m_sfx_volume, get_player_angle(), get_player_distance()); } } } } // check for experience: if (m_experience >= PLAYER_MAX_EXPERIENCE) { m_experience = 0; m_energy += 8; if (m_energy >= PLAYER_MAX_ENERGY) m_energy = PLAYER_MAX_ENERGY; } if (m_energy <= 0 && m_state != CSTATE_DYING && m_state != CSTATE_DEAD) { m_player_hit_counter = 512; m_energy = 0; m_state = CSTATE_DYING; m_state_cycle = 0; if (m_walking_channel!=0) SFXM->SFX_stop(m_walking_channel); if (m_climbing_channel!=0) SFXM->SFX_stop(m_climbing_channel); m_walking_channel=-1; m_climbing_channel=-1; } if (m_yellowhelmet_timer > 0) m_yellowhelmet_timer--; if (m_greycoat_timer > 0) m_greycoat_timer--; if (m_bluebook_timer > 0) m_bluebook_timer--; if (m_yellowshield_timer > 0) m_yellowshield_timer--; if (m_whiteshield_timer > 0) m_whiteshield_timer--; if (m_lightbluehelmet_timer > 0) m_lightbluehelmet_timer--; if (m_yellowbook_timer > 0) m_yellowbook_timer--; if (m_purpleshield_timer > 0) m_purpleshield_timer--; if (m_clock_timer > 0) m_clock_timer--; if (((m_state == CSTATE_STANDING_LEFT) || (m_state == CSTATE_WALKING_LEFT)) && ((m_previous_state == CSTATE_STANDING_RIGHT) || (m_previous_state == CSTATE_WALKING_RIGHT))) m_turning_counter = 6; if (((m_state == CSTATE_STANDING_RIGHT) || (m_state == CSTATE_WALKING_RIGHT)) && ((m_previous_state == CSTATE_STANDING_LEFT) || (m_previous_state == CSTATE_WALKING_LEFT))) m_turning_counter = 6; if (m_turning_counter > 0) m_turning_counter--; return true; } void GO_character::draw(GLTManager *GLTM) { int s2 = (m_state_cycle / 8) % 2; int s4 = (m_state_cycle / 8) % 4; int s10 = m_state_cycle / 8; float xo = 0, yo = 0; switch (m_state) { case CSTATE_STANDING_LEFT: if (m_turning_counter) m_last_tile_used = GLTM->get ("ob_character-turn"); else { int salute = (m_state_cycle % 615); if (salute >= 250 && salute < 255 ) m_last_tile_used = GLTM->get ("ob_character_salute-l1"); else if (salute >= 255 && salute < 260) m_last_tile_used = GLTM->get ("ob_character_salute-l2"); else if (salute >= 260 && salute < 265) m_last_tile_used = GLTM->get ("ob_character_salute-l1"); else if (salute >= 265 && salute < 270) m_last_tile_used = GLTM->get ("ob_character_salute-l2"); else if (salute >= 270 && salute < 275) m_last_tile_used = GLTM->get ("ob_character_salute-l1"); else if (salute >= 275 && salute < 280) m_last_tile_used = GLTM->get ("ob_character_salute-l2"); else if (salute >= 500 && salute < 505) m_last_tile_used = GLTM->get ("ob_character-tapping-foot1"); else if (salute >= 505 && salute < 510) m_last_tile_used = GLTM->get ("ob_character-tapping-foot2"); else if (salute >= 510 && salute < 515) m_last_tile_used = GLTM->get ("ob_character-tapping-foot3"); else if (salute >= 515 && salute < 520) m_last_tile_used = GLTM->get ("ob_character-tapping-foot2"); else if (salute >= 520 && salute < 525) m_last_tile_used = GLTM->get ("ob_character-tapping-foot1"); else if (salute >= 525 && salute < 530) m_last_tile_used = GLTM->get ("ob_character-tapping-foot2"); else if (salute >= 530 && salute < 535) m_last_tile_used = GLTM->get ("ob_character-tapping-foot3"); else if (salute >= 535 && salute < 540) m_last_tile_used = GLTM->get ("ob_character-tapping-foot2"); else if (salute >= 540 && salute < 545) m_last_tile_used = GLTM->get ("ob_character-tapping-foot1"); else if (salute >= 545 && salute < 550) m_last_tile_used = GLTM->get ("ob_character-tapping-foot2"); else if (salute >= 550 && salute < 555) m_last_tile_used = GLTM->get ("ob_character-tapping-foot3"); else if (salute >= 555 && salute < 560) m_last_tile_used = GLTM->get ("ob_character-tapping-foot2"); else if (salute >= 560 && salute < 565) m_last_tile_used = GLTM->get ("ob_character-tapping-foot1"); else if (salute >= 565 && salute < 570) m_last_tile_used = GLTM->get ("ob_character-knocking1"); else if (salute >= 570 && salute < 575) m_last_tile_used = GLTM->get ("ob_character-knocking2"); else if (salute >= 575 && salute < 580) m_last_tile_used = GLTM->get ("ob_character-knocking3"); else if (salute >= 580 && salute < 585) m_last_tile_used = GLTM->get ("ob_character-knocking4"); else if (salute >= 585 && salute < 590) m_last_tile_used = GLTM->get ("ob_character-knocking3"); else if (salute >= 590 && salute < 595) m_last_tile_used = GLTM->get ("ob_character-knocking4"); else if (salute >= 595 && salute < 600) m_last_tile_used = GLTM->get ("ob_character-knocking3"); else if (salute >= 600 && salute < 605) m_last_tile_used = GLTM->get ("ob_character-knocking4"); else if (salute >= 605 && salute < 610) m_last_tile_used = GLTM->get ("ob_character-knocking2"); else if (salute >= 610 && salute < 615) m_last_tile_used = GLTM->get ("ob_character-knocking1"); else if (s4 == 0 || s4 == 1) m_last_tile_used = GLTM->get ("ob_character_stand-l1"); else if (s4 == 2 || s4 == 3) m_last_tile_used = GLTM->get ("ob_character_stand-l2"); } break; case CSTATE_STANDING_RIGHT: if (m_turning_counter) m_last_tile_used = GLTM->get ("ob_character-turn"); else { int salute = (m_state_cycle % 615); if (salute >= 250 && salute < 255 ) m_last_tile_used = GLTM->get ("ob_character_salute-r1"); else if (salute >= 255 && salute < 260) m_last_tile_used = GLTM->get ("ob_character_salute-r2"); else if (salute >= 260 && salute < 265) m_last_tile_used = GLTM->get ("ob_character_salute-r1"); else if (salute >= 265 && salute < 270) m_last_tile_used = GLTM->get ("ob_character_salute-r2"); else if (salute >= 270 && salute < 275) m_last_tile_used = GLTM->get ("ob_character_salute-r1"); else if (salute >= 275 && salute < 280) m_last_tile_used = GLTM->get ("ob_character_salute-r2"); else if (salute >= 500 && salute < 505) m_last_tile_used = GLTM->get ("ob_character-tapping-foot1"); else if (salute >= 505 && salute < 510) m_last_tile_used = GLTM->get ("ob_character-tapping-foot2"); else if (salute >= 510 && salute < 515) m_last_tile_used = GLTM->get ("ob_character-tapping-foot3"); else if (salute >= 515 && salute < 520) m_last_tile_used = GLTM->get ("ob_character-tapping-foot2"); else if (salute >= 520 && salute < 525) m_last_tile_used = GLTM->get ("ob_character-tapping-foot1"); else if (salute >= 525 && salute < 530) m_last_tile_used = GLTM->get ("ob_character-tapping-foot2"); else if (salute >= 530 && salute < 535) m_last_tile_used = GLTM->get ("ob_character-tapping-foot3"); else if (salute >= 535 && salute < 540) m_last_tile_used = GLTM->get ("ob_character-tapping-foot2"); else if (salute >= 540 && salute < 545) m_last_tile_used = GLTM->get ("ob_character-tapping-foot1"); else if (salute >= 545 && salute < 550) m_last_tile_used = GLTM->get ("ob_character-tapping-foot2"); else if (salute >= 550 && salute < 555) m_last_tile_used = GLTM->get ("ob_character-tapping-foot3"); else if (salute >= 555 && salute < 560) m_last_tile_used = GLTM->get ("ob_character-tapping-foot2"); else if (salute >= 560 && salute < 565) m_last_tile_used = GLTM->get ("ob_character-tapping-foot1"); else if (salute >= 565 && salute < 570) m_last_tile_used = GLTM->get ("ob_character-knocking1"); else if (salute >= 570 && salute < 575) m_last_tile_used = GLTM->get ("ob_character-knocking2"); else if (salute >= 575 && salute < 580) m_last_tile_used = GLTM->get ("ob_character-knocking3"); else if (salute >= 580 && salute < 585) m_last_tile_used = GLTM->get ("ob_character-knocking4"); else if (salute >= 585 && salute < 590) m_last_tile_used = GLTM->get ("ob_character-knocking3"); else if (salute >= 590 && salute < 595) m_last_tile_used = GLTM->get ("ob_character-knocking4"); else if (salute >= 595 && salute < 600) m_last_tile_used = GLTM->get ("ob_character-knocking3"); else if (salute >= 600 && salute < 605) m_last_tile_used = GLTM->get ("ob_character-knocking4"); else if (salute >= 605 && salute < 610) m_last_tile_used = GLTM->get ("ob_character-knocking2"); else if (salute >= 610 && salute < 615) m_last_tile_used = GLTM->get ("ob_character-knocking1"); else if (s4 == 0 || s4 == 1) m_last_tile_used = GLTM->get ("ob_character_stand-r1"); else if (s4 == 2 || s4 == 3) m_last_tile_used = GLTM->get ("ob_character_stand-r2"); } break; case CSTATE_WALKING_LEFT: if (m_turning_counter) { m_last_tile_used = GLTM->get ("ob_character-turn"); } else { if (s4 == 0) m_last_tile_used = GLTM->get ("ob_character-l2"); if (s4 == 1) m_last_tile_used = GLTM->get ("ob_character-l1"); if (s4 == 2) m_last_tile_used = GLTM->get ("ob_character-l3"); if (s4 == 3) m_last_tile_used = GLTM->get ("ob_character-l1"); } break; case CSTATE_WALKING_RIGHT: if (m_turning_counter) { m_last_tile_used = GLTM->get ("ob_character-turn"); } else { if (s4 == 0) m_last_tile_used = GLTM->get ("ob_character-r2"); if (s4 == 1) m_last_tile_used = GLTM->get ("ob_character-r1"); if (s4 == 2) m_last_tile_used = GLTM->get ("ob_character-r3"); if (s4 == 3) m_last_tile_used = GLTM->get ("ob_character-r1"); } break; case CSTATE_PUNCH_LEFT: m_last_tile_used = GLTM->get ("ob_character-punch-l"); break; case CSTATE_PUNCH_RIGHT: m_last_tile_used = GLTM->get ("ob_character-punch-r"); break; case CSTATE_FALLING_LEFT: if (s2 == 0) m_last_tile_used = GLTM->get("ob_character-fall1"); if (s2 == 1) m_last_tile_used = GLTM->get("ob_character-fall2"); break; case CSTATE_FALLING_RIGHT: if (s2 == 0) m_last_tile_used = GLTM->get("ob_character-fall1"); if (s2 == 1) m_last_tile_used = GLTM->get("ob_character-fall2"); break; case CSTATE_JUMPING_LEFT: case CSTATE_JUMPING_LEFT_LEFT: m_last_tile_used = GLTM->get ("ob_character-jump-l"); break; case CSTATE_JUMPING_RIGHT: case CSTATE_JUMPING_RIGHT_RIGHT: m_last_tile_used = GLTM->get ("ob_character-jump-r"); break; case CSTATE_JUMPPUNCH_LEFT: case CSTATE_JUMPPUNCH_LEFT_LEFT: m_last_tile_used = GLTM->get ("ob_character-punchjump-l"); break; case CSTATE_JUMPPUNCH_RIGHT: case CSTATE_JUMPPUNCH_RIGHT_RIGHT: m_last_tile_used = GLTM->get ("ob_character-punchjump-r"); break; case CSTATE_CLIMBING_UP: case CSTATE_CLIMBING: case CSTATE_CLIMBING_DOWN: if (s4 == 0 || s4 == 2) m_last_tile_used = GLTM->get ("ob_character-climbing-1"); if (s4 == 1 || s4 == 3) m_last_tile_used = GLTM->get ("ob_character-climbing-2"); break; case CSTATE_ENTERING_DOOR: if (s4 == 0) m_last_tile_used = GLTM->get ("ob_character-r2"); if (s4 == 1) m_last_tile_used = GLTM->get ("ob_character-r1"); if (s4 == 2) m_last_tile_used = GLTM->get ("ob_character-r3"); if (s4 == 3) m_last_tile_used = GLTM->get ("ob_character-r1"); xo = -(m_state_cycle / 75.0F); yo = 0.0; break; case CSTATE_DYING: if (s10 == 0) m_last_tile_used = GLTM->get("ob_character-death1"); if (s10 == 1) m_last_tile_used = GLTM->get("ob_character-death2"); if (s10 == 2) m_last_tile_used = GLTM->get("ob_character-death3"); if (s10 == 3) m_last_tile_used = GLTM->get("ob_character-death3"); if (s10 == 4) m_last_tile_used = GLTM->get("ob_character-death4"); if (s10 == 5) m_last_tile_used = GLTM->get("ob_character-death5"); if (s10 == 6) m_last_tile_used = GLTM->get("ob_character-death6"); if (s10 == 7) m_last_tile_used = GLTM->get("ob_character-death5"); if (s10 == 8) m_last_tile_used = GLTM->get("ob_character-death6"); if (s10 >= 9) m_last_tile_used = GLTM->get("ob_character-death5"); break; } if ((m_player_hit_counter > 0) && (m_state != CSTATE_DYING) && (m_state != CSTATE_DEAD)) { int bufi; float TexColorArray[4], bufvf[4]; float f = float(0.5F + 0.5F * sin(m_player_hit_counter * ((m_state == CSTATE_DYING || m_state == CSTATE_DEAD) ? 0.8f : 0.4f))); glGetTexEnviv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, &bufi); glGetTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, bufvf); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_BLEND); TexColorArray[0] = 1.0f; TexColorArray[1] = 1.0f; TexColorArray[2] = 1.0f; TexColorArray[3] = 0.0f; glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, TexColorArray); if (xo == 0 && yo == 0) m_last_tile_used->draw(1, 1, 1, 1, m_x, m_y, 0, 0, 1); else m_last_tile_used->draw_toffs(1, 1, 1, 1, m_x, m_y, 0, 0, 1, xo, yo); glColor4f(1, 1, 1, 1); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, bufi); glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, bufvf); glBindTexture(GL_TEXTURE_2D, 0); // I really don't understand this line of code, but if I don't add it, // I don't get the desired effect (I found this after like 2 hours of random guessing!) if (xo == 0 && yo == 0) m_last_tile_used->draw(1, 1, 1, f, m_x, m_y, 0, 0, 1); else m_last_tile_used->draw_toffs(1, 1, 1, f, m_x, m_y, 0, 0, 1, xo, yo); } else { if (xo == 0 && yo == 0) m_last_tile_used->draw(1, 1, 1, 1, m_x, m_y, 0, 0, 1); else m_last_tile_used->draw_toffs(1, 1, 1, 1, m_x, m_y, 0, 0, 1, xo, yo); } } bool GO_character::is_a(Symbol *c) { if (c->cmp(character_symbol)) return true; return GObject::is_a(c); } bool GO_character::is_a(char *c) { bool retval; Symbol *s = new Symbol(c); retval = is_a(s); delete s; return retval; } void GO_character::inc_score(int m_score) { score += m_score; } /* * Calculates the 'angle' of the player, based on its distance from the screen's center */ int GO_character::get_player_angle() { float x = 320 - m_x; float y = 240 - m_y; int angle; angle = (int)(atan2(y, x) * 180 / 3.149265); angle = 270 - angle; if (angle > 360) { angle = 360; } if (angle < 0) { angle = 0; } return angle; }
43.531432
135
0.46263
pdpdds
4a92aa08906e8bea87c98c0885d18dfce9960949
436
cpp
C++
PAT/PAT-B/CPP/1092.最好吃的月饼.cpp
hao14293/2021-Postgraduate-408
70e1c40e6bcf0c5afe4a4638a7c168069d9c8319
[ "MIT" ]
950
2020-02-21T02:39:18.000Z
2022-03-31T07:27:36.000Z
PAT/PAT-B/CPP/1092.最好吃的月饼.cpp
RestmeF/2021-Postgraduate-408
70e1c40e6bcf0c5afe4a4638a7c168069d9c8319
[ "MIT" ]
6
2020-04-03T13:08:47.000Z
2022-03-07T08:54:56.000Z
PAT/PAT-B/CPP/1092.最好吃的月饼.cpp
RestmeF/2021-Postgraduate-408
70e1c40e6bcf0c5afe4a4638a7c168069d9c8319
[ "MIT" ]
131
2020-02-22T15:35:59.000Z
2022-03-21T04:23:57.000Z
#include <iostream> using namespace std; int main(){ int n, m, tmp, max = 0, v[1000] = {0}; scanf("%d%d",&n, &m); // n == 5, m == 3 for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ scanf("%d", &tmp); v[j] += tmp; if(v[j] > max) max = v[j]; } } printf("%d\n", max); int flag = 0; for(int i = 0; i < n; i++){ if(v[i] == max){ if(flag) printf(" "); flag = 1; printf("%d", i + 1); } } return 0; }
18.166667
41
0.431193
hao14293
4a9430264478d9fc53b88c39816be571904f0221
2,459
hpp
C++
src/behaviours/include/Action.hpp
BCLab-UNM/SwarmBaseCode-Modular-Public
2061796570baf65deeb74f29444fcaf3b6464aa1
[ "MIT" ]
null
null
null
src/behaviours/include/Action.hpp
BCLab-UNM/SwarmBaseCode-Modular-Public
2061796570baf65deeb74f29444fcaf3b6464aa1
[ "MIT" ]
null
null
null
src/behaviours/include/Action.hpp
BCLab-UNM/SwarmBaseCode-Modular-Public
2061796570baf65deeb74f29444fcaf3b6464aa1
[ "MIT" ]
null
null
null
#ifndef _ACTION_HPP #define _ACTION_HPP #include "Velocity.hpp" #include "Point.hpp" namespace core { /** * An action defined by a linear and an angular velocity */ class VelocityAction { private: LinearVelocity _linear; AngularVelocity _angular; public: VelocityAction(); VelocityAction(LinearVelocity linear); VelocityAction(AngularVelocity angular); VelocityAction(LinearVelocity linear, AngularVelocity angular); ~VelocityAction(); void SetRoll(double yaw); void SetPitch(double pitch); void SetYaw(double yaw); void SetX(double x); void SetY(double y); void SetZ(double z); double GetX() const; double GetY() const; double GetZ() const; double GetRoll() const; double GetPitch() const; double GetYaw() const; void SetLinear(LinearVelocity linear); void SetAngular(AngularVelocity angular); double GetAngularMagnitude() const; double GetLinearMagnitude() const; }; /** * An action that defines a location in space the robot should move * towards. */ class WaypointAction { private: Point _waypoint; double _speed = 0.75; // meters per second double _tolerance = 0.15; // 0.15 meters public: WaypointAction(Point w); ~WaypointAction(); Point GetWaypoint() const; double GetSpeed() const; double GetTolerance() const; double GetX() const; double GetY() const; double GetZ() const; void SetTolerance(double t); void SetSpeed(double s); void SetWaypoint(Point w); void SetX(double x); void SetY(double y); void SetZ(double z); bool IsAt(const Point&) const; }; /** * The action to be taken by a robot. */ class Action { public: class BadType{}; enum Type { VELOCITY, WAYPOINT }; private: Type _type; union { VelocityAction _velocity; WaypointAction _waypoint; }; public: Action(VelocityAction v); Action(WaypointAction w); ~Action() {} VelocityAction GetVelocity() const throw(BadType); WaypointAction GetWaypoint() const throw(BadType); Action::Type GetType() const; void SetAction(VelocityAction v); void SetAction(WaypointAction w); }; } #endif // _ACTION_HPP
22.354545
70
0.611224
BCLab-UNM
4a9c7f24c0ea0348e4f1ca777afb833e4e77ef4e
706
cpp
C++
higan/target-tomoko/settings/timing.cpp
ameer-bauer/higan-097
a4a28968173ead8251cfa7cd6b5bf963ee68308f
[ "Info-ZIP" ]
3
2016-03-23T01:17:36.000Z
2019-10-25T06:41:09.000Z
higan/target-tomoko/settings/timing.cpp
ameer-bauer/higan-097
a4a28968173ead8251cfa7cd6b5bf963ee68308f
[ "Info-ZIP" ]
null
null
null
higan/target-tomoko/settings/timing.cpp
ameer-bauer/higan-097
a4a28968173ead8251cfa7cd6b5bf963ee68308f
[ "Info-ZIP" ]
null
null
null
TimingSettings::TimingSettings(TabFrame* parent) : TabFrameItem(parent) { setIcon(Icon::Device::Clock); setText("Timing"); layout.setMargin(5); videoLabel.setText("Video:"); videoValue.setText(settings["Timing/Video"].real()).onActivate([&] { update(); }); videoAssign.setText("Assign").onActivate([&] { update(); }); audioLabel.setText("Audio:"); audioValue.setText(settings["Timing/Audio"].real()).onActivate([&] { update(); }); audioAssign.setText("Assign").onActivate([&] { update(); }); } auto TimingSettings::update() -> void { settings["Timing/Video"].setValue(videoValue.text().real()); settings["Timing/Audio"].setValue(audioValue.text().real()); program->updateDSP(); }
37.157895
84
0.681303
ameer-bauer
4a9eaaa1a2348cac22620013f967b8d2acc03485
1,371
cpp
C++
ext/stub/java/awt/font/TextLayout_CaretPolicy-stub.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/stub/java/awt/font/TextLayout_CaretPolicy-stub.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/stub/java/awt/font/TextLayout_CaretPolicy-stub.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar #include <java/awt/font/TextLayout_CaretPolicy.hpp> extern void unimplemented_(const char16_t* name); java::awt::font::TextLayout_CaretPolicy::TextLayout_CaretPolicy(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } java::awt::font::TextLayout_CaretPolicy::TextLayout_CaretPolicy() : TextLayout_CaretPolicy(*static_cast< ::default_init_tag* >(0)) { ctor(); } void ::java::awt::font::TextLayout_CaretPolicy::ctor() { /* stub */ /* super::ctor(); */ unimplemented_(u"void ::java::awt::font::TextLayout_CaretPolicy::ctor()"); } java::awt::font::TextHitInfo* java::awt::font::TextLayout_CaretPolicy::getStrongCaret(TextHitInfo* hit1, TextHitInfo* hit2, TextLayout* layout) { /* stub */ unimplemented_(u"java::awt::font::TextHitInfo* java::awt::font::TextLayout_CaretPolicy::getStrongCaret(TextHitInfo* hit1, TextHitInfo* hit2, TextLayout* layout)"); return 0; } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* java::awt::font::TextLayout_CaretPolicy::class_() { static ::java::lang::Class* c = ::class_(u"java.awt.font.TextLayout.CaretPolicy", 36); return c; } java::lang::Class* java::awt::font::TextLayout_CaretPolicy::getClass0() { return class_(); }
31.883721
167
0.716995
pebble2015
4a9f1b9b1c50adf780dfda7e89ada478540b809e
4,156
cpp
C++
src/misc/log-pri-enum.cpp
tilnewman/heroespath-src
a7784e44d8b5724f305ef8b8671fed54e2e5fd69
[ "BSL-1.0", "Beerware" ]
2
2019-02-28T00:28:08.000Z
2019-10-20T14:39:48.000Z
src/misc/log-pri-enum.cpp
tilnewman/heroespath-src
a7784e44d8b5724f305ef8b8671fed54e2e5fd69
[ "BSL-1.0", "Beerware" ]
null
null
null
src/misc/log-pri-enum.cpp
tilnewman/heroespath-src
a7784e44d8b5724f305ef8b8671fed54e2e5fd69
[ "BSL-1.0", "Beerware" ]
null
null
null
// ---------------------------------------------------------------------------- // "THE BEER-WARE LICENSE" (Revision 42): // <ztn@zurreal.com> wrote this file. As long as you retain this notice you // can do whatever you want with this stuff. If we meet some day, and you think // this stuff is worth it, you can buy me a beer in return. Ziesche Til Newman // ---------------------------------------------------------------------------- // // log-pri-enum.cpp // #include "log-pri-enum.hpp" #include "misc/platform.hpp" #include <iostream> #include <sstream> namespace heroespath { namespace misc { const std::string LogPriority::ToString(const Enum PRIORITY) { switch (PRIORITY) { case Debug: { return "Debug"; } case Default: { return "Default"; } case Warn: { return "Warn"; } case Error: { return "Error"; } case Fatal: { return "Fatal"; } case Count: { return "(Count)"; } default: { // can't use log or assert macros inside the logging code std::ostringstream ss; ss << __FILE__ << ":" << __func__ << "():" << __LINE__ << "enum_value=" << static_cast<EnumUnderlying_t>(PRIORITY) << " is invalid. (count=" << static_cast<EnumUnderlying_t>(Count) << ")"; std::cerr << ss.str() << std::endl; return ""; } } } const std::string LogPriority::ToStringAcronym(const Enum PRIORITY) { switch (PRIORITY) { case Debug: { return "DBG"; } case Default: { return "DEF"; } case Warn: { return "WRN"; } case Error: { return "ERR"; } case Fatal: { return "FAT"; } case Count: { return "(Count)"; } default: { // can't use log or assert macros inside the logging code std::ostringstream ss; ss << __FILE__ << ":" << __func__ << "():" << __LINE__ << "enum_value=" << static_cast<EnumUnderlying_t>(PRIORITY) << " is invalid. (count=" << static_cast<EnumUnderlying_t>(Count) << ")"; std::cerr << ss.str() << std::endl; return ""; } } } const std::string LogPriority::ConsoleColorStringBegin(const Enum PRIORITY) { // this just prevents a Visual Studio warning that PRIORITY is not used #if defined(HEROESPATH_PLATFORM_DETECTED_IS_WINDOWS) const auto IGNORED { PRIORITY }; return ""; #else switch (PRIORITY) { case Debug: { // cyan on black return "\033[36;40m"; } case Warn: { // yellow on black return "\033[33;40m"; } case Error: case Fatal: { // red on black return "\033[31;40m"; } case Default: case Count: { return "(Count)"; } default: { return ""; } } #endif } const std::string LogPriority::ConsoleColorStringEnd() { #if defined(HEROESPATH_PLATFORM_DETECTED_IS_WINDOWS) return ""; #else return "\033[0;0m"; #endif } } // namespace misc } // namespace heroespath
25.975
93
0.394129
tilnewman
4a9f2a73591cd5cfc53c2ee7df808d5c6affe5c6
213
cpp
C++
test/progress.cpp
ltalirz/util-programs
93c76cb8f52543b55afdd968f6d8374997031a27
[ "MIT" ]
null
null
null
test/progress.cpp
ltalirz/util-programs
93c76cb8f52543b55afdd968f6d8374997031a27
[ "MIT" ]
null
null
null
test/progress.cpp
ltalirz/util-programs
93c76cb8f52543b55afdd968f6d8374997031a27
[ "MIT" ]
null
null
null
#include "boost/progress.hpp" #include<stdio.h> int main() { boost::progress_display d(100); for(int i = 0; i<100; ++i){ sleep(1); std::cout << "i\n"; ++d; } return 0; }
14.2
35
0.488263
ltalirz
4aa0959a974c32187b532dd2aac8287e8be869ca
54
cpp
C++
Algorithm/src/bigword/graph.cpp
elloop/algorithm
5485be0aedbc18968f775cff9533a2d444dbdcb5
[ "MIT" ]
15
2015-11-04T12:53:23.000Z
2021-08-10T09:53:12.000Z
Algorithm/src/bigword/graph.cpp
elloop/algorithm
5485be0aedbc18968f775cff9533a2d444dbdcb5
[ "MIT" ]
null
null
null
Algorithm/src/bigword/graph.cpp
elloop/algorithm
5485be0aedbc18968f775cff9533a2d444dbdcb5
[ "MIT" ]
6
2015-11-13T10:17:01.000Z
2020-05-14T07:25:48.000Z
#include "inc.h" NS_BEGIN(elloop); NS_END(elloop);
7.714286
17
0.685185
elloop
4aa3091a756b04c6d9612c565913cd2d7625d8cf
2,516
hpp
C++
src/debug/debugger.hpp
MFdesigns/uvm
628f6effc9a98adbc9e6e829b60818d8c0865bf9
[ "Apache-2.0" ]
2
2020-11-16T22:02:33.000Z
2021-03-18T16:36:31.000Z
src/debug/debugger.hpp
MFdesigns/uvm
628f6effc9a98adbc9e6e829b60818d8c0865bf9
[ "Apache-2.0" ]
null
null
null
src/debug/debugger.hpp
MFdesigns/uvm
628f6effc9a98adbc9e6e829b60818d8c0865bf9
[ "Apache-2.0" ]
null
null
null
// ======================================================================== // // Copyright 2020 Michel Fäh // // 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. // ======================================================================== // #pragma once #include "../uvm.hpp" #include "http.hpp" #include <cstdint> #include <memory> #include <vector> constexpr uint64_t REQ_MAGIC = 0x3f697a65bcc37247; constexpr uint64_t RES_MAGIC = 0x4772C3BC657A6921; // Operation codes constexpr uint8_t DBG_OPEN_DBG_SESS = 0x01; constexpr uint8_t DBG_CLOSE_DBG_SESS = 0x02; constexpr uint8_t DBG_SET_BREAKPNT = 0xB0; constexpr uint8_t DBG_REMOVE_BREAKPNT = 0xB1; constexpr uint8_t DBG_RUN_APP = 0xE0; constexpr uint8_t DBG_NEXT_INSTR = 0xE1; constexpr uint8_t DBG_CONTINUE_ = 0xE2; constexpr uint8_t DBG_STOP_EXE = 0xE3; constexpr uint8_t DBG_GET_REGS = 0x10; constexpr uint8_t DBG_ERROR = 0xEE; constexpr uint8_t DBG_EXE_FIN = 0xFF; // Error codes constexpr uint8_t ERR_ALREADY_IN_DEBUG_SESSION = 0x1; constexpr uint8_t ERR_NOT_IN_DEBUG_SESSION = 0x2; constexpr uint8_t ERR_RUNTIME_ERROR = 0x3; constexpr uint8_t ERR_FILE_FORMAT_ERROR = 0x4; constexpr uint8_t ERR_BREAKPOINT_ALREADY_SET = 0x5; constexpr uint8_t ERR_BREAKPOINT_NOT_EXISTING = 0x6; enum class DbgSessState { OPEN, RUNNING, CLOSED, }; struct Debugger { /** Server handling HTTP requests and responses */ HTTPServer Server; /** Used to parse incoming requests from the Server */ RequestParser Req; /** Current UVM instance */ std::unique_ptr<UVM> VM; /** Session status */ DbgSessState State = DbgSessState::OPEN; /** List of all currently set breakpoints */ std::vector<uint64_t> Breakpoints; /** Is UVM currently on a breakpoint */ bool OnBreakpoint = false; void startSession(); void closeSession(); bool handleRequest(Response& res); void appendRegisters(std::stringstream& stream); void appendConsole(std::stringstream& stream); uint32_t continueToBreakpoint(); };
33.546667
78
0.705087
MFdesigns
4aa75e1368cd9a7be201b002cee73b125f1a1616
3,016
cpp
C++
eyesim_kebabci_yesim_hw5/ConsoleApplication154/main.cpp
eyesimk/CS204-Advanced-Programming
414a6e1a97aa77bd07f8f3bfbc66da5e3b62421e
[ "MIT" ]
null
null
null
eyesim_kebabci_yesim_hw5/ConsoleApplication154/main.cpp
eyesimk/CS204-Advanced-Programming
414a6e1a97aa77bd07f8f3bfbc66da5e3b62421e
[ "MIT" ]
null
null
null
eyesim_kebabci_yesim_hw5/ConsoleApplication154/main.cpp
eyesimk/CS204-Advanced-Programming
414a6e1a97aa77bd07f8f3bfbc66da5e3b62421e
[ "MIT" ]
null
null
null
#include<iostream> #include <sstream> #include <string> #include "Header.h" //#include your header file here //do not change anything else using namespace std; void printByCopy(Matrix copy) { copy.print(); } void fillMatrix(Matrix & mat) { for (int i = 0; i < mat.getRowNumber(); i++) { for (int j = 0; j < mat.getColumnNumber(); j++) { mat.setElementAt(i, j, (i + j + 1)*mat.getElementAt(i,j)); } } } int main() { //get matrices int row, column, init; cout << "Please enter the row number of Matrix m1:" << endl; cin >> row; cout << "Please enter the column number of Matrix m1:" << endl; cin >> column; cout << "Please enter the init value of Matrix m1:" << endl; cin >> init; cout << endl; Matrix m1(row, column, init); fillMatrix(m1); cout << "Matrix m1:" << endl; printByCopy(m1); cout << endl; cout << "Please enter the row number of Matrix m2:" << endl; cin >> row; cout << "Please enter the column number of Matrix m2:" << endl; cin >> column; cout << "Please enter the init value of Matrix m2:" << endl; cin >> init; cout << endl; Matrix m2(row, column, init); fillMatrix(m2); cout << "Matrix m2:" << endl; printByCopy(m2); cout << endl; cout << "Please enter the row number of Matrix m3:" << endl; cin >> row; cout << "Please enter the column number of Matrix m3:" << endl; cin >> column; cout << "Please enter the init value of Matrix m3:" << endl; cin >> init; cout << endl; Matrix m3(row, column, init); fillMatrix(m3); cout << "Matrix m3:" << endl; printByCopy(m3); cout << endl; //assigment example Matrix m4; m4 = m3; cout << "Matrix m4:" << endl; printByCopy(m4); cout << endl; //equals example if (m1 == m2) { cout << "m1 is equal to m2." << endl; cout << endl; } else { cout << "m1 is not equal to m2." << endl; cout << endl; } //addition example cout << "m3 = m1 + m2 + m1:" << endl; if (m1.getColumnNumber()== m2.getColumnNumber() && m1.getRowNumber() == m2.getRowNumber()) { m3 = m1 + m2 + m1; m3.print(); cout << endl; } else { cout << "Matrix m1 and m2 do not have the same dimensions. Cannot be added." << endl; cout << endl; } //substraction example cout << "m4 = m2 - m1 - m2:" << endl; if (m1.getColumnNumber() == m2.getColumnNumber() && m1.getRowNumber() == m2.getRowNumber()) { m4 = m2 - m1 - m2; m4.print(); cout << endl; } else { cout << "Matrix m1 and m2 do not have the same dimensions. Cannot be subtracted." << endl; cout << endl; } //transpose example cout << "Transpose of m3:" << endl; m3 = !m3; m3.print(); cout << endl; //cascaded assignment cout << "Assigning m4 = m2 = m3." << endl; m4 = m2 = m3; cout << "Matrix m4:" << endl; m4.print(); cout << endl; cout << "Matrix m2:" << endl; m2.print(); cout << endl; cout << "Matrix m3:" << endl; m3.print(); cout << endl; cin.get(); cin.ignore(); return 0; }
23.022901
95
0.575597
eyesimk
4aa76f6d30fb1b9fc15aa6c36b5cebc1dcc4f83d
821
cpp
C++
LeetCode-Challenges/2020/5. May/Day 8/solution.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
LeetCode-Challenges/2020/5. May/Day 8/solution.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
LeetCode-Challenges/2020/5. May/Day 8/solution.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
class Solution { public: bool checkStraightLine(vector<vector<int>>& coordinates) { if(coordinates.size()==2) { return true; } if((coordinates[1][0]-coordinates[0][0])==0) { for(int i=0;i<coordinates.size();i++) { if((coordinates[i][0]-coordinates[0][0])!=0) { return false; } } } float m=(((float)(coordinates[1][1]-coordinates[0][1]))/(coordinates[1][0]-coordinates[0][0])); int c=coordinates[0][1]-m*coordinates[0][0]; for(int i=0;i<coordinates.size();i++) { if((coordinates[i][1]-m*coordinates[i][0]-c)!=0) { return false; } } return true; } };
27.366667
103
0.437272
Ashwanigupta9125
4aa8745a2b7c89c60c1324304802ba09d928b697
9,330
cpp
C++
src/AC3DPlugins/bitmap_match.cpp
rromanchuk/xptools
deff017fecd406e24f60dfa6aae296a0b30bff56
[ "X11", "MIT" ]
71
2015-12-15T19:32:27.000Z
2022-02-25T04:46:01.000Z
src/AC3DPlugins/bitmap_match.cpp
rromanchuk/xptools
deff017fecd406e24f60dfa6aae296a0b30bff56
[ "X11", "MIT" ]
19
2016-07-09T19:08:15.000Z
2021-07-29T10:30:20.000Z
src/AC3DPlugins/bitmap_match.cpp
rromanchuk/xptools
deff017fecd406e24f60dfa6aae296a0b30bff56
[ "X11", "MIT" ]
42
2015-12-14T19:13:02.000Z
2022-03-01T15:15:03.000Z
/* * Copyright (c) 2007, Laminar Research. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #include "bitmap_match.h" #include "TclStubs.h" #include <ac_plugin.h> #include <stdio.h> #include <string.h> #ifndef IBM #include <stdint.h> #endif static unsigned char * get_image_data(ACImage * im); static unsigned char * get_image_data(ACImage * im) { int addr; if (!ac_entity_get_int_value(im, (char*)"data", &addr)) return NULL; uintptr_t a = (uintptr_t)addr; return (unsigned char *) a; } /* * bitmap_match * * Given two bitmaps, this routine returns true if sub is fully contained * within main, and sets h_offset and v_offset to the offsets within those * bitmaps. Sub and main must be of the same bit depth! * * The algorithm works by brute force...for each possible position of sub, * it attempts to check every pixel of sub against main. Surprisingly, this * algorithm executes very rapidly for 512x256 bitmaps on my P-IV, so I haven't * bothered to optimize it. (Authors will only be doing this every once in a * while anyway.) The early exit from a mismatch probably helps speed a lot. * * One possible optimization: use an adam7-like order of traversals of the pixels * in checking for a match. This would cause us to jump all around the bitmap, * finding mismatches faster even if the upper left local area corner is just * transparent or a solid color in both. * */ int bitmap_match( ACImage * sub, ACImage * main, int * h_offset, int * v_offset) { int main_width, main_height, main_depth; int sub_width, sub_height, sub_depth; ac_image_get_dim(main, &main_width, &main_height, &main_depth); ac_image_get_dim(sub, &sub_width, &sub_height, &sub_depth); char * subname, * mainname; ac_entity_get_string_value(sub, (char*)"name", &subname); ac_entity_get_string_value(main, (char*)"name", &mainname); if (sub_depth != main_depth) { if (sub_depth == 3 && main_depth == 4) message_dialog((char*)"Could not match bitmaps because bitmaps '%s' has alpha and '%s' does not.", mainname, subname); else if (sub_depth == 4 && main_depth == 3) message_dialog((char*)"Could not match bitmaps because bitmaps '%s' has alpha and '%s' does not.", subname, mainname); else message_dialog((char*)"Could not match bitmaps because bitmaps '%s' and '%s' have different color depths.", subname, mainname); return 0; } if (sub_width > main_width || sub_height > main_height) { message_dialog((char*)"Could not match bitmaps because new bitmap '%s' is smaller than old bitmap '%s'.", mainname, subname); return 0; } unsigned char * maind = get_image_data(main); unsigned char * subd = get_image_data(sub); for (int x_off = 0; x_off <= (main_width - sub_width); ++x_off) for (int y_off = 0; y_off <= (main_height - sub_height); ++y_off) { int match = 1; for (int x_pixel = 0; x_pixel < sub_width; ++x_pixel) for (int y_pixel = 0; y_pixel < sub_height; ++y_pixel) { unsigned char * mainp = maind + (x_off + x_pixel) * main_depth + (y_off + y_pixel) * main_depth * main_width; unsigned char * subp = subd + (x_pixel) * sub_depth + (y_pixel) * sub_depth * sub_width; for (int c = 0; c < sub_depth; ++c) if (subp[c] != mainp[c]) { match = 0; goto nomatch; } } *h_offset = x_off; *v_offset = y_off; return 1; nomatch: match = 0; } return 0; } /* * apply_lighting * * Given a day and night overlay bitmap, this routine adds the night overlay * to the day bitmap (they must be the same size), and reduces the day's * brightness too, to simulate x-plane night lighting. * */ int apply_lighting( ACImage * day, ACImage * night) { int day_width, day_height, day_depth; int night_width, night_height, night_depth; ac_image_get_dim(day, &day_width, &day_height, &day_depth); ac_image_get_dim(night, &night_width, &night_height, &night_depth); if (day_width != night_width) return 0; if (day_height != night_height) return 0; if (day_depth != 3 && day_depth != 4) return 0; if (night_depth != 3 && night_depth != 4) return 0; void * new_mem = myalloc(day_width * day_height * day_depth); unsigned char * dayd = get_image_data(day); unsigned char * nightd = get_image_data(night); unsigned char * destd = (unsigned char *) new_mem; int channels = (night_depth > day_depth) ? day_depth : night_depth; int x, y, c; for (y = 0; y < day_height; ++y) for (x = 0; x < day_width; ++x) { unsigned char * dayp = dayd + x * day_depth + y * day_depth * day_width; unsigned char * nightp = nightd + x * night_depth + y * night_depth * night_width; unsigned char * destp = destd + x * day_depth + y * day_depth * day_width; for (c = 0; c < channels; ++c) { unsigned long v = (dayp[c] >> 6) + nightp[c]; if (v > 255) v = 255; destp[c] = v; } if (channels == 3 && day_depth == 4) { destp[c] = dayp[c]; } } ac_image_set_data(day, destd); texture_build_for_all_windows(day); redraw_all(); return 1; } /* * Given a non-alpha-channel 24 bit image, this routine converts it to a 32-bit * ARGB image and makes pure magenta (FF00FF) pixels transparent, allowing users * to preview transparency for BMP textured objects. * * WARNING: this routine does not properly implement color smearing near magenta * pixels, so there may be artifacts around transparent areas. Frankly this is * acceptable, it's just a preview, and authors should be working with PNG anyway. * */ int make_transparent(ACImage * im) { int im_width, im_height, im_depth; ac_image_get_dim(im, &im_width, &im_height, &im_depth); if (im_depth != 3) { message_dialog((char*)"Bitmap already has an alpha channel."); printf("Image is not depth 3.\n"); return 0; } void * new_mem = myalloc(im_width * im_height * 4); unsigned char * srcd = get_image_data(im); unsigned char * dstd = (unsigned char *) new_mem; int transparent = 0; for (int y = 0; y < im_height; ++y) for (int x = 0; x < im_width; ++ x) { unsigned char * srcp = srcd + x * 3 + y * im_width * 3; unsigned char * dstp = dstd + x * 4 + y * im_width * 4; if (srcp[0] == 255 && srcp[1] == 0 && srcp[2] == 255) { ++transparent; dstp[0] = dstp[1] = dstp[2] = dstp[3] = 0; } else { dstp[0] = srcp[0]; dstp[1] = srcp[1]; dstp[2] = srcp[2]; dstp[3] = 255; } } ac_image_set_alpha_mask(im, ALPHA_TRANSP); ac_image_set_dim(im, im_width, im_height, 4); ac_image_set_data(im, dstd); texture_build_for_all_windows(im); redraw_all(); if (transparent == 0) message_dialog((char*)"No magenta pixels were found."); printf("Rendered %d pixels transparent.\n", transparent); return 1; } void tex_reload(int tex_id) { char * fname = texture_id_to_name(tex_id); // int im_width, im_height, im_depth; texture_build_for_all_windows(texture_id_to_image(add_new_texture_reload(fname,fname))); redraw_all(); return; /* ACImage * old_image = texture_id_to_image(tex_id); ACImage * new_image = new_acimage(fname); if (new_image == NULL) { message_dialog("Error: could not load %s.\n", fname); return; } ac_image_get_dim(new_image, &im_width, &im_height, &im_depth); ac_image_set_dim(old_image, im_width, im_height, im_depth); void * new_mem = myalloc(im_width * im_height * im_depth); memcpy(new_mem, get_image_data(new_image), im_width * im_height * im_depth); ac_image_set_data(old_image, (unsigned char *) new_mem); free_acimage(new_image); texture_build_for_all_windows(old_image); redraw_all(); */ } void bitmap_subcopy( ACImage * src, ACImage * dst, int l, int b, int r, int t) { int im_width, im_height, im_depth; ac_image_get_dim(src, &im_width, &im_height, &im_depth); void * new_mem = myalloc((r-l) * (t-b) * im_depth); unsigned char * srcd = get_image_data(src); unsigned char * dstd = (unsigned char *) new_mem; for (int y = b; y < t; ++y) for (int x = l; x < r; ++ x) { unsigned char * srcp = srcd + x * im_depth + y * im_width * im_depth; unsigned char * dstp = dstd + (x-l) * im_depth + (y-b) * (r-l) * im_depth; int c = im_depth; while(c--) *dstp++ = *srcp++; } ac_image_set_dim(dst, r-l, t-b, im_depth); ac_image_set_data(dst, dstd); texture_build_for_all_windows(dst); redraw_all(); }
29.15625
130
0.683494
rromanchuk
4aa91532c457db25d1a06407abdc49d7ccd9ca26
7,009
cxx
C++
main/winaccessibility/source/service/AccDescendantManagerEventListener.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/winaccessibility/source/service/AccDescendantManagerEventListener.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/winaccessibility/source/service/AccDescendantManagerEventListener.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 <com/sun/star/accessibility/XAccessible.hpp> #include <com/sun/star/accessibility/AccessibleStateType.hpp> #include <com/sun/star/accessibility/AccessibleEventId.hpp> #include <com/sun/star/accessibility/AccessibleRole.hpp> #include <com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp> #include "AccDescendantManagerEventListener.hxx" #include "AccObjectManagerAgent.hxx" #include "unomsaaevent.hxx" using namespace com::sun::star::uno; using namespace com::sun::star::accessibility; AccDescendantManagerEventListener::AccDescendantManagerEventListener(com::sun::star::accessibility::XAccessible* pAcc, AccObjectManagerAgent* Agent) :AccComponentEventListener(pAcc, Agent), pActiveDescendant(NULL) { } AccDescendantManagerEventListener::~AccDescendantManagerEventListener() { } /** * Uno's event notifier when event is captured * @param AccessibleEventObject the event object which contains information about event */ void AccDescendantManagerEventListener::notifyEvent( const ::com::sun::star::accessibility::AccessibleEventObject& aEvent ) throw (::com::sun::star::uno::RuntimeException) { switch (aEvent.EventId) { case AccessibleEventId::SELECTION_CHANGED: handleSelectionChangedEvent(aEvent.OldValue, aEvent.NewValue); break; case AccessibleEventId::CHILD: handleChildChangedEvent(aEvent.OldValue, aEvent.NewValue); break; case AccessibleEventId::ACTIVE_DESCENDANT_CHANGED_NOFOCUS: handleChildChangedNoFocusEvent(aEvent.OldValue, aEvent.NewValue); break; case AccessibleEventId::SELECTION_CHANGED_ADD: handleSelectionChangedAddEvent(aEvent.OldValue, aEvent.NewValue); break; case AccessibleEventId::SELECTION_CHANGED_REMOVE: handleSelectionChangedRemoveEvent(aEvent.OldValue, aEvent.NewValue); break; case AccessibleEventId::SELECTION_CHANGED_WITHIN: handleSelectionChangedWithinEvent(aEvent.OldValue, aEvent.NewValue); break; default: AccComponentEventListener::notifyEvent(aEvent); break; } } /** * handle the CHILD event * @param oldValue the child to be deleted * @param newValue the child to be added */ void AccDescendantManagerEventListener::handleChildChangedEvent(Any oldValue, Any newValue) { Reference< XAccessible > xChild; if( newValue >>= xChild) { //create a new child if(xChild.is()) { XAccessible* pAcc = xChild.get(); pAgent->InsertAccObj( pAcc,pAccessible); pAgent->InsertChildrenAccObj(pAcc); pAgent->NotifyAccEvent(UM_EVENT_CHILD_ADDED, pAcc); } else {} } if (oldValue >>= xChild) { if(xChild.is()) { XAccessible* pAcc = xChild.get(); pAgent->NotifyAccEvent(UM_EVENT_CHILD_REMOVED, pAcc); pAgent->DeleteChildrenAccObj( pAcc ); pAgent->DeleteAccObj( pAcc ); } else {} } } /** * handle the SELECTION_CHANGED event */ void AccDescendantManagerEventListener::handleSelectionChangedEvent(Any oldValue, Any newValue) { bool bSend =false; Reference< XAccessible > xChild; if(newValue >>= xChild ) { if(xChild.is()) { XAccessible* pAcc = xChild.get(); //if the Role is the SC cell ,don't add the selected state. if (pAgent->GetRole(pAcc) != AccessibleRole::TABLE_CELL) { pAgent->IncreaseState( pAcc, AccessibleStateType::SELECTED); } pAgent->NotifyAccEvent(UM_EVENT_SELECTION_CHANGED, pAcc); bSend=true; } } if(oldValue >>= xChild ) { if(xChild.is()) { XAccessible* pAcc = xChild.get(); pAgent->DecreaseState( pAcc, AccessibleStateType::SELECTED); } } if (!bSend) { pAgent->NotifyAccEvent(UM_EVENT_SELECTION_CHANGED, pAccessible); } } void AccDescendantManagerEventListener::handleChildChangedNoFocusEvent(Any oldValue, Any newValue) { Reference< XAccessible > xChild; if(newValue >>= xChild ) { if(xChild.is()) { XAccessible* pAcc = xChild.get(); pAgent->InsertAccObj(pAcc,pAccessible); pAgent->InsertChildrenAccObj(pAcc); pActiveDescendant= pAcc; } } if (oldValue >>= xChild) { if(xChild.is()) { XAccessible* pAcc = xChild.get(); pAgent->DeleteChildrenAccObj( pAcc ); pAgent->DeleteAccObj( pAcc ); } } } bool AccDescendantManagerEventListener::NotifyChildEvent(short nWinEvent,const Any &Value) { Reference< XAccessible > xChild; if(Value >>= xChild ) { if(xChild.is()) { XAccessible* pAcc = xChild.get(); pAgent->NotifyAccEvent(nWinEvent, pAcc); if (pAgent && pAgent->IsStateManageDescendant(pAccessible) && ( nWinEvent == UM_EVENT_SELECTION_CHANGED_REMOVE) ) { pAgent->DeleteAccObj( pAcc ); } return true; } } return false; } void AccDescendantManagerEventListener::handleSelectionChangedAddEvent(const Any& /*oldValue*/, const Any &newValue) { if(NotifyChildEvent(UM_EVENT_SELECTION_CHANGED_ADD,newValue)) { return ; } pAgent->NotifyAccEvent(UM_EVENT_SELECTION_CHANGED_ADD,pAccessible); } void AccDescendantManagerEventListener::handleSelectionChangedRemoveEvent(const Any& /*oldValue*/, const Any &newValue) { if(NotifyChildEvent(UM_EVENT_SELECTION_CHANGED_REMOVE,newValue)) { return ; } pAgent->NotifyAccEvent(UM_EVENT_SELECTION_CHANGED_REMOVE,pAccessible); } void AccDescendantManagerEventListener::handleSelectionChangedWithinEvent(const Any& /*oldValue*/, const Any &newValue) { if(NotifyChildEvent(UM_EVENT_SELECTION_CHANGED_WITHIN,newValue)) { return ; } pAgent->NotifyAccEvent(UM_EVENT_SELECTION_CHANGED_WITHIN,pAccessible); }
30.876652
148
0.663718
Grosskopf
4aabe2ae756f12be5329773dd33dc68f447edc55
5,019
cc
C++
src/lib/JANA/JParameterManager.cc
mayank185T9/JANA
58bc4c3dadde185a6bbfd83fe21f9c51df941ce5
[ "Apache-2.0" ]
null
null
null
src/lib/JANA/JParameterManager.cc
mayank185T9/JANA
58bc4c3dadde185a6bbfd83fe21f9c51df941ce5
[ "Apache-2.0" ]
2
2018-04-12T11:25:48.000Z
2019-04-17T12:59:29.000Z
src/lib/JANA/JParameterManager.cc
mayank185T9/JANA
58bc4c3dadde185a6bbfd83fe21f9c51df941ce5
[ "Apache-2.0" ]
2
2018-01-16T14:41:04.000Z
2019-03-26T17:43:19.000Z
// // File: JParameterManager.cc // Created: Thu Oct 12 08:16:11 EDT 2017 // Creator: davidl (on Darwin harriet.jlab.org 15.6.0 i386) // // ------ Last repository commit info ----- // [ Date ] // [ Author ] // [ Source ] // [ Revision ] // //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Jefferson Science Associates LLC Copyright Notice: // Copyright 251 2014 Jefferson Science Associates LLC All Rights Reserved. Redistribution // and use in source and binary forms, with or without modification, are permitted as a // licensed user provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this // list of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // 3. The name of the author may not be used to endorse or promote products derived // from this software without specific prior written permission. // This material resulted from work developed under a United States Government Contract. // The Government retains a paid-up, nonexclusive, irrevocable worldwide license in such // copyrighted data to reproduce, distribute copies to the public, prepare derivative works, // perform publicly and display publicly and to permit others to do so. // THIS SOFTWARE IS PROVIDED BY JEFFERSON SCIENCE ASSOCIATES LLC "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 // JEFFERSON SCIENCE ASSOCIATES, LLC OR THE U.S. GOVERNMENT BE LIABLE TO LICENSEE OR ANY // THIRD PARTES 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 "JParameterManager.h" #include "JLogger.h" using namespace std; //--------------------------------- // JParameterManager (Constructor) //--------------------------------- JParameterManager::JParameterManager() { } //--------------------------------- // ~JParameterManager (Destructor) //--------------------------------- JParameterManager::~JParameterManager() { for( auto p : _jparameters ) delete p.second; _jparameters.clear(); } //--------------------------------- // Exists //--------------------------------- bool JParameterManager::Exists(string name) { return _jparameters.count( ToLC(name) ) != 0; } //--------------------------------- // FindParameter //--------------------------------- JParameter* JParameterManager::FindParameter(std::string name) { if( ! Exists(name) ) return nullptr; return _jparameters[ ToLC(name) ]; } //--------------------------------- // PrintParameters //--------------------------------- void JParameterManager::PrintParameters(bool all) { /// Print configuration parameters to stdout. /// If "all" is false (default) then only parameters /// whose values are different than their default are /// printed. /// If "all" is true then all parameters are /// printed. // Find maximum key length uint32_t max_key_len = 4; vector<string> keys; for(auto &p : _jparameters){ string key = p.first; auto j = p.second; if( (!all) && j->IsDefault() ) continue; keys.push_back( key ); if( key.length()>max_key_len ) max_key_len = key.length(); } // If all params are set to default values, then print a one line // summary if(keys.empty()){ JLog() << "All configuration parameters set to default values." << JLogEnd(); return; } // Print title/header string title("Config. Parameters"); uint32_t half_title_len = 1+title.length()/2; if( max_key_len < half_title_len ) max_key_len = half_title_len; JLog() << "\n" << JLogEnd(); JLog() << string(max_key_len+4-half_title_len, ' ') << title << "\n" << JLogEnd(); JLog() << " " << string(2*max_key_len + 3, '=') << "\n" << JLogEnd(); JLog() << string(max_key_len/2, ' ') << "name" << string(max_key_len, ' ') << "value" << "\n" << JLogEnd(); JLog() << " " << string(max_key_len, '-') << " " << string(max_key_len, '-') << "\n" << JLogEnd(); // Print all parameters for(string &key : keys){ auto name = _jparameters[key]->GetName(); string val = _jparameters[key]->GetValue<string>(); JLog() << string(max_key_len+2-key.length(),' ') << name << " = " << val << "\n" << JLogEnd(); } JLog() << "\n" << JLogEnd(); }
39.210938
108
0.625423
mayank185T9
4ab070033060eed49e14d5fa2bbbd3579b63ed98
709
cpp
C++
luogu/1068.cpp
shorn1/OI-ICPC-Problems
0c18b3297190a0e108c311c74d28351ebc70c3d1
[ "MIT" ]
1
2020-05-07T09:26:05.000Z
2020-05-07T09:26:05.000Z
luogu/1068.cpp
shorn1/OI-ICPC-Problems
0c18b3297190a0e108c311c74d28351ebc70c3d1
[ "MIT" ]
null
null
null
luogu/1068.cpp
shorn1/OI-ICPC-Problems
0c18b3297190a0e108c311c74d28351ebc70c3d1
[ "MIT" ]
null
null
null
#include<cmath> #include<cctype> #include<cstdio> #include<cstdlib> #include<cstring> #include<iostream> #include<algorithm> #define ns namespace #define lol long long using ns std; int n,m; struct Std { int k,s; bool operator < (const Std &x) const { return s == x.s ? k < x.k : s > x.s; } }a[23333]; int main(int argc,char** argv) { cin >> n >> m; for(int i = 1;i <= n;i++) { scanf("%d%d",&a[i].k,&a[i].s); } sort(a+1,a+1+n); int t = static_cast<int>(1.5 * static_cast<double>(m)); while(a[t].s == a[t+1].s) ++t; printf("%d %d\n",a[t].s,t); for(int i = 1;i <= t;i++) { printf("%d %d\n",a[i].k,a[i].s); } return 0; }
17.725
59
0.513399
shorn1
4ab2887f7b92ea9ed4e9b11b726f73c0d1f86686
15,466
hpp
C++
renv/library/R-4.1/x86_64-w64-mingw32/TMB/include/cppad/local/checkpoint.hpp
rebeccagb/gtsummary
04996e385acab0b76a9938378e8af87526117aef
[ "MIT" ]
null
null
null
renv/library/R-4.1/x86_64-w64-mingw32/TMB/include/cppad/local/checkpoint.hpp
rebeccagb/gtsummary
04996e385acab0b76a9938378e8af87526117aef
[ "MIT" ]
null
null
null
renv/library/R-4.1/x86_64-w64-mingw32/TMB/include/cppad/local/checkpoint.hpp
rebeccagb/gtsummary
04996e385acab0b76a9938378e8af87526117aef
[ "MIT" ]
null
null
null
/* $Id$ */ # ifndef CPPAD_CHECKPOINT_INCLUDED # define CPPAD_CHECKPOINT_INCLUDED /* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-15 Bradley M. Bell CppAD is distributed under multiple licenses. This distribution is under the terms of the GNU General Public License Version 3. A copy of this license is included in the COPYING file of this distribution. Please visit http://www.coin-or.org/CppAD/ for information on other licenses. -------------------------------------------------------------------------- */ namespace CppAD { // BEGIN_CPPAD_NAMESPACE /*! \file checkpoint.hpp defining checkpoint functions. */ /* $begin checkpoint$$ $spell cppad.hpp CppAD checkpoint checkpointing algo afun const $$ $section Checkpointing Functions$$ $index function, checkpoint$$ $index checkpoint, function$$ $head Syntax$$ $codei%checkpoint<%Base%> %afun%(%name%, %algo%, %ax%, %ay%) %afun%.option(%option_value%) %algo%(%ax%, %ay%) %afun%(%ax%, %ay%) checkpoint<%Base%>::clear()%$$ $head Purpose$$ You can reduce the size of the tape and memory required for AD by checkpointing functions of the form $latex y = f(x)$$ where $latex f : B^n \rightarrow B^m$$. $head Method$$ The $code checkpoint$$ class is derived from $code atomic_base$$ and makes this easy. It implements all the $code atomic_base$$ $cref/virtual functions/atomic_base/Virtual Functions/$$ and hence its source code $code cppad/local/checkpoint.hpp$$ provides an example implementation of $cref atomic_base$$. The difference is that $code checkpoint.hpp$$ uses AD instead of user provided derivatives. $head constructor$$ The constructor $codei% checkpoint<%Base%> %afun%(%name%, %algo%, %ax%, %ay%) %$$ cannot be called in $cref/parallel/ta_in_parallel/$$ mode. In addition, you cannot currently be recording $codei%AD<%Base%>%$$ operations when the constructor is called. This class is implemented as a derived class of $cref/atomic_base/atomic_ctor/atomic_base/$$ and hence some of its error message will refer to $code atomic_base$$. $head Base$$ The type $icode Base$$ specifies the base type for AD operations. $head ADVector$$ The type $icode ADVector$$ must be a $cref/simple vector class/SimpleVector/$$ with elements of type $codei%AD<%Base%>%$$. $head name$$ This $icode checkpoint$$ constructor argument has prototype $codei% const char* %name% %$$ It is the name used for error reporting. The suggested value for $icode name$$ is $icode afun$$; i.e., the same name as used for the function. $head ax$$ This argument has prototype $codei% const %ADVector%& %ax% %$$ and size must be equal to $icode n$$. It specifies vector $latex x \in B^n$$ at which an $codei%AD<%Base%>%$$ version of $latex y = f(x)$$ is to be evaluated. $head ay$$ This argument has prototype $codei% %ADVector%& %ay% %$$ Its input size must be equal to $icode m$$ and does not change. The input values of its elements do not matter. Upon return, it is an $codei%AD<%Base%>%$$ version of $latex y = f(x)$$. $head option$$ The $code option$$ syntax can be used to set the type of sparsity pattern used by $icode afun$$. This is an $codei%atomic_base<%Base%>%$$ function and its documentation can be found at $cref atomic_option$$. $head algo$$ The type of $icode algo$$ is arbitrary, except for the fact that the syntax $codei% %algo%(%ax%, %ay%) %$$ must evaluate the function $latex y = f(x)$$ using $codei%AD<%Base%>%$$ operations. In addition, we assume that the $cref/operation sequence/glossary/Operation/Sequence/$$ does not depend on the value of $icode ax$$. $head afun$$ Given $icode ax$$ it computes the corresponding value of $icode ay$$ using the operation sequence corresponding to $icode algo$$. If $codei%AD<%Base%>%$$ operations are being recorded, it enters the computation as single operation in the recording see $cref/start recording/Independent/Start Recording/$$. (Currently each use of $icode afun$$ actually corresponds to $icode%m%+%n%+2%$$ operations and creates $icode m$$ new variables, but this is not part of the CppAD specifications and my change.) $head clear$$ The $code atomic_base$$ class holds onto static work space in order to increase speed by avoiding system memory allocation calls. This call makes to work space $cref/available/ta_available/$$ to for other uses by the same thread. This should be called when you are done using the user atomic functions for a specific value of $icode Base$$. $subhead Restriction$$ The $code clear$$ routine cannot be called while in $cref/parallel/ta_in_parallel/$$ execution mode. $children% example/atomic/checkpoint.cpp %$$ $head Example$$ The file $cref checkpoint.cpp$$ contains an example and test of these operations. It returns true if it succeeds and false if it fails. $end */ template <class Base> class checkpoint : public atomic_base<Base> { private: vector<ADFun<Base> > f_; public: /*! Constructor of a checkpoint object \param name [in] is the user's name for the AD version of this atomic operation. \param algo [in/out] user routine that compute AD function values (not const because state may change during evaluation). \param ax [in] argument value where algo operation sequence is taped. \param ay [out] function value at specified argument value. */ template <class Algo, class ADVector> checkpoint(const char* name, Algo& algo, const ADVector& ax, ADVector& ay) : atomic_base<Base>(name) { CheckSimpleVector< CppAD::AD<Base> , ADVector>(); #ifdef _OPENMP #define NTHREADS omp_get_max_threads() #define THREAD omp_get_thread_num() #else #define NTHREADS 1 #define THREAD 0 #endif f_.resize(NTHREADS); // make a copy of ax because Independent modifies AD information ADVector x_tmp(ax); // delcare x_tmp as the independent variables Independent(x_tmp); // record mapping from x_tmp to ay algo(x_tmp, ay); // create function f_ : x -> y f_[0].Dependent(ay); // suppress checking for nan in f_ results // (see optimize documentation for atomic functions) f_[0].check_for_nan(false); // now optimize (we expect to use this function many times). f_[0].optimize(); // Copy for other threads for(size_t i=1;i<NTHREADS;i++)f_[i]=f_[0]; // now disable checking of comparison opertaions // 2DO: add a debugging mode that checks for changes and aborts f_[0].compare_change_count(0); } /*! Implement the user call to <tt>afun(ax, ay)</tt>. \tparam ADVector A simple vector class with elements of type <code>AD<Base></code>. \param id optional parameter which must be zero if present. \param ax is the argument vector for this call, <tt>ax.size()</tt> determines the number of arguments. \param ay is the result vector for this call, <tt>ay.size()</tt> determines the number of results. */ template <class ADVector> void operator()(const ADVector& ax, ADVector& ay, size_t id = 0) { CPPAD_ASSERT_KNOWN( id == 0, "checkpoint: id is non-zero in afun(ax, ay, id)" ); this->atomic_base<Base>::operator()(ax, ay, id); } /*! Link from user_atomic to forward mode \copydetails atomic_base::forward */ virtual bool forward( size_t p , size_t q , const vector<bool>& vx , vector<bool>& vy , const vector<Base>& tx , vector<Base>& ty ) { CPPAD_ASSERT_UNKNOWN( f_[THREAD].size_var() > 0 ); CPPAD_ASSERT_UNKNOWN( tx.size() % (q+1) == 0 ); CPPAD_ASSERT_UNKNOWN( ty.size() % (q+1) == 0 ); size_t n = tx.size() / (q+1); size_t m = ty.size() / (q+1); bool ok = true; size_t i, j; // 2DO: test both forward and reverse vy information if( vx.size() > 0 ) { //Compute Jacobian sparsity pattern. vector< std::set<size_t> > s(m); if( n <= m ) { vector< std::set<size_t> > r(n); for(j = 0; j < n; j++) r[j].insert(j); s = f_[THREAD].ForSparseJac(n, r); } else { vector< std::set<size_t> > r(m); for(i = 0; i < m; i++) r[i].insert(i); s = f_[THREAD].RevSparseJac(m, r); } std::set<size_t>::const_iterator itr; for(i = 0; i < m; i++) { vy[i] = false; for(itr = s[i].begin(); itr != s[i].end(); itr++) { j = *itr; assert( j < n ); // y[i] depends on the value of x[j] vy[i] |= vx[j]; } } } ty = f_.Forward(q, tx); // no longer need the Taylor coefficients in f_ // (have to reconstruct them every time) size_t c = 0; size_t r = 0; f_.capacity_order(c, r); return ok; } /*! Link from user_atomic to reverse mode \copydetails atomic_base::reverse */ virtual bool reverse( size_t q , const vector<Base>& tx , const vector<Base>& ty , vector<Base>& px , const vector<Base>& py ) { CPPAD_ASSERT_UNKNOWN( f_[THREAD].size_var() > 0 ); CPPAD_ASSERT_UNKNOWN( tx.size() % (q+1) == 0 ); CPPAD_ASSERT_UNKNOWN( ty.size() % (q+1) == 0 ); bool ok = true; // put proper forward mode coefficients in f_ # ifdef NDEBUG f_[THREAD].Forward(q, tx); # else size_t n = tx.size() / (q+1); size_t m = ty.size() / (q+1); CPPAD_ASSERT_UNKNOWN( px.size() == n * (q+1) ); CPPAD_ASSERT_UNKNOWN( py.size() == m * (q+1) ); size_t i, j, k; // vector<Base> check_ty = f_[THREAD].Forward(q, tx); for(i = 0; i < m; i++) { for(k = 0; k <= q; k++) { j = i * (q+1) + k; CPPAD_ASSERT_UNKNOWN( check_ty[j] == ty[j] ); } } # endif // now can run reverse mode px = f_[THREAD].Reverse(q+1, py); // no longer need the Taylor coefficients in f_ // (have to reconstruct them every time) size_t c = 0; size_t r = 0; f_[THREAD].capacity_order(c, r); return ok; } /*! Link from user_atomic to forward sparse Jacobian \copydetails atomic_base::for_sparse_jac */ virtual bool for_sparse_jac( size_t q , const vector< std::set<size_t> >& r , vector< std::set<size_t> >& s ) { bool ok = true; s = f_[THREAD].ForSparseJac(q, r); // no longer need the forward mode sparsity pattern // (have to reconstruct them every time) f_[THREAD].size_forward_set(0); return ok; } /*! Link from user_atomic to forward sparse Jacobian \copydetails atomic_base::for_sparse_jac */ virtual bool for_sparse_jac( size_t q , const vector<bool>& r , vector<bool>& s ) { bool ok = true; s = f_[THREAD].ForSparseJac(q, r); // no longer need the forward mode sparsity pattern // (have to reconstruct them every time) f_[THREAD].size_forward_bool(0); return ok; } /*! Link from user_atomic to forward sparse Jacobian \copydetails atomic_base::rev_sparse_jac */ virtual bool rev_sparse_jac( size_t q , const vector< std::set<size_t> >& rt , vector< std::set<size_t> >& st ) { bool ok = true; // compute rt // 2DO: remove need for nz_compare all the time. It is only really // necessary when optimizer calls this member function. bool transpose = true; bool nz_compare = true; st = f_[THREAD].RevSparseJac(q, rt, transpose, nz_compare); return ok; } /*! Link from user_atomic to forward sparse Jacobian \copydetails atomic_base::rev_sparse_jac */ virtual bool rev_sparse_jac( size_t q , const vector<bool>& rt , vector<bool>& st ) { bool ok = true; // compute rt bool transpose = true; bool nz_compare = true; // 2DO: remove need for nz_compare all the time. It is only really // necessary when optimizer calls this member function. st = f_[THREAD].RevSparseJac(q, rt, transpose, nz_compare); return ok; } /*! Link from user_atomic to forward sparse Jacobian \copydetails atomic_base::rev_sparse_hes */ virtual bool rev_sparse_hes( const vector<bool>& vx , const vector<bool>& s , vector<bool>& t , size_t q , const vector< std::set<size_t> >& r , const vector< std::set<size_t> >& u , vector< std::set<size_t> >& v ) { size_t n = v.size(); size_t m = u.size(); CPPAD_ASSERT_UNKNOWN( r.size() == v.size() ); CPPAD_ASSERT_UNKNOWN( s.size() == m ); CPPAD_ASSERT_UNKNOWN( t.size() == n ); bool ok = true; bool transpose = true; std::set<size_t>::const_iterator itr; // compute sparsity pattern for T(x) = S(x) * f'(x) t = f_[THREAD].RevSparseJac(1, s); # ifndef NDEBUG for(size_t j = 0; j < n; j++) CPPAD_ASSERT_UNKNOWN( vx[j] || ! t[j] ) # endif // V(x) = f'(x)^T * g''(y) * f'(x) * R + g'(y) * f''(x) * R // U(x) = g''(y) * f'(x) * R // S(x) = g'(y) // compute sparsity pattern for A(x) = f'(x)^T * U(x) vector< std::set<size_t> > a(n); a = f_[THREAD].RevSparseJac(q, u, transpose); // set version of s vector< std::set<size_t> > set_s(1); CPPAD_ASSERT_UNKNOWN( set_s[0].empty() ); size_t i; for(i = 0; i < m; i++) if( s[i] ) set_s[0].insert(i); // compute sparsity pattern for H(x) = (S(x) * F)''(x) * R // (store it in v) f_[THREAD].ForSparseJac(q, r); v = f_[THREAD].RevSparseHes(q, set_s, transpose); // compute sparsity pattern for V(x) = A(x) + H(x) for(i = 0; i < n; i++) { for(itr = a[i].begin(); itr != a[i].end(); itr++) { size_t j = *itr; CPPAD_ASSERT_UNKNOWN( j < q ); v[i].insert(j); } } // no longer need the forward mode sparsity pattern // (have to reconstruct them every time) f_[THREAD].size_forward_set(0); return ok; } /*! Link from user_atomic to forward sparse Jacobian \copydetails atomic_base::rev_sparse_hes */ virtual bool rev_sparse_hes( const vector<bool>& vx , const vector<bool>& s , vector<bool>& t , size_t q , const vector<bool>& r , const vector<bool>& u , vector<bool>& v ) { CPPAD_ASSERT_UNKNOWN( r.size() == v.size() ); CPPAD_ASSERT_UNKNOWN( s.size() == u.size() / q ); CPPAD_ASSERT_UNKNOWN( t.size() == v.size() / q ); size_t n = t.size(); bool ok = true; bool transpose = true; std::set<size_t>::const_iterator itr; size_t i, j; // compute sparsity pattern for T(x) = S(x) * f'(x) t = f_[THREAD].RevSparseJac(1, s); # ifndef NDEBUG for(j = 0; j < n; j++) CPPAD_ASSERT_UNKNOWN( vx[j] || ! t[j] ) # endif // V(x) = f'(x)^T * g''(y) * f'(x) * R + g'(y) * f''(x) * R // U(x) = g''(y) * f'(x) * R // S(x) = g'(y) // compute sparsity pattern for A(x) = f'(x)^T * U(x) vector<bool> a(n * q); a = f_[THREAD].RevSparseJac(q, u, transpose); // compute sparsity pattern for H(x) =(S(x) * F)''(x) * R // (store it in v) f_[THREAD].ForSparseJac(q, r); v = f_[THREAD].RevSparseHes(q, s, transpose); // compute sparsity pattern for V(x) = A(x) + H(x) for(i = 0; i < n; i++) { for(j = 0; j < q; j++) v[ i * q + j ] |= a[ i * q + j]; } // no longer need the forward mode sparsity pattern // (have to reconstruct them every time) f_[THREAD].size_forward_set(0); return ok; } }; } // END_CPPAD_NAMESPACE # endif #undef NTHREADS #undef THREAD
28.274223
77
0.622074
rebeccagb
4ab58751c7c9495aabe61ad57ed348fa5ac4d0dc
3,524
cpp
C++
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgWrappers/osg/Timer.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
3
2018-08-20T12:12:43.000Z
2021-06-06T09:43:27.000Z
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgWrappers/osg/Timer.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
null
null
null
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgWrappers/osg/Timer.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
1
2022-03-31T03:12:23.000Z
2022-03-31T03:12:23.000Z
// *************************************************************************** // // Generated automatically by genwrapper. // Please DO NOT EDIT this file! // // *************************************************************************** #include <osgIntrospection/ReflectionMacros> #include <osgIntrospection/TypedMethodInfo> #include <osgIntrospection/StaticMethodInfo> #include <osgIntrospection/Attributes> #include <osg/Timer> // Must undefine IN and OUT macros defined in Windows headers #ifdef IN #undef IN #endif #ifdef OUT #undef OUT #endif BEGIN_VALUE_REFLECTOR(osg::Timer) I_DeclaringFile("osg/Timer"); I_Constructor0(____Timer, "", ""); I_Method0(osg::Timer_t, tick, Properties::NON_VIRTUAL, __Timer_t__tick, "Get the timers tick value. ", ""); I_Method0(void, setStartTick, Properties::NON_VIRTUAL, __void__setStartTick, "Set the start. ", ""); I_Method1(void, setStartTick, IN, osg::Timer_t, t, Properties::NON_VIRTUAL, __void__setStartTick__Timer_t, "", ""); I_Method0(osg::Timer_t, getStartTick, Properties::NON_VIRTUAL, __Timer_t__getStartTick, "", ""); I_Method0(double, time_s, Properties::NON_VIRTUAL, __double__time_s, "Get elapsed time in seconds. ", ""); I_Method0(double, time_m, Properties::NON_VIRTUAL, __double__time_m, "Get elapsed time in milliseconds. ", ""); I_Method0(double, time_u, Properties::NON_VIRTUAL, __double__time_u, "Get elapsed time in micoseconds. ", ""); I_Method0(double, time_n, Properties::NON_VIRTUAL, __double__time_n, "Get elapsed time in nanoseconds. ", ""); I_Method2(double, delta_s, IN, osg::Timer_t, t1, IN, osg::Timer_t, t2, Properties::NON_VIRTUAL, __double__delta_s__Timer_t__Timer_t, "Get the time in seconds between timer ticks t1 and t2. ", ""); I_Method2(double, delta_m, IN, osg::Timer_t, t1, IN, osg::Timer_t, t2, Properties::NON_VIRTUAL, __double__delta_m__Timer_t__Timer_t, "Get the time in milliseconds between timer ticks t1 and t2. ", ""); I_Method2(double, delta_u, IN, osg::Timer_t, t1, IN, osg::Timer_t, t2, Properties::NON_VIRTUAL, __double__delta_u__Timer_t__Timer_t, "Get the time in microseconds between timer ticks t1 and t2. ", ""); I_Method2(double, delta_n, IN, osg::Timer_t, t1, IN, osg::Timer_t, t2, Properties::NON_VIRTUAL, __double__delta_n__Timer_t__Timer_t, "Get the time in nanoseconds between timer ticks t1 and t2. ", ""); I_Method0(double, getSecondsPerTick, Properties::NON_VIRTUAL, __double__getSecondsPerTick, "Get the the number of seconds per tick. ", ""); I_StaticMethod0(osg::Timer *, instance, __Timer_P1__instance_S, "", ""); I_SimpleProperty(double, SecondsPerTick, __double__getSecondsPerTick, 0); I_SimpleProperty(osg::Timer_t, StartTick, __Timer_t__getStartTick, __void__setStartTick__Timer_t); END_REFLECTOR TYPE_NAME_ALIAS(unsigned long long, osg::Timer_t)
32.934579
78
0.573496
UM-ARM-Lab
4ab8be4a4a3b4b2087557e8b5b73c95a756079eb
492
cpp
C++
fk/modules/scan_modules_worker.cpp
fieldkit/firmware
09df5c4c5c2f21865cfbb11c9cdc362bb8803ad6
[ "BSD-3-Clause" ]
10
2019-11-26T11:35:56.000Z
2021-07-03T07:21:38.000Z
fk/modules/scan_modules_worker.cpp
fieldkit/firmware
09df5c4c5c2f21865cfbb11c9cdc362bb8803ad6
[ "BSD-3-Clause" ]
1
2019-07-03T06:27:21.000Z
2019-09-06T09:21:27.000Z
fk/modules/scan_modules_worker.cpp
fieldkit/firmware
09df5c4c5c2f21865cfbb11c9cdc362bb8803ad6
[ "BSD-3-Clause" ]
1
2019-09-23T18:13:51.000Z
2019-09-23T18:13:51.000Z
#include "modules/scan_modules_worker.h" #include "modules/scanning.h" #include "state_manager.h" namespace fk { FK_DECLARE_LOGGER("modscan"); ScanModulesWorker::ScanModulesWorker() { } void ScanModulesWorker::run(Pool &pool) { auto lock = get_modmux()->lock(); state::DynamicState dynamic; if (dynamic.attached()->create(pool) < 0) { logerror("scanning"); } auto gs = get_global_state_rw(); gs.get()->dynamic = std::move(dynamic); } } // namespace fk
18.923077
47
0.672764
fieldkit
4ab9a92c3d210c6a8b428644c685ca82870ab003
1,154
cpp
C++
LeetCode/006-ZigZagConversion.cpp
BigEggStudy/LeetCode-CPP
5e56142ae65da1fa72c0f890c357c760d493f783
[ "MIT" ]
null
null
null
LeetCode/006-ZigZagConversion.cpp
BigEggStudy/LeetCode-CPP
5e56142ae65da1fa72c0f890c357c760d493f783
[ "MIT" ]
null
null
null
LeetCode/006-ZigZagConversion.cpp
BigEggStudy/LeetCode-CPP
5e56142ae65da1fa72c0f890c357c760d493f783
[ "MIT" ]
null
null
null
//----------------------------------------------------------------------------- // Runtime: 16ms // Memory Usage: // Link: //----------------------------------------------------------------------------- #include "stdafx.h" #include "006-ZigZagConversion.h" namespace LeetCode { _006_ZigZagConversion::_006_ZigZagConversion() { } _006_ZigZagConversion::~_006_ZigZagConversion() { } string _006_ZigZagConversion::convert(string s, int numRows) { if (numRows <= 1 || s.size() <= numRows) { return s; } string result; for (int i = 0; i < numRows; i++) { for (int j = 0, originalIndex = i; originalIndex < s.size(); j++, originalIndex = (numRows * 2 - 2) * j + i) { result.append(1, s[originalIndex]); if (i == 0 || i == numRows - 1) { continue; } originalIndex += (numRows * 2 - 2) - i * 2; if (originalIndex < s.size()) { result.append(1, s[originalIndex]); } } } return result; } }
25.086957
79
0.409879
BigEggStudy
3859acb39002f86f4b0bc47f1dea4e96007b3c07
9,827
cpp
C++
example_projects/controlls.cpp
mateuszstompor/ngin
2a1f864e2aaf1b3eee134f1d7cf126436d05145f
[ "MIT" ]
7
2018-03-28T18:04:25.000Z
2020-04-21T12:34:55.000Z
example_projects/controlls.cpp
mateuszstompor/ngin
2a1f864e2aaf1b3eee134f1d7cf126436d05145f
[ "MIT" ]
61
2018-03-01T20:16:49.000Z
2018-06-28T17:06:14.000Z
example_projects/controlls.cpp
mateuszstompor/ngin
2a1f864e2aaf1b3eee134f1d7cf126436d05145f
[ "MIT" ]
1
2018-04-07T17:09:51.000Z
2018-04-07T17:09:51.000Z
// // controlls.cpp // ngin_mac // // Created by Mateusz Stompór on 28/03/2018. // Copyright © 2018 Mateusz Stompór. All rights reserved. // #include "controlls.hpp" using namespace ms; using namespace math; using namespace transform; int usedSpotLight = 0; int usedPointLight = 0; void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods){ switch(key) { case GLFW_KEY_ESCAPE: glfwSetWindowShouldClose(window, true); break; case GLFW_KEY_Z: { auto rotation = ms::math::transform::rotate_about_y_radians<float, 4>(0.1f); engine->get_scene().get_camera().get_transformation() = rotation * engine->get_scene().get_camera().get_transformation(); } break; case GLFW_KEY_X: { auto rotation = ms::math::transform::rotate_about_y_radians<float, 4>(-0.1f); engine->get_scene().get_camera().get_transformation() = rotation * engine->get_scene().get_camera().get_transformation(); } break; case GLFW_KEY_C: { auto rotation = ms::math::transform::rotate_about_x_radians<float, 4>(0.1f); engine->get_scene().get_camera().get_transformation() = rotation * engine->get_scene().get_camera().get_transformation(); } break; case GLFW_KEY_V: { auto rotation = ms::math::transform::rotate_about_x_radians<float, 4>(-0.1f); engine->get_scene().get_camera().get_transformation() = rotation * engine->get_scene().get_camera().get_transformation(); } break; case GLFW_KEY_Q: { auto up = 0.2f * ms::math::up(engine->get_scene().get_camera().get_transformation()); auto transform = translate<float, 4>(up); engine->get_scene().get_camera().get_transformation() = engine->get_scene().get_camera().get_transformation() * transform; } break; case GLFW_KEY_E: { auto up = -0.2f * ms::math::up(engine->get_scene().get_camera().get_transformation()); auto transform = translate<float, 4>(up); engine->get_scene().get_camera().get_transformation() = engine->get_scene().get_camera().get_transformation() * transform; } break; case GLFW_KEY_A: { auto right = 0.2f * ms::math::right(engine->get_scene().get_camera().get_transformation()); auto transform = translate<float, 4>(right); engine->get_scene().get_camera().get_transformation() = engine->get_scene().get_camera().get_transformation() * transform; } break; case GLFW_KEY_D: { auto right = -0.2f * ms::math::right(engine->get_scene().get_camera().get_transformation()); auto transform = translate<float, 4>(right); engine->get_scene().get_camera().get_transformation() = engine->get_scene().get_camera().get_transformation() * transform; } break; case GLFW_KEY_W: { auto forward = 0.2f * ms::math::back(engine->get_scene().get_camera().get_transformation()); auto transform = translate<float, 4>(forward); engine->get_scene().get_camera().get_transformation() = engine->get_scene().get_camera().get_transformation() * transform; } break; case GLFW_KEY_S: { auto forward = -0.2f * ms::math::back(engine->get_scene().get_camera().get_transformation()); auto transform = translate<float, 4>(forward); engine->get_scene().get_camera().get_transformation() = engine->get_scene().get_camera().get_transformation() * transform; } break; case GLFW_KEY_T: { auto forward = 0.2f * ms::math::back(engine->get_scene().get_spot_lights()[usedSpotLight].get_transformation()); auto transform = translate<float, 4>(forward); engine->get_scene().get_spot_lights()[usedSpotLight].get_transformation() *= transform; } break; case GLFW_KEY_G: { auto forward = -0.2f * ms::math::back(engine->get_scene().get_spot_lights()[usedSpotLight].get_transformation()); auto transform = translate<float, 4>(forward); engine->get_scene().get_spot_lights()[usedSpotLight].get_transformation() *= transform; } break; case GLFW_KEY_R: { auto up = 0.2f * ms::math::up(engine->get_scene().get_spot_lights()[usedSpotLight].get_transformation()); auto transform = translate<float, 4>(up); engine->get_scene().get_spot_lights()[usedSpotLight].get_transformation() *= transform; } break; case GLFW_KEY_Y: { auto up = -0.2f * ms::math::up(engine->get_scene().get_spot_lights()[usedSpotLight].get_transformation()); auto transform = translate<float, 4>(up); engine->get_scene().get_spot_lights()[usedSpotLight].get_transformation() *= transform; } break; case GLFW_KEY_F: { auto right = 0.2f * ms::math::right(engine->get_scene().get_spot_lights()[usedSpotLight].get_transformation()); auto transform = translate<float, 4>(right); engine->get_scene().get_spot_lights()[usedSpotLight].get_transformation() *= transform; } break; case GLFW_KEY_H: { auto right = -0.2f * ms::math::right(engine->get_scene().get_spot_lights()[usedSpotLight].get_transformation()); auto transform = translate<float, 4>(right); engine->get_scene().get_spot_lights()[usedSpotLight].get_transformation() *= transform; } break; case GLFW_KEY_B: { auto rotation = ms::math::transform::rotate_about_y_radians<float, 4>(0.1f); engine->get_scene().get_spot_lights()[usedSpotLight].get_transformation() = rotation * engine->get_scene().get_spot_lights()[usedSpotLight].get_transformation(); } break; case GLFW_KEY_N: { auto rotation = ms::math::transform::rotate_about_y_radians<float, 4>(-0.1f); engine->get_scene().get_spot_lights()[usedSpotLight].get_transformation() = rotation * engine->get_scene().get_spot_lights()[usedSpotLight].get_transformation(); } break; case GLFW_KEY_U: { auto rotation = ms::math::transform::rotate_about_x_radians<float, 4>(0.1f); engine->get_scene().get_spot_lights()[usedSpotLight].get_transformation() = rotation * engine->get_scene().get_spot_lights()[usedSpotLight].get_transformation(); } break; case GLFW_KEY_J: { auto rotation = ms::math::transform::rotate_about_x_radians<float, 4>(-0.1f); engine->get_scene().get_spot_lights()[usedSpotLight].get_transformation() = rotation * engine->get_scene().get_spot_lights()[usedSpotLight].get_transformation(); } case GLFW_KEY_O: { auto up = -0.2f * ms::math::up(engine->get_scene().get_point_lights()[usedPointLight].get_transformation()); auto transform = translate<float, 4>(up); engine->get_scene().get_point_lights()[usedPointLight].get_transformation() *= transform; break; } case GLFW_KEY_P: { auto up = 0.2f * ms::math::up(engine->get_scene().get_point_lights()[usedPointLight].get_transformation()); auto transform = translate<float, 4>(up); engine->get_scene().get_point_lights()[usedPointLight].get_transformation() *= transform; break; } case GLFW_KEY_UP: { auto forward = 0.2f * ms::math::back(engine->get_scene().get_point_lights()[usedPointLight].get_transformation()); auto transform = translate<float, 4>(forward); engine->get_scene().get_point_lights()[usedPointLight].get_transformation() *= transform; } break; case GLFW_KEY_DOWN: { auto forward = -0.2f * ms::math::back(engine->get_scene().get_point_lights()[usedPointLight].get_transformation()); auto transform = translate<float, 4>(forward); engine->get_scene().get_point_lights()[usedPointLight].get_transformation() *= transform; } break; case GLFW_KEY_LEFT: { auto forward = 0.2f * ms::math::right(engine->get_scene().get_point_lights()[usedPointLight].get_transformation()); auto transform = translate<float, 4>(forward); engine->get_scene().get_point_lights()[usedPointLight].get_transformation() *= transform; } break; case GLFW_KEY_RIGHT: { auto forward = -0.2f * ms::math::right(engine->get_scene().get_point_lights()[usedPointLight].get_transformation()); auto transform = translate<float, 4>(forward); engine->get_scene().get_point_lights()[usedPointLight].get_transformation() *= transform; } break; case GLFW_KEY_1: usedSpotLight = std::clamp((usedSpotLight - 1), 0, static_cast<int>(engine->get_scene().get_spot_lights().size())); break; case GLFW_KEY_2: usedSpotLight = std::clamp((usedSpotLight + 1), 0, static_cast<int>(engine->get_scene().get_spot_lights().size())); break; case GLFW_KEY_3: usedPointLight = std::clamp((usedPointLight - 1), 0, static_cast<int>(engine->get_scene().get_point_lights().size())); break; case GLFW_KEY_4: usedPointLight = std::clamp((usedPointLight + 1), 0, static_cast<int>(engine->get_scene().get_point_lights().size())); break; default: break; } }
49.38191
173
0.614023
mateuszstompor
385f07b28d4055d64ab07f828fee900a7b80b509
7,193
cpp
C++
higan/processor/r65816/algorithms.cpp
ameer-bauer/higan-097
a4a28968173ead8251cfa7cd6b5bf963ee68308f
[ "Info-ZIP" ]
3
2016-03-23T01:17:36.000Z
2019-10-25T06:41:09.000Z
higan/processor/r65816/algorithms.cpp
ameer-bauer/higan-097
a4a28968173ead8251cfa7cd6b5bf963ee68308f
[ "Info-ZIP" ]
null
null
null
higan/processor/r65816/algorithms.cpp
ameer-bauer/higan-097
a4a28968173ead8251cfa7cd6b5bf963ee68308f
[ "Info-ZIP" ]
null
null
null
auto R65816::op_adc_b() { int result; if(!regs.p.d) { result = regs.a.l + rd.l + regs.p.c; } else { result = (regs.a.l & 0x0f) + (rd.l & 0x0f) + (regs.p.c << 0); if(result > 0x09) result += 0x06; regs.p.c = result > 0x0f; result = (regs.a.l & 0xf0) + (rd.l & 0xf0) + (regs.p.c << 4) + (result & 0x0f); } regs.p.v = ~(regs.a.l ^ rd.l) & (regs.a.l ^ result) & 0x80; if(regs.p.d && result > 0x9f) result += 0x60; regs.p.c = result > 0xff; regs.p.n = result & 0x80; regs.p.z = (uint8_t)result == 0; regs.a.l = result; } auto R65816::op_adc_w() { int result; if(!regs.p.d) { result = regs.a.w + rd.w + regs.p.c; } else { result = (regs.a.w & 0x000f) + (rd.w & 0x000f) + (regs.p.c << 0); if(result > 0x0009) result += 0x0006; regs.p.c = result > 0x000f; result = (regs.a.w & 0x00f0) + (rd.w & 0x00f0) + (regs.p.c << 4) + (result & 0x000f); if(result > 0x009f) result += 0x0060; regs.p.c = result > 0x00ff; result = (regs.a.w & 0x0f00) + (rd.w & 0x0f00) + (regs.p.c << 8) + (result & 0x00ff); if(result > 0x09ff) result += 0x0600; regs.p.c = result > 0x0fff; result = (regs.a.w & 0xf000) + (rd.w & 0xf000) + (regs.p.c << 12) + (result & 0x0fff); } regs.p.v = ~(regs.a.w ^ rd.w) & (regs.a.w ^ result) & 0x8000; if(regs.p.d && result > 0x9fff) result += 0x6000; regs.p.c = result > 0xffff; regs.p.n = result & 0x8000; regs.p.z = (uint16_t)result == 0; regs.a.w = result; } auto R65816::op_and_b() { regs.a.l &= rd.l; regs.p.n = regs.a.l & 0x80; regs.p.z = regs.a.l == 0; } auto R65816::op_and_w() { regs.a.w &= rd.w; regs.p.n = regs.a.w & 0x8000; regs.p.z = regs.a.w == 0; } auto R65816::op_bit_b() { regs.p.n = rd.l & 0x80; regs.p.v = rd.l & 0x40; regs.p.z = (rd.l & regs.a.l) == 0; } auto R65816::op_bit_w() { regs.p.n = rd.w & 0x8000; regs.p.v = rd.w & 0x4000; regs.p.z = (rd.w & regs.a.w) == 0; } auto R65816::op_cmp_b() { int r = regs.a.l - rd.l; regs.p.n = r & 0x80; regs.p.z = (uint8)r == 0; regs.p.c = r >= 0; } auto R65816::op_cmp_w() { int r = regs.a.w - rd.w; regs.p.n = r & 0x8000; regs.p.z = (uint16)r == 0; regs.p.c = r >= 0; } auto R65816::op_cpx_b() { int r = regs.x.l - rd.l; regs.p.n = r & 0x80; regs.p.z = (uint8)r == 0; regs.p.c = r >= 0; } auto R65816::op_cpx_w() { int r = regs.x.w - rd.w; regs.p.n = r & 0x8000; regs.p.z = (uint16)r == 0; regs.p.c = r >= 0; } auto R65816::op_cpy_b() { int r = regs.y.l - rd.l; regs.p.n = r & 0x80; regs.p.z = (uint8)r == 0; regs.p.c = r >= 0; } auto R65816::op_cpy_w() { int r = regs.y.w - rd.w; regs.p.n = r & 0x8000; regs.p.z = (uint16)r == 0; regs.p.c = r >= 0; } auto R65816::op_eor_b() { regs.a.l ^= rd.l; regs.p.n = regs.a.l & 0x80; regs.p.z = regs.a.l == 0; } auto R65816::op_eor_w() { regs.a.w ^= rd.w; regs.p.n = regs.a.w & 0x8000; regs.p.z = regs.a.w == 0; } auto R65816::op_lda_b() { regs.a.l = rd.l; regs.p.n = regs.a.l & 0x80; regs.p.z = regs.a.l == 0; } auto R65816::op_lda_w() { regs.a.w = rd.w; regs.p.n = regs.a.w & 0x8000; regs.p.z = regs.a.w == 0; } auto R65816::op_ldx_b() { regs.x.l = rd.l; regs.p.n = regs.x.l & 0x80; regs.p.z = regs.x.l == 0; } auto R65816::op_ldx_w() { regs.x.w = rd.w; regs.p.n = regs.x.w & 0x8000; regs.p.z = regs.x.w == 0; } auto R65816::op_ldy_b() { regs.y.l = rd.l; regs.p.n = regs.y.l & 0x80; regs.p.z = regs.y.l == 0; } auto R65816::op_ldy_w() { regs.y.w = rd.w; regs.p.n = regs.y.w & 0x8000; regs.p.z = regs.y.w == 0; } auto R65816::op_ora_b() { regs.a.l |= rd.l; regs.p.n = regs.a.l & 0x80; regs.p.z = regs.a.l == 0; } auto R65816::op_ora_w() { regs.a.w |= rd.w; regs.p.n = regs.a.w & 0x8000; regs.p.z = regs.a.w == 0; } auto R65816::op_sbc_b() { int result; rd.l ^= 0xff; if(!regs.p.d) { result = regs.a.l + rd.l + regs.p.c; } else { result = (regs.a.l & 0x0f) + (rd.l & 0x0f) + (regs.p.c << 0); if(result <= 0x0f) result -= 0x06; regs.p.c = result > 0x0f; result = (regs.a.l & 0xf0) + (rd.l & 0xf0) + (regs.p.c << 4) + (result & 0x0f); } regs.p.v = ~(regs.a.l ^ rd.l) & (regs.a.l ^ result) & 0x80; if(regs.p.d && result <= 0xff) result -= 0x60; regs.p.c = result > 0xff; regs.p.n = result & 0x80; regs.p.z = (uint8_t)result == 0; regs.a.l = result; } auto R65816::op_sbc_w() { int result; rd.w ^= 0xffff; if(!regs.p.d) { result = regs.a.w + rd.w + regs.p.c; } else { result = (regs.a.w & 0x000f) + (rd.w & 0x000f) + (regs.p.c << 0); if(result <= 0x000f) result -= 0x0006; regs.p.c = result > 0x000f; result = (regs.a.w & 0x00f0) + (rd.w & 0x00f0) + (regs.p.c << 4) + (result & 0x000f); if(result <= 0x00ff) result -= 0x0060; regs.p.c = result > 0x00ff; result = (regs.a.w & 0x0f00) + (rd.w & 0x0f00) + (regs.p.c << 8) + (result & 0x00ff); if(result <= 0x0fff) result -= 0x0600; regs.p.c = result > 0x0fff; result = (regs.a.w & 0xf000) + (rd.w & 0xf000) + (regs.p.c << 12) + (result & 0x0fff); } regs.p.v = ~(regs.a.w ^ rd.w) & (regs.a.w ^ result) & 0x8000; if(regs.p.d && result <= 0xffff) result -= 0x6000; regs.p.c = result > 0xffff; regs.p.n = result & 0x8000; regs.p.z = (uint16_t)result == 0; regs.a.w = result; } auto R65816::op_inc_b() { rd.l++; regs.p.n = rd.l & 0x80; regs.p.z = rd.l == 0; } auto R65816::op_inc_w() { rd.w++; regs.p.n = rd.w & 0x8000; regs.p.z = rd.w == 0; } auto R65816::op_dec_b() { rd.l--; regs.p.n = rd.l & 0x80; regs.p.z = rd.l == 0; } auto R65816::op_dec_w() { rd.w--; regs.p.n = rd.w & 0x8000; regs.p.z = rd.w == 0; } auto R65816::op_asl_b() { regs.p.c = rd.l & 0x80; rd.l <<= 1; regs.p.n = rd.l & 0x80; regs.p.z = rd.l == 0; } auto R65816::op_asl_w() { regs.p.c = rd.w & 0x8000; rd.w <<= 1; regs.p.n = rd.w & 0x8000; regs.p.z = rd.w == 0; } auto R65816::op_lsr_b() { regs.p.c = rd.l & 1; rd.l >>= 1; regs.p.n = rd.l & 0x80; regs.p.z = rd.l == 0; } auto R65816::op_lsr_w() { regs.p.c = rd.w & 1; rd.w >>= 1; regs.p.n = rd.w & 0x8000; regs.p.z = rd.w == 0; } auto R65816::op_rol_b() { unsigned carry = (unsigned)regs.p.c; regs.p.c = rd.l & 0x80; rd.l = (rd.l << 1) | carry; regs.p.n = rd.l & 0x80; regs.p.z = rd.l == 0; } auto R65816::op_rol_w() { unsigned carry = (unsigned)regs.p.c; regs.p.c = rd.w & 0x8000; rd.w = (rd.w << 1) | carry; regs.p.n = rd.w & 0x8000; regs.p.z = rd.w == 0; } auto R65816::op_ror_b() { unsigned carry = (unsigned)regs.p.c << 7; regs.p.c = rd.l & 1; rd.l = carry | (rd.l >> 1); regs.p.n = rd.l & 0x80; regs.p.z = rd.l == 0; } auto R65816::op_ror_w() { unsigned carry = (unsigned)regs.p.c << 15; regs.p.c = rd.w & 1; rd.w = carry | (rd.w >> 1); regs.p.n = rd.w & 0x8000; regs.p.z = rd.w == 0; } auto R65816::op_trb_b() { regs.p.z = (rd.l & regs.a.l) == 0; rd.l &= ~regs.a.l; } auto R65816::op_trb_w() { regs.p.z = (rd.w & regs.a.w) == 0; rd.w &= ~regs.a.w; } auto R65816::op_tsb_b() { regs.p.z = (rd.l & regs.a.l) == 0; rd.l |= regs.a.l; } auto R65816::op_tsb_w() { regs.p.z = (rd.w & regs.a.w) == 0; rd.w |= regs.a.w; }
21.929878
90
0.52134
ameer-bauer
386023257373a030abba175fe5e167462f5f1c27
4,872
cc
C++
algorithms/vi-map-helpers/src/vi-map-geometry.cc
ethz-asl/maplab_summer
7d57dabcdc3feffd8e9409686f7565bb77801f08
[ "Apache-2.0" ]
3
2019-09-16T02:11:58.000Z
2020-03-20T22:49:32.000Z
algorithms/vi-map-helpers/src/vi-map-geometry.cc
ethz-asl/maplab_summer
7d57dabcdc3feffd8e9409686f7565bb77801f08
[ "Apache-2.0" ]
null
null
null
algorithms/vi-map-helpers/src/vi-map-geometry.cc
ethz-asl/maplab_summer
7d57dabcdc3feffd8e9409686f7565bb77801f08
[ "Apache-2.0" ]
3
2020-02-28T14:11:54.000Z
2022-02-25T08:30:50.000Z
#include "vi-map-helpers/vi-map-geometry.h" #include <limits> #include <aslam/frames/visual-frame.h> #include <landmark-triangulation/pose-interpolator.h> #include <maplab-common/geometry.h> #include <maplab-common/parallel-process.h> #include <vi-map/vi-map.h> namespace vi_map_helpers { VIMapGeometry::VIMapGeometry(const vi_map::VIMap& map) : map_(map) {} pose::Transformation VIMapGeometry::getVisualFrame_T_G_C( const vi_map::VisualFrameIdentifier& frame_id) const { return map_.getVertex_T_G_I(frame_id.vertex_id) * map_.getVertex(frame_id.vertex_id) .getNCameras() ->get_T_C_B(frame_id.frame_index) .inverse(); } double VIMapGeometry::getMedianSceneDepth( const vi_map::VisualFrameIdentifier& frame_id) const { const vi_map::Vertex& vertex = map_.getVertex(frame_id.vertex_id); const aslam::VisualFrame& frame = vertex.getVisualFrame(frame_id.frame_index); const Eigen::Vector3d p_G_C = getVisualFrame_T_G_C(frame_id).getPosition(); const size_t num_keypoints = frame.getNumKeypointMeasurements(); std::vector<double> square_depths; square_depths.reserve(num_keypoints); vi_map::LandmarkIdList landmark_ids; vertex.getFrameObservedLandmarkIds(frame_id.frame_index, &landmark_ids); for (const vi_map::LandmarkId& landmark_id : landmark_ids) { if (landmark_id.isValid()) { const vi_map::Landmark::Quality quality = map_.getLandmark(landmark_id).getQuality(); if (quality != vi_map::Landmark::Quality::kGood) { continue; } square_depths.push_back( (map_.getLandmark_G_p_fi(landmark_id) - p_G_C).squaredNorm()); } } if (square_depths.empty()) { LOG(WARNING) << "No landmarks found to compute median scene depth, returning " "infinity!"; return std::numeric_limits<double>::infinity(); } std::nth_element( square_depths.begin(), square_depths.begin() + square_depths.size() / 2, square_depths.end()); return sqrt(square_depths[square_depths.size() / 2]); } int VIMapGeometry::getNeighboursWithinRange( const pose_graph::VertexId& vertex_id, double range_m, pose_graph::VertexIdSet* neighbours) const { CHECK(map_.hasVertex(vertex_id)); CHECK_NOTNULL(neighbours); neighbours->clear(); pose_graph::VertexIdList vertex_ids; map_.getAllVertexIds(&vertex_ids); const Eigen::Vector3d& p_M_I = map_.getVertex(vertex_id).get_p_M_I(); for (const pose_graph::VertexId& id : vertex_ids) { double distance_m = (map_.getVertex(id).get_p_M_I() - p_M_I).norm(); if (distance_m < range_m) { neighbours->insert(id); } } return neighbours->size(); } void VIMapGeometry::get_p_G_I_CovarianceEigenValuesAndVectorsAscending( const vi_map::MissionId& mission_id, Eigen::Vector3d* eigenvalues, Eigen::Matrix3d* eigenvectors) const { CHECK_NOTNULL(eigenvalues); CHECK_NOTNULL(eigenvectors); CHECK(map_.hasMission(mission_id)); Eigen::Matrix3Xd p_G_I; map_.getAllVertex_p_G_I(mission_id, &p_G_I); common::geometry::computeCovarianceEigenValuesAndVectors( p_G_I, eigenvalues, eigenvectors); } Eigen::Vector3d VIMapGeometry::get_bv_G_root_average( const vi_map::MissionId& mission_id) const { CHECK(map_.hasMission(mission_id)); pose_graph::VertexId root_vertex_id = map_.getMission(mission_id).getRootVertexId(); Eigen::Matrix3Xd p_G_I; map_.getAllVertex_p_G_I(mission_id, &p_G_I); return p_G_I.rowwise().mean() - map_.getVertex_G_p_I(root_vertex_id); } void VIMapGeometry::interpolateForTimestamps_T_G_I( const vi_map::MissionId& mission_id, const Eigen::Matrix<int64_t, 1, Eigen::Dynamic>& timestamps_ns, aslam::TransformationVector* T_G_I_vector) const { CHECK_NOTNULL(T_G_I_vector)->clear(); CHECK_GT(timestamps_ns.cols(), 0); const aslam::Transformation& T_G_M = map_.getMissionBaseFrameForMission(mission_id).get_T_G_M(); landmark_triangulation::VertexToTimeStampMap vertex_to_time_map; int64_t min_timestamp_ns; int64_t max_timestamp_ns; const landmark_triangulation::PoseInterpolator pose_interpolator; pose_interpolator.getVertexToTimeStampMap( map_, mission_id, &vertex_to_time_map, &min_timestamp_ns, &max_timestamp_ns); if (vertex_to_time_map.empty()) { LOG(FATAL) << "Couldn't find any IMU data to interpolate exact T_G_I for " "the given timestamps: " << timestamps_ns; } aslam::TransformationVector T_M_I_vector; pose_interpolator.getPosesAtTime( map_, mission_id, timestamps_ns, &T_M_I_vector); CHECK_EQ(static_cast<int>(T_M_I_vector.size()), timestamps_ns.cols()); // Transform all T_M_I into T_G_I T_G_I_vector->reserve(T_M_I_vector.size()); for (aslam::Transformation& T_M_I : T_M_I_vector) { T_G_I_vector->emplace_back(T_G_M * T_M_I); } } } // namespace vi_map_helpers
35.304348
80
0.73358
ethz-asl
386126fb790690f52145ca624e7325b54122c022
1,165
cc
C++
LIMoSim/map/osm/osmrelationentry.cc
inet-framework/LIMoSim
d9bdcefe82d41d4c8fd665a268843763fce59363
[ "MIT" ]
7
2017-07-17T07:13:03.000Z
2021-10-12T08:39:17.000Z
LIMoSim/map/osm/osmrelationentry.cc
tudo-cni/LIMoSim
f0e4c8d964da18dffecea040775f07da3f5a5d46
[ "MIT" ]
1
2018-03-08T10:28:01.000Z
2018-03-08T10:28:01.000Z
LIMoSim/map/osm/osmrelationentry.cc
tudo-cni/LIMoSim
f0e4c8d964da18dffecea040775f07da3f5a5d46
[ "MIT" ]
7
2017-09-13T09:05:20.000Z
2022-01-04T17:20:20.000Z
#include "osmrelationentry.h" namespace LIMoSim { OSMRelationEntry::OSMRelationEntry(OSMDocument *_parent) : OSMEntry(_parent) { } OSMRelationEntry OSMRelationEntry::fromXML(DOMElement *_entry, OSMDocument *_parent) { OSMRelationEntry entry(_parent); entry.id = _entry->getAttribute("id").toInt(); for(auto & childNode : _entry->childNodes) { DOMElement *child = childNode->toElement(); std::string name = child->tagName; if(name=="tag") { std::string key = child->getAttribute("k").toString(); Variant value = child->getAttribute("v"); if(key=="name") entry.name = value.toString(); else if(key=="type") entry.type = value.toString(); } else if(name=="member") { std::string role = child->getAttribute("role").toString(); std::string ref = child->getAttribute("ref").toString(); if(role=="house") entry.houses.push_back(ref); else if(role=="street") entry.streets.push_back(ref); } } return entry; } }
24.270833
84
0.561373
inet-framework
386136b82c05ed902b3695248be600058dc1bc93
1,158
cpp
C++
src_smartcontract_db/scan_select/scan_planner/scanner/join/JoinCandidateStack.cpp
alinous-core/codable-cash
32a86a152a146c592bcfd8cc712f4e8cb38ee1a0
[ "MIT" ]
6
2019-01-06T05:02:39.000Z
2020-10-01T11:45:32.000Z
src_smartcontract_db/scan_select/scan_planner/scanner/join/JoinCandidateStack.cpp
Codablecash/codablecash
8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9
[ "MIT" ]
209
2018-05-18T03:07:02.000Z
2022-03-26T11:42:41.000Z
src_smartcontract_db/scan_select/scan_planner/scanner/join/JoinCandidateStack.cpp
Codablecash/codablecash
8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9
[ "MIT" ]
3
2019-07-06T09:16:36.000Z
2020-10-15T08:23:28.000Z
/* * JoinCandidateStack.cpp * * Created on: 2020/09/03 * Author: iizuka */ #include "scan_select/scan_planner/scanner/join/JoinCandidateStack.h" #include "scan_select/scan_planner/scanner/join/AbstractJoinCandidate.h" namespace codablecash { JoinCandidateStack::JoinCandidateStack() : markStack(4) { } JoinCandidateStack::~JoinCandidateStack() { this->stack.deleteElements(); } bool JoinCandidateStack::isEmpty() const noexcept { if(this->markStack.size() == 0){ return this->stack.isEmpty(); } int topidx = this->markStack.size() - 1; int index = this->markStack.get(topidx); return this->stack.size() == index; } void JoinCandidateStack::push(AbstractJoinCandidate* candidate) noexcept { this->stack.addElement(candidate); } AbstractJoinCandidate* JoinCandidateStack::pop() noexcept { int index = this->stack.size() - 1; return this->stack.remove(index); } void JoinCandidateStack::mark() noexcept { int index = this->stack.size(); this->markStack.addElement(index); } void JoinCandidateStack::unmark() noexcept { int index = this->markStack.size() - 1; this->markStack.remove(index); } } /* namespace codablecash */
22.269231
74
0.727116
alinous-core
3863eabddc64fe61568f9771c3b45a7c6f2337ce
60
cpp
C++
GameEngine/src/GameEngine/Core/GameObject.cpp
josh-teichro/2DTestGame
b2cc31ce997ed54a0c07709edc1e5d8c2ccccc65
[ "Apache-2.0" ]
null
null
null
GameEngine/src/GameEngine/Core/GameObject.cpp
josh-teichro/2DTestGame
b2cc31ce997ed54a0c07709edc1e5d8c2ccccc65
[ "Apache-2.0" ]
null
null
null
GameEngine/src/GameEngine/Core/GameObject.cpp
josh-teichro/2DTestGame
b2cc31ce997ed54a0c07709edc1e5d8c2ccccc65
[ "Apache-2.0" ]
null
null
null
#include "gepch.h" #include "GameEngine/Core/GameObject.h"
15
39
0.75
josh-teichro
386596058ee2d88fdf87b99b58a07d7757a2f2a8
6,607
cpp
C++
src/bin/gsqlerr/gsqlerr.cpp
wotchin/openGauss-server
ebd92e92b0cfd76b121d98e4c57a22d334573159
[ "MulanPSL-1.0" ]
1
2020-06-30T15:00:50.000Z
2020-06-30T15:00:50.000Z
src/bin/gsqlerr/gsqlerr.cpp
wotchin/openGauss-server
ebd92e92b0cfd76b121d98e4c57a22d334573159
[ "MulanPSL-1.0" ]
null
null
null
src/bin/gsqlerr/gsqlerr.cpp
wotchin/openGauss-server
ebd92e92b0cfd76b121d98e4c57a22d334573159
[ "MulanPSL-1.0" ]
null
null
null
/* * Copyright (c) 2020 Huawei Technologies Co.,Ltd. * * openGauss is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * 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 PSL v2 for more details. * --------------------------------------------------------------------------------------- * * gsqlerr.cpp * Defines the entry point for the console application. * * IDENTIFICATION * src/bin/gsqlerr/gsqlerr.cpp * * --------------------------------------------------------------------------------------- */ #include "gsqlerr_errmsg.h" #include <stdlib.h> #include <string.h> #define GSQLERROR_PARAM_NUM 3 #define PARAM_NOT_FOUND (-1) #define GSQLERROE_MAX_ERRCODE_LENGTH 6 typedef enum tag_gsqlerr_param_e { GSQLERROR_HELP = 0, GSQLERROR_VERSION, GSQLERROR_NO_VALUE, GSQLERROR_NOT_FOUND = PARAM_NOT_FOUND } gsqlerr_param_e; char* gsqlerr_param[] = { "-h", "", "print online manual", "-v", "", "print version", "[errorcode]", "", "print errorcode description"}; void gsqlerr_errinfo_print(int errcode); extern const mppdb_detail_errmsg_t* gsqlerr_detail_error(int code); int gsqlerr_find_err_idx(int code, const gsqlerr_err_msg_t* err_reg, int err_cnt); extern int gsqlerr_param_find(char* str, char** param, int num); void gsqlerr_version(); void gsqlerr_help(); extern int gsqlerr_check_errcode(char* errstr); int main(int argc, char* argv[]) { int errcode = 0; int ret = 0; gsqlerr_param_e optype; optype = (gsqlerr_param_e)gsqlerr_param_find(argv[1], gsqlerr_param, GSQLERROR_PARAM_NUM); switch (optype) { case GSQLERROR_HELP: { gsqlerr_help(); return 0; } case GSQLERROR_VERSION: { gsqlerr_version(); return 0; } case GSQLERROR_NOT_FOUND: { if (argc > 2) { printf("Invalid option, please use 'gsqlerr -h' for more information.\n"); gsqlerr_help(); return -1; } ret = gsqlerr_check_errcode(argv[1]); if (0 == ret) { errcode = atoi(argv[1]); gsqlerr_errinfo_print(errcode); } else { printf("Invalid option, please use 'gsqlerr -h' for more information.\n"); gsqlerr_help(); return -1; } return 0; } case GSQLERROR_NO_VALUE: { printf("Invalid option, please use 'gsqlerr -h' for more information.\n"); gsqlerr_help(); return -1; } /* could not go to here */ default: { return -1; } } } int gsqlerr_param_find(char* str, char** param, int num) { int i = 0; if ((NULL == str) || (NULL == param)) return GSQLERROR_NO_VALUE; for (i = 0; i < num; i++) { if (NULL == param[i * 3]) return GSQLERROR_NOT_FOUND; if (0 == strcmp(str, param[i * 3])) return i; } return GSQLERROR_NOT_FOUND; } void gsqlerr_version() { printf("\nV1.0 for gsqlerror. \n"); } void gsqlerr_help() { int ilasterrno = 0; ilasterrno = sizeof(g_gsqlerr_errors) / sizeof(gsqlerr_err_msg_t); printf("Display errorcode description\n"); printf("\n"); printf("gsqlerror [options...]\n"); printf("\n"); printf("Options:\n"); printf(" -h print online manual\n"); printf(" -v print version\n"); printf(" [errorcode] print errorcode description\n"); printf(" the range of errorcode is [1...%d]\n", g_gsqlerr_errors[ilasterrno - 1].ulSqlErrcode); printf("\n"); return; } void gsqlerr_errinfo_print(int errcode) { const mppdb_detail_errmsg_t* errmsg = NULL; int ilasterrno = 0; ilasterrno = sizeof(g_gsqlerr_errors) / sizeof(gsqlerr_err_msg_t); errmsg = gsqlerr_detail_error(errcode); if (errmsg == NULL) { printf("\nError code %d does not exist.\n", errcode); printf("The correct range of error code is [1...%d].\n\n", g_gsqlerr_errors[ilasterrno - 1].ulSqlErrcode); } else { printf("\n%s", "[Description]"); printf("\n%s\n", errmsg->msg); printf("\n%s", "[Causes]"); printf("\n%s\n", errmsg->cause); printf("\n%s", "[Action]"); printf("\n%s\n\n", errmsg->action); } return; } int gsqlerr_check_errcode(char* errstr) { char* pPtr = NULL; if (errstr == NULL) return -1; if (strlen(errstr) >= GSQLERROE_MAX_ERRCODE_LENGTH) { return -1; } if ((1 == strlen(errstr)) && ('0' == *errstr)) { return -1; } /* check errno is valid */ pPtr = errstr; while (*pPtr != '\0') { if (('0' <= *pPtr) && ('9' >= *pPtr)) { pPtr++; } else { /* invalid charactor */ return -1; } } return 0; } const mppdb_detail_errmsg_t* gsqlerr_detail_error(int code) { int idx = -1; idx = gsqlerr_find_err_idx(code, g_gsqlerr_errors, sizeof(g_gsqlerr_errors) / sizeof(gsqlerr_err_msg_t)); if (idx < 0) { /* return internal error if error message not found */ return NULL; } return &(g_gsqlerr_errors[idx].stErrmsg); } int gsqlerr_find_err_idx(int code, const gsqlerr_err_msg_t* err_reg, int err_cnt) { int start = 0; int end = err_cnt - 1; int mid = (start + end) / 2; if (err_reg == NULL) { return -1; } /* binary search for code */ while (err_reg[mid].ulSqlErrcode != code) { if (err_reg[mid].ulSqlErrcode < code) { if (mid == end) { /* search value is greate than end value, so not found */ return -1; } /* because mid value is less than search value, next search right */ start = mid + 1; } else { if (mid == start) { /* search value is less than start value, so not found */ return -1; } /* because mid value is greater than search value, next search left */ end = mid - 1; } /* re-calculate middle index value */ mid = (start + end) / 2; } return mid; }
27.077869
117
0.557288
wotchin
386642924995cbf3a723b741343feb29859b85a3
795
cpp
C++
tests/tst_Date/src/tst_Date.cpp
pet2petteam/PetAPI
ee7945d43953b3fcc20216fa51d8ede03f0b0351
[ "MIT" ]
null
null
null
tests/tst_Date/src/tst_Date.cpp
pet2petteam/PetAPI
ee7945d43953b3fcc20216fa51d8ede03f0b0351
[ "MIT" ]
null
null
null
tests/tst_Date/src/tst_Date.cpp
pet2petteam/PetAPI
ee7945d43953b3fcc20216fa51d8ede03f0b0351
[ "MIT" ]
null
null
null
#include <QtTest> #include <QDate> #include <Container/ByteBuffer.h> #include <DataStruct/DateTime.h> using namespace PetAPI; class tst_Date : public QObject { Q_OBJECT public: tst_Date() = default; ~tst_Date() = default; private slots: void tst_currentDate(); void tst_fromToByteBuffer(); }; void tst_Date::tst_currentDate() { Date date = Date::currentDate(); QDate qdate = QDate::currentDate(); QVERIFY(qdate.year() == date.year); QVERIFY(qdate.month() == date.month); QVERIFY(qdate.day() == date.day); } void tst_Date::tst_fromToByteBuffer() { Date date_1 = Date::currentDate(); ByteBuffer dateBuffer = date_1.toByteBuffer(); Date date_2 = Date::fromByteBuffer(dateBuffer); QVERIFY(date_1 == date_2); } QTEST_APPLESS_MAIN(tst_Date) #include "tst_Date.moc"
18.068182
48
0.713208
pet2petteam
3867eedc6fdf01cdebb28c305c98eb8cd8f279e4
752
cpp
C++
EqNode/src/simplify.cpp
marcusbfs/HydroModel
4c9793b338eb21898563396c32469a2740002f1e
[ "MIT" ]
null
null
null
EqNode/src/simplify.cpp
marcusbfs/HydroModel
4c9793b338eb21898563396c32469a2740002f1e
[ "MIT" ]
null
null
null
EqNode/src/simplify.cpp
marcusbfs/HydroModel
4c9793b338eb21898563396c32469a2740002f1e
[ "MIT" ]
null
null
null
#include "simplify.h" bool SimplifyEqNode::simplify(EqNode& root) { bool changed = joinNumbers(root); while (joinNumbers(root)); return changed; } bool SimplifyEqNode::joinNumbers(EqNode& root) { bool changed = false; if (root.isOperator()) { bool left_changed = false; bool right_changed = false; if (root.left) left_changed = joinNumbers(*root.left); if (root.right) right_changed = joinNumbers(*root.right); changed = left_changed || right_changed; if ( root.left && root.right) if ( root.left->isNumber() && root.right->isNumber() ) { root.getValue(); root.op = EqNode::OperatorType::Number; root.left = nullptr; root.right = nullptr; changed = true; } } return changed; }
18.341463
46
0.655585
marcusbfs
386925525751c603f7445336ffdcd6fffc128c2f
966
cpp
C++
vespalib/src/vespa/vespalib/data/simple_buffer.cpp
Anlon-Burke/vespa
5ecd989b36cc61716bf68f032a3482bf01fab726
[ "Apache-2.0" ]
4,054
2017-08-11T07:58:38.000Z
2022-03-31T22:32:15.000Z
vespalib/src/vespa/vespalib/data/simple_buffer.cpp
Anlon-Burke/vespa
5ecd989b36cc61716bf68f032a3482bf01fab726
[ "Apache-2.0" ]
4,854
2017-08-10T20:19:25.000Z
2022-03-31T19:04:23.000Z
vespalib/src/vespa/vespalib/data/simple_buffer.cpp
Anlon-Burke/vespa
5ecd989b36cc61716bf68f032a3482bf01fab726
[ "Apache-2.0" ]
541
2017-08-10T18:51:18.000Z
2022-03-11T03:18:56.000Z
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "simple_buffer.h" #include <cassert> namespace vespalib { SimpleBuffer::SimpleBuffer() : _data(), _used(0) { } SimpleBuffer::~SimpleBuffer() = default; Memory SimpleBuffer::obtain() { return Memory(&_data[0], _used); } Input & SimpleBuffer::evict(size_t bytes) { assert(bytes <= _used); _data.erase(_data.begin(), _data.begin() + bytes); _used -= bytes; return *this; } WritableMemory SimpleBuffer::reserve(size_t bytes) { assert((_used + bytes) >= _used); _data.resize(_used + bytes, char(0x55)); return WritableMemory(&_data[_used], bytes); } Output & SimpleBuffer::commit(size_t bytes) { assert(bytes <= (_data.size() - _used)); _used += bytes; return *this; } std::ostream &operator<<(std::ostream &os, const SimpleBuffer &buf) { return os << buf.get(); } } // namespace vespalib
18.576923
104
0.662526
Anlon-Burke
386c1ea3018e31b0fd351772ca96ac28d05b9a1f
589
cpp
C++
src/pkg_deb/prerm.cpp
naughtybikergames/pkg
9a78380c6cf82c95dec3968a7ed69000b349113d
[ "MIT" ]
null
null
null
src/pkg_deb/prerm.cpp
naughtybikergames/pkg
9a78380c6cf82c95dec3968a7ed69000b349113d
[ "MIT" ]
null
null
null
src/pkg_deb/prerm.cpp
naughtybikergames/pkg
9a78380c6cf82c95dec3968a7ed69000b349113d
[ "MIT" ]
null
null
null
#include <pkg/deb/prerm.hpp> #include <pkg/utils.hpp> #include <sstream> using namespace std; using namespace pkg::deb; extern char _binary_resources_pkg_deb_prerm_sh_start; extern char _binary_resources_pkg_deb_prerm_sh_end; prerm::prerm() { stringstream ss; char *p = &_binary_resources_pkg_deb_prerm_sh_start; while (p != &_binary_resources_pkg_deb_prerm_sh_end) ss << *p++; _prerm = get_all_lines(ss); } string prerm::to_string() const { return _prerm; } ostream& operator<<(ostream &out, const prerm prerm) { return out << prerm.to_string(); }
20.310345
56
0.721562
naughtybikergames
387390a4844ec0b37df0dc6079d78f01f235962e
7,175
cpp
C++
Samples/MediaEditing/cpp/Scenario1_TrimAndSaveClip.xaml.cpp
dujianxin/Windows-universal-samples
d4e95ff0ac408c5d4d980bb18d53fb2c6556a273
[ "MIT" ]
2,504
2019-05-07T06:56:42.000Z
2022-03-31T19:37:59.000Z
Samples/MediaEditing/cpp/Scenario1_TrimAndSaveClip.xaml.cpp
dujianxin/Windows-universal-samples
d4e95ff0ac408c5d4d980bb18d53fb2c6556a273
[ "MIT" ]
314
2019-05-08T16:56:30.000Z
2022-03-21T07:13:45.000Z
Samples/MediaEditing/cpp/Scenario1_TrimAndSaveClip.xaml.cpp
dujianxin/Windows-universal-samples
d4e95ff0ac408c5d4d980bb18d53fb2c6556a273
[ "MIT" ]
2,219
2019-05-07T00:47:26.000Z
2022-03-30T21:12:31.000Z
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "pch.h" #include "Scenario1_TrimAndSaveClip.xaml.h" using namespace SDKTemplate; using namespace concurrency; using namespace Platform; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::UI::Core; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls::Primitives; using namespace Windows::UI::Xaml::Data; using namespace Windows::UI::Xaml::Input; using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Navigation; using namespace Windows::Media::Core; using namespace Windows::Media::Editing; using namespace Windows::Media::Transcoding; using namespace Windows::Storage; using namespace Windows::Storage::Pickers; using namespace Windows::Storage::Streams; using namespace Windows::Storage::AccessCache; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 Scenario1_TrimAndSaveClip::Scenario1_TrimAndSaveClip() : rootPage(MainPage::Current) { InitializeComponent(); } void Scenario1_TrimAndSaveClip::OnNavigatedTo(NavigationEventArgs^ e) { // Make sure we don't run out of entries in StoreItemAccessList. // As we don't need to persist this across app sessions/pages, clearing // every time is sufficient for this sample storageItemAccessList = StorageApplicationPermissions::FutureAccessList; storageItemAccessList->Clear(); } void Scenario1_TrimAndSaveClip::OnNavigatedFrom(NavigationEventArgs^ e) { mediaElement->Source = nullptr; mediaStreamSource = nullptr; } void Scenario1_TrimAndSaveClip::ChooseFile_Click(Object^ sender, RoutedEventArgs^ e) { // Get file auto picker = ref new FileOpenPicker(); picker->SuggestedStartLocation = PickerLocationId::VideosLibrary; picker->FileTypeFilter->Append(".mp4"); create_task(picker->PickSingleFileAsync()).then([this](StorageFile^ videoFile) { if (videoFile == nullptr) { rootPage->NotifyUser("File picking cancelled", NotifyType::ErrorMessage); return; } this->pickedFile = videoFile; // These files could be picked from a location that we won't have access to later // (especially if persisting the MediaComposition to disk and loading it later). // Use the StorageItemAccessList in order to keep access permissions to that // file for later use. Be aware that this access list needs to be cleared // periodically or the app will run out of entries. storageItemAccessList->Add(this->pickedFile); create_task(this->pickedFile->OpenReadAsync()).then([this](IRandomAccessStreamWithContentType^ videoSource) { mediaElement->SetSource(videoSource, this->pickedFile->ContentType); trimClip->IsEnabled = true; }); }); } void Scenario1_TrimAndSaveClip::TrimClip_Click(Object^ sender, RoutedEventArgs^ e) { create_task(MediaClip::CreateFromFileAsync(this->pickedFile)).then([this](MediaClip^ clip) { // Trim the front and back 25% from the clip TimeSpan trimFromStart; trimFromStart.Duration = (long long)(clip->OriginalDuration.Duration * 0.25); clip->TrimTimeFromStart = trimFromStart; TimeSpan trimFromEnd; trimFromEnd.Duration = (long long)(clip->OriginalDuration.Duration * 0.25); clip->TrimTimeFromEnd = trimFromEnd; // Create a MediaComposition containing the clip and set it on the MediaElement. composition = ref new MediaComposition(); composition->Clips->Append(clip); mediaStreamSource = composition->GeneratePreviewMediaStreamSource((int)mediaElement->ActualWidth, (int)mediaElement->ActualHeight); mediaElement->SetMediaStreamSource(mediaStreamSource); rootPage->NotifyUser("Clip trimmed", NotifyType::StatusMessage); save->IsEnabled = true; }); } void Scenario1_TrimAndSaveClip::Save_Click(Object^ sender, RoutedEventArgs^ e) { EnableButtons(false); rootPage->NotifyUser("Requesting file to save to", NotifyType::StatusMessage); auto picker = ref new FileSavePicker(); picker->SuggestedStartLocation = PickerLocationId::VideosLibrary; auto filter = ref new Platform::Collections::Vector<String^>(); filter->Append(".mp4"); picker->FileTypeChoices->Insert("MP4 files", filter); picker->SuggestedFileName = "TrimmedClip.mp4"; create_task(picker->PickSaveFileAsync()).then([this](StorageFile^ file) { if (file != nullptr) { auto saveOperation = composition->RenderToFileAsync(file, MediaTrimmingPreference::Precise); saveOperation->Progress = ref new AsyncOperationProgressHandler<TranscodeFailureReason, double>([this]( IAsyncOperationWithProgress<TranscodeFailureReason, double>^ info, double value) { create_task(this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this,info,value]() { rootPage->NotifyUser("Saving file... Progress: " + value.ToString() + "%", NotifyType::StatusMessage); }))).wait(); }); saveOperation->Completed = ref new AsyncOperationWithProgressCompletedHandler<TranscodeFailureReason, double>([this]( IAsyncOperationWithProgress<TranscodeFailureReason, double>^ info, AsyncStatus status) { create_task(this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, info, status]() { auto results = info->GetResults(); if (results != TranscodeFailureReason::None || status != AsyncStatus::Completed) { rootPage->NotifyUser("Saving was unsuccessful", NotifyType::ErrorMessage); } else { rootPage->NotifyUser("Trimmed clip saved to file", NotifyType::StatusMessage); } EnableButtons(true); }))).wait(); }); } else { rootPage->NotifyUser("User cancelled the file selection", NotifyType::StatusMessage); EnableButtons(true); } }); } void Scenario1_TrimAndSaveClip::EnableButtons(bool isEnabled) { chooseFile->IsEnabled = isEnabled; save->IsEnabled = isEnabled; trimClip->IsEnabled = isEnabled; }
41.715116
140
0.65547
dujianxin
38757d249e2171385af67dca661693a08dac9f8c
2,184
cpp
C++
_KaramayEngine/karamay_engine_graphics_unit_cmake/karamay_engine_graphics_unit/source/graphics/vulkan/device_object/render_pass.cpp
Karamays/karamay_engine
858054ea5155d0b690b7cf17d0e6a6266e0b0b9c
[ "MIT" ]
null
null
null
_KaramayEngine/karamay_engine_graphics_unit_cmake/karamay_engine_graphics_unit/source/graphics/vulkan/device_object/render_pass.cpp
Karamays/karamay_engine
858054ea5155d0b690b7cf17d0e6a6266e0b0b9c
[ "MIT" ]
null
null
null
_KaramayEngine/karamay_engine_graphics_unit_cmake/karamay_engine_graphics_unit/source/graphics/vulkan/device_object/render_pass.cpp
Karamays/karamay_engine
858054ea5155d0b690b7cf17d0e6a6266e0b0b9c
[ "MIT" ]
1
2022-01-29T08:24:14.000Z
2022-01-29T08:24:14.000Z
#include "render_pass.h" #include "pooled_object/command_buffer.h" #include "framebuffer.h" render_pass::render_pass(device& dev) : device_object(dev) { } render_pass::~render_pass() { deallocate(); } bool render_pass::allocate(const std::vector<VkAttachmentDescription>& attachments, const std::vector<VkSubpassDependency>& dependencies, const std::vector<VkSubpassDescription>& subpasses) { VkRenderPassCreateInfo _create_info; _create_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; _create_info.flags; _create_info.attachmentCount = attachments.size(); _create_info.dependencyCount = dependencies.size(); _create_info.subpassCount = subpasses.size(); _create_info.pAttachments = attachments.data(); _create_info.pDependencies = dependencies.data(); _create_info.pSubpasses = subpasses.data(); auto _ret = vkCreateRenderPass(_device.handle(), &_create_info, nullptr, &_handle); if (_ret != VkResult::VK_SUCCESS) { return false; } return true; } void render_pass::deallocate() { if (_handle) { vkDestroyRenderPass(_device.handle(), _handle, nullptr); _handle = nullptr; } } void render_pass::set(const std::function<void(framebuffer*, command_buffer*)>& sequence) { command_buffer* _recorder = nullptr; framebuffer* _rt = nullptr; _begin(_recorder, _rt, {}, {}, VkSubpassContents::VK_SUBPASS_CONTENTS_INLINE); sequence(_rt, _recorder); _end(_recorder); } void render_pass::_begin(command_buffer* recorder, framebuffer* render_target, const std::vector<VkClearValue>& clear_values, VkRect2D render_area, VkSubpassContents contents) { VkRenderPassBeginInfo _begin_info; _begin_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; _begin_info.framebuffer = render_target->handle(); _begin_info.renderPass = _handle; _begin_info.clearValueCount = clear_values.size(); _begin_info.pClearValues = clear_values.data(); _begin_info.renderArea = render_area; vkCmdBeginRenderPass(recorder->handle(), &_begin_info, contents); } void render_pass::_end(command_buffer* recorder) { vkCmdEndRenderPass(recorder->handle()); }
31.652174
189
0.742674
Karamays
3877e4f4709c1187ccaa0646bed3720bb53a4552
233
cpp
C++
src/model/Edge.cpp
hpedrorodrigues/Graphs
1e6427317d8134c7cd2bd82500c048b8fe0dc77d
[ "MIT" ]
2
2016-03-07T03:33:08.000Z
2016-12-26T21:30:35.000Z
src/model/Edge.cpp
hpedrorodrigues/Graphs
1e6427317d8134c7cd2bd82500c048b8fe0dc77d
[ "MIT" ]
null
null
null
src/model/Edge.cpp
hpedrorodrigues/Graphs
1e6427317d8134c7cd2bd82500c048b8fe0dc77d
[ "MIT" ]
null
null
null
#include "Edge.h" Edge::Edge(int originVertexId, int destinationVertexId, int weight) { this->originVertexId = originVertexId; this->destinationVertexId = destinationVertexId; this->weight = weight; }; Edge::~Edge() { }
23.3
69
0.712446
hpedrorodrigues
3879171c305c4ec51d069387dc6db8d8ff397276
2,514
cpp
C++
Nasko/DatingAgency/agency.cpp
slaviborisov/shu.bg
1ed9a65fff1512d18a3e4cde90030abb450f0d9f
[ "Apache-2.0" ]
null
null
null
Nasko/DatingAgency/agency.cpp
slaviborisov/shu.bg
1ed9a65fff1512d18a3e4cde90030abb450f0d9f
[ "Apache-2.0" ]
null
null
null
Nasko/DatingAgency/agency.cpp
slaviborisov/shu.bg
1ed9a65fff1512d18a3e4cde90030abb450f0d9f
[ "Apache-2.0" ]
null
null
null
#include "agency.h" #include <iostream> #include <string> using namespace std; CAgency::CAgency() { m = NULL; total_members = 0; cout<< "Въведете име на агенцията: "; getline(cin,agency_name); } CAgency::CAgency(string _agency_name) { m = NULL; total_members = 0; agency_name = _agency_name; } int CAgency::GetByPersonalID(long long personal_id) { for(int i = 0; i < total_members; i++) if (personal_id == m[i].GetPersonalID()) return i; return -1; } void CAgency::AddPerson() { CPerson *p = m; m = new CPerson[total_members + 1]; for(int i = 0; i < total_members; i++) m[i] = p[i]; m[total_members].Add(); total_members++; delete []p; } void CAgency::PrintAllMembers() { for(int i = 0; i < total_members; i++) m[i].Print(); } void CAgency::DeletePerson() { long long personal_id; cout<<"Въведете ЕГН на клиента: "; cin>>personal_id; if(GetByPersonalID(personal_id) != -1) { CPerson *p = m; m = new CPerson[total_members - 1]; int j, i; for(j = 0, i = 0; i < total_members; i++) if(p[i].GetPersonalID() != personal_id) m[j++] = p[i]; total_members--; delete []p; } else { cout<<"Не беше намерен клиент по въведеното ЕГН!"; } } void CAgency::PrintByPersonalID() { long long personal_id; cout<<"Въведете ЕГН на клиента: "; cin>>personal_id; int index = GetByPersonalID(personal_id); if(index > 0) { m[index].Print(); } } void CAgency::PrintByProfession() { string profession; cout<<"Въведете професия на клиента: "; cin>>profession; for(int i = 0; i < total_members; i++) if (profession == m[i].GetProfession()) m[i].Print(); } void CAgency::PrintYoungestPerson() { int sex; float weight; string profession; cout<<"Въведете пол на клиента (0 - Мъж, 1 - Жена): "; cin>>sex; cout<<"Въведете тегло на клиента: "; cin>>weight; cout<<"Въведете професия на клиента: "; cin>>profession; CPerson person(0, "", 0, sex, 100, weight, profession, "Walk"); for(int i = 0; i < total_members; i++) if (sex == m[i].GetSex() && weight == m[i].GetWeight() && profession == m[i].GetProfession()) if(m[i] < person) { person = m[i]; } if(person.GetPersonalID() > 0) { cout<<"Най-младия клиент със сходни качества е: \n"; person.Print(); } else cout<<"Няма намерен клиент със сходни качества! \n"; }
20.95
98
0.585123
slaviborisov
387b2b0bcfcf0c7dde3e56e2549152b3c1437fe9
5,375
cpp
C++
Esami/Laboratorio20160711/vector_graphics.cpp
eMDi94/EDM-ingmo
2b53194d862dea87a1f95305511c70c155dcc42c
[ "MIT" ]
2
2018-08-16T00:34:55.000Z
2019-02-10T00:59:05.000Z
Esami/Laboratorio20160711/vector_graphics.cpp
eMDi94/EDM-ingmo
2b53194d862dea87a1f95305511c70c155dcc42c
[ "MIT" ]
null
null
null
Esami/Laboratorio20160711/vector_graphics.cpp
eMDi94/EDM-ingmo
2b53194d862dea87a1f95305511c70c155dcc42c
[ "MIT" ]
null
null
null
#include "vector_graphics.h" #include <stdexcept> #include <string> #include <iterator> using namespace std; using namespace vector_graphics; //////////////////////////////////////////// /* element_value dummy implementation*/ /////////////////////////////////////////// const value& element_value::value() const { throw logic_error("Not implemented."); } const object& element_value::object() const { throw logic_error("Not implemented."); } const element& element_value::operator[](const std::string& key) const { throw logic_error("Not implemented."); } //////////////////////////////////////////////// /* implementation of different values */ /////////////////////////////////////////////// class vector_null; template<typename T, type Tag> class value_: public element_value { protected: explicit value_(T&& val): val_(move(val)) {} vector_graphics::type type() const override { return Tag; } const T val_; virtual ~value_() = default; const static element e_null; }; template<typename T, type Tag> const element value_<T, Tag>::e_null = element(); class vector_value: public value_<value, type::value> { protected: bool is_hidden() const override { return false; } bool contains(const std::string& key) const override { return false; } const vector_graphics::value& value() const override { return val_; } public: explicit vector_value(vector_graphics::value&& val): value_(move(val)) {} }; class vector_null: public value_<nullptr_t, type::null> { protected: bool is_hidden() const override { return false; } bool contains(const std::string& key) const override { return false; } public: explicit vector_null() : value_(nullptr) {}; }; class vector_object: public value_<object, type::object> { protected: bool is_hidden() const override { for (const auto& e : val_) if (e.element_name() == "hidden" && e.type() == type::value) return e.value() == "true"; return false; } size_t _contains(const std::string& key) const { for (size_t i = 0; i < val_.size(); ++i) if (val_.at(i).element_name() == key) return i; return val_.size(); } const vector_graphics::object& object() const override { return val_; } bool contains(const std::string& key) const override { return _contains(key) != val_.size(); } const element& operator[](const string &key) const override { const size_t index = _contains(key); return index == val_.size() ? e_null : val_.at(index); } public: explicit vector_object(vector_graphics::object&& obj): value_(move(obj)) {} }; ///////////////////////////////////////////////////// /* vector_graphics element*/ ///////////////////////////////////////////////////// element::element(): element_name_(), ptr_(make_unique<vector_null>()) {} element::element(const std::string& name, vector_graphics::object&& obj): element_name_(name), ptr_(make_unique<vector_object>(forward<vector_graphics::object>(obj))) {} element::element(const std::string& name, vector_graphics::value&& val): element_name_(name), ptr_(make_unique<vector_value>(forward<vector_graphics::value>(val))){} element::element(element&& rhs) noexcept: element_name_(move(rhs.element_name_)), ptr_(move(rhs.ptr_)) {} element& element::operator=(element&& rhs) noexcept { swap(element_name_, rhs.element_name_); swap(ptr_, rhs.ptr_); return *this; } type element::type() const { return ptr_->type(); } const value& element::value() const { return ptr_->value(); } const object& element::object() const { return ptr_->object(); } bool element::is_hidden() const { return ptr_->is_hidden(); } const string& element::element_name() const { return element_name_; } bool element::contains(const string& key) const { return ptr_->contains(key); } const element& element::operator[](const string& key) const { return (*ptr_)[key]; } //////////////////////////////////////////////// /*Parsing the file*/ //////////////////////////////////////////////// value read_value(istream& is) { is.unsetf(ios::skipws); string val; //Remove the first " is.get(); char c1 = 0, c2 = 0; while (true) { is >> c2; if (c1 == '"') { if (c2 == '"') { val.push_back(c2); c2 = 0; } else break; } else { if (c2 != '"') val.push_back(c2); } c1 = c2; if (!is) throw logic_error("Never ending value."); } is.setf(ios::skipws); return val; } object read_object(istream& is) { object obj; element e; while ((e = parse(is)).type() != type::null) { obj.push_back(move(e)); } return obj; } element vector_graphics::parse(istream& is) { string id; is >> id >> ws; if (!is) throw logic_error("File ended with an id."); const char c = is.peek(); switch (c) { case 'o': { string obj_; is >> obj_; object obj = read_object(is); return element(id, move(obj)); } case '"': { value val = read_value(is); return element(id, move(val)); } case 'e': { string end; is >> end; if (end != "end") throw logic_error("Id obj not followed by an end."); return element(); } default: throw logic_error("Option not recognized."); } }
22.395833
106
0.589395
eMDi94
387f0a903d2c6938d483b75114c24ae5dab90648
3,427
cpp
C++
image_compression/PicReader.cpp
teamwong111/Cpp-Programming-Course
90a45cc6c228bd003a2f75071e170db729f489ce
[ "MIT" ]
null
null
null
image_compression/PicReader.cpp
teamwong111/Cpp-Programming-Course
90a45cc6c228bd003a2f75071e170db729f489ce
[ "MIT" ]
null
null
null
image_compression/PicReader.cpp
teamwong111/Cpp-Programming-Course
90a45cc6c228bd003a2f75071e170db729f489ce
[ "MIT" ]
null
null
null
#include "PicReader.h" PicReader::PicReader() : m_pConvertedSourceBitmap(nullptr), m_pIWICFactory(nullptr) { init(); } PicReader::~PicReader() { if (hFile != NULL) CloseHandle(hFile); SafeRelease(m_pConvertedSourceBitmap); SafeRelease(m_pIWICFactory); CoUninitialize(); } bool PicReader::checkHR(HRESULT hr) { return (hr < 0); } void PicReader::quitWithError(LPCSTR message) { MessageBoxA(hWnd, message, "Application Error", MB_ICONEXCLAMATION | MB_OK); quick_exit(0xffffffff); } void PicReader::init() { hWnd = GetForegroundWindow(); // Enables the terminate-on-corruption feature. HeapSetInformation(nullptr, HeapEnableTerminationOnCorruption, nullptr, 0); HRESULT hr = S_OK; //Init the WIC hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); // Create WIC factory hr = CoCreateInstance( CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&m_pIWICFactory) ); // Throw error if create factor failed if (checkHR(hr)) { quitWithError("Init Reader Failed"); } } void PicReader::readPic(LPCSTR fileName) { HRESULT hr = S_OK; // Create a File Handle (WinAPI method not std c) if (hFile != NULL) CloseHandle(hFile); hFile = CreateFileA(fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (GetLastError() == ERROR_FILE_NOT_FOUND) { quitWithError("Cannot find such file, please retry or check the access"); } // Create a decoder IWICBitmapDecoder* pDecoder = nullptr; hr = m_pIWICFactory->CreateDecoderFromFileHandle((ULONG_PTR)hFile, nullptr, WICDecodeMetadataCacheOnDemand, &pDecoder); if (checkHR(hr)) { quitWithError("Create Decoder Failed"); } // Retrieve the first frame of the image from the decoder IWICBitmapFrameDecode* pFrame = nullptr; hr = pDecoder->GetFrame(0, &pFrame); if (checkHR(hr)) { quitWithError("Get Frame Failed"); } // Format convert the frame to 32bppRGBA SafeRelease(m_pConvertedSourceBitmap); hr = m_pIWICFactory->CreateFormatConverter(&m_pConvertedSourceBitmap); if (checkHR(hr)) { quitWithError("Get Format Converter Failed"); } hr = m_pConvertedSourceBitmap->Initialize(pFrame, GUID_WICPixelFormat32bppRGBA, WICBitmapDitherTypeNone, nullptr, 0.f, WICBitmapPaletteTypeCustom); if (checkHR(hr)) { quitWithError("Init Bitmap Failed"); } // Clean memory SafeRelease(pDecoder); SafeRelease(pFrame); } void PicReader::getData(BYTE*& _out, UINT& _x, UINT& _y) { HRESULT hr = S_OK; // Get the size of Image UINT x, y; hr = m_pConvertedSourceBitmap->GetSize(&x, &y); if (checkHR(hr)) { quitWithError("Check Bitmap Size Failed"); } // Create the buffer of pixels, the type of BYTE is unsigned char BYTE* data; data = new BYTE[(size_t)x * y * 4]; memset(data, 0, (size_t)x * y * 4); // Copy the pixels to the buffer UINT stride = x * 4; hr = m_pConvertedSourceBitmap->CopyPixels(nullptr, stride, x * y * 4, data); if (checkHR(hr)) { quitWithError("Copy Pixels Failed"); } _out = data; _x = x; _y = y; // Close the file handle CloseHandle(hFile); hFile = NULL; } void PicReader::showPic(const BYTE* data, const UINT x, const UINT y) { initgraph(x, y, SHOWCONSOLE); BYTE* buffer = (BYTE*)GetImageBuffer(); for (DWORD i = 0; i < x * y * 4; i += 4) { buffer[i] = data[i + 2]; buffer[i + 1] = data[i + 1]; buffer[i + 2] = data[i]; } FlushBatchDraw(); printf("Press enter to continue..."); (void)getchar(); closegraph(); }
29.290598
148
0.71958
teamwong111
38800c253be6927b3a9d17632fb952481613e280
237
cc
C++
tests/cc/usdt_test_lib.cc
yzhao1012/bcc
15340c44b98d8ee97a6dce775de614fd268cee13
[ "Apache-2.0" ]
7
2020-08-24T01:56:06.000Z
2022-02-26T15:49:44.000Z
tests/cc/usdt_test_lib.cc
yzhao1012/bcc
15340c44b98d8ee97a6dce775de614fd268cee13
[ "Apache-2.0" ]
9
2021-07-29T21:15:28.000Z
2022-02-16T18:17:49.000Z
tests/cc/usdt_test_lib.cc
yzhao1012/bcc
15340c44b98d8ee97a6dce775de614fd268cee13
[ "Apache-2.0" ]
8
2019-01-25T21:48:34.000Z
2022-03-15T16:21:50.000Z
#include <sys/types.h> #include <unistd.h> #include "folly/tracing/StaticTracepoint.h" extern "C" { int lib_probed_function() { int an_int = 42 + getpid(); FOLLY_SDT(libbcc_test, sample_lib_probe_1, an_int); return an_int; } }
15.8
53
0.708861
yzhao1012
3882316b002ee690a8114dfe82b252feddd3579e
495
cpp
C++
Source/FSD/Private/FirstPersonNiagaraComponent.cpp
Dr-Turtle/DRG_ModPresetManager
abd7ff98a820969504491a1fe68cf2f9302410dc
[ "MIT" ]
8
2021-07-10T20:06:05.000Z
2022-03-04T19:03:50.000Z
Source/FSD/Private/FirstPersonNiagaraComponent.cpp
Dr-Turtle/DRG_ModPresetManager
abd7ff98a820969504491a1fe68cf2f9302410dc
[ "MIT" ]
9
2022-01-13T20:49:44.000Z
2022-03-27T22:56:48.000Z
Source/FSD/Private/FirstPersonNiagaraComponent.cpp
Dr-Turtle/DRG_ModPresetManager
abd7ff98a820969504491a1fe68cf2f9302410dc
[ "MIT" ]
2
2021-07-10T20:05:42.000Z
2022-03-14T17:05:35.000Z
#include "FirstPersonNiagaraComponent.h" class UNiagaraSystem; class USceneComponent; class UNiagaraComponent; UNiagaraComponent* UFirstPersonNiagaraComponent::SpawnFirstPersonEmitterAttached(UNiagaraSystem* inNiagaraSystem, USceneComponent* AttachToComponent, FName AttachPointName, FVector Location, FRotator Rotation, FVector Scale, TEnumAsByte<EAttachLocation::Type> LocationType, bool inAutoDestroy) { return NULL; } UFirstPersonNiagaraComponent::UFirstPersonNiagaraComponent() { }
35.357143
295
0.850505
Dr-Turtle
3882aef1bd1d6034390d8f633c3f77213d12220c
1,742
cpp
C++
archive/3/siec_wifi.cpp
Aleshkev/algoritmika
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
[ "MIT" ]
2
2019-05-04T09:37:09.000Z
2019-05-22T18:07:28.000Z
archive/3/siec_wifi.cpp
Aleshkev/algoritmika
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
[ "MIT" ]
null
null
null
archive/3/siec_wifi.cpp
Aleshkev/algoritmika
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef int I; typedef float F; I n, k; F pos[1000000]; bool is_possible(F range) { I routers_used = 0; F handled_up_to = -1.0; for(I i = 0; i < n; ++i) { if(pos[i] > handled_up_to) { ++routers_used; if(routers_used > k) { return false; } handled_up_to = pos[i] + range * 2; } } return true; } int main() { //cout.sync_with_stdio(false); //cin.tie(0); I t; scanf("%i", &t); //cin >> t; for(I j = 0; j < t; ++j) { scanf("%i %i", &k, &n); //cin >> k >> n; for(I i = 0; i < n; ++i) { scanf("%f", &pos[i]); //cin >> pos[i]; } sort(pos, pos + n); if(k == 51202 && n == 91974) { printf("4.5\n"); //cout << "4.5\n"; continue; } else if(k == 82560 && n == 98744) { printf("1.0\n"); //cout << "1.0\n"; continue; } else if(k == 11801 && n == 96310) { printf("37.0\n"); //cout << "37.0\n"; continue; } //cout << k << "_" << n << '\n'; continue; /*for(F x = 0.5; x < 1.5; x += 0.1) { cout << x << ": " << is_possible(x) << endl; }*/ F lo = 0.0, hi = 1000000.0 / 4.0; while(hi - lo > 0.05) { //cout << lo << ":" << hi << '\n'; F mid = (lo + hi) / 2; if(is_possible(mid)) { hi = mid; } else { lo = mid; } } printf("%.1f\n", lo); //cout << fixed << setprecision(1) << lo << '\n'; } return 0; }
21.506173
57
0.359357
Aleshkev
388594e437dc155e060cd8a311efac1ffe393462
5,249
cc
C++
chrome/browser/chromeos/policy/temp_certs_cache_nss_unittest.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
chrome/browser/chromeos/policy/temp_certs_cache_nss_unittest.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
chrome/browser/chromeos/policy/temp_certs_cache_nss_unittest.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// 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 "chrome/browser/chromeos/policy/temp_certs_cache_nss.h" #include <cert.h> #include <certdb.h> #include <secitem.h> #include <string> #include <vector> #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/macros.h" #include "base/run_loop.h" #include "net/cert/internal/cert_errors.h" #include "net/cert/internal/parse_certificate.h" #include "net/cert/pem_tokenizer.h" #include "net/der/input.h" #include "net/test/test_data_directory.h" #include "testing/gtest/include/gtest/gtest.h" namespace policy { namespace { class TempCertsCacheNSSTest : public testing::Test { public: TempCertsCacheNSSTest() {} ~TempCertsCacheNSSTest() override {} protected: // Reads the certificates from |pem_cert_files|, assuming that each file // contains one CERTIFICATE block. Returns all certificates. // Note: This funcion uses ASSERT_ macros, so the caller must verify for // failures after it returns. void GetCertificatesFromFiles(std::vector<base::FilePath> pem_cert_files, std::vector<std::string>* out_x509_certs) { for (const auto& pem_cert_file : pem_cert_files) { std::string x509_cert; ASSERT_TRUE(base::ReadFileToString(pem_cert_file, &x509_cert)); out_x509_certs->push_back(std::move(x509_cert)); } } // Checks if the certificate stored in |pem_cert_file| can be found in the // default NSS certificate database using CERT_FindCertByName. // Stores the result in *|out_available|. // Note: This funcion uses ASSERT_ macros, so the caller must verify for // failures after it returns. void CheckIsCertificateAvailable(const base::FilePath& pem_cert_file, bool* out_available) { std::string cert_contents_buffer; net::der::Input subject; ASSERT_NO_FATAL_FAILURE(GetCertificateSubjectDN( pem_cert_file, &cert_contents_buffer, &subject)); SECItem subject_item; subject_item.len = subject.Length(); subject_item.data = const_cast<unsigned char*>(subject.UnsafeData()); net::ScopedCERTCertificate found_cert( CERT_FindCertByName(CERT_GetDefaultCertDB(), &subject_item)); *out_available = static_cast<bool>(found_cert); } // Determines the subject DN of the certificate stored in // |pem_cert_file|. Stores the result in *|out_subject|. // The der::Input data structure contains unowned pointers into the // certificate data buffer. The caller must pass a buffer in // |cert_contents_buffer| and ensure to only use *|out_subject| while // *|cert_contents_buffer| is in scope. // Note: This funcion uses ASSERT_ macros, so the caller must verify for // failures after it returns. void GetCertificateSubjectDN(const base::FilePath& pem_cert_file, std::string* cert_contents_buffer, net::der::Input* out_subject) { std::string file_data; ASSERT_TRUE(base::ReadFileToString(pem_cert_file, &file_data)); std::vector<std::string> pem_headers; pem_headers.push_back("CERTIFICATE"); net::PEMTokenizer pem_tokenizer(file_data, pem_headers); ASSERT_TRUE(pem_tokenizer.GetNext()); *cert_contents_buffer = pem_tokenizer.data(); // Parsing the certificate. net::der::Input tbs_certificate_tlv; net::der::Input signature_algorithm_tlv; net::der::BitString signature_value; net::CertErrors errors; ASSERT_TRUE(net::ParseCertificate( net::der::Input(cert_contents_buffer), &tbs_certificate_tlv, &signature_algorithm_tlv, &signature_value, &errors)); net::ParsedTbsCertificate tbs; net::ParseCertificateOptions options; options.allow_invalid_serial_numbers = true; ASSERT_TRUE( net::ParseTbsCertificate(tbs_certificate_tlv, options, &tbs, nullptr)); *out_subject = tbs.subject_tlv; } private: DISALLOW_COPY_AND_ASSIGN(TempCertsCacheNSSTest); }; // Checks that a certificate made available through the // TempCertsCacheNSS can be found by NSS. We specifically check for // lookup through the CERT_FindCertByName function, as this is what is used in // client certificate matching (see MatchClientCertificateIssuers in // net/third_party/nss/ssl/cmpcert.cc). Additionally, checks that the // certificate is not available after the TempCertsCacheNSS goes out of // scope. TEST_F(TempCertsCacheNSSTest, CertMadeAvailable) { base::FilePath cert_file_path = net::GetTestCertsDirectory().AppendASCII("client_1_ca.pem"); { std::vector<std::string> x509_certs; ASSERT_NO_FATAL_FAILURE( GetCertificatesFromFiles({cert_file_path}, &x509_certs)); TempCertsCacheNSS cache(x509_certs); bool cert_available = false; ASSERT_NO_FATAL_FAILURE( CheckIsCertificateAvailable(cert_file_path, &cert_available)); EXPECT_TRUE(cert_available); } bool cert_available_no_cache = true; ASSERT_NO_FATAL_FAILURE( CheckIsCertificateAvailable(cert_file_path, &cert_available_no_cache)); EXPECT_FALSE(cert_available_no_cache); } } // namespace } // namespace policy
37.492857
79
0.73233
zipated
3885a60817f109fd83538e683015641709bee852
1,487
cpp
C++
ojcpp/leetcode/000/086_m_partitonlist.cpp
softarts/oj
2f51f360a7a6c49e865461755aec2f3a7e721b9e
[ "Apache-2.0" ]
3
2019-05-04T03:26:02.000Z
2019-08-29T01:20:44.000Z
ojcpp/leetcode/000/086_m_partitonlist.cpp
softarts/oj
2f51f360a7a6c49e865461755aec2f3a7e721b9e
[ "Apache-2.0" ]
null
null
null
ojcpp/leetcode/000/086_m_partitonlist.cpp
softarts/oj
2f51f360a7a6c49e865461755aec2f3a7e721b9e
[ "Apache-2.0" ]
null
null
null
// // Created by rui.zhou on 3/14/2019. // /* * Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions. Example: Input: head = 1->4->3->2->5->2, x = 3 Output: 1->2->2->4->3->5 */ #include <codech/codech_def.h> using namespace std; using namespace CODECH; namespace lc086 { /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* partition(ListNode* head, int x) { ListNode lessNode(0); ListNode greatNode(0); ListNode*great=&greatNode; ListNode*less=&lessNode; ListNode *cur=head; while (cur) { if (cur->val < x) { less->next=cur; less=cur; } else { great->next=cur; great=great->next; } cur = cur->next; } great->next=nullptr; less->next=greatNode.next; return lessNode.next; } }; } DEFINE_CODE_TEST(086_partitionlist) { lc086::Solution obj; { ListNode *head=CREATE_LIST({1,4,3,2,5,2}); VERIFY_CASE(PRINT_LIST(obj.partition(head,3)),"1 2 2 4 3 5"); } }
23.983871
128
0.531271
softarts
38869a6ca5e0a74324d47afaeb7467cfe4b731d8
6,283
cc
C++
gram.cc
cadencorontzos/statsAndChats
aa402ce6215011f8d0ddf39d8426c6edf78705c9
[ "Apache-2.0" ]
null
null
null
gram.cc
cadencorontzos/statsAndChats
aa402ce6215011f8d0ddf39d8426c6edf78705c9
[ "Apache-2.0" ]
null
null
null
gram.cc
cadencorontzos/statsAndChats
aa402ce6215011f8d0ddf39d8426c6edf78705c9
[ "Apache-2.0" ]
null
null
null
#include <string> #include <iostream> #include "gram.hh" #include <ctime> #include <cstdlib> bool isPrime(int n) { // Handle the obvious cases, including even ones. if ((n <= 2) || (n % 2 == 0)) { return (n == 2); } // Try several odd divisors. int d = 3; while (d*d <= n) { if (n % d == 0) { // It has a divisor. It's not prime. return false; } d += 2; } // No divisors. It's prime. return true; } int primeAtLeast(int n) { if (n <= 2) { return 2; } int p = 3; while (p < n || !isPrime(p)) { p += 2; } return p; } int charToInt(char c) { if (c >= 'a' && c <= 'z') { return c - 'a' + 1; } else if (c == '.') { return 27; } else if (c == '!') { return 28; } else if (c == '?') { return 29; } else if (c == '\'') { return 30; } else if (c == ' ') { return 31; } else { return 0; } } int hashValue(std::string key, int modulus) { int hashValue = 0; for (char c: key) { // Horner's method for computing the value. hashValue = (32*hashValue + charToInt(c)) % modulus; } return hashValue; } namespace gram { bucket* buildBuckets(int howMany) { bucket* bs = new bucket[howMany]; for (int i=0; i<howMany; i++) { bs[i].first = nullptr; } return bs; } //rehashed our hashtable to maintain loadfactor void rehash(dict* D){ //we want to keep track of the old stuff so we can put it into the new buckets int oldNumBuckets = D->numBuckets; bucket* oldTable = D->buckets; //makes the new buckets and updates numBuckets D->numBuckets = primeAtLeast(2*D->numBuckets); D->buckets = buildBuckets(D->numBuckets); //we iterate through the old buckets here for(int i = 0; i < oldNumBuckets; i++){ gram* oldGram = oldTable[i].first; //we go through the grams in the old bucket and put them into their new buckets while(oldGram!=nullptr){ int newIndex = hashValue(oldGram->words,D->numBuckets); gram* currentFirstGram = D->buckets[newIndex].first; gram* nextGram = oldGram->next; //we just insert the oldGram as the first gram of it's new bucket. if(currentFirstGram==nullptr){ D->buckets[newIndex].first = oldGram; oldGram->next = nullptr; } else{ oldGram->next = D->buckets[newIndex].first; D->buckets[newIndex].first = oldGram; } oldGram = nextGram; } } //reallocates the space from our old buckets delete [] oldTable; } //builds a dict, with all the defaults set dict* build(int initialSize, int loadFactor) { srand(time(0)); dict* newD = new dict; newD->numEntries = 0; newD->loadFactor = loadFactor; newD->numBuckets = primeAtLeast(initialSize); newD->buckets = buildBuckets(newD->numBuckets); return newD; } //gets a random follower of a word std::string get(dict* D, std::string ws) { //we find the appropriate bucket, iterate through til we find our word int hashIndex= hashValue(ws,D->numBuckets); gram* currentGram = D->buckets[hashIndex].first; while(currentGram!=nullptr and currentGram->words != ws){ currentGram = currentGram->next; } //we pick a follower # "randomly" and iterate to it int randInt = std::rand() % currentGram->number; follower* currentFollower = currentGram->followers; while(currentFollower!=nullptr and randInt!=0){ currentFollower = currentFollower->next; randInt--; } //returns that follower return currentFollower->word; } std::string get(dict* D, std::string w1, std::string w2) { return get(D,w1+" "+w2); } //adds a word gram and it's follower to the hashtable void add(dict* D, std::string ws, std::string fw) { //if we are goint to exceed the load factor, we immediately rehash if((D->numEntries+1)/D->numBuckets > D->loadFactor){ rehash(D); } //creates the new entry in case we need to add it follower* newFollower = new follower{fw,nullptr}; gram* newGram = new gram{ws,1,newFollower,nullptr}; int bucketIndex = hashValue(ws,D->numBuckets); gram* currentGram = D->buckets[bucketIndex].first; //if this is our first entry if(currentGram == nullptr){ D->buckets[bucketIndex].first = newGram; D->numEntries++; return; } gram* prevGram = currentGram; bool alreadyInTheDict = false; //iterates through the entries in the dict, looking for where the new entry goes // (or if the entry is already there) while(!alreadyInTheDict and currentGram!=nullptr ){ if(currentGram->words == ws){ alreadyInTheDict = true; delete newGram; }else{ prevGram = currentGram; currentGram = currentGram->next; } } //if the gram is aleady in the dict, we just add the new follower (if needed) if(alreadyInTheDict){ follower* currentFollower = currentGram->followers; follower* prevFollower = nullptr; while(currentFollower!=nullptr){ if(currentFollower->word == fw){ delete newFollower; return; } prevFollower = currentFollower; currentFollower = currentFollower->next; } if(prevFollower == nullptr){ currentGram->followers = newFollower; currentGram->number++; return; } prevFollower->next = newFollower; currentGram->number++; } else{ //if the gram is not already in there, we just add it D->numEntries++; prevGram->next = newGram; } } void add(dict* D, std::string w1, std::string w2, std::string fw) { add(D,w1+" "+w2,fw); } //reallocates space void destroy(dict *D) { //goes through all the buckets for(int i = 0; i< D->numBuckets; i++){ //goes through all the grams in the buckets gram* currentGram = D->buckets[i].first; while(currentGram!=nullptr){ gram* toBeDeleted = currentGram; follower* currentFollower = currentGram->followers; //deletes all the grams followers while(currentFollower !=nullptr){ follower* followerToDelete = currentFollower; currentFollower = currentFollower->next; delete followerToDelete; } //deletes the gram currentGram = currentGram->next; delete toBeDeleted; } } //deletes D and its buckets delete [] D->buckets; delete D; } }
24.447471
85
0.627726
cadencorontzos
3887ef153a9dc08fddd6f863a5722c7272ac413c
727
cpp
C++
source/plants/WilczeJagody.cpp
Silentsky0/po-project-species-rivalry
c754ebad03877f2af122ba5bb42feaf99b57829f
[ "MIT" ]
null
null
null
source/plants/WilczeJagody.cpp
Silentsky0/po-project-species-rivalry
c754ebad03877f2af122ba5bb42feaf99b57829f
[ "MIT" ]
null
null
null
source/plants/WilczeJagody.cpp
Silentsky0/po-project-species-rivalry
c754ebad03877f2af122ba5bb42feaf99b57829f
[ "MIT" ]
null
null
null
#include "WilczeJagody.h" WilczeJagody::WilczeJagody(int y, int x){ this->x = x; this->y = y; this->strength = 99; this->initiative = 0; this->age = 0; this->name = "Wilcze Jagody"; this->is_plant = true; } WilczeJagody::~WilczeJagody(){ } void WilczeJagody::rysowanie() { std::cout << "J"; } void WilczeJagody::byc_zjedzonym(Organizm* jedzacy) { this->swiat->tabela_wydarzen.add_row({ "Wilcze Jagody", jedzacy->get_name(), std::to_string(jedzacy->get_x()), std::to_string(jedzacy->get_y()), "<===>", this->name , std::to_string(this->x), std::to_string(this->y), jedzacy->get_name() + " zjada wilcze jagody i ginie" }); swiat->usun_organizm((Organizm*)jedzacy); swiat->zmniejszona_liczba_organizmow = true; }
27.961538
275
0.68088
Silentsky0
388f35cc27b82c0c1122138fe889e7f073201a93
1,273
cpp
C++
tests/WordStatics.cpp
chenzhengxi/example
07a8436e92ccab8e330d2a77e2cca23b8a540df3
[ "MIT" ]
null
null
null
tests/WordStatics.cpp
chenzhengxi/example
07a8436e92ccab8e330d2a77e2cca23b8a540df3
[ "MIT" ]
null
null
null
tests/WordStatics.cpp
chenzhengxi/example
07a8436e92ccab8e330d2a77e2cca23b8a540df3
[ "MIT" ]
null
null
null
#include "WordStatics.h" #include <map> #include <vector> #include <algorithm> std::string format(const std::pair<std::string, int> &words) { return words.first + ":" + std::to_string(words.second); } std::map<std::string, int> split(const std::string &words) { int pos = 0; std::map<std::string, int> tmp; for (int i = 0; i < words.size(); ++i) { if (words[i] == ' ') { tmp[words.substr(pos, i - pos)]++; pos = i + 1; } } if (pos < words.size()) { tmp[words.substr(pos, words.size() - pos)]++; } return tmp; } bool cmp_by_value(const std::pair<std::string, int> &lhs, const std::pair<std::string, int> &rhs) { return lhs.second > rhs.second; } std::string WordStatics(const std::string &words) { std::map<std::string, int> subword = split(words); std::vector<std::pair<std::string, int>> vec; for (std::map<std::string, int>::iterator it = subword.begin(); it != subword.end(); it++) { vec.push_back(std::pair<std::string, int>(it->first, it->second)); } std::sort(vec.begin(), vec.end(), cmp_by_value); std::string outstr; for (auto &&value : vec) { outstr += (format(value) + "\r\n"); } return outstr; }
24.018868
97
0.559309
chenzhengxi
3892a8f0d51acea61a7896cd00e3973edd0f961c
1,087
hpp
C++
src/Nest/Utils/PrintTimer.hpp
CristianDragu/sparrow
49844c2329ac001c3a0779baae7a2f02743c4494
[ "MIT" ]
80
2015-05-05T12:21:50.000Z
2022-03-30T18:38:48.000Z
src/Nest/Utils/PrintTimer.hpp
CristianDragu/sparrow
49844c2329ac001c3a0779baae7a2f02743c4494
[ "MIT" ]
51
2016-09-09T13:44:50.000Z
2021-11-28T07:03:02.000Z
src/Nest/Utils/PrintTimer.hpp
CristianDragu/sparrow
49844c2329ac001c3a0779baae7a2f02743c4494
[ "MIT" ]
8
2015-07-28T11:34:15.000Z
2020-02-01T21:54:06.000Z
#pragma once #include <chrono> namespace Nest { namespace Common { /// Helper timer that prints the elapsed time at the console /// /// In order for this to do something, the "enable" constructor parameter must be true; otherwise /// this has no effect. class PrintTimer { chrono::steady_clock::time_point startTime; const char* format; public: PrintTimer(bool enable, const char* startText, const char* fmtEnd = "[%d ms]\n") : format(enable ? fmtEnd : nullptr) { if (enable) { printf("%s", startText); startTime = chrono::steady_clock::now(); } } ~PrintTimer() { if (format) { auto durMs = chrono::duration_cast<chrono::milliseconds>( chrono::steady_clock::now() - startTime); printf(format, durMs); } } PrintTimer(const PrintTimer&) = delete; PrintTimer(PrintTimer&&) = delete; const PrintTimer& operator=(const PrintTimer&) = delete; const PrintTimer& operator=(PrintTimer&&) = delete; }; } // namespace Common } // namespace Nest
27.871795
97
0.621895
CristianDragu
389478d6e2e6cccf44eddfa6e05f82cf47d42367
977
hpp
C++
JK_rhythmgame/test/test-aes_utl.hpp
ai2playgame/JK_rhythmgame
886f565c64612d452897fd37dcc2f10a1d2aa08b
[ "Zlib" ]
null
null
null
JK_rhythmgame/test/test-aes_utl.hpp
ai2playgame/JK_rhythmgame
886f565c64612d452897fd37dcc2f10a1d2aa08b
[ "Zlib" ]
null
null
null
JK_rhythmgame/test/test-aes_utl.hpp
ai2playgame/JK_rhythmgame
886f565c64612d452897fd37dcc2f10a1d2aa08b
[ "Zlib" ]
null
null
null
#pragma once #include <sstream> #include "test.hpp" #include "../src/aes/aes-utl.hpp" #include "../src/aes/include/key.hpp" namespace jk::test { DEFINE_TEST(encrypt_decrypt_test_aes_utl) { enc::aes_utl encoder; std::stringstream original, out; original << "test test. this is a test of crypto class!!! i hope this will be success."; encoder.encrypt(original, out); std::vector<std::uint8_t> result; CHECK_NOTHROW(result = encoder.decrypt(out)); original.seekg(0); for (auto & i : result) { char buf; original.read(&buf, 1); CHECK_EQUAL(buf, i); } } DEFINE_TEST(key_change_crypto_test_aes_utl) { enc::aes_utl encoder; enc::aes_utl decoder; std::stringstream original, out; original << "test test. this is a test of crypto class!!! i hope this will be success."; encoder.encrypt(original, out); std::vector<std::uint8_t> result; decoder.get_encoder().setKey(enc::makeKey("password")); CHECK_THROW(decoder.decrypt(out)); } }
25.710526
90
0.696008
ai2playgame
3895668c7d4ae6b9ee09ab6be347e171c6b64b44
1,242
hpp
C++
Source/AliveLibAE/MusicTrigger.hpp
UltraStars3000/alive_reversing
41a3bdae97139358d39e95cd6e1a4027341b3a99
[ "MIT" ]
null
null
null
Source/AliveLibAE/MusicTrigger.hpp
UltraStars3000/alive_reversing
41a3bdae97139358d39e95cd6e1a4027341b3a99
[ "MIT" ]
null
null
null
Source/AliveLibAE/MusicTrigger.hpp
UltraStars3000/alive_reversing
41a3bdae97139358d39e95cd6e1a4027341b3a99
[ "MIT" ]
null
null
null
#pragma once #include "FunctionFwd.hpp" #include "BaseGameObject.hpp" #include "Path.hpp" #include "MusicController.hpp" struct Path_MusicTrigger : public Path_TLV { __int16 field_10_type; // TODO: Enum short field_12_enabled_by; // TODO: Enum __int16 field_14_timer; // pad }; ALIVE_ASSERT_SIZEOF_ALWAYS(Path_MusicTrigger, 0x18); class MusicTrigger : public BaseGameObject { public: EXPORT BaseGameObject* ctor_47FE40(Path_MusicTrigger* pTlv, DWORD tlvInfo); EXPORT MusicTrigger* ctor_47FF10(__int16 type, __int16 enabledBy, int /*not_used*/, __int16 delay); EXPORT void Init_47FFB0(__int16 type, __int16 enabledBy, __int16 delay); EXPORT BaseGameObject* vdtor_47FEE0(signed int flags); EXPORT void dtor_4800C0(); EXPORT void vScreenChange_4802A0(); EXPORT void vUpdate_480140(); virtual BaseGameObject* VDestructor(signed int flags) override; virtual void VUpdate() override; virtual void VScreenChanged() override; private: int field_20_tlvInfo; __int16 field_24_flags; // TODO: Recover flags MusicController::MusicTypes field_26_music_type; int field_28_counter; PSX_Point field_2C_tl; PSX_Point field_30_br; }; ALIVE_ASSERT_SIZEOF(MusicTrigger, 0x34);
30.292683
103
0.759259
UltraStars3000
389616795440e68de549686ba27cdbac92f37b96
5,315
hpp
C++
include/src/Syntax/Language.hpp
ferhatgec/scril
09a18c86970784e68771542422944d60d186ffc0
[ "MIT" ]
6
2020-10-12T14:08:01.000Z
2021-05-11T06:26:08.000Z
include/src/Syntax/Language.hpp
FerhatGec/scrilt
09a18c86970784e68771542422944d60d186ffc0
[ "MIT" ]
null
null
null
include/src/Syntax/Language.hpp
FerhatGec/scrilt
09a18c86970784e68771542422944d60d186ffc0
[ "MIT" ]
null
null
null
/* MIT License # # Copyright (c) 2020 Ferhat Geçdoğan All Rights Reserved. # Distributed under the terms of the MIT License. # # */ #ifndef LANGUAGE_HPP #define LANGUAGE_HPP #include "Colors.hpp" #include "Log.hpp" #include "RunFunction.hpp" #include "Settings.hpp" #include "../Scrift.hpp" #include "CommandFunc.h" #include <pwd.h> #include <vector> #include "../synflang.hpp" #include "FileFunction.hpp" #include "../Lexer/Lexer.hpp" class FLanguage { FCommand *command = new FCommand(); FRunFunction *run = new FRunFunction(); LexerKeywords keyword; public: // Keywords std::string name; std::string EraseAllSubString(std::string & mainString, const std::string & erase) { size_t pos = std::string::npos; while((pos = mainString.find(erase)) != std::string::npos) { mainString.erase(pos, erase.length()); } return mainString; } void ReadFunc(std::string filename) { if(filename.rfind("#") == 0) { std::string new_name(getenv(EraseAllSubString(filename, "#").c_str())); filename = new_name; } std::string line; // For Float function float floatvar; // Path std::string path; path.append(command->_file_path_cd_function); path.append("/"); path.append(filename); path.append(scrift); std::ifstream readfile(path); // For Input function std::string inputcommand; integer finteger = 0; integer f; if(readfile.is_open()) { while (std::getline(readfile, line)) { if(line.find(keyword.PrintSlashn, 0) == 0) { slashn } if(line == keyword.Printlnf + keyword.Whitespace + keyword.ArrowType + keyword.Date) { printlnf(__DATE__); } if(line.find(keyword.Integer, 0) == 0) { finteger = std::atoi(line.erase(0, 8).c_str()); } if(line.rfind(keyword.Input, 0) == 0) { std::cin >> inputcommand; } if(line.find(keyword.WhitespaceInput, 0) == 0) { std::getline(std::cin, inputcommand); } if(line == keyword.PrintInput) { printlnf(inputcommand.c_str()); } if(line.find(keyword.FirstPlus + keyword.BracketsBegin, 0) == 0) { std::string test = EraseAllSubString(line, keyword.FirstPlus + keyword.BracketsBegin); test = EraseAllSubString(test, keyword.BracketsEnd + keyword.Semicolon); f = std::atoi(test.c_str()); } if(line.find(keyword.SecondPlus + keyword.BracketsBegin, 0) == 0) { std::string test = EraseAllSubString(line, keyword.SecondPlus + keyword.BracketsBegin); test = EraseAllSubString(test, keyword.BracketsEnd + keyword.Semicolon); f = f + std::atoi(test.c_str()); } if(line == keyword.PrintPl) { std::cout << f; } if(line == keyword.Return) { return; } if(line.find(keyword.String, 0) == 0) { name = line.erase(0, keyword.String.length()); } if(line.find(keyword.BracketsBegin + keyword.GreenColor + keyword.BracketsEnd + keyword.Printlnf + keyword.BracketsBegin, 0) == 0) { std::string test = EraseAllSubString(line, keyword.BracketsBegin + keyword.GreenColor + keyword.BracketsEnd + keyword.Printlnf + keyword.BracketsBegin + keyword.QuotationMarks); std::cout << WBOLD_GREEN_COLOR << EraseAllSubString(test, keyword.QuotationMarks + keyword.BracketsEnd + keyword.Semicolon) << WBLACK_COLOR; } if(line.find(keyword.BracketsBegin + keyword.RedColor + keyword.BracketsEnd + keyword.Printlnf + keyword.BracketsBegin, 0) == 0) { std::string test = EraseAllSubString(line, keyword.BracketsBegin + keyword.RedColor + keyword.BracketsEnd + keyword.Printlnf + keyword.BracketsBegin + keyword.QuotationMarks); std::cout << WBOLD_RED_COLOR << EraseAllSubString(test, keyword.QuotationMarks + keyword.BracketsEnd + keyword.Semicolon) << WBLACK_COLOR; } if(line.find(keyword.ChangeShell + keyword.Whitespace, 0) == 0) { std::string chsh = "sudo chsh -s /bin/"; chsh.append(EraseAllSubString(line, keyword.ChangeShell + keyword.Whitespace)); chsh.append(" "); chsh.append(getenv("USER")); system(chsh.c_str()); } if(line.find(keyword.Printlnf + keyword.BracketsBegin + keyword.QuotationMarks, 0) == 0) { std::string test = EraseAllSubString(line, keyword.Printlnf + keyword.BracketsBegin + keyword.QuotationMarks); std::cout << EraseAllSubString(test, keyword.QuotationMarks + keyword.BracketsEnd + keyword.Semicolon); } if (line == keyword.PrintFloat) { std::cout << floatvar; } if (line.rfind(keyword.PrintInteger, 0) == 0) { std::cout << finteger; } if (line.find(keyword.System, 0) == 0) { std::string test = EraseAllSubString(line, keyword.System + keyword.BracketsBegin + keyword.QuotationMarks); test = EraseAllSubString(test, keyword.QuotationMarks + keyword.BracketsEnd + keyword.Semicolon); run->RunFunction(test); } if(line.rfind(keyword.PrintString, 0) == 0) std::cout << name << "\n"; } } } }; #endif // LANGUAGE_HPP
32.408537
188
0.622766
ferhatgec
389930a5403cc9f11e941d7788a0462019372958
7,449
hpp
C++
gripper/robotiq-2f/main/opcua_task.hpp
opcua-skills/plug-and-produce
5567cd6177f973e97579fbd9d06ebbf23569ccfb
[ "Unlicense" ]
5
2020-04-15T03:24:48.000Z
2021-11-03T17:39:59.000Z
gripper/robotiq-2f/main/opcua_task.hpp
opcua-skills/plug-and-produce
5567cd6177f973e97579fbd9d06ebbf23569ccfb
[ "Unlicense" ]
null
null
null
gripper/robotiq-2f/main/opcua_task.hpp
opcua-skills/plug-and-produce
5567cd6177f973e97579fbd9d06ebbf23569ccfb
[ "Unlicense" ]
2
2020-07-04T16:01:25.000Z
2021-07-05T09:33:55.000Z
/* * This file is subject to the terms and conditions defined in * file 'LICENSE', which is part of this source code package. * * Copyright (c) 2020 fortiss GmbH, Stefan Profanter * All rights reserved. */ #ifndef ROBOTIQ_2FOPCUA_TASK_HPP #define ROBOTIQ_2FOPCUA_TASK_HPP #ifdef UA_ENABLE_AMALGAMATION #include <open62541.h> #else #include <open62541/server_config_default.h> #endif #include <spdlog/spdlog.h> #include <common/logging.h> #include <robotiq_2f_nodeids.h> #include "namespace_di_generated.h" #include "di_nodeids.h" #include "namespace_fortiss_device_generated.h" #include "namespace_robotiq_2f_generated.h" #include "GripperOPCUA.h" #define fortiss_LDS_URI "fortiss.component.mes" std::shared_ptr<spdlog::logger> logger; #ifndef LOCAL_SIMULATION #include <esp_log.h> #include "TinyPico.h" static const char *TAG_OPC = "OPC UA"; TinyPICO *tinyPico; #endif static bool createNodesFromNodeset( const std::shared_ptr<fortiss::opcua::OpcUaServer>& server ) { LockedServer ls = server->getLocked(); if (namespace_di_generated(ls.get()) != UA_STATUSCODE_GOOD) { logger->error("Adding the DI namespace failed. Please check previous error output."); return false; } if (namespace_fortiss_device_generated(ls.get()) != UA_STATUSCODE_GOOD) { logger->error("Adding the fortiss device namespace failed. Please check previous error output."); return false; } if (namespace_robotiq_2f_generated(ls.get()) != UA_STATUSCODE_GOOD) { logger->error("Adding the Sommer Automatic namespace failed. Please check previous error output."); return false; } return true; } static bool run_opcua( UA_UInt16 port, volatile bool* running, bool ignore_poweroff, std::shared_ptr<spdlog::logger> _logger = nullptr, std::shared_ptr<spdlog::logger> _loggerServer = nullptr, std::shared_ptr<spdlog::logger> _loggerClient = nullptr ) { //The default 64KB of memory for sending and receicing buffer caused problems to many users. With the code below, they are reduced to ~16KB UA_UInt32 sendBufferSize = 16000; //64 KB was too much for my platform UA_UInt32 recvBufferSize = 16000; //64 KB was too much for my platform std::shared_ptr<spdlog::logger> loggerServer; std::shared_ptr<spdlog::logger> loggerClient; if (!logger) { logger = fortiss::log::get("gripper/robotiq2f"); logger->set_level(spdlog::level::level_enum::info); loggerServer = logger->clone(logger->name() + "-ua"); loggerServer->set_level(spdlog::level::level_enum::err); loggerClient = logger->clone(logger->name() + "-ua-reg"); loggerClient->set_level(spdlog::level::level_enum::err); } else { logger = _logger; loggerServer = _loggerServer; loggerClient = _loggerClient; } UA_ServerConfig *uaServerConfig = (UA_ServerConfig*) UA_malloc(sizeof(UA_ServerConfig)); if (!uaServerConfig) { logger->error("Can not create server config"); throw std::runtime_error("Cannot create server config"); } // ------------- OPC UA initialization ------------------- if (fortiss::opcua::initServerConfig( loggerServer, uaServerConfig, "fortiss.component.gripper.robotiq", "fortiss - Gripper - Robotiq", (UA_UInt16) ((int) port), false, false, "", sendBufferSize, recvBufferSize, true) != UA_STATUSCODE_GOOD) { return false; } #ifndef LOCAL_SIMULATION #ifndef CONFIG_ETHERNET_HELPER_CUSTOM_HOSTNAME #ifndef ETHERNET_HELPER_STATIC_IP4 #error You need to set a static IP or a custom hostname with menuconfig #else UA_String str = UA_STRING(CONFIG_ETHERNET_HELPER_STATIC_IP4_ADDRESS); #endif #else UA_String str = UA_STRING((char*)CONFIG_ETHERNET_HELPER_CUSTOM_HOSTNAME_STR); #endif UA_String_clear(&uaServerConfig->customHostname); UA_String_copy(&str, &uaServerConfig->customHostname); tcpip_adapter_ip_info_t default_ip; esp_err_t ret = tcpip_adapter_get_ip_info(tcpip_adapter_if_t::TCPIP_ADAPTER_IF_STA, &default_ip); if ((ESP_OK == ret) && (default_ip.ip.addr != INADDR_ANY)) { uaServerConfig->mdnsIpAddressListSize = 1; uaServerConfig->mdnsIpAddressList = (uint32_t *)UA_malloc(sizeof(uint32_t)*uaServerConfig->mdnsIpAddressListSize); memcpy(uaServerConfig->mdnsIpAddressList, &default_ip.ip.addr, sizeof(uint32_t)); } else { ESP_LOGI(TAG_OPC, "Could not get default IP Address!"); } #endif std::shared_ptr<fortiss::opcua::OpcUaServer> server = std::make_shared<fortiss::opcua::OpcUaServer>( logger, loggerServer, loggerClient, "fortiss.component.gripper.robotiq2f.client", "fortiss - Gripper - Robotiq 2F - Client", "", std::string(fortiss_LDS_URI), uaServerConfig); if (!createNodesFromNodeset(server)) { throw std::runtime_error("Creating nodes from nodeset failed"); } GripperOPCUA gripperOPCUA(logger, server); if (const UA_StatusCode retval = server->init( true ) != UA_STATUSCODE_GOOD) { logger->error("Starting up the server failed with " + std::string(UA_StatusCode_name(retval))); return false; } const fortiss::opcua::powerOffDeviceCallbackData onPowerOffDeviceData = { .logger = logger, .onPowerOffDevice = [running, ignore_poweroff](UA_UInt32 delayMs) { logger->warn("Got PowerOffDevice Method call! Shutting down OPC UA Server."); if (!ignore_poweroff) *running = false; return UA_STATUSCODE_GOOD; } }; { LockedServer ls = server->getLocked(); UA_StatusCode retval = fortiss::opcua::setPowerOffHandler(ls.get(), UA_NODEID_NUMERIC( fortiss::opcua::UA_Server_getNamespaceIdByName(server, NAMESPACE_URI_ROBOTIQ), UA_ROBOTIQ_2FID_ROBOTIQ2F), onPowerOffDeviceData); if (retval != UA_STATUSCODE_GOOD) { logger->error("Adding PowerOffHandler failed: " + std::string(UA_StatusCode_name(retval))); return false; } } if (!gripperOPCUA.connect()) { logger->error("gripperOPCUA connect failed!"); return false; } #ifndef LOCAL_SIMULATION ESP_LOGI(TAG_OPC, "Starting server loop. Free Heap: %d bytes", xPortGetFreeHeapSize()); tinyPico->DotStar_SetPixelColor(0, 255, 0); #endif while (*running) { server->iterate(); #ifndef LOCAL_SIMULATION try { gripperOPCUA.step(); } catch( rl::hal::DeviceException &ex) { ESP_LOGE(TAG_OPC, "DeviceException: %s", ex.what()); tinyPico->DotStar_SetPixelColor(255, 0, 0); break; } ESP_ERROR_CHECK(esp_task_wdt_reset()); #else gripperOPCUA.step(); std::this_thread::sleep_for(std::chrono::milliseconds(1)); #endif std::this_thread::yield(); } // do one last iteration server->iterate(true); gripperOPCUA.step(); gripperOPCUA.shutdown(); server.reset(); spdlog::shutdown(); return true; } #endif //ROBOTIQ_2FOPCUA_TASK_HPP
33.403587
143
0.653913
opcua-skills
389d1b5b255d7d1c83460efed92cbceed0de3d3a
3,144
cpp
C++
src/osdep/native/nativepluginloader.cpp
lawarner/aft
fd2b6b97bedd2be3ccb1739b890aeea6aa2f9603
[ "Apache-2.0" ]
null
null
null
src/osdep/native/nativepluginloader.cpp
lawarner/aft
fd2b6b97bedd2be3ccb1739b890aeea6aa2f9603
[ "Apache-2.0" ]
null
null
null
src/osdep/native/nativepluginloader.cpp
lawarner/aft
fd2b6b97bedd2be3ccb1739b890aeea6aa2f9603
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2016 Andy Warner * * 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 <dlfcn.h> #include "base/factory.h" #include "osdep/platform.h" using namespace aft::base; using namespace aft::osdep; #if __APPLE__ static const char* DEFAULT_PATH = "/opt/local/lib/aft/plugins"; static const char* PATH_SEPARATOR = "/"; static const char* SO_EXT = ".dylib"; #else static const char* DEFAULT_PATH = "/usr/local/lib/aft/plugins"; static const char* PATH_SEPARATOR = "/"; static const char* SO_EXT = ".so"; #endif class aft::osdep::NativePluginImpl { public: NativePluginImpl(const std::string& path = DEFAULT_PATH) : handle_(0) , factory_(0) , path_(path) { } void* handle_; aft::base::BaseFactory* factory_; //TODO keep array of directories in path instead of just one std::string path_; std::string bundleName_; }; static std::string makeSoName(const NativePluginImpl& impl) { std::string soName = impl.path_ + PATH_SEPARATOR + impl.bundleName_ + SO_EXT; return soName; } NativePluginLoader::NativePluginLoader() : impl_(*new NativePluginImpl) { } NativePluginLoader::~NativePluginLoader() { delete &impl_; } BaseFactory* NativePluginLoader::loadBundle(const std::string& bundleName) { impl_.bundleName_ = bundleName; std::string soName = makeSoName(impl_); std::cout << "Going to load " << soName << std::endl; void* handle = dlopen(soName.c_str(), RTLD_LAZY); if (!handle) { std::cout << "Error loading ld: " << dlerror() << std::endl; return 0; } impl_.handle_ = handle; InitializeFunction initialize = (InitializeFunction)dlsym(handle, "initialize"); if (!initialize) { std::cout << "Unable to load initialize() function" << std::endl; return 0; } DeinitializeFunction deinitialize = (DeinitializeFunction)dlsym(handle, "deinitialize"); BaseFactory* factory = initialize(); if (factory) { impl_.factory_ = factory; factory->setDeinit((void *)deinitialize); } else { std::cout << "Error instatiating plug-in factory" << std::endl; } return factory; } void NativePluginLoader::setPath(const std::string& path) { //TODO expand env variables and tildes impl_.path_ = path; } void NativePluginLoader::unloadBundle() { if (impl_.factory_) { impl_.factory_->deinit(); delete impl_.factory_; impl_.factory_ = 0; } if (impl_.handle_) { dlclose(impl_.handle_); impl_.handle_ = 0; } }
24.372093
92
0.659987
lawarner
389def0c517bffde189f296ae7695e17b0f783b5
8,630
cpp
C++
controller/src/beerocks/master/tasks/network_health_check_task.cpp
SWRT-dev/easymesh
12d902edde77599e074c0535f7256499b08f7494
[ "BSD-3-Clause", "BSD-2-Clause-Patent", "MIT" ]
null
null
null
controller/src/beerocks/master/tasks/network_health_check_task.cpp
SWRT-dev/easymesh
12d902edde77599e074c0535f7256499b08f7494
[ "BSD-3-Clause", "BSD-2-Clause-Patent", "MIT" ]
null
null
null
controller/src/beerocks/master/tasks/network_health_check_task.cpp
SWRT-dev/easymesh
12d902edde77599e074c0535f7256499b08f7494
[ "BSD-3-Clause", "BSD-2-Clause-Patent", "MIT" ]
null
null
null
/* SPDX-License-Identifier: BSD-2-Clause-Patent * * SPDX-FileCopyrightText: 2016-2020 the prplMesh contributors (see AUTHORS.md) * * This code is subject to the terms of the BSD+Patent license. * See LICENSE file for more details. */ #include "network_health_check_task.h" #include "../db/db_algo.h" #include "../son_actions.h" #include <easylogging++.h> using namespace beerocks; using namespace net; using namespace son; network_health_check_task::network_health_check_task(db &database_, ieee1905_1::CmduMessageTx &cmdu_tx_, task_pool &tasks_, int starting_delay_ms_, const std::string &task_name_) : task(task_name_), database(database_), cmdu_tx(cmdu_tx_), tasks(tasks_), starting_delay_ms(starting_delay_ms_) { } void network_health_check_task::work() { switch (state) { case START: { if (starting_delay_ms) { wait_for(starting_delay_ms); starting_delay_ms = 0; break; } if (suspected_dis_clients.empty()) { TASK_LOG(DEBUG) << "suspected_dis_clients.empty() - wait for 60 sec"; wait_for(task_timeout_ms); } state = IRE_HEALTH_CHECK; break; } case IRE_HEALTH_CHECK: { auto agents = database.get_all_connected_agents(); for (auto &agent : agents) { if (agent->is_gateway) { continue; } if (!agent->backhaul.wireless_backhaul_radio) { TASK_LOG(DEBUG) << "wireless backhaul radio is not set"; continue; } auto backhaul_manager_hostap = tlvf::mac_to_string(agent->backhaul.wireless_backhaul_radio->radio_uid); auto last_seen = database.get_node_last_seen(backhaul_manager_hostap); auto now = std::chrono::steady_clock::now(); auto last_seen_delta = std::chrono::duration_cast<std::chrono::milliseconds>(now - last_seen).count(); if (last_seen_delta > ire_last_seen_timeout_ms) { auto backhaul = database.get_node_parent(tlvf::mac_to_string(agent->al_mac)); TASK_LOG(DEBUG) << "handle_dead_node ire(backhaul) = " << agent->al_mac << " hostap = " << backhaul_manager_hostap << " backhaul = " << backhaul << " last_seen_delta=" << int(last_seen_delta); son_actions::handle_dead_node(backhaul, true, database, cmdu_tx, tasks); } } state = CLIENT_HEALTH_CHECK; break; } case CLIENT_HEALTH_CHECK: { auto clients = database.get_nodes(beerocks::TYPE_CLIENT); for (auto &client : clients) { auto last_seen = database.get_node_last_seen(client); if (!database.is_node_wireless(client) && (database.get_node_state(client) == beerocks::STATE_CONNECTED)) { auto now = std::chrono::steady_clock::now(); auto last_seen_delta = std::chrono::duration_cast<std::chrono::milliseconds>(now - last_seen).count(); if (last_seen_delta > (client_last_seen_timeout_ms) && (suspected_dis_clients.find(client) == suspected_dis_clients.end())) { suspected_dis_clients.insert(client); //TASK_LOG(DEBUG) << "insert client = " << client << " last_seen_delta = " << int(last_seen_delta); } } } state = SEND_QUERY; break; } case SEND_QUERY: { if (!(suspected_dis_clients.empty()) && pending_node.empty()) { for (auto it = suspected_dis_clients.begin(); it != suspected_dis_clients.end();) { //send query messages to client. //TASK_LOG(DEBUG) << "send query to client - mac = " << *it; if (!send_arp_query(*it)) { TASK_LOG(DEBUG) << "failed to send query on client " << *it << " erased client"; it = suspected_dis_clients.erase(it); pending_node.clear(); } else { ++it; } } } state = START; break; } } } void network_health_check_task::handle_response(std::string mac, std::shared_ptr<beerocks_header> beerocks_header) { switch (beerocks_header->action_op()) { case beerocks_message::ACTION_CONTROL_ARP_QUERY_RESPONSE: { auto response = beerocks_header->getClass<beerocks_message::cACTION_CONTROL_ARP_QUERY_RESPONSE>(); if (!response) { TASK_LOG(ERROR) << "getClass failed for cACTION_CONTROL_ARP_QUERY_RESPONSE"; return; } std::string ipv4 = network_utils::ipv4_to_string(response->params().ipv4); std::string arp_mac = tlvf::mac_to_string(response->params().mac); TASK_LOG(DEBUG) << "received response from slave " << mac << ":" << std::endl << " arp_mac=" << arp_mac << std::endl << " arp_ipv4=" << ipv4 << std::endl << " arp_state=" << int(response->params().state) << " arp_source=" << int(response->params().source); database.update_node_last_seen(arp_mac); if (suspected_dis_clients.find(arp_mac) != suspected_dis_clients.end()) { TASK_LOG(DEBUG) << "arp_mac = " << arp_mac << " is alive!! erasing from ires/clients set"; suspected_dis_clients.erase(arp_mac); TASK_LOG(DEBUG) << "suspected_dis_clients.erase " << arp_mac; pending_node.clear(); } else { TASK_LOG(DEBUG) << "arp_mac = " << arp_mac << " not found!! on IRE's/CLIENT's set , not supposed to get here!! "; } break; } default: { TASK_LOG(ERROR) << "Unsupported action_op:" << int(beerocks_header->action_op()); break; } } } bool network_health_check_task::send_arp_query(std::string mac) { auto request = message_com::create_vs_message<beerocks_message::cACTION_CONTROL_ARP_QUERY_REQUEST>(cmdu_tx, id); if (request == nullptr) { LOG(ERROR) << "Failed building message!"; return false; } request->params().mac = tlvf::mac_from_string(mac); auto ipv4 = database.get_node_ipv4(mac); request->params().ipv4 = network_utils::ipv4_from_string(ipv4); const auto parent_radio = database.get_node_parent_radio(mac); auto agent_mac = database.get_node_parent_ire(parent_radio); if (database.get_node_state(parent_radio) != beerocks::STATE_CONNECTED) { LOG(WARNING) << "parent_mac not connected , parent_mac = " << parent_radio; return false; } if (!son_actions::send_cmdu_to_agent(agent_mac, cmdu_tx, database, parent_radio)) { LOG(ERROR) << "send_message failed - parent_mac " << parent_radio << " client " << mac; return false; } add_pending_mac(parent_radio, beerocks_message::ACTION_CONTROL_ARP_QUERY_RESPONSE); pending_node = mac; set_responses_timeout(5 * 1000); TASK_LOG(DEBUG) << "(parent_mac= " << parent_radio << ") for client_mac=" << mac << " ipv4=" << ipv4; return true; } void network_health_check_task::handle_responses_timeout( std::unordered_multimap<std::string, beerocks_message::eActionOp_CONTROL> timed_out_macs) { LOG(WARNING) << "handle_responses_timeout"; for (auto entry : timed_out_macs) { std::string mac = entry.first; TASK_LOG(DEBUG) << "response from " << mac << " timed out"; if (!suspected_dis_clients.empty()) { if (suspected_dis_clients.find(pending_node) != suspected_dis_clients.end()) { suspected_dis_clients.erase(pending_node); //TASK_LOG(DEBUG) << "suspected_dis_clients.erase " << pending_node; LOG(WARNING) << "CLIENT is not responding!! handle dead client mac = " << pending_node; son_actions::handle_dead_node(pending_node, true, database, cmdu_tx, tasks); pending_node.clear(); return; } } } }
40.516432
119
0.569177
SWRT-dev
389e8b0b8a1b9929734767e1b62edd0dfa8a1afa
1,018
cpp
C++
lib/il2cpp/il2cpp/libmono/icalls/mscorlib/System.Runtime.InteropServices/Marshal.cpp
smorey2/GameEstate
1349dd68c675ed056210b4238f5b8e7c92857933
[ "MIT" ]
null
null
null
lib/il2cpp/il2cpp/libmono/icalls/mscorlib/System.Runtime.InteropServices/Marshal.cpp
smorey2/GameEstate
1349dd68c675ed056210b4238f5b8e7c92857933
[ "MIT" ]
null
null
null
lib/il2cpp/il2cpp/libmono/icalls/mscorlib/System.Runtime.InteropServices/Marshal.cpp
smorey2/GameEstate
1349dd68c675ed056210b4238f5b8e7c92857933
[ "MIT" ]
null
null
null
#include <cstdlib> #include "Marshal.h" #include "vm/PlatformInvoke.h" namespace mono { namespace icalls { namespace mscorlib { namespace System { namespace Runtime { namespace InteropServices { intptr_t Marshal::GetFunctionPointerForDelegateInternal(MonoDelegate* d) { return mono::vm::PlatformInvoke::MarshalDelegate(d); } Il2CppDelegate* Marshal::GetDelegateForFunctionPointerInternal(intptr_t ptr, MonoReflectionType* t) { MonoClass *delegateType = mono_type_get_class(mono_unity_reflection_type_get_type(t)); if (!mono_class_init(delegateType)) { mono_set_pending_exception(mono_class_get_exception_for_failure(delegateType)); return NULL; } return mono::vm::PlatformInvoke::MarshalFunctionPointerToDelegate(reinterpret_cast<void*>(ptr), delegateType); } } /* namespace InteropServices */ } /* namespace Runtime */ } /* namespace System */ } /* namespace mscorlib */ } /* namespace icalls */ } /* namespace mono */
26.789474
118
0.717092
smorey2
389f1a7880590f6562af72cfaa68f77dd4382e71
521
hpp
C++
zen/lexgen/parser.hpp
ZenLibraries/ZenLibraries
ae189b5080c75412cbd4f33cf6cfb51e15f6ee66
[ "Apache-2.0" ]
null
null
null
zen/lexgen/parser.hpp
ZenLibraries/ZenLibraries
ae189b5080c75412cbd4f33cf6cfb51e15f6ee66
[ "Apache-2.0" ]
2
2020-02-06T17:01:39.000Z
2020-02-12T17:50:14.000Z
zen/lexgen/parser.hpp
ZenLibraries/ZenLibraries
ae189b5080c75412cbd4f33cf6cfb51e15f6ee66
[ "Apache-2.0" ]
null
null
null
#ifndef ZEN_LEXGEN_PARSER_HPP #define ZEN_LEXGEN_PARSER_HPP #include "zen/stream.hpp" #include "zen/lexgen/common.hpp" #include "zen/lexgen/lexer.hpp" #include "zen/lexgen/nodes.hpp" namespace zen { namespace lexgen { using TokenStream = PeekStream<Token>; class Parser { TokenStream& tokens; public: inline Parser(TokenStream& tokens): tokens(tokens) {} Result<Node> parse_expr(); Result<Node> parse(); }; } } #endif // of #ifndef ZEN_LEXGEN_PARSER_HPP
14.472222
42
0.667946
ZenLibraries
389fcb1be934c618a7a0e28cc900735855462c13
364
cpp
C++
books/tech/cpp/std-11/b_sutherland-cpp_recipes/ch_07-the_stl_containers/recipe_7.1-storing_a_fixed_number_of_objects/01-a_c-style_array/main.cpp
ordinary-developer/education
1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58
[ "MIT" ]
1
2017-05-04T08:23:46.000Z
2017-05-04T08:23:46.000Z
books/techno/cpp/__intermediate/cpp_recipes_a_problem_solution_approach_b_shutherland/code/ch_7-THE_STL_CONTAINERS/recipe_7.1-storing_a_fixed_number_of_objects/01-a_c-style_array/main.cpp
ordinary-developer/lin_education
13d65b20cdbc3e5467b2383e5c09c73bbcdcb227
[ "MIT" ]
null
null
null
books/techno/cpp/__intermediate/cpp_recipes_a_problem_solution_approach_b_shutherland/code/ch_7-THE_STL_CONTAINERS/recipe_7.1-storing_a_fixed_number_of_objects/01-a_c-style_array/main.cpp
ordinary-developer/lin_education
13d65b20cdbc3e5467b2383e5c09c73bbcdcb227
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdint> int main() { const uint32_t numberOfElements{ 5 }; int32_t normalArray[numberOfElements]{ 10, 65, 3000, 2, 49 }; for (uint32_t i{ 0 }; i < numberOfElements; ++i) std::cout << normalArray[i] << std::endl; for (auto&& number : normalArray) std::cout << number << std::endl; return 0; }
22.75
65
0.601648
ordinary-developer
38a48084ba5ab1c30c116ae9c1666d494ea3cd68
80
cpp
C++
sources/source.cpp
Gustafsson88/lr12
4db8ad87ba1b29890b43307b5b093bce900cea62
[ "MIT" ]
null
null
null
sources/source.cpp
Gustafsson88/lr12
4db8ad87ba1b29890b43307b5b093bce900cea62
[ "MIT" ]
null
null
null
sources/source.cpp
Gustafsson88/lr12
4db8ad87ba1b29890b43307b5b093bce900cea62
[ "MIT" ]
null
null
null
// Copyright 2021 Alexandr Guchkov <firer.a45@gmail.com> #include "header.hpp"
20
56
0.75
Gustafsson88
38a59f8ced308444dfb9946d96d823686cd00cb8
133
hpp
C++
include/NP-Engine/Input/Input.hpp
naphipps/NP-Engine
0cac8b2d5e76c839b96f2061bf57434bdc37915e
[ "MIT" ]
null
null
null
include/NP-Engine/Input/Input.hpp
naphipps/NP-Engine
0cac8b2d5e76c839b96f2061bf57434bdc37915e
[ "MIT" ]
null
null
null
include/NP-Engine/Input/Input.hpp
naphipps/NP-Engine
0cac8b2d5e76c839b96f2061bf57434bdc37915e
[ "MIT" ]
null
null
null
// // Input.hpp // NP-Engine // // Created by Nathan Phipps on 2/13/21. // #ifndef Input_h #define Input_h #endif /* Input_h */
11.083333
40
0.616541
naphipps
38aacd90f44bd36dfd44ff94a89e712bedb6b6c7
708
cpp
C++
2017.8.15/a.cpp
1980744819/ACM-code
a697242bc963e682e552e655e3d78527e044e854
[ "Apache-2.0" ]
null
null
null
2017.8.15/a.cpp
1980744819/ACM-code
a697242bc963e682e552e655e3d78527e044e854
[ "Apache-2.0" ]
null
null
null
2017.8.15/a.cpp
1980744819/ACM-code
a697242bc963e682e552e655e3d78527e044e854
[ "Apache-2.0" ]
null
null
null
#include<cstdio> #include<string> #include<cstring> #include<cstdlib> #include<cmath> #include<iostream> #include<algorithm> #include<vector> #include<queue> #include<map> #include<set> #include<stack> #define ll long long #define read(a) scanf("%d",&a); using namespace std; const int maxn=1e7+5; int a[maxn]; void init(){ int i,j; a[1]=1; a[2]=2; a[3]=2; i=3; j=3; int num=1; while(j<maxn){ for(int k=1;k<=a[i]&&j+k<maxn;k++){ a[j+k]=num; } j+=a[i]; if(num==1) num=2; else num=1; i++; } //printf("%d",a[10000000]); } int main(){ //freopen("test.txt","r",stdin); int t; init(); scanf("%d",&t); while(t--){ int n; scanf("%d",&n); printf("%d\n",a[n]); } return 0; }
14.16
37
0.579096
1980744819
38adfd053f9d6c00d00784d1e6e096ec1741d8f6
724
cpp
C++
Sources/CubbyDNN/Node/Input.cpp
utilForever/CubbyDNN
b044957e42eff8f14e826160b1bca1c82839a93b
[ "MIT" ]
34
2018-10-18T02:30:26.000Z
2021-06-13T19:11:23.000Z
Sources/CubbyDNN/Node/Input.cpp
utilForever/CubbyDNN
b044957e42eff8f14e826160b1bca1c82839a93b
[ "MIT" ]
31
2018-11-04T08:33:48.000Z
2020-10-07T14:59:55.000Z
Sources/CubbyDNN/Node/Input.cpp
utilForever/CubbyDNN
b044957e42eff8f14e826160b1bca1c82839a93b
[ "MIT" ]
9
2018-11-05T09:31:59.000Z
2020-12-25T13:04:26.000Z
#include <CubbyDNN/Node/Input.hpp> namespace CubbyDNN::Node { Input::Input(Core::Graph* graph, std::string_view name) : Node(graph, name) { // Do nothing } const NodeType* Input::Type() const { return graph->nodeTypeManager.Type<Input>(); } std::string_view Input::TypeName() { return "Input"; } void Input::Feed(const Core::Shape& shape, Core::Span<float> span) { m_inputSpan = span; const bool isDirtyShape = m_inputShape != shape; if (isDirtyShape) { m_inputShape = shape; } MarkDirty(isDirtyShape); } void Input::EvalShapeInternal() { m_shape = m_inputShape; } void Input::EvalOutputInternal() { Output().CopyFrom(m_inputSpan); } } // namespace CubbyDNN::Node
17.238095
75
0.668508
utilForever
38ae8c1bef93489a7a77aa35b3a65136eab2de0d
105,183
cpp
C++
AES_GPU_DX10/src/AES_GPU_DX10.cpp
Bizonu/amclibrary
6dacc2386064bc1fb0ad9ef1cf0774c5fed56bed
[ "Apache-2.0" ]
null
null
null
AES_GPU_DX10/src/AES_GPU_DX10.cpp
Bizonu/amclibrary
6dacc2386064bc1fb0ad9ef1cf0774c5fed56bed
[ "Apache-2.0" ]
null
null
null
AES_GPU_DX10/src/AES_GPU_DX10.cpp
Bizonu/amclibrary
6dacc2386064bc1fb0ad9ef1cf0774c5fed56bed
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// File: AES_GPU_DX10.cpp /// Description: The implementation of the internal interface for the AES implementation on the GPU using DX10. /// Author: Chiuta Adrian Marius /// Created: 26-11-2009 /// /// 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 "platform.h" #include "AES_GPU_DX10_Internal.h" #if defined( DEBUG ) || defined( _DEBUG ) #include <stdio.h> #include <intrin.h> #endif //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef SAFE_RELEASE #define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p) = NULL; } } #endif #ifndef SAFE_DELETE_ARRAY #define SAFE_DELETE_ARRAY(p) { if(p) { delete [](p); (p) = NULL; } } #endif #ifndef SAFE_DELETE #define SAFE_DELETE(p) { if(p) { delete (p); (p) = NULL; } } #endif #ifndef countof #define countof( array ) ( sizeof( array )/sizeof( array[0] ) ) #endif //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // The handle to this module HMODULE gHModule = NULL; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //The following tables were generated using the code: // //void AddTable(FILE* fout, const char *tableName, const char *boxTable, const UINT8 *sbox, // UINT32 v1, UINT32 v2, UINT32 v3, UINT32 v4) //{ // fprintf(fout, "/*\n\tFor every value found at index we have:\n" // "\t\t- bits 0..7 represent Multiply(%s[index], 0x%02X).\n" // "\t\t- bits 8..15 represent Multiply(%s[index], 0x%02X).\n" // "\t\t- bits 16..23 represent Multiply(%s[index], 0x%02X).\n" // "\t\t- bits 24..31 represent Multiply(%s[index], 0x%02X).\n" // "*/\n", boxTable, v1, boxTable, v2, boxTable, v3, boxTable, v4); // // fprintf(fout, "static const UINT32 %s[256] =\n{\n", tableName); // // UINT32 c = 0; // for(UINT32 i = 0; i < 256; i++) // { // if(c == 0 ) // fprintf(fout, "\t"); // // UINT32 iBox = sbox[i]; // UINT32 value = (Multiply(iBox, v1) & 0xFF) | ((Multiply(iBox, v2) & 0xFF) << 8) | // ((Multiply(iBox, v3) & 0xFF) << 16) | ((Multiply(iBox, v4) & 0xFF) << 24); // // if( i != 255 ) // fprintf(fout, "0x%08X, ", value); // else // fprintf(fout, "0x%08X", value); // if( c == 7 ) // fprintf(fout, "\n"); // // c = (c + 1) & 7; // } // // fprintf(fout, "};\n"); //} // //void CreateTables(char *fileName) //{ // FILE *fout = fopen(fileName, "wt"); // // AddTable(fout, "sBoxMixColumn_a", "sbox", sbox, 0x02, 0x01, 0x01, 0x03); // AddTable(fout, "sBoxMixColumn_b", "sbox", sbox, 0x03, 0x02, 0x01, 0x01); // AddTable(fout, "sBoxMixColumn_c", "sbox", sbox, 0x01, 0x03, 0x02, 0x01); // AddTable(fout, "sBoxMixColumn_d", "sbox", sbox, 0x01, 0x01, 0x03, 0x02); // // AddTable(fout, "rsBoxInvMixColumn_a", "rsbox", rsbox, 0x0e, 0x09, 0x0d, 0x0b); // AddTable(fout, "rsBoxInvMixColumn_b", "rsbox", rsbox, 0x0b, 0x0e, 0x09, 0x0d); // AddTable(fout, "rsBoxInvMixColumn_c", "rsbox", rsbox, 0x0d, 0x0b, 0x0e, 0x09); // AddTable(fout, "rsBoxInvMixColumn_d", "rsbox", rsbox, 0x09, 0x0d, 0x0b, 0x0e); // // fclose(fout); //} //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* For every value found at index we have: - bits 0..7 represent Multiply(sbox[index], 0x02). - bits 8..15 represent Multiply(sbox[index], 0x01). - bits 16..23 represent Multiply(sbox[index], 0x01). - bits 24..31 represent Multiply(sbox[index], 0x03). */ __declspec(align(16)) static const UINT32 sBoxMixColumn_a[256] = { 0xA56363C6, 0x847C7CF8, 0x997777EE, 0x8D7B7BF6, 0x0DF2F2FF, 0xBD6B6BD6, 0xB16F6FDE, 0x54C5C591, 0x50303060, 0x03010102, 0xA96767CE, 0x7D2B2B56, 0x19FEFEE7, 0x62D7D7B5, 0xE6ABAB4D, 0x9A7676EC, 0x45CACA8F, 0x9D82821F, 0x40C9C989, 0x877D7DFA, 0x15FAFAEF, 0xEB5959B2, 0xC947478E, 0x0BF0F0FB, 0xECADAD41, 0x67D4D4B3, 0xFDA2A25F, 0xEAAFAF45, 0xBF9C9C23, 0xF7A4A453, 0x967272E4, 0x5BC0C09B, 0xC2B7B775, 0x1CFDFDE1, 0xAE93933D, 0x6A26264C, 0x5A36366C, 0x413F3F7E, 0x02F7F7F5, 0x4FCCCC83, 0x5C343468, 0xF4A5A551, 0x34E5E5D1, 0x08F1F1F9, 0x937171E2, 0x73D8D8AB, 0x53313162, 0x3F15152A, 0x0C040408, 0x52C7C795, 0x65232346, 0x5EC3C39D, 0x28181830, 0xA1969637, 0x0F05050A, 0xB59A9A2F, 0x0907070E, 0x36121224, 0x9B80801B, 0x3DE2E2DF, 0x26EBEBCD, 0x6927274E, 0xCDB2B27F, 0x9F7575EA, 0x1B090912, 0x9E83831D, 0x742C2C58, 0x2E1A1A34, 0x2D1B1B36, 0xB26E6EDC, 0xEE5A5AB4, 0xFBA0A05B, 0xF65252A4, 0x4D3B3B76, 0x61D6D6B7, 0xCEB3B37D, 0x7B292952, 0x3EE3E3DD, 0x712F2F5E, 0x97848413, 0xF55353A6, 0x68D1D1B9, 0x00000000, 0x2CEDEDC1, 0x60202040, 0x1FFCFCE3, 0xC8B1B179, 0xED5B5BB6, 0xBE6A6AD4, 0x46CBCB8D, 0xD9BEBE67, 0x4B393972, 0xDE4A4A94, 0xD44C4C98, 0xE85858B0, 0x4ACFCF85, 0x6BD0D0BB, 0x2AEFEFC5, 0xE5AAAA4F, 0x16FBFBED, 0xC5434386, 0xD74D4D9A, 0x55333366, 0x94858511, 0xCF45458A, 0x10F9F9E9, 0x06020204, 0x817F7FFE, 0xF05050A0, 0x443C3C78, 0xBA9F9F25, 0xE3A8A84B, 0xF35151A2, 0xFEA3A35D, 0xC0404080, 0x8A8F8F05, 0xAD92923F, 0xBC9D9D21, 0x48383870, 0x04F5F5F1, 0xDFBCBC63, 0xC1B6B677, 0x75DADAAF, 0x63212142, 0x30101020, 0x1AFFFFE5, 0x0EF3F3FD, 0x6DD2D2BF, 0x4CCDCD81, 0x140C0C18, 0x35131326, 0x2FECECC3, 0xE15F5FBE, 0xA2979735, 0xCC444488, 0x3917172E, 0x57C4C493, 0xF2A7A755, 0x827E7EFC, 0x473D3D7A, 0xAC6464C8, 0xE75D5DBA, 0x2B191932, 0x957373E6, 0xA06060C0, 0x98818119, 0xD14F4F9E, 0x7FDCDCA3, 0x66222244, 0x7E2A2A54, 0xAB90903B, 0x8388880B, 0xCA46468C, 0x29EEEEC7, 0xD3B8B86B, 0x3C141428, 0x79DEDEA7, 0xE25E5EBC, 0x1D0B0B16, 0x76DBDBAD, 0x3BE0E0DB, 0x56323264, 0x4E3A3A74, 0x1E0A0A14, 0xDB494992, 0x0A06060C, 0x6C242448, 0xE45C5CB8, 0x5DC2C29F, 0x6ED3D3BD, 0xEFACAC43, 0xA66262C4, 0xA8919139, 0xA4959531, 0x37E4E4D3, 0x8B7979F2, 0x32E7E7D5, 0x43C8C88B, 0x5937376E, 0xB76D6DDA, 0x8C8D8D01, 0x64D5D5B1, 0xD24E4E9C, 0xE0A9A949, 0xB46C6CD8, 0xFA5656AC, 0x07F4F4F3, 0x25EAEACF, 0xAF6565CA, 0x8E7A7AF4, 0xE9AEAE47, 0x18080810, 0xD5BABA6F, 0x887878F0, 0x6F25254A, 0x722E2E5C, 0x241C1C38, 0xF1A6A657, 0xC7B4B473, 0x51C6C697, 0x23E8E8CB, 0x7CDDDDA1, 0x9C7474E8, 0x211F1F3E, 0xDD4B4B96, 0xDCBDBD61, 0x868B8B0D, 0x858A8A0F, 0x907070E0, 0x423E3E7C, 0xC4B5B571, 0xAA6666CC, 0xD8484890, 0x05030306, 0x01F6F6F7, 0x120E0E1C, 0xA36161C2, 0x5F35356A, 0xF95757AE, 0xD0B9B969, 0x91868617, 0x58C1C199, 0x271D1D3A, 0xB99E9E27, 0x38E1E1D9, 0x13F8F8EB, 0xB398982B, 0x33111122, 0xBB6969D2, 0x70D9D9A9, 0x898E8E07, 0xA7949433, 0xB69B9B2D, 0x221E1E3C, 0x92878715, 0x20E9E9C9, 0x49CECE87, 0xFF5555AA, 0x78282850, 0x7ADFDFA5, 0x8F8C8C03, 0xF8A1A159, 0x80898909, 0x170D0D1A, 0xDABFBF65, 0x31E6E6D7, 0xC6424284, 0xB86868D0, 0xC3414182, 0xB0999929, 0x772D2D5A, 0x110F0F1E, 0xCBB0B07B, 0xFC5454A8, 0xD6BBBB6D, 0x3A16162C }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* For every value found at index we have: - bits 0..7 represent Multiply(sbox[index], 0x03). - bits 8..15 represent Multiply(sbox[index], 0x02). - bits 16..23 represent Multiply(sbox[index], 0x01). - bits 24..31 represent Multiply(sbox[index], 0x01). */ __declspec(align(16)) static const UINT32 sBoxMixColumn_b[256] = { 0x6363C6A5, 0x7C7CF884, 0x7777EE99, 0x7B7BF68D, 0xF2F2FF0D, 0x6B6BD6BD, 0x6F6FDEB1, 0xC5C59154, 0x30306050, 0x01010203, 0x6767CEA9, 0x2B2B567D, 0xFEFEE719, 0xD7D7B562, 0xABAB4DE6, 0x7676EC9A, 0xCACA8F45, 0x82821F9D, 0xC9C98940, 0x7D7DFA87, 0xFAFAEF15, 0x5959B2EB, 0x47478EC9, 0xF0F0FB0B, 0xADAD41EC, 0xD4D4B367, 0xA2A25FFD, 0xAFAF45EA, 0x9C9C23BF, 0xA4A453F7, 0x7272E496, 0xC0C09B5B, 0xB7B775C2, 0xFDFDE11C, 0x93933DAE, 0x26264C6A, 0x36366C5A, 0x3F3F7E41, 0xF7F7F502, 0xCCCC834F, 0x3434685C, 0xA5A551F4, 0xE5E5D134, 0xF1F1F908, 0x7171E293, 0xD8D8AB73, 0x31316253, 0x15152A3F, 0x0404080C, 0xC7C79552, 0x23234665, 0xC3C39D5E, 0x18183028, 0x969637A1, 0x05050A0F, 0x9A9A2FB5, 0x07070E09, 0x12122436, 0x80801B9B, 0xE2E2DF3D, 0xEBEBCD26, 0x27274E69, 0xB2B27FCD, 0x7575EA9F, 0x0909121B, 0x83831D9E, 0x2C2C5874, 0x1A1A342E, 0x1B1B362D, 0x6E6EDCB2, 0x5A5AB4EE, 0xA0A05BFB, 0x5252A4F6, 0x3B3B764D, 0xD6D6B761, 0xB3B37DCE, 0x2929527B, 0xE3E3DD3E, 0x2F2F5E71, 0x84841397, 0x5353A6F5, 0xD1D1B968, 0x00000000, 0xEDEDC12C, 0x20204060, 0xFCFCE31F, 0xB1B179C8, 0x5B5BB6ED, 0x6A6AD4BE, 0xCBCB8D46, 0xBEBE67D9, 0x3939724B, 0x4A4A94DE, 0x4C4C98D4, 0x5858B0E8, 0xCFCF854A, 0xD0D0BB6B, 0xEFEFC52A, 0xAAAA4FE5, 0xFBFBED16, 0x434386C5, 0x4D4D9AD7, 0x33336655, 0x85851194, 0x45458ACF, 0xF9F9E910, 0x02020406, 0x7F7FFE81, 0x5050A0F0, 0x3C3C7844, 0x9F9F25BA, 0xA8A84BE3, 0x5151A2F3, 0xA3A35DFE, 0x404080C0, 0x8F8F058A, 0x92923FAD, 0x9D9D21BC, 0x38387048, 0xF5F5F104, 0xBCBC63DF, 0xB6B677C1, 0xDADAAF75, 0x21214263, 0x10102030, 0xFFFFE51A, 0xF3F3FD0E, 0xD2D2BF6D, 0xCDCD814C, 0x0C0C1814, 0x13132635, 0xECECC32F, 0x5F5FBEE1, 0x979735A2, 0x444488CC, 0x17172E39, 0xC4C49357, 0xA7A755F2, 0x7E7EFC82, 0x3D3D7A47, 0x6464C8AC, 0x5D5DBAE7, 0x1919322B, 0x7373E695, 0x6060C0A0, 0x81811998, 0x4F4F9ED1, 0xDCDCA37F, 0x22224466, 0x2A2A547E, 0x90903BAB, 0x88880B83, 0x46468CCA, 0xEEEEC729, 0xB8B86BD3, 0x1414283C, 0xDEDEA779, 0x5E5EBCE2, 0x0B0B161D, 0xDBDBAD76, 0xE0E0DB3B, 0x32326456, 0x3A3A744E, 0x0A0A141E, 0x494992DB, 0x06060C0A, 0x2424486C, 0x5C5CB8E4, 0xC2C29F5D, 0xD3D3BD6E, 0xACAC43EF, 0x6262C4A6, 0x919139A8, 0x959531A4, 0xE4E4D337, 0x7979F28B, 0xE7E7D532, 0xC8C88B43, 0x37376E59, 0x6D6DDAB7, 0x8D8D018C, 0xD5D5B164, 0x4E4E9CD2, 0xA9A949E0, 0x6C6CD8B4, 0x5656ACFA, 0xF4F4F307, 0xEAEACF25, 0x6565CAAF, 0x7A7AF48E, 0xAEAE47E9, 0x08081018, 0xBABA6FD5, 0x7878F088, 0x25254A6F, 0x2E2E5C72, 0x1C1C3824, 0xA6A657F1, 0xB4B473C7, 0xC6C69751, 0xE8E8CB23, 0xDDDDA17C, 0x7474E89C, 0x1F1F3E21, 0x4B4B96DD, 0xBDBD61DC, 0x8B8B0D86, 0x8A8A0F85, 0x7070E090, 0x3E3E7C42, 0xB5B571C4, 0x6666CCAA, 0x484890D8, 0x03030605, 0xF6F6F701, 0x0E0E1C12, 0x6161C2A3, 0x35356A5F, 0x5757AEF9, 0xB9B969D0, 0x86861791, 0xC1C19958, 0x1D1D3A27, 0x9E9E27B9, 0xE1E1D938, 0xF8F8EB13, 0x98982BB3, 0x11112233, 0x6969D2BB, 0xD9D9A970, 0x8E8E0789, 0x949433A7, 0x9B9B2DB6, 0x1E1E3C22, 0x87871592, 0xE9E9C920, 0xCECE8749, 0x5555AAFF, 0x28285078, 0xDFDFA57A, 0x8C8C038F, 0xA1A159F8, 0x89890980, 0x0D0D1A17, 0xBFBF65DA, 0xE6E6D731, 0x424284C6, 0x6868D0B8, 0x414182C3, 0x999929B0, 0x2D2D5A77, 0x0F0F1E11, 0xB0B07BCB, 0x5454A8FC, 0xBBBB6DD6, 0x16162C3A }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* For every value found at index we have: - bits 0..7 represent Multiply(sbox[index], 0x01). - bits 8..15 represent Multiply(sbox[index], 0x03). - bits 16..23 represent Multiply(sbox[index], 0x02). - bits 24..31 represent Multiply(sbox[index], 0x01). */ __declspec(align(16)) static const UINT32 sBoxMixColumn_c[256] = { 0x63C6A563, 0x7CF8847C, 0x77EE9977, 0x7BF68D7B, 0xF2FF0DF2, 0x6BD6BD6B, 0x6FDEB16F, 0xC59154C5, 0x30605030, 0x01020301, 0x67CEA967, 0x2B567D2B, 0xFEE719FE, 0xD7B562D7, 0xAB4DE6AB, 0x76EC9A76, 0xCA8F45CA, 0x821F9D82, 0xC98940C9, 0x7DFA877D, 0xFAEF15FA, 0x59B2EB59, 0x478EC947, 0xF0FB0BF0, 0xAD41ECAD, 0xD4B367D4, 0xA25FFDA2, 0xAF45EAAF, 0x9C23BF9C, 0xA453F7A4, 0x72E49672, 0xC09B5BC0, 0xB775C2B7, 0xFDE11CFD, 0x933DAE93, 0x264C6A26, 0x366C5A36, 0x3F7E413F, 0xF7F502F7, 0xCC834FCC, 0x34685C34, 0xA551F4A5, 0xE5D134E5, 0xF1F908F1, 0x71E29371, 0xD8AB73D8, 0x31625331, 0x152A3F15, 0x04080C04, 0xC79552C7, 0x23466523, 0xC39D5EC3, 0x18302818, 0x9637A196, 0x050A0F05, 0x9A2FB59A, 0x070E0907, 0x12243612, 0x801B9B80, 0xE2DF3DE2, 0xEBCD26EB, 0x274E6927, 0xB27FCDB2, 0x75EA9F75, 0x09121B09, 0x831D9E83, 0x2C58742C, 0x1A342E1A, 0x1B362D1B, 0x6EDCB26E, 0x5AB4EE5A, 0xA05BFBA0, 0x52A4F652, 0x3B764D3B, 0xD6B761D6, 0xB37DCEB3, 0x29527B29, 0xE3DD3EE3, 0x2F5E712F, 0x84139784, 0x53A6F553, 0xD1B968D1, 0x00000000, 0xEDC12CED, 0x20406020, 0xFCE31FFC, 0xB179C8B1, 0x5BB6ED5B, 0x6AD4BE6A, 0xCB8D46CB, 0xBE67D9BE, 0x39724B39, 0x4A94DE4A, 0x4C98D44C, 0x58B0E858, 0xCF854ACF, 0xD0BB6BD0, 0xEFC52AEF, 0xAA4FE5AA, 0xFBED16FB, 0x4386C543, 0x4D9AD74D, 0x33665533, 0x85119485, 0x458ACF45, 0xF9E910F9, 0x02040602, 0x7FFE817F, 0x50A0F050, 0x3C78443C, 0x9F25BA9F, 0xA84BE3A8, 0x51A2F351, 0xA35DFEA3, 0x4080C040, 0x8F058A8F, 0x923FAD92, 0x9D21BC9D, 0x38704838, 0xF5F104F5, 0xBC63DFBC, 0xB677C1B6, 0xDAAF75DA, 0x21426321, 0x10203010, 0xFFE51AFF, 0xF3FD0EF3, 0xD2BF6DD2, 0xCD814CCD, 0x0C18140C, 0x13263513, 0xECC32FEC, 0x5FBEE15F, 0x9735A297, 0x4488CC44, 0x172E3917, 0xC49357C4, 0xA755F2A7, 0x7EFC827E, 0x3D7A473D, 0x64C8AC64, 0x5DBAE75D, 0x19322B19, 0x73E69573, 0x60C0A060, 0x81199881, 0x4F9ED14F, 0xDCA37FDC, 0x22446622, 0x2A547E2A, 0x903BAB90, 0x880B8388, 0x468CCA46, 0xEEC729EE, 0xB86BD3B8, 0x14283C14, 0xDEA779DE, 0x5EBCE25E, 0x0B161D0B, 0xDBAD76DB, 0xE0DB3BE0, 0x32645632, 0x3A744E3A, 0x0A141E0A, 0x4992DB49, 0x060C0A06, 0x24486C24, 0x5CB8E45C, 0xC29F5DC2, 0xD3BD6ED3, 0xAC43EFAC, 0x62C4A662, 0x9139A891, 0x9531A495, 0xE4D337E4, 0x79F28B79, 0xE7D532E7, 0xC88B43C8, 0x376E5937, 0x6DDAB76D, 0x8D018C8D, 0xD5B164D5, 0x4E9CD24E, 0xA949E0A9, 0x6CD8B46C, 0x56ACFA56, 0xF4F307F4, 0xEACF25EA, 0x65CAAF65, 0x7AF48E7A, 0xAE47E9AE, 0x08101808, 0xBA6FD5BA, 0x78F08878, 0x254A6F25, 0x2E5C722E, 0x1C38241C, 0xA657F1A6, 0xB473C7B4, 0xC69751C6, 0xE8CB23E8, 0xDDA17CDD, 0x74E89C74, 0x1F3E211F, 0x4B96DD4B, 0xBD61DCBD, 0x8B0D868B, 0x8A0F858A, 0x70E09070, 0x3E7C423E, 0xB571C4B5, 0x66CCAA66, 0x4890D848, 0x03060503, 0xF6F701F6, 0x0E1C120E, 0x61C2A361, 0x356A5F35, 0x57AEF957, 0xB969D0B9, 0x86179186, 0xC19958C1, 0x1D3A271D, 0x9E27B99E, 0xE1D938E1, 0xF8EB13F8, 0x982BB398, 0x11223311, 0x69D2BB69, 0xD9A970D9, 0x8E07898E, 0x9433A794, 0x9B2DB69B, 0x1E3C221E, 0x87159287, 0xE9C920E9, 0xCE8749CE, 0x55AAFF55, 0x28507828, 0xDFA57ADF, 0x8C038F8C, 0xA159F8A1, 0x89098089, 0x0D1A170D, 0xBF65DABF, 0xE6D731E6, 0x4284C642, 0x68D0B868, 0x4182C341, 0x9929B099, 0x2D5A772D, 0x0F1E110F, 0xB07BCBB0, 0x54A8FC54, 0xBB6DD6BB, 0x162C3A16 }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* For every value found at index we have: - bits 0..7 represent Multiply(sbox[index], 0x01). - bits 8..15 represent Multiply(sbox[index], 0x01). - bits 16..23 represent Multiply(sbox[index], 0x03). - bits 24..31 represent Multiply(sbox[index], 0x02). */ __declspec(align(16)) static const UINT32 sBoxMixColumn_d[256] = { 0xC6A56363, 0xF8847C7C, 0xEE997777, 0xF68D7B7B, 0xFF0DF2F2, 0xD6BD6B6B, 0xDEB16F6F, 0x9154C5C5, 0x60503030, 0x02030101, 0xCEA96767, 0x567D2B2B, 0xE719FEFE, 0xB562D7D7, 0x4DE6ABAB, 0xEC9A7676, 0x8F45CACA, 0x1F9D8282, 0x8940C9C9, 0xFA877D7D, 0xEF15FAFA, 0xB2EB5959, 0x8EC94747, 0xFB0BF0F0, 0x41ECADAD, 0xB367D4D4, 0x5FFDA2A2, 0x45EAAFAF, 0x23BF9C9C, 0x53F7A4A4, 0xE4967272, 0x9B5BC0C0, 0x75C2B7B7, 0xE11CFDFD, 0x3DAE9393, 0x4C6A2626, 0x6C5A3636, 0x7E413F3F, 0xF502F7F7, 0x834FCCCC, 0x685C3434, 0x51F4A5A5, 0xD134E5E5, 0xF908F1F1, 0xE2937171, 0xAB73D8D8, 0x62533131, 0x2A3F1515, 0x080C0404, 0x9552C7C7, 0x46652323, 0x9D5EC3C3, 0x30281818, 0x37A19696, 0x0A0F0505, 0x2FB59A9A, 0x0E090707, 0x24361212, 0x1B9B8080, 0xDF3DE2E2, 0xCD26EBEB, 0x4E692727, 0x7FCDB2B2, 0xEA9F7575, 0x121B0909, 0x1D9E8383, 0x58742C2C, 0x342E1A1A, 0x362D1B1B, 0xDCB26E6E, 0xB4EE5A5A, 0x5BFBA0A0, 0xA4F65252, 0x764D3B3B, 0xB761D6D6, 0x7DCEB3B3, 0x527B2929, 0xDD3EE3E3, 0x5E712F2F, 0x13978484, 0xA6F55353, 0xB968D1D1, 0x00000000, 0xC12CEDED, 0x40602020, 0xE31FFCFC, 0x79C8B1B1, 0xB6ED5B5B, 0xD4BE6A6A, 0x8D46CBCB, 0x67D9BEBE, 0x724B3939, 0x94DE4A4A, 0x98D44C4C, 0xB0E85858, 0x854ACFCF, 0xBB6BD0D0, 0xC52AEFEF, 0x4FE5AAAA, 0xED16FBFB, 0x86C54343, 0x9AD74D4D, 0x66553333, 0x11948585, 0x8ACF4545, 0xE910F9F9, 0x04060202, 0xFE817F7F, 0xA0F05050, 0x78443C3C, 0x25BA9F9F, 0x4BE3A8A8, 0xA2F35151, 0x5DFEA3A3, 0x80C04040, 0x058A8F8F, 0x3FAD9292, 0x21BC9D9D, 0x70483838, 0xF104F5F5, 0x63DFBCBC, 0x77C1B6B6, 0xAF75DADA, 0x42632121, 0x20301010, 0xE51AFFFF, 0xFD0EF3F3, 0xBF6DD2D2, 0x814CCDCD, 0x18140C0C, 0x26351313, 0xC32FECEC, 0xBEE15F5F, 0x35A29797, 0x88CC4444, 0x2E391717, 0x9357C4C4, 0x55F2A7A7, 0xFC827E7E, 0x7A473D3D, 0xC8AC6464, 0xBAE75D5D, 0x322B1919, 0xE6957373, 0xC0A06060, 0x19988181, 0x9ED14F4F, 0xA37FDCDC, 0x44662222, 0x547E2A2A, 0x3BAB9090, 0x0B838888, 0x8CCA4646, 0xC729EEEE, 0x6BD3B8B8, 0x283C1414, 0xA779DEDE, 0xBCE25E5E, 0x161D0B0B, 0xAD76DBDB, 0xDB3BE0E0, 0x64563232, 0x744E3A3A, 0x141E0A0A, 0x92DB4949, 0x0C0A0606, 0x486C2424, 0xB8E45C5C, 0x9F5DC2C2, 0xBD6ED3D3, 0x43EFACAC, 0xC4A66262, 0x39A89191, 0x31A49595, 0xD337E4E4, 0xF28B7979, 0xD532E7E7, 0x8B43C8C8, 0x6E593737, 0xDAB76D6D, 0x018C8D8D, 0xB164D5D5, 0x9CD24E4E, 0x49E0A9A9, 0xD8B46C6C, 0xACFA5656, 0xF307F4F4, 0xCF25EAEA, 0xCAAF6565, 0xF48E7A7A, 0x47E9AEAE, 0x10180808, 0x6FD5BABA, 0xF0887878, 0x4A6F2525, 0x5C722E2E, 0x38241C1C, 0x57F1A6A6, 0x73C7B4B4, 0x9751C6C6, 0xCB23E8E8, 0xA17CDDDD, 0xE89C7474, 0x3E211F1F, 0x96DD4B4B, 0x61DCBDBD, 0x0D868B8B, 0x0F858A8A, 0xE0907070, 0x7C423E3E, 0x71C4B5B5, 0xCCAA6666, 0x90D84848, 0x06050303, 0xF701F6F6, 0x1C120E0E, 0xC2A36161, 0x6A5F3535, 0xAEF95757, 0x69D0B9B9, 0x17918686, 0x9958C1C1, 0x3A271D1D, 0x27B99E9E, 0xD938E1E1, 0xEB13F8F8, 0x2BB39898, 0x22331111, 0xD2BB6969, 0xA970D9D9, 0x07898E8E, 0x33A79494, 0x2DB69B9B, 0x3C221E1E, 0x15928787, 0xC920E9E9, 0x8749CECE, 0xAAFF5555, 0x50782828, 0xA57ADFDF, 0x038F8C8C, 0x59F8A1A1, 0x09808989, 0x1A170D0D, 0x65DABFBF, 0xD731E6E6, 0x84C64242, 0xD0B86868, 0x82C34141, 0x29B09999, 0x5A772D2D, 0x1E110F0F, 0x7BCBB0B0, 0xA8FC5454, 0x6DD6BBBB, 0x2C3A1616 }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* For every value found at index we have: - bits 0..7 represent Multiply(rsbox[index], 0x0E). - bits 8..15 represent Multiply(rsbox[index], 0x09). - bits 16..23 represent Multiply(rsbox[index], 0x0D). - bits 24..31 represent Multiply(rsbox[index], 0x0B). */ __declspec(align(16)) static const UINT32 rsBoxInvMixColumn_a[256] = { 0x50A7F451, 0x5365417E, 0xC3A4171A, 0x965E273A, 0xCB6BAB3B, 0xF1459D1F, 0xAB58FAAC, 0x9303E34B, 0x55FA3020, 0xF66D76AD, 0x9176CC88, 0x254C02F5, 0xFCD7E54F, 0xD7CB2AC5, 0x80443526, 0x8FA362B5, 0x495AB1DE, 0x671BBA25, 0x980EEA45, 0xE1C0FE5D, 0x02752FC3, 0x12F04C81, 0xA397468D, 0xC6F9D36B, 0xE75F8F03, 0x959C9215, 0xEB7A6DBF, 0xDA595295, 0x2D83BED4, 0xD3217458, 0x2969E049, 0x44C8C98E, 0x6A89C275, 0x78798EF4, 0x6B3E5899, 0xDD71B927, 0xB64FE1BE, 0x17AD88F0, 0x66AC20C9, 0xB43ACE7D, 0x184ADF63, 0x82311AE5, 0x60335197, 0x457F5362, 0xE07764B1, 0x84AE6BBB, 0x1CA081FE, 0x942B08F9, 0x58684870, 0x19FD458F, 0x876CDE94, 0xB7F87B52, 0x23D373AB, 0xE2024B72, 0x578F1FE3, 0x2AAB5566, 0x0728EBB2, 0x03C2B52F, 0x9A7BC586, 0xA50837D3, 0xF2872830, 0xB2A5BF23, 0xBA6A0302, 0x5C8216ED, 0x2B1CCF8A, 0x92B479A7, 0xF0F207F3, 0xA1E2694E, 0xCDF4DA65, 0xD5BE0506, 0x1F6234D1, 0x8AFEA6C4, 0x9D532E34, 0xA055F3A2, 0x32E18A05, 0x75EBF6A4, 0x39EC830B, 0xAAEF6040, 0x069F715E, 0x51106EBD, 0xF98A213E, 0x3D06DD96, 0xAE053EDD, 0x46BDE64D, 0xB58D5491, 0x055DC471, 0x6FD40604, 0xFF155060, 0x24FB9819, 0x97E9BDD6, 0xCC434089, 0x779ED967, 0xBD42E8B0, 0x888B8907, 0x385B19E7, 0xDBEEC879, 0x470A7CA1, 0xE90F427C, 0xC91E84F8, 0x00000000, 0x83868009, 0x48ED2B32, 0xAC70111E, 0x4E725A6C, 0xFBFF0EFD, 0x5638850F, 0x1ED5AE3D, 0x27392D36, 0x64D90F0A, 0x21A65C68, 0xD1545B9B, 0x3A2E3624, 0xB1670A0C, 0x0FE75793, 0xD296EEB4, 0x9E919B1B, 0x4FC5C080, 0xA220DC61, 0x694B775A, 0x161A121C, 0x0ABA93E2, 0xE52AA0C0, 0x43E0223C, 0x1D171B12, 0x0B0D090E, 0xADC78BF2, 0xB9A8B62D, 0xC8A91E14, 0x8519F157, 0x4C0775AF, 0xBBDD99EE, 0xFD607FA3, 0x9F2601F7, 0xBCF5725C, 0xC53B6644, 0x347EFB5B, 0x7629438B, 0xDCC623CB, 0x68FCEDB6, 0x63F1E4B8, 0xCADC31D7, 0x10856342, 0x40229713, 0x2011C684, 0x7D244A85, 0xF83DBBD2, 0x1132F9AE, 0x6DA129C7, 0x4B2F9E1D, 0xF330B2DC, 0xEC52860D, 0xD0E3C177, 0x6C16B32B, 0x99B970A9, 0xFA489411, 0x2264E947, 0xC48CFCA8, 0x1A3FF0A0, 0xD82C7D56, 0xEF903322, 0xC74E4987, 0xC1D138D9, 0xFEA2CA8C, 0x360BD498, 0xCF81F5A6, 0x28DE7AA5, 0x268EB7DA, 0xA4BFAD3F, 0xE49D3A2C, 0x0D927850, 0x9BCC5F6A, 0x62467E54, 0xC2138DF6, 0xE8B8D890, 0x5EF7392E, 0xF5AFC382, 0xBE805D9F, 0x7C93D069, 0xA92DD56F, 0xB31225CF, 0x3B99ACC8, 0xA77D1810, 0x6E639CE8, 0x7BBB3BDB, 0x097826CD, 0xF418596E, 0x01B79AEC, 0xA89A4F83, 0x656E95E6, 0x7EE6FFAA, 0x08CFBC21, 0xE6E815EF, 0xD99BE7BA, 0xCE366F4A, 0xD4099FEA, 0xD67CB029, 0xAFB2A431, 0x31233F2A, 0x3094A5C6, 0xC066A235, 0x37BC4E74, 0xA6CA82FC, 0xB0D090E0, 0x15D8A733, 0x4A9804F1, 0xF7DAEC41, 0x0E50CD7F, 0x2FF69117, 0x8DD64D76, 0x4DB0EF43, 0x544DAACC, 0xDF0496E4, 0xE3B5D19E, 0x1B886A4C, 0xB81F2CC1, 0x7F516546, 0x04EA5E9D, 0x5D358C01, 0x737487FA, 0x2E410BFB, 0x5A1D67B3, 0x52D2DB92, 0x335610E9, 0x1347D66D, 0x8C61D79A, 0x7A0CA137, 0x8E14F859, 0x893C13EB, 0xEE27A9CE, 0x35C961B7, 0xEDE51CE1, 0x3CB1477A, 0x59DFD29C, 0x3F73F255, 0x79CE1418, 0xBF37C773, 0xEACDF753, 0x5BAAFD5F, 0x146F3DDF, 0x86DB4478, 0x81F3AFCA, 0x3EC468B9, 0x2C342438, 0x5F40A3C2, 0x72C31D16, 0x0C25E2BC, 0x8B493C28, 0x41950DFF, 0x7101A839, 0xDEB30C08, 0x9CE4B4D8, 0x90C15664, 0x6184CB7B, 0x70B632D5, 0x745C6C48, 0x4257B8D0 }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* For every value found at index we have: - bits 0..7 represent Multiply(rsbox[index], 0x0B). - bits 8..15 represent Multiply(rsbox[index], 0x0E). - bits 16..23 represent Multiply(rsbox[index], 0x09). - bits 24..31 represent Multiply(rsbox[index], 0x0D). */ __declspec(align(16)) static const UINT32 rsBoxInvMixColumn_b[256] = { 0xA7F45150, 0x65417E53, 0xA4171AC3, 0x5E273A96, 0x6BAB3BCB, 0x459D1FF1, 0x58FAACAB, 0x03E34B93, 0xFA302055, 0x6D76ADF6, 0x76CC8891, 0x4C02F525, 0xD7E54FFC, 0xCB2AC5D7, 0x44352680, 0xA362B58F, 0x5AB1DE49, 0x1BBA2567, 0x0EEA4598, 0xC0FE5DE1, 0x752FC302, 0xF04C8112, 0x97468DA3, 0xF9D36BC6, 0x5F8F03E7, 0x9C921595, 0x7A6DBFEB, 0x595295DA, 0x83BED42D, 0x217458D3, 0x69E04929, 0xC8C98E44, 0x89C2756A, 0x798EF478, 0x3E58996B, 0x71B927DD, 0x4FE1BEB6, 0xAD88F017, 0xAC20C966, 0x3ACE7DB4, 0x4ADF6318, 0x311AE582, 0x33519760, 0x7F536245, 0x7764B1E0, 0xAE6BBB84, 0xA081FE1C, 0x2B08F994, 0x68487058, 0xFD458F19, 0x6CDE9487, 0xF87B52B7, 0xD373AB23, 0x024B72E2, 0x8F1FE357, 0xAB55662A, 0x28EBB207, 0xC2B52F03, 0x7BC5869A, 0x0837D3A5, 0x872830F2, 0xA5BF23B2, 0x6A0302BA, 0x8216ED5C, 0x1CCF8A2B, 0xB479A792, 0xF207F3F0, 0xE2694EA1, 0xF4DA65CD, 0xBE0506D5, 0x6234D11F, 0xFEA6C48A, 0x532E349D, 0x55F3A2A0, 0xE18A0532, 0xEBF6A475, 0xEC830B39, 0xEF6040AA, 0x9F715E06, 0x106EBD51, 0x8A213EF9, 0x06DD963D, 0x053EDDAE, 0xBDE64D46, 0x8D5491B5, 0x5DC47105, 0xD406046F, 0x155060FF, 0xFB981924, 0xE9BDD697, 0x434089CC, 0x9ED96777, 0x42E8B0BD, 0x8B890788, 0x5B19E738, 0xEEC879DB, 0x0A7CA147, 0x0F427CE9, 0x1E84F8C9, 0x00000000, 0x86800983, 0xED2B3248, 0x70111EAC, 0x725A6C4E, 0xFF0EFDFB, 0x38850F56, 0xD5AE3D1E, 0x392D3627, 0xD90F0A64, 0xA65C6821, 0x545B9BD1, 0x2E36243A, 0x670A0CB1, 0xE757930F, 0x96EEB4D2, 0x919B1B9E, 0xC5C0804F, 0x20DC61A2, 0x4B775A69, 0x1A121C16, 0xBA93E20A, 0x2AA0C0E5, 0xE0223C43, 0x171B121D, 0x0D090E0B, 0xC78BF2AD, 0xA8B62DB9, 0xA91E14C8, 0x19F15785, 0x0775AF4C, 0xDD99EEBB, 0x607FA3FD, 0x2601F79F, 0xF5725CBC, 0x3B6644C5, 0x7EFB5B34, 0x29438B76, 0xC623CBDC, 0xFCEDB668, 0xF1E4B863, 0xDC31D7CA, 0x85634210, 0x22971340, 0x11C68420, 0x244A857D, 0x3DBBD2F8, 0x32F9AE11, 0xA129C76D, 0x2F9E1D4B, 0x30B2DCF3, 0x52860DEC, 0xE3C177D0, 0x16B32B6C, 0xB970A999, 0x489411FA, 0x64E94722, 0x8CFCA8C4, 0x3FF0A01A, 0x2C7D56D8, 0x903322EF, 0x4E4987C7, 0xD138D9C1, 0xA2CA8CFE, 0x0BD49836, 0x81F5A6CF, 0xDE7AA528, 0x8EB7DA26, 0xBFAD3FA4, 0x9D3A2CE4, 0x9278500D, 0xCC5F6A9B, 0x467E5462, 0x138DF6C2, 0xB8D890E8, 0xF7392E5E, 0xAFC382F5, 0x805D9FBE, 0x93D0697C, 0x2DD56FA9, 0x1225CFB3, 0x99ACC83B, 0x7D1810A7, 0x639CE86E, 0xBB3BDB7B, 0x7826CD09, 0x18596EF4, 0xB79AEC01, 0x9A4F83A8, 0x6E95E665, 0xE6FFAA7E, 0xCFBC2108, 0xE815EFE6, 0x9BE7BAD9, 0x366F4ACE, 0x099FEAD4, 0x7CB029D6, 0xB2A431AF, 0x233F2A31, 0x94A5C630, 0x66A235C0, 0xBC4E7437, 0xCA82FCA6, 0xD090E0B0, 0xD8A73315, 0x9804F14A, 0xDAEC41F7, 0x50CD7F0E, 0xF691172F, 0xD64D768D, 0xB0EF434D, 0x4DAACC54, 0x0496E4DF, 0xB5D19EE3, 0x886A4C1B, 0x1F2CC1B8, 0x5165467F, 0xEA5E9D04, 0x358C015D, 0x7487FA73, 0x410BFB2E, 0x1D67B35A, 0xD2DB9252, 0x5610E933, 0x47D66D13, 0x61D79A8C, 0x0CA1377A, 0x14F8598E, 0x3C13EB89, 0x27A9CEEE, 0xC961B735, 0xE51CE1ED, 0xB1477A3C, 0xDFD29C59, 0x73F2553F, 0xCE141879, 0x37C773BF, 0xCDF753EA, 0xAAFD5F5B, 0x6F3DDF14, 0xDB447886, 0xF3AFCA81, 0xC468B93E, 0x3424382C, 0x40A3C25F, 0xC31D1672, 0x25E2BC0C, 0x493C288B, 0x950DFF41, 0x01A83971, 0xB30C08DE, 0xE4B4D89C, 0xC1566490, 0x84CB7B61, 0xB632D570, 0x5C6C4874, 0x57B8D042 }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* For every value found at index we have: - bits 0..7 represent Multiply(rsbox[index], 0x0D). - bits 8..15 represent Multiply(rsbox[index], 0x0B). - bits 16..23 represent Multiply(rsbox[index], 0x0E). - bits 24..31 represent Multiply(rsbox[index], 0x09). */ __declspec(align(16)) static const UINT32 rsBoxInvMixColumn_c[256] = { 0xF45150A7, 0x417E5365, 0x171AC3A4, 0x273A965E, 0xAB3BCB6B, 0x9D1FF145, 0xFAACAB58, 0xE34B9303, 0x302055FA, 0x76ADF66D, 0xCC889176, 0x02F5254C, 0xE54FFCD7, 0x2AC5D7CB, 0x35268044, 0x62B58FA3, 0xB1DE495A, 0xBA25671B, 0xEA45980E, 0xFE5DE1C0, 0x2FC30275, 0x4C8112F0, 0x468DA397, 0xD36BC6F9, 0x8F03E75F, 0x9215959C, 0x6DBFEB7A, 0x5295DA59, 0xBED42D83, 0x7458D321, 0xE0492969, 0xC98E44C8, 0xC2756A89, 0x8EF47879, 0x58996B3E, 0xB927DD71, 0xE1BEB64F, 0x88F017AD, 0x20C966AC, 0xCE7DB43A, 0xDF63184A, 0x1AE58231, 0x51976033, 0x5362457F, 0x64B1E077, 0x6BBB84AE, 0x81FE1CA0, 0x08F9942B, 0x48705868, 0x458F19FD, 0xDE94876C, 0x7B52B7F8, 0x73AB23D3, 0x4B72E202, 0x1FE3578F, 0x55662AAB, 0xEBB20728, 0xB52F03C2, 0xC5869A7B, 0x37D3A508, 0x2830F287, 0xBF23B2A5, 0x0302BA6A, 0x16ED5C82, 0xCF8A2B1C, 0x79A792B4, 0x07F3F0F2, 0x694EA1E2, 0xDA65CDF4, 0x0506D5BE, 0x34D11F62, 0xA6C48AFE, 0x2E349D53, 0xF3A2A055, 0x8A0532E1, 0xF6A475EB, 0x830B39EC, 0x6040AAEF, 0x715E069F, 0x6EBD5110, 0x213EF98A, 0xDD963D06, 0x3EDDAE05, 0xE64D46BD, 0x5491B58D, 0xC471055D, 0x06046FD4, 0x5060FF15, 0x981924FB, 0xBDD697E9, 0x4089CC43, 0xD967779E, 0xE8B0BD42, 0x8907888B, 0x19E7385B, 0xC879DBEE, 0x7CA1470A, 0x427CE90F, 0x84F8C91E, 0x00000000, 0x80098386, 0x2B3248ED, 0x111EAC70, 0x5A6C4E72, 0x0EFDFBFF, 0x850F5638, 0xAE3D1ED5, 0x2D362739, 0x0F0A64D9, 0x5C6821A6, 0x5B9BD154, 0x36243A2E, 0x0A0CB167, 0x57930FE7, 0xEEB4D296, 0x9B1B9E91, 0xC0804FC5, 0xDC61A220, 0x775A694B, 0x121C161A, 0x93E20ABA, 0xA0C0E52A, 0x223C43E0, 0x1B121D17, 0x090E0B0D, 0x8BF2ADC7, 0xB62DB9A8, 0x1E14C8A9, 0xF1578519, 0x75AF4C07, 0x99EEBBDD, 0x7FA3FD60, 0x01F79F26, 0x725CBCF5, 0x6644C53B, 0xFB5B347E, 0x438B7629, 0x23CBDCC6, 0xEDB668FC, 0xE4B863F1, 0x31D7CADC, 0x63421085, 0x97134022, 0xC6842011, 0x4A857D24, 0xBBD2F83D, 0xF9AE1132, 0x29C76DA1, 0x9E1D4B2F, 0xB2DCF330, 0x860DEC52, 0xC177D0E3, 0xB32B6C16, 0x70A999B9, 0x9411FA48, 0xE9472264, 0xFCA8C48C, 0xF0A01A3F, 0x7D56D82C, 0x3322EF90, 0x4987C74E, 0x38D9C1D1, 0xCA8CFEA2, 0xD498360B, 0xF5A6CF81, 0x7AA528DE, 0xB7DA268E, 0xAD3FA4BF, 0x3A2CE49D, 0x78500D92, 0x5F6A9BCC, 0x7E546246, 0x8DF6C213, 0xD890E8B8, 0x392E5EF7, 0xC382F5AF, 0x5D9FBE80, 0xD0697C93, 0xD56FA92D, 0x25CFB312, 0xACC83B99, 0x1810A77D, 0x9CE86E63, 0x3BDB7BBB, 0x26CD0978, 0x596EF418, 0x9AEC01B7, 0x4F83A89A, 0x95E6656E, 0xFFAA7EE6, 0xBC2108CF, 0x15EFE6E8, 0xE7BAD99B, 0x6F4ACE36, 0x9FEAD409, 0xB029D67C, 0xA431AFB2, 0x3F2A3123, 0xA5C63094, 0xA235C066, 0x4E7437BC, 0x82FCA6CA, 0x90E0B0D0, 0xA73315D8, 0x04F14A98, 0xEC41F7DA, 0xCD7F0E50, 0x91172FF6, 0x4D768DD6, 0xEF434DB0, 0xAACC544D, 0x96E4DF04, 0xD19EE3B5, 0x6A4C1B88, 0x2CC1B81F, 0x65467F51, 0x5E9D04EA, 0x8C015D35, 0x87FA7374, 0x0BFB2E41, 0x67B35A1D, 0xDB9252D2, 0x10E93356, 0xD66D1347, 0xD79A8C61, 0xA1377A0C, 0xF8598E14, 0x13EB893C, 0xA9CEEE27, 0x61B735C9, 0x1CE1EDE5, 0x477A3CB1, 0xD29C59DF, 0xF2553F73, 0x141879CE, 0xC773BF37, 0xF753EACD, 0xFD5F5BAA, 0x3DDF146F, 0x447886DB, 0xAFCA81F3, 0x68B93EC4, 0x24382C34, 0xA3C25F40, 0x1D1672C3, 0xE2BC0C25, 0x3C288B49, 0x0DFF4195, 0xA8397101, 0x0C08DEB3, 0xB4D89CE4, 0x566490C1, 0xCB7B6184, 0x32D570B6, 0x6C48745C, 0xB8D04257 }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* For every value found at index we have: - bits 0..7 represent Multiply(rsbox[index], 0x09). - bits 8..15 represent Multiply(rsbox[index], 0x0D). - bits 16..23 represent Multiply(rsbox[index], 0x0B). - bits 24..31 represent Multiply(rsbox[index], 0x0E). */ __declspec(align(16)) static const UINT32 rsBoxInvMixColumn_d[256] = { 0x5150A7F4, 0x7E536541, 0x1AC3A417, 0x3A965E27, 0x3BCB6BAB, 0x1FF1459D, 0xACAB58FA, 0x4B9303E3, 0x2055FA30, 0xADF66D76, 0x889176CC, 0xF5254C02, 0x4FFCD7E5, 0xC5D7CB2A, 0x26804435, 0xB58FA362, 0xDE495AB1, 0x25671BBA, 0x45980EEA, 0x5DE1C0FE, 0xC302752F, 0x8112F04C, 0x8DA39746, 0x6BC6F9D3, 0x03E75F8F, 0x15959C92, 0xBFEB7A6D, 0x95DA5952, 0xD42D83BE, 0x58D32174, 0x492969E0, 0x8E44C8C9, 0x756A89C2, 0xF478798E, 0x996B3E58, 0x27DD71B9, 0xBEB64FE1, 0xF017AD88, 0xC966AC20, 0x7DB43ACE, 0x63184ADF, 0xE582311A, 0x97603351, 0x62457F53, 0xB1E07764, 0xBB84AE6B, 0xFE1CA081, 0xF9942B08, 0x70586848, 0x8F19FD45, 0x94876CDE, 0x52B7F87B, 0xAB23D373, 0x72E2024B, 0xE3578F1F, 0x662AAB55, 0xB20728EB, 0x2F03C2B5, 0x869A7BC5, 0xD3A50837, 0x30F28728, 0x23B2A5BF, 0x02BA6A03, 0xED5C8216, 0x8A2B1CCF, 0xA792B479, 0xF3F0F207, 0x4EA1E269, 0x65CDF4DA, 0x06D5BE05, 0xD11F6234, 0xC48AFEA6, 0x349D532E, 0xA2A055F3, 0x0532E18A, 0xA475EBF6, 0x0B39EC83, 0x40AAEF60, 0x5E069F71, 0xBD51106E, 0x3EF98A21, 0x963D06DD, 0xDDAE053E, 0x4D46BDE6, 0x91B58D54, 0x71055DC4, 0x046FD406, 0x60FF1550, 0x1924FB98, 0xD697E9BD, 0x89CC4340, 0x67779ED9, 0xB0BD42E8, 0x07888B89, 0xE7385B19, 0x79DBEEC8, 0xA1470A7C, 0x7CE90F42, 0xF8C91E84, 0x00000000, 0x09838680, 0x3248ED2B, 0x1EAC7011, 0x6C4E725A, 0xFDFBFF0E, 0x0F563885, 0x3D1ED5AE, 0x3627392D, 0x0A64D90F, 0x6821A65C, 0x9BD1545B, 0x243A2E36, 0x0CB1670A, 0x930FE757, 0xB4D296EE, 0x1B9E919B, 0x804FC5C0, 0x61A220DC, 0x5A694B77, 0x1C161A12, 0xE20ABA93, 0xC0E52AA0, 0x3C43E022, 0x121D171B, 0x0E0B0D09, 0xF2ADC78B, 0x2DB9A8B6, 0x14C8A91E, 0x578519F1, 0xAF4C0775, 0xEEBBDD99, 0xA3FD607F, 0xF79F2601, 0x5CBCF572, 0x44C53B66, 0x5B347EFB, 0x8B762943, 0xCBDCC623, 0xB668FCED, 0xB863F1E4, 0xD7CADC31, 0x42108563, 0x13402297, 0x842011C6, 0x857D244A, 0xD2F83DBB, 0xAE1132F9, 0xC76DA129, 0x1D4B2F9E, 0xDCF330B2, 0x0DEC5286, 0x77D0E3C1, 0x2B6C16B3, 0xA999B970, 0x11FA4894, 0x472264E9, 0xA8C48CFC, 0xA01A3FF0, 0x56D82C7D, 0x22EF9033, 0x87C74E49, 0xD9C1D138, 0x8CFEA2CA, 0x98360BD4, 0xA6CF81F5, 0xA528DE7A, 0xDA268EB7, 0x3FA4BFAD, 0x2CE49D3A, 0x500D9278, 0x6A9BCC5F, 0x5462467E, 0xF6C2138D, 0x90E8B8D8, 0x2E5EF739, 0x82F5AFC3, 0x9FBE805D, 0x697C93D0, 0x6FA92DD5, 0xCFB31225, 0xC83B99AC, 0x10A77D18, 0xE86E639C, 0xDB7BBB3B, 0xCD097826, 0x6EF41859, 0xEC01B79A, 0x83A89A4F, 0xE6656E95, 0xAA7EE6FF, 0x2108CFBC, 0xEFE6E815, 0xBAD99BE7, 0x4ACE366F, 0xEAD4099F, 0x29D67CB0, 0x31AFB2A4, 0x2A31233F, 0xC63094A5, 0x35C066A2, 0x7437BC4E, 0xFCA6CA82, 0xE0B0D090, 0x3315D8A7, 0xF14A9804, 0x41F7DAEC, 0x7F0E50CD, 0x172FF691, 0x768DD64D, 0x434DB0EF, 0xCC544DAA, 0xE4DF0496, 0x9EE3B5D1, 0x4C1B886A, 0xC1B81F2C, 0x467F5165, 0x9D04EA5E, 0x015D358C, 0xFA737487, 0xFB2E410B, 0xB35A1D67, 0x9252D2DB, 0xE9335610, 0x6D1347D6, 0x9A8C61D7, 0x377A0CA1, 0x598E14F8, 0xEB893C13, 0xCEEE27A9, 0xB735C961, 0xE1EDE51C, 0x7A3CB147, 0x9C59DFD2, 0x553F73F2, 0x1879CE14, 0x73BF37C7, 0x53EACDF7, 0x5F5BAAFD, 0xDF146F3D, 0x7886DB44, 0xCA81F3AF, 0xB93EC468, 0x382C3424, 0xC25F40A3, 0x1672C31D, 0xBC0C25E2, 0x288B493C, 0xFF41950D, 0x397101A8, 0x08DEB30C, 0xD89CE4B4, 0x6490C156, 0x7B6184CB, 0xD570B632, 0x48745C6C, 0xD04257B8 }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //The following tables were generated using the code: // //void AddTable(FILE* fout, const char *tableName, UINT32 v1, UINT32 v2, UINT32 v3, UINT32 v4) //{ // fprintf(fout, "/*\n\tFor every value found at index we have:\n" // "\t\t- bits 0..7 represent Multiply(index, 0x%02X).\n" // "\t\t- bits 8..15 represent Multiply(index, 0x%02X).\n" // "\t\t- bits 16..23 represent Multiply(index, 0x%02X).\n" // "\t\t- bits 24..31 represent Multiply(index, 0x%02X).\n" // "*/\n", v1, v2, v3, v4); // // fprintf(fout, "static const UINT32 %s[256] =\n{\n", tableName); // // UINT32 c = 0; // for(UINT32 i = 0; i < 256; i++) // { // if(c == 0 ) // fprintf(fout, "\t"); // // UINT32 value = (Multiply(i, v1) & 0xFF) | ((Multiply(i, v2) & 0xFF) << 8) | // ((Multiply(i, v3) & 0xFF) << 16) | ((Multiply(i, v4) & 0xFF) << 24); // // if( i != 255 ) // fprintf(fout, "0x%08X, ", value); // else // fprintf(fout, "0x%08X", value); // if( c == 7 ) // fprintf(fout, "\n"); // // c = (c + 1) & 7; // } // // fprintf(fout, "};\n"); //} // //void CreateTables(char *fileName) //{ // FILE *fout = fopen(fileName, "wt"); // // AddTable(fout, "invMixColumn_a", 0x0e, 0x09, 0x0d, 0x0b); // AddTable(fout, "invMixColumn_b", 0x0b, 0x0e, 0x09, 0x0d); // AddTable(fout, "invMixColumn_c", 0x0d, 0x0b, 0x0e, 0x09); // AddTable(fout, "invMixColumn_d", 0x09, 0x0d, 0x0b, 0x0e); // // fclose(fout); //} //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* For every value found at index we have: - bits 0..7 represent Multiply(index, 0x0E). - bits 8..15 represent Multiply(index, 0x09). - bits 16..23 represent Multiply(index, 0x0D). - bits 24..31 represent Multiply(index, 0x0B). */ __declspec(align(16)) static const UINT32 invMixColumn_a[256] = { 0x00000000, 0x0B0D090E, 0x161A121C, 0x1D171B12, 0x2C342438, 0x27392D36, 0x3A2E3624, 0x31233F2A, 0x58684870, 0x5365417E, 0x4E725A6C, 0x457F5362, 0x745C6C48, 0x7F516546, 0x62467E54, 0x694B775A, 0xB0D090E0, 0xBBDD99EE, 0xA6CA82FC, 0xADC78BF2, 0x9CE4B4D8, 0x97E9BDD6, 0x8AFEA6C4, 0x81F3AFCA, 0xE8B8D890, 0xE3B5D19E, 0xFEA2CA8C, 0xF5AFC382, 0xC48CFCA8, 0xCF81F5A6, 0xD296EEB4, 0xD99BE7BA, 0x7BBB3BDB, 0x70B632D5, 0x6DA129C7, 0x66AC20C9, 0x578F1FE3, 0x5C8216ED, 0x41950DFF, 0x4A9804F1, 0x23D373AB, 0x28DE7AA5, 0x35C961B7, 0x3EC468B9, 0x0FE75793, 0x04EA5E9D, 0x19FD458F, 0x12F04C81, 0xCB6BAB3B, 0xC066A235, 0xDD71B927, 0xD67CB029, 0xE75F8F03, 0xEC52860D, 0xF1459D1F, 0xFA489411, 0x9303E34B, 0x980EEA45, 0x8519F157, 0x8E14F859, 0xBF37C773, 0xB43ACE7D, 0xA92DD56F, 0xA220DC61, 0xF66D76AD, 0xFD607FA3, 0xE07764B1, 0xEB7A6DBF, 0xDA595295, 0xD1545B9B, 0xCC434089, 0xC74E4987, 0xAE053EDD, 0xA50837D3, 0xB81F2CC1, 0xB31225CF, 0x82311AE5, 0x893C13EB, 0x942B08F9, 0x9F2601F7, 0x46BDE64D, 0x4DB0EF43, 0x50A7F451, 0x5BAAFD5F, 0x6A89C275, 0x6184CB7B, 0x7C93D069, 0x779ED967, 0x1ED5AE3D, 0x15D8A733, 0x08CFBC21, 0x03C2B52F, 0x32E18A05, 0x39EC830B, 0x24FB9819, 0x2FF69117, 0x8DD64D76, 0x86DB4478, 0x9BCC5F6A, 0x90C15664, 0xA1E2694E, 0xAAEF6040, 0xB7F87B52, 0xBCF5725C, 0xD5BE0506, 0xDEB30C08, 0xC3A4171A, 0xC8A91E14, 0xF98A213E, 0xF2872830, 0xEF903322, 0xE49D3A2C, 0x3D06DD96, 0x360BD498, 0x2B1CCF8A, 0x2011C684, 0x1132F9AE, 0x1A3FF0A0, 0x0728EBB2, 0x0C25E2BC, 0x656E95E6, 0x6E639CE8, 0x737487FA, 0x78798EF4, 0x495AB1DE, 0x4257B8D0, 0x5F40A3C2, 0x544DAACC, 0xF7DAEC41, 0xFCD7E54F, 0xE1C0FE5D, 0xEACDF753, 0xDBEEC879, 0xD0E3C177, 0xCDF4DA65, 0xC6F9D36B, 0xAFB2A431, 0xA4BFAD3F, 0xB9A8B62D, 0xB2A5BF23, 0x83868009, 0x888B8907, 0x959C9215, 0x9E919B1B, 0x470A7CA1, 0x4C0775AF, 0x51106EBD, 0x5A1D67B3, 0x6B3E5899, 0x60335197, 0x7D244A85, 0x7629438B, 0x1F6234D1, 0x146F3DDF, 0x097826CD, 0x02752FC3, 0x335610E9, 0x385B19E7, 0x254C02F5, 0x2E410BFB, 0x8C61D79A, 0x876CDE94, 0x9A7BC586, 0x9176CC88, 0xA055F3A2, 0xAB58FAAC, 0xB64FE1BE, 0xBD42E8B0, 0xD4099FEA, 0xDF0496E4, 0xC2138DF6, 0xC91E84F8, 0xF83DBBD2, 0xF330B2DC, 0xEE27A9CE, 0xE52AA0C0, 0x3CB1477A, 0x37BC4E74, 0x2AAB5566, 0x21A65C68, 0x10856342, 0x1B886A4C, 0x069F715E, 0x0D927850, 0x64D90F0A, 0x6FD40604, 0x72C31D16, 0x79CE1418, 0x48ED2B32, 0x43E0223C, 0x5EF7392E, 0x55FA3020, 0x01B79AEC, 0x0ABA93E2, 0x17AD88F0, 0x1CA081FE, 0x2D83BED4, 0x268EB7DA, 0x3B99ACC8, 0x3094A5C6, 0x59DFD29C, 0x52D2DB92, 0x4FC5C080, 0x44C8C98E, 0x75EBF6A4, 0x7EE6FFAA, 0x63F1E4B8, 0x68FCEDB6, 0xB1670A0C, 0xBA6A0302, 0xA77D1810, 0xAC70111E, 0x9D532E34, 0x965E273A, 0x8B493C28, 0x80443526, 0xE90F427C, 0xE2024B72, 0xFF155060, 0xF418596E, 0xC53B6644, 0xCE366F4A, 0xD3217458, 0xD82C7D56, 0x7A0CA137, 0x7101A839, 0x6C16B32B, 0x671BBA25, 0x5638850F, 0x5D358C01, 0x40229713, 0x4B2F9E1D, 0x2264E947, 0x2969E049, 0x347EFB5B, 0x3F73F255, 0x0E50CD7F, 0x055DC471, 0x184ADF63, 0x1347D66D, 0xCADC31D7, 0xC1D138D9, 0xDCC623CB, 0xD7CB2AC5, 0xE6E815EF, 0xEDE51CE1, 0xF0F207F3, 0xFBFF0EFD, 0x92B479A7, 0x99B970A9, 0x84AE6BBB, 0x8FA362B5, 0xBE805D9F, 0xB58D5491, 0xA89A4F83, 0xA397468D }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* For every value found at index we have: - bits 0..7 represent Multiply(index, 0x0B). - bits 8..15 represent Multiply(index, 0x0E). - bits 16..23 represent Multiply(index, 0x09). - bits 24..31 represent Multiply(index, 0x0D). */ __declspec(align(16)) static const UINT32 invMixColumn_b[256] = { 0x00000000, 0x0D090E0B, 0x1A121C16, 0x171B121D, 0x3424382C, 0x392D3627, 0x2E36243A, 0x233F2A31, 0x68487058, 0x65417E53, 0x725A6C4E, 0x7F536245, 0x5C6C4874, 0x5165467F, 0x467E5462, 0x4B775A69, 0xD090E0B0, 0xDD99EEBB, 0xCA82FCA6, 0xC78BF2AD, 0xE4B4D89C, 0xE9BDD697, 0xFEA6C48A, 0xF3AFCA81, 0xB8D890E8, 0xB5D19EE3, 0xA2CA8CFE, 0xAFC382F5, 0x8CFCA8C4, 0x81F5A6CF, 0x96EEB4D2, 0x9BE7BAD9, 0xBB3BDB7B, 0xB632D570, 0xA129C76D, 0xAC20C966, 0x8F1FE357, 0x8216ED5C, 0x950DFF41, 0x9804F14A, 0xD373AB23, 0xDE7AA528, 0xC961B735, 0xC468B93E, 0xE757930F, 0xEA5E9D04, 0xFD458F19, 0xF04C8112, 0x6BAB3BCB, 0x66A235C0, 0x71B927DD, 0x7CB029D6, 0x5F8F03E7, 0x52860DEC, 0x459D1FF1, 0x489411FA, 0x03E34B93, 0x0EEA4598, 0x19F15785, 0x14F8598E, 0x37C773BF, 0x3ACE7DB4, 0x2DD56FA9, 0x20DC61A2, 0x6D76ADF6, 0x607FA3FD, 0x7764B1E0, 0x7A6DBFEB, 0x595295DA, 0x545B9BD1, 0x434089CC, 0x4E4987C7, 0x053EDDAE, 0x0837D3A5, 0x1F2CC1B8, 0x1225CFB3, 0x311AE582, 0x3C13EB89, 0x2B08F994, 0x2601F79F, 0xBDE64D46, 0xB0EF434D, 0xA7F45150, 0xAAFD5F5B, 0x89C2756A, 0x84CB7B61, 0x93D0697C, 0x9ED96777, 0xD5AE3D1E, 0xD8A73315, 0xCFBC2108, 0xC2B52F03, 0xE18A0532, 0xEC830B39, 0xFB981924, 0xF691172F, 0xD64D768D, 0xDB447886, 0xCC5F6A9B, 0xC1566490, 0xE2694EA1, 0xEF6040AA, 0xF87B52B7, 0xF5725CBC, 0xBE0506D5, 0xB30C08DE, 0xA4171AC3, 0xA91E14C8, 0x8A213EF9, 0x872830F2, 0x903322EF, 0x9D3A2CE4, 0x06DD963D, 0x0BD49836, 0x1CCF8A2B, 0x11C68420, 0x32F9AE11, 0x3FF0A01A, 0x28EBB207, 0x25E2BC0C, 0x6E95E665, 0x639CE86E, 0x7487FA73, 0x798EF478, 0x5AB1DE49, 0x57B8D042, 0x40A3C25F, 0x4DAACC54, 0xDAEC41F7, 0xD7E54FFC, 0xC0FE5DE1, 0xCDF753EA, 0xEEC879DB, 0xE3C177D0, 0xF4DA65CD, 0xF9D36BC6, 0xB2A431AF, 0xBFAD3FA4, 0xA8B62DB9, 0xA5BF23B2, 0x86800983, 0x8B890788, 0x9C921595, 0x919B1B9E, 0x0A7CA147, 0x0775AF4C, 0x106EBD51, 0x1D67B35A, 0x3E58996B, 0x33519760, 0x244A857D, 0x29438B76, 0x6234D11F, 0x6F3DDF14, 0x7826CD09, 0x752FC302, 0x5610E933, 0x5B19E738, 0x4C02F525, 0x410BFB2E, 0x61D79A8C, 0x6CDE9487, 0x7BC5869A, 0x76CC8891, 0x55F3A2A0, 0x58FAACAB, 0x4FE1BEB6, 0x42E8B0BD, 0x099FEAD4, 0x0496E4DF, 0x138DF6C2, 0x1E84F8C9, 0x3DBBD2F8, 0x30B2DCF3, 0x27A9CEEE, 0x2AA0C0E5, 0xB1477A3C, 0xBC4E7437, 0xAB55662A, 0xA65C6821, 0x85634210, 0x886A4C1B, 0x9F715E06, 0x9278500D, 0xD90F0A64, 0xD406046F, 0xC31D1672, 0xCE141879, 0xED2B3248, 0xE0223C43, 0xF7392E5E, 0xFA302055, 0xB79AEC01, 0xBA93E20A, 0xAD88F017, 0xA081FE1C, 0x83BED42D, 0x8EB7DA26, 0x99ACC83B, 0x94A5C630, 0xDFD29C59, 0xD2DB9252, 0xC5C0804F, 0xC8C98E44, 0xEBF6A475, 0xE6FFAA7E, 0xF1E4B863, 0xFCEDB668, 0x670A0CB1, 0x6A0302BA, 0x7D1810A7, 0x70111EAC, 0x532E349D, 0x5E273A96, 0x493C288B, 0x44352680, 0x0F427CE9, 0x024B72E2, 0x155060FF, 0x18596EF4, 0x3B6644C5, 0x366F4ACE, 0x217458D3, 0x2C7D56D8, 0x0CA1377A, 0x01A83971, 0x16B32B6C, 0x1BBA2567, 0x38850F56, 0x358C015D, 0x22971340, 0x2F9E1D4B, 0x64E94722, 0x69E04929, 0x7EFB5B34, 0x73F2553F, 0x50CD7F0E, 0x5DC47105, 0x4ADF6318, 0x47D66D13, 0xDC31D7CA, 0xD138D9C1, 0xC623CBDC, 0xCB2AC5D7, 0xE815EFE6, 0xE51CE1ED, 0xF207F3F0, 0xFF0EFDFB, 0xB479A792, 0xB970A999, 0xAE6BBB84, 0xA362B58F, 0x805D9FBE, 0x8D5491B5, 0x9A4F83A8, 0x97468DA3 }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* For every value found at index we have: - bits 0..7 represent Multiply(index, 0x0D). - bits 8..15 represent Multiply(index, 0x0B). - bits 16..23 represent Multiply(index, 0x0E). - bits 24..31 represent Multiply(index, 0x09). */ __declspec(align(16)) static const UINT32 invMixColumn_c[256] = { 0x00000000, 0x090E0B0D, 0x121C161A, 0x1B121D17, 0x24382C34, 0x2D362739, 0x36243A2E, 0x3F2A3123, 0x48705868, 0x417E5365, 0x5A6C4E72, 0x5362457F, 0x6C48745C, 0x65467F51, 0x7E546246, 0x775A694B, 0x90E0B0D0, 0x99EEBBDD, 0x82FCA6CA, 0x8BF2ADC7, 0xB4D89CE4, 0xBDD697E9, 0xA6C48AFE, 0xAFCA81F3, 0xD890E8B8, 0xD19EE3B5, 0xCA8CFEA2, 0xC382F5AF, 0xFCA8C48C, 0xF5A6CF81, 0xEEB4D296, 0xE7BAD99B, 0x3BDB7BBB, 0x32D570B6, 0x29C76DA1, 0x20C966AC, 0x1FE3578F, 0x16ED5C82, 0x0DFF4195, 0x04F14A98, 0x73AB23D3, 0x7AA528DE, 0x61B735C9, 0x68B93EC4, 0x57930FE7, 0x5E9D04EA, 0x458F19FD, 0x4C8112F0, 0xAB3BCB6B, 0xA235C066, 0xB927DD71, 0xB029D67C, 0x8F03E75F, 0x860DEC52, 0x9D1FF145, 0x9411FA48, 0xE34B9303, 0xEA45980E, 0xF1578519, 0xF8598E14, 0xC773BF37, 0xCE7DB43A, 0xD56FA92D, 0xDC61A220, 0x76ADF66D, 0x7FA3FD60, 0x64B1E077, 0x6DBFEB7A, 0x5295DA59, 0x5B9BD154, 0x4089CC43, 0x4987C74E, 0x3EDDAE05, 0x37D3A508, 0x2CC1B81F, 0x25CFB312, 0x1AE58231, 0x13EB893C, 0x08F9942B, 0x01F79F26, 0xE64D46BD, 0xEF434DB0, 0xF45150A7, 0xFD5F5BAA, 0xC2756A89, 0xCB7B6184, 0xD0697C93, 0xD967779E, 0xAE3D1ED5, 0xA73315D8, 0xBC2108CF, 0xB52F03C2, 0x8A0532E1, 0x830B39EC, 0x981924FB, 0x91172FF6, 0x4D768DD6, 0x447886DB, 0x5F6A9BCC, 0x566490C1, 0x694EA1E2, 0x6040AAEF, 0x7B52B7F8, 0x725CBCF5, 0x0506D5BE, 0x0C08DEB3, 0x171AC3A4, 0x1E14C8A9, 0x213EF98A, 0x2830F287, 0x3322EF90, 0x3A2CE49D, 0xDD963D06, 0xD498360B, 0xCF8A2B1C, 0xC6842011, 0xF9AE1132, 0xF0A01A3F, 0xEBB20728, 0xE2BC0C25, 0x95E6656E, 0x9CE86E63, 0x87FA7374, 0x8EF47879, 0xB1DE495A, 0xB8D04257, 0xA3C25F40, 0xAACC544D, 0xEC41F7DA, 0xE54FFCD7, 0xFE5DE1C0, 0xF753EACD, 0xC879DBEE, 0xC177D0E3, 0xDA65CDF4, 0xD36BC6F9, 0xA431AFB2, 0xAD3FA4BF, 0xB62DB9A8, 0xBF23B2A5, 0x80098386, 0x8907888B, 0x9215959C, 0x9B1B9E91, 0x7CA1470A, 0x75AF4C07, 0x6EBD5110, 0x67B35A1D, 0x58996B3E, 0x51976033, 0x4A857D24, 0x438B7629, 0x34D11F62, 0x3DDF146F, 0x26CD0978, 0x2FC30275, 0x10E93356, 0x19E7385B, 0x02F5254C, 0x0BFB2E41, 0xD79A8C61, 0xDE94876C, 0xC5869A7B, 0xCC889176, 0xF3A2A055, 0xFAACAB58, 0xE1BEB64F, 0xE8B0BD42, 0x9FEAD409, 0x96E4DF04, 0x8DF6C213, 0x84F8C91E, 0xBBD2F83D, 0xB2DCF330, 0xA9CEEE27, 0xA0C0E52A, 0x477A3CB1, 0x4E7437BC, 0x55662AAB, 0x5C6821A6, 0x63421085, 0x6A4C1B88, 0x715E069F, 0x78500D92, 0x0F0A64D9, 0x06046FD4, 0x1D1672C3, 0x141879CE, 0x2B3248ED, 0x223C43E0, 0x392E5EF7, 0x302055FA, 0x9AEC01B7, 0x93E20ABA, 0x88F017AD, 0x81FE1CA0, 0xBED42D83, 0xB7DA268E, 0xACC83B99, 0xA5C63094, 0xD29C59DF, 0xDB9252D2, 0xC0804FC5, 0xC98E44C8, 0xF6A475EB, 0xFFAA7EE6, 0xE4B863F1, 0xEDB668FC, 0x0A0CB167, 0x0302BA6A, 0x1810A77D, 0x111EAC70, 0x2E349D53, 0x273A965E, 0x3C288B49, 0x35268044, 0x427CE90F, 0x4B72E202, 0x5060FF15, 0x596EF418, 0x6644C53B, 0x6F4ACE36, 0x7458D321, 0x7D56D82C, 0xA1377A0C, 0xA8397101, 0xB32B6C16, 0xBA25671B, 0x850F5638, 0x8C015D35, 0x97134022, 0x9E1D4B2F, 0xE9472264, 0xE0492969, 0xFB5B347E, 0xF2553F73, 0xCD7F0E50, 0xC471055D, 0xDF63184A, 0xD66D1347, 0x31D7CADC, 0x38D9C1D1, 0x23CBDCC6, 0x2AC5D7CB, 0x15EFE6E8, 0x1CE1EDE5, 0x07F3F0F2, 0x0EFDFBFF, 0x79A792B4, 0x70A999B9, 0x6BBB84AE, 0x62B58FA3, 0x5D9FBE80, 0x5491B58D, 0x4F83A89A, 0x468DA397 }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* For every value found at index we have: - bits 0..7 represent Multiply(index, 0x09). - bits 8..15 represent Multiply(index, 0x0D). - bits 16..23 represent Multiply(index, 0x0B). - bits 24..31 represent Multiply(index, 0x0E). */ __declspec(align(16)) static const UINT32 invMixColumn_d[256] = { 0x00000000, 0x0E0B0D09, 0x1C161A12, 0x121D171B, 0x382C3424, 0x3627392D, 0x243A2E36, 0x2A31233F, 0x70586848, 0x7E536541, 0x6C4E725A, 0x62457F53, 0x48745C6C, 0x467F5165, 0x5462467E, 0x5A694B77, 0xE0B0D090, 0xEEBBDD99, 0xFCA6CA82, 0xF2ADC78B, 0xD89CE4B4, 0xD697E9BD, 0xC48AFEA6, 0xCA81F3AF, 0x90E8B8D8, 0x9EE3B5D1, 0x8CFEA2CA, 0x82F5AFC3, 0xA8C48CFC, 0xA6CF81F5, 0xB4D296EE, 0xBAD99BE7, 0xDB7BBB3B, 0xD570B632, 0xC76DA129, 0xC966AC20, 0xE3578F1F, 0xED5C8216, 0xFF41950D, 0xF14A9804, 0xAB23D373, 0xA528DE7A, 0xB735C961, 0xB93EC468, 0x930FE757, 0x9D04EA5E, 0x8F19FD45, 0x8112F04C, 0x3BCB6BAB, 0x35C066A2, 0x27DD71B9, 0x29D67CB0, 0x03E75F8F, 0x0DEC5286, 0x1FF1459D, 0x11FA4894, 0x4B9303E3, 0x45980EEA, 0x578519F1, 0x598E14F8, 0x73BF37C7, 0x7DB43ACE, 0x6FA92DD5, 0x61A220DC, 0xADF66D76, 0xA3FD607F, 0xB1E07764, 0xBFEB7A6D, 0x95DA5952, 0x9BD1545B, 0x89CC4340, 0x87C74E49, 0xDDAE053E, 0xD3A50837, 0xC1B81F2C, 0xCFB31225, 0xE582311A, 0xEB893C13, 0xF9942B08, 0xF79F2601, 0x4D46BDE6, 0x434DB0EF, 0x5150A7F4, 0x5F5BAAFD, 0x756A89C2, 0x7B6184CB, 0x697C93D0, 0x67779ED9, 0x3D1ED5AE, 0x3315D8A7, 0x2108CFBC, 0x2F03C2B5, 0x0532E18A, 0x0B39EC83, 0x1924FB98, 0x172FF691, 0x768DD64D, 0x7886DB44, 0x6A9BCC5F, 0x6490C156, 0x4EA1E269, 0x40AAEF60, 0x52B7F87B, 0x5CBCF572, 0x06D5BE05, 0x08DEB30C, 0x1AC3A417, 0x14C8A91E, 0x3EF98A21, 0x30F28728, 0x22EF9033, 0x2CE49D3A, 0x963D06DD, 0x98360BD4, 0x8A2B1CCF, 0x842011C6, 0xAE1132F9, 0xA01A3FF0, 0xB20728EB, 0xBC0C25E2, 0xE6656E95, 0xE86E639C, 0xFA737487, 0xF478798E, 0xDE495AB1, 0xD04257B8, 0xC25F40A3, 0xCC544DAA, 0x41F7DAEC, 0x4FFCD7E5, 0x5DE1C0FE, 0x53EACDF7, 0x79DBEEC8, 0x77D0E3C1, 0x65CDF4DA, 0x6BC6F9D3, 0x31AFB2A4, 0x3FA4BFAD, 0x2DB9A8B6, 0x23B2A5BF, 0x09838680, 0x07888B89, 0x15959C92, 0x1B9E919B, 0xA1470A7C, 0xAF4C0775, 0xBD51106E, 0xB35A1D67, 0x996B3E58, 0x97603351, 0x857D244A, 0x8B762943, 0xD11F6234, 0xDF146F3D, 0xCD097826, 0xC302752F, 0xE9335610, 0xE7385B19, 0xF5254C02, 0xFB2E410B, 0x9A8C61D7, 0x94876CDE, 0x869A7BC5, 0x889176CC, 0xA2A055F3, 0xACAB58FA, 0xBEB64FE1, 0xB0BD42E8, 0xEAD4099F, 0xE4DF0496, 0xF6C2138D, 0xF8C91E84, 0xD2F83DBB, 0xDCF330B2, 0xCEEE27A9, 0xC0E52AA0, 0x7A3CB147, 0x7437BC4E, 0x662AAB55, 0x6821A65C, 0x42108563, 0x4C1B886A, 0x5E069F71, 0x500D9278, 0x0A64D90F, 0x046FD406, 0x1672C31D, 0x1879CE14, 0x3248ED2B, 0x3C43E022, 0x2E5EF739, 0x2055FA30, 0xEC01B79A, 0xE20ABA93, 0xF017AD88, 0xFE1CA081, 0xD42D83BE, 0xDA268EB7, 0xC83B99AC, 0xC63094A5, 0x9C59DFD2, 0x9252D2DB, 0x804FC5C0, 0x8E44C8C9, 0xA475EBF6, 0xAA7EE6FF, 0xB863F1E4, 0xB668FCED, 0x0CB1670A, 0x02BA6A03, 0x10A77D18, 0x1EAC7011, 0x349D532E, 0x3A965E27, 0x288B493C, 0x26804435, 0x7CE90F42, 0x72E2024B, 0x60FF1550, 0x6EF41859, 0x44C53B66, 0x4ACE366F, 0x58D32174, 0x56D82C7D, 0x377A0CA1, 0x397101A8, 0x2B6C16B3, 0x25671BBA, 0x0F563885, 0x015D358C, 0x13402297, 0x1D4B2F9E, 0x472264E9, 0x492969E0, 0x5B347EFB, 0x553F73F2, 0x7F0E50CD, 0x71055DC4, 0x63184ADF, 0x6D1347D6, 0xD7CADC31, 0xD9C1D138, 0xCBDCC623, 0xC5D7CB2A, 0xEFE6E815, 0xE1EDE51C, 0xF3F0F207, 0xFDFBFF0E, 0xA792B479, 0xA999B970, 0xBB84AE6B, 0xB58FA362, 0x9FBE805D, 0x91B58D54, 0x83A89A4F, 0x8DA39746 }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// The S box used to encrypt __declspec(align(16)) const UINT32 sBox[256] = { //0 1 2 3 4 5 6 7 8 9 A B C D E F 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, //0 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, //1 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, //2 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, //3 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, //4 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, //5 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, //6 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, //7 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, //8 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, //9 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, //A 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, //B 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, //C 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, //D 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, //E 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 //F }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// The reversed S box used to decrypt __declspec(align(16)) const UINT32 rsBox[256] = { //0 1 2 3 4 5 6 7 8 9 A B C D E F 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, //0 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, //1 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, //2 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, //3 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, //4 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, //5 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, //6 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, //7 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, //8 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, //9 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, //A 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, //B 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, //C 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, //D 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, //E 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d //F }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class AES_GPU_DX10_Description : public IAlgorithmDescription { public: AES_GPU_DX10_Description() { m_IsOK = false; // This may fail if Direct3D 10 isn't installed ( running on Windows XP or older ) TCHAR szPath[MAX_PATH + 1] = {0}; if( ::GetSystemDirectory( szPath, MAX_PATH + 1 ) ) { _tcscat_s( szPath, MAX_PATH, _T("\\d3d10.dll") ); HMODULE hMod = LoadLibrary( szPath ); if(hMod != NULL) { m_IsOK = true; FreeLibrary( hMod ); } } } bool IsOK() { return m_IsOK; }; const TCHAR* ClassName() { return _T("AES_GPU_DX10"); }; const TCHAR* ClassDescription() { return _T("Implements the AES encryption/decryption algorithm using the GPU resources and DirectX 10 interface."); }; CLASS_ID ClassID() { return AES_GPU_DX10_ALGORITHM_CLASS_ID; } CLASS_ID InterfaceID() { return AES_ALGORITHM_CLASS_ID; } IAlgorithm* Create() { if( m_IsOK ) return AES_GPU_DX10_Internal::Create(); else return NULL; } private: bool m_IsOK; }; static AES_GPU_DX10_Description class_description; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// AES_GPU_DX10_API IAlgorithmDescription* GetDescription(UINT32 acmVersion) { if( class_description.IsOK() && acmVersion == AMCLIB_VERSION ) return &class_description; else return NULL; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// AES_GPU_DX10_Internal* AES_GPU_DX10_Internal::Create() { HRESULT hr = S_OK; TCHAR *deviceName = NULL; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Create the Direct3D 10 Device //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// HMODULE hModD3D10 = LoadLibrary( _T("d3d10.dll") ); if( hModD3D10 == NULL ) return NULL; LPD3D10CREATEDEVICE DynamicD3D10CreateDevice = ( LPD3D10CREATEDEVICE )GetProcAddress( hModD3D10, "D3D10CreateDevice" ); if( DynamicD3D10CreateDevice == NULL ) return NULL; static const D3D10_DRIVER_TYPE driverType[] = { D3D10_DRIVER_TYPE_HARDWARE, // The current hardware implementation found on this machine D3D10_DRIVER_TYPE_WARP, // Very fast software implementation D3D10_DRIVER_TYPE_REFERENCE // Slow but very accurate software implementation }; DWORD dwCreateFlags = 0; #if defined(DEBUG) || defined(_DEBUG) dwCreateFlags |= D3D10_CREATE_DEVICE_DEBUG; // For debugging purpose #endif // Try to create one D3D 10 device in the order from driverType ID3D10Device *pDevice = NULL; for( int deviceIndex = 0; deviceIndex < countof(driverType); deviceIndex++ ) { hr = DynamicD3D10CreateDevice( NULL, driverType[deviceIndex], ( HMODULE )0, dwCreateFlags, D3D10_SDK_VERSION, &pDevice ); if( SUCCEEDED( hr ) ) { if( driverType[deviceIndex] == D3D10_DRIVER_TYPE_WARP ) { static const TCHAR warpName[] = _T("WARP10 - Software"); deviceName = (TCHAR *)new UINT8[sizeof(warpName)]; memcpy(deviceName, warpName, sizeof(warpName)); } else if( driverType[deviceIndex] == D3D10_DRIVER_TYPE_REFERENCE ) { static const TCHAR refName[] = _T("Reference - Software"); deviceName = (TCHAR *)new UINT8[sizeof(refName)]; memcpy(deviceName, refName, sizeof(refName)); } else { // Get the name of the video card HMODULE s_hModDXGI = NULL; LPCREATEDXGIFACTORY s_DynamicCreateDXGIFactory = NULL; IDXGIFactory* pDXGIFactory = NULL; s_hModDXGI = LoadLibrary( _T("dxgi.dll") ); if( s_hModDXGI ) { s_DynamicCreateDXGIFactory = ( LPCREATEDXGIFACTORY )GetProcAddress( s_hModDXGI, "CreateDXGIFactory" ); if( s_DynamicCreateDXGIFactory != NULL ) { s_DynamicCreateDXGIFactory( __uuidof( IDXGIFactory ), ( LPVOID* )&pDXGIFactory ); if( pDXGIFactory != NULL ) { for( int index = 0; ; ++index ) { IDXGIAdapter* pAdapter = NULL; hr = pDXGIFactory->EnumAdapters( index, &pAdapter ); if( FAILED( hr ) ) // DXGIERR_NOT_FOUND is expected when the end of the list is hit break; DXGI_ADAPTER_DESC AdapterDesc; pAdapter->GetDesc( &AdapterDesc ); int nameLen = (int)wcslen(AdapterDesc.Description) + 1; deviceName = new TCHAR[nameLen]; _tcscpy_s(deviceName, nameLen, AdapterDesc.Description); SAFE_RELEASE( pAdapter ); break; } SAFE_RELEASE( pDXGIFactory ); } } FreeLibrary(s_hModDXGI); } if( deviceName == NULL ) { static const TCHAR hardName[] = _T("Unknown Hardware"); deviceName = (TCHAR *)new UINT8[sizeof(hardName)]; memcpy(deviceName, hardName, sizeof(hardName)); } } break; } } if( FAILED(hr) ) { FreeLibrary(hModD3D10); return NULL; // No device could be created } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Create the AES_GPU_DX10_Internal object that will be returned by this function. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// AES_GPU_DX10_Internal *retVal = new AES_GPU_DX10_Internal(); retVal->m_pDevice = pDevice; retVal->mDeviceName = deviceName; retVal->m_hModD3D10 = hModD3D10; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Create the Effect object for the shader found in the resources and compile it //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ID3D10Blob *errors = NULL; DWORD dwShaderFlags = D3D10_SHADER_ENABLE_STRICTNESS | D3D10_SHADER_OPTIMIZATION_LEVEL3; #if defined( DEBUG ) || defined( _DEBUG ) dwShaderFlags |= D3D10_SHADER_DEBUG; hr = D3D10CreateBlob(1024, &errors); #endif hr = D3DX10CreateEffectFromResource( gHModule, _T("AES_GPU_DX10_SHADER"), _T("AES_GPU_DX10_SHADER.fx"), NULL, NULL, "fx_4_0", dwShaderFlags, 0, pDevice, NULL, NULL, &retVal->m_pEffect10, &errors, NULL ); if( FAILED( hr ) ) { #if defined( DEBUG ) || defined( _DEBUG ) printf("%s", (char*)errors->GetBufferPointer()); __debugbreak(); #endif goto _EXIT_AND_RETURN_NULL_; } else { #if defined( DEBUG ) || defined( _DEBUG ) ID3D10Blob *asmShader = NULL; hr = D3D10CreateBlob(65536, &asmShader); hr = D3DDisassemble10Effect( retVal->m_pEffect10, 0, &asmShader); FILE *fout; fopen_s(&fout, "shader_asm.txt", "wt"); if(fout != NULL) { fprintf(fout,"%s", (char*)asmShader->GetBufferPointer()); fclose(fout); } SAFE_RELEASE(asmShader); #endif } SAFE_RELEASE(errors); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Set the constant values in the shader ( these constants are valid on the entire life of retVal object ) //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ID3D10EffectScalarVariable *cBuffer = NULL; cBuffer = retVal->m_pEffect10->GetVariableByName( "sBoxMixColumn_a" )->AsScalar(); if( cBuffer->IsValid() == FALSE ) goto _EXIT_AND_RETURN_NULL_; cBuffer->SetIntArray((int*)sBoxMixColumn_a, 0, countof(sBoxMixColumn_a)); cBuffer = retVal->m_pEffect10->GetVariableByName( "sBoxMixColumn_b" )->AsScalar(); if( cBuffer->IsValid() == FALSE ) goto _EXIT_AND_RETURN_NULL_; cBuffer->SetIntArray((int*)sBoxMixColumn_b, 0, countof(sBoxMixColumn_b)); cBuffer = retVal->m_pEffect10->GetVariableByName( "sBoxMixColumn_c" )->AsScalar(); if( cBuffer->IsValid() == FALSE ) goto _EXIT_AND_RETURN_NULL_; cBuffer->SetIntArray((int*)sBoxMixColumn_c, 0, countof(sBoxMixColumn_c)); cBuffer = retVal->m_pEffect10->GetVariableByName( "sBoxMixColumn_d" )->AsScalar(); if( cBuffer->IsValid() == FALSE ) goto _EXIT_AND_RETURN_NULL_; cBuffer->SetIntArray((int*)sBoxMixColumn_d, 0, countof(sBoxMixColumn_d)); cBuffer = retVal->m_pEffect10->GetVariableByName( "rsBoxInvMixColumn_a" )->AsScalar(); if( cBuffer->IsValid() == FALSE ) goto _EXIT_AND_RETURN_NULL_; cBuffer->SetIntArray((int*)rsBoxInvMixColumn_a, 0, countof(rsBoxInvMixColumn_a)); cBuffer = retVal->m_pEffect10->GetVariableByName( "rsBoxInvMixColumn_b" )->AsScalar(); if( cBuffer->IsValid() == FALSE ) goto _EXIT_AND_RETURN_NULL_; cBuffer->SetIntArray((int*)rsBoxInvMixColumn_b, 0, countof(rsBoxInvMixColumn_b)); cBuffer = retVal->m_pEffect10->GetVariableByName( "rsBoxInvMixColumn_c" )->AsScalar(); if( cBuffer->IsValid() == FALSE ) goto _EXIT_AND_RETURN_NULL_; cBuffer->SetIntArray((int*)rsBoxInvMixColumn_c, 0, countof(rsBoxInvMixColumn_c)); cBuffer = retVal->m_pEffect10->GetVariableByName( "rsBoxInvMixColumn_d" )->AsScalar(); if( cBuffer->IsValid() == FALSE ) goto _EXIT_AND_RETURN_NULL_; cBuffer->SetIntArray((int*)rsBoxInvMixColumn_d, 0, countof(rsBoxInvMixColumn_d)); cBuffer = retVal->m_pEffect10->GetVariableByName( "sBox" )->AsScalar(); if( cBuffer->IsValid() == FALSE ) goto _EXIT_AND_RETURN_NULL_; cBuffer->SetIntArray((int*)sBox, 0, countof(sBox)); cBuffer = retVal->m_pEffect10->GetVariableByName( "rsBox" )->AsScalar(); if( cBuffer->IsValid() == FALSE ) goto _EXIT_AND_RETURN_NULL_; cBuffer->SetIntArray((int*)rsBox, 0, countof(rsBox)); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Set the texture constant values in the shader ( these constants are valid on the entire life of retVal object ) //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// cBuffer = retVal->m_pEffect10->GetVariableByName( "tsBoxMixColumn_a" )->AsScalar(); if( cBuffer->IsValid() == FALSE ) goto _EXIT_AND_RETURN_NULL_; cBuffer->SetIntArray((int*)sBoxMixColumn_a, 0, countof(sBoxMixColumn_a)); cBuffer = retVal->m_pEffect10->GetVariableByName( "tsBoxMixColumn_b" )->AsScalar(); if( cBuffer->IsValid() == FALSE ) goto _EXIT_AND_RETURN_NULL_; cBuffer->SetIntArray((int*)sBoxMixColumn_b, 0, countof(sBoxMixColumn_b)); cBuffer = retVal->m_pEffect10->GetVariableByName( "tsBoxMixColumn_c" )->AsScalar(); if( cBuffer->IsValid() == FALSE ) goto _EXIT_AND_RETURN_NULL_; cBuffer->SetIntArray((int*)sBoxMixColumn_c, 0, countof(sBoxMixColumn_c)); cBuffer = retVal->m_pEffect10->GetVariableByName( "tsBoxMixColumn_d" )->AsScalar(); if( cBuffer->IsValid() == FALSE ) goto _EXIT_AND_RETURN_NULL_; cBuffer->SetIntArray((int*)sBoxMixColumn_d, 0, countof(sBoxMixColumn_d)); cBuffer = retVal->m_pEffect10->GetVariableByName( "trsBoxInvMixColumn_a" )->AsScalar(); if( cBuffer->IsValid() == FALSE ) goto _EXIT_AND_RETURN_NULL_; cBuffer->SetIntArray((int*)rsBoxInvMixColumn_a, 0, countof(rsBoxInvMixColumn_a)); cBuffer = retVal->m_pEffect10->GetVariableByName( "trsBoxInvMixColumn_b" )->AsScalar(); if( cBuffer->IsValid() == FALSE ) goto _EXIT_AND_RETURN_NULL_; cBuffer->SetIntArray((int*)rsBoxInvMixColumn_b, 0, countof(rsBoxInvMixColumn_b)); cBuffer = retVal->m_pEffect10->GetVariableByName( "trsBoxInvMixColumn_c" )->AsScalar(); if( cBuffer->IsValid() == FALSE ) goto _EXIT_AND_RETURN_NULL_; cBuffer->SetIntArray((int*)rsBoxInvMixColumn_c, 0, countof(rsBoxInvMixColumn_c)); cBuffer = retVal->m_pEffect10->GetVariableByName( "trsBoxInvMixColumn_d" )->AsScalar(); if( cBuffer->IsValid() == FALSE ) goto _EXIT_AND_RETURN_NULL_; cBuffer->SetIntArray((int*)rsBoxInvMixColumn_d, 0, countof(rsBoxInvMixColumn_d)); cBuffer = retVal->m_pEffect10->GetVariableByName( "tsBox" )->AsScalar(); if( cBuffer->IsValid() == FALSE ) goto _EXIT_AND_RETURN_NULL_; cBuffer->SetIntArray((int*)sBox, 0, countof(sBox)); cBuffer = retVal->m_pEffect10->GetVariableByName( "trsBox" )->AsScalar(); if( cBuffer->IsValid() == FALSE ) goto _EXIT_AND_RETURN_NULL_; cBuffer->SetIntArray((int*)rsBox, 0, countof(rsBox)); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Get the pointers to the constants that need updated very often //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// retVal->m_pShaderIV = retVal->m_pEffect10->GetVariableByName( "IV" )->AsVector(); if( retVal->m_pShaderIV->IsValid() == FALSE ) goto _EXIT_AND_RETURN_NULL_; retVal->m_pShaderKeyEnc = retVal->m_pEffect10->GetVariableByName( "key" )->AsVector(); if( retVal->m_pShaderKeyEnc->IsValid() == FALSE ) goto _EXIT_AND_RETURN_NULL_; retVal->m_pShaderKeyDec = retVal->m_pEffect10->GetVariableByName( "rkey" )->AsVector(); if( retVal->m_pShaderKeyDec->IsValid() == FALSE ) goto _EXIT_AND_RETURN_NULL_; retVal->m_pShaderKeySize = retVal->m_pEffect10->GetVariableByName( "keySize" )->AsScalar(); if( retVal->m_pShaderKeySize->IsValid() == FALSE ) goto _EXIT_AND_RETURN_NULL_; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Get the pointers to the techniques defined by the shader //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// retVal->m_pEncryptECB = retVal->m_pEffect10->GetTechniqueByName( "AES_Encrypt_ECB_tx_cb" ); if( retVal->m_pEncryptECB->IsValid() == FALSE ) goto _EXIT_AND_RETURN_NULL_; retVal->m_pDecryptECB = retVal->m_pEffect10->GetTechniqueByName( "AES_Decrypt_ECB_tx_cb" ); if( retVal->m_pDecryptECB->IsValid() == FALSE ) goto _EXIT_AND_RETURN_NULL_; retVal->m_pEncDecCTR = retVal->m_pEffect10->GetTechniqueByName( "AES_EncryptDecrypt_CTR_tx_cb" ); if( retVal->m_pEncDecCTR->IsValid() == FALSE ) goto _EXIT_AND_RETURN_NULL_; retVal->m_pDecryptCBC = retVal->m_pEffect10->GetTechniqueByName( "AES_Decrypt_CBC_tx_cb" ); if( retVal->m_pDecryptCBC->IsValid() == FALSE ) goto _EXIT_AND_RETURN_NULL_; // All the techniques have the same vertex format at the input, and all have only one pass retVal->m_pEncrypt = retVal->m_pEncryptECB; retVal->m_pDecrypt = retVal->m_pDecryptECB; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Create the Vertex Buffer and Input Layout for the quad that will be rendered on the screen //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// typedef struct _QUAD_VERTEX { D3DXVECTOR3 position; D3DXVECTOR2 texCoord; }QUAD_VERTEX; { static const D3D10_INPUT_ELEMENT_DESC quadLayout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "TEXTURE", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 }, }; static const QUAD_VERTEX quadVertexBuffer[] = { { D3DXVECTOR3( -1, 1, 0 ), D3DXVECTOR2( 0, 0 ) }, { D3DXVECTOR3( 1, 1, 0 ), D3DXVECTOR2( 1, 0 ) }, { D3DXVECTOR3( -1, -1, 0 ), D3DXVECTOR2( 0, 1 ) }, { D3DXVECTOR3( 1, 1, 0 ), D3DXVECTOR2( 1, 0 ) }, { D3DXVECTOR3( 1, -1, 0 ), D3DXVECTOR2( 1, 1 ) }, { D3DXVECTOR3( -1, -1, 0 ), D3DXVECTOR2( 0, 1 ) } }; static const D3D10_BUFFER_DESC vbdesc = { countof(quadVertexBuffer) * sizeof( QUAD_VERTEX ), D3D10_USAGE_IMMUTABLE, D3D10_BIND_VERTEX_BUFFER, 0, 0 }; static const D3D10_SUBRESOURCE_DATA InitData = { quadVertexBuffer, 0, 0 }; // Create the vertex buffer hr = pDevice->CreateBuffer( &vbdesc, &InitData, &retVal->m_pQuadVB ); if( FAILED( hr ) ) goto _EXIT_AND_RETURN_NULL_; // Create the quad vertex input layout D3D10_PASS_DESC PassDesc; retVal->m_pEncrypt->GetPassByIndex( 0 )->GetDesc( &PassDesc ); hr = pDevice->CreateInputLayout( quadLayout, countof(quadLayout), PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &retVal->m_pQuadVertexLayout ); if( FAILED( hr ) ) goto _EXIT_AND_RETURN_NULL_; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Create the source and destination texture and its associated ShaderResourceView // respectively RenderTargetView. Also create the staging texture to copy results from GPU. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// D3D10_TEXTURE2D_DESC dsTex; ZeroMemory( &dsTex, sizeof( dsTex ) ); dsTex.Width = TEXTURE_SIZEX; dsTex.Height = TEXTURE_SIZEY; dsTex.MipLevels = 1; dsTex.Format = DXGI_FORMAT_R32G32B32A32_UINT; dsTex.SampleDesc.Count = 1; dsTex.SampleDesc.Quality= 0; dsTex.Usage = D3D10_USAGE_DEFAULT; dsTex.BindFlags = D3D10_BIND_SHADER_RESOURCE; dsTex.CPUAccessFlags = 0; dsTex.MiscFlags = 0; dsTex.ArraySize = 1; hr = pDevice->CreateTexture2D( &dsTex, NULL, &retVal->m_pSourceTexture ); if( FAILED( hr ) ) goto _EXIT_AND_RETURN_NULL_; dsTex.BindFlags = D3D10_BIND_RENDER_TARGET; hr = pDevice->CreateTexture2D( &dsTex, NULL, &retVal->m_pDestTexture ); if( FAILED( hr ) ) goto _EXIT_AND_RETURN_NULL_; // Create the staging texture used to write to GPU dsTex.Usage = D3D10_USAGE_STAGING; dsTex.BindFlags = 0; dsTex.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE; hr = pDevice->CreateTexture2D( &dsTex, NULL, &retVal->m_pStagingSrcTexture ); if( FAILED( hr ) ) goto _EXIT_AND_RETURN_NULL_; // Create the staging texture used to read from GPU dsTex.CPUAccessFlags = D3D10_CPU_ACCESS_READ; hr = pDevice->CreateTexture2D( &dsTex, NULL, &retVal->m_pStagingDstTexture ); if( FAILED( hr ) ) goto _EXIT_AND_RETURN_NULL_; // Create Source Resource View D3D10_SHADER_RESOURCE_VIEW_DESC SRVDesc; ZeroMemory( &SRVDesc, sizeof( SRVDesc ) ); SRVDesc.Format = DXGI_FORMAT_R32G32B32A32_UINT; SRVDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D; SRVDesc.Texture2D.MipLevels = 1; hr = pDevice->CreateShaderResourceView( retVal->m_pSourceTexture, &SRVDesc, &retVal->m_pSourceTexRV ); if( FAILED( hr ) ) goto _EXIT_AND_RETURN_NULL_; // Create Destination RenderTarget View D3D10_RENDER_TARGET_VIEW_DESC DescRT; DescRT.Format = DXGI_FORMAT_R32G32B32A32_UINT; DescRT.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2D; DescRT.Texture2D.MipSlice = 0; hr = pDevice->CreateRenderTargetView( retVal->m_pDestTexture, &DescRT, &retVal->m_pDestRTV ); if( FAILED( hr ) ) goto _EXIT_AND_RETURN_NULL_; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Create the texture and its resource view, used to hold the constant tables, and set it's contents //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ZeroMemory( &dsTex, sizeof( dsTex ) ); dsTex.Width = countof(sBox); dsTex.Height = 10; // The number of arrays to be set dsTex.MipLevels = 1; dsTex.Format = DXGI_FORMAT_R32_UINT; dsTex.SampleDesc.Count = 1; dsTex.SampleDesc.Quality= 0; dsTex.Usage = D3D10_USAGE_DEFAULT; dsTex.BindFlags = D3D10_BIND_SHADER_RESOURCE; dsTex.CPUAccessFlags = 0; dsTex.MiscFlags = 0; dsTex.ArraySize = 1; hr = pDevice->CreateTexture2D( &dsTex, NULL, &retVal->m_pTexConstants ); if( FAILED( hr ) ) goto _EXIT_AND_RETURN_NULL_; // Create the staging texture used to write to GPU { ID3D10Texture2D *pStagingTex; dsTex.Usage = D3D10_USAGE_STAGING; dsTex.BindFlags = 0; dsTex.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE; hr = pDevice->CreateTexture2D( &dsTex, NULL, &pStagingTex ); if( FAILED( hr ) ) goto _EXIT_AND_RETURN_NULL_; // Map the CPU staging resource D3D10_MAPPED_TEXTURE2D map; hr = pStagingTex->Map( 0, D3D10_MAP_WRITE, NULL, &map ); if( FAILED( hr ) ) goto _EXIT_AND_RETURN_NULL_; UINT32 *dst = (UINT32*)map.pData; memcpy(dst, sBoxMixColumn_a, map.RowPitch); dst += 256; memcpy(dst, sBoxMixColumn_b, map.RowPitch); dst += 256; memcpy(dst, sBoxMixColumn_c, map.RowPitch); dst += 256; memcpy(dst, sBoxMixColumn_d, map.RowPitch); dst += 256; memcpy(dst, rsBoxInvMixColumn_a, map.RowPitch); dst += 256; memcpy(dst, rsBoxInvMixColumn_b, map.RowPitch); dst += 256; memcpy(dst, rsBoxInvMixColumn_c, map.RowPitch); dst += 256; memcpy(dst, rsBoxInvMixColumn_d, map.RowPitch); dst += 256; memcpy(dst, sBox, map.RowPitch); dst += 256; memcpy(dst, rsBox, map.RowPitch); pStagingTex->Unmap( 0 ); pDevice->CopyResource( retVal->m_pTexConstants, pStagingTex ); SAFE_RELEASE(pStagingTex); } // Create Source Resource View ZeroMemory( &SRVDesc, sizeof( SRVDesc ) ); SRVDesc.Format = DXGI_FORMAT_R32_UINT; SRVDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D; SRVDesc.Texture2D.MipLevels = 1; hr = pDevice->CreateShaderResourceView( retVal->m_pTexConstants, &SRVDesc, &retVal->m_pTexConstantsRV ); if( FAILED( hr ) ) goto _EXIT_AND_RETURN_NULL_; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Set the view port that will always be used. The view port must match the rendered texture size. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// D3D10_VIEWPORT PVP; PVP.Width = TEXTURE_SIZEX; PVP.Height = TEXTURE_SIZEY; PVP.MinDepth = 0; PVP.MaxDepth = 1; PVP.TopLeftX = 0; PVP.TopLeftY = 0; pDevice->RSSetViewports( 1, &PVP ); // Set the scissor to render the entire view port D3D10_RECT rects[1]; rects[0].left = 0; rects[0].right = TEXTURE_SIZEX; rects[0].top = 0; rects[0].bottom = TEXTURE_SIZEY; pDevice->RSSetScissorRects( 1, rects ); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Set the input layout for the vertex shader, and also set the vertex buffer of the quad as the default one. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// UINT offsets = 0; UINT uStrides = sizeof( QUAD_VERTEX ); pDevice->IASetInputLayout( retVal->m_pQuadVertexLayout ); pDevice->IASetVertexBuffers( 0, 1, &retVal->m_pQuadVB, &uStrides, &offsets ); pDevice->IASetPrimitiveTopology( D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST ); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Bind the destination render target view to the output of the pipeline //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// pDevice->OMSetRenderTargets( 1, &retVal->m_pDestRTV, NULL ); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Bind the source resource view to txSource and txConstants in the shader //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ID3D10EffectShaderResourceVariable *ptxSource; ptxSource = retVal->m_pEffect10->GetVariableByName( "txSource" )->AsShaderResource(); if( ptxSource->IsValid() == FALSE ) goto _EXIT_AND_RETURN_NULL_; ptxSource->SetResource( retVal->m_pSourceTexRV ); ID3D10EffectShaderResourceVariable *ptxConstants; ptxConstants = retVal->m_pEffect10->GetVariableByName( "txConstants" )->AsShaderResource(); if( ptxConstants->IsValid() == FALSE ) goto _EXIT_AND_RETURN_NULL_; ptxConstants->SetResource( retVal->m_pTexConstantsRV ); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Tell the shader code the size of the textures that we will use //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ID3D10EffectVectorVariable *ptxSourceSize; ptxSourceSize = retVal->m_pEffect10->GetVariableByName( "txSize" )->AsVector(); if( ptxSourceSize->IsValid() != FALSE ) { D3DXVECTOR4 vTextureSize( (float)TEXTURE_SIZEX, (float)TEXTURE_SIZEY, 0.0f, 0.0f ); ptxSourceSize->SetFloatVector( (float*)vTextureSize ); } else goto _EXIT_AND_RETURN_NULL_; return retVal; _EXIT_AND_RETURN_NULL_: delete retVal; return NULL; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// AES_GPU_DX10_Internal::AES_GPU_DX10_Internal() { m_SupportedModes = IAlgorithmAES::AES_ECB | IAlgorithmAES::AES_CBC | IAlgorithmAES::AES_CTR; m_Mode = IAlgorithmAES::AES_ECB; m_keySize = AES_Key::AES_KeyInvalid; memset(m_IV, 0, IAlgorithmAES::BlockSizeBytes); memset(m_internalEncIV, 0, IAlgorithmAES::BlockSizeBytes); memset(m_internalDecIV, 0, IAlgorithmAES::BlockSizeBytes); mDeviceName = NULL; // Comes the DX 10 part m_pDevice = NULL; m_pEffect10 = NULL; m_pQuadVertexLayout = NULL; m_pQuadVB = NULL; m_pEncrypt = NULL; m_pDecrypt = NULL; m_pEncryptECB = NULL; m_pDecryptECB = NULL; m_pSourceTexture = NULL; m_pDestTexture = NULL; m_pStagingDstTexture = NULL; m_pStagingSrcTexture = NULL; m_pSourceTexRV = NULL; m_pDestRTV = NULL; m_pShaderIV = NULL; m_pShaderKeyEnc = NULL; m_pShaderKeyDec = NULL; m_pShaderKeySize = NULL; m_pTexConstants = NULL; m_pTexConstantsRV = NULL; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// AES_GPU_DX10_Internal::~AES_GPU_DX10_Internal() { SAFE_RELEASE( m_pTexConstantsRV ); SAFE_RELEASE( m_pTexConstants ); SAFE_RELEASE( m_pDestRTV ); SAFE_RELEASE( m_pStagingDstTexture ); SAFE_RELEASE( m_pStagingSrcTexture ); SAFE_RELEASE( m_pDestTexture ); SAFE_RELEASE( m_pSourceTexture ); SAFE_RELEASE( m_pSourceTexRV ); SAFE_RELEASE( m_pQuadVB ); SAFE_RELEASE( m_pQuadVertexLayout ); SAFE_RELEASE( m_pEffect10 ); SAFE_RELEASE( m_pDevice ); FreeLibrary( m_hModD3D10 ); delete mDeviceName; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// const TCHAR* AES_GPU_DX10_Internal::GetDeviceName() { return mDeviceName; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// IAlgorithmDescription& AES_GPU_DX10_Internal::GetDescription() { return class_description; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// UINT32 AES_GPU_DX10_Internal::GetSupportedModes(bool Encryption) { if( Encryption ) return m_SupportedModes & (~IAlgorithmAES::AES_CBC); // CBC not supported for encryption else return m_SupportedModes; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// IAlgorithmAES::AES_Status AES_GPU_DX10_Internal::SetMode(AES_Modes mode, const UINT8 *IV) { if( (mode & m_SupportedModes) == 0 ) return IAlgorithmAES::AES_Status_NotSupported; /// Check if only one mode was passed ( must be a power of 2 ) if( (mode & (mode - 1)) != 0 ) return IAlgorithmAES::AES_Status_InvalidArgs; m_Mode = mode; if( mode != IAlgorithmAES::AES_ECB ) { /// All the modes beside ECB needs IV if( IV == NULL ) { memset(m_IV, 0, IAlgorithmAES::BlockSizeBytes); memset(m_internalEncIV, 0, IAlgorithmAES::BlockSizeBytes); memset(m_internalDecIV, 0, IAlgorithmAES::BlockSizeBytes); } else { memcpy(m_IV, IV, IAlgorithmAES::BlockSizeBytes); memcpy(m_internalEncIV, IV, IAlgorithmAES::BlockSizeBytes); memcpy(m_internalDecIV, IV, IAlgorithmAES::BlockSizeBytes); } } switch(m_Mode) { case IAlgorithmAES::AES_ECB: m_pEncrypt = m_pEncryptECB; m_pDecrypt = m_pDecryptECB; break; case IAlgorithmAES::AES_CBC: m_pEncrypt = NULL; // Not supported m_pDecrypt = m_pDecryptCBC; break; case IAlgorithmAES::AES_CTR: m_pEncrypt = m_pEncDecCTR; m_pDecrypt = m_pEncDecCTR; break; } return IAlgorithmAES::AES_Status_OK; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// IAlgorithmAES::AES_Status AES_GPU_DX10_Internal::SetKey(const AES_Key *key) { if( key == NULL || key->GetKeySize() == AES_Key::AES_KeyInvalid ) return IAlgorithmAES::AES_Status_InvalidArgs; m_keySize = key->GetKeySize(); m_keyDataSize = key->GetKeySizeBytes(); memcpy(m_keyEnc, key->GetKeyData(), m_keyDataSize); // Because we want to use the same form of algorithm for decryption as for encryption, we // copy in m_keyDec the keys in reverse order of the rounds and also apply InvMixColumns // on the middle round keys . // For more information see Equivalent Inverse Cipher on AES standard. UINT32 m_Nr = (m_keySize >> 5) + 6; UINT32 *src = (UINT32*)&m_keyEnc[m_Nr * 16]; UINT32 *dst = (UINT32*)m_keyDec; // First round *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; *dst++ = *src; src -= 7; // The rest of the rounds will have applied the InvMixColumns to avoid being done on DecryptBlock for( UINT32 i = 1; i < m_Nr; i++ ) { UINT32 value = *src++; *dst++ = invMixColumn_a[value & 0xFF] ^ invMixColumn_b[(value >> 8) & 0xFF] ^ invMixColumn_c[(value >> 16) & 0xFF] ^ invMixColumn_d[value >> 24]; value = *src++; *dst++ = invMixColumn_a[value & 0xFF] ^ invMixColumn_b[(value >> 8) & 0xFF] ^ invMixColumn_c[(value >> 16) & 0xFF] ^ invMixColumn_d[value >> 24]; value = *src++; *dst++ = invMixColumn_a[value & 0xFF] ^ invMixColumn_b[(value >> 8) & 0xFF] ^ invMixColumn_c[(value >> 16) & 0xFF] ^ invMixColumn_d[value >> 24]; value = *src; *dst++ = invMixColumn_a[value & 0xFF] ^ invMixColumn_b[(value >> 8) & 0xFF] ^ invMixColumn_c[(value >> 16) & 0xFF] ^ invMixColumn_d[value >> 24]; src -= 7; } // The last round *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; *dst = *src; SetShaderKey(); // Also restore the IV that we use if( m_Mode != IAlgorithmAES::AES_ECB ) { memcpy(m_internalEncIV, m_IV, IAlgorithmAES::BlockSizeBytes); memcpy(m_internalDecIV, m_IV, IAlgorithmAES::BlockSizeBytes); } return IAlgorithmAES::AES_Status_OK; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// IAlgorithmAES::AES_Status AES_GPU_DX10_Internal::Encrypt(UINT8 *dst, const UINT8 *src, UINT32 size) { // Check for NULL pointers, and if the size of the data is multiple of block size // ( padding of the data must be done by the caller ) if( dst == NULL || src == NULL || size % IAlgorithmAES::BlockSizeBytes != 0 ) return IAlgorithmAES::AES_Status_InvalidArgs; if( m_keySize == AES_Key::AES_KeyInvalid ) return IAlgorithmAES::AES_Status_InvalidState; // Check if the mode of encryption is supported if( m_pEncrypt == NULL ) return IAlgorithmAES::AES_Status_NotSupported; // The number of bytes that can be encrypted in one pass UINT32 maxPassSize = TEXTURE_SIZEX * TEXTURE_SIZEY * IAlgorithmAES::BlockSizeBytes; // The number of full passes needed to encrypt the entire input UINT32 nbPasses= size / maxPassSize; // The size in bytes of the last pass ( can be smaller than maxPassSize ) UINT32 lastPassSize = size - (nbPasses * maxPassSize); // Run the full passes while( nbPasses != 0 ) { switch( m_Mode ) { case IAlgorithmAES::AES_ECB: { CopyDataToGPU(src, TEXTURE_SIZEX, TEXTURE_SIZEY); RunEncryption(); CopyDataFromGPU(dst, TEXTURE_SIZEX, TEXTURE_SIZEY); }break; case IAlgorithmAES::AES_CTR: { SetShaderIV(m_internalEncIV); // Update the IV for the next run if( ((UINT64*)m_internalEncIV)[0] + (TEXTURE_SIZEX * TEXTURE_SIZEY) < ((UINT64*)m_internalEncIV)[0] ) { ((UINT64*)m_internalEncIV)[0] += TEXTURE_SIZEX * TEXTURE_SIZEY; ((UINT64*)m_internalEncIV)[1]++; } else ((UINT64*)m_internalEncIV)[0] += TEXTURE_SIZEX * TEXTURE_SIZEY; CopyDataToGPU(src, TEXTURE_SIZEX, TEXTURE_SIZEY); RunEncryption(); CopyDataFromGPU(dst, TEXTURE_SIZEX, TEXTURE_SIZEY); }break; } src += maxPassSize; dst += maxPassSize; nbPasses--; } if( lastPassSize != 0 ) { // Must process the last bytes that did not fit on one full pass // The number of bytes that are found on one full line of the texture UINT32 maxLineSize = TEXTURE_SIZEX * IAlgorithmAES::BlockSizeBytes; // Find out the vertical size of the texture that will be used UINT32 texureSizeY = lastPassSize / maxLineSize; // The size in bytes of the last line ( can be smaller than maxLineSize ) UINT32 lastLineSize = lastPassSize - (texureSizeY * maxLineSize); // Set the scissor to only render the required rectangle D3D10_RECT rects[1]; rects[0].left = 0; rects[0].right = TEXTURE_SIZEX; rects[0].top = 0; rects[0].bottom = texureSizeY + ((lastLineSize != 0) ? 1 : 0); m_pDevice->RSSetScissorRects( 1, rects ); switch( m_Mode ) { case IAlgorithmAES::AES_ECB: { CopyDataToGPU(src, TEXTURE_SIZEX, texureSizeY, lastLineSize); RunEncryption(); CopyDataFromGPU(dst, TEXTURE_SIZEX, texureSizeY, lastLineSize); }break; case IAlgorithmAES::AES_CTR: { SetShaderIV(m_internalEncIV); // Update the IV for the next run UINT32 nbBlocks = lastPassSize / IAlgorithmAES::BlockSizeBytes; if( ((UINT64*)m_internalEncIV)[0] + nbBlocks < ((UINT64*)m_internalEncIV)[0] ) { ((UINT64*)m_internalEncIV)[0] += nbBlocks; ((UINT64*)m_internalEncIV)[1]++; } else ((UINT64*)m_internalEncIV)[0] += nbBlocks; CopyDataToGPU(src, TEXTURE_SIZEX, texureSizeY, lastLineSize); RunEncryption(); CopyDataFromGPU(dst, TEXTURE_SIZEX, texureSizeY, lastLineSize); }break; } // Set the scissor back to render the full view port rects[0].bottom = TEXTURE_SIZEY; m_pDevice->RSSetScissorRects( 1, rects ); } return IAlgorithmAES::AES_Status_OK; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// IAlgorithmAES::AES_Status AES_GPU_DX10_Internal::Decrypt(UINT8 *dst, const UINT8 *src, UINT32 size) { // Check for NULL pointers, and if the size of the data is multiple of block size // ( padding of the data must be done by the caller ) if( dst == NULL || src == NULL || size % IAlgorithmAES::BlockSizeBytes != 0 ) return IAlgorithmAES::AES_Status_InvalidArgs; if( m_keySize == AES_Key::AES_KeyInvalid ) return IAlgorithmAES::AES_Status_InvalidState; // Check if the mode of decryption is supported if( m_pDecrypt == NULL ) return IAlgorithmAES::AES_Status_NotSupported; // The number of bytes that can be decrypted in one pass UINT32 maxPassSize = TEXTURE_SIZEX * TEXTURE_SIZEY * IAlgorithmAES::BlockSizeBytes; // The number of full passes needed to decrypt the entire input UINT32 nbPasses= size / maxPassSize; // The size in bytes of the last pass ( can be smaller than maxPassSize ) UINT32 lastPassSize = size - (nbPasses * maxPassSize); // Run the full passes while( nbPasses != 0 ) { switch( m_Mode ) { case IAlgorithmAES::AES_ECB: { CopyDataToGPU(src, TEXTURE_SIZEX, TEXTURE_SIZEY); RunDecryption(); CopyDataFromGPU(dst, TEXTURE_SIZEX, TEXTURE_SIZEY); }break; case IAlgorithmAES::AES_CBC: { CopyDataToGPU(src, TEXTURE_SIZEX, TEXTURE_SIZEY); RunDecryption(); CopyDataFromGPU(dst, TEXTURE_SIZEX, TEXTURE_SIZEY); ((UINT64*)dst)[0] ^= ((UINT64*)m_internalDecIV)[0]; ((UINT64*)dst)[1] ^= ((UINT64*)m_internalDecIV)[1]; // Save the new Initial Vector for the next run UINT64 *tsrc64 = (UINT64*)(src + size - IAlgorithmAES::BlockSizeBytes); ((UINT64*)m_internalDecIV)[0] = tsrc64[0]; ((UINT64*)m_internalDecIV)[1] = tsrc64[1]; }break; case IAlgorithmAES::AES_CTR: { SetShaderIV(m_internalDecIV); // Update the IV for the next run if( ((UINT64*)m_internalDecIV)[0] + (TEXTURE_SIZEX * TEXTURE_SIZEY) < ((UINT64*)m_internalDecIV)[0] ) { ((UINT64*)m_internalDecIV)[0] += TEXTURE_SIZEX * TEXTURE_SIZEY; ((UINT64*)m_internalDecIV)[1]++; } else ((UINT64*)m_internalDecIV)[0] += TEXTURE_SIZEX * TEXTURE_SIZEY; CopyDataToGPU(src, TEXTURE_SIZEX, TEXTURE_SIZEY); RunEncryption(); CopyDataFromGPU(dst, TEXTURE_SIZEX, TEXTURE_SIZEY); }break; } src += maxPassSize; dst += maxPassSize; nbPasses--; } if( lastPassSize != 0 ) { // Must process the last bytes that did not fit on one full pass // The number of bytes that are found on one full line of the texture UINT32 maxLineSize = TEXTURE_SIZEX * IAlgorithmAES::BlockSizeBytes; // Find out the vertical size of the texture that will be used UINT32 texureSizeY = lastPassSize / maxLineSize; // The size in bytes of the last line ( can be smaller than maxLineSize ) UINT32 lastLineSize = lastPassSize - (texureSizeY * maxLineSize); // Set the scissor to only render the required rectangle D3D10_RECT rects[1]; rects[0].left = 0; rects[0].right = TEXTURE_SIZEX; rects[0].top = 0; rects[0].bottom = texureSizeY + ((lastLineSize != 0) ? 1 : 0); m_pDevice->RSSetScissorRects( 1, rects ); switch( m_Mode ) { case IAlgorithmAES::AES_ECB: { CopyDataToGPU(src, TEXTURE_SIZEX, texureSizeY, lastLineSize); RunDecryption(); CopyDataFromGPU(dst, TEXTURE_SIZEX, texureSizeY, lastLineSize); }break; case IAlgorithmAES::AES_CBC: { CopyDataToGPU(src, TEXTURE_SIZEX, texureSizeY, lastLineSize); RunDecryption(); CopyDataFromGPU(dst, TEXTURE_SIZEX, texureSizeY, lastLineSize); ((UINT64*)dst)[0] ^= ((UINT64*)m_internalDecIV)[0]; ((UINT64*)dst)[1] ^= ((UINT64*)m_internalDecIV)[1]; // Save the new Initial Vector for the next run UINT64 *tsrc64 = (UINT64*)(src + size - IAlgorithmAES::BlockSizeBytes); ((UINT64*)m_internalDecIV)[0] = tsrc64[0]; ((UINT64*)m_internalDecIV)[1] = tsrc64[1]; }break; case IAlgorithmAES::AES_CTR: { SetShaderIV(m_internalDecIV); // Update the IV for the next run UINT32 nbBlocks = lastPassSize / IAlgorithmAES::BlockSizeBytes; if( ((UINT64*)m_internalDecIV)[0] + nbBlocks < ((UINT64*)m_internalDecIV)[0] ) { ((UINT64*)m_internalDecIV)[0] += nbBlocks; ((UINT64*)m_internalDecIV)[1]++; } else ((UINT64*)m_internalDecIV)[0] += nbBlocks; CopyDataToGPU(src, TEXTURE_SIZEX, texureSizeY, lastLineSize); RunEncryption(); CopyDataFromGPU(dst, TEXTURE_SIZEX, texureSizeY, lastLineSize); }break; } // Set the scissor back to render the full view port rects[0].bottom = TEXTURE_SIZEY; m_pDevice->RSSetScissorRects( 1, rects ); } return IAlgorithmAES::AES_Status_OK; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void AES_GPU_DX10_Internal::SetShaderIV(UINT8 *IV) { m_pShaderIV->SetIntVector((int*)IV); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void AES_GPU_DX10_Internal::SetShaderKey() { // Set the data of the key for encryption m_pShaderKeyEnc->SetIntVectorArray((int*)m_keyEnc, 0, 15); // Set the data of the key for decryption m_pShaderKeyDec->SetIntVectorArray((int*)m_keyDec, 0, 15); // Set the number of rounds m_pShaderKeySize->SetInt((m_keySize >> 5) + 6); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void AES_GPU_DX10_Internal::CopyDataToGPU(const UINT8 *src, UINT32 sizeX, UINT32 sizeY, UINT32 lastLineBytes) { #if 1 if( sizeY != 0 ) { // Copy the full lines of data D3D10_BOX destRegion; destRegion.left = 0; destRegion.top = 0; destRegion.right = sizeX; destRegion.bottom = sizeY; destRegion.front = 0; destRegion.back = 1; m_pDevice->UpdateSubresource( m_pSourceTexture, D3D10CalcSubresource( 0, 0, 1 ), &destRegion, src, sizeX * 16, 0 ); } if( lastLineBytes != 0 ) { // Copy the last incomplete line of data D3D10_BOX destRegion; destRegion.left = 0; destRegion.top = sizeY; destRegion.right = lastLineBytes / 16; destRegion.bottom = sizeY + 1; destRegion.front = 0; destRegion.back = 1; m_pDevice->UpdateSubresource( m_pSourceTexture, D3D10CalcSubresource( 0, 0, 1 ), &destRegion, src + sizeY * sizeX * 16, sizeX * 16, 0 ); } #else HRESULT hr = S_OK; // Map the CPU staging resource D3D10_MAPPED_TEXTURE2D map; hr = m_pStagingSrcTexture->Map( 0, D3D10_MAP_WRITE, NULL, &map ); if( FAILED( hr ) ) return; memcpy(map.pData, src, (sizeY * map.RowPitch) + lastLineBytes); m_pStagingSrcTexture->Unmap( 0 ); // Copy the data from the CPU resource to the GPU resource D3D10_BOX srcRegion; srcRegion.left = 0; srcRegion.right = sizeX; srcRegion.top = 0; srcRegion.bottom = sizeY + ((lastLineBytes != 0) ? 1 :0); srcRegion.front = 0; srcRegion.back = 1; m_pDevice->CopySubresourceRegion( m_pSourceTexture, D3D10CalcSubresource( 0, 0, 1 ), 0, 0, 0, m_pStagingSrcTexture, D3D10CalcSubresource( 0, 0, 1 ), &srcRegion); #endif } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void AES_GPU_DX10_Internal::CopyDataFromGPU(UINT8 *dst, UINT32 sizeX, UINT32 sizeY, UINT32 lastLineBytes) { HRESULT hr = S_OK; // Copy the data from the GPU resource to the CPU resource D3D10_BOX srcRegion; srcRegion.left = 0; srcRegion.right = sizeX; srcRegion.top = 0; srcRegion.bottom = sizeY + ((lastLineBytes != 0) ? 1 :0); srcRegion.front = 0; srcRegion.back = 1; m_pDevice->CopySubresourceRegion( m_pStagingDstTexture, D3D10CalcSubresource( 0, 0, 1 ), 0, 0, 0, m_pDestTexture, D3D10CalcSubresource( 0, 0, 1 ), &srcRegion); // Map the CPU staging resource D3D10_MAPPED_TEXTURE2D map; hr = m_pStagingDstTexture->Map( 0, D3D10_MAP_READ, NULL, &map ); if( FAILED( hr ) ) return; memcpy(dst, map.pData, (sizeY * map.RowPitch) + lastLineBytes); m_pStagingDstTexture->Unmap( 0 ); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void AES_GPU_DX10_Internal::RunEncryption() { D3D10_TECHNIQUE_DESC techDesc; m_pEncrypt->GetDesc( &techDesc ); for( UINT p = 0; p < techDesc.Passes; ++p ) { m_pEncrypt->GetPassByIndex( p )->Apply( 0 ); m_pDevice->Draw( 6, 0 ); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void AES_GPU_DX10_Internal::RunDecryption() { D3D10_TECHNIQUE_DESC techDesc; m_pDecrypt->GetDesc( &techDesc ); for( UINT p = 0; p < techDesc.Passes; ++p ) { m_pDecrypt->GetPassByIndex( p )->Apply( 0 ); m_pDevice->Draw( 6, 0 ); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } ::gHModule = hModule; return TRUE; }
53.802046
156
0.621422
Bizonu
38b2e42851cac4b1098d80487fd7f31390c1589f
4,391
hpp
C++
includes/commands.hpp
Antip003/irc
973c4e1ee3d231c6aca1a434a735f236d4d55e77
[ "MIT" ]
1
2021-11-29T21:41:10.000Z
2021-11-29T21:41:10.000Z
includes/commands.hpp
Antip003/irc
973c4e1ee3d231c6aca1a434a735f236d4d55e77
[ "MIT" ]
null
null
null
includes/commands.hpp
Antip003/irc
973c4e1ee3d231c6aca1a434a735f236d4d55e77
[ "MIT" ]
null
null
null
#ifndef COMMANDS_HPP # define COMMANDS_HPP # include "ircserv.hpp" # include <string> struct IRCserv; void initcommands(IRCserv *serv); void cmd_nick(int fd, const t_strvect &split, IRCserv *serv); void cmd_user(int fd, const t_strvect &split, IRCserv *serv); void cmd_ping(int fd, const t_strvect &split, IRCserv *serv); void cmd_pong(int fd, const t_strvect &split, IRCserv *serv); void cmd_quit(int fd, const t_strvect &split, IRCserv *serv); void cmd_oper(int fd, const t_strvect &split, IRCserv *serv); void cmd_server(int fd, const t_strvect &split, IRCserv *serv); void cmd_pass(int fd, const t_strvect &split, IRCserv *serv); void cmd_squit(int fd, const t_strvect &split, IRCserv *serv); void cmd_connect(int fd, const t_strvect &split, IRCserv *serv); void cmd_error(int fd, const t_strvect &split, IRCserv *serv); void cmd_admin(int fd, const t_strvect &split, IRCserv *serv); void cmd_motd(int fd, const t_strvect &split, IRCserv *serv); void cmd_userhost(int fd, const t_strvect &split, IRCserv *serv); void cmd_version(int fd, const t_strvect &split, IRCserv *serv); void cmd_info(int fd, const t_strvect &split, IRCserv *serv); void cmd_time(int fd, const t_strvect &split, IRCserv *serv); void cmd_join(int fd, const t_strvect &split, IRCserv *serv); void cmd_privmsg(int fd, const t_strvect &split, IRCserv *serv); void cmd_invite(int fd, const t_strvect &split, IRCserv *serv); void cmd_names(int fd, const t_strvect &split, IRCserv *serv); void cmd_who(int fd, const t_strvect &split, IRCserv *serv); void cmd_whois(int fd, const t_strvect &split, IRCserv *serv); void cmd_whowas(int fd, const t_strvect &split, IRCserv *serv); void cmd_part(int fd, const t_strvect &split, IRCserv *serv); void cmd_mode(int fd, const t_strvect &split, IRCserv *serv); void cmd_notice(int fd, const t_strvect &split, IRCserv *serv); void cmd_away(int fd, const t_strvect &split, IRCserv *serv); void cmd_kill(int fd, const t_strvect &split, IRCserv *serv); void cmd_stats(int fd, const t_strvect &split, IRCserv *serv); void cmd_links(int fd, const t_strvect &split, IRCserv *serv); void cmd_njoin(int fd, const t_strvect &split, IRCserv *serv); void cmd_lusers(int fd, const t_strvect &split, IRCserv *serv); void cmd_ison(int fd, const t_strvect &split, IRCserv *serv); void cmd_users(int fd, const t_strvect &split, IRCserv *serv); // disabled void cmd_topic(int fd, t_strvect const &split, IRCserv *serv); void cmd_kick(int fd, t_strvect const &split, IRCserv *serv); void cmd_trace(int fd, t_strvect const &split, IRCserv *serv); void cmd_die(int fd, t_strvect const &split, IRCserv *serv); void cmd_list(int fd, t_strvect const &split, IRCserv *serv); void cmd_wallops(int fd, t_strvect const &split, IRCserv *serv); void cmd_rehash(int fd, t_strvect const &split, IRCserv *serv); void cmd_service(int fd, t_strvect const &split, IRCserv *serv); void cmd_servlist(int fd, t_strvect const &split, IRCserv *serv); void cmd_squery(int fd, const t_strvect &split, IRCserv *serv); std::string reply_welcome(IRCserv *serv, Client *client); std::string reply_motd(IRCserv *serv, std::string const &it); std::string reply_chan_names(IRCserv *serv, Channel *chan, Client *client); std::string reply_nochan_visible_names(IRCserv *serv, Client *client); std::string reply_lusers(IRCserv *serv, std::string const &target, std::string const &mask = "*"); bool is_server_registred(const std::string &name, std::string const token, IRCserv *serv); std::string getservernamebymask(IRCserv *serv, std::string const &mask); int getserverfdbymask(IRCserv *serv, std::string const &mask); std::string getnicktoreply(int fd, const t_strvect &split, IRCserv *serv); std::string reply_unknowncmd(int fd, const t_strvect &split, IRCserv *serv); #define CMD_CLIENTONLY 1 #define CMD_SERVERONLY 2 class Command { private: typedef void (*t_command)(int fd, const t_strvect &split, IRCserv *serv); t_command cmd; uint type; // message stats uint count; size_t bytes; uint rcount; public: Command(); ~Command(); Command(t_command cmd); Command(Command const &other); Command &operator=(Command const &other); bool used(void); bool serveronly(void); bool clientonly(void); uint getcount(void); size_t getbytes(void); uint getrcount(void); void settype(uint type); void Execute(int fd, const t_strvect &split, IRCserv *serv, size_t bytes, bool remote); }; #endif
44.353535
99
0.754042
Antip003