blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
247
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 4
111
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
58
| visit_date
timestamp[ns]date 2015-07-25 18:16:41
2023-09-06 10:45:08
| revision_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| github_id
int64 3.89k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 25
values | gha_event_created_at
timestamp[ns]date 2012-06-07 00:51:45
2023-09-14 21:58:52
⌀ | gha_created_at
timestamp[ns]date 2008-03-27 23:40:48
2023-08-24 19:49:39
⌀ | gha_language
stringclasses 159
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
10.5M
| extension
stringclasses 111
values | filename
stringlengths 1
195
| text
stringlengths 7
10.5M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
45767473f713ac356b90823f8c9ce1149194456a
|
95e24c3032b0e6b45b3239e5e23d74e017a3ba11
|
/Strings/Balanced Parenthesis problem.[Imp]/Balanced Parenthesis problem.[Imp].cpp
|
a1eb86a382cd706066a1aec1d50a0669715e3cad
|
[] |
no_license
|
keshavjaiswal39/DSA-450-Questions-Love-Babbar-DataSheet
|
b167470f913b6d4e5e525583ecd1e7d070c335f7
|
b6885254063427ddc6e7f7751512caaf788f1a83
|
refs/heads/master
| 2023-05-29T06:08:52.624084
| 2021-06-20T11:10:24
| 2021-06-20T11:10:24
| 347,831,521
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,264
|
cpp
|
Balanced Parenthesis problem.[Imp].cpp
|
bool ispar(string e)
{
// Your code here
stack<char> s;
char x;
for(int i=0;i<e.size();i++)
{
if(e[i]=='(' || e[i]=='{' || e[i]=='[')
{
s.push(e[i]);
continue;
}
if(s.empty())
{
return false;
}
if(e[i]==')')
{
x=s.top();
s.pop();
if(x=='{' || x=='[')
{
return false;
}
}
if(e[i]=='}')
{
x=s.top();
s.pop();
if(x=='(' || x=='[')
{
return false;
}
}
if(e[i]==']')
{
x=s.top();
s.pop();
if(x=='{' || x=='(')
{
return false;
}
}
}
if(s.empty())
{
return true;
}
else
{
return false;
}
}
};
|
aa6b008662d92ed927cb162725196a6491597574
|
091afb7001e86146209397ea362da70ffd63a916
|
/inst/include/nt2/include/functions/scalar/split_high.hpp
|
657e1fc8b0d233c572871307a0439ba6dde224fb
|
[] |
no_license
|
RcppCore/RcppNT2
|
f156b58c08863243f259d1e609c9a7a8cf669990
|
cd7e548daa2d679b6ccebe19744b9a36f1e9139c
|
refs/heads/master
| 2021-01-10T16:15:16.861239
| 2016-02-02T22:18:25
| 2016-02-02T22:18:25
| 50,460,545
| 15
| 1
| null | 2019-11-15T22:08:50
| 2016-01-26T21:29:34
|
C++
|
UTF-8
|
C++
| false
| false
| 191
|
hpp
|
split_high.hpp
|
#ifndef NT2_INCLUDE_FUNCTIONS_SCALAR_SPLIT_HIGH_HPP_INCLUDED
#define NT2_INCLUDE_FUNCTIONS_SCALAR_SPLIT_HIGH_HPP_INCLUDED
#include <nt2/swar/include/functions/scalar/split_high.hpp>
#endif
|
59b343559603f14dbbf0faf3e788a4892a92a0d5
|
bfb7da132ff44f801bcb38f793d0cf79366df9ed
|
/hw5/1a.cpp
|
f96a8f66b5d7ca144285eb5efcdba772d9ee01c6
|
[] |
no_license
|
maxim-kocheganov/homework
|
9ce0d939e6bd0c755b8f582cdb834ee83045a4d8
|
2cbd5bfa4dcef0cf7b428b3833efabd7900ad19d
|
refs/heads/master
| 2021-05-28T21:36:43.361213
| 2015-05-18T22:37:07
| 2015-05-18T22:37:07
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 894
|
cpp
|
1a.cpp
|
#include <iostream>
#include <cstdlib>
using namespace std;
int inputNum();
const int max = 10;
const int err = -1;
int main()
{
int tvarp;
while (true)
{
tvarp = inputNum();
cout << "tvarp: " << tvarp << endl;
if (tvarp != err)
{
int tax = 0;
if (tvarp - 5000 > 0)
tax += ((tvarp - 5000) % 10000) / 10;
if (tvarp - 5000 - 10000 > 0)
tax += (((tvarp - 5000 - 10000) % 20000) * 15) / 100;
if (tvarp - 5000 - 10000 - 20000 > 0)
tax += (tvarp - 5000 - 10000 - 20000) / 5;
cout << "tax: " << tax << endl;
}
else
{
cout << "end" << endl;
break;
}
}
cin.ignore();
return 0;
}
int inputNum()
{
int a;
char buf[max] = {};
cin.read(buf,max);
for (int i = 0; i < max; i++)
{
if (isdigit(buf[i]))
continue;
else
{
if (buf[i] == '\0')
break;
else
return err;
}
}
a = atoi(buf);
if (a < 0)
a = err;
return a;
}
|
66f8b13655b21a9ec7a7f3520bf958fa2ed3cf58
|
b783b2a661f721862aba4a3e607c87b9fd243434
|
/eclipseWorkSpaces/corman/07_advancingArray_prj/src/main.cpp
|
22d973859f2f9918684e06b81490933025f42461
|
[] |
no_license
|
thesellersab/sole
|
c8988b1f8ac139e1bc5e351435a8eac49543e8a0
|
f9ede0c49df462c9bb654f4320e1bcbc4e8905bc
|
refs/heads/master
| 2022-11-23T10:38:12.908567
| 2020-07-31T10:51:42
| 2020-07-31T10:51:42
| 264,410,421
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,009
|
cpp
|
main.cpp
|
/*
* * * * * * * * * *
* * * * * * * * *
|| مصنف:موسیقار پروگرامر ||
* * * * * * * * *
* * * * * * * * * *
*/
/*
* main.cpp
*
* Created on: Jul 11, 2020
* Author: موسیقار پروگرامر (Programming Musician)
*/
//#define ADVANCE
#ifdef ADVANCE
#include "utilities/array_utilities.hpp"
#include "advancing_array_game.hpp"
using namespace maosikar;
int main ( int argc , char *argv[])
{
int data[4] = {2,-10,0,1};
print1DArray(data, 4);
std::cout<<"----------Given Array-----------"<<std::endl;
print1DArray(data,4);
if(isStartToEndPossible(data,4))
std::cout<<"Advancing through this array is POSSIBLE !"<<std::endl;
else
std::cout<<"Advancing through this array is NOT-POSSIBLE !"<<std::endl;
int size = 32;
bool flag = true;
int *data2 = new int[size];
while(flag)
{
genRandomArray(data2, size);
flag = isStartToEndPossible(data2,size);
print1DArray(data2,size);
}
std::cout<<"----------Given Array-----------"<<std::endl;
print1DArray(data2,size);
if(isStartToEndPossible(data2,size))
std::cout<<"Advancing through this array is POSSIBLE !"<<std::endl;
else
std::cout<<"Advancing through this array is NOT-POSSIBLE !"<<std::endl;
return 0;
}
#else
#include <iostream>
#include "duplicate_removal.hpp"
#include "utilities/array_utilities.hpp"
using namespace maosikar;
int main( int argc, char *argv[])
{
int data[6] = {1,2,2,2,3,4};
int data2[13] = {10,20,4,4,30,5,4,1,2,2,2,3,4};
std::cout<<"------ Input Array:"<<std::endl;
print1DArray(data, 6);
int newLength = removeDuplicates(data, 6);
std::cout<<"Array After Duplicate removal:"<<std::endl;
print1DArray(data, newLength);
std::cout<<"Remove key : 2 from Array:"<<std::endl;
print1DArray(data2, 13);
int newLength2 = removeKey(data2, 4, 13);
print1DArray(data2, newLength2);
return 0;
}
#endif
|
54957e8bcdfd2d678cd999488c1c3b3bcadde1b8
|
80ed6942824dc76b11e988ec63458f30ed9ad69e
|
/examples/pb_sample.pb.h
|
4415d86423816c37e9c7bd478e8f3cbae8fa61a0
|
[] |
no_license
|
Apsalar/cpp-parquet
|
83083d3a674f20b0980ae668213fea4e1694fabe
|
3250cd60eed11df9b07e1320811e376952ec20fa
|
refs/heads/master
| 2021-01-24T15:24:51.563479
| 2016-03-09T01:27:55
| 2016-03-09T01:27:55
| 46,075,744
| 0
| 0
| null | 2015-11-12T19:27:41
| 2015-11-12T19:27:41
| null |
UTF-8
|
C++
| false
| true
| 27,221
|
h
|
pb_sample.pb.h
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: pb_sample.proto
#ifndef PROTOBUF_pb_5fsample_2eproto__INCLUDED
#define PROTOBUF_pb_5fsample_2eproto__INCLUDED
#include <string>
#include <google/protobuf/stubs/common.h>
#if GOOGLE_PROTOBUF_VERSION < 2005000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 2005000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
namespace pb_sample {
// Internal implementation detail -- do not call these.
void protobuf_AddDesc_pb_5fsample_2eproto();
void protobuf_AssignDesc_pb_5fsample_2eproto();
void protobuf_ShutdownFile_pb_5fsample_2eproto();
class Document;
class Document_mlinks;
class Document_mname;
class Document_mname_mlanguage;
// ===================================================================
class Document_mlinks : public ::google::protobuf::Message {
public:
Document_mlinks();
virtual ~Document_mlinks();
Document_mlinks(const Document_mlinks& from);
inline Document_mlinks& operator=(const Document_mlinks& from) {
CopyFrom(from);
return *this;
}
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _unknown_fields_;
}
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const ::google::protobuf::Descriptor* descriptor();
static const Document_mlinks& default_instance();
void Swap(Document_mlinks* other);
// implements Message ----------------------------------------------
Document_mlinks* New() const;
void CopyFrom(const ::google::protobuf::Message& from);
void MergeFrom(const ::google::protobuf::Message& from);
void CopyFrom(const Document_mlinks& from);
void MergeFrom(const Document_mlinks& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::google::protobuf::Metadata GetMetadata() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// repeated int64 Backward = 1;
inline int backward_size() const;
inline void clear_backward();
static const int kBackwardFieldNumber = 1;
inline ::google::protobuf::int64 backward(int index) const;
inline void set_backward(int index, ::google::protobuf::int64 value);
inline void add_backward(::google::protobuf::int64 value);
inline const ::google::protobuf::RepeatedField< ::google::protobuf::int64 >&
backward() const;
inline ::google::protobuf::RepeatedField< ::google::protobuf::int64 >*
mutable_backward();
// repeated int64 Forward = 2;
inline int forward_size() const;
inline void clear_forward();
static const int kForwardFieldNumber = 2;
inline ::google::protobuf::int64 forward(int index) const;
inline void set_forward(int index, ::google::protobuf::int64 value);
inline void add_forward(::google::protobuf::int64 value);
inline const ::google::protobuf::RepeatedField< ::google::protobuf::int64 >&
forward() const;
inline ::google::protobuf::RepeatedField< ::google::protobuf::int64 >*
mutable_forward();
// @@protoc_insertion_point(class_scope:pb_sample.Document.mlinks)
private:
::google::protobuf::UnknownFieldSet _unknown_fields_;
::google::protobuf::RepeatedField< ::google::protobuf::int64 > backward_;
::google::protobuf::RepeatedField< ::google::protobuf::int64 > forward_;
mutable int _cached_size_;
::google::protobuf::uint32 _has_bits_[(2 + 31) / 32];
friend void protobuf_AddDesc_pb_5fsample_2eproto();
friend void protobuf_AssignDesc_pb_5fsample_2eproto();
friend void protobuf_ShutdownFile_pb_5fsample_2eproto();
void InitAsDefaultInstance();
static Document_mlinks* default_instance_;
};
// -------------------------------------------------------------------
class Document_mname_mlanguage : public ::google::protobuf::Message {
public:
Document_mname_mlanguage();
virtual ~Document_mname_mlanguage();
Document_mname_mlanguage(const Document_mname_mlanguage& from);
inline Document_mname_mlanguage& operator=(const Document_mname_mlanguage& from) {
CopyFrom(from);
return *this;
}
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _unknown_fields_;
}
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const ::google::protobuf::Descriptor* descriptor();
static const Document_mname_mlanguage& default_instance();
void Swap(Document_mname_mlanguage* other);
// implements Message ----------------------------------------------
Document_mname_mlanguage* New() const;
void CopyFrom(const ::google::protobuf::Message& from);
void MergeFrom(const ::google::protobuf::Message& from);
void CopyFrom(const Document_mname_mlanguage& from);
void MergeFrom(const Document_mname_mlanguage& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::google::protobuf::Metadata GetMetadata() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// required string Code = 1;
inline bool has_code() const;
inline void clear_code();
static const int kCodeFieldNumber = 1;
inline const ::std::string& code() const;
inline void set_code(const ::std::string& value);
inline void set_code(const char* value);
inline void set_code(const char* value, size_t size);
inline ::std::string* mutable_code();
inline ::std::string* release_code();
inline void set_allocated_code(::std::string* code);
// optional string Country = 2;
inline bool has_country() const;
inline void clear_country();
static const int kCountryFieldNumber = 2;
inline const ::std::string& country() const;
inline void set_country(const ::std::string& value);
inline void set_country(const char* value);
inline void set_country(const char* value, size_t size);
inline ::std::string* mutable_country();
inline ::std::string* release_country();
inline void set_allocated_country(::std::string* country);
// @@protoc_insertion_point(class_scope:pb_sample.Document.mname.mlanguage)
private:
inline void set_has_code();
inline void clear_has_code();
inline void set_has_country();
inline void clear_has_country();
::google::protobuf::UnknownFieldSet _unknown_fields_;
::std::string* code_;
::std::string* country_;
mutable int _cached_size_;
::google::protobuf::uint32 _has_bits_[(2 + 31) / 32];
friend void protobuf_AddDesc_pb_5fsample_2eproto();
friend void protobuf_AssignDesc_pb_5fsample_2eproto();
friend void protobuf_ShutdownFile_pb_5fsample_2eproto();
void InitAsDefaultInstance();
static Document_mname_mlanguage* default_instance_;
};
// -------------------------------------------------------------------
class Document_mname : public ::google::protobuf::Message {
public:
Document_mname();
virtual ~Document_mname();
Document_mname(const Document_mname& from);
inline Document_mname& operator=(const Document_mname& from) {
CopyFrom(from);
return *this;
}
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _unknown_fields_;
}
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const ::google::protobuf::Descriptor* descriptor();
static const Document_mname& default_instance();
void Swap(Document_mname* other);
// implements Message ----------------------------------------------
Document_mname* New() const;
void CopyFrom(const ::google::protobuf::Message& from);
void MergeFrom(const ::google::protobuf::Message& from);
void CopyFrom(const Document_mname& from);
void MergeFrom(const Document_mname& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::google::protobuf::Metadata GetMetadata() const;
// nested types ----------------------------------------------------
typedef Document_mname_mlanguage mlanguage;
// accessors -------------------------------------------------------
// repeated .pb_sample.Document.mname.mlanguage Language = 1;
inline int language_size() const;
inline void clear_language();
static const int kLanguageFieldNumber = 1;
inline const ::pb_sample::Document_mname_mlanguage& language(int index) const;
inline ::pb_sample::Document_mname_mlanguage* mutable_language(int index);
inline ::pb_sample::Document_mname_mlanguage* add_language();
inline const ::google::protobuf::RepeatedPtrField< ::pb_sample::Document_mname_mlanguage >&
language() const;
inline ::google::protobuf::RepeatedPtrField< ::pb_sample::Document_mname_mlanguage >*
mutable_language();
// optional string Url = 2;
inline bool has_url() const;
inline void clear_url();
static const int kUrlFieldNumber = 2;
inline const ::std::string& url() const;
inline void set_url(const ::std::string& value);
inline void set_url(const char* value);
inline void set_url(const char* value, size_t size);
inline ::std::string* mutable_url();
inline ::std::string* release_url();
inline void set_allocated_url(::std::string* url);
// @@protoc_insertion_point(class_scope:pb_sample.Document.mname)
private:
inline void set_has_url();
inline void clear_has_url();
::google::protobuf::UnknownFieldSet _unknown_fields_;
::google::protobuf::RepeatedPtrField< ::pb_sample::Document_mname_mlanguage > language_;
::std::string* url_;
mutable int _cached_size_;
::google::protobuf::uint32 _has_bits_[(2 + 31) / 32];
friend void protobuf_AddDesc_pb_5fsample_2eproto();
friend void protobuf_AssignDesc_pb_5fsample_2eproto();
friend void protobuf_ShutdownFile_pb_5fsample_2eproto();
void InitAsDefaultInstance();
static Document_mname* default_instance_;
};
// -------------------------------------------------------------------
class Document : public ::google::protobuf::Message {
public:
Document();
virtual ~Document();
Document(const Document& from);
inline Document& operator=(const Document& from) {
CopyFrom(from);
return *this;
}
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _unknown_fields_;
}
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const ::google::protobuf::Descriptor* descriptor();
static const Document& default_instance();
void Swap(Document* other);
// implements Message ----------------------------------------------
Document* New() const;
void CopyFrom(const ::google::protobuf::Message& from);
void MergeFrom(const ::google::protobuf::Message& from);
void CopyFrom(const Document& from);
void MergeFrom(const Document& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::google::protobuf::Metadata GetMetadata() const;
// nested types ----------------------------------------------------
typedef Document_mlinks mlinks;
typedef Document_mname mname;
// accessors -------------------------------------------------------
// required int64 DocId = 1;
inline bool has_docid() const;
inline void clear_docid();
static const int kDocIdFieldNumber = 1;
inline ::google::protobuf::int64 docid() const;
inline void set_docid(::google::protobuf::int64 value);
// optional .pb_sample.Document.mlinks Links = 2;
inline bool has_links() const;
inline void clear_links();
static const int kLinksFieldNumber = 2;
inline const ::pb_sample::Document_mlinks& links() const;
inline ::pb_sample::Document_mlinks* mutable_links();
inline ::pb_sample::Document_mlinks* release_links();
inline void set_allocated_links(::pb_sample::Document_mlinks* links);
// repeated .pb_sample.Document.mname Name = 3;
inline int name_size() const;
inline void clear_name();
static const int kNameFieldNumber = 3;
inline const ::pb_sample::Document_mname& name(int index) const;
inline ::pb_sample::Document_mname* mutable_name(int index);
inline ::pb_sample::Document_mname* add_name();
inline const ::google::protobuf::RepeatedPtrField< ::pb_sample::Document_mname >&
name() const;
inline ::google::protobuf::RepeatedPtrField< ::pb_sample::Document_mname >*
mutable_name();
// @@protoc_insertion_point(class_scope:pb_sample.Document)
private:
inline void set_has_docid();
inline void clear_has_docid();
inline void set_has_links();
inline void clear_has_links();
::google::protobuf::UnknownFieldSet _unknown_fields_;
::google::protobuf::int64 docid_;
::pb_sample::Document_mlinks* links_;
::google::protobuf::RepeatedPtrField< ::pb_sample::Document_mname > name_;
mutable int _cached_size_;
::google::protobuf::uint32 _has_bits_[(3 + 31) / 32];
friend void protobuf_AddDesc_pb_5fsample_2eproto();
friend void protobuf_AssignDesc_pb_5fsample_2eproto();
friend void protobuf_ShutdownFile_pb_5fsample_2eproto();
void InitAsDefaultInstance();
static Document* default_instance_;
};
// ===================================================================
// ===================================================================
// Document_mlinks
// repeated int64 Backward = 1;
inline int Document_mlinks::backward_size() const {
return backward_.size();
}
inline void Document_mlinks::clear_backward() {
backward_.Clear();
}
inline ::google::protobuf::int64 Document_mlinks::backward(int index) const {
return backward_.Get(index);
}
inline void Document_mlinks::set_backward(int index, ::google::protobuf::int64 value) {
backward_.Set(index, value);
}
inline void Document_mlinks::add_backward(::google::protobuf::int64 value) {
backward_.Add(value);
}
inline const ::google::protobuf::RepeatedField< ::google::protobuf::int64 >&
Document_mlinks::backward() const {
return backward_;
}
inline ::google::protobuf::RepeatedField< ::google::protobuf::int64 >*
Document_mlinks::mutable_backward() {
return &backward_;
}
// repeated int64 Forward = 2;
inline int Document_mlinks::forward_size() const {
return forward_.size();
}
inline void Document_mlinks::clear_forward() {
forward_.Clear();
}
inline ::google::protobuf::int64 Document_mlinks::forward(int index) const {
return forward_.Get(index);
}
inline void Document_mlinks::set_forward(int index, ::google::protobuf::int64 value) {
forward_.Set(index, value);
}
inline void Document_mlinks::add_forward(::google::protobuf::int64 value) {
forward_.Add(value);
}
inline const ::google::protobuf::RepeatedField< ::google::protobuf::int64 >&
Document_mlinks::forward() const {
return forward_;
}
inline ::google::protobuf::RepeatedField< ::google::protobuf::int64 >*
Document_mlinks::mutable_forward() {
return &forward_;
}
// -------------------------------------------------------------------
// Document_mname_mlanguage
// required string Code = 1;
inline bool Document_mname_mlanguage::has_code() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void Document_mname_mlanguage::set_has_code() {
_has_bits_[0] |= 0x00000001u;
}
inline void Document_mname_mlanguage::clear_has_code() {
_has_bits_[0] &= ~0x00000001u;
}
inline void Document_mname_mlanguage::clear_code() {
if (code_ != &::google::protobuf::internal::kEmptyString) {
code_->clear();
}
clear_has_code();
}
inline const ::std::string& Document_mname_mlanguage::code() const {
return *code_;
}
inline void Document_mname_mlanguage::set_code(const ::std::string& value) {
set_has_code();
if (code_ == &::google::protobuf::internal::kEmptyString) {
code_ = new ::std::string;
}
code_->assign(value);
}
inline void Document_mname_mlanguage::set_code(const char* value) {
set_has_code();
if (code_ == &::google::protobuf::internal::kEmptyString) {
code_ = new ::std::string;
}
code_->assign(value);
}
inline void Document_mname_mlanguage::set_code(const char* value, size_t size) {
set_has_code();
if (code_ == &::google::protobuf::internal::kEmptyString) {
code_ = new ::std::string;
}
code_->assign(reinterpret_cast<const char*>(value), size);
}
inline ::std::string* Document_mname_mlanguage::mutable_code() {
set_has_code();
if (code_ == &::google::protobuf::internal::kEmptyString) {
code_ = new ::std::string;
}
return code_;
}
inline ::std::string* Document_mname_mlanguage::release_code() {
clear_has_code();
if (code_ == &::google::protobuf::internal::kEmptyString) {
return NULL;
} else {
::std::string* temp = code_;
code_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString);
return temp;
}
}
inline void Document_mname_mlanguage::set_allocated_code(::std::string* code) {
if (code_ != &::google::protobuf::internal::kEmptyString) {
delete code_;
}
if (code) {
set_has_code();
code_ = code;
} else {
clear_has_code();
code_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString);
}
}
// optional string Country = 2;
inline bool Document_mname_mlanguage::has_country() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void Document_mname_mlanguage::set_has_country() {
_has_bits_[0] |= 0x00000002u;
}
inline void Document_mname_mlanguage::clear_has_country() {
_has_bits_[0] &= ~0x00000002u;
}
inline void Document_mname_mlanguage::clear_country() {
if (country_ != &::google::protobuf::internal::kEmptyString) {
country_->clear();
}
clear_has_country();
}
inline const ::std::string& Document_mname_mlanguage::country() const {
return *country_;
}
inline void Document_mname_mlanguage::set_country(const ::std::string& value) {
set_has_country();
if (country_ == &::google::protobuf::internal::kEmptyString) {
country_ = new ::std::string;
}
country_->assign(value);
}
inline void Document_mname_mlanguage::set_country(const char* value) {
set_has_country();
if (country_ == &::google::protobuf::internal::kEmptyString) {
country_ = new ::std::string;
}
country_->assign(value);
}
inline void Document_mname_mlanguage::set_country(const char* value, size_t size) {
set_has_country();
if (country_ == &::google::protobuf::internal::kEmptyString) {
country_ = new ::std::string;
}
country_->assign(reinterpret_cast<const char*>(value), size);
}
inline ::std::string* Document_mname_mlanguage::mutable_country() {
set_has_country();
if (country_ == &::google::protobuf::internal::kEmptyString) {
country_ = new ::std::string;
}
return country_;
}
inline ::std::string* Document_mname_mlanguage::release_country() {
clear_has_country();
if (country_ == &::google::protobuf::internal::kEmptyString) {
return NULL;
} else {
::std::string* temp = country_;
country_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString);
return temp;
}
}
inline void Document_mname_mlanguage::set_allocated_country(::std::string* country) {
if (country_ != &::google::protobuf::internal::kEmptyString) {
delete country_;
}
if (country) {
set_has_country();
country_ = country;
} else {
clear_has_country();
country_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString);
}
}
// -------------------------------------------------------------------
// Document_mname
// repeated .pb_sample.Document.mname.mlanguage Language = 1;
inline int Document_mname::language_size() const {
return language_.size();
}
inline void Document_mname::clear_language() {
language_.Clear();
}
inline const ::pb_sample::Document_mname_mlanguage& Document_mname::language(int index) const {
return language_.Get(index);
}
inline ::pb_sample::Document_mname_mlanguage* Document_mname::mutable_language(int index) {
return language_.Mutable(index);
}
inline ::pb_sample::Document_mname_mlanguage* Document_mname::add_language() {
return language_.Add();
}
inline const ::google::protobuf::RepeatedPtrField< ::pb_sample::Document_mname_mlanguage >&
Document_mname::language() const {
return language_;
}
inline ::google::protobuf::RepeatedPtrField< ::pb_sample::Document_mname_mlanguage >*
Document_mname::mutable_language() {
return &language_;
}
// optional string Url = 2;
inline bool Document_mname::has_url() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void Document_mname::set_has_url() {
_has_bits_[0] |= 0x00000002u;
}
inline void Document_mname::clear_has_url() {
_has_bits_[0] &= ~0x00000002u;
}
inline void Document_mname::clear_url() {
if (url_ != &::google::protobuf::internal::kEmptyString) {
url_->clear();
}
clear_has_url();
}
inline const ::std::string& Document_mname::url() const {
return *url_;
}
inline void Document_mname::set_url(const ::std::string& value) {
set_has_url();
if (url_ == &::google::protobuf::internal::kEmptyString) {
url_ = new ::std::string;
}
url_->assign(value);
}
inline void Document_mname::set_url(const char* value) {
set_has_url();
if (url_ == &::google::protobuf::internal::kEmptyString) {
url_ = new ::std::string;
}
url_->assign(value);
}
inline void Document_mname::set_url(const char* value, size_t size) {
set_has_url();
if (url_ == &::google::protobuf::internal::kEmptyString) {
url_ = new ::std::string;
}
url_->assign(reinterpret_cast<const char*>(value), size);
}
inline ::std::string* Document_mname::mutable_url() {
set_has_url();
if (url_ == &::google::protobuf::internal::kEmptyString) {
url_ = new ::std::string;
}
return url_;
}
inline ::std::string* Document_mname::release_url() {
clear_has_url();
if (url_ == &::google::protobuf::internal::kEmptyString) {
return NULL;
} else {
::std::string* temp = url_;
url_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString);
return temp;
}
}
inline void Document_mname::set_allocated_url(::std::string* url) {
if (url_ != &::google::protobuf::internal::kEmptyString) {
delete url_;
}
if (url) {
set_has_url();
url_ = url;
} else {
clear_has_url();
url_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString);
}
}
// -------------------------------------------------------------------
// Document
// required int64 DocId = 1;
inline bool Document::has_docid() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void Document::set_has_docid() {
_has_bits_[0] |= 0x00000001u;
}
inline void Document::clear_has_docid() {
_has_bits_[0] &= ~0x00000001u;
}
inline void Document::clear_docid() {
docid_ = GOOGLE_LONGLONG(0);
clear_has_docid();
}
inline ::google::protobuf::int64 Document::docid() const {
return docid_;
}
inline void Document::set_docid(::google::protobuf::int64 value) {
set_has_docid();
docid_ = value;
}
// optional .pb_sample.Document.mlinks Links = 2;
inline bool Document::has_links() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void Document::set_has_links() {
_has_bits_[0] |= 0x00000002u;
}
inline void Document::clear_has_links() {
_has_bits_[0] &= ~0x00000002u;
}
inline void Document::clear_links() {
if (links_ != NULL) links_->::pb_sample::Document_mlinks::Clear();
clear_has_links();
}
inline const ::pb_sample::Document_mlinks& Document::links() const {
return links_ != NULL ? *links_ : *default_instance_->links_;
}
inline ::pb_sample::Document_mlinks* Document::mutable_links() {
set_has_links();
if (links_ == NULL) links_ = new ::pb_sample::Document_mlinks;
return links_;
}
inline ::pb_sample::Document_mlinks* Document::release_links() {
clear_has_links();
::pb_sample::Document_mlinks* temp = links_;
links_ = NULL;
return temp;
}
inline void Document::set_allocated_links(::pb_sample::Document_mlinks* links) {
delete links_;
links_ = links;
if (links) {
set_has_links();
} else {
clear_has_links();
}
}
// repeated .pb_sample.Document.mname Name = 3;
inline int Document::name_size() const {
return name_.size();
}
inline void Document::clear_name() {
name_.Clear();
}
inline const ::pb_sample::Document_mname& Document::name(int index) const {
return name_.Get(index);
}
inline ::pb_sample::Document_mname* Document::mutable_name(int index) {
return name_.Mutable(index);
}
inline ::pb_sample::Document_mname* Document::add_name() {
return name_.Add();
}
inline const ::google::protobuf::RepeatedPtrField< ::pb_sample::Document_mname >&
Document::name() const {
return name_;
}
inline ::google::protobuf::RepeatedPtrField< ::pb_sample::Document_mname >*
Document::mutable_name() {
return &name_;
}
// @@protoc_insertion_point(namespace_scope)
} // namespace pb_sample
#ifndef SWIG
namespace google {
namespace protobuf {
} // namespace google
} // namespace protobuf
#endif // SWIG
// @@protoc_insertion_point(global_scope)
#endif // PROTOBUF_pb_5fsample_2eproto__INCLUDED
|
dedc4af91a32bcd64d3e8358ab8147ca74f85526
|
7b633bd7d0872885644c0bd40c445edd03512748
|
/beakjoon/beakjoon/step/all/4_1_10952.cpp
|
10ef6bc3e572a69de82a30e7923ae4208951d7bf
|
[] |
no_license
|
capple8230/Algorithm
|
54cb10f00312bc255bdcdf97a078a110b9cb73bf
|
f57c8790c2299470c480c45fcefd87740218dcdc
|
refs/heads/main
| 2023-05-05T05:07:18.035533
| 2021-05-29T06:05:47
| 2021-05-29T06:05:47
| 371,889,297
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 294
|
cpp
|
4_1_10952.cpp
|
#include <iostream>
int main()
{
int a = 0, b = 0;
while (1) {
std::cin >> a >> b;
if (a == 0 && b == 0)
break;
std::cout << a + b << "\n";
}
//int a = 1, b = 1;
//while (a != 0 && b != 0) {
// std::cin >> a >> b;
// if (a != 0 && b != 0) std::cout << a + b << "\n";
//}
}
|
315cf272654837fb059ae08202c0d2d61e1932d9
|
1c8951c2c8ce98eec60e59403c8742706b9122c7
|
/1/模擬題5.cpp
|
7573fe3c0a495aad3d3832a44f486eb5b65d507d
|
[] |
no_license
|
Evelyn05/1071-c-programming
|
7d7a2594ee72994d213a438d463542680e331b4e
|
c47f18710701f212bff99ce347d85563828c764f
|
refs/heads/master
| 2021-07-25T15:18:51.897204
| 2019-01-04T06:33:28
| 2019-01-04T06:33:28
| 149,092,496
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,498
|
cpp
|
模擬題5.cpp
|
#include <stdio.h>
int ari(int in1,int in2,int sum,int minus,int multi,int dev,int a){
sum=in1+in2;
minus=in1-in2;
multi=in1*in2;
dev=in1/in2;
a=in1%in2;
printf("%d+%d=%d\n",in1,in2,sum);
printf("%d-%d=%d\n",in1,in2,minus);
printf("%d*%d=%d\n",in1,in2,multi);
printf("%d/%d=%d\n",in1,in2,dev);
printf("%d%c%d=%d\n",in1,'%',in2,a);
}
int BMI(int h1,int h2,float a1,float a2){
if(h1>0&&h2>0){
for(int i=h1;i<=h2;i++){
a1=(i*i/10000.)*18.5;
a2=(i*i/10000.)*24;
printf("%4d cm=%.1f ~ %.1f(Kg)\n",i,a1,a2);
}
}
}
void prchar(char c,int n){
for(int i=1;i<=n;i++){
printf("%c",c);
}
}
int Triangles(int height){
if(height>0){
for(int i=1;i<=height;i++){
prchar(' ',height-i);
prchar('*',i);
prchar(' ',2);
prchar('*',i);
printf("\n");}
}
}
int enc(int N,int encode){
if(N>0){
encode=(N%1000%100/10)*1000+(N%1000%100%10)*100+((N/1000+5)%10)*10+N%1000/100;
printf("encode(%d)=%d\n",N,encode);
}
}
int dec(int n,int decode){
if(n>0){
decode=((n%1000%100/10)+5)%10*1000+(n%1000%100%10)*100+(n/1000)*10+(n%1000/100);
printf("decode(%d)=%d\n",n,decode);
}
}
int main(){
int choice;
int in1,in2,sum,minus,multi,dev,a;
int h1,h2;
float a1,a2;
int height;
int N,encode;
int n,decode;
while(1){
printf("(1) Arithmetic Computation\n");
printf("(2) List BMI ranges \n");
printf("(3) Draw Four Vertical Triangles\n");
printf("(4) encode(n) \n");
printf("(5)decode(n) \n");
printf("(6) Exit \n");
scanf("%d",&choice);
if(choice==6){
printf("Bye! Coding by 406530120\n");
break;
}
switch(choice){
case 1:
printf("Enter two integers: ");
scanf("%d %d",&in1,&in2);
ari(in1,in2,sum,minus,multi,dev,a);
break;
case 2:
printf("Enter height: ");
scanf("%d %d",&h1,&h2);
BMI(h1,h2,a1,a2);
break;
case 3:
printf("Enter height: ");
scanf("%d",&height);
Triangles(height);
break;
case 4:
printf("Enter N: ");
scanf("%d",&N);
enc(N,encode);
break;
case 5:
printf("Enter n: ");
scanf("%d",&n);
dec(n,decode);
break;
}
}return 0;
}
|
b04e8bcaac15441da60c8da83ee19c843f4fc82e
|
55a0fe2065baad3f4b509389a7bf6e96723b2682
|
/step1_五种数据结构/StString.cpp
|
784262205fd085a71a469892feeb7595d4cd527f
|
[] |
no_license
|
haohaoxuexi4/Learn_Redis
|
e98464b52eefa46d47cd24948a781950aaaca5b1
|
dd5c014b2617671fbfb437e00101d5cc7bdb0785
|
refs/heads/master
| 2021-01-24T08:00:12.500384
| 2017-06-14T12:45:54
| 2017-06-14T12:45:54
| 93,368,580
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,981
|
cpp
|
StString.cpp
|
//
// StString.cpp
// suitredies
//
// Created by 仙女 on 2017/5/23.
// Copyright © 2017年 仙女. All rights reserved.
//
#include "StString.hpp"
#include <assert.h>
#define MAXININSIZE 100
StString::StString()
{
data=new char[1];
data[0]='\0';
freelen=0;
usedlen=0;
}
StString::StString(const char* init,ssize_t initsize)
{
assert(init!=NULL);
data=new char[initsize+1];
memcpy(data,init,initsize);
data[initsize]='\0';
freelen=0;
usedlen=initsize;
}
StString::StString(const char* init)
{
assert(init!=nullptr);
ssize_t len=strlen(init);
data=new char [len+1];
memcpy(data, init, len);
data[len]='\0';
freelen=0;
usedlen=len;
}
StString::StString(const StString& st)
{
usedlen=st.usedlen;
freelen=st.freelen;
ssize_t len=strlen(st.data);
data=new char[len+1];
memcpy(data, st.data, len);
data[len]='\0';
}
StString& StString::operator=(const StString &st)
{
if(&st==this) return *this;
delete []data;
usedlen=st.usedlen;
freelen=st.freelen;
data=new char[strlen(st.data)+1];
memcpy(data, st.data, strlen(st.data));
data[strlen(st.data)]='\0';
return *this;
}
StString::~StString()
{
delete [] data;
freelen=0;
usedlen=0;
}
void StString::MakeRoom(ssize_t len)
{
const char* tmp=data;
ssize_t usedlentmp=usedlen;
//ssize_t freelentmp=freelen;
data=new char[len+1];
memcpy(data, tmp, usedlentmp);
data[usedlentmp]='\0';
usedlen=usedlentmp;
freelen=len-usedlentmp;
delete [] tmp;
}
/*
将长度为appendlen的数据追加到buf末尾
返回追加了多少字节
第一种情况:free >= appendlen
第二种: free<appendlen
默认,如果总长度小于1024,则扩展2倍,如果大于1024,就扩展所需空间
*/
ssize_t StString::AppendData(const char *apdata, ssize_t aplen)
{
assert(apdata!=nullptr);
if(freelen>=aplen)
{
//直接扩展
memcpy(data+usedlen, apdata, aplen);
usedlen=usedlen+aplen;
freelen=freelen-aplen;
data[usedlen]='\0';
}
else
{
//先申请空间
if((usedlen+aplen)<MAXININSIZE)
{
ssize_t len=(usedlen+aplen)*2;
MakeRoom(len);
memcpy(data+usedlen, apdata, aplen);
usedlen=usedlen+aplen;
//printf("len=%d,uselen=%d\n",len,usedlen);
freelen=len-usedlen;
data[usedlen]='\0';
}
else
{
ssize_t len=usedlen+aplen;
MakeRoom(len);
memcpy(data+usedlen, apdata, aplen);
usedlen=usedlen+aplen;
freelen=len-usedlen;
data[usedlen]='\0';
}
}
return aplen;
}
ssize_t StString::AppendDate(const char *apdata)
{
assert(apdata!=nullptr);
ssize_t len=strlen(apdata);
return AppendData(apdata, len);
}
|
ee120dd1f30dbd8b21e39a722f86e0f607b1fc4b
|
82a3e40b75d0cc4250998702c2bff873590d92db
|
/src/aera/TabFrame.cpp
|
ebad4e4f1ee81ded7b0b48d0973f96e34a620b69
|
[] |
no_license
|
PavelAmialiushka/Aera.demo
|
12c7981d0883e8b832c2f3e72fee14234cdeb3b0
|
4beeb315a99da6f90a87ba0bb5b3dffa6c52bd2d
|
refs/heads/master
| 2021-10-11T14:41:00.180456
| 2019-01-27T13:38:21
| 2019-01-27T13:38:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,462
|
cpp
|
TabFrame.cpp
|
#include "stdafx.h"
#include "TabFrame.h"
#include "utilites/Localizator.h"
#include "resource.h"
#include "tileview/TVFrame.h"
LRESULT CTabbedChildWindowX::OnNotify(int id, LPNMHDR hdr)
{
if (hdr->code >= TVFN_FIRST && hdr->code <= TVFN_LAST)
{
return ::SendMessage(GetParent(), WM_NOTIFY, (WPARAM)id, (LPARAM)hdr);
}
else
{
switch (hdr->code)
{
case NM_RCLICK:
{
CMenu menu( ::CreatePopupMenu() );
menu.AppendMenu(MF_STRING, IDC_PAGES_NEW_PAGE, _lcs("&New page"));
menu.AppendMenu(MF_STRING, IDC_PAGES_RENAME_PAGE, _lcs("&Rename"));
menu.AppendMenu(MF_SEPARATOR);
menu.AppendMenu(MF_STRING, IDC_PAGES_DELETE_PAGE, _lcs("&Delete tab"));
CPoint pt; GetCursorPos(&pt);
int ret=menu.TrackPopupMenu(
TPM_RETURNCMD|TPM_BOTTOMALIGN|TPM_RIGHTALIGN,
pt.x, pt.y, *this);
if (ret!=0)
{
::PostMessage(GetParent(), WM_COMMAND, MAKEWPARAM(ret, 1), 0);
}
}
break;
case CTCN_SELCHANGE:
::SetFocus(GetActiveView());
default:
break;
}
}
SetMsgHandled(false);
return 0;
}
HWND CTabbedChildWindowX :: GetView(unsigned index)
{
CTabViewTabItem *item=GetTabCtrl().GetItem(index);
debug::Assert<fault>(item, HERE);
return item->GetTabView();
}
|
270a619610c715517ade05269cd06a3dee4152cc
|
d4bd481b1f2fed4f532c8805bfb8b3bfdce73c41
|
/src/system/main_control_loop.cpp
|
5ee1806f65173feddf0952b682a461c8ab3d772e
|
[
"MIT"
] |
permissive
|
unhuman-io/motor
|
09b6875fc39370ac65320f8c61c89a2b846e56ba
|
b1a37f6fa851bc5d08ef0a1d94b9782b6a7c4233
|
refs/heads/master
| 2020-04-03T17:53:14.992725
| 2018-10-31T15:59:56
| 2018-10-31T15:59:56
| 155,462,651
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 32
|
cpp
|
main_control_loop.cpp
|
#include "main_control_loop.h"
|
87e790ad866420658384d17d2ff49a3605576209
|
2095e4d95bb5140536bc97f63def5ca8b8a49b3c
|
/q3D2D.h
|
200898f659c183ac36c7bfc95aea6ceb03b4297b
|
[] |
no_license
|
IdeGelis/q3D2D
|
eecf63f5581ddb6c9bd6e6a2769bb31ee1548d37
|
2f40b36a152df9a485b4aaf76d80c55b0f91810c
|
refs/heads/master
| 2021-09-17T06:53:10.878370
| 2018-06-28T23:19:20
| 2018-06-28T23:19:20
| 114,896,046
| 6
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,944
|
h
|
q3D2D.h
|
//##########################################################################
//# #
//# CLOUDCOMPARE PLUGIN: q3D2D #
//# #
//# This program is free software; you can redistribute it and/or modify #
//# it under the terms of the GNU General Public License as published by #
//# the Free Software Foundation; version 2 of the License. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU General Public License for more details. #
//# #
//# COPYRIGHT: ENSG Iris de Gelis #
//# #
//##########################################################################
#ifndef Q_3D2D_PLUGIN_HEADER
#define Q_3D2D_PLUGIN_HEADER
//qCC
#include "../ccStdPluginInterface.h"
/** The most important one is the
'getActions' method. This method should return all actions
(QAction objects). CloudCompare will automatically add them to an
icon in the plugin toolbar and to an entry in the plugin menu
(if your plugin returns several actions, CC will create a dedicated
toolbar and sub-menu).
You are responsible to connect these actions to custom slots of your
plugin.
Look at the ccStdPluginInterface::m_app attribute to get access to
most of CC components (database, 3D views, console, etc.).
**/
class q3D2D : public QObject, public ccStdPluginInterface
{
Q_OBJECT
Q_INTERFACES(ccStdPluginInterface)
//replace qDummy by the plugin name (IID should be unique - let's hope your plugin name is unique ;)
Q_PLUGIN_METADATA(IID "cccorp.cloudcompare.plugin.q3D2D")
public:
//! Default constructor
explicit q3D2D(QObject* parent = 0);
//inherited from ccPluginInterface
virtual QString getName() const override { return "q3D2D"; }
virtual QString getDescription() const override { return "Reprojection 3D to 2D"; }
virtual QIcon getIcon() const override;
//inherited from ccStdPluginInterface
void onNewSelection(const ccHObject::Container& selectedEntities) override;
virtual void getActions(QActionGroup& group) override;
protected slots:
/*** ADD YOUR CUSTOM ACTIONS' SLOTS HERE ***/
void doAction();
protected:
//! Default action
/** You can add as many actions as you want in a plugin.
All actions will correspond to an icon in the dedicated
toolbar and an entry in the plugin menu.
**/
QAction* m_action;
};
#endif
|
b7a02af21d3ae8da47ec52b14315ceba4b36e1c8
|
78054846318f3b4b962550816fa83daa05b7dcc8
|
/nthTriangle/main.cpp
|
253e5ed50943d244db5d11933fdfb96a92801b54
|
[] |
no_license
|
anmolduainter/cLionProjects
|
2ee6563900ed294254d7014df6698149aa2ed332
|
8186f13b6a79de23b97e8f03bbf043c4b8222208
|
refs/heads/master
| 2021-05-16T00:37:01.518370
| 2017-10-21T06:40:58
| 2017-10-21T06:40:58
| 106,949,402
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 500
|
cpp
|
main.cpp
|
#include<bits/stdc++.h>
using namespace std;
int totient(int n){
float result=n;
for (int i = 2; i < sqrt(n) ; ++i) {
if (n%i==0){
while(n%i==0){
n/=i;
}
result*=(1.0-1.0/(float)i);
}
}
if(n>1){
result*=(1.0-1.0/(float)n);
}
return (int)result;
}
int main(){
int t;
cin>>t;
for (int i = 0; i < t ; ++i) {
int a;
cin>>a;
cout<<totient(a)<<endl;
}
}
|
68b090ee7c0dd57b153a7cdcac2455fbc477e765
|
62aecb16eb942d06983a43c9ec9e335b684a0a48
|
/engine/src/vulkan/command/ClearScreenRecorder.hpp
|
169423f7c1570865a62075b8919ab87567aec369
|
[
"MIT"
] |
permissive
|
Velikss/Bus-Simulator
|
1a707a7cadb16d35eefe864e0a3de28777253d19
|
13bf0b66b9b44e3f4cb1375fc363720ea8f23e19
|
refs/heads/master
| 2022-11-06T12:06:59.054896
| 2020-06-15T12:42:58
| 2020-06-15T12:42:58
| 266,741,328
| 0
| 0
|
MIT
| 2020-06-15T12:31:43
| 2020-05-25T09:41:51
|
C++
|
UTF-8
|
C++
| false
| false
| 1,979
|
hpp
|
ClearScreenRecorder.hpp
|
#pragma once
#include <pch.hpp>
#include <vulkan/module/lighting/LightingRenderPass.hpp>
#include <vulkan/swapchain/SwapChain.hpp>
#include <vulkan/command/CommandBufferRecorder.hpp>
class cClearScreenRecorder : public iCommandBufferRecorder
{
private:
cRenderPass* ppRenderPass;
cSwapChain* ppSwapChain;
VkRenderPassBeginInfo ptRenderPassInfo = {};
std::array<VkClearValue, 2> paoClearValues = {};
public:
cClearScreenRecorder(cRenderPass* pRenderPass,
cSwapChain* pSwapChain);
void Setup(uint uiIndex) override;
void RecordCommands(VkCommandBuffer& oCommandBuffer, uint uiIndex) override;
};
cClearScreenRecorder::cClearScreenRecorder(cRenderPass* pRenderPass,
cSwapChain* pSwapChain)
{
ppRenderPass = pRenderPass;
ppSwapChain = pSwapChain;
}
void cClearScreenRecorder::Setup(uint uiIndex)
{
// Struct with information about our render pass
ptRenderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
// Set the render pass and framebuffer
ptRenderPassInfo.renderPass = ppRenderPass->GetRenderPass();
ptRenderPassInfo.framebuffer = ppSwapChain->GetFramebuffer(uiIndex);
// Set the render area size
ptRenderPassInfo.renderArea.offset = {0, 0};
ptRenderPassInfo.renderArea.extent = ppSwapChain->ptSwapChainExtent;
// Defines the clear color value to use
paoClearValues[0].color = {0.0f, 0.0f, 0.0f, 1.0f}; // black with 100% opacity
paoClearValues[1].depthStencil = {1.0f, 0}; // furthest possible depth
ptRenderPassInfo.clearValueCount = (uint) paoClearValues.size();
ptRenderPassInfo.pClearValues = paoClearValues.data();
}
void cClearScreenRecorder::RecordCommands(VkCommandBuffer& oCommandBuffer, uint uiIndex)
{
// Begin the render pass
vkCmdBeginRenderPass(oCommandBuffer, &ptRenderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
// End the render pass
vkCmdEndRenderPass(oCommandBuffer);
}
|
bde7c06c10e0a36c98bd7399c8bd0255450c451d
|
eab1807e5f09e31a5cacc0ba1275eead24cea76e
|
/qt_GL/Widgets_SiTTuGAs/Plugins/welemento_aplugin.cpp
|
59080b3c6f0d01dc866f79303aa804014bde7e89
|
[] |
no_license
|
mbravod/aeros
|
8af48c0e3d1d9055195236915c951ddd730d219c
|
239ba1fae4ab7a8f01aa58df4dfe627ac3f9e731
|
refs/heads/master
| 2016-09-05T12:40:15.205595
| 2014-01-09T21:29:49
| 2014-01-09T21:29:49
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,260
|
cpp
|
welemento_aplugin.cpp
|
#include "welemento_a.h"
#include "welemento_aplugin.h"
#include <QtCore/QtPlugin>
wElemento_APlugin::wElemento_APlugin(QObject *parent)
: QObject(parent)
{
m_initialized = false;
}
void wElemento_APlugin::initialize(QDesignerFormEditorInterface * /* core */)
{
if (m_initialized)
return;
// Add extension registrations, etc. here
m_initialized = true;
}
bool wElemento_APlugin::isInitialized() const
{
return m_initialized;
}
QWidget *wElemento_APlugin::createWidget(QWidget *parent)
{
return new wElemento_A(parent);
}
QString wElemento_APlugin::name() const
{
return QLatin1String("wElemento_A");
}
QString wElemento_APlugin::group() const
{
return QLatin1String("");
}
QIcon wElemento_APlugin::icon() const
{
return QIcon();
}
QString wElemento_APlugin::toolTip() const
{
return QLatin1String("");
}
QString wElemento_APlugin::whatsThis() const
{
return QLatin1String("");
}
bool wElemento_APlugin::isContainer() const
{
return false;
}
QString wElemento_APlugin::domXml() const
{
return QLatin1String("<widget class=\"wElemento_A\" name=\"w_Elemento_A\">\n</widget>\n");
}
QString wElemento_APlugin::includeFile() const
{
return QLatin1String("welemento_a.h");
}
|
6a1d55026407e05f6c0e2597c7bd11bccaa99768
|
41495754cf8b951b23cece87b5c79a726748cff7
|
/Solutions/UVA/10306.cpp
|
7f2334d6def6da577c3fd6cc38a5f4cb63dc5e69
|
[] |
no_license
|
PedroAngeli/Competitive-Programming
|
86ad490eced6980d7bc3376a49744832e470c639
|
ff64a092023987d5e3fdd720f56c62b99ad175a6
|
refs/heads/master
| 2021-10-23T04:49:51.508166
| 2021-10-13T21:39:21
| 2021-10-13T21:39:21
| 198,916,501
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,818
|
cpp
|
10306.cpp
|
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define endl '\n'
#define f first
#define s second
#define ub upper_bound
#define lb lower_bound
#define pb push_back
#define all(c) (c).begin(), (c).end()
#define sz(x) (int)(x).size()
#define ordered_set tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update>
#define fbo find_by_order
#define ook order_of_key
#define fastio ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define debug(...) __f(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1>
void __f(const char* name, Arg1&& arg1){
cerr << "[" << name << " : " << arg1 << "]" << endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args){
const char* comma = strchr(names + 1, ',');cerr << "[";
cerr.write(names, comma - names) << " : " << arg1<<"] | ";__f(comma+1, args...);
}
using ld = long double;
using ll = long long;
using pii = pair <int,int>;
using pll = pair <ll,ll>;
using vi = vector <int>;
using vll = vector <ll>;
using vpii = vector <pii>;
using vpll = vector<pll>;
using vs = vector <string>;
int dp[301][301];
int n, S;
int x[40], y[40];
const int INF = 1e9 + 7;
int solve(int i, int j){
if(i*i + j*j > S*S) return INF;
if(i*i + j*j == S*S) return 0;
int& state = dp[i][j];
if(state != -1) return state;
state = INF;
for(int k=0;k<n;k++)
state = min(state, 1 + solve(i+x[k], j+y[k]));
return state;
}
int main(){
fastio;
int t;
cin >> t;
while(t--){
memset(dp, -1, sizeof dp);
cin >>n >> S;
for(int i=0;i<n;i++) cin >> x[i] >> y[i];
int ans = solve(0, 0);
if(ans == INF) cout << "not possible" << endl;
else cout << ans << endl;
}
return 0;
}
|
440e517fe0d36b7974591c786b5b4e3a94003b9a
|
38bd1cf9e52ea23b43223d53d8139aad52bb1c70
|
/cpp/iedriver/Browser.h
|
23b0084b9a881617dbea8ba8a31ee6d5eaab255d
|
[
"Apache-2.0"
] |
permissive
|
SeleniumHQ/selenium
|
46d9553e3a45412a7540dd3f7d1f34be6ef42b1b
|
cc41a883b5138962c6b4408a0fdf4e932bd08071
|
refs/heads/trunk
| 2023-09-03T22:56:56.403484
| 2023-09-02T19:20:45
| 2023-09-02T19:20:45
| 7,613,257
| 30,383
| 9,671
|
Apache-2.0
| 2023-09-14T18:47:42
| 2013-01-14T21:40:56
|
Java
|
UTF-8
|
C++
| false
| false
| 6,396
|
h
|
Browser.h
|
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
#ifndef WEBDRIVER_IE_BROWSER_H_
#define WEBDRIVER_IE_BROWSER_H_
#include <string>
#include <vector>
#include <exdispid.h>
#include <mshtml.h>
#include "DocumentHost.h"
namespace webdriver {
struct BrowserReattachInfo {
DWORD current_process_id;
std::vector<DWORD> known_process_ids;
std::string browser_id;
};
struct NewWindowInfo {
std::string target_url;
LPSTREAM browser_stream;
};
// Forward declaration of classes to avoid
// circular include files.
class ElementRepository;
class Browser : public DocumentHost, public IDispEventSimpleImpl<1, Browser, &DIID_DWebBrowserEvents2> {
public:
Browser(IWebBrowser2* browser, HWND hwnd, HWND session_handle, bool isEdgeChrome = false);
virtual ~Browser(void);
static inline _ATL_FUNC_INFO* BeforeNavigate2Info() {
static _ATL_FUNC_INFO kBeforeNavigate2 = { CC_STDCALL,
VT_EMPTY,
7,
{ VT_DISPATCH,
VT_VARIANT | VT_BYREF,
VT_VARIANT | VT_BYREF,
VT_VARIANT | VT_BYREF,
VT_VARIANT | VT_BYREF,
VT_VARIANT | VT_BYREF,
VT_BOOL | VT_BYREF } };
return &kBeforeNavigate2;
}
static inline _ATL_FUNC_INFO* DocumentCompleteInfo() {
static _ATL_FUNC_INFO kDocumentComplete = { CC_STDCALL,
VT_EMPTY,
2,
{ VT_DISPATCH,
VT_VARIANT|VT_BYREF } };
return &kDocumentComplete;
}
static inline _ATL_FUNC_INFO* NoArgumentsInfo() {
static _ATL_FUNC_INFO kNoArguments = { CC_STDCALL, VT_EMPTY, 0 };
return &kNoArguments;
}
static inline _ATL_FUNC_INFO* NewWindow3Info() {
static _ATL_FUNC_INFO kNewWindow3 = { CC_STDCALL, VT_EMPTY, 5,
{ VT_DISPATCH | VT_BYREF,
VT_BOOL | VT_BYREF,
VT_I4,
VT_BSTR,
VT_BSTR } };
return &kNewWindow3;
}
static inline _ATL_FUNC_INFO* NewProcessInfo() {
static _ATL_FUNC_INFO kNewProcess = { CC_STDCALL, VT_EMPTY, 3,
{ VT_I4,
VT_DISPATCH,
VT_BOOL | VT_BYREF } };
return &kNewProcess;
}
BEGIN_SINK_MAP(Browser)
SINK_ENTRY_INFO(1, DIID_DWebBrowserEvents2, DISPID_BEFORENAVIGATE2, BeforeNavigate2, BeforeNavigate2Info())
SINK_ENTRY_INFO(1, DIID_DWebBrowserEvents2, DISPID_DOCUMENTCOMPLETE, DocumentComplete, DocumentCompleteInfo())
SINK_ENTRY_INFO(1, DIID_DWebBrowserEvents2, DISPID_ONQUIT, OnQuit, NoArgumentsInfo())
SINK_ENTRY_INFO(1, DIID_DWebBrowserEvents2, DISPID_NEWWINDOW3, NewWindow3, NewWindow3Info())
SINK_ENTRY_INFO(1, DIID_DWebBrowserEvents2, DISPID_NEWPROCESS, NewProcess, NewProcessInfo())
END_SINK_MAP()
STDMETHOD_(void, BeforeNavigate2)(IDispatch* pObject, VARIANT* pvarUrl, VARIANT* pvarFlags,
VARIANT* pvarTargetFrame, VARIANT* pvarData, VARIANT* pvarHeaders, VARIANT_BOOL* pbCancel);
STDMETHOD_(void, DocumentComplete)(IDispatch* pDisp, VARIANT* URL);
STDMETHOD_(void, OnQuit)();
STDMETHOD_(void, NewWindow3)(IDispatch** ppDisp, VARIANT_BOOL* pbCancel, DWORD dwFlags, BSTR bstrUrlContext, BSTR bstrUrl);
STDMETHOD_(void, NewProcess)(DWORD lCauseFlag, IDispatch* pWB2, VARIANT_BOOL* pbCancel);
bool Wait(const std::string& page_load_strategy);
void Close(void);
bool IsBusy(void);
void GetDocument(const bool force_top_level_document,
IHTMLDocument2** doc);
void GetDocument(IHTMLDocument2** doc);
std::string GetWindowName(void);
std::string GetTitle(void);
std::string GetBrowserUrl(void);
HWND GetContentWindowHandle(void);
HWND GetBrowserWindowHandle(void);
HWND GetTopLevelWindowHandle(void);
HWND GetActiveDialogWindowHandle(void);
long GetWidth(void);
long GetHeight(void);
void SetWidth(long width);
void SetHeight(long height);
int NavigateToUrl(const std::string& url, std::string* error_message);
int NavigateBack(void);
int NavigateForward(void);
int Refresh(void);
bool IsValidWindow(void);
bool IsFullScreen(void);
bool SetFullScreen(bool is_full_screen);
void InitiateBrowserReattach(void);
void ReattachBrowser(IWebBrowser2* browser);
bool is_explicit_close_requested(void) const {
return this->is_explicit_close_requested_;
}
IWebBrowser2* browser(void) { return this->browser_; }
private:
void AttachEvents(void);
void DetachEvents(void);
bool IsDocumentNavigating(const std::string& page_load_strategy,
IHTMLDocument2* doc);
bool GetDocumentFromWindow(IHTMLWindow2* window, IHTMLDocument2** doc);
void CheckDialogType(HWND dialog_window_handle);
static unsigned int WINAPI GoBackThreadProc(LPVOID param);
static unsigned int WINAPI GoForwardThreadProc(LPVOID param);
CComPtr<IWebBrowser2> browser_;
bool is_navigation_started_;
bool is_explicit_close_requested_;
std::vector<DWORD> known_process_ids_;
};
} // namespace webdriver
#endif // WEBDRIVER_IE_BROWSER_H_
|
94e0f353a128c5e805470c4f97b0124a43c01214
|
39bad846f4e8795e47f7ffef5d75faf4bfb7a5e2
|
/calculator.cpp
|
92a841ed115072cd51a3c5a4aa1f4699e1bbd4f4
|
[] |
no_license
|
kino6052/hubert
|
1b61c4d044748c327ab6b71ee86ddcebbfca5f3b
|
bc880959eca4724d571e76e599e27b8eff473a98
|
refs/heads/master
| 2021-01-10T08:25:19.271524
| 2015-12-11T04:51:45
| 2015-12-11T04:51:45
| 47,732,598
| 0
| 0
| null | 2015-12-11T04:51:46
| 2015-12-10T02:27:30
|
C++
|
UTF-8
|
C++
| false
| false
| 1,245
|
cpp
|
calculator.cpp
|
#include "data.h"
#include "calculator.h"
#include <string>
using namespace std;
Calculator::Calculator(){arrayLength=0;};
void Calculator::addIdAndWeight(int idInput, int weightInput){
int counter=0;
while (counter<arrayLength){
if (idArray[counter] == idInput){ //if id is in the array
countArray[counter]++;
return;
}
counter++;
}
countArray[arrayLength]++;
idArray[arrayLength] = idInput;
weightArray[arrayLength] += weightInput; // add weights to then divide by the number of times store shows up
arrayLength++;
};
int Calculator::getIdArray(int index){
return idArray[index];
}
int Calculator::getCountArray(int index){
return countArray[index];
}
int Calculator::getWeightArray(int index){
return weightArray[index];
}
void Calculator::calculateAverageWeight(){
for (int i=0; i<arrayLength; i++){
weightArray[i] = weightArray[i]/countArray[i];
}
}
int Calculator::findDonorIdWithMaximumAverageDonationWeight(){
int max = 0;
int index = 0;
for (int i=0; i<arrayLength; i++){
if (weightArray[i] > max){
max = weightArray[i];
index = i;
}
}
return idArray[index];
}
|
7fa8ad56079e95ced2d847537aeebc4a062e439f
|
aa34ffe019da12cac9dc41e1ec939de31bbf3134
|
/gamecrash/src/GameCloud.cpp
|
868aac29d265416995fe2088ab7539852276cbc7
|
[] |
no_license
|
alexeyqian/study
|
1ce7e43bf9058e2624735380be7f0cb4024884b1
|
8995bae5aeaacb3a7da82022c65aa04b74a06f0a
|
refs/heads/master
| 2023-06-26T12:21:43.304638
| 2021-08-01T08:21:24
| 2021-08-01T08:21:24
| 391,025,286
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 416
|
cpp
|
GameCloud.cpp
|
#include "./include/GameCloud.h"
#include <SFML/Graphics.hpp>
using namespace sf;
void GameCloud::setup() {
Texture textureCloud;
textureCloud.loadFromFile("../src/graphics/cloud.png");
for(int i = 0; i < DEFAULT_CLOUD_COUNT; i++){
Sprite cloud;
cloud.setTexture(textureCloud);
cloud.setPosition(0, i * 250);
cloudActives[i] = false;
cloudSpeeds[i] = 0;
}
}
|
91a9f310c8d3d6fb0e4663f7e62081e9a821c0c8
|
f81124e4a52878ceeb3e4b85afca44431ce68af2
|
/re20_2/processor44/5/phi
|
b9e28cea1db0ca8836fda0329b47fae85d44fc82
|
[] |
no_license
|
chaseguy15/coe-of2
|
7f47a72987638e60fd7491ee1310ee6a153a5c10
|
dc09e8d5f172489eaa32610e08e1ee7fc665068c
|
refs/heads/master
| 2023-03-29T16:59:14.421456
| 2021-04-06T23:26:52
| 2021-04-06T23:26:52
| 355,040,336
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,413
|
phi
|
/*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 7
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class surfaceScalarField;
location "5";
object phi;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 3 -1 0 0 0 0];
internalField nonuniform List<scalar>
649
(
0.00270223
-2.68467e-05
4.26866e-09
0.00272742
-2.51906e-05
4.41176e-09
0.00275099
-2.35773e-05
4.50961e-09
-2.20111e-05
4.55957e-09
0.00270109
0.00272624
-5.03395e-05
0.00274978
-4.71187e-05
-4.39919e-05
0.00272388
-7.54148e-05
0.00274736
-7.05982e-05
-6.59217e-05
0.00272033
-0.000100381
0.00274371
-9.39867e-05
-8.77768e-05
0.00271557
-0.000125207
0.00273884
-0.000117257
-0.000109535
0.00270959
-0.000149861
0.00273272
-0.000140384
-0.000131177
0.00270236
-0.000174319
0.00272533
-0.000163348
-0.000152686
0.00269387
-0.000198557
0.00271665
-0.000186129
-0.000174047
0.00268409
-0.000222558
0.00270668
-0.000208715
-0.000195253
0.00267299
-0.000246311
0.00269537
-0.000231097
-0.000216295
0.00266054
-0.000269806
0.00268271
-0.000253269
-0.000237174
0.00264671
-0.000293042
0.00266868
-0.000275233
-0.00025789
0.00263148
-0.000316021
0.00265324
-0.000296992
-0.000278451
0.00261483
-0.000338751
0.00263639
-0.000318555
-0.000298867
0.00259673
-0.000361245
0.00261811
-0.000339938
-0.000319154
0.00257715
-0.000383521
0.00259837
-0.000361157
-0.00033933
0.00255609
0.00257716
-0.000382236
0.00259725
-0.000359417
-0.000337211
0.00255449
-0.000403199
0.00257451
-0.00037944
-0.000356305
0.00253033
-0.000424077
0.00255032
-0.00039943
-0.000375413
0.00250469
-0.000444901
0.00252468
-0.000419416
-0.000394565
0.00247757
-0.000465705
0.00249759
-0.000439433
-0.000413794
0.00244898
-0.000486528
0.00246906
-0.000459516
-0.000433134
0.00241892
-0.000507408
0.00243911
-0.000479704
-0.000452623
0.00238749
-0.000528384
0.00240782
-0.000500032
-0.000472294
0.00769364
-0.000558624
0.00772269
-0.000529076
-0.00050014
0.00775805
-0.000583229
0.00778184
-0.00055287
-0.000523105
0.00782294
-0.000602222
0.0078415
-0.000571428
-0.000541198
0.0078875
-0.000615769
0.00790097
-0.000584891
-0.000554536
0.00795091
-0.000624149
0.00795952
-0.000593505
-0.000563336
0.0080124
-0.000627736
0.0080165
-0.000597602
-0.000567891
0.00807135
-0.00062697
0.00807132
-0.000597579
-0.000568556
0.00812724
-0.000622329
0.00812353
-0.000593869
-0.000565721
0.00817974
-0.000614306
0.0081728
-0.000586921
-0.000559793
0.00822864
-0.000603386
0.0082189
-0.000577181
-0.00055118
0.00827385
-0.000590029
0.00826174
-0.000565073
-0.000540274
0.00831541
-0.00057466
0.00830133
-0.000550993
-0.00052744
0.00835343
-0.00055766
0.00833773
-0.000535298
-0.00051301
0.0083881
-0.000539364
0.0083711
-0.000518303
-0.000497279
0.00841963
-0.000520061
0.00840161
-0.00050028
-0.000480507
0.00844828
-0.000499993
0.00842946
-0.000481461
-0.000462912
0.00847428
-0.000479363
0.00845486
-0.000462042
-0.00044468
0.00849789
-0.000458336
0.00847803
-0.00044218
-0.000425966
0.00851933
-0.000437044
0.00849915
-0.000422007
-0.000406895
0.00853881
-0.000415593
0.00851843
-0.000401624
-0.000387569
0.00855653
-0.000394065
0.00853602
-0.000381115
-0.00036807
0.00857266
-0.000372521
0.00855209
-0.000360542
-0.000348461
0.00858735
-0.00035101
0.00856676
-0.000339954
-0.000328793
0.00860073
-0.000329564
0.00858016
-0.000319387
-0.000309103
0.0086129
-0.000308208
0.00859238
-0.000298868
-0.00028942
0.00862397
-0.000286958
0.00860352
-0.000278415
-0.000269765
0.00863402
-0.000265823
0.00861365
-0.000258041
-0.000250153
0.00864312
-0.000244808
0.00862283
-0.000237752
-0.000230593
0.00865133
-0.000223914
0.00863113
-0.000217552
-0.000211093
0.0086587
-0.000203137
0.00863859
-0.000197441
-0.000191655
0.00866527
-0.000182473
0.00864525
-0.000177418
-0.000172279
0.0086711
-0.000161914
0.00865116
-0.000157477
-0.000152964
0.0086762
-0.000141452
0.00865633
-0.000137613
0.00863707
-0.000133706
-0.000129746
0.0086806
0.00866081
-0.000117818
0.0086416
-0.0001145
-0.000111136
0.0086646
-9.80848e-05
0.00864544
-9.53417e-05
-9.25592e-05
0.00866774
-7.84037e-05
0.00864862
-7.62234e-05
-7.40111e-05
0.00867023
-5.8765e-05
0.00865114
-5.71381e-05
-5.54868e-05
0.00867209
-3.91585e-05
0.00865303
-3.80778e-05
-3.69808e-05
0.00867332
-1.95739e-05
0.00865428
-1.90345e-05
-1.84873e-05
0.00867393
0.0086549
-0.000558615
0.00769364
0.000528376
-0.000583221
0.00775804
-0.000602214
0.00782293
-0.000615761
0.0078875
-0.000624141
0.0079509
-0.000627729
0.00801239
-0.000626963
0.00807134
-0.000622322
0.00812724
-0.0006143
0.00817974
-0.00060338
0.00822863
-0.000590023
0.00827384
-0.000574654
0.0083154
-0.000557655
0.00835342
-0.000539359
0.00838809
-0.000520056
0.00841962
-0.000499989
0.00844827
-0.000479359
0.00847427
-0.000458332
0.00849788
-0.000437041
0.00851932
-0.00041559
0.0085388
-0.000394062
0.00855652
-0.000372519
0.00857265
-0.000351007
0.00858734
-0.000329562
0.00860072
-0.000308206
0.00861289
-0.000286956
0.00862396
-0.000265822
0.00863401
-0.000244807
0.00864311
-0.000223913
0.00865132
-0.000203136
0.00865869
-0.000182472
0.00866527
-0.000161913
0.00867109
-0.000141451
0.00867619
-0.000121076
0.00868059
-0.000100777
0.00868433
-8.05429e-05
0.00868741
-6.03609e-05
0.00868986
-4.02184e-05
0.00869168
-2.01024e-05
0.0086929
0.0086935
-0.000529068
0.00772268
0.000500024
-0.000552862
0.00778183
-0.00057142
0.00784149
-0.000584883
0.00790096
-0.000593497
0.00795951
-0.000597595
0.00801649
-0.000597572
0.00807131
-0.000593863
0.00812353
-0.000586915
0.00817279
-0.000577175
0.00821889
-0.000565068
0.00826173
-0.000550988
0.00830132
-0.000535293
0.00833773
-0.000518298
0.00837109
-0.000500275
0.0084016
-0.000481457
0.00842945
-0.000462038
0.00845485
-0.000442177
0.00847802
-0.000422003
0.00849914
-0.000401621
0.00851842
-0.000381112
0.00853601
-0.000360539
0.00855208
-0.000339952
0.00856675
-0.000319385
0.00858015
-0.000298866
0.00859237
-0.000278413
0.00860351
-0.000258039
0.00861364
-0.00023775
0.00862282
-0.00021755
0.00863112
-0.00019744
0.00863858
-0.000177417
0.00864524
-0.000157476
0.00865115
-0.000137612
0.00865632
-0.000117817
0.0086608
-9.80843e-05
0.00866459
-7.84032e-05
0.00866773
-5.87646e-05
0.00867022
-3.91583e-05
0.00867208
-1.95737e-05
0.00867331
0.00867393
-0.000500132
0.000472286
-0.000523097
-0.00054119
-0.000554528
-0.000563329
-0.000567884
-0.000568549
-0.000565714
-0.000559787
-0.000551174
-0.000540268
-0.000527434
-0.000513005
-0.000497275
-0.000480502
-0.000462907
-0.000444676
-0.000425962
-0.000406891
-0.000387566
-0.000368067
-0.000348459
-0.00032879
-0.0003091
-0.000289418
-0.000269763
-0.000250151
-0.000230592
-0.000211092
-0.000191654
-0.000172278
-0.000152963
-0.000133705
-0.0001145
-9.53411e-05
-7.62229e-05
-5.71377e-05
-3.80776e-05
-1.90346e-05
0.00238749
0.0005074
0.00240782
0.000479695
0.000452614
0.00241892
0.000486519
0.00243911
0.000459507
0.000433125
0.00244898
0.000465697
0.00246906
0.000439424
0.000413785
0.00247757
0.000444892
0.00249759
0.000419407
0.000394556
0.00250469
0.000424068
0.00252467
0.000399421
0.000375404
0.00253033
0.000403191
0.00255032
0.000379432
0.000356296
0.00255449
0.000382227
0.00257451
0.000359408
0.000337203
0.00255609
0.000383513
0.00257716
0.000361149
0.00259725
0.000339321
0.00257715
0.000361237
0.00259837
0.000339929
0.000319145
0.00259672
0.000338743
0.00261811
0.000318547
0.000298859
0.00261483
0.000316012
0.00263639
0.000296983
0.000278442
0.00263148
0.000293033
0.00265324
0.000275224
0.000257881
0.00264671
0.000269798
0.00266867
0.000253261
0.000237165
0.00266054
0.000246302
0.00268271
0.000231088
0.000216286
0.00267299
0.00022255
0.00269537
0.000208706
0.000195244
0.00268409
0.000198548
0.00270668
0.00018612
0.000174038
0.00269387
0.00017431
0.00271665
0.000163339
0.000152677
0.00270236
0.000149852
0.00272533
0.000140375
0.000131168
0.00270959
0.000125198
0.00273271
0.000117248
0.000109526
0.00271557
0.000100373
0.00273884
9.39777e-05
8.77678e-05
0.00272033
7.5406e-05
0.00274371
7.05893e-05
6.59126e-05
0.00272388
5.03307e-05
0.00274736
4.71097e-05
4.39827e-05
0.00270109
2.68382e-05
0.00272624
2.51818e-05
0.00274978
2.35683e-05
2.2002e-05
0.00270223
0.00272742
0.00275099
)
;
boundaryField
{
inlet
{
type calculated;
value nonuniform 0();
}
outlet
{
type calculated;
value nonuniform 0();
}
cylinder
{
type calculated;
value nonuniform 0();
}
top
{
type symmetryPlane;
value uniform 0;
}
bottom
{
type symmetryPlane;
value uniform 0;
}
defaultFaces
{
type empty;
value nonuniform 0();
}
procBoundary44to43
{
type processor;
value nonuniform List<scalar>
133
(
-0.00267539
-0.00267429
-5.36456e-05
-0.0026988
-0.00269536
-0.00269074
-0.00268493
-0.00267791
-0.00266964
-0.00266009
-0.00264924
-0.00263704
-0.00262348
-0.00260851
-0.0025921
-0.00257423
-0.00255487
-0.00253401
-0.0004056
-0.00253352
-0.00250945
-0.00248387
-0.00245677
-0.00242816
-0.00239804
-0.00236652
-0.0076634
-0.00773344
-0.00780394
-0.00787396
-0.00794253
-0.00800881
-0.00807211
-0.00813189
-0.00818777
-0.00823956
-0.00828721
-0.00833078
-0.00837043
-0.00840639
-0.00843894
-0.00846835
-0.00849491
-0.00851891
-0.00854062
-0.00856026
-0.00857806
-0.00859421
-0.00860886
-0.00862217
-0.00863426
-0.00864522
-0.00865516
-0.00866413
-0.00867222
-0.00867947
-0.00868594
-0.00869166
-0.00869666
-0.00870098
-0.000121077
-0.00868434
-0.00868742
-0.00868987
-0.00869169
-0.0086929
-0.00869351
-0.0076634
-0.00773344
-0.00780394
-0.00787395
-0.00794252
-0.00800881
-0.0080721
-0.00813188
-0.00818776
-0.00823955
-0.0082872
-0.00833077
-0.00837042
-0.00840638
-0.00843893
-0.00846834
-0.0084949
-0.0085189
-0.00854061
-0.00856025
-0.00857805
-0.0085942
-0.00860885
-0.00862216
-0.00863425
-0.00864521
-0.00865515
-0.00866412
-0.00867221
-0.00867947
-0.00868593
-0.00869165
-0.00869665
-0.00870097
-0.00870463
-0.00870765
-0.00871004
-0.00871183
-0.00871301
-0.0087136
-0.00236652
-0.00239804
-0.00242816
-0.00245677
-0.00248386
-0.00250945
-0.00253352
-0.000405592
-0.00253401
-0.00255487
-0.00257423
-0.0025921
-0.00260851
-0.00262348
-0.00263704
-0.00264923
-0.00266009
-0.00266963
-0.00267791
-0.00268493
-0.00269074
-0.00269536
-0.0026988
-5.3637e-05
-0.00267429
-0.00267539
)
;
}
procBoundary44to45
{
type processor;
value nonuniform List<scalar>
131
(
0.002773
0.00277176
0.00276929
0.00276557
0.0027606
0.00275436
0.00274684
0.00273802
0.00272788
0.00271641
0.00270359
0.00268939
0.0026738
0.00265681
0.00263839
0.00261854
0.000318103
0.00261636
0.0025936
0.00256942
0.00254383
0.00251682
0.0024884
0.0024586
0.00242749
0.00775053
0.00780481
0.00785959
0.0079143
0.00796832
0.00802105
0.00807199
0.0081207
0.00816687
0.00821029
0.00825084
0.00828849
0.0083233
0.00835537
0.00838484
0.00841187
0.00843663
0.00845931
0.00848008
0.0084991
0.00851652
0.00853248
0.00854709
0.00856047
0.0085727
0.00858386
0.00859403
0.00860327
0.00861163
0.00861915
0.00862587
0.00863184
0.000148392
0.00861843
0.00862299
0.00862687
0.00863007
0.00863262
0.00863452
0.00863578
0.00863641
0.00775053
0.0078048
0.00785958
0.0079143
0.00796831
0.00802105
0.00807198
0.00812069
0.00816686
0.00821028
0.00825083
0.00828848
0.0083233
0.00835536
0.00838483
0.00841186
0.00843662
0.0084593
0.00848007
0.00849909
0.00851652
0.00853247
0.00854709
0.00856046
0.00857269
0.00858385
0.00859403
0.00860326
0.00861162
0.00861914
0.00862587
0.00863183
0.00863707
0.00864159
0.00864544
0.00864861
0.00865114
0.00865302
0.00865427
0.00865489
0.00242749
0.0024586
0.0024884
0.00251682
0.00254383
0.00256942
0.0025936
0.00261636
0.000318094
0.00261854
0.00263839
0.00265681
0.0026738
0.00268939
0.00270359
0.00271641
0.00272788
0.00273802
0.00274684
0.00275436
0.0027606
0.00276557
0.00276929
0.00277176
0.002773
)
;
}
}
// ************************************************************************* //
|
|
ae394e2d81b192a1692c2b8bd1d19425fe46130b
|
df7073074ff14a6854aac6ad64f996dee9237811
|
/gzw_valueid.cpp
|
7907caa72e6c55d2b6e87766690a8b7ae01e423f
|
[
"MIT"
] |
permissive
|
aldrinleal/goopenzwave
|
8931840f7b69aaaeb53b05a9c897b9ae829f9c2c
|
04a0f3ef63288b302bd725c5382071e9f1b005c4
|
refs/heads/master
| 2020-05-31T06:14:30.622087
| 2019-06-04T06:10:18
| 2019-06-04T06:10:18
| 190,137,895
| 0
| 0
|
MIT
| 2019-06-04T05:52:26
| 2019-06-04T05:52:26
| null |
UTF-8
|
C++
| false
| false
| 3,409
|
cpp
|
gzw_valueid.cpp
|
#include "gzw_valueid.h"
#include <value_classes/ValueID.h>
//
// Public member functions.
//
uint32_t valueid_getHomeId(valueid_t v)
{
OpenZWave::ValueID *valid = (OpenZWave::ValueID*)v;
return valid->GetHomeId();
}
uint8_t valueid_getNodeId(valueid_t v)
{
OpenZWave::ValueID *valid = (OpenZWave::ValueID*)v;
return valid->GetNodeId();
}
valueid_genre valueid_getGenre(valueid_t v)
{
OpenZWave::ValueID *valid = (OpenZWave::ValueID*)v;
valueid_genre val_genre;
switch (valid->GetGenre()) {
case OpenZWave::ValueID::ValueGenre_Basic:
val_genre = valueid_genre_basic;
break;
case OpenZWave::ValueID::ValueGenre_User:
val_genre = valueid_genre_user;
break;
case OpenZWave::ValueID::ValueGenre_Config:
val_genre = valueid_genre_config;
break;
case OpenZWave::ValueID::ValueGenre_System:
val_genre = valueid_genre_system;
break;
case OpenZWave::ValueID::ValueGenre_Count:
val_genre = valueid_genre_count;
break;
}
return val_genre;
}
uint8_t valueid_getCommandClassId(valueid_t v)
{
OpenZWave::ValueID *valid = (OpenZWave::ValueID*)v;
return valid->GetCommandClassId();
}
uint8_t valueid_getInstance(valueid_t v)
{
OpenZWave::ValueID *valid = (OpenZWave::ValueID*)v;
return valid->GetInstance();
}
uint8_t valueid_getIndex(valueid_t v)
{
OpenZWave::ValueID *valid = (OpenZWave::ValueID*)v;
return valid->GetIndex();
}
valueid_type valueid_getType(valueid_t v)
{
OpenZWave::ValueID *valid = (OpenZWave::ValueID*)v;
valueid_type val_type;
switch (valid->GetType()) {
case OpenZWave::ValueID::ValueType_Bool:
val_type = valueid_type_bool;
break;
case OpenZWave::ValueID::ValueType_Byte:
val_type = valueid_type_byte;
break;
case OpenZWave::ValueID::ValueType_Decimal:
val_type = valueid_type_decimal;
break;
case OpenZWave::ValueID::ValueType_Int:
val_type = valueid_type_int;
break;
case OpenZWave::ValueID::ValueType_List:
val_type = valueid_type_list;
break;
case OpenZWave::ValueID::ValueType_Schedule:
val_type = valueid_type_schedule;
break;
case OpenZWave::ValueID::ValueType_Short:
val_type = valueid_type_short;
break;
case OpenZWave::ValueID::ValueType_String:
val_type = valueid_type_string;
break;
case OpenZWave::ValueID::ValueType_Button:
val_type = valueid_type_button;
break;
case OpenZWave::ValueID::ValueType_Raw:
val_type = valueid_type_raw;
break;
// case OpenZWave::ValueID::ValueType_Max:
// val_type = valueid_type_max;
// break;
}
return val_type;
}
uint64_t valueid_getId(valueid_t v)
{
OpenZWave::ValueID *valid = (OpenZWave::ValueID*)v;
return valid->GetId();
}
//
// Go helper functions.
//
valueid_t valueid_create(uint32_t homeId, uint64_t id)
{
OpenZWave::ValueID *valueid = new OpenZWave::ValueID(homeId, (uint64)id);
return (valueid_t)valueid;
}
void valueid_free(valueid_t valueid)
{
OpenZWave::ValueID *val = (OpenZWave::ValueID*)valueid;
delete val;
}
|
8347bfdcffe0bfca623d4392b992c1189845c588
|
9de18ef120a8ae68483b866c1d4c7b9c2fbef46e
|
/src/SessionSetup/ProcessItemModel.cpp
|
b0a4294396952666e2c8d1444273f865dfe56a99
|
[
"BSD-2-Clause",
"LicenseRef-scancode-free-unknown"
] |
permissive
|
google/orbit
|
02a5b4556cd2f979f377b87c24dd2b0a90dff1e2
|
68c4ae85a6fe7b91047d020259234f7e4961361c
|
refs/heads/main
| 2023-09-03T13:14:49.830576
| 2023-08-25T06:28:36
| 2023-08-25T06:28:36
| 104,358,587
| 2,680
| 325
|
BSD-2-Clause
| 2023-08-25T06:28:37
| 2017-09-21T14:28:35
|
C++
|
UTF-8
|
C++
| false
| false
| 5,320
|
cpp
|
ProcessItemModel.cpp
|
// Copyright (c) 2020 The Orbit 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 "SessionSetup/ProcessItemModel.h"
#include <QFlags>
#include <algorithm>
#include <functional>
#include <iterator>
#include "GrpcProtos/process.pb.h"
#include "OrbitBase/Logging.h"
#include "OrbitBase/Sort.h"
#include "google/protobuf/util/message_differencer.h"
namespace orbit_session_setup {
using orbit_grpc_protos::ProcessInfo;
int ProcessItemModel::columnCount(const QModelIndex& parent) const {
return parent.isValid() ? 0 : static_cast<int>(Column::kEnd);
}
QVariant ProcessItemModel::data(const QModelIndex& idx, int role) const {
ORBIT_CHECK(idx.isValid());
ORBIT_CHECK(idx.model() == static_cast<const QAbstractItemModel*>(this));
ORBIT_CHECK(idx.row() >= 0 && idx.row() < static_cast<int>(processes_.size()));
ORBIT_CHECK(idx.column() >= 0 && idx.column() < static_cast<int>(Column::kEnd));
const auto& process = processes_[idx.row()];
if (role == Qt::UserRole) {
return QVariant::fromValue(&process);
}
if (role == Qt::DisplayRole) {
switch (static_cast<Column>(idx.column())) {
case Column::kPid:
return process.pid();
case Column::kName:
return QString::fromStdString(process.name());
case Column::kCpu:
return QString("%1 %").arg(process.cpu_usage(), 0, 'f', 1);
case Column::kEnd:
ORBIT_UNREACHABLE();
}
}
// When the EditRole is requested, we return the unformatted raw value, which
// means the CPU Usage is returned as a double.
if (role == Qt::EditRole) {
switch (static_cast<Column>(idx.column())) {
case Column::kPid:
return process.pid();
case Column::kName:
return QString::fromStdString(process.name());
case Column::kCpu:
return process.cpu_usage();
case Column::kEnd:
ORBIT_UNREACHABLE();
}
}
if (role == Qt::ToolTipRole) {
// We don't care about the column when showing tooltip. It's the same for
// the whole row.
return QString::fromStdString(process.command_line());
}
if (role == Qt::TextAlignmentRole) {
switch (static_cast<Column>(idx.column())) {
case Column::kPid:
return QVariant::fromValue(Qt::AlignVCenter | Qt::AlignRight);
case Column::kName:
return {};
case Column::kCpu:
return QVariant::fromValue(Qt::AlignVCenter | Qt::AlignRight);
case Column::kEnd:
ORBIT_UNREACHABLE();
}
}
return {};
}
QVariant ProcessItemModel::headerData(int section, Qt::Orientation orientation, int role) const {
if (orientation == Qt::Vertical) {
return {};
}
if (role == Qt::DisplayRole) {
switch (static_cast<Column>(section)) {
case Column::kPid:
return "PID";
case Column::kName:
return "Name";
case Column::kCpu:
return "CPU %";
case Column::kEnd:
ORBIT_UNREACHABLE();
}
}
return {};
}
QModelIndex ProcessItemModel::index(int row, int column, const QModelIndex& parent) const {
if (parent.isValid()) return {};
if (row < 0 || row >= static_cast<int>(processes_.size())) return {};
if (column < 0 || column >= static_cast<int>(Column::kEnd)) return {};
return createIndex(row, column);
}
QModelIndex ProcessItemModel::parent(const QModelIndex& /*parent*/) const { return {}; }
int ProcessItemModel::rowCount(const QModelIndex& parent) const {
if (parent.isValid()) {
return 0;
}
return processes_.size();
}
void ProcessItemModel::SetProcesses(QVector<ProcessInfo> new_processes) {
orbit_base::sort(new_processes.begin(), new_processes.end(), &ProcessInfo::pid);
auto* old_iter = processes_.begin();
auto* new_iter = new_processes.begin();
while (old_iter != processes_.end() && new_iter != new_processes.end()) {
const int current_row = static_cast<int>(std::distance(processes_.begin(), old_iter));
if (old_iter->pid() == new_iter->pid()) {
if (!google::protobuf::util::MessageDifferencer::Equivalent(*old_iter, *new_iter)) {
*old_iter = *new_iter;
emit dataChanged(index(current_row, 0, {}),
index(current_row, static_cast<int>(Column::kEnd) - 1, {}));
}
++old_iter;
++new_iter;
} else if (old_iter->pid() < new_iter->pid()) {
beginRemoveRows({}, current_row, current_row);
old_iter = processes_.erase(old_iter);
endRemoveRows();
} else {
beginInsertRows({}, current_row, current_row);
old_iter = processes_.insert(old_iter, *new_iter);
++old_iter;
++new_iter;
endInsertRows();
}
}
if (old_iter == processes_.end() && new_iter != new_processes.end()) {
beginInsertRows({}, processes_.size(), new_processes.size() - 1);
std::copy(new_iter, new_processes.end(), std::back_inserter(processes_));
ORBIT_CHECK(processes_.size() == new_processes.size());
endInsertRows();
} else if (old_iter != processes_.end() && new_iter == new_processes.end()) {
beginRemoveRows({}, new_processes.size(), processes_.size() - 1);
processes_.erase(old_iter, processes_.end());
ORBIT_CHECK(processes_.size() == new_processes.size());
endRemoveRows();
}
}
} // namespace orbit_session_setup
|
b4729672ffd70e5393ba9764b1d1535bc186adc3
|
527cf55f84cfac6585130f20b0b50e887112322e
|
/inc/ktl/wdx.h
|
7e97fac087c713a82277fdee9b9dac477d07956f
|
[
"MIT"
] |
permissive
|
cnsuhao/ktl
|
282ff3573f5e63096ccbb3536c35dfe34f1a0b08
|
d0f9e354cf6ebcfb7568596aaee224d4bd9c9a2b
|
refs/heads/master
| 2021-05-31T08:09:06.031181
| 2016-07-12T09:10:56
| 2016-07-12T09:10:56
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,807
|
h
|
wdx.h
|
#pragma once
#include <wdf.h>
#include <utility>
#include <memory>
#include <cstdint>
#include <new>
#include "code_annotation.h"
namespace ktl
{
// WDF does not call our object's constructor for us, so we need to call it.
template<typename T>
class wdx_object_context
{
alignas(T) std::uint8_t buffer[sizeof(T)] = {};
T * val()
{
return static_cast<T*>(static_cast<void*>(buffer));
}
T const * val() const
{
return static_cast<T const*>(static_cast<void const*>(buffer));
}
public:
wdx_object_context() { }
// This object cannot be moved or copied because it doesn't know if its
// contents have been initialized, so is unable to determine if the
// destination buffer, or the local buffer, is initialized or not.
// However it IS assumed that by the time the destructor is called, init() has been called
wdx_object_context(wdx_object_context const & rhs) = delete;
wdx_object_context(wdx_object_context && rhs) = delete;
wdx_object_context& operator=(wdx_object_context const & rhs) = delete;
wdx_object_context& operator=(wdx_object_context && rhs) = delete;
~wdx_object_context()
{
std::destroy_at(val());
}
// This should be called exactly once after the context has been allocated
template<typename... Args>
void init(Args&&... args)
{
new (buffer) T(std::forward<Args>(args)...);
}
T * operator->()
{
return val();
}
T const * operator->() const
{
return val();
}
T & operator*()
{
return *val();
}
T const & operator*() const
{
return *val();
}
};
}
#define WDX_INIT_CONTEXT(_object, _contexttype, ...) \
(WdfObjectGetTypedContext(_object, WDX_ ## _contexttype))->init(__VA_ARGS__)
#define WDX_DECLARE_CASTING_FUNCTION(_contextType, _cType, _castingFunction) \
__forceinline _contextType & _castingFunction(_In_ WDFOBJECT handle) \
{ \
return **(WdfObjectGetTypedContext(handle, _cType));\
}
#define WDX_DECLARE_CONTEXT_TYPE(_contextType) \
WDX_DECLARE_CONTEXT_TYPE_WITH_NAME(_contextType, WdxObjectGet_ ## _contextType)
#define WDX_DECLARE_CONTEXT_TYPE_WITH_NAME(_contextType, _castingFunction) \
using WDX_ ## _contextType = ktl::wdx_object_context<_contextType>; \
WDF_DECLARE_CONTEXT_TYPE(WDX_ ## _contextType); \
WDX_DECLARE_CASTING_FUNCTION(_contextType, WDX_ ## _contextType, _castingFunction)
#define WDX_OBJECT_ATTRIBUTES_SET_CONTEXT_TYPE(_attributes, _contexttype) \
WDF_OBJECT_ATTRIBUTES_SET_CONTEXT_TYPE(_attributes, WDX_ ## _contexttype); \
(_attributes)->EvtDestroyCallback = [](_In_ WDFOBJECT handle) NONPAGED { \
std::destroy_at(WdfObjectGetTypedContext(handle, WDX_ ## _contexttype)); \
}
#define WDX_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(_attributes, _contextType) \
WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(_attributes, WDX_ ## _contextType)
|
c8c107d6b2bdaea4f7a3818c496a9df6452c527a
|
87d8af054e17e0c346b6f59636402883fbf0158d
|
/Cpp/SDK/SirensAnimation_classes.h
|
7b1d9660235db8b3ff9fb67883e2d54c88420ca1
|
[] |
no_license
|
AthenaVision/SoT-SDK-2
|
53676d349bca171b5e48dc812fd7bb97b9a4f1d8
|
4a803206d707a081b86c89a4b866a1761119613d
|
refs/heads/main
| 2023-03-20T10:48:21.491008
| 2021-03-10T21:55:10
| 2021-03-10T21:55:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,293
|
h
|
SirensAnimation_classes.h
|
#pragma once
// Name: sot, Version: 4.2
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// Class SirensAnimation.SirenAnimationData
// 0x0040 (FullSize[0x0068] - InheritedSize[0x0028])
class USirenAnimationData : public UAnimationData
{
public:
struct FSirenAnimationDataStructure SirenAnimationData; // 0x0028(0x0040) (Edit, DisableEditOnInstance)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class SirensAnimation.SirenAnimationData");
return ptr;
}
};
// Class SirensAnimation.SirenAnimationInstance
// 0x0220 (FullSize[0x0660] - InheritedSize[0x0440])
class USirenAnimationInstance : public UAnimInstance
{
public:
unsigned char UnknownData_1Z0R[0x8]; // 0x0440(0x0008) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY)
struct FSirenAnimationDataStructure SirenAnimationData; // 0x0448(0x0040) (BlueprintVisible, BlueprintReadOnly)
struct FAthenaAnimationWeapon AttackAnimations; // 0x0488(0x00B8) (BlueprintVisible, BlueprintReadOnly)
float ForwardSpeed; // 0x0540(0x0004) (BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
float TiltDirectionAngleDegrees; // 0x0544(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
float TiltAngleAlpha; // 0x0548(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
float SpinAngleDegrees; // 0x054C(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
float MaxTiltAngleRepresentedByAdditiveBendAnimations; // 0x0550(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
bool UpperBodyOverlayActive; // 0x0554(0x0001) (BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor)
bool SwimmingLongways; // 0x0555(0x0001) (BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor)
unsigned char UnknownData_FUC4[0x6]; // 0x0556(0x0006) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY)
bool AnimationsLoaded; // 0x055C(0x0001) (BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor)
unsigned char UnknownData_FAUD[0x3]; // 0x055D(0x0003) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY)
struct FCustomAnimationMontageStateMachine FullBodyStateMachine; // 0x0560(0x00D8)
unsigned char UnknownData_R1OF[0x28]; // 0x0638(0x0028) MISSED OFFSET (PADDING)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class SirensAnimation.SirenAnimationInstance");
return ptr;
}
void ClearActiveAttack();
void BeginNewAttack();
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
caee339f1b38d05053c9a74188b5706fa0a13368
|
0d43fe5c5d119a733c47e3fc3a6c294e93ac7c3a
|
/Client.h
|
106b9e39a614ebcc5d9d6ef7ca11d19a2a4a6edb
|
[] |
no_license
|
DeltaHarbinger/OOPProject
|
fb409f04ff158146a92da7016fc5e229c482b1d1
|
77b3f97fff96230ace40d24abc5a3ecbefa54c60
|
refs/heads/master
| 2021-05-07T21:51:32.801943
| 2017-11-18T04:17:16
| 2017-11-18T04:17:16
| 109,067,986
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,118
|
h
|
Client.h
|
//Created by Philip newman and Brandon Chung
#ifndef CLIENT_H
#define CLIENT_H
#include <string>
class Client
{
public:
Client()
{
this -> fName = "";
this -> lName = "";
this -> telephoneNo = "";
this -> address = "";
this -> email = "";
}
Client(std::string fName, std::string lName, std::string telephoneNo, std::string address, std::string email)
{
incrementCounter();
this -> id = numberOfClients;
this -> fName = fName;
this -> lName = lName;
this -> telephoneNo = telephoneNo;
this -> address = address;
this -> email = email;
}
~Client()
{
}
//Getters
int getId(){
return id;
}
std::string getFName(){
return fName;
}
std::string getLName(){
return lName;
}
std::string getTelephoneNo(){
return telephoneNo;
}
std::string getAddress(){
return address;
}
std::string getEmail(){
return email;
}
void setId(int id){
this -> id = id;
}
void setFName(std::string fName){
this -> fName = fName;
}
void setLName(std::string){
this -> lName = lName;
}
void setTelephoneNo(std::string telephoneNo){
this -> telephoneNo = telephoneNo;
}
void setAddress(std::string addess){
this -> address = address;
}
void setEmail(std::string email){
this -> email = email;
}
void incrementCounter(){
numberOfClients = numberOfClients + 1;
}
void display(){
std::cout << "Name:\t" << fName << " " << lName << std::endl << "Telephone #:\t" << telephoneNo << std::endl << "Address:\t" << address << std::endl << "Email:\t" << email << std::endl;
}
void writeToFile(){
std::ofstream clientWriter;
try{
clientWriter.open("newClients.txt", std::ios::app);
clientWriter << id << '\t' << fName << '\t' << lName << '\t' << telephoneNo << '\t' << address << '\t' << email << '\n';
} catch(std::exception& e){
system("cls");
std::cout << "Failure while storing clients" << std::endl;
system("pause");
}
}
private:
int id;
std::string fName;
std::string lName;
std::string telephoneNo;
std::string address;
std::string email;
static int numberOfClients;
};
int Client::numberOfClients = 0;
#endif
|
7b49133fabb87be2de052a97cca64a2ed74693b8
|
c89e5dbdd73a6a0e1b9f299856d4ae3e8a463e83
|
/include/Lz/detail/TakeEveryIterator.hpp
|
29722715e3e64662992ad89c431bb3887cf2dc24
|
[
"MIT"
] |
permissive
|
ExternalRepositories/cpp-lazy
|
208319bb21020eeb35d564e76988ec98168d390b
|
df9295a5a2a7f4c3ef4657f73d5e84b576fc82c3
|
refs/heads/master
| 2023-07-13T16:22:05.047584
| 2021-08-16T16:44:26
| 2021-08-16T16:44:26
| 375,169,594
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,499
|
hpp
|
TakeEveryIterator.hpp
|
#pragma once
#ifndef LZ_TAKE_EVERY_ITERATOR_HPP
# define LZ_TAKE_EVERY_ITERATOR_HPP
# include "LzTools.hpp"
namespace lz {
namespace internal {
template<class Iterator>
class TakeEveryIterator {
using IterTraits = std::iterator_traits<Iterator>;
public:
using value_type = typename IterTraits::value_type;
using iterator_category = typename std::common_type<std::forward_iterator_tag, typename IterTraits::iterator_category>::type;
using difference_type = typename IterTraits::difference_type;
using reference = typename IterTraits::reference;
using pointer = FakePointerProxy<reference>;
Iterator _iterator{};
Iterator _end{};
difference_type _offset{};
difference_type _currentDistance{};
void next() {
if (_offset >= _currentDistance) {
_iterator = _end;
_currentDistance = 0;
}
else {
_iterator = std::next(std::move(_iterator), _offset);
_currentDistance -= _offset;
}
}
public:
LZ_CONSTEXPR_CXX_20
TakeEveryIterator(Iterator iterator, Iterator end, const difference_type offset, const difference_type distance) :
_iterator(std::move(iterator)),
_end(std::move(end)),
_offset(offset),
_currentDistance(distance) {
}
constexpr TakeEveryIterator() = default;
LZ_NODISCARD LZ_CONSTEXPR_CXX_20 reference operator*() const {
return *_iterator;
}
LZ_NODISCARD LZ_CONSTEXPR_CXX_20 pointer operator->() const {
return FakePointerProxy<decltype(**this)>(**this);
}
LZ_CONSTEXPR_CXX_20 TakeEveryIterator& operator++() {
this->next();
return *this;
}
LZ_CONSTEXPR_CXX_20 TakeEveryIterator operator++(int) {
TakeEveryIterator tmp(*this);
++*this;
return tmp;
}
LZ_NODISCARD LZ_CONSTEXPR_CXX_20 friend bool operator==(const TakeEveryIterator& a, const TakeEveryIterator& b) {
return !(a != b); // NOLINT
}
LZ_NODISCARD LZ_CONSTEXPR_CXX_20 friend bool operator!=(const TakeEveryIterator& a, const TakeEveryIterator& b) {
LZ_ASSERT(a._offset == b._offset, "incompatible iterator types: different offsets");
return a._iterator != b._iterator;
}
LZ_NODISCARD LZ_CONSTEXPR_CXX_20 friend difference_type operator-(const TakeEveryIterator& a, const TakeEveryIterator& b) {
LZ_ASSERT(a._offset == b._offset, "incompatible iterator types: different offsets");
const auto dist = getIterLength(b._iterator, a._iterator);
if (isEven(dist) && isEven(a._offset)) {
return static_cast<difference_type>(dist / a._offset);
}
return static_cast<difference_type>(dist / a._offset) + 1;
}
LZ_NODISCARD LZ_CONSTEXPR_CXX_20 TakeEveryIterator operator+(const difference_type offset) const {
using lz::next;
using std::next;
const auto dist = getIterLength(_iterator, _end);
const auto diffOffset = _offset * offset;
if (diffOffset >= dist) {
return { _end, _end, _offset, dist };
}
return { next(_iterator, diffOffset), _end, _offset, dist };
}
};
} // namespace internal
/**
* Gets the distance between begin and end. If the underlying iterator type is random access, distance is O(1).
* @param begin Beginning of the sequence.
* @param end Ending of the sequence.
* @return The distance between begin and end.
*/
template<LZ_CONCEPT_ITERATOR Iterator>
LZ_NODISCARD LZ_CONSTEXPR_CXX_20 typename internal::TakeEveryIterator<Iterator>::difference_type
distance(const internal::TakeEveryIterator<Iterator>& begin, const internal::TakeEveryIterator<Iterator>& end) {
return end - begin;
}
/**
* Gets the nth value from iter. If the underlying iterator type is random access, next is O(1).
* @param iter A take every iterator instance.
* @param value The amount to add.
* @return A take every iterator with offset iter + value.
*/
template<LZ_CONCEPT_ITERATOR Iterator>
LZ_NODISCARD LZ_CONSTEXPR_CXX_20 internal::TakeEveryIterator<Iterator>
next(const internal::TakeEveryIterator<Iterator>& t, const internal::DiffType<internal::TakeEveryIterator<Iterator>> value) {
LZ_ASSERT(value >= 0, "offset must be greater than 0 since this is not a bidirectional/random access iterator");
return t + value;
}
} // namespace lz
#endif
|
f9781709b0be11b8d50e2e7597fc6d235acdc063
|
e9fffeaa872969f9dc384fb44c245df34aae946c
|
/StarEngine/Glow.h
|
ff086038ba1b9e708e53190043b1a5d699d0a09f
|
[] |
no_license
|
StarfighterDevTeam/StarFighter
|
ab4252ef886fadc3fa811de01da93737a59b5386
|
4c6b5c8f3b3f73104094cfb7c66b45b8d3864388
|
refs/heads/master
| 2022-10-28T09:08:57.837077
| 2016-10-04T16:18:00
| 2016-10-04T16:18:00
| 15,851,654
| 2
| 0
| null | 2015-08-16T08:52:00
| 2014-01-12T21:50:44
|
HTML
|
UTF-8
|
C++
| false
| false
| 740
|
h
|
Glow.h
|
#ifndef GLOW_H_INCLUDED
#define GLOW_H_INCLUDED
#include "Globals.h"
#include "SEGame.h"
#include "GameObject.h"
class Glow : public GameObject
{
public :
Glow(GameObject* parent, sf::Color color);
Glow(GameObject* parent, sf::Color color, int glow_thickness, int stroke_size = 0);
Glow(GameObject* parent, sf::Color color, int glow_thickness, int stroke_size, float glow_animation_duration, int glow_min_thickness);
static sf::Uint8* CreateGlowFrame(GameObject* parent, sf::Color color, int glow_thickness, int stroke_size = 0);
virtual ~Glow();
void update(sf::Time deltaTime) override;
sf::Color m_color;
Uint8 m_glow_radius;
sf::Clock m_glow_variation_clock;
float m_glow_animation_duration;
};
#endif // GLOW_H_INCLUDED
|
978c1b467557ddcb8cf3a61fc592df65d057c72d
|
45aeb07ddc93ee8d1c3a2f3c65329ff98ba1d6eb
|
/libhttpserver/HTTPParser.cpp
|
443c4633e392d6de83b9fb44be78d70e897b1fea
|
[
"MIT"
] |
permissive
|
harsath/Asynchronous-HTTP-Framework-CPP
|
ef782d57c3eae81052227f477201bb5e1eba9c8a
|
140fb59997e9049bb4ca89806df527556ed890a0
|
refs/heads/master
| 2023-03-10T08:18:38.213469
| 2021-02-25T06:06:22
| 2021-02-25T06:06:22
| 276,506,846
| 0
| 0
|
MIT
| 2021-02-21T15:26:18
| 2020-07-01T23:58:06
|
C++
|
UTF-8
|
C++
| false
| false
| 18,287
|
cpp
|
HTTPParser.cpp
|
#include "HTTPParser.hpp"
#include "HTTPMessage.hpp"
#include "HTTPHelpers.hpp"
#include "io/IOBuffer.hpp"
#include <cctype>
#include <memory>
#include <optional>
#include <string>
namespace {
#define str3cmp_macro(ptr, c0, c1, c2) *(ptr+0) == c0 && *(ptr+1) == c1 && *(ptr+2) == c2
static inline bool str3cmp(const char* ptr, const char* cmp){
return str3cmp_macro(ptr, *(cmp+0), *(cmp+1), *(cmp+2));
}
#define str4cmp_macro(ptr, c0, c1, c2, c3) *(ptr+0) == c0 && *(ptr+1) == c1 && *(ptr+2) == c2 && *(ptr+3) == c3
static inline bool str4cmp(const char* ptr, const char* cmp){
return str4cmp_macro(ptr, *(cmp+0), *(cmp+1), *(cmp+2), *(cmp+3));
}
}
#define DEBUG false
#if DEBUG
#define Debug(...) __VA_ARGS__
#else
#define Debug(...)
#endif
namespace Parser = HTTP::HTTP1Parser;
/* HTTP-Message (generic-message) = start-line
* *(HTTP Message Headers CRLF)
* CRLF
* [ HTTP Message Body ]
*
* start-line = Request-Line | Status-Line
*
* Request-Line = Method SP Request-URI SP HTTP-Version CFLF
*
* Method(supported as of now) = "GET" | "POST"
*
* Request-URI(abs path for now) = absolute path
*
* Abs-Path = "/"*CHAR
*
* HTTP-Version = "HTTP" "/" "DIGIT"."DIGIT"
*
* Message-header = field-name BWS ":" [ field-value ]
*
* field-name = token
*
* field-value = *( field-content | LWS )
*
* message-body = entity-body
*/
std::pair<HTTP::HTTP1Parser::ParserState, std::unique_ptr<HTTP::HTTPMessage>>
HTTP::HTTP1Parser::HTTP11Parser(
const std::unique_ptr<blueth::io::IOBuffer<char>>& io_buffer,
ParserState& current_state,
std::unique_ptr<HTTP::HTTPMessage> http_message
){
using namespace Parser;
std::string tmp_header_name;
std::string tmp_header_value;
std::string tmp_request_type;
const char* start_input = io_buffer->getStartOffsetPointer();
const char* end_input = io_buffer->getEndOffsetPointer();
bool is_protocol_fail{false};
auto increment_byte = [&start_input](void) -> void { start_input++; };
while(start_input != end_input && (!is_protocol_fail)){
switch(current_state){
case ParserState::REQUEST_LINE_BEGIN:
{
if(is_token(*start_input)){
// Let's begin parsing Request-Method
current_state = ParserState::REQUEST_METHOD;
tmp_request_type.push_back(*start_input);
//http_message->GetRequestType().push_back(*start_input);
Debug(std::cout << *start_input << std::endl;)
Debug(std::cout << state_as_string(ParserState::REQUEST_LINE_BEGIN) << std::endl;)
increment_byte();
}else{
current_state = ParserState::PROTOCOL_ERROR;
Debug(std::cout << state_as_string(ParserState::PROTOCOL_ERROR) << std::endl;)
}
break;
}
case ParserState::REQUEST_METHOD:
{
if(*start_input == static_cast<char>(LexConst::SP)){
if(str3cmp("GET", tmp_request_type.c_str()))
{ http_message->SetRequestType(HTTPConst::HTTP_REQUEST_TYPE::GET); }
else if(str4cmp("HEAD", tmp_request_type.c_str()))
{ http_message->SetRequestType(HTTPConst::HTTP_REQUEST_TYPE::HEAD); }
else if(str4cmp("POST", tmp_request_type.c_str()))
{ http_message->SetRequestType(HTTPConst::HTTP_REQUEST_TYPE::POST); }
else
{ http_message->SetRequestType(HTTPConst::HTTP_REQUEST_TYPE::UNSUPPORTED); }
// We parsed Request-Method, Let's begin parsing Request-URI
current_state = ParserState::REQUEST_RESOURCE_BEGIN;
Debug(std::cout << *start_input << std::endl;)
Debug(std::cout << state_as_string(ParserState::REQUEST_METHOD) << " - SP" << std::endl;)
increment_byte();
}else if(is_token(*start_input)){
// No state transition
tmp_request_type.push_back(*start_input);
//http_message->GetRequestType().push_back(*start_input);
Debug(std::cout << *start_input << std::endl;)
Debug(std::cout << state_as_string(ParserState::REQUEST_METHOD) << std::endl;)
increment_byte();
}else{
Debug(std::cout << state_as_string(ParserState::PROTOCOL_ERROR) << std::endl;)
current_state = ParserState::PROTOCOL_ERROR;
}
break;
}
case ParserState::REQUEST_RESOURCE_BEGIN:
{
if(std::isprint(*start_input)){
current_state = ParserState::REQUEST_RESOURCE;
Debug(std::cout << *start_input << std::endl;)
Debug(std::cout << state_as_string(ParserState::REQUEST_RESOURCE_BEGIN) << std::endl;)
}else{
Debug(std::cout << state_as_string(ParserState::PROTOCOL_ERROR) << std::endl;)
current_state = ParserState::PROTOCOL_ERROR;
}
break;
}
case ParserState::REQUEST_RESOURCE:
{
if(*start_input == static_cast<char>(LexConst::SP)){
// WE parsed Request-URI, Let's begin parsing Protocol-Version
current_state = ParserState::REQUEST_PROTOCOL_BEGIN;
Debug(std::cout << *start_input << std::endl;)
Debug(std::cout << state_as_string(ParserState::REQUEST_RESOURCE) << " SP " << std::endl;)
increment_byte();
}else if(std::isprint(*start_input)){
http_message->GetTargetResource().push_back(*start_input);
Debug(std::cout << *start_input << std::endl;)
Debug(std::cout << state_as_string(ParserState::REQUEST_RESOURCE) << std::endl;)
increment_byte();
}else{
Debug(std::cout << state_as_string(ParserState::PROTOCOL_ERROR) << std::endl;)
current_state = ParserState::PROTOCOL_ERROR;
}
break;
}
case ParserState::REQUEST_PROTOCOL_BEGIN:
{
if(*start_input == 'H'){
http_message->GetHTTPVersion().push_back(*start_input);
current_state = ParserState::REQUEST_PROTOCOL_T1;
Debug(std::cout << "H" << std::endl;)
Debug(std::cout << *start_input << state_as_string(ParserState::REQUEST_PROTOCOL_BEGIN) << std::endl;)
increment_byte();
}else{
Debug(std::cout << state_as_string(ParserState::REQUEST_PROTOCOL_BEGIN) << " != H state" << std::endl;)
current_state = ParserState::PROTOCOL_ERROR;
}
break;
}
case ParserState::REQUEST_PROTOCOL_T1:
{
if(*start_input == 'T'){
http_message->GetHTTPVersion().push_back(*start_input);
current_state = ParserState::REQUEST_PROTOCOL_T2;
Debug(std::cout << "T" << std::endl;)
Debug(std::cout << state_as_string(ParserState::REQUEST_PROTOCOL_T1);)
increment_byte();
}else{
current_state = ParserState::PROTOCOL_ERROR;
Debug(std::cout << state_as_string(ParserState::PROTOCOL_ERROR) << std::endl;)
}
break;
}
case ParserState::REQUEST_PROTOCOL_T2:
{
if(*start_input == 'T'){
http_message->GetHTTPVersion().push_back(*start_input);
current_state = ParserState::REQUEST_PROTOCOL_P;
Debug(std::cout << "T" << std::endl;)
Debug(std::cout << state_as_string(ParserState::REQUEST_PROTOCOL_T2) << std::endl;)
increment_byte();
}else{
current_state = ParserState::PROTOCOL_ERROR;
Debug(std::cout << state_as_string(ParserState::PROTOCOL_ERROR) << std::endl;)
}
break;
}
case ParserState::REQUEST_PROTOCOL_P:
{
if(*start_input == 'P'){
http_message->GetHTTPVersion().push_back(*start_input);
current_state = ParserState::REQUEST_PROTOCOL_SLASH;
Debug(std::cout << "P" << std::endl;)
Debug(std::cout << state_as_string(ParserState::REQUEST_PROTOCOL_P) << std::endl;)
increment_byte();
}else{
current_state = ParserState::PROTOCOL_ERROR;
Debug(std::cout << state_as_string(ParserState::PROTOCOL_ERROR) << std::endl;)
}
break;
}
case ParserState::REQUEST_PROTOCOL_SLASH:
{
if(*start_input == '/'){
http_message->GetHTTPVersion().push_back(*start_input);
Debug(std::cout << *start_input << std::endl;)
Debug(std::cout << state_as_string(ParserState::REQUEST_PROTOCOL_SLASH);)
increment_byte();
current_state = ParserState::REQUEST_PROTOCOL_VERSION_MAJOR;
}else{
Debug(std::cout << *start_input << std::endl;)
Debug(std::cout << state_as_string(ParserState::PROTOCOL_ERROR);)
current_state = ParserState::PROTOCOL_ERROR;
}
break;
}
case ParserState::REQUEST_PROTOCOL_VERSION_MAJOR:
{
if(std::isdigit(*start_input)){
http_message->GetHTTPVersion().push_back(*start_input);
current_state = ParserState::REQUEST_PROTOCOL_VERSION_MAJOR;
Debug(std::cout << state_as_string(ParserState::REQUEST_PROTOCOL_VERSION_MAJOR) << std::endl;)
increment_byte();
}else if(*start_input == '.'){
http_message->GetHTTPVersion().push_back(*start_input);
current_state = ParserState::REQUEST_PROTOCOL_VERSION_MINOR;
Debug(std::cout << state_as_string(ParserState::REQUEST_PROTOCOL_VERSION_MAJOR) << std::endl;)
increment_byte();
}else{
Debug(std::cout << state_as_string(ParserState::PROTOCOL_ERROR) << std::endl;)
current_state = ParserState::PROTOCOL_ERROR;
}
break;
}
case ParserState::REQUEST_PROTOCOL_VERSION_MINOR:
{
if(*start_input == '.'){
http_message->GetHTTPVersion().push_back(*start_input);
current_state = ParserState::REQUEST_PROTOCOL_VERSION_MINOR;
Debug(std::cout << state_as_string(ParserState::REQUEST_PROTOCOL_VERSION_MINOR) << std::endl;)
increment_byte();
}else if(std::isdigit(*start_input)){
http_message->GetHTTPVersion().push_back(*start_input);
current_state = ParserState::REQUEST_PROTOCOL_VERSION_MINOR;
Debug(std::cout << state_as_string(ParserState::REQUEST_PROTOCOL_VERSION_MINOR) << std::endl;)
increment_byte();
}else if(*start_input == static_cast<char>(LexConst::CR)){
current_state = ParserState::REQUEST_LINE_LF;
Debug(std::cout << state_as_string(ParserState::REQUEST_PROTOCOL_VERSION_MINOR) << std::endl;)
increment_byte();
}else{
current_state = ParserState::PROTOCOL_ERROR;
Debug(std::cout << state_as_string(ParserState::PROTOCOL_ERROR) << std::endl;)
}
break;
}
case ParserState::REQUEST_LINE_LF:
{
if(*start_input == static_cast<char>(LexConst::LF)){
current_state = ParserState::HEADER_NAME_BEGIN;
Debug(std::cout << state_as_string(ParserState::REQUEST_LINE_LF) << std::endl;)
increment_byte();
}else{
Debug(std::cout << state_as_string(ParserState::PROTOCOL_ERROR) << std::endl;)
current_state = ParserState::PROTOCOL_ERROR;
}
break;
}
case ParserState::HEADER_NAME_BEGIN:
{
if(is_token(*start_input)){
tmp_header_name.push_back(*start_input);
Debug(std::cout << *start_input << std::endl;)
Debug(std::cout << state_as_string(ParserState::HEADER_NAME_BEGIN) << std::endl;)
current_state = ParserState::HEADER_NAME;
increment_byte();
}else if(*start_input == static_cast<char>(LexConst::CR)){
Debug(std::cout << "CR" << std::endl;)
Debug(std::cout << state_as_string(ParserState::HEADER_NAME_BEGIN) << std::endl;)
current_state = ParserState::HEADER_END_LF;
increment_byte();
}else{
Debug(std::cout << state_as_string(ParserState::PROTOCOL_ERROR) << std::endl;)
current_state = ParserState::PROTOCOL_ERROR;
}
break;
}
case ParserState::HEADER_NAME:
{
if(is_token(*start_input)){
tmp_header_name.push_back(*start_input);
Debug(std::cout << *start_input << std::endl;)
Debug(std::cout << state_as_string(ParserState::HEADER_NAME) << std::endl;)
increment_byte();
}else if(*start_input == ':'){
Debug(std::cout << state_as_string(ParserState::HEADER_NAME) << std::endl;)
current_state = ParserState::HEADER_VALUE_BEGIN;
increment_byte();
}else{
Debug(std::cout << state_as_string(ParserState::PROTOCOL_ERROR) << std::endl;)
current_state = ParserState::PROTOCOL_ERROR;
}
break;
}
case ParserState::HEADER_VALUE_BEGIN:
{
if(is_text(*start_input)){
current_state = ParserState::HEADER_VALUE;
Debug(std::cout << *start_input << std::endl;)
Debug(std::cout << state_as_string(ParserState::HEADER_VALUE_BEGIN) << std::endl;)
increment_byte();
}else if(*start_input == static_cast<char>(LexConst::CR)){
Debug(std::cout << "CR" << std::endl;)
Debug(std::cout << state_as_string(ParserState::HEADER_VALUE_BEGIN) << std::endl;)
current_state = ParserState::HEADER_END_LF;
}else{
Debug(std::cout << state_as_string(ParserState::PROTOCOL_ERROR) << std::endl;)
current_state = ParserState::PROTOCOL_ERROR;
}
break;
}
case ParserState::HEADER_VALUE:
{
if(*start_input == static_cast<char>(LexConst::CR)){
current_state = ParserState::HEADER_VALUE_LF;
Debug(std::cout << "LF" << std::endl;)
Debug(std::cout << state_as_string(ParserState::HEADER_VALUE) << std::endl;)
increment_byte();
}else if(is_text(*start_input)){
Debug(std::cout << *start_input << std::endl;)
Debug(std::cout << state_as_string(ParserState::HEADER_VALUE) << std::endl;)
tmp_header_value.push_back(*start_input);
increment_byte();
}else{
Debug(std::cout << state_as_string(ParserState::HEADER_VALUE) << std::endl;)
current_state = ParserState::PROTOCOL_ERROR;
}
break;
}
case ParserState::HEADER_VALUE_LF:
{
if(*start_input == static_cast<char>(LexConst::LF)){
current_state = ParserState::HEADER_VALUE_END;
Debug(std::cout << state_as_string(ParserState::HEADER_VALUE_LF) << std::endl;)
increment_byte();
}else{
Debug(std::cout << state_as_string(ParserState::PROTOCOL_ERROR) << std::endl;);
current_state = ParserState::PROTOCOL_ERROR;
}
break;
}
case ParserState::HEADER_VALUE_END:
{
http_message->AddHeader(tmp_header_name, tmp_header_value);
Debug(std::cout << tmp_header_name << " " << tmp_header_value << std::endl;)
Debug(std::cout << state_as_string(ParserState::HEADER_VALUE_END) << std::endl;)
tmp_header_name.clear();
tmp_header_value.clear();
current_state = ParserState::HEADER_NAME_BEGIN;
break;
}
case ParserState::HEADER_END_LF:
{
if(*start_input == static_cast<char>(LexConst::LF)){
Debug(std::cout << state_as_string(ParserState::HEADER_END_LF) << std::endl;)
if(http_message->GetRequestType() == HTTPConst::HTTP_REQUEST_TYPE::GET){
Debug(std::cout << "GET Request Parsing done" << std::endl;)
current_state = ParserState::PARSING_DONE;
}else if(http_message->GetRequestType() == HTTPConst::HTTP_REQUEST_TYPE::POST){
Debug(std::cout << "POST Request is parsing" << std::endl;)
if(!http_message->GetHeaderValue("Content-Length").has_value())
{ current_state = ParserState::PROTOCOL_ERROR; break; }
current_state = ParserState::CONTENT;
increment_byte();
}else if(http_message->GetRequestType() == HTTPConst::HTTP_REQUEST_TYPE::HEAD){
Debug(std::cout << "HEAD Request Parsing done" << std::endl;)
current_state = ParserState::PARSING_DONE;
}else{
current_state = ParserState::PROTOCOL_ERROR;
}
}else{
Debug(std::cout << state_as_string(ParserState::PROTOCOL_ERROR) << std::endl;)
current_state = ParserState::PROTOCOL_ERROR;
}
break;
}
case ParserState::CONTENT:
{
if((start_input+1) == end_input){
current_state = ParserState::PARSING_DONE;
}
http_message->GetRawBody().push_back(*start_input);
Debug(std::cout << state_as_string(ParserState::CONTENT) << std::endl;)
increment_byte();
break;
}
case ParserState::PROTOCOL_ERROR:
{
Debug(std::cout << state_as_string(ParserState::PROTOCOL_ERROR) << std::endl;)
Debug(std::cout << "Parsing end with PROTOCOL_ERROR" << std::endl;)
is_protocol_fail = true;
}
break;
case ParserState::PARSING_DONE:
goto FINISH;
}
}
FINISH:
return {current_state, std::move(http_message)};
}
std::string Parser::state_as_string(const ParserState &state){
switch(state){
case ParserState::PROTOCOL_ERROR:
return "protocol-error";
case ParserState::REQUEST_LINE_BEGIN:
return "request-line-begin";
case ParserState::REQUEST_METHOD:
return "request-method";
case ParserState::REQUEST_RESOURCE_BEGIN:
return "request-resource-begin";
case ParserState::REQUEST_RESOURCE:
return "request-resource";
case ParserState::REQUEST_PROTOCOL_BEGIN:
return "request-protocol-begin";
case ParserState::REQUEST_PROTOCOL_T1:
return "request-protocol-T1";
case ParserState::REQUEST_PROTOCOL_T2:
return "request-protocol-T2";
case ParserState::REQUEST_PROTOCOL_P:
return "request-protocol-P";
case ParserState::REQUEST_PROTOCOL_SLASH:
return "request-protocol-slash";
case ParserState::REQUEST_PROTOCOL_VERSION_MAJOR:
return "request-protocol-version-major";
case ParserState::REQUEST_PROTOCOL_VERSION_MINOR:
return "request-protocol-version-minor";
case ParserState::REQUEST_LINE_LF:
return "request-protocol-slash";
case ParserState::HEADER_NAME_BEGIN:
return "header-name-begin";
case ParserState::HEADER_NAME:
return "header-name";
case ParserState::HEADER_VALUE_BEGIN:
return "header-value-begin";
case ParserState::HEADER_VALUE:
return "header-value";
case ParserState::HEADER_VALUE_LF:
return "header-value-lf";
case ParserState::HEADER_VALUE_END:
return "header-value-end";
case ParserState::HEADER_END_LF:
return "header-end-lf";
case ParserState::CONTENT:
return "content";
default:
return "Error - No such parser state";
}
}
bool Parser::is_char(char value){
return static_cast<unsigned>(value) <= 127;
}
bool Parser::is_control(char value){
// remember: does not include SP
return (value >= 0 && value <= 31) || value == 127;
}
bool Parser::is_separator(char value){
switch(value){
case '(':
case ')':
case '<':
case '>':
case '@':
case ',':
case ';':
case ':':
case '\\':
case '"':
case '/':
case '[':
case ']':
case '?':
case '=':
case '{':
case '}':
case static_cast<char>(Parser::LexConst::SP):
case static_cast<char>(Parser::LexConst::HT):
return true;
default:
return false;
}
}
bool Parser::is_token(char value){
return is_char(value) && !( is_control(value) || is_separator(value));
}
bool Parser::is_text(char value){
// any byte except CONTROL-char but including LWS
return !is_control(value) ||
value == static_cast<char>(Parser::LexConst::SP) ||
value == static_cast<char>(Parser::LexConst::HT);
}
|
71c8f6f5a1d9da0936a5fb3dd7d95cf1c7e55fa4
|
9a266c4a101ce7174081debec864c38892c5003c
|
/CoffeeFW/ManualController.cpp
|
74114caef9d76a3a7059a63dce952f759a483bac
|
[] |
no_license
|
Tomek-Stolarczyk/CoffeeRoaster
|
2e9c2528b788c3bff952c9253ccdc9f91872496d
|
e212fdbf811d43340d6ad24d34224032ffeb1f1c
|
refs/heads/master
| 2020-03-20T19:10:37.091447
| 2019-11-29T04:50:40
| 2019-11-29T04:50:40
| 137,625,039
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 680
|
cpp
|
ManualController.cpp
|
#include "ManualController.hpp"
Updateable* CreateManualController()
{
return new ManualController<Pins::kManualControllerEnable,
Pins::kManualControllerValue>();
}
template<AnalogPin enable, AnalogPin value>
bool const ManualController<enable, value>::IsOverrideEnabled() const
{
return m_enabled;
}
template<AnalogPin enable, AnalogPin value>
uint32_t const ManualController<enable,value>::GetOverrideValue() const
{
return m_value;
}
template<AnalogPin enable, AnalogPin value>
void ManualController<enable,value>::Update()
{
m_enabled = analogRead(static_cast<uint8_t>(enable));
m_value = analogRead(static_cast<uint8_t>(value));
}
|
6f93818ea3952eb2813e6179ca34833c76217356
|
2270ceeef5a852f6a457ad63efa9d4b0cda668e9
|
/MCG_GFX_Framework/Sphere.cpp
|
44e45c3e317220ddb7331c24489e808e5c2a68be
|
[] |
no_license
|
BitRapture/MCG-Raytracer
|
d75af953dd410a0847f616b10434cc83bbcc27a2
|
44782a208120ee260e4a2eea8688784e83246629
|
refs/heads/master
| 2023-04-15T00:45:37.068119
| 2021-05-04T00:09:39
| 2021-05-04T00:09:39
| 360,754,861
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,571
|
cpp
|
Sphere.cpp
|
#include "Sphere.h"
// Sphere
namespace MRT
{
bool Sphere::Intersect(Ray& _ray)
{
// Get ray origin and direction
glm::fvec3 rO = _ray.GetOrigin(), rD = _ray.GetDirection();
// Calculate vector from ray origin to sphere origin
glm::fvec3 lRO = position - rO;
// Project lRO length onto ray direction
float lPD = glm::dot(lRO, rD);
// Ray wont intersect if the projected length is behind it
if (lPD < 0) return false;
// Get the length of the middle point of the ray to the sphere origin
float mL = glm::dot(lRO, lRO) - (lPD * lPD);
// Ray wont interesect if the length is greater than the radius
if (mL > radiusSqr) return false;
// Calculate half the length from mL mapped to the ray direction
float sHL = glm::sqrt(radiusSqr - mL);
// Calculate the possible starting and ending intersects
float iStart = lPD - sHL,
iEnd = lPD + sHL;
float intersect = iStart;
// If either intersection lengths are less than 0, there is no intersect
if (iStart < 0)
{
intersect = iEnd;
if (iEnd < 0) return false;
}
// Check if intersect length is greater than current ray length
if (_ray.GetLength() < intersect) return false;
// Send hit information to the ray
HitInformation hitInfo{ intersect, glm::normalize((rO + rD * intersect) - position), color };
_ray.SetHitInfo(hitInfo);
return true;
}
Sphere::Sphere(glm::fvec3 _position, float _radius, ColorPixel _color)
:
Primitive(_position, _color),
radius{ _radius }
{
// Precalculate the square of the radius
radiusSqr = _radius * _radius;
}
}
|
b993ce9ae935f5ce36a055be9434e2926d5f3c8a
|
9296e9fde8d6d2342e4addbe2cdcb416c176b18a
|
/222/d.cpp
|
a08e7f3e2566cda983323a98af4d4ae0af6d0772
|
[] |
no_license
|
flxf/codeforces
|
cd816dcbd79e88b1884c72c3e091e516da069962
|
f0c12bc81ac9dfeb816cfdfc9c57d29ad5a756f8
|
refs/heads/master
| 2016-09-05T16:23:37.239451
| 2014-02-17T07:26:57
| 2014-02-17T07:26:57
| 16,295,874
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 616
|
cpp
|
d.cpp
|
#include <iostream>
#include <algorithm>
using namespace std;
int a[100000];
int b[100000];
int main() {
int n, x;
cin >> n >> x;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
for (int i = 0; i < n; i++) {
cin >> b[i];
}
sort(a,a+n);
reverse(a, a+n);
sort(b,b+n);
int wins = 0;
int start = 0;
for (int i = 0; i < n; i++) {
int req = x - a[i];
int fnd = lower_bound(b + start, b + n, req) - b;
if (fnd == n) { // no ans
if (start == i) {
start++;
}
} else {
wins++;
start = fnd + 1;
}
}
cout << 1 << " " << wins << endl;
}
|
e0c1c711331e004e4f73328c3a87a80d3270ae6b
|
964b754233ab5990b16b9d395ae7bb9fecbf91a0
|
/src/xelect/xutil.h
|
b600e657d436c12fb5f2ebc25bb9346dfaafbb67
|
[] |
no_license
|
Yarkin/x-research-prototype
|
351a2cea9a0dd5fdcb65ef353ec93b50c1112fe7
|
695c7d7f273e305c881d81d0a37e490714ea6665
|
refs/heads/master
| 2020-04-12T13:59:24.032176
| 2018-12-25T01:46:06
| 2018-12-25T01:46:06
| 162,538,417
| 1
| 0
| null | 2018-12-20T06:47:27
| 2018-12-20T06:47:27
| null |
UTF-8
|
C++
| false
| false
| 1,782
|
h
|
xutil.h
|
#pragma once
#include "xdefine.h"
#include "xblock.h"
#include <time.h>
NS_BEG2(top, elect2)
class xutil {
public:
static std::string format_str(const std::string &fmt ...);
// for struct xelect_result
static std::string to_string(const xshard &shard);
static std::string to_string(const xzone &zone);
static std::string to_string(const xelect_result &res);
static void to_json(xJson::Value &root, const xshard &shard);
static void to_json(xJson::Value &root, const xzone &zone);
static void to_json(xJson::Value &root, const xelect_result &res);
static std::string get_gmtime(time_t sec);
static std::string get_gmtime(struct timeval &tv);
static std::string get_gmtime();
static std::string get_localtime(time_t sec);
static std::string get_localtime(struct timeval &tv);
static std::string get_localtime();
static void dump(const xelect_result &res);
static std::string to_string(const xnetann &netann);
static std::string to_string(const deq_ann_t &deq);
static std::string pack_to(const xelect_result &res);
static bool unpack_from(xelect_result &res, const std::string &str_buf);
static std::string pack_to(const xblock &b);
static bool unpack_from(xblock &b, const std::string &str_buf);
static std::string pack_to(const xnetann &netann);
static bool unpack_from(xnetann &netann, const std::string &str_buf);
// 1 zone 1 shard: (0, 0)
static void make_unique_shard(xelect_result &res, const std::string &local_account, const xannset &annset);
// at most 3 zones and 2 shards every zone and scatter free nodes
// just for testnet 11-10
static void make_1110_shards(xelect_result &res, const std::string &local_account, const xannset &annset);
};
NS_END2
|
7733b64a7dbe7bbf674639739fe5c848dbcfc2a7
|
9d6b4a4a8a99775fa99c241230dfa3aca78d2ca2
|
/StackSimulateQueue/main.cpp
|
fc32ec3904277d689e0d99044527d92fe2b9ed64
|
[] |
no_license
|
W-David/pat-learn-cpp
|
65c6510d896ea86efb25b7b43570533ebfd238c6
|
86aa735d416951a217d190e277ec8896b8905ee3
|
refs/heads/master
| 2020-12-15T20:52:04.154230
| 2020-03-03T15:03:42
| 2020-03-03T15:03:42
| 235,250,168
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 837
|
cpp
|
main.cpp
|
#include <iostream>
#include <stack>
using namespace std;
stack<int> s1,s2;
int main() {
int n,m; cin>>n>>m;
if(n < m) swap(n,m);
char c;
while(true){
cin>>c;
if(c == 'T') break;
else if(c == 'A'){
int i; cin>>i;
if(s2.size() == m && s1.size() == m) cout<<"ERROR:Full"<<endl;
else if(s2.size() == m) {
while(!s2.empty()) s1.push(s2.top()),s2.pop();
s2.push(i);
}
else s2.push(i);
} else {
if(s1.empty() && s2.empty()) cout<<"ERROR:Empty"<<endl;
else if(s1.empty()) {
while(!s2.empty()) {s1.push(s2.top()),s2.pop();}
cout<<s1.top()<<endl,s1.pop();
}
else cout<<s1.top()<<endl,s1.pop();
}
}
return 0;
}
|
91b8054df03a75fa92edc68c83eb07dfec570705
|
0eff74b05b60098333ad66cf801bdd93becc9ea4
|
/second/download/mutt/gumtree/mutt_repos_function_987_mutt-1.6.2.cpp
|
636de5cde5a971b56404329b9ccdfe061fe2f6d8
|
[] |
no_license
|
niuxu18/logTracker-old
|
97543445ea7e414ed40bdc681239365d33418975
|
f2b060f13a0295387fe02187543db124916eb446
|
refs/heads/master
| 2021-09-13T21:39:37.686481
| 2017-12-11T03:36:34
| 2017-12-11T03:36:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,655
|
cpp
|
mutt_repos_function_987_mutt-1.6.2.cpp
|
static int external_body_handler (BODY *b, STATE *s)
{
const char *access_type;
const char *expiration;
time_t expire;
access_type = mutt_get_parameter ("access-type", b->parameter);
if (!access_type)
{
if (s->flags & M_DISPLAY)
{
state_mark_attach (s);
state_puts (_("[-- Error: message/external-body has no access-type parameter --]\n"), s);
return 0;
}
else
return -1;
}
expiration = mutt_get_parameter ("expiration", b->parameter);
if (expiration)
expire = mutt_parse_date (expiration, NULL);
else
expire = -1;
if (!ascii_strcasecmp (access_type, "x-mutt-deleted"))
{
if (s->flags & (M_DISPLAY|M_PRINTING))
{
char *length;
char pretty_size[10];
state_mark_attach (s);
state_printf (s, _("[-- This %s/%s attachment "),
TYPE(b->parts), b->parts->subtype);
length = mutt_get_parameter ("length", b->parameter);
if (length)
{
mutt_pretty_size (pretty_size, sizeof (pretty_size),
strtol (length, NULL, 10));
state_printf (s, _("(size %s bytes) "), pretty_size);
}
state_puts (_("has been deleted --]\n"), s);
if (expire != -1)
{
state_mark_attach (s);
state_printf (s, _("[-- on %s --]\n"), expiration);
}
if (b->parts->filename)
{
state_mark_attach (s);
state_printf (s, _("[-- name: %s --]\n"), b->parts->filename);
}
mutt_copy_hdr (s->fpin, s->fpout, ftello (s->fpin), b->parts->offset,
(option (OPTWEED) ? (CH_WEED | CH_REORDER) : 0) |
CH_DECODE , NULL);
}
}
else if(expiration && expire < time(NULL))
{
if (s->flags & M_DISPLAY)
{
state_mark_attach (s);
state_printf (s, _("[-- This %s/%s attachment is not included, --]\n"),
TYPE(b->parts), b->parts->subtype);
state_attach_puts (_("[-- and the indicated external source has --]\n"
"[-- expired. --]\n"), s);
mutt_copy_hdr(s->fpin, s->fpout, ftello (s->fpin), b->parts->offset,
(option (OPTWEED) ? (CH_WEED | CH_REORDER) : 0) |
CH_DECODE | CH_DISPLAY, NULL);
}
}
else
{
if (s->flags & M_DISPLAY)
{
state_mark_attach (s);
state_printf (s,
_("[-- This %s/%s attachment is not included, --]\n"),
TYPE (b->parts), b->parts->subtype);
state_mark_attach (s);
state_printf (s,
_("[-- and the indicated access-type %s is unsupported --]\n"),
access_type);
mutt_copy_hdr (s->fpin, s->fpout, ftello (s->fpin), b->parts->offset,
(option (OPTWEED) ? (CH_WEED | CH_REORDER) : 0) |
CH_DECODE | CH_DISPLAY, NULL);
}
}
return 0;
}
|
bb57e4f288fcfb0483b6ebc0636fa58f486602eb
|
875f360a9d075d1c165706f806eae3901eb7e366
|
/src/Project.cpp
|
b6fddd8179af5f568236ba40600010a187be80e9
|
[
"MIT"
] |
permissive
|
lawadr/gridiron
|
d435483ecaac5d4d5f8f0f35bd873afed05480c2
|
950aa96a7574a825fb3eb56e802f54c311587413
|
refs/heads/master
| 2021-01-18T15:23:07.862350
| 2013-01-28T20:41:33
| 2020-04-18T19:46:38
| 7,512,138
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,580
|
cpp
|
Project.cpp
|
/*
Copyright (c) 2012-2013 Lawrence Adranghi
See LICENSE in root directory.
*/
#include "Project.h"
#include <QtCore/qdir.h>
#include <QtCore/qtextstream.h>
#include <QtXml/qdom.h>
Project2::Project2() {
}
Project2::~Project2() {
}
bool Project2::open(const QString& fileName) {
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return false;
QXmlStreamReader stream(&file);
if (stream.readNextStartElement()) {
if (stream.qualifiedName() == "Project") {
if (stream.qualifiedName() == "Name") {
name_ = stream.readElementText();
}
}
}
close();
fileName_ = file.fileName();
location_ = file.fileName();
loadTypes();
return true;
}
bool Project2::save() {
QDir directory(location_);
QFile file(directory.absoluteFilePath(fileName_));
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
return false;
}
QXmlStreamWriter stream(&file);
stream.writeStartDocument();
stream.writeStartElement("Project");
stream.writeTextElement("Name", name_);
stream.writeEndElement();
stream.writeEndElement();
stream.writeEndDocument();
file.close();
return true;
}
void Project2::close() {
name_.clear();
location_.clear();
fileName_.clear();
floorTypes_.clear();
wallTypes_.clear();
objectTypes_.clear();
//world_.clear();
}
void Project2::loadTypes() {
QFile file(QDir(location_).filePath("Types.xml"));
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QXmlStreamReader stream(&file);
if (stream.readNextStartElement()) {
if (stream.qualifiedName() == "Types") {
while (stream.readNextStartElement()) {
if (stream.qualifiedName() == "Floor") {
FloorType2 type;
type.read(stream);
floorTypes_.push_back(type);
} else if (stream.qualifiedName() == "Wall") {
WallType2 type;
type.read(stream);
wallTypes_.push_back(type);
} else if (stream.qualifiedName() == "Object") {
ObjectType2 type;
type.read(stream);
objectTypes_.push_back(type);
}
}
}
}
file.close();
}
void Project2::saveTypes() {
QFile file(QDir(location_).filePath("Types.xml"));
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
return;
QXmlStreamWriter stream(&file);
stream.writeStartDocument();
stream.writeStartElement("Types");
QVector<FloorType2>::const_iterator floorTypeIt;
for (floorTypeIt = floorTypes_.begin(); floorTypeIt != floorTypes_.begin(); ++floorTypeIt) {
stream.writeStartElement("Floor");
floorTypeIt->write(stream);
stream.writeEndElement();
}
QVector<WallType2>::const_iterator wallTypeIt;
for (wallTypeIt = wallTypes_.begin(); wallTypeIt != wallTypes_.begin(); ++wallTypeIt) {
stream.writeStartElement("Wall");
wallTypeIt->write(stream);
stream.writeEndElement();
}
QVector<ObjectType2>::const_iterator objectTypeIt;
for (objectTypeIt = objectTypes_.begin(); objectTypeIt != objectTypes_.begin(); ++objectTypeIt) {
stream.writeStartElement("Object");
objectTypeIt->write(stream);
stream.writeEndElement();
}
stream.writeEndElement();
stream.writeEndDocument();
file.close();
}
|
99950971e23b3d785a6f025cd2aa2297352af5e8
|
52ecc81aba92258924ff6bbe62e536e1ad85ff03
|
/3d/pygame-soft3d/3d.build/__helpers.hpp
|
86a6a4d0cf5efc05ddc49312465da50c4a37739f
|
[] |
no_license
|
mdurrer/cgd
|
df02709a9b5db7d3696f82c521405f1ada67febf
|
bbbb2960e2c47531b464f888146d758ca96c5b64
|
refs/heads/master
| 2020-05-21T12:28:54.901920
| 2018-07-25T20:06:48
| 2018-07-25T20:06:48
| 52,598,365
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 21,638
|
hpp
|
__helpers.hpp
|
#ifndef __NUITKA_TUPLES_H__
#define __NUITKA_TUPLES_H__
NUITKA_MAY_BE_UNUSED static PyObject *MAKE_TUPLE1( PyObject *element0 )
{
PyObject *result = PyTuple_New( 1 );
if (unlikely( result == NULL ))
{
throw PythonException();
}
assertObject( element0 );
PyTuple_SET_ITEM( result, 0, INCREASE_REFCOUNT( element0 ) );
assert( Py_REFCNT( result ) == 1 );
return result;
}
NUITKA_MAY_BE_UNUSED static PyObject *MAKE_TUPLE2( PyObject *element0, PyObject *element1 )
{
PyObject *result = PyTuple_New( 2 );
if (unlikely( result == NULL ))
{
throw PythonException();
}
assertObject( element0 );
PyTuple_SET_ITEM( result, 0, INCREASE_REFCOUNT( element0 ) );
assertObject( element1 );
PyTuple_SET_ITEM( result, 1, INCREASE_REFCOUNT( element1 ) );
assert( Py_REFCNT( result ) == 1 );
return result;
}
NUITKA_MAY_BE_UNUSED static PyObject *MAKE_TUPLE3( PyObject *element0, PyObject *element1, PyObject *element2 )
{
PyObject *result = PyTuple_New( 3 );
if (unlikely( result == NULL ))
{
throw PythonException();
}
assertObject( element0 );
PyTuple_SET_ITEM( result, 0, INCREASE_REFCOUNT( element0 ) );
assertObject( element1 );
PyTuple_SET_ITEM( result, 1, INCREASE_REFCOUNT( element1 ) );
assertObject( element2 );
PyTuple_SET_ITEM( result, 2, INCREASE_REFCOUNT( element2 ) );
assert( Py_REFCNT( result ) == 1 );
return result;
}
NUITKA_MAY_BE_UNUSED static PyObject *MAKE_TUPLE4( PyObject *element0, PyObject *element1, PyObject *element2, PyObject *element3 )
{
PyObject *result = PyTuple_New( 4 );
if (unlikely( result == NULL ))
{
throw PythonException();
}
assertObject( element0 );
PyTuple_SET_ITEM( result, 0, INCREASE_REFCOUNT( element0 ) );
assertObject( element1 );
PyTuple_SET_ITEM( result, 1, INCREASE_REFCOUNT( element1 ) );
assertObject( element2 );
PyTuple_SET_ITEM( result, 2, INCREASE_REFCOUNT( element2 ) );
assertObject( element3 );
PyTuple_SET_ITEM( result, 3, INCREASE_REFCOUNT( element3 ) );
assert( Py_REFCNT( result ) == 1 );
return result;
}
NUITKA_MAY_BE_UNUSED static PyObject *MAKE_TUPLE5( PyObject *element0, PyObject *element1, PyObject *element2, PyObject *element3, PyObject *element4 )
{
PyObject *result = PyTuple_New( 5 );
if (unlikely( result == NULL ))
{
throw PythonException();
}
assertObject( element0 );
PyTuple_SET_ITEM( result, 0, INCREASE_REFCOUNT( element0 ) );
assertObject( element1 );
PyTuple_SET_ITEM( result, 1, INCREASE_REFCOUNT( element1 ) );
assertObject( element2 );
PyTuple_SET_ITEM( result, 2, INCREASE_REFCOUNT( element2 ) );
assertObject( element3 );
PyTuple_SET_ITEM( result, 3, INCREASE_REFCOUNT( element3 ) );
assertObject( element4 );
PyTuple_SET_ITEM( result, 4, INCREASE_REFCOUNT( element4 ) );
assert( Py_REFCNT( result ) == 1 );
return result;
}
NUITKA_MAY_BE_UNUSED static PyObject *MAKE_TUPLE6( PyObject *element0, PyObject *element1, PyObject *element2, PyObject *element3, PyObject *element4, PyObject *element5 )
{
PyObject *result = PyTuple_New( 6 );
if (unlikely( result == NULL ))
{
throw PythonException();
}
assertObject( element0 );
PyTuple_SET_ITEM( result, 0, INCREASE_REFCOUNT( element0 ) );
assertObject( element1 );
PyTuple_SET_ITEM( result, 1, INCREASE_REFCOUNT( element1 ) );
assertObject( element2 );
PyTuple_SET_ITEM( result, 2, INCREASE_REFCOUNT( element2 ) );
assertObject( element3 );
PyTuple_SET_ITEM( result, 3, INCREASE_REFCOUNT( element3 ) );
assertObject( element4 );
PyTuple_SET_ITEM( result, 4, INCREASE_REFCOUNT( element4 ) );
assertObject( element5 );
PyTuple_SET_ITEM( result, 5, INCREASE_REFCOUNT( element5 ) );
assert( Py_REFCNT( result ) == 1 );
return result;
}
NUITKA_MAY_BE_UNUSED static PyObject *MAKE_TUPLE7( PyObject *element0, PyObject *element1, PyObject *element2, PyObject *element3, PyObject *element4, PyObject *element5, PyObject *element6 )
{
PyObject *result = PyTuple_New( 7 );
if (unlikely( result == NULL ))
{
throw PythonException();
}
assertObject( element0 );
PyTuple_SET_ITEM( result, 0, INCREASE_REFCOUNT( element0 ) );
assertObject( element1 );
PyTuple_SET_ITEM( result, 1, INCREASE_REFCOUNT( element1 ) );
assertObject( element2 );
PyTuple_SET_ITEM( result, 2, INCREASE_REFCOUNT( element2 ) );
assertObject( element3 );
PyTuple_SET_ITEM( result, 3, INCREASE_REFCOUNT( element3 ) );
assertObject( element4 );
PyTuple_SET_ITEM( result, 4, INCREASE_REFCOUNT( element4 ) );
assertObject( element5 );
PyTuple_SET_ITEM( result, 5, INCREASE_REFCOUNT( element5 ) );
assertObject( element6 );
PyTuple_SET_ITEM( result, 6, INCREASE_REFCOUNT( element6 ) );
assert( Py_REFCNT( result ) == 1 );
return result;
}
NUITKA_MAY_BE_UNUSED static PyObject *MAKE_TUPLE9( PyObject *element0, PyObject *element1, PyObject *element2, PyObject *element3, PyObject *element4, PyObject *element5, PyObject *element6, PyObject *element7, PyObject *element8 )
{
PyObject *result = PyTuple_New( 9 );
if (unlikely( result == NULL ))
{
throw PythonException();
}
assertObject( element0 );
PyTuple_SET_ITEM( result, 0, INCREASE_REFCOUNT( element0 ) );
assertObject( element1 );
PyTuple_SET_ITEM( result, 1, INCREASE_REFCOUNT( element1 ) );
assertObject( element2 );
PyTuple_SET_ITEM( result, 2, INCREASE_REFCOUNT( element2 ) );
assertObject( element3 );
PyTuple_SET_ITEM( result, 3, INCREASE_REFCOUNT( element3 ) );
assertObject( element4 );
PyTuple_SET_ITEM( result, 4, INCREASE_REFCOUNT( element4 ) );
assertObject( element5 );
PyTuple_SET_ITEM( result, 5, INCREASE_REFCOUNT( element5 ) );
assertObject( element6 );
PyTuple_SET_ITEM( result, 6, INCREASE_REFCOUNT( element6 ) );
assertObject( element7 );
PyTuple_SET_ITEM( result, 7, INCREASE_REFCOUNT( element7 ) );
assertObject( element8 );
PyTuple_SET_ITEM( result, 8, INCREASE_REFCOUNT( element8 ) );
assert( Py_REFCNT( result ) == 1 );
return result;
}
NUITKA_MAY_BE_UNUSED static PyObject *MAKE_TUPLE10( PyObject *element0, PyObject *element1, PyObject *element2, PyObject *element3, PyObject *element4, PyObject *element5, PyObject *element6, PyObject *element7, PyObject *element8, PyObject *element9 )
{
PyObject *result = PyTuple_New( 10 );
if (unlikely( result == NULL ))
{
throw PythonException();
}
assertObject( element0 );
PyTuple_SET_ITEM( result, 0, INCREASE_REFCOUNT( element0 ) );
assertObject( element1 );
PyTuple_SET_ITEM( result, 1, INCREASE_REFCOUNT( element1 ) );
assertObject( element2 );
PyTuple_SET_ITEM( result, 2, INCREASE_REFCOUNT( element2 ) );
assertObject( element3 );
PyTuple_SET_ITEM( result, 3, INCREASE_REFCOUNT( element3 ) );
assertObject( element4 );
PyTuple_SET_ITEM( result, 4, INCREASE_REFCOUNT( element4 ) );
assertObject( element5 );
PyTuple_SET_ITEM( result, 5, INCREASE_REFCOUNT( element5 ) );
assertObject( element6 );
PyTuple_SET_ITEM( result, 6, INCREASE_REFCOUNT( element6 ) );
assertObject( element7 );
PyTuple_SET_ITEM( result, 7, INCREASE_REFCOUNT( element7 ) );
assertObject( element8 );
PyTuple_SET_ITEM( result, 8, INCREASE_REFCOUNT( element8 ) );
assertObject( element9 );
PyTuple_SET_ITEM( result, 9, INCREASE_REFCOUNT( element9 ) );
assert( Py_REFCNT( result ) == 1 );
return result;
}
NUITKA_MAY_BE_UNUSED static PyObject *MAKE_TUPLE11( PyObject *element0, PyObject *element1, PyObject *element2, PyObject *element3, PyObject *element4, PyObject *element5, PyObject *element6, PyObject *element7, PyObject *element8, PyObject *element9, PyObject *element10 )
{
PyObject *result = PyTuple_New( 11 );
if (unlikely( result == NULL ))
{
throw PythonException();
}
assertObject( element0 );
PyTuple_SET_ITEM( result, 0, INCREASE_REFCOUNT( element0 ) );
assertObject( element1 );
PyTuple_SET_ITEM( result, 1, INCREASE_REFCOUNT( element1 ) );
assertObject( element2 );
PyTuple_SET_ITEM( result, 2, INCREASE_REFCOUNT( element2 ) );
assertObject( element3 );
PyTuple_SET_ITEM( result, 3, INCREASE_REFCOUNT( element3 ) );
assertObject( element4 );
PyTuple_SET_ITEM( result, 4, INCREASE_REFCOUNT( element4 ) );
assertObject( element5 );
PyTuple_SET_ITEM( result, 5, INCREASE_REFCOUNT( element5 ) );
assertObject( element6 );
PyTuple_SET_ITEM( result, 6, INCREASE_REFCOUNT( element6 ) );
assertObject( element7 );
PyTuple_SET_ITEM( result, 7, INCREASE_REFCOUNT( element7 ) );
assertObject( element8 );
PyTuple_SET_ITEM( result, 8, INCREASE_REFCOUNT( element8 ) );
assertObject( element9 );
PyTuple_SET_ITEM( result, 9, INCREASE_REFCOUNT( element9 ) );
assertObject( element10 );
PyTuple_SET_ITEM( result, 10, INCREASE_REFCOUNT( element10 ) );
assert( Py_REFCNT( result ) == 1 );
return result;
}
NUITKA_MAY_BE_UNUSED static PyObject *MAKE_TUPLE14( PyObject *element0, PyObject *element1, PyObject *element2, PyObject *element3, PyObject *element4, PyObject *element5, PyObject *element6, PyObject *element7, PyObject *element8, PyObject *element9, PyObject *element10, PyObject *element11, PyObject *element12, PyObject *element13 )
{
PyObject *result = PyTuple_New( 14 );
if (unlikely( result == NULL ))
{
throw PythonException();
}
assertObject( element0 );
PyTuple_SET_ITEM( result, 0, INCREASE_REFCOUNT( element0 ) );
assertObject( element1 );
PyTuple_SET_ITEM( result, 1, INCREASE_REFCOUNT( element1 ) );
assertObject( element2 );
PyTuple_SET_ITEM( result, 2, INCREASE_REFCOUNT( element2 ) );
assertObject( element3 );
PyTuple_SET_ITEM( result, 3, INCREASE_REFCOUNT( element3 ) );
assertObject( element4 );
PyTuple_SET_ITEM( result, 4, INCREASE_REFCOUNT( element4 ) );
assertObject( element5 );
PyTuple_SET_ITEM( result, 5, INCREASE_REFCOUNT( element5 ) );
assertObject( element6 );
PyTuple_SET_ITEM( result, 6, INCREASE_REFCOUNT( element6 ) );
assertObject( element7 );
PyTuple_SET_ITEM( result, 7, INCREASE_REFCOUNT( element7 ) );
assertObject( element8 );
PyTuple_SET_ITEM( result, 8, INCREASE_REFCOUNT( element8 ) );
assertObject( element9 );
PyTuple_SET_ITEM( result, 9, INCREASE_REFCOUNT( element9 ) );
assertObject( element10 );
PyTuple_SET_ITEM( result, 10, INCREASE_REFCOUNT( element10 ) );
assertObject( element11 );
PyTuple_SET_ITEM( result, 11, INCREASE_REFCOUNT( element11 ) );
assertObject( element12 );
PyTuple_SET_ITEM( result, 12, INCREASE_REFCOUNT( element12 ) );
assertObject( element13 );
PyTuple_SET_ITEM( result, 13, INCREASE_REFCOUNT( element13 ) );
assert( Py_REFCNT( result ) == 1 );
return result;
}
NUITKA_MAY_BE_UNUSED static PyObject *MAKE_TUPLE22( PyObject *element0, PyObject *element1, PyObject *element2, PyObject *element3, PyObject *element4, PyObject *element5, PyObject *element6, PyObject *element7, PyObject *element8, PyObject *element9, PyObject *element10, PyObject *element11, PyObject *element12, PyObject *element13, PyObject *element14, PyObject *element15, PyObject *element16, PyObject *element17, PyObject *element18, PyObject *element19, PyObject *element20, PyObject *element21 )
{
PyObject *result = PyTuple_New( 22 );
if (unlikely( result == NULL ))
{
throw PythonException();
}
assertObject( element0 );
PyTuple_SET_ITEM( result, 0, INCREASE_REFCOUNT( element0 ) );
assertObject( element1 );
PyTuple_SET_ITEM( result, 1, INCREASE_REFCOUNT( element1 ) );
assertObject( element2 );
PyTuple_SET_ITEM( result, 2, INCREASE_REFCOUNT( element2 ) );
assertObject( element3 );
PyTuple_SET_ITEM( result, 3, INCREASE_REFCOUNT( element3 ) );
assertObject( element4 );
PyTuple_SET_ITEM( result, 4, INCREASE_REFCOUNT( element4 ) );
assertObject( element5 );
PyTuple_SET_ITEM( result, 5, INCREASE_REFCOUNT( element5 ) );
assertObject( element6 );
PyTuple_SET_ITEM( result, 6, INCREASE_REFCOUNT( element6 ) );
assertObject( element7 );
PyTuple_SET_ITEM( result, 7, INCREASE_REFCOUNT( element7 ) );
assertObject( element8 );
PyTuple_SET_ITEM( result, 8, INCREASE_REFCOUNT( element8 ) );
assertObject( element9 );
PyTuple_SET_ITEM( result, 9, INCREASE_REFCOUNT( element9 ) );
assertObject( element10 );
PyTuple_SET_ITEM( result, 10, INCREASE_REFCOUNT( element10 ) );
assertObject( element11 );
PyTuple_SET_ITEM( result, 11, INCREASE_REFCOUNT( element11 ) );
assertObject( element12 );
PyTuple_SET_ITEM( result, 12, INCREASE_REFCOUNT( element12 ) );
assertObject( element13 );
PyTuple_SET_ITEM( result, 13, INCREASE_REFCOUNT( element13 ) );
assertObject( element14 );
PyTuple_SET_ITEM( result, 14, INCREASE_REFCOUNT( element14 ) );
assertObject( element15 );
PyTuple_SET_ITEM( result, 15, INCREASE_REFCOUNT( element15 ) );
assertObject( element16 );
PyTuple_SET_ITEM( result, 16, INCREASE_REFCOUNT( element16 ) );
assertObject( element17 );
PyTuple_SET_ITEM( result, 17, INCREASE_REFCOUNT( element17 ) );
assertObject( element18 );
PyTuple_SET_ITEM( result, 18, INCREASE_REFCOUNT( element18 ) );
assertObject( element19 );
PyTuple_SET_ITEM( result, 19, INCREASE_REFCOUNT( element19 ) );
assertObject( element20 );
PyTuple_SET_ITEM( result, 20, INCREASE_REFCOUNT( element20 ) );
assertObject( element21 );
PyTuple_SET_ITEM( result, 21, INCREASE_REFCOUNT( element21 ) );
assert( Py_REFCNT( result ) == 1 );
return result;
}
NUITKA_MAY_BE_UNUSED static PyObject *MAKE_TUPLE25( PyObject *element0, PyObject *element1, PyObject *element2, PyObject *element3, PyObject *element4, PyObject *element5, PyObject *element6, PyObject *element7, PyObject *element8, PyObject *element9, PyObject *element10, PyObject *element11, PyObject *element12, PyObject *element13, PyObject *element14, PyObject *element15, PyObject *element16, PyObject *element17, PyObject *element18, PyObject *element19, PyObject *element20, PyObject *element21, PyObject *element22, PyObject *element23, PyObject *element24 )
{
PyObject *result = PyTuple_New( 25 );
if (unlikely( result == NULL ))
{
throw PythonException();
}
assertObject( element0 );
PyTuple_SET_ITEM( result, 0, INCREASE_REFCOUNT( element0 ) );
assertObject( element1 );
PyTuple_SET_ITEM( result, 1, INCREASE_REFCOUNT( element1 ) );
assertObject( element2 );
PyTuple_SET_ITEM( result, 2, INCREASE_REFCOUNT( element2 ) );
assertObject( element3 );
PyTuple_SET_ITEM( result, 3, INCREASE_REFCOUNT( element3 ) );
assertObject( element4 );
PyTuple_SET_ITEM( result, 4, INCREASE_REFCOUNT( element4 ) );
assertObject( element5 );
PyTuple_SET_ITEM( result, 5, INCREASE_REFCOUNT( element5 ) );
assertObject( element6 );
PyTuple_SET_ITEM( result, 6, INCREASE_REFCOUNT( element6 ) );
assertObject( element7 );
PyTuple_SET_ITEM( result, 7, INCREASE_REFCOUNT( element7 ) );
assertObject( element8 );
PyTuple_SET_ITEM( result, 8, INCREASE_REFCOUNT( element8 ) );
assertObject( element9 );
PyTuple_SET_ITEM( result, 9, INCREASE_REFCOUNT( element9 ) );
assertObject( element10 );
PyTuple_SET_ITEM( result, 10, INCREASE_REFCOUNT( element10 ) );
assertObject( element11 );
PyTuple_SET_ITEM( result, 11, INCREASE_REFCOUNT( element11 ) );
assertObject( element12 );
PyTuple_SET_ITEM( result, 12, INCREASE_REFCOUNT( element12 ) );
assertObject( element13 );
PyTuple_SET_ITEM( result, 13, INCREASE_REFCOUNT( element13 ) );
assertObject( element14 );
PyTuple_SET_ITEM( result, 14, INCREASE_REFCOUNT( element14 ) );
assertObject( element15 );
PyTuple_SET_ITEM( result, 15, INCREASE_REFCOUNT( element15 ) );
assertObject( element16 );
PyTuple_SET_ITEM( result, 16, INCREASE_REFCOUNT( element16 ) );
assertObject( element17 );
PyTuple_SET_ITEM( result, 17, INCREASE_REFCOUNT( element17 ) );
assertObject( element18 );
PyTuple_SET_ITEM( result, 18, INCREASE_REFCOUNT( element18 ) );
assertObject( element19 );
PyTuple_SET_ITEM( result, 19, INCREASE_REFCOUNT( element19 ) );
assertObject( element20 );
PyTuple_SET_ITEM( result, 20, INCREASE_REFCOUNT( element20 ) );
assertObject( element21 );
PyTuple_SET_ITEM( result, 21, INCREASE_REFCOUNT( element21 ) );
assertObject( element22 );
PyTuple_SET_ITEM( result, 22, INCREASE_REFCOUNT( element22 ) );
assertObject( element23 );
PyTuple_SET_ITEM( result, 23, INCREASE_REFCOUNT( element23 ) );
assertObject( element24 );
PyTuple_SET_ITEM( result, 24, INCREASE_REFCOUNT( element24 ) );
assert( Py_REFCNT( result ) == 1 );
return result;
}
#endif
#ifndef __NUITKA_LISTS_H__
#define __NUITKA_LISTS_H__
NUITKA_MAY_BE_UNUSED static PyObject *MAKE_LIST0( )
{
PyObject *result = PyList_New( 0 );
if (unlikely( result == NULL ))
{
throw PythonException();
}
assert( Py_REFCNT( result ) == 1 );
return result;
}
NUITKA_MAY_BE_UNUSED static PyObject *MAKE_LIST2( PyObject *element0, PyObject *element1 )
{
PyObject *result = PyList_New( 2 );
if (unlikely( result == NULL ))
{
throw PythonException();
}
assertObject( element0 );
PyList_SET_ITEM( result, 0, element0 );
assertObject( element1 );
PyList_SET_ITEM( result, 1, element1 );
assert( Py_REFCNT( result ) == 1 );
return result;
}
NUITKA_MAY_BE_UNUSED static PyObject *MAKE_LIST3( PyObject *element0, PyObject *element1, PyObject *element2 )
{
PyObject *result = PyList_New( 3 );
if (unlikely( result == NULL ))
{
throw PythonException();
}
assertObject( element0 );
PyList_SET_ITEM( result, 0, element0 );
assertObject( element1 );
PyList_SET_ITEM( result, 1, element1 );
assertObject( element2 );
PyList_SET_ITEM( result, 2, element2 );
assert( Py_REFCNT( result ) == 1 );
return result;
}
NUITKA_MAY_BE_UNUSED static PyObject *MAKE_LIST5( PyObject *element0, PyObject *element1, PyObject *element2, PyObject *element3, PyObject *element4 )
{
PyObject *result = PyList_New( 5 );
if (unlikely( result == NULL ))
{
throw PythonException();
}
assertObject( element0 );
PyList_SET_ITEM( result, 0, element0 );
assertObject( element1 );
PyList_SET_ITEM( result, 1, element1 );
assertObject( element2 );
PyList_SET_ITEM( result, 2, element2 );
assertObject( element3 );
PyList_SET_ITEM( result, 3, element3 );
assertObject( element4 );
PyList_SET_ITEM( result, 4, element4 );
assert( Py_REFCNT( result ) == 1 );
return result;
}
#endif
#ifndef __NUITKA_DICTS_H__
#define __NUITKA_DICTS_H__
NUITKA_MAY_BE_UNUSED static PyObject *MAKE_DICT0( )
{
PyObject *result = _PyDict_NewPresized( 0 );
if (unlikely( result == NULL ))
{
throw PythonException();
}
assert( Py_REFCNT( result ) == 1 );
return result;
}
NUITKA_MAY_BE_UNUSED static PyObject *MAKE_DICT1( PyObject *value1, PyObject *key1 )
{
PyObject *result = _PyDict_NewPresized( 1 );
if (unlikely( result == NULL ))
{
throw PythonException();
}
assertObject( key1 );
assertObject( value1 );
{
int status = PyDict_SetItem( result, key1, value1 );
if (unlikely( status == -1 ))
{
throw PythonException();
}
}
assert( Py_REFCNT( result ) == 1 );
return result;
}
NUITKA_MAY_BE_UNUSED static PyObject *MAKE_DICT2( PyObject *value1, PyObject *key1, PyObject *value2, PyObject *key2 )
{
PyObject *result = _PyDict_NewPresized( 2 );
if (unlikely( result == NULL ))
{
throw PythonException();
}
assertObject( key1 );
assertObject( value1 );
{
int status = PyDict_SetItem( result, key1, value1 );
if (unlikely( status == -1 ))
{
throw PythonException();
}
}
assertObject( key2 );
assertObject( value2 );
{
int status = PyDict_SetItem( result, key2, value2 );
if (unlikely( status == -1 ))
{
throw PythonException();
}
}
assert( Py_REFCNT( result ) == 1 );
return result;
}
#endif
#ifndef __NUITKA_SETS_H__
#define __NUITKA_SETS_H__
#endif
#ifndef __NUITKA_CALLS_H__
#define __NUITKA_CALLS_H__
extern PyObject *CALL_FUNCTION_WITH_ARGS1( PyObject *called, PyObject *arg0 );
extern PyObject *CALL_FUNCTION_WITH_ARGS2( PyObject *called, PyObject *arg0, PyObject *arg1 );
extern PyObject *CALL_FUNCTION_WITH_ARGS3( PyObject *called, PyObject *arg0, PyObject *arg1, PyObject *arg2 );
extern PyObject *CALL_FUNCTION_WITH_ARGS4( PyObject *called, PyObject *arg0, PyObject *arg1, PyObject *arg2, PyObject *arg3 );
extern PyObject *CALL_FUNCTION_WITH_ARGS6( PyObject *called, PyObject *arg0, PyObject *arg1, PyObject *arg2, PyObject *arg3, PyObject *arg4, PyObject *arg5 );
extern PyObject *CALL_FUNCTION_WITH_ARGS11( PyObject *called, PyObject *arg0, PyObject *arg1, PyObject *arg2, PyObject *arg3, PyObject *arg4, PyObject *arg5, PyObject *arg6, PyObject *arg7, PyObject *arg8, PyObject *arg9, PyObject *arg10 );
#endif
|
7fb6096172958e337ee5d6674935246ab07fcf52
|
9c60aada9d6c0b7a9e128915546187481f5d0436
|
/HK_FlippingBits.cpp
|
6eba45b53a79de6fe8b48cba4a5d5151f4c6ac9f
|
[] |
no_license
|
rukonfahim/hackerrank
|
5975cc962a6d1b7e0bb25d7e621193201badff4e
|
b395983cec275ce1c4ced5a2674fd7a24763b911
|
refs/heads/master
| 2022-03-04T08:01:37.251500
| 2019-11-17T08:26:21
| 2019-11-17T08:26:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 643
|
cpp
|
HK_FlippingBits.cpp
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int i;
string s;
cin >> s;// cout<<s[9]<<endl;
if (s[8] == 'P' || s[8] == 'p') {
i = (int)s[0] - 48;//cout << i << endl;
i = (int)s[1] - 48;//cout << i << endl;
if (i < 12) {
i += 12;
s[0] = (i / 10) + 48;
s[1] = (i % 10) + 48;
}
}
if (s[8] == 'A' || s[8] == 'a') {
i = (int)s[0] - 48;//cout << i << endl;
i = (int)s[1] - 48;//cout << i << endl;
if (i == 12) {
s[0] = (0) + 48;
s[1] = (0) + 48;
}
}
s.resize(8);
cout << s;
}
|
acc3d08b3c5dde2a0ac68bbab322dd8170b5b44d
|
5f3e48cbd471ff75f7ad93c4f27ef9c6ba2f2d72
|
/motor_on/motor_on.ino
|
9c80fe51a7bec35cd2e97362070f275e8fbc2493
|
[] |
no_license
|
seven320/-Target_on_with_Arduino
|
b96a5eda06c6c95f2fbbe0a2d31e7fe31d950253
|
e4bda452244d2ab4e00d0cf472e002adc0007890
|
refs/heads/master
| 2023-08-07T18:50:02.660157
| 2023-07-29T02:29:58
| 2023-07-29T02:29:58
| 198,784,036
| 1
| 0
| null | 2020-03-12T03:04:24
| 2019-07-25T07:49:15
|
C++
|
UTF-8
|
C++
| false
| false
| 891
|
ino
|
motor_on.ino
|
#include <Stepper.h>
#define MOTOR_1 (4) // blue
#define MOTOR_2 (5) // pink
#define MOTOR_3 (6) // yellow
#define MOTOR_4 (7) // orange
#define SW (3)
#define MOTOR_STEPS (2048)
// ライブラリが想定している配線が異なるので2番、3番を入れ替える
Stepper myStepper(MOTOR_STEPS, MOTOR_1, MOTOR_3, MOTOR_2, MOTOR_4);
void setup() {
pinMode(SW, INPUT);
myStepper.setSpeed(10);
}
void loop() {
// スイッチを押して離すとモーターを45°回転させる
while (!digitalRead(SW)) { delay(50); }
while (digitalRead(SW)) { delay(50); }
myStepper.step(256);
// 静止時の負荷が無く勿体無いので電流を止める
stopMotor();
}
// モーターへの電流を止める
void stopMotor() {
digitalWrite(MOTOR_1, LOW);
digitalWrite(MOTOR_2, LOW);
digitalWrite(MOTOR_3, LOW);
digitalWrite(MOTOR_4, LOW);
}
|
b4dc7f57536aec3702dffd667cb913ee5a844bad
|
6a99735bcda67e9ed2721c6ebecaa548096e3e38
|
/最小栈/minStack.cpp
|
e909fe9faaf3a4631b588cbdf176f4fa45b6f38b
|
[] |
no_license
|
ghworld/algorithm
|
39a89f4cbfaa5fb0a3d8c8e2818af8020df2e2a5
|
cfeb1557f8b42cf28313bd9d3f2aaa0f2e986e1c
|
refs/heads/master
| 2021-01-23T10:20:26.731427
| 2018-09-02T07:53:56
| 2018-09-02T07:53:56
| 93,052,202
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 220
|
cpp
|
minStack.cpp
|
//
// Created by guohao on 2/22/18.
//
//最小栈
#include <vector>
#include <iostream>
#include <stack>
typedef int ElemenType;
using namespace std;
class Solution {
void push(){};
ElemenType pop(){};
};
|
53286732cca62c3d7e9fc337419bb0ce9270521f
|
5178f07f43c968f8fba0975558b8d07d268d1cb6
|
/Core/src/Search.h
|
8b4ac19152f7875dd6cef04db32ca0a22dc36350
|
[] |
no_license
|
dominichofer/Cassandra_new
|
55adf1f487036f8b44875919e2d696222d96e51f
|
a85216f5e2658ebd0acd1dc40fe07f1fa42a4f62
|
refs/heads/master
| 2023-07-25T06:44:55.602042
| 2019-03-22T15:03:01
| 2019-03-22T15:03:01
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,032
|
h
|
Search.h
|
#pragma once
#include "Position.h"
#include <chrono>
#include <cstdint>
#include <memory>
class Engine;
namespace Search
{
constexpr int infinity = +65;
struct CSpecification
{
int8_t depth;
uint8_t selectivity;
CSpecification(int8_t depth, uint8_t selectivity);
static CSpecification SolveExact(CPosition pos) { return CSpecification(pos.EmptyCount(), 0); }
};
struct CResult
{
int8_t score;
std::size_t node_count;
std::chrono::nanoseconds duration;
CResult(int8_t score, std::size_t node_count, std::chrono::nanoseconds duration);
};
class CAlgorithm
{
protected:
std::shared_ptr<Engine> engine;
std::size_t node_counter = 0;
static int EvalGameOver(const CPosition&); // TODO: Remove!
public:
CAlgorithm(std::shared_ptr<Engine>);
virtual std::unique_ptr<CAlgorithm> Clone() const = 0;
virtual CResult Eval(const CPosition&, CSpecification) = 0;
virtual CResult Eval(const CPosition&);
std::size_t NodeCount() const { return node_counter; }
};
class oArchive;
struct ILog
{
struct CEntry
{
CPosition position;
std::size_t index;
int original_score;
CSpecification specification;
CResult result;
CEntry(CPosition position, std::size_t index, int original_score, CSpecification specification, CResult result)
: position(position), index(index), original_score(original_score), specification(specification), result(result)
{}
};
std::size_t index = 0;
virtual std::unique_ptr<ILog> Clone() const = 0;
virtual void push_back(CPosition, int original_score, CSpecification, CResult) = 0;
virtual void Serialize(oArchive&) const = 0;
};
class oArchive
{
public:
virtual ~oArchive() = default;
virtual void Header() {}
virtual void Footer() {}
virtual void Serialize(const ILog::CEntry&) = 0;
oArchive& operator<<(const ILog& obj) { obj.Serialize(*this); return *this; }
};
class CLogNull : public ILog
{
public:
std::unique_ptr<ILog> Clone() const override;
void push_back(CPosition, int, CSpecification, CResult) override {}
void Serialize(oArchive&) const override {}
};
class CLogCollector : public ILog
{
std::vector<CEntry> m_vec;
public:
CLogCollector() = default;
CLogCollector(const CLogCollector&);
std::unique_ptr<ILog> Clone() const override;
void push_back(CPosition pos, int original_score, CSpecification spec, CResult result) override { m_vec.emplace_back(pos, index, original_score, spec, result); }
void Serialize(oArchive& archive) const override { for (const auto& it : m_vec) archive.Serialize(it); }
};
class CLogPassThrough : public ILog
{
oArchive& m_archive;
public:
CLogPassThrough(oArchive& archive) : m_archive(archive) {}
CLogPassThrough(const CLogPassThrough&);
std::unique_ptr<ILog> Clone() const override;
void push_back(CPosition pos, int original_score, CSpecification spec, CResult result) override { m_archive.Serialize(CLogCollector::CEntry(pos, index, original_score, spec, result)); }
void Serialize(oArchive&) const override {}
};
}
|
de7e1efff8c99ea440e113b527056be05e61a497
|
41bcc244a2b1307ca4a15c6587cbdbb5bfc89690
|
/WorldSkillKorea/HowToPlay.h
|
248f3137079865ac18e139eb7d9cf24224bcb6b3
|
[] |
no_license
|
Dongjun-Jii/WorldSkillKorea_Daejeon
|
427ab8fc935f5fcb997dda849a770e4fdc07a741
|
2c446d068c323cd0cd6576f8ea31cfa17762424f
|
refs/heads/master
| 2023-01-24T13:05:01.940852
| 2017-05-19T06:50:42
| 2017-05-19T06:50:42
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 406
|
h
|
HowToPlay.h
|
#pragma once
#include "GameLevel.h"
#include "Background.h"
class HowToPlay : public GameLevel {
public:
HowToPlay() = delete;
HowToPlay(HowToPlay&) = delete;
HowToPlay(ID3D11Device* device);
virtual ~HowToPlay();
virtual void update(float deltaTime) override;
virtual void draw(ID3D11DeviceContext* deviceContext, CXMMATRIX orthoMatrix) override;
private:
Texture* bgTexture;
Background* bg;
};
|
08fd77555be8f96598d4ac00d12f8a2351325363
|
b3e525a3c48800303019adac8f9079109c88004e
|
/nic/metaswitch/stubs/hals/pds_ms_rtr_mac.cc
|
bf728753cdf3f6d44a1da2e90f2e08b846ca6cde
|
[] |
no_license
|
PsymonLi/sw
|
d272aee23bf66ebb1143785d6cb5e6fa3927f784
|
3890a88283a4a4b4f7488f0f79698445c814ee81
|
refs/heads/master
| 2022-12-16T21:04:26.379534
| 2020-08-27T07:57:22
| 2020-08-28T01:15:20
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 950
|
cc
|
pds_ms_rtr_mac.cc
|
//---------------------------------------------------------------
// {C} Copyright 2019 Pensando Systems Inc. All rights reserved
// Router MAC integration
//---------------------------------------------------------------
#include "nic/metaswitch/stubs/hals/pds_ms_rtr_mac.hpp"
#include <nar_fte.hpp>
#include <nar_arp_nl.hpp>
namespace pds_ms {
void rtr_mac_update(ATG_INET_ADDRESS *ip_address,
NBB_BYTE *mac_addr,
NBB_ULONG if_index,
const char *vrf_name,
bool is_delete)
{
NBS_ENTER_SHARED_CONTEXT(nar::Fte::proc_id());
NBS_GET_SHARED_DATA();
auto& nar_fte = nar::Fte::get();
nar::ArpNetlink *arp_netlink = nar_fte.get_arp_netlink();
arp_netlink->evpn_router_mac_arp_event(ip_address, mac_addr, if_index,
is_delete);
NBS_RELEASE_SHARED_DATA();
NBS_EXIT_SHARED_CONTEXT();
}
}
|
b9f60da1da9e7449705eeeb12ee2b23c2d48b955
|
dbe617f081a09df8698b70ec08af25dd827b3f2d
|
/algorithm/topology/Wedge/WMesh.cpp
|
899ea221ad6aba516efe1bcdb6010ebf6939c0e6
|
[] |
no_license
|
kabukunz/meshlib
|
827052ff3c11fea772deb85eb26ce934be79d12b
|
329d405dd210b2dde05cfe480a79b9c15ac01ffe
|
refs/heads/main
| 2023-06-16T00:44:54.397676
| 2021-07-09T10:31:15
| 2021-07-09T10:31:15
| 384,402,573
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,436
|
cpp
|
WMesh.cpp
|
/*!
* \file WMesh.cpp
* \brief Implement CWMesh class
* \author David Gu
* \date Document 10/11/2010
*
* Slice a mesh along its sharp edges to form a new open mesh.
*
*/
#include "WMesh.h"
using namespace MeshLib::Topology;
/*! CWedge constructor
* \param half_edge the first corner of the wedge
*/
//////////////////////////////////////////////////////////////////////////////////////////
// constructor
//////////////////////////////////////////////////////////////////////////////////////////
CWedge::CWedge(CSMesh * pMesh, CWedgeHalfEdge * half_edge)
:m_mesh(pMesh),m_vertex( m_mesh->halfedgeVertex( half_edge ) )
{
CWedgeEdge * edge = m_mesh->halfedgeEdge( half_edge );
//if the half_edge isBoundary, then it must be the most Ccwone
if( edge->boundary() || edge->sharp() )
{
if( edge->boundary() )
{
CWedgeVertex * pW = m_mesh->halfedgeTarget( half_edge );
assert( m_mesh->edgeHalfedge( edge,0 ) == m_mesh->vertexMostCcwInHalfEdge( pW ) );
}
/*
* build a half wedge
*/
CWedgeHalfEdge * he = m_mesh->edgeHalfedge( edge, 0 );
if( he->vertex() != m_vertex )
he = m_mesh->halfedgeSym( he );
m_mostCcwHEdge = he;
CWedgeHalfEdge * he_prev;
do{
he_prev = he;
he = m_mesh->vertexNextClwInHalfEdge( he );
}while( he != NULL && ! m_mesh->halfedgeEdge( he )->sharp() );
m_mostClwHEdge = he_prev;
}
else
{
/*
* build a full wedge
*/
CWedgeHalfEdge * he = m_mesh->vertexMostCcwInHalfEdge( m_vertex );
m_mostCcwHEdge = he;
m_mostClwHEdge = m_mesh->vertexNextCcwInHalfEdge( he );
}
};
/*-----------------------------------------------------------------------------------------------------------------
Constructor/ Destructor
------------------------------------------------------------------------------------------------------------------*/
/*! CWMesh constructor
*/
CWMesh::CWMesh()
{
}
/*! CWMesh constructor
* \param pMesh the input mesh
*/
CWMesh::CWMesh( CSMesh * pMesh )
{
m_pMesh = pMesh;
};
/*! CWMesh destructor
* release all the memories for the list of wedges.
*/
CWMesh::~CWMesh()
{
for( std::list<CWedge*>::iterator witer = m_wedges.begin() ; witer != m_wedges.end(); witer ++ )
{
CWedge * w = *witer;
delete w;
}
};
/*-----------------------------------------------------------------------------------------------------------------
Slice the mesh along sharp edges to form a new open mesh
------------------------------------------------------------------------------------------------------------------*/
/*! Slice the mesh along sharp edges to form a new open mesh.
*/
void CWMesh::Slice()
{
_construct();
_convert();
};
/*-----------------------------------------------------------------------------------------------------------------
Compute the topological valence of a vertex
------------------------------------------------------------------------------------------------------------------*/
int CWMesh::__topovalence( CWedgeVertex * vertex )
{
int valence = 0;
for( CSMesh::VertexEdgeIterator veiter( vertex ); !veiter.end(); ++ veiter)
{
CWedgeEdge * edge = *veiter;
if( edge->boundary() || edge->sharp() )
{
valence ++;
}
}
return valence;
};
/*-----------------------------------------------------------------------------------------------------------------
Construct a mesh, each vertex is an wedge
------------------------------------------------------------------------------------------------------------------*/
void CWMesh::_construct()
{
for( CSMesh::MeshVertexIterator viter( m_pMesh ); !viter.end(); ++ viter )
{
CWedgeVertex * vertex = *viter;
vertex->valence() = __topovalence( vertex );
if( vertex->valence() == 0 )
{
//find most ccw HEdge of vertex
CWedgeHalfEdge * he = m_pMesh->vertexMostCcwInHalfEdge(vertex);
assert( he != NULL );
//generate a new wedge
CWedge * wedge = new CWedge( m_pMesh, he );
assert( wedge );
m_wedges.push_back( wedge );
for( CSMesh::VertexInHalfedgeIterator vhiter( m_pMesh, vertex ); !vhiter.end(); vhiter ++ )
{
CWedgeHalfEdge * pH = *vhiter;
pH->wedge() = wedge;
}
}
else
{
//boundary vertex
//assume this rotate Clw, if the vertex is on the boundary,
//the first edge is the most Ccw Edge
CWedgeHalfEdge * he = m_pMesh->vertexMostCcwInHalfEdge( vertex );
CWedge * head = NULL;
CWedgeEdge * pE = m_pMesh->halfedgeEdge( he );
while( !pE->boundary() && !pE->sharp() )
{
he = m_pMesh->vertexNextClwInHalfEdge( he );
pE = m_pMesh->halfedgeEdge( he );
}
CWedgeHalfEdge * anchor = he;
while( true )
{
if( m_pMesh->halfedgeEdge( he )->boundary() || m_pMesh->halfedgeEdge( he )->sharp() )
{
//generate a wedge
CWedge * wedge = new CWedge( m_pMesh, he );
assert( wedge );
m_wedges.push_back( wedge );
//assign all corners' wedge
for( he = wedge->mostCcwHalfEdge(); he != wedge->mostClwHalfEdge(); he = m_pMesh->vertexNextClwInHalfEdge( he ) )
{
he->wedge() = wedge;
pE = m_pMesh->halfedgeEdge( he );
}
assert( he == wedge->mostClwHalfEdge() );
he->wedge() = wedge;
}
he = m_pMesh->vertexNextClwInHalfEdge( he ); //he->clw_rotate_about_target();
if( he == NULL && m_pMesh->isBoundary( vertex ) ) break;
if( he == anchor ) break;
}
}
}
};
/*-----------------------------------------------------------------------------------------------------------------
Convert wedge mesh to common mesh
------------------------------------------------------------------------------------------------------------------*/
void CWMesh::_convert()
{
int ind = 1;
for( std::list<CWedge*>::iterator witer = m_wedges.begin( ); witer != m_wedges.end(); witer++ )
{
CWedge * wedge = * witer;
CWedgeVertex * wvertex = m_wmesh.createVertex( ind ++ );
assert( wvertex );
wvertex->string()= wedge->vertex()->string();
wvertex->point() = wedge->vertex()->point();
wedge->wvertex() = wvertex;
wvertex->father() = wedge->vertex()->id();
//For Computing Tight Fundamental Group Generators
//wvertex->parent() = (wedge->vertex()->parent()!= 0)?wedge->vertex()->parent():wedge->vertex()->id();
}
int find = 1;
for( CSMesh::MeshFaceIterator fiter( m_pMesh ); !fiter.end(); ++ fiter )
{
CFace * f = *fiter;
std::vector<CWedgeVertex*> v;
for( CSMesh::FaceHalfedgeIterator fhiter( f ); !fhiter.end(); ++ fhiter )
{
CWedgeHalfEdge * he = *fhiter;
CWedge * w = he->wedge();
assert( w );
v.push_back( w->wvertex() );
}
CFace *wf = m_wmesh.createFace(v,find++);
wf->string() = f->string();
}
for( CSMesh::MeshEdgeIterator eiter( &m_wmesh); !eiter.end(); ++ eiter )
{
CWedgeEdge * e = *eiter;
CWedgeVertex * v1 = m_wmesh.edgeVertex1( e );
CWedgeVertex * v2 = m_wmesh.edgeVertex2( e );
int f1 = v1->father();
int f2 = v2->father();
CWedgeVertex * fv1 = m_pMesh->idVertex( f1 );
CWedgeVertex * fv2 = m_pMesh->idVertex( f2 );
CWedgeEdge * pFE = m_pMesh->vertexEdge( fv1, fv2 );
e->string() = pFE->string();
if( e->boundary() )
{
v1->boundary() = true;
v2->boundary() = true;
}
}
//Arrange the boundary half_edge of boundary vertices, to make its halfedge
//to be the most ccw in half_edge
for(std::list<CWedgeVertex*>::iterator viter = m_wmesh.vertices().begin(); viter != m_wmesh.vertices().end() ; ++ viter )
{
CWedgeVertex * v = *viter;
if( !v->boundary() ) continue;
CWedgeHalfEdge * he = m_wmesh.vertexHalfedge( v );
while( m_wmesh.halfedgeSym( he ) != NULL )
{
he = m_wmesh.vertexNextCcwInHalfEdge( he );
}
v->halfedge() = he;
}
//copy corner information
for( CSMesh::MeshFaceIterator fiter( &m_wmesh ); !fiter.end(); ++ fiter )
{
CFace * f = *fiter;
for( CSMesh::FaceHalfedgeIterator fhiter( f ); !fhiter.end(); ++ fhiter )
{
CWedgeHalfEdge * he = *fhiter;
CWedgeVertex * target = m_wmesh.halfedgeTarget( he );
CWedgeVertex * source = m_wmesh.halfedgeSource( he );
int ft = target->father();
int fs = source->father();
CWedgeVertex * pWT = m_pMesh->idVertex( ft );
CWedgeVertex * pWS = m_pMesh->idVertex( fs );
CWedgeHalfEdge * pWH = m_pMesh->vertexHalfedge( pWS, pWT );
if( pWH == NULL )
{
printf("Face ID %d Error\n", f->id() );
}
assert( pWH != NULL );
he->string() = pWH->string();
}
}
};
|
b78918081d4c281105e09cd90b9be8f410325d5e
|
ae7ec837eb954d7be7878f367aa7afb70d1a3897
|
/litwindow/result.hpp
|
1cd2f11177467a63a3f3cc9a46335381eaae3dee
|
[
"MIT",
"BSD-3-Clause"
] |
permissive
|
hajokirchhoff/litwindow
|
0387bd1e59200eddb77784c665ba921089589026
|
7f574d4e80ee8339ac11c35f075857c20391c223
|
refs/heads/master
| 2022-06-18T20:15:21.475921
| 2016-12-28T18:16:58
| 2016-12-28T18:16:58
| 77,551,164
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,025
|
hpp
|
result.hpp
|
/*
* Copyright 2004, Hajo Kirchhoff - Lit Window Productions, http://www.litwindow.com
* This file is part of the Lit Window Library. All use of this material - copying
* in full or part, including in other works, using in non-profit or for-profit work
* and other uses - is governed by the licence contained in the Lit Window Library
* distribution, file LICENCE.TXT
* $Id: result.hpp,v 1.2 2006/01/17 08:55:22 hajo Exp $
*/
#ifndef _RESULT_HPP
#define _RESULT_HPP
#ifdef _MSC_VER
#pragma once
#endif
namespace litwindow {
#define ASSERT assert
struct result_base_t
{
};
template <class ResultCode>
class result_t:public result_base_t
{
public:
result_t()
{
init();
}
result_t(const ResultCode &_hr)
{
init();
set_result_code(_hr);
}
result_t(const result_t<ResultCode> &_hr)
{
init();
set_result_code(_hr);
_hr.m_was_matched=true;
}
~result_t(void)
{
if (!m_was_matched && !std::uncaught_exception())
raise_exception_on_failure();
}
result_t& operator=(ResultCode _hr)
{
set_result_code(_hr);
return *this;
}
result_t& operator=(const result_t<ResultCode> &_hr)
{
set_result_code(_hr);
_hr.m_was_matched=true;
return *this;
}
bool operator==(ResultCode _hr) const
{
bool r= (hr==_hr);
m_was_matched= (m_was_matched || r);
return r;
}
bool operator!=(ResultCode _hr) const
{
return hr!=_hr;
}
bool operator!() const
{
return failed();
}
void clear() // reset error code
{
init();
}
void set_result_code(ResultCode _hr)
{
if (!m_was_matched)
raise_exception_on_failure();
hr=_hr;
if (!success())
trace_error();
m_was_matched=false;
}
ResultCode get_result_code() const
{
m_was_matched=true;
return hr;
}
bool failed() const
{
m_was_matched=true;
return is_failure();
}
bool success() const
{
m_was_matched=true;
return !is_failure();
}
void assert_success() const
{
raise_exception_on_failure();
}
operator ResultCode() const
{
return hr;
}
void trace_error() const
{
ASSERT("Not implemented"!=0);
}
result_t<ResultCode>& ignore() // call this to explicitly ignore this error
{
m_was_matched=true;
return *this;
}
protected:
bool is_failure() const
{
return hr!=0;
}
void raise_exception_on_failure() const
{
if (!success()) {
trace_error();
ASSERT(success());
throw *this;
}
}
void init()
{
hr=0;
m_was_matched=true;
}
mutable bool m_was_matched;
ResultCode hr;
};
//-----------------------------------------------------------------------------------------------------------//
//-----------------------------------------------------------------------------------------------------------//
///@name Commonly used WIN32 specializations
//@{
#if defined(_WIN32_WINDOWS)
#ifdef _ATL_VER
template <>
inline void result_t<HRESULT>::trace_error() const
{
AtlTraceErrorRecords(hr);
}
template <> inline bool result_t<HRESULT>::is_failure() const
{
return FAILED(hr);
}
#endif
template<> inline bool result_t<BOOL>::is_failure() const
{
return !hr;
}
template<> inline bool result_t<UINT_PTR>::is_failure() const
{
return hr==0;
}
template<> inline void result_t<BOOL>::trace_error() const
{
// AtlTrace("result_t<BOOL>::trace_error: The result returned from the function was FALSE! LastError was %08lx.\n", ::GetLastError());
}
template<> inline void result_t<BOOL>::init()
{
hr=TRUE; m_was_matched=true;
}
template<> inline void result_t<UINT_PTR>::trace_error() const
{
// AtlTrace("result_t<UINT_PTR>::trace_error: The function call returned 0. LastError was %08lx.\n", ::GetLastError());
}
template<> inline void result_t<UINT_PTR>::init()
{
hr=0; m_was_matched=true;
}
typedef result_t<HRESULT> HResult;
typedef result_t<BOOL> BResult;
#endif
//@}
template <> inline bool result_t<bool>::is_failure() const
{
return !hr;
}
typedef result_t<bool> bool_result;
typedef result_t<int> int_result;
template <> inline result_t<bool>::operator bool() const
{
m_was_matched=true; return hr;
}
} // end namespace
#endif
|
2b80a0805ca2282b11de7c2c47ce91371d4d5313
|
377b1a9f30df8966e8b0f86500848465eb39d7f2
|
/src/systems/Updater.cpp
|
810125298e95fa7649737d99c4f56ecc0e721c74
|
[] |
no_license
|
mdzidko/Simple2DEngine
|
08194eb35227687cc474a97be188ebe81117779e
|
6ffad5df3498b3d1e1573ba1d844959be18096ec
|
refs/heads/master
| 2021-04-06T00:37:17.662702
| 2018-08-13T20:15:26
| 2018-08-13T20:15:26
| 125,253,605
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 318
|
cpp
|
Updater.cpp
|
#include <algorithm>
#include "Updater.h"
void Updater::Refresh()
{
entities.erase(std::remove_if(entities.begin(), entities.end(),
[](Entity* ent) { return !ent->IsAlive(); }), entities.end());
}
void Updater::AddEntityToContainer(Entity *entity)
{
entities.push_back(entity);
}
|
4a4259a206caa15b538b100211612d9d1b11cbfd
|
2acbfdf0d2bb09ba535d71e5f00a2a41335bc6f5
|
/headers/HighScoreSubmission.hpp
|
70d124b8a2f572d99db4664896057c21f2e8472e
|
[] |
no_license
|
Adikso/NecroDancerHeaders
|
d5ddc01df881d082230506ddc2bdfaf3e56c0df3
|
228e14c0e0420105366b552228e25a8b6a63b8c0
|
refs/heads/master
| 2020-04-02T23:03:05.824455
| 2018-11-16T20:00:27
| 2018-11-16T20:00:27
| 154,854,162
| 5
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,393
|
hpp
|
HighScoreSubmission.hpp
|
// Generated automatically. Do not edit!
#ifndef _HighScoreSubmission_
#define _HighScoreSubmission_
class String;
#include "Object.hpp"
class HighScoreSubmission : public Object {
public:
String * pendingSubmitLeaderboard;
int submissionAttemptNumber;
bool submitted;
int pendingSubmitScore;
int pendingSubmitZone;
int pendingSubmitLevel;
String * data;
// Wrappers
HighScoreSubmission(int s, int z, int l, String * lb, int sa, String * dt) {
ptr::CSTR_HighScoreSubmission(this);
ptr::New(this, s, z, l, lb, sa, dt);
}
inline HighScoreSubmission * New(int s, int z, int l, String * lb, int sa, String * dt) { return ptr::New(this, s, z, l, lb, sa, dt); }
inline HighScoreSubmission * _new2() { return ptr::_new2(); }
inline void _mark() { ptr::_mark(); }
class ptr {
public:
static HighScoreSubmission * (*New)(HighScoreSubmission * self, int s, int z, int l, String * lb, int sa, String * dt);
static HighScoreSubmission * (*_new2)();
static void (*_mark)();
static void (*CSTR_HighScoreSubmission)(HighScoreSubmission * self);
};
};
#ifdef _WIN32
inline HighScoreSubmission * (*HighScoreSubmission::ptr::New)(HighScoreSubmission * self, int s, int z, int l, String * lb, int sa, String * dt) = (HighScoreSubmission * (*)(HighScoreSubmission * self, int s, int z, int l, String * lb, int sa, String * dt)) 0x66f750;
inline HighScoreSubmission * (*HighScoreSubmission::ptr::_new2)() = (HighScoreSubmission * (*)()) 0x0;
inline void (*HighScoreSubmission::ptr::_mark)() = (void (*)()) 0x0;
inline void (*HighScoreSubmission::ptr::CSTR_HighScoreSubmission)(HighScoreSubmission * self) = (void (*)(HighScoreSubmission * self)) 0x66f540;
#endif
#ifdef __linux__
inline HighScoreSubmission * (*HighScoreSubmission::ptr::New)(HighScoreSubmission * self, int s, int z, int l, String * lb, int sa, String * dt) = (HighScoreSubmission * (*)(HighScoreSubmission * self, int s, int z, int l, String * lb, int sa, String * dt)) 0x81db6b0;
inline HighScoreSubmission * (*HighScoreSubmission::ptr::_new2)() = (HighScoreSubmission * (*)()) 0x81db730;
inline void (*HighScoreSubmission::ptr::_mark)() = (void (*)()) 0x8077f60;
inline void (*HighScoreSubmission::ptr::CSTR_HighScoreSubmission)(HighScoreSubmission * self) = (void (*)(HighScoreSubmission * self)) 0x81db600;
#endif
#endif
|
69d4a93f7d52a68be27c9bc475e766c2e502e3f5
|
680440f5e59eb2157c1ecb41fd891880ac47c459
|
/XJOI/Level1/XJOI1203 数组-密码破译/password.cpp
|
a01ab2f87388c1b20a982b7cb1235baf51c581ba
|
[] |
no_license
|
Skywt2003/codes
|
a705dc3a4f5f79d47450179fc597bd92639f3d93
|
0e09198dc84e3f6907a11b117a068f5e0f55ca68
|
refs/heads/master
| 2020-03-29T09:29:54.014364
| 2019-11-15T12:39:47
| 2019-11-15T12:39:47
| 149,760,952
| 6
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 288
|
cpp
|
password.cpp
|
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
const int maxn=105;
int main(){
char ch=getchar();
while (ch!=-1){
if (ch>='a'&&ch<='z'){
if (ch=='z') putchar('a'); else putchar(ch+1);
} else putchar(ch);
ch=getchar();
}
return 0;
}
|
4403f48da3ac21b7f84a22bc7b1e846a4b46ff9f
|
953f2b90c99d4dc305dd02c141efce2e0c308199
|
/ardtool.cpp
|
265dd270be03831c5a647d856aef3e786c53a4a8
|
[] |
no_license
|
Phitherek/ardtool
|
a8684cce976102001715314a631ba2eba27262d8
|
2887170292edbff289a05a0cc10585545bf409b5
|
refs/heads/master
| 2021-03-12T20:06:45.964557
| 2014-10-09T00:10:52
| 2014-10-09T00:11:25
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,809
|
cpp
|
ardtool.cpp
|
#include "ConfigFile.h"
#include "Project.h"
#include "Exceptions.h"
#include <iostream>
#include <cstdlib>
#include <string>
#include <exception>
#include <unistd.h>
using namespace std;
using namespace ARDTool;
void show_help(int argc, char** argv) {
cout << "Usage: " << argv[0] << " <project_name|command>" << endl << endl;
cout << "Available commands:" << endl;
cout << "help - Shows this message" << endl;
}
int main(int argc, char** argv) {
cout << "ARDTool v. 0.2 (C) 2014 by Phitherek_" << endl;
if(argc == 2) {
string arg1 = "";
arg1 += argv[1];
if(arg1 == "help") {
show_help(argc, argv);
} else {
try {
string home = getenv("HOME");
string confpath = home;
confpath += "/.ardtool/config";
ConfigFile cf(confpath);
Project p = cf.getProjectByName(argv[1]);
if(!p.valid()) {
cout << "Could not find project " << argv[1] << " in the configuration! Exiting..." << endl;
exit(EXIT_FAILURE);
} else {
cout << "Processing " << p.getName() << "..." << endl;
cout << "Changing directory to: " << p.getPath() << "..." << endl;
chdir(p.getPath().c_str());
cout << "Running in environment: " << p.getEnv() << "..." << endl;
string bundle_cmd = "bundle";
if(p.getRVM() != "") {
cout << "Using RVM environment: " << p.getRVM() << "..." << endl;
string rvm_path = getenv("rvm_path");
bundle_cmd = rvm_path;
bundle_cmd += "/wrappers/";
bundle_cmd += p.getRVM();
bundle_cmd += "/bundle";
}
while(!p.modulesEnd()) {
string modname = p.getNextModule();
cout << "Running module: " << modname << endl;
if(modname == "bundle") {
string cmd = "";
cmd += "RAILS_ENV=";
cmd += p.getEnv();
cmd += " ";
cmd += bundle_cmd;
cmd += " install";
cout << "Executing: " << cmd << endl;
system(cmd.c_str());
} else if(modname == "db") {
string cmd = "";
cmd += "RAILS_ENV=";
cmd += p.getEnv();
cmd += " ";
cmd += bundle_cmd;
cmd += " exec rake db:migrate";
cout << "Executing: " << cmd << endl;
system(cmd.c_str());
} else if(modname == "assets") {
string cmd = "";
cmd += "RAILS_ENV=";
cmd += p.getEnv();
cmd += " ";
cmd += bundle_cmd;
cmd += " exec rake assets:clean";
cout << "Executing: " << cmd << endl;
system(cmd.c_str());
cmd = "";
cmd += "RAILS_ENV=";
cmd += p.getEnv();
cmd += " ";
cmd += bundle_cmd;
cmd += " exec rake assets:precompile";
cout << "Executing: " << cmd << endl;
system(cmd.c_str());
} else if(modname == "restart") {
string cmd = "touch tmp/restart.txt";
cout << "Executing: " << cmd << endl;
system(cmd.c_str());
} else if(modname == "custom") {
while(!p.customEnd()) {
string cmd = p.getNextCustom();
cout << "Executing: " << cmd << endl;
system(cmd.c_str());
}
}
}
}
cout << "ARDTool finished!" << endl;
} catch(exception& e) {
cout << "Exception caught: " << e.what() << endl;
exit(EXIT_FAILURE);
}
}
} else {
show_help(argc, argv);
}
return EXIT_SUCCESS;
}
|
e908cabdbbe9d133109eb24ba4304cfae81daa30
|
7f25ac596812ed201f289248de52d8d616d81b93
|
/Manjuska/light1215.cpp
|
4401ec75d759769700c51fe0aeb3a799da50a40d
|
[] |
no_license
|
AplusB/ACEveryDay
|
dc6ff890f9926d328b95ff536abf6510cef57eb7
|
e958245213dcdba8c7134259a831bde8b3d511bb
|
refs/heads/master
| 2021-01-23T22:15:34.946922
| 2018-04-07T01:45:20
| 2018-04-07T01:45:20
| 58,846,919
| 25
| 49
| null | 2016-07-14T10:38:25
| 2016-05-15T06:08:55
|
C++
|
UTF-8
|
C++
| false
| false
| 618
|
cpp
|
light1215.cpp
|
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
long long gcd(long long a,long long b)
{
return b == 0 ? a : gcd(b, a%b);
}
long long lcm(long long a,long long b)
{
return a*b / gcd(a, b);
}
int main()
{
int T, num = 1;
cin >> T;
long long a, b, c, m, t, g, l;
while(T--)
{
cin >> a >> b >> l;
m = lcm(a, b);
if(l%m!=0||m>l)
{
cout << "Case " << num++ << ": " << "impossible" << endl;
}
else
{
c = l / m;
t = gcd(c, m);
while(t!=1)
{
c = c*t;
m /= t;
t = gcd(c, m);
}
cout << "Case " << num++ << ": " << c << endl;
}
}
return 0;
}
|
0bf90fbc442fb427563862ab2fc086e4edddf60f
|
986964448a8813d5b9116b4f984543db043b6224
|
/src/ui/player_edit_view/music_slider.h
|
689ff537b37b70dbec777ddb5036cf6848f5c694
|
[] |
no_license
|
Lenium37/SigLight
|
3c34c25a3ab673012685b3d535467049bed90bcf
|
cdc639f7667a3ee082446925fd7c4b9c9e7315df
|
refs/heads/master
| 2021-07-12T04:16:35.385565
| 2020-10-15T12:01:50
| 2020-10-15T12:01:50
| 213,935,458
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 538
|
h
|
music_slider.h
|
#ifndef MUSIC_SLIDER_H
#define MUSIC_SLIDER_H
#include <QObject>
#include <QGraphicsItem>
#include <QPainter>
class Music_slider : public QGraphicsItem
{
Q_INTERFACES(QGraphicsItem)
public:
Music_slider(int h);
QRectF boundingRect() const;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
void set_height(int height);
void position_changed(qint64 position);
void set_time(quint32 t);
private:
int m_height;
quint32 m_time;
};
#endif // MUSIC_SLIDER_H
|
f14e46d6cdc53c274deffde03773128c40d37d5c
|
649242b5dc401b2626c1d2b8de09656867299b0e
|
/modules/segment-tree-app/src/segment_tree.cpp
|
b4fd51852e94d47264d99d76b0144d03595f02de
|
[
"CC-BY-4.0"
] |
permissive
|
LuckyDmitry/devtools-course-practice
|
45db4f988b38c08365ed8b96f2b6cf3ae8414ae6
|
2384acf591161b8a90c3548929b2425a72d93c50
|
refs/heads/master
| 2022-10-06T03:50:15.806822
| 2020-06-07T17:42:39
| 2020-06-07T17:42:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,191
|
cpp
|
segment_tree.cpp
|
// Copyright 2020 Boganov Sergei
#include "include/segment_tree.h"
#include <vector>
#include <algorithm>
#include <string>
#include <climits>
SegmentTree::SegmentTree(int size) {
if (size <= 0) {
throw std::string("Cannot be negative or zero size");
} else {
_size = size;
tree.resize(4*size);
}
}
SegmentTree::SegmentTree(const std::vector<int>& input,
std::string operation) {
int size = static_cast<int>(input.size());
if (size <= 0) {
throw std::string("Cannot be negative or zero size");
} else {
_size = size;
_operation = operation;
tree.resize(4*size);
build(input, 1, 0, size - 1);
}
}
int SegmentTree::gcd(int x, int y) const {
while (x > 0 && y > 0) {
if (x >= y) {
x %= y;
} else {
y %= x;
}
}
return x + y;
}
int SegmentTree::op(int x, int y) const {
if (_operation == "+") {
return x + y;
} else if (_operation == "max") {
return std::max(x, y);
} else if (_operation == "min") {
return std::min(x, y);
} else if (_operation == "gcd") {
return gcd(x, y);
} else {
throw std::string("Cannot be this operation");
}
}
void SegmentTree::build(const std::vector<int>& arr, int index,
int left, int right) {
if (left == right) {
tree[index] = arr[left];
} else {
int mid = left + (right - left)/2;
build(arr, 2*index, left, mid);
build(arr, 2*index + 1, mid + 1, right);
tree[index] = op(tree[2*index], tree[2*index + 1]);
}
}
std::vector<int> SegmentTree::Get() const {
return tree;
}
int SegmentTree::query(int index, int l, int r, int left, int right) const {
if (left > right) {
return (_operation == "min" ? INT_MAX : 0);
} else if (left == l && right == r) {
return tree[index];
} else {
int mid = l + (r - l)/2;
return op(query(2*index, l, mid, left, std::min(right, mid)),
query(2*index + 1, mid + 1, r, std::max(left, mid + 1), right));
}
}
int SegmentTree::query(int left, int right) const {
if (left < 0 || right < 0) {
throw std::string("left or right interval cannot be negative");
}
if (right < left) {
throw std::string("left interval cannot be > than right");
}
if (right >= _size) {
throw std::string("right interval cannot be > that size");
}
return query(1, 0, _size - 1, left, right);
}
void SegmentTree::update(int index, int l, int r, int change_index, int value) {
if (l == r) {
tree[index] = value;
return;
}
int mid = l + (r - l)/2;
if (change_index <= mid) {
update(2*index, l, mid, change_index, value);
} else {
update(2*index + 1, mid + 1, r, change_index, value);
}
tree[index] = op(tree[2*index], tree[2*index + 1]);
}
void SegmentTree::update(int change_index, int value) {
if (change_index < 0 || change_index >= _size) {
throw std::string("Index cannot be zero or > size");
}
update(1, 0, _size - 1, change_index, value);
}
|
44e7b5aaef4f0da6d81926e8393a914b547455ee
|
06c12a65e1c6c8dd67b27db1d8aabd9589c206dd
|
/FW/Project/GameEngine/Source/Core/Memory/Memory.cpp
|
b814ebed537809c5497a4c8cb718c01eefebed37
|
[] |
no_license
|
aik6980/GameFrameworkCpp
|
2b64b9e49033199c6eb021a106e5d264c1e2044d
|
c7ce5efd63ab5251800d84477e4a5cfaf56119c3
|
refs/heads/master
| 2021-01-19T10:58:50.317980
| 2014-07-16T07:55:23
| 2014-07-16T07:55:23
| 7,741,813
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 215
|
cpp
|
Memory.cpp
|
#include "stdafx.h"
#include "Memory.h"
void* operator new (size_t size, size_t alignment)
{
return _aligned_malloc(size, alignment);
}
void operator delete (void* ptr, size_t alignment)
{
_aligned_free(ptr);
}
|
cfde13c637f6302864d7d3ff673bffa12564a262
|
dbbee1b50e56ca17c48577062a36bc936dda72aa
|
/src/x509/error.cpp
|
1399ed3347dd3db98a63b895f667057e1791c9ff
|
[] |
no_license
|
robertblackwell/x509_certificate_library
|
11afa79e610ed3837c9be9327c41633b409cd6d4
|
6efc7cd37ea020a8233b775907e81d27ba9fa430
|
refs/heads/master
| 2021-10-11T09:07:23.215115
| 2021-10-03T04:33:50
| 2021-10-03T04:33:50
| 240,992,929
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,765
|
cpp
|
error.cpp
|
//
// error.cpp
// openssl_10_6
//
// Created by ROBERT BLACKWELL on 10/26/17.
// Copyright © 2017 Blackwellapps. All rights reserved.
//
#include <stdio.h>
#include <string>
#include <stdlib.h>
#include <malloc.h>
#include <sstream>
#include <openssl/bio.h>
#include <exception>
#include <openssl/err.h>
#include <cert/error.hpp>
/**
* Erro handler for Cert functions
*/
void Cert::errorHandler (std::string func, std::string file, int lineno, std::string msg)
{
std::string message(msg);
std::stringstream messageStream;
messageStream << "Error in function: " << func << " file: " << file << " at lineNo: " << lineno << std::endl << "Message: [" << message << "]" ;
throw Cert::Exception(messageStream.str());
}
/**
* Erro handler for Cert::x509 functions
*/
void Cert::x509::errorHandler (std::string func, std::string file, int lineno, std::string msg)
{
// char buf[100001];
std::string message(msg);
std::stringstream messageStream;
messageStream << "Error in function: " << func << " file: " << file << " at lineNo: " << lineno << std::endl << "Message: [" << message << "]" ;
long e = ERR_peek_last_error();
const char* err_str = ERR_reason_error_string(e);
std::string open_ssl_message = "NO OPENSSL ERROR";
if (err_str == NULL) {
} else {
open_ssl_message = std::string(err_str);
}
messageStream << std::endl << "OpenSSL error message is : [" << open_ssl_message <<"]" << std::endl;
// ERR_print_errors_fp (stderr);
throw Cert::Exception(messageStream.str());
}
using namespace Cert;
Cert::Exception::Exception(std::string aMessage) : x509_ErrMessage(aMessage){}
const char* Cert::Exception::what() const noexcept{ return x509_ErrMessage.c_str(); }
|
bb9dfd1ec2ba9d355834ca58fa389415aa8ec5f8
|
dbc0e3582d65bcf9d8fba29d872d6407454f9e28
|
/CodeForces/1263A.cpp
|
0f079292b1ada41b6886e47bf0f39466432c0f2a
|
[] |
no_license
|
sirAdarsh/CP-files
|
0b7430e2146620535451e0ab8959f70047bd7ea2
|
8d411224293fec547a3caa2708eed351c977ebed
|
refs/heads/master
| 2023-04-05T09:07:21.554361
| 2021-04-08T19:57:33
| 2021-04-08T19:57:33
| 297,582,418
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 789
|
cpp
|
1263A.cpp
|
/*----- || Hare Krishna || -----*/
/* "WHY DO WE FALL, BRUCE?" */
#include<bits/stdc++.h>
#define ll long long
#define endl '\n'
#define elif else if
#define PI 3.1415926535897932384
#define MOD 1000000007
using namespace std;
char alpha[26] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
string s;
int t;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
cin >> t;
while(t--){
int a[3];
for(int i=0; i<3; i++){
cin >> a[i];
}
sort(a,a+3);
int s = a[1]+a[2];
int days = a[0];
s -= a[0];
a[1]=min(a[1],s/2);
a[2]= s-a[1] ;
days += min(a[1],a[2]);
cout << days << endl;
}
}
|
1140956fee57e95ad2eec357945a0a6325118ff1
|
3195a10dfa0cb342135634b7dfd539f4dc799c25
|
/include/Entities/Sapheer.h
|
6bc160e16477f9cf0c591837bff7e8a989c88ce4
|
[] |
no_license
|
antonioganea/CrystalDM
|
d5c04c4a4157498054701d156f10f561cea0422a
|
46e3e6a898fe61efff39f622b153b00dd8eaf318
|
refs/heads/master
| 2021-01-16T17:58:43.127833
| 2017-10-21T18:13:39
| 2017-10-21T18:13:39
| 100,030,783
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,237
|
h
|
Sapheer.h
|
#ifndef SAPHEER_H
#define SAPHEER_H
#include "Crystal.h"
#include "RubieLaser.h"
#include <SFML/Graphics/Sprite.hpp>
#include "Particle.h"
class Sapheer : public Crystal{
public:
Sapheer();
void draw();
void update( float dt );
bool isDead();
bool dead;
void input( const sf::Event & event );
sf::Vector2f getPosition();
void setPosition ( const sf::Vector2f& position );
void setSyncable( bool syncable );
void move();
void attack();
void ultimate();
void pushCrystal( const sf::Vector2f& velocity );
bool syncable;
float getRadius();
bool isCollidable();
void markDead();
int syncer;
void setSyncer( int syncer );
int getSyncer();
protected:
private:
const static float acceleration;
const static float friction;
sf::Sprite sprite;
sf::RectangleShape * shield;
void throwShield();
Particle * shootParticles;
void shoot();
sf::Vector2f velocity;
int w,a,s,d;
int cooldown, animationTimer, shieldTimer;
};
#endif // SAPHEER_H
|
2d25d4e4b193ae3fb3d0c4e1b61a8dd3d99ef057
|
5241a49fc86a3229e1127427146b5537b3dfd48f
|
/src/Sparrow/Tests/TimeDependent/CISTestCalculation.cpp
|
302885b2d29f985da611f9139863da9be90d29aa
|
[
"BSD-3-Clause"
] |
permissive
|
qcscine/sparrow
|
05fb1e53ce0addc74e84251ac73d6871f0807337
|
f1a1b149d7ada9ec9d5037c417fbd10884177cba
|
refs/heads/master
| 2023-05-29T21:58:56.712197
| 2023-05-12T06:56:50
| 2023-05-12T06:56:50
| 191,568,488
| 68
| 14
|
BSD-3-Clause
| 2021-12-15T08:19:47
| 2019-06-12T12:39:30
|
C++
|
UTF-8
|
C++
| false
| false
| 32,106
|
cpp
|
CISTestCalculation.cpp
|
/**
* @file
* @copyright This code is licensed under the 3-clause BSD license.\n
* Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n
* See LICENSE.txt for details.
*/
#include <Core/Interfaces/Calculator.h>
#include <Core/ModuleManager.h>
#include <Sparrow/Implementations/Dftb/Dftb2/Wrapper/DFTB2MethodWrapper.h>
#include <Sparrow/Implementations/Exceptions.h>
#include <Sparrow/Implementations/Nddo/Am1/Wrapper/AM1TypeMethodWrapper.h>
#include <Sparrow/Implementations/Nddo/Pm6/Wrapper/PM6MethodWrapper.h>
#include <Sparrow/Implementations/Nddo/TimeDependent/LinearResponse/CISLinearResponseTimeDependentCalculator.h>
#include <Sparrow/Implementations/TimeDependent/DiagonalPreconditionerEvaluator.h>
#include <Utils/CalculatorBasics.h>
#include <Utils/Constants.h>
#include <Utils/IO/ChemicalFileFormats/XyzStreamHandler.h>
#include <Utils/Scf/LcaoUtils/SpinMode.h>
#include <Utils/Settings.h>
#include <Utils/UniversalSettings/SettingsNames.h>
#include <gmock/gmock.h>
#include <chrono>
using namespace testing;
namespace Scine {
namespace Sparrow {
/**
* Reference values for this test are calculated with the CIS module of the ORCA 4.1.0
* software.
* Example input file:
*
* !PM3 RHF PRINTMOS
* %cis
* NRoots 20
* triplets true
* end
*
* *xyz 0 1
* C 0.000000 0.000000 0.000000
* O 0.000000 0.000000 1.212200
* H 0.937197 0.000000 -0.584262
* H -0.937197 0.000000 -0.584262
* *
*
*/
class ACISTestCalculation : public Test {
public:
std::shared_ptr<Core::Calculator> calculator;
std::shared_ptr<Core::Calculator> calculatorH;
std::shared_ptr<Core::Calculator> calculatorHF;
std::shared_ptr<Core::Calculator> calculatorCH3;
std::shared_ptr<Core::Calculator> calculatorPor;
std::shared_ptr<Core::Calculator> calculatorOxa;
std::shared_ptr<Core::Calculator> methodWrapper_;
std::shared_ptr<Core::CalculatorWithReference> polymorphicCIS;
std::shared_ptr<Core::CalculatorWithReference> interfaceCIS;
CISLinearResponseTimeDependentCalculator CISCalculator;
protected:
void SetUp() final {
std::stringstream ss("4\n\n"
"C 0.000000 0.000000 0.000000\n"
"O 0.000000 0.000000 1.212200\n"
"H 0.937197 0.000000 -0.584262\n"
"H -0.937197 0.000000 -0.584262");
std::stringstream ssHH("2\n\n"
"H 0.11827444 0.000000 0\n"
"H 0.88172556 0.000000 0");
std::stringstream ssHF("2\n\n"
"H 0.01720534 0.00000 0.00000000\n"
"F 0.98279466 0.00000 0.00000000");
std::stringstream ssPorphyrine("36\n\n"
"N -0.3782 1.9570 -0.0014\n"
"N 1.9571 0.3783 0.0000\n"
"N -1.9571 -0.3782 0.0007\n"
"N 0.3782 -1.9570 0.0017\n"
"C 0.4931 2.9223 -0.0010\n"
"C 2.9224 -0.4930 0.0009\n"
"C -2.9223 0.4931 0.0003\n"
"C -0.4931 -2.9224 0.0002\n"
"C -1.6076 2.5726 -0.0008\n"
"C 2.5726 1.6075 0.0001\n"
"C -2.5725 -1.6075 0.0007\n"
"C 1.6075 -2.5726 0.0002\n"
"C 1.9692 2.8039 -0.0005\n"
"C 2.8039 -1.9692 0.0003\n"
"C -2.8040 1.9692 -0.0001\n"
"C -1.9693 -2.8039 0.0004\n"
"C -0.0844 4.2732 -0.0003\n"
"C 4.2734 0.0844 0.0012\n"
"C -4.2733 -0.0843 0.0005\n"
"C 0.0844 -4.2734 -0.0023\n"
"C -1.3904 3.9982 -0.0001\n"
"C 3.9982 1.3903 0.0007\n"
"C -3.9982 -1.3903 0.0007\n"
"C 1.3904 -3.9983 -0.0022\n"
"H 2.5488 3.7221 -0.0005\n"
"H 3.7220 -2.5487 -0.0012\n"
"H -3.7221 2.5488 0.0007\n"
"H -2.5489 -3.7221 0.0002\n"
"H 0.4202 5.2213 0.0003\n"
"H 5.2214 -0.4202 0.0017\n"
"H -5.2213 0.4203 0.0005\n"
"H -0.4202 -5.2214 -0.0039\n"
"H -2.1793 4.7348 0.0005\n"
"H 4.7349 2.1792 0.0007\n"
"H -4.7349 -2.1793 0.0009\n"
"H 2.1793 -4.7349 -0.0038");
std::stringstream ssOxadiazole("31\n\n"
"C -4.72638293 1.42028071 0.21488213\n"
"C -6.07154217 1.24300816 -0.11971503\n"
"C -6.54204856 -0.01457229 -0.47681026\n"
"C -5.66996128 -1.09762221 -0.49789970\n"
"C -4.33798633 -0.92650673 -0.14379704\n"
"C -3.84431524 0.32898246 0.22432885\n"
"H -6.75814904 2.09751616 -0.10053013\n"
"H -7.59688216 -0.15140007 -0.73854141\n"
"H -6.03399299 -2.09011559 -0.78430435\n"
"H -3.66654734 -1.79464397 -0.14191096\n"
"S -2.17490031 0.51958250 0.78273141\n"
"C -4.29262738 2.77600580 0.56133840\n"
"O -3.58479588 3.54391605 -0.34398808\n"
"C -3.36442701 4.75261104 0.25680566\n"
"N -3.91940199 4.72906507 1.46127889\n"
"N -4.49627788 3.51093434 1.65171700\n"
"H -1.33769534 -1.54441748 -0.22809850\n"
"H -2.80707987 5.52123460 -0.28003351\n"
"C -1.21113637 -0.46501565 -0.43480790\n"
"C 0.22398843 -0.08543102 -0.34496922\n"
"C 1.08285196 -0.79516742 0.49815207\n"
"C 2.42997738 -0.45910455 0.56249805\n"
"C 2.92814395 0.58402121 -0.21112038\n"
"C 2.07614325 1.29295343 -1.05154120\n"
"C 0.72807757 0.96108082 -1.12144039\n"
"H 0.69278006 -1.61504710 1.11234037\n"
"H 3.09835877 -1.01845433 1.22526917\n"
"H 3.98969630 0.84730854 -0.15852854\n"
"H 2.46832221 2.11470261 -1.65984566\n"
"H 0.05861219 1.52405414 -1.78174762\n"
"H -1.59963993 -0.29678580 -1.45598699");
auto structure = Utils::XyzStreamHandler::read(ss);
calculator = std::make_shared<PM3MethodWrapper>();
calculator->setLog(Core::Log::silent());
calculator->setStructure(structure);
calculatorH = calculator->clone();
calculatorH->setStructure(Utils::XyzStreamHandler::read(ssHH));
calculatorHF = calculator->clone();
calculatorHF->setStructure(Utils::XyzStreamHandler::read(ssHF));
calculatorPor = calculator->clone();
calculatorPor->setStructure(Utils::XyzStreamHandler::read(ssPorphyrine));
calculatorPor->settings().modifyDouble(Utils::SettingsNames::selfConsistenceCriterion, 1e-8);
calculatorOxa = calculator->clone();
auto structure2 = Utils::XyzStreamHandler::read(ssOxadiazole);
calculatorOxa->setStructure(structure2);
calculatorOxa->settings().modifyDouble(Utils::SettingsNames::selfConsistenceCriterion, 1e-8);
polymorphicCIS = std::make_shared<CISLinearResponseTimeDependentCalculator>();
CISCalculator.setLog(Core::Log::silent());
polymorphicCIS->setLog(Core::Log::silent());
};
};
TEST_F(ACISTestCalculation, CanAssignCalculator) {
CISCalculator.setReferenceCalculator(calculator);
}
TEST_F(ACISTestCalculation, ThrowsIfMethodIsNotNDDO) {
std::shared_ptr<Core::Calculator> dftbCalculator = std::make_shared<DFTB2MethodWrapper>();
ASSERT_THROW(CISCalculator.setReferenceCalculator(dftbCalculator), InvalidCalculatorTypeForCIS);
}
TEST_F(ACISTestCalculation, CanPerformReferenceCalculation) {
CISCalculator.setReferenceCalculator(calculator->clone());
CISCalculator.referenceCalculation();
calculator->settings().modifyInt(Utils::SettingsNames::spinMultiplicity, 1);
calculator->setRequiredProperties(Utils::Property::Energy);
calculator->calculate("CIS reference calculation.");
ASSERT_THAT(calculator->results().get<Utils::Property::Energy>(),
DoubleNear(CISCalculator.getReferenceCalculator().results().get<Utils::Property::Energy>(), 1e-6));
}
TEST_F(ACISTestCalculation, ThrowsIfNoReferenceCalculationPerformed) {
CISCalculator.settings().modifyString(Utils::SettingsNames::spinBlock, "singlet");
CISCalculator.setReferenceCalculator(calculator->clone());
ASSERT_THROW(CISCalculator.calculate(), InvalidReferenceCalculationException);
}
TEST_F(ACISTestCalculation, RHFCISPreconditionerEvaluatedCorrectly) {
Utils::SingleParticleEnergies energies;
auto mos = Utils::MolecularOrbitals::createFromRestrictedCoefficients(Eigen::MatrixXd::Random(5, 5));
Utils::LcaoUtils::ElectronicOccupation occupation;
occupation.fillLowestRestrictedOrbitalsWithElectrons(4);
Eigen::VectorXd arbitraryEnergies(5);
arbitraryEnergies << -3.2, -1.0, 2.4, 5.7, 6.2;
energies.setRestricted(arbitraryEnergies);
Eigen::VectorXd energyDifferences(6);
energyDifferences << 5.6, 8.9, 9.4, 3.4, 6.7, 7.2;
Eigen::VectorXd diff1 = energyDifferences.array() - 1;
Eigen::VectorXd diff2 = energyDifferences.array() - 2;
Eigen::VectorXd invDiff1 = diff1.cwiseInverse();
Eigen::VectorXd invDiff2 = diff2.cwiseInverse();
Utils::SpinAdaptedContainer<Utils::Reference::Restricted, Eigen::VectorXd> energyDifferenceVector;
TimeDependentUtils::generateEnergyDifferenceVector(energies, occupation, energyDifferenceVector);
DiagonalPreconditionerEvaluator eval(energyDifferenceVector);
auto result1 = eval.evaluate(Eigen::VectorXd::Ones(energyDifferenceVector.restricted.size()), 1);
auto result2 = eval.evaluate(Eigen::VectorXd::Ones(energyDifferenceVector.restricted.size()), 2);
for (int i = 0; i < result1.size(); ++i) {
EXPECT_THAT(-result1(i), DoubleNear(invDiff1(i), 1e-6));
EXPECT_THAT(-result2(i), DoubleNear(invDiff2(i), 1e-6));
}
Eigen::VectorXd orderedEnDiffs(6);
orderedEnDiffs << 3.4, 5.6, 6.7, 7.2, 8.9, 9.4;
diff1 = orderedEnDiffs.array() - 1;
diff2 = orderedEnDiffs.array() - 2;
invDiff1 = diff1.cwiseInverse();
invDiff2 = diff2.cwiseInverse();
DiagonalPreconditionerEvaluator evalOrdered(energyDifferenceVector, OrderTag{});
result1 = evalOrdered.evaluate(Eigen::VectorXd::Ones(energyDifferenceVector.restricted.size()), 1);
result2 = evalOrdered.evaluate(Eigen::VectorXd::Ones(energyDifferenceVector.restricted.size()), 2);
for (int i = 0; i < result1.size(); ++i) {
EXPECT_THAT(-result1(i), DoubleNear(invDiff1(i), 1e-6));
EXPECT_THAT(-result2(i), DoubleNear(invDiff2(i), 1e-6));
}
}
TEST_F(ACISTestCalculation, CanPerformDenseCalculationOnSingletBlockForHF) {
CISCalculator.settings().modifyString(Utils::SettingsNames::spinBlock, Utils::SettingsNames::SpinBlocks::singlet);
CISCalculator.setReferenceCalculator(calculatorHF->clone());
CISCalculator.referenceCalculation();
CISCalculator.settings().modifyInt(Utils::SettingsNames::numberOfEigenstates, 4);
CISCalculator.settings().modifyInt(Utils::SettingsNames::initialSubspaceDimension, 8);
auto eigenPairs = CISCalculator.calculate().get<Utils::Property::ExcitedStates>().singlet->eigenStates;
Eigen::VectorXd singletEnergies(4);
singletEnergies << 8.178, 8.178, 8.741, 17.759;
for (int i = 0; i < eigenPairs.eigenValues.size(); ++i) {
ASSERT_THAT(eigenPairs.eigenValues(i) * Utils::Constants::ev_per_hartree, DoubleNear(singletEnergies(i), 5e-3));
}
}
TEST_F(ACISTestCalculation, CanPerformDenseCalculationOnSingletBlockForHFWithUHF) {
CISCalculator.setReferenceCalculator(calculatorHF->clone());
CISCalculator.getReferenceCalculator().settings().modifyString(
Utils::SettingsNames::spinMode, Utils::SpinModeInterpreter::getStringFromSpinMode(Utils::SpinMode::Unrestricted));
CISCalculator.referenceCalculation();
CISCalculator.settings().modifyInt(Utils::SettingsNames::numberOfEigenstates, 4);
CISCalculator.settings().modifyInt(Utils::SettingsNames::initialSubspaceDimension, 8);
auto eigenPairs = CISCalculator.calculate().get<Utils::Property::ExcitedStates>().unrestricted->eigenStates;
Eigen::VectorXd singletEnergies(4);
singletEnergies << 7.832, 7.832, 8.178, 8.178;
for (int i = 0; i < eigenPairs.eigenValues.size(); ++i) {
ASSERT_THAT(eigenPairs.eigenValues(i) * Utils::Constants::ev_per_hartree, DoubleNear(singletEnergies(i), 5e-3));
}
}
TEST_F(ACISTestCalculation, CanPerformDenseCalculationOnSingletBlockForHydrogen) {
CISCalculator.settings().modifyString(Utils::SettingsNames::spinBlock, "singlet");
CISCalculator.setReferenceCalculator(calculatorH->clone());
CISCalculator.referenceCalculation();
CISCalculator.settings().modifyInt(Utils::SettingsNames::numberOfEigenstates, 1);
CISCalculator.settings().modifyInt(Utils::SettingsNames::initialSubspaceDimension, 1);
auto eigenPairs = CISCalculator.calculate().get<Utils::Property::ExcitedStates>().singlet->eigenStates;
Eigen::VectorXd singletEnergies(1);
singletEnergies << 10.061;
for (int i = 0; i < eigenPairs.eigenValues.size(); ++i) {
ASSERT_THAT(eigenPairs.eigenValues(i) * Utils::Constants::ev_per_hartree, DoubleNear(singletEnergies(i), 5e-3));
}
}
TEST_F(ACISTestCalculation, CanPerformDenseCalculationOnTripletBlockForHydrogen) {
CISCalculator.settings().modifyString(Utils::SettingsNames::spinBlock, "triplet");
CISCalculator.setReferenceCalculator(calculatorH->clone());
CISCalculator.referenceCalculation();
CISCalculator.settings().modifyInt(Utils::SettingsNames::numberOfEigenstates, 1);
CISCalculator.settings().modifyInt(Utils::SettingsNames::initialSubspaceDimension, 1);
auto eigenPairs = CISCalculator.calculate().get<Utils::Property::ExcitedStates>().triplet->eigenStates;
Eigen::VectorXd tripletEnergies(1);
// From Orca PM3
tripletEnergies << 6.908;
for (int i = 0; i < eigenPairs.eigenValues.size(); ++i) {
ASSERT_THAT(eigenPairs.eigenValues(i) * Utils::Constants::ev_per_hartree, DoubleNear(tripletEnergies(i), 1e-3));
}
}
TEST_F(ACISTestCalculation, CanPerformDenseCalculationOnSingletBlock) {
CISCalculator.settings().modifyString(Utils::SettingsNames::spinBlock, "singlet");
CISCalculator.setReferenceCalculator(calculator->clone());
CISCalculator.referenceCalculation();
CISCalculator.settings().modifyInt(Utils::SettingsNames::numberOfEigenstates, 10);
CISCalculator.settings().modifyInt(Utils::SettingsNames::initialSubspaceDimension, 10);
auto eigenPairs = CISCalculator.calculate().get<Utils::Property::ExcitedStates>().singlet->eigenStates;
Eigen::VectorXd singletEnergies(10);
singletEnergies << 2.716, 5.476, 6.506, 7.986, 8.526, 9.111, 9.114, 9.606, 10.719, 11.041;
for (int i = 0; i < eigenPairs.eigenValues.size(); ++i) {
ASSERT_THAT(eigenPairs.eigenValues(i) * Utils::Constants::ev_per_hartree, DoubleNear(singletEnergies(i), 2e-3));
}
}
TEST_F(ACISTestCalculation, CanPerformDenseCalculationOnTripletBlock) {
CISCalculator.settings().modifyString(Utils::SettingsNames::spinBlock, "triplet");
CISCalculator.setReferenceCalculator(calculator->clone());
CISCalculator.referenceCalculation();
CISCalculator.settings().modifyInt(Utils::SettingsNames::numberOfEigenstates, 10);
CISCalculator.settings().modifyInt(Utils::SettingsNames::initialSubspaceDimension, 10);
auto eigenPairs = CISCalculator.calculate().get<Utils::Property::ExcitedStates>().triplet->eigenStates;
Eigen::VectorXd tripletEnergies(10);
tripletEnergies << 2.341, 4.316, 4.868, 5.706, 7.094, 7.908, 8.533, 9.037, 10.271, 10.369;
for (int i = 0; i < eigenPairs.eigenValues.size(); ++i) {
ASSERT_THAT(eigenPairs.eigenValues(i) * Utils::Constants::ev_per_hartree, DoubleNear(tripletEnergies(i), 5e-3));
}
}
TEST_F(ACISTestCalculation, CanPerformDenseCalculationOnSingletBlockForBiggerSystem) {
CISCalculator.settings().modifyString(Utils::SettingsNames::spinBlock, "singlet");
CISCalculator.setReferenceCalculator(calculatorPor->clone());
CISCalculator.referenceCalculation();
CISCalculator.settings().modifyInt(Utils::SettingsNames::numberOfEigenstates, 3);
CISCalculator.settings().modifyInt(Utils::SettingsNames::initialSubspaceDimension, 10);
auto eigenPairs = CISCalculator.calculate().get<Utils::Property::ExcitedStates>().singlet->eigenStates;
Eigen::VectorXd singletEnergies(10);
singletEnergies << 2.178, 2.346, 2.537, 2.537, 2.769, 3.183, 3.183, 3.216, 3.503, 3.868;
for (int i = 0; i < 3; ++i) {
ASSERT_THAT(eigenPairs.eigenValues(i) * Utils::Constants::ev_per_hartree, DoubleNear(singletEnergies(i), 2e-3));
}
}
TEST_F(ACISTestCalculation, CanPerformDenseCalculationOnSingletBlockForOxadiazoleRHF) {
CISCalculator.settings().modifyString(Utils::SettingsNames::spinBlock, "singlet");
CISCalculator.setReferenceCalculator(calculatorOxa->clone());
CISCalculator.referenceCalculation();
CISCalculator.settings().modifyInt(Utils::SettingsNames::numberOfEigenstates, 3);
CISCalculator.settings().modifyInt(Utils::SettingsNames::initialSubspaceDimension, 20);
auto eigenPairs = CISCalculator.calculate().get<Utils::Property::ExcitedStates>().singlet->eigenStates;
Eigen::VectorXd singletEnergies(20);
singletEnergies << 3.134, 3.502, 3.798, 3.958, 3.968, 4.105, 4.112, 4.346, 4.465, 4.737, 4.976, 5.055, 5.095, 5.208,
5.235, 5.317, 5.415, 5.498, 5.549, 5.614;
for (int i = 0; i < 3; ++i) {
EXPECT_THAT(eigenPairs.eigenValues(i) * Utils::Constants::ev_per_hartree, DoubleNear(singletEnergies(i), 2e-3));
}
}
TEST_F(ACISTestCalculation, CanPerformDenseCalculationOnTripletBlockForOxadiazoleRHF) {
CISCalculator.settings().modifyString(Utils::SettingsNames::spinBlock, "triplet");
CISCalculator.setReferenceCalculator(calculatorOxa->clone());
CISCalculator.referenceCalculation();
CISCalculator.settings().modifyInt(Utils::SettingsNames::numberOfEigenstates, 3);
CISCalculator.settings().modifyInt(Utils::SettingsNames::initialSubspaceDimension, 20);
auto eigenPairs = CISCalculator.calculate().get<Utils::Property::ExcitedStates>().triplet->eigenStates;
Eigen::VectorXd singletEnergies(20);
singletEnergies << 2.037, 2.171, 2.255, 2.557, 2.750, 3.254, 3.272, 3.291, 3.393, 3.398, 3.648, 3.695, 3.822, 3.965,
4.047, 4.337, 4.583, 4.607, 4.639, 4.788;
for (int i = 0; i < 3; ++i) {
ASSERT_THAT(eigenPairs.eigenValues(i) * Utils::Constants::ev_per_hartree, DoubleNear(singletEnergies(i), 2e-3));
}
}
TEST_F(ACISTestCalculation, CanPerformDenseCalculationForOxadiazoleUHF) {
CISCalculator.setReferenceCalculator(calculatorOxa->clone());
CISCalculator.getReferenceCalculator().settings().modifyString(
Utils::SettingsNames::spinMode, Utils::SpinModeInterpreter::getStringFromSpinMode(Utils::SpinMode::Unrestricted));
CISCalculator.referenceCalculation();
CISCalculator.settings().modifyInt(Utils::SettingsNames::numberOfEigenstates, 3);
CISCalculator.settings().modifyInt(Utils::SettingsNames::initialSubspaceDimension, 20);
auto eigenPairs = CISCalculator.calculate().get<Utils::Property::ExcitedStates>().unrestricted->eigenStates;
// put 20 just to know all the data
Eigen::VectorXd unrestrictedEnergies(20);
unrestrictedEnergies << 2.037, 2.171, 2.255, 2.557, 2.750, 3.134, 3.254, 3.272, 3.291, 3.393, 3.398, 3.502, 3.648,
3.695, 3.798, 3.822, 3.958, 3.965, 3.968, 4.047;
for (int i = 0; i < 3; ++i) {
ASSERT_THAT(eigenPairs.eigenValues(i) * Utils::Constants::ev_per_hartree, DoubleNear(unrestrictedEnergies(i), 1.5e-3));
}
}
TEST_F(ACISTestCalculation, CanPerformDenseCalculationOnTripletBlockForBiggerSystem) {
CISCalculator.settings().modifyString(Utils::SettingsNames::spinBlock, "triplet");
CISCalculator.setReferenceCalculator(calculatorPor->clone());
CISCalculator.referenceCalculation();
CISCalculator.settings().modifyInt(Utils::SettingsNames::numberOfEigenstates, 3);
CISCalculator.settings().modifyInt(Utils::SettingsNames::initialSubspaceDimension, 20);
auto eigenPairs = CISCalculator.calculate().get<Utils::Property::ExcitedStates>().triplet->eigenStates;
Eigen::VectorXd tripletEnergies(20);
tripletEnergies << 1.163, 1.561, 1.561, 1.849, 2.026, 2.053, 2.076, 2.076, 2.178, 2.178, 2.219, 2.340, 3.068, 3.318,
3.318, 3.497, 4.196, 4.218, 4.218, 4.297;
for (int i = 0; i < 3; ++i) {
ASSERT_THAT(eigenPairs.eigenValues(i) * Utils::Constants::ev_per_hartree, DoubleNear(tripletEnergies(i), 2e-3));
}
}
TEST_F(ACISTestCalculation, CanAskForCISThroughInterface) {
auto& manager = Core::ModuleManager::getInstance();
interfaceCIS = manager.get<Core::CalculatorWithReference>("CIS-NDDO");
}
TEST_F(ACISTestCalculation, CanPerformCalculationThroughModuleInterface) {
auto& manager = Core::ModuleManager::getInstance();
interfaceCIS = manager.get<Core::CalculatorWithReference>("CIS-NDDO");
interfaceCIS->setLog(Core::Log::silent());
interfaceCIS->setReferenceCalculator(calculator->clone());
interfaceCIS->settings().modifyInt(Utils::SettingsNames::numberOfEigenstates, 10);
interfaceCIS->settings().modifyInt(Utils::SettingsNames::initialSubspaceDimension, 10);
interfaceCIS->settings().modifyString(Utils::SettingsNames::spinBlock, "singlet");
interfaceCIS->applySettings();
interfaceCIS->referenceCalculation();
auto eigenPairs = interfaceCIS->calculate().get<Utils::Property::ExcitedStates>();
Eigen::VectorXd singletEnergies(10);
singletEnergies << 2.716, 5.476, 6.506, 7.986, 8.526, 9.111, 9.114, 9.606, 10.719, 11.041;
for (int i = 0; i < eigenPairs.singlet->eigenStates.eigenValues.size(); ++i) {
ASSERT_THAT(eigenPairs.singlet->eigenStates.eigenValues(i) * Utils::Constants::ev_per_hartree,
DoubleNear(singletEnergies(i), 5e-3));
}
}
TEST_F(ACISTestCalculation, CanPerformUHFCalculationThroughModuleInterface) {
auto& manager = Core::ModuleManager::getInstance();
calculator->settings().modifyString(Utils::SettingsNames::spinMode,
Utils::SpinModeInterpreter::getStringFromSpinMode(Utils::SpinMode::Unrestricted));
interfaceCIS = manager.get<Core::CalculatorWithReference>("CIS-NDDO");
interfaceCIS->setLog(Core::Log::silent());
interfaceCIS->setReferenceCalculator(calculator->clone());
interfaceCIS->settings().modifyInt(Utils::SettingsNames::numberOfEigenstates, 10);
interfaceCIS->settings().modifyInt(Utils::SettingsNames::initialSubspaceDimension, 10);
interfaceCIS->applySettings();
interfaceCIS->referenceCalculation();
omp_set_num_threads(1);
auto eigenPairs = interfaceCIS->calculate().get<Utils::Property::ExcitedStates>();
omp_set_num_threads(4);
Eigen::VectorXd singletEnergies(10);
singletEnergies << 2.341, 2.716, 4.316, 4.868, 5.476, 5.706, 6.506, 7.094, 7.908, 7.986;
for (int i = 0; i < eigenPairs.unrestricted->eigenStates.eigenValues.size(); ++i) {
ASSERT_THAT(eigenPairs.unrestricted->eigenStates.eigenValues(i) * Utils::Constants::ev_per_hartree,
DoubleNear(singletEnergies(i), 5e-3));
}
}
TEST_F(ACISTestCalculation, GeneratesCorrectEnergyOrderMap) {
Utils::SpinAdaptedContainer<Utils::Reference::Restricted, Eigen::VectorXd> energyDifferenceVector;
energyDifferenceVector.restricted = Eigen::VectorXd(4);
energyDifferenceVector.restricted << 3.5, 2.2, 6.4, 1.0; // Order should be 3, 1, 0, 2
auto enMap = TimeDependentUtils::generateEnergyOrderMap(energyDifferenceVector);
ASSERT_EQ(enMap.size(), 4);
EXPECT_EQ(enMap[0], 3);
EXPECT_EQ(enMap[1], 1);
EXPECT_EQ(enMap[2], 0);
EXPECT_EQ(enMap[3], 2);
Utils::SpinAdaptedContainer<Utils::Reference::Unrestricted, Eigen::VectorXd> unrestrictedEnergyDifferenceVector;
unrestrictedEnergyDifferenceVector.alpha = Eigen::VectorXd(4);
unrestrictedEnergyDifferenceVector.alpha << 3.5, 2.2, 6.4, 1.0; // Order should be 3, 1, 0, 2
unrestrictedEnergyDifferenceVector.beta = Eigen::VectorXd(4);
unrestrictedEnergyDifferenceVector.beta << 3.2, 7.4, 1.2, -1.2; // Order should be 3, 2, 0, 1
auto unEnMap = TimeDependentUtils::generateEnergyOrderMap(unrestrictedEnergyDifferenceVector);
ASSERT_EQ(unEnMap.size(), 8);
EXPECT_EQ(unEnMap[0], 7);
EXPECT_EQ(unEnMap[1], 3);
EXPECT_EQ(unEnMap[2], 6);
EXPECT_EQ(unEnMap[3], 1);
EXPECT_EQ(unEnMap[4], 4);
EXPECT_EQ(unEnMap[5], 0);
EXPECT_EQ(unEnMap[6], 2);
EXPECT_EQ(unEnMap[7], 5);
}
TEST_F(ACISTestCalculation, CorrectlyTransformsToOrders) {
std::vector<int> orderMap{3, 1, 0, 2};
Eigen::VectorXd vecToTransform(4);
vecToTransform << 0, 1, 2, 3;
std::vector<int> stdVecToTransform(4);
stdVecToTransform[0] = 0;
stdVecToTransform[1] = 1;
stdVecToTransform[2] = 2;
stdVecToTransform[3] = 3;
Eigen::VectorXd transformedVector;
TimeDependentUtils::transformOrder(vecToTransform, transformedVector, orderMap, TimeDependentUtils::Direction::To);
ASSERT_EQ(transformedVector.size(), 4);
EXPECT_EQ(transformedVector(0), 3);
EXPECT_EQ(transformedVector(1), 1);
EXPECT_EQ(transformedVector(2), 0);
EXPECT_EQ(transformedVector(3), 2);
Eigen::VectorXd backTransformedVec;
TimeDependentUtils::transformOrder(transformedVector, backTransformedVec, orderMap, TimeDependentUtils::Direction::From);
ASSERT_EQ(backTransformedVec.size(), 4);
EXPECT_EQ(backTransformedVec(0), vecToTransform(0));
EXPECT_EQ(backTransformedVec(1), vecToTransform(1));
EXPECT_EQ(backTransformedVec(2), vecToTransform(2));
EXPECT_EQ(backTransformedVec(3), vecToTransform(3));
std::vector<int> transformedStdVector;
TimeDependentUtils::transformOrder(stdVecToTransform, transformedStdVector, orderMap, TimeDependentUtils::Direction::To);
ASSERT_EQ(transformedStdVector.size(), 4);
EXPECT_EQ(transformedStdVector[0], 3);
EXPECT_EQ(transformedStdVector[1], 1);
EXPECT_EQ(transformedStdVector[2], 0);
EXPECT_EQ(transformedStdVector[3], 2);
std::vector<int> backTransformedStdVec;
TimeDependentUtils::transformOrder(transformedStdVector, backTransformedStdVec, orderMap, TimeDependentUtils::Direction::From);
ASSERT_EQ(backTransformedStdVec.size(), 4);
EXPECT_EQ(backTransformedStdVec[0], stdVecToTransform[0]);
EXPECT_EQ(backTransformedStdVec[1], stdVecToTransform[1]);
EXPECT_EQ(backTransformedStdVec[2], stdVecToTransform[2]);
EXPECT_EQ(backTransformedStdVec[3], stdVecToTransform[3]);
Eigen::MatrixXd matToTransform(4, 2);
matToTransform << 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5;
Eigen::MatrixXd transformedMatrix;
TimeDependentUtils::transformOrder(matToTransform, transformedMatrix, orderMap, TimeDependentUtils::Direction::To);
ASSERT_EQ(transformedMatrix.rows(), 4);
ASSERT_EQ(transformedMatrix.cols(), 2);
EXPECT_EQ(transformedMatrix(0, 0), 3);
EXPECT_EQ(transformedMatrix(0, 1), 3.5);
EXPECT_EQ(transformedMatrix(1, 0), 1);
EXPECT_EQ(transformedMatrix(1, 1), 1.5);
EXPECT_EQ(transformedMatrix(2, 0), 0);
EXPECT_EQ(transformedMatrix(2, 1), 0.5);
EXPECT_EQ(transformedMatrix(3, 0), 2);
EXPECT_EQ(transformedMatrix(3, 1), 2.5);
Eigen::MatrixXd backTransformedMat;
TimeDependentUtils::transformOrder(transformedMatrix, backTransformedMat, orderMap, TimeDependentUtils::Direction::From);
ASSERT_EQ(backTransformedMat.rows(), 4);
ASSERT_EQ(backTransformedMat.cols(), 2);
EXPECT_EQ(backTransformedMat.row(0), matToTransform.row(0));
EXPECT_EQ(backTransformedMat.row(1), matToTransform.row(1));
EXPECT_EQ(backTransformedMat.row(2), matToTransform.row(2));
EXPECT_EQ(backTransformedMat.row(3), matToTransform.row(3));
matToTransform = Eigen::MatrixXd::Random(4, 20);
TimeDependentUtils::transformOrder(matToTransform.leftCols(2), transformedMatrix, orderMap,
TimeDependentUtils::Direction::To);
ASSERT_EQ(transformedMatrix.rows(), 4);
ASSERT_EQ(transformedMatrix.cols(), 2);
EXPECT_EQ(transformedMatrix.row(0), matToTransform.leftCols(2).row(3));
EXPECT_EQ(transformedMatrix.row(1), matToTransform.leftCols(2).row(1));
EXPECT_EQ(transformedMatrix.row(2), matToTransform.leftCols(2).row(0));
EXPECT_EQ(transformedMatrix.row(3), matToTransform.leftCols(2).row(2));
TimeDependentUtils::transformOrder(transformedMatrix, backTransformedMat, orderMap, TimeDependentUtils::Direction::From);
ASSERT_EQ(backTransformedMat.rows(), 4);
ASSERT_EQ(backTransformedMat.cols(), 2);
EXPECT_EQ(backTransformedMat.row(0), matToTransform.leftCols(2).row(0));
EXPECT_EQ(backTransformedMat.row(1), matToTransform.leftCols(2).row(1));
EXPECT_EQ(backTransformedMat.row(2), matToTransform.leftCols(2).row(2));
EXPECT_EQ(backTransformedMat.row(3), matToTransform.leftCols(2).row(3));
}
TEST_F(ACISTestCalculation, CanCalculateHydrogenFluoride) {
calculatorHF->settings().modifyDouble(Utils::SettingsNames::selfConsistenceCriterion, 1e-9);
calculatorHF->settings().modifyString(Utils::SettingsNames::spinMode,
Utils::SpinModeInterpreter::getStringFromSpinMode(Utils::SpinMode::Unrestricted));
CISCalculator.setReferenceCalculator(calculatorHF);
CISCalculator.referenceCalculation();
CISCalculator.settings().modifyInt(Utils::SettingsNames::numberOfEigenstates, 4);
CISCalculator.settings().modifyInt(Utils::SettingsNames::initialSubspaceDimension, 4);
auto results = CISCalculator.calculate();
std::vector<std::string> notOrderedLabels{"0a -> 4a", "1a -> 4a", "2a -> 4a", "3a -> 4a",
"0b -> 4b", "1b -> 4b", "2b -> 4b", "3b -> 4b"};
auto labels = results.get<Utils::Property::ExcitedStates>().transitionLabels;
std::vector<int> order(8);
for (unsigned int i = 0; i < notOrderedLabels.size(); ++i) {
auto it = std::find(notOrderedLabels.begin(), notOrderedLabels.end(), labels[i]);
order[i] = std::distance(notOrderedLabels.begin(), it);
}
int nAlphaExcitations = 4;
auto eigenPairs = results.get<Utils::Property::ExcitedStates>().unrestricted->eigenStates;
Eigen::MatrixXd reorderedEigenVectors;
TimeDependentUtils::transformOrder(eigenPairs.eigenVectors, reorderedEigenVectors, order, TimeDependentUtils::Direction::From);
EXPECT_THAT(reorderedEigenVectors(0, 2), DoubleNear(reorderedEigenVectors(0 + nAlphaExcitations, 2), 1e-8));
EXPECT_THAT(reorderedEigenVectors(1, 2), DoubleNear(reorderedEigenVectors(1 + nAlphaExcitations, 2), 1e-8));
EXPECT_THAT(reorderedEigenVectors(2, 2), DoubleNear(reorderedEigenVectors(2 + nAlphaExcitations, 2), 1e-8));
EXPECT_THAT(reorderedEigenVectors(3, 2), DoubleNear(reorderedEigenVectors(3 + nAlphaExcitations, 2), 1e-8));
}
} // namespace Sparrow
} // namespace Scine
|
d1085fb9185d1012c8344ca3d631a507b37d8081
|
95ae7b9dc4829d6d3af5a133beeabe0187c4a4e3
|
/CrazyArcade/JumpObject.h
|
766c6ac1c834a206d006c3abed348b59abfcb477
|
[] |
no_license
|
iamjungdamin/CrazyArcade
|
2d8ca4ad6d682a1ed4196c6bd5d2ed408cb7f06a
|
7899ef76e3661baf4cd3a10c4e83db0296d11978
|
refs/heads/master
| 2023-07-16T04:28:28.257856
| 2021-09-02T21:46:03
| 2021-09-02T21:46:03
| 378,920,021
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,276
|
h
|
JumpObject.h
|
#pragma once
#include "Object.h"
enum STATE
{
jIDLE,
jPATROL,
jCHASE
};
class BulletManager;
class BubbleManager;
class WallManager;
class JumpObject : public Object
{
public:
JumpObject();
JumpObject(const string& textureFilePath);
JumpObject(const string& textureFilePath, const Vector2f& position);
virtual ~JumpObject() = default;
private:
Vector2f position{ 0.f,0.f };
Vector2f velocity{ 0.f,0.f };
Vector2f acceleration{ 0.f,0.f };
Vector2f direction{ 0.f,0.f };
Vector2f patrolPosition = { 0.f, 0.f };
int state = jIDLE;
float speed = 50.f;
float gravity = 2.f;
BulletManager* bulletMgr = nullptr;
float shootCoolTime = 0.1f;
Vector2f bulletTargetPosition{ 0.f, 0.f };
BubbleManager* bubbleMgr = nullptr;
float addBubbleCoolTime = 0.5f;
WallManager* wallMgr = nullptr;
public:
virtual void Destroy();
BulletManager* GetBulletMgr();
BubbleManager* GetBubbleMgr();
const Vector2f& GetDirection();
void SetDirection(const Vector2f& direction);
void JumpUpdate(const float& deltaTime);
void Jump();
void Shoot();
void AddBubble();
void TargetMove(const Vector2f& targetPosition);
virtual void Update(const float& deltaTime);
virtual void Update(const Vector2f& mousePostion);
virtual void Render(RenderTarget* target);
};
|
8c8a61c7706dbf843343811a6d5e0325c9e21f8a
|
176225156d82830b69cde4355648daad373700c9
|
/src/espros_nogui/src/interface.cpp
|
c513839f8fbe75b0603801ad7409499c89f31add
|
[] |
no_license
|
MarbleInc/espros-driver
|
99b7528af25d4eb523bcf542140c73dd0437c706
|
728b2174d92c72dddaca7b66187545e5407318e2
|
refs/heads/master
| 2021-04-29T18:17:53.944038
| 2018-03-14T21:36:52
| 2018-03-14T21:36:52
| 121,690,167
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,361
|
cpp
|
interface.cpp
|
#include "espros_nogui/interface.h"
#include "espros_nogui/tcp_cmd_connection.h"
#include "espros_nogui/udp_data_connection.h"
#include "espros_nogui/data_header.h"
#include <QByteArray>
#include <QDebug>
#include <QtCore>
//commands GUI-->TOFCAM
typedef enum
{
TOFCAM_COMMAND_SET_INT_TIMES = 1,
TOFCAM_COMMAND_GET_DISTANCE_AMPLITUDE = 2,
TOFCAM_COMMAND_GET_DISTANCE = 3,
TOFCAM_COMMAND_GET_AMPLITUDE = 4,
TOFCAM_COMMAND_GET_GRAYSCALE = 5,
TOFCAM_COMMAND_STOP_STREAM = 6,
TOFCAM_COMMAND_SET_OFFSET = 20,
TOFCAM_COMMAND_SET_MIN_AMPLITUDE = 21,
TOFCAM_COMMAND_CALIBRATE = 30,
TOFCAM_COMMAND_CALIBRATE_SYSTEM_OFFSET = 31
}tofcamCommand_e;
//answers TOFCAM-->GUI
typedef enum
{
TOFCAM_ANSWER_ACK = 0,
TOFCAM_ANSWER_ERROR = 1
}tofcamAnswer_e;
Interface::Interface(QObject *parent __attribute__((unused)))
{
numMeasurements = 0;
udpThread = new InterfaceThread();
tcpThread = new InterfaceThread();
timerThread = new InterfaceThread();
dataConnection = new UdpDataConnection(this);
connect(dataConnection, &DataConnection::receivedData, this, &Interface::receivedData);
dataConnection->setPort(45454);
cmdConnection = new TcpCmdConnection();
cmdConnection->setConnectionParameters("10.10.31.180", 50660);
connect(cmdConnection, &TcpCmdConnection::receivedAnswer, this, &Interface::receivedAnswer);
connect(cmdConnection, &TcpCmdConnection::connected, this, &Interface::cmdConnectionConnected);
connect(cmdConnection, &TcpCmdConnection::disconnected, this, &Interface::cmdConnectionDisconnected);
waitAck = false;
cmdConnection->moveToThread(tcpThread);
cmdConnection->connect(tcpThread, &QThread::started, cmdConnection, &CmdConnection::startRunning);
cmdConnection->connect(tcpThread, &QThread::finished, cmdConnection, &CmdConnection::stopRunning);
tcpThread->start();
dataConnection->moveToThread(udpThread);
dataConnection->connect(udpThread, &QThread::started, dataConnection, &DataConnection::startRunning);
dataConnection->connect(udpThread, &QThread::finished, dataConnection, &DataConnection::stopRunning);
udpThread->start();
fpsTimer = new QTimer(0); //Parent must be null
fpsTimer->setInterval(1000);
fpsTimer->start();
fpsTimer->moveToThread(timerThread);
connect(fpsTimer, SIGNAL(timeout()), this, SLOT(onUpdateFps()));
timerThread->start();
}
Interface::~Interface()
{
close();
delete cmdConnection;
delete dataConnection;
delete udpThread;
}
void Interface::close()
{
stopStream();
udpThread->stopRunning();
tcpThread->stopRunning();
timerThread->stopRunning();
waitAck = true;
QTimer timer;
timer.setSingleShot(true);
timer.start(1000);
while(waitAck && (timer.isActive()))
{
QCoreApplication::processEvents();
}
cmdConnection->close();
}
void Interface::insertValue(QByteArray &output, const uint16_t value)
{
output.append(value >> 8);
output.append(value & 0xFF);
}
void Interface::insertValue(QByteArray &output, const int16_t value)
{
output.append(value >> 8);
output.append(value & 0xFF);
}
uint8_t Interface::boolToUint8(const bool value)
{
if (value)
{
return 1;
}
else
{
return 0;
}
}
void Interface::sendCommand(QByteArray &dataToSend, const QByteArray &userData)
{
//If present, add user data
if (userData != nullptr)
{
dataToSend.append(userData);
}
cmdConnection->sendCommand(dataToSend);
}
void Interface::requestDistanceAmplitude(const bool doStream, const QByteArray &userData)
{
QByteArray outputData;
uint16_t command = TOFCAM_COMMAND_GET_DISTANCE_AMPLITUDE;
uint8_t stream = boolToUint8(doStream);
//Insert the 16Bit command
insertValue(outputData, command);
//Insert the stream flag
outputData.insert(2, stream);
sendCommand(outputData, userData);
}
void Interface::requestDistance(const bool doStream, const QByteArray &userData)
{
QByteArray outputData;
uint16_t command = TOFCAM_COMMAND_GET_DISTANCE;
uint8_t stream = boolToUint8(doStream);
//Insert the 16Bit command
insertValue(outputData, command);
//Insert the stream flag
outputData.insert(2, stream);
sendCommand(outputData, userData);
}
void Interface::requestGrayscale(const bool doStream, const QByteArray &userData)
{
QByteArray outputData;
uint16_t command = TOFCAM_COMMAND_GET_GRAYSCALE;
uint8_t stream = boolToUint8(doStream);
//Insert the 16Bit command
insertValue(outputData, command);
//Insert the stream flag
outputData.insert(2, stream);
sendCommand(outputData, userData);
}
void Interface::setIntegrationTimes(const uint16_t integrationTime3d[3], const uint16_t integrationTimeGrayscale, const QByteArray &userData)
{
QByteArray outputData;
uint16_t command = TOFCAM_COMMAND_SET_INT_TIMES;
//Insert the 16Bit command
insertValue(outputData, command);
//Insert the 3 integration times for 3D
for (int i = 0; i < 3; i++)
{
insertValue(outputData, integrationTime3d[i]);
}
//Insert the integration time for grayscale
insertValue(outputData, integrationTimeGrayscale);
sendCommand(outputData, userData);
}
void Interface::setOffset(const int16_t offset, const QByteArray &userData)
{
QByteArray outputData;
uint16_t command = TOFCAM_COMMAND_SET_OFFSET;
//Insert the 16Bit command
insertValue(outputData, command);
//Insert the offset
insertValue(outputData, offset);
sendCommand(outputData, userData);
}
void Interface::setMinAmplitude(const uint16_t minAmplitude, const QByteArray &userData)
{
QByteArray outputData;
uint16_t command = TOFCAM_COMMAND_SET_MIN_AMPLITUDE;
//Insert the 16Bit command
insertValue(outputData, command);
//Insert the min Amplitude
insertValue(outputData, minAmplitude);
sendCommand(outputData, userData);
}
void Interface::stopStream(const QByteArray &userData)
{
QByteArray outputData;
uint16_t command = TOFCAM_COMMAND_STOP_STREAM;
//Insert the 16Bit command
insertValue(outputData, command);
sendCommand(outputData, userData);
}
void Interface::calibrate(const QByteArray &userData)
{
QByteArray outputData;
uint16_t command = TOFCAM_COMMAND_CALIBRATE;
//Insert the 16Bit command
insertValue(outputData, command);
sendCommand(outputData, userData);
}
void Interface::calibrateSystemOffset(const QByteArray &userData)
{
QByteArray outputData;
uint16_t command = TOFCAM_COMMAND_CALIBRATE_SYSTEM_OFFSET;
//Insert the 16Bit command
insertValue(outputData, command);
sendCommand(outputData, userData);
}
void Interface::receivedAnswer(QByteArray data)
{
uint8_t answer = data.at(0);
switch(answer)
{
case TOFCAM_ANSWER_ACK:
emit receivedAck();
waitAck = false;
break;
case TOFCAM_ANSWER_ERROR:
{
uint8_t errorNumber = data.at(1);
emit receivedError(errorNumber);
qDebug() << "Received Error: " << errorNumber;
}
break;
default:
qDebug() << "Unknown answer";
break;
}
}
void Interface::onUpdateFps()
{
emit updateFps(numMeasurements);
numMeasurements = 0;
}
void Interface::receivedData(const char *pData, const int length, bool complete)
{
if (complete)
{
numMeasurements++;
}
emit receivedMeasurementData(pData, length, complete);
}
void Interface::cmdConnectionConnected()
{
emit connected();
}
void Interface::cmdConnectionDisconnected()
{
emit disconnected();
}
|
b3b34e08b28fdff3c83314253c8db620f0e93723
|
9de813a282cdf2ef3cb5c32a05b3428ac362746c
|
/src/casswrapper/casswrapper_impl.cpp
|
8d4d9c87b9e8fc59c740bd94621d11c17d486b32
|
[
"MIT"
] |
permissive
|
m2osw/libcasswrapper
|
b9a88962d218ce4521acc68d6b854ddf3f40f228
|
d1c56ad386acde738eb25243b4fefbce97459634
|
refs/heads/main
| 2023-08-20T07:46:55.785243
| 2021-11-13T02:13:13
| 2021-11-13T02:13:13
| 106,984,688
| 3
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 30,069
|
cpp
|
casswrapper_impl.cpp
|
/*
* Text:
* src/casswrapper/casswrapper_impl.cpp
*
* Description:
* Handling of the CQL interface.
*
* Documentation:
* See each function below.
*
* License:
* Copyright (c) 2011-2019 Made to Order Software Corp. All Rights Reserved
*
* https://snapwebsites.org/
* contact@m2osw.com
*
* 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 "casswrapper_impl.h"
#include "exception_impl.h"
#include <sstream>
/** \mainpage
* \brief libcasswrapper C++ Documentation
*
* \section introduction Introduction
*
* The libcasswrapper library provides a light wrapper around the Cassandra CPP
* Driver API.
*
* Datastax's library is sadly NOT really C++, but consistent straight C, in
* terms of design. All of the resources handles returned are not managed
* with constructors/destructors to deal with object lifetime. The developer is
* responsible to make sure resources are properly destroyed once he/she is
* finished with them. This opens up the door to memory and resource leaks.
*
* In order to avoid those pitfalls, we've written a thin C++ "wrapper" around
* the driver API itself. The resource handles are preserved in std smart
* pointers, which automatically manage the lifetimes and prevent resource
* leaks. This makes the library a lot easier to use in an object oriented
* situation, consistent with the tried and true design principle of RAII.
*
* \section core Core Classes
*
* At the core of this library is the Query class. Since Cassandra migrated to
* CQL and away from their traditional binary driver (which required Thrift), a
* method is needed to deal with sending CQL queries to the database server.
* Also, the unique design of this distributed database means that you should
* not code your app to sit around and wait for a response. One needs to think
* in a distributed, threaded way. You can "block" until the operation
* completes, but a more effective way is to use the non-block switch and take
* advantage of the callback. For example, here is a traditional "blocking" way
* to make a database query:
*
* \code
* Query::pointer_t my_query( Query::create(session) );
* my_query->query( "SELECT foo,bar FROM my_database.foobar" );
* my_query->setPagingSize( 100 ); // listen for 100 records at a time
* my_query->start(); // defaults to blocking
* //
* do
* {
* while( q->nextRow() )
* {
* const int32_t foo(my_query->getInt32Column("foo"));
* const QString bar(my_query->getStringColumn("bar"));
* // Do stuff
* }
* }
* while( q->nextPage() );
* \endcode
*
* However, if you attach to the Qt5 signal queryFinished(), then instead of
* calling, you can return processing to other critical areas of your code and
* process the returned rows when they are ready.
*
* \section whats_next What's Next?
*
* There are certain elements of Datastax's API which we have not yet
* implemented, however we have captured the most critical aspects. You can
* peruse the database schema without having to directly query the system tables
* (which are subject to change between versions of the database), you can take
* advantage of batch processing, all data types are supported, and you even can
* create an SSL connection to your database.
*
* And the huge advantage is that we put all resources into smart pointer
* containers, so this will help you keep resource and memory leaks to a minimum
* in your software.
*
* \sa casswrapper::Query::queryFinished(), casswrapper::Query, casswrapper::Session
*/
namespace casswrapper
{
//===============================================================================
// batch
//
void batch::deleter_t::operator()(CassBatch* p) const
{
cass_batch_free( p );
}
batch::batch( CassBatchType type )
: f_ptr(cass_batch_new(type),deleter_t())
{
}
void batch::set_consistency ( CassConsistency const c ) const
{
CassError const rc = cass_batch_set_consistency( f_ptr.get(), c );
if( rc != CASS_OK )
{
throw cassandra_exception_impl("Cannot set batch consistency!",rc);
}
}
void batch::set_serial_consistency ( CassConsistency const c ) const
{
CassError const rc = cass_batch_set_serial_consistency( f_ptr.get(), c );
if( rc != CASS_OK )
{
throw cassandra_exception_impl("Cannot set batch serial consistency!",rc);
}
}
void batch::set_timestamp ( int64_t const timestamp ) const
{
CassError rc = cass_batch_set_timestamp( f_ptr.get(), timestamp );
if( rc != CASS_OK )
{
throw cassandra_exception_impl("Cannot set batch timestamp!",rc);
}
}
void batch::set_request_timeout ( int64_t const timeout ) const
{
CassError rc = cass_batch_set_request_timeout( f_ptr.get(), timeout );
if( rc != CASS_OK )
{
throw cassandra_exception_impl("Cannot set batch request timeout!",rc);
}
}
void batch::set_is_idempotent ( bool const val ) const
{
CassError rc = cass_batch_set_is_idempotent( f_ptr.get(), val? cass_true: cass_false );
if( rc != CASS_OK )
{
throw cassandra_exception_impl("Cannot set batch idempotent status!",rc);
}
}
void batch::set_retry_policy ( retry_policy const& p ) const
{
CassError rc = cass_batch_set_retry_policy( f_ptr.get(), p.f_ptr.get() );
if( rc != CASS_OK )
{
throw cassandra_exception_impl("Cannot set batch retry policy!",rc);
}
}
void batch::set_custom_payload ( custom_payload const& p ) const
{
CassError rc = cass_batch_set_custom_payload( f_ptr.get(), p.f_ptr.get() );
if( rc != CASS_OK )
{
throw cassandra_exception_impl("Cannot set batch custom payload!",rc);
}
}
void batch::add_statement ( statement const& p ) const
{
CassError rc = cass_batch_add_statement( f_ptr.get(), p.f_ptr.get() );
if( rc != CASS_OK )
{
throw cassandra_exception_impl("Cannot add statement to batch!",rc);
}
}
//===============================================================================
// collection
//
collection::collection( CassCollectionType type, size_t item_count )
: f_ptr( cass_collection_new( type, item_count ), deleter_t() )
{
}
void collection::deleter_t::operator()(CassCollection* p) const
{
cass_collection_free(p);
}
void collection::append_string( const std::string& value ) const
{
const CassError rc = cass_collection_append_string( f_ptr.get(), value.c_str() );
if( rc != CASS_OK )
{
throw cassandra_exception_impl(
QString("Cannot append string '%1' to collection!")
.arg(value.c_str())
, rc
);
}
}
//===============================================================================
// column_meta
//
column_meta::column_meta( CassColumnMeta* p )
: f_ptr( p, deleter_t() )
{
}
void column_meta::deleter_t::operator()(const CassColumnMeta*) const
{
// No need to delete anything
//cass_column_meta_free(p);
}
QString column_meta::get_name() const
{
const char * name;
size_t len;
cass_column_meta_name( f_ptr.get(), &name, &len );
return QString::fromUtf8(name,len);
}
CassColumnType column_meta::get_column_type() const
{
return cass_column_meta_type( f_ptr.get() );
}
CassValueType column_meta::get_value_type() const
{
return cass_data_type_type( cass_column_meta_data_type(f_ptr.get()) );
}
iterator column_meta::get_fields() const
{
return iterator( cass_iterator_fields_from_column_meta( f_ptr.get() ) );
}
//===============================================================================
// cluster
//
cluster::cluster()
: f_ptr(cass_cluster_new(), deleter_t())
{
}
void cluster::deleter_t::operator()( CassCluster * p) const
{
cass_cluster_free(p);
}
void cluster::set_contact_points( const QString& host_list )
{
cass_cluster_set_contact_points( f_ptr.get(), host_list.toUtf8().data() );
}
void cluster::set_port( const int port )
{
cass_cluster_set_port( f_ptr.get(), port );
}
void cluster::set_request_timeout( const timeout_t timeout )
{
cass_cluster_set_request_timeout( f_ptr.get(), static_cast<unsigned>(timeout) );
}
void cluster::reset_ssl() const
{
cass_cluster_set_ssl( f_ptr.get(), nullptr );
}
void cluster::set_ssl( const ssl& ssl ) const
{
cass_cluster_set_ssl( f_ptr.get(), ssl.f_ptr.get() );
}
//===============================================================================
// custom_payload
//
custom_payload::custom_payload()
: f_ptr(cass_custom_payload_new(),deleter_t())
{
}
void custom_payload::deleter_t::operator()(CassCustomPayload* p) const
{
cass_custom_payload_free( p );
}
void custom_payload::payload_set( QString const& name, QByteArray const& value ) const
{
cass_custom_payload_set_n
( f_ptr.get()
, name.toUtf8().data()
, name.size()
, reinterpret_cast<const cass_byte_t*>(value.data())
, value.size()
);
}
void custom_payload::payload_remove( QString const& name ) const
{
cass_custom_payload_remove_n
( f_ptr.get()
, name.toUtf8().data()
, name.size()
);
}
//===============================================================================
// future
//
future::future()
{
}
future::future( CassFuture* p )
: f_ptr( p, deleter_t() )
{
}
void future::deleter_t::operator()(CassFuture * p) const
{
cass_future_free(p);
}
future::future( const session& sess, const cluster& cl )
: f_ptr( cass_session_connect( sess.f_ptr.get(), cl.f_ptr.get() ), deleter_t() )
{
}
CassError future::get_error_code() const
{
return cass_future_error_code( f_ptr.get() );
}
QString future::get_error_message() const
{
const char* message = 0;
size_t length = 0;
cass_future_error_message( f_ptr.get(), &message, &length );
return QString::fromUtf8(message,length);
}
result future::get_result() const
{
return result( const_cast<CassResult*>(cass_future_get_result(f_ptr.get())) );
}
bool future::is_ready() const
{
return cass_future_ready( f_ptr.get() );
}
void future::set_callback( void* callback, void* data )
{
cass_future_set_callback( f_ptr.get(), reinterpret_cast<CassFutureCallback>(callback), data );
}
void future::wait() const
{
cass_future_wait( f_ptr.get() );
}
bool future::operator ==( const future& f )
{
return f_ptr == f.f_ptr;
}
bool future::operator !=( const future& f )
{
return !(*this == f);
}
//===============================================================================
// iterator
//
iterator::iterator( CassIterator* p )
: f_ptr(p, deleter_t())
{
}
iterator::iterator( const iterator& iter )
: f_ptr( iter.f_ptr )
{
}
void iterator::deleter_t::operator()(CassIterator* p) const
{
cass_iterator_free( p );
}
bool iterator::next() const
{
if(f_ptr == nullptr)
{
return false;
}
return cass_iterator_next( f_ptr.get() ) == cass_true;
}
value iterator::get_map_key() const
{
if(f_ptr == nullptr)
{
return value(nullptr);
}
return value( const_cast<CassValue*>(cass_iterator_get_map_key(f_ptr.get())) );
}
value iterator::get_map_value() const
{
if(f_ptr == nullptr)
{
return value(nullptr);
}
return value( const_cast<CassValue*>(cass_iterator_get_map_value(f_ptr.get())) );
}
value iterator::get_value() const
{
if(f_ptr == nullptr)
{
return value(nullptr);
}
return value( const_cast<CassValue*>(cass_iterator_get_value(f_ptr.get())) );
}
QString iterator::get_meta_field_name() const
{
if(f_ptr == nullptr)
{
return QString();
}
const char * name(nullptr);
size_t len(0);
const CassError rc = cass_iterator_get_meta_field_name( f_ptr.get(), &name, &len );
if( rc != CASS_OK )
{
throw cassandra_exception_impl( "Cannot get field name from iterator!", rc );
}
return QString::fromUtf8( name, len );
}
value iterator::get_meta_field_value() const
{
if(f_ptr == nullptr)
{
return value(nullptr);
}
return value( const_cast<CassValue*>(cass_iterator_get_meta_field_value( f_ptr.get() )) );
}
row iterator::get_row() const
{
if(f_ptr == nullptr)
{
return row();
}
return row( const_cast<CassRow*>(cass_iterator_get_row(f_ptr.get())) );
}
keyspace_meta iterator::get_keyspace_meta() const
{
if(f_ptr == nullptr)
{
return keyspace_meta(nullptr);
}
return keyspace_meta( const_cast<CassKeyspaceMeta*>(cass_iterator_get_keyspace_meta(f_ptr.get())) );
}
table_meta iterator::get_table_meta() const
{
if(f_ptr == nullptr)
{
return table_meta(nullptr);
}
return table_meta( const_cast<CassTableMeta*>(cass_iterator_get_table_meta(f_ptr.get())) );
}
column_meta iterator::get_column_meta() const
{
if(f_ptr == nullptr)
{
return column_meta(nullptr);
}
return column_meta( const_cast<CassColumnMeta*>(cass_iterator_get_column_meta(f_ptr.get())) );
}
//===============================================================================
// keyspace_meta
//
keyspace_meta::keyspace_meta( CassKeyspaceMeta* p )
: f_ptr( p, deleter_t() )
{
//cass_keyspace_meta_deleter(p);
}
void keyspace_meta::deleter_t::operator()( CassKeyspaceMeta* ) const
{
// No need to do this...
//
//cass_keyspace_meta_deleter(p);
}
iterator keyspace_meta::get_fields() const
{
return iterator( cass_iterator_fields_from_keyspace_meta( f_ptr.get() ) );
}
iterator keyspace_meta::get_tables() const
{
return iterator( cass_iterator_tables_from_keyspace_meta( f_ptr.get() ) );
}
QString keyspace_meta::get_name() const
{
const char* name = 0;
size_t length = 0;
cass_keyspace_meta_name( f_ptr.get(), &name, &length );
return QString::fromUtf8( name, length );
}
//===============================================================================
// retry_policy
//
retry_policy::retry_policy( type_t const t )
{
switch( t )
{
case type_t::Default:
f_ptr.reset(cass_retry_policy_default_new(), deleter_t());
break;
case type_t::FallThrough:
f_ptr.reset(cass_retry_policy_fallthrough_new(), deleter_t());
break;
case type_t::DowngradingConsistency: // this one may be completely removed in the future (it is deprecated)
case type_t::Logging:
throw libexcept::exception_t("The policy type you tried with is not available. You must use the other constructor for retry_policy(). We need a child policy.");
break;
}
}
retry_policy::retry_policy( retry_policy const& child_policy )
: f_ptr( cass_retry_policy_logging_new(child_policy.f_ptr.get()), deleter_t() )
{
}
void retry_policy::deleter_t::operator()( CassRetryPolicy* p ) const
{
cass_retry_policy_free(p);
}
//===============================================================================
// result
//
result::result( CassResult* p )
: f_ptr(p, deleter_t() )
{
}
result::result( const result& res )
: f_ptr( res.f_ptr )
{
}
void result::deleter_t::operator()(const CassResult* p) const
{
cass_result_free(p);
}
iterator result::get_iterator() const
{
return cass_iterator_from_result( f_ptr.get() );
}
size_t result::get_row_count() const
{
return cass_result_row_count( f_ptr.get() );
}
size_t result::get_column_count() const
{
return cass_result_column_count( f_ptr.get() );
}
bool result::has_more_pages() const
{
return cass_result_has_more_pages( f_ptr.get() ) == cass_true? true: false;
}
QString result::get_column_name( size_t const index ) const
{
const char * name;
size_t len;
CassError rc = cass_result_column_name( f_ptr.get(), index, &name, &len );
if( rc != CASS_OK )
{
throw cassandra_exception_impl( QString("Error fetching column name from column %1").arg(index), rc );
}
return QString::fromUtf8( name, len );
}
CassValueType result::get_column_type( size_t const index ) const
{
return cass_result_column_type( f_ptr.get(), index );
}
row result::get_first_row() const
{
return cass_result_first_row(f_ptr.get());
}
//===============================================================================
// row
//
row::row()
{
}
row::row( CassRow* p )
: f_ptr( p, deleter_t() )
{
}
row::row( CassRow const* p )
: f_ptr( const_cast<CassRow*>(p), deleter_t() )
{
}
void row::deleter_t::operator()( CassRow* ) const
{
// Not needed, API deletes it on its own.
//cass_row_free(p);
}
value row::get_column_by_name( const QString& name ) const
{
return value(
const_cast<CassValue*>(cass_row_get_column_by_name( f_ptr.get(), name.toUtf8().data() ))
);
}
value row::get_column( const int num ) const
{
return value(
const_cast<CassValue*>(cass_row_get_column( f_ptr.get(), num ))
);
}
iterator row::get_iterator() const
{
return iterator(
cass_iterator_from_row( f_ptr.get() )
);
}
//===============================================================================
// schema_meta
//
schema_meta::schema_meta( const session& s )
: f_ptr( const_cast<CassSchemaMeta*>(cass_session_get_schema_meta(s.f_ptr.get())), deleter_t() )
{
}
void schema_meta::deleter_t::operator()(const CassSchemaMeta* p) const
{
cass_schema_meta_free(p);
}
iterator schema_meta::get_keyspaces() const
{
return( cass_iterator_keyspaces_from_schema_meta( f_ptr.get() ) );
}
//===============================================================================
// session
//
session::session()
: f_ptr(cass_session_new(), deleter_t())
{
}
void session::deleter_t::operator()(CassSession* p) const
{
cass_session_free(p);
}
future session::execute( const statement& s ) const
{
return future(
cass_session_execute( f_ptr.get(), s.f_ptr.get() )
);
}
future session::execute_batch( const batch& b ) const
{
return future(
cass_session_execute_batch( f_ptr.get(), b.f_ptr.get() )
);
}
future session::close() const
{
return future( cass_session_close(f_ptr.get()) );
}
//===============================================================================
// ssl
//
ssl::ssl()
: f_ptr( cass_ssl_new(), deleter_t() )
{
cass_ssl_set_verify_flags( f_ptr.get(), CASS_SSL_VERIFY_PEER_CERT | CASS_SSL_VERIFY_PEER_IDENTITY );
}
void ssl::deleter_t::operator()(CassSsl* p) const
{
cass_ssl_free(p);
}
void ssl::add_trusted_cert( const QString& cert )
{
CassError rc = cass_ssl_add_trusted_cert_n
( f_ptr.get()
, cert.toUtf8().data()
, cert.size()
);
if( rc != CASS_OK )
{
throw cassandra_exception_impl( "Error loading SSL certificate", rc );
}
}
//===============================================================================
// statement
//
statement::statement( const QString& query, const int bind_count )
: f_ptr(const_cast<CassStatement*>(cass_statement_new(query.toUtf8().data(), bind_count)), deleter_t())
, f_query(query)
{
}
void statement::deleter_t::operator()(CassStatement* p) const
{
cass_statement_free(p);
}
void statement::set_consistency( const CassConsistency consist ) const
{
cass_statement_set_consistency( f_ptr.get(), consist );
}
void statement::set_timestamp( const int64_t timestamp ) const
{
cass_int64_t const cass_time( static_cast<cass_int64_t>(timestamp) );
cass_statement_set_timestamp( f_ptr.get(), cass_time );
}
void statement::set_paging_size( const int size ) const
{
cass_statement_set_paging_size( f_ptr.get(), size );
}
void statement::set_paging_state( const result& res ) const
{
cass_statement_set_paging_state( f_ptr.get(), res.f_ptr.get() );
}
void statement::bind_bool( const size_t id, const bool value ) const
{
cass_statement_bind_bool( f_ptr.get(), id, value? cass_true: cass_false );
}
void statement::bind_bool( const QString& id, const bool value ) const
{
cass_statement_bind_bool_by_name( f_ptr.get(), id.toUtf8().data(), value? cass_true: cass_false );
}
void statement::bind_int32( const size_t id, const int32_t value ) const
{
cass_statement_bind_int32( f_ptr.get(), id, value );
}
void statement::bind_int32( const QString& id, const int32_t value ) const
{
cass_statement_bind_int32_by_name( f_ptr.get(), id.toUtf8().data(), value );
}
void statement::bind_uint32( const size_t id, const uint32_t value ) const
{
cass_statement_bind_uint32( f_ptr.get(), id, value );
}
void statement::bind_uint32( const QString& id, const uint32_t value ) const
{
cass_statement_bind_uint32_by_name( f_ptr.get(), id.toUtf8().data(), value );
}
void statement::bind_int64( const size_t id, const int64_t value ) const
{
cass_statement_bind_int64( f_ptr.get(), id, value );
}
void statement::bind_int64( const QString& id, const int64_t value ) const
{
cass_statement_bind_int64_by_name( f_ptr.get(), id.toUtf8().data(), value );
}
void statement::bind_float( const size_t id, const float value ) const
{
cass_statement_bind_float( f_ptr.get(), id, value );
}
void statement::bind_float( const QString& id, const float value ) const
{
cass_statement_bind_float_by_name( f_ptr.get(), id.toUtf8().data(), value );
}
void statement::bind_double( const size_t id, const double value ) const
{
cass_statement_bind_double( f_ptr.get(), id, value );
}
void statement::bind_double( const QString& id, const double value ) const
{
cass_statement_bind_double_by_name( f_ptr.get(), id.toUtf8().data(), value );
}
void statement::bind_string( const size_t id, const std::string& value ) const
{
bind_blob( id, value.c_str() );
}
void statement::bind_string( const QString& id, const std::string& value ) const
{
bind_blob( id, value.c_str() );
}
void statement::bind_string( const size_t id, const QString& value ) const
{
bind_blob( id, value.toUtf8() );
}
void statement::bind_string( const QString& id, const QString& value ) const
{
bind_blob( id, value.toUtf8() );
}
void statement::bind_blob( const size_t id, const QByteArray& value ) const
{
cass_statement_bind_string_n( f_ptr.get(), id, value.constData(), value.size() );
}
void statement::bind_blob( const QString& id, const QByteArray& value ) const
{
cass_statement_bind_string_by_name_n( f_ptr.get(), id.toUtf8().data(), id.size(), value.constData(), value.size() );
}
void statement::bind_collection ( const size_t id, const collection& value ) const
{
cass_statement_bind_collection( f_ptr.get(), id, value.f_ptr.get() );
}
void statement::bind_collection ( const QString& id, const collection& value ) const
{
cass_statement_bind_collection_by_name( f_ptr.get(), id.toUtf8().data(), value.f_ptr.get() );
}
//===============================================================================
// table_meta
//
table_meta::table_meta( CassTableMeta* p )
: f_ptr( p, deleter_t() )
{
}
void table_meta::deleter_t::operator()( CassTableMeta* ) const
{
//cass_table_meta_free(p);
}
iterator table_meta::get_fields() const
{
if(f_ptr == nullptr)
{
return iterator(nullptr);
}
return iterator( cass_iterator_fields_from_table_meta( f_ptr.get() ) );
}
iterator table_meta::get_columns() const
{
if(f_ptr == nullptr)
{
return iterator(nullptr);
}
return iterator( cass_iterator_columns_from_table_meta( f_ptr.get() ) );
}
QString table_meta::get_name() const
{
if(f_ptr == nullptr)
{
return QString();
}
const char * name(nullptr);
size_t len(0);
cass_table_meta_name( f_ptr.get(), &name, &len );
return QString::fromUtf8( name, len );
}
//===============================================================================
// value
//
value::value( CassValue* p )
: f_ptr(p, deleter_t() )
{
}
void value::deleter_t::operator()(CassValue*) const
{
// no deletion necessary
}
iterator value::get_iterator_from_map() const
{
if(f_ptr == nullptr)
{
return iterator(nullptr);
}
return iterator( cass_iterator_from_map(f_ptr.get()) );
}
iterator value::get_iterator_from_collection() const
{
if(f_ptr == nullptr)
{
return iterator(nullptr);
}
return iterator( cass_iterator_from_collection(f_ptr.get()) );
}
iterator value::get_iterator_from_tuple() const
{
if(f_ptr == nullptr)
{
return iterator(nullptr);
}
return iterator( cass_iterator_from_tuple(f_ptr.get()) );
}
CassValueType value::get_type() const
{
if(f_ptr == nullptr)
{
return CASS_VALUE_TYPE_UNKNOWN;
}
return cass_value_type( f_ptr.get() );
}
QString value::get_string() const
{
if(f_ptr == nullptr)
{
return QString();
}
const char * str = nullptr;
size_t len = 0;
CassError rc = cass_value_get_string( f_ptr.get(), &str, &len );
if( rc != CASS_OK )
{
throw cassandra_exception_impl( "Can't extract value string!", rc );
}
return QString::fromUtf8( str, len );
}
QByteArray value::get_blob() const
{
if(f_ptr == nullptr)
{
return QByteArray();
}
const cass_byte_t * buff = nullptr;
size_t len = 0;
CassError rc = cass_value_get_bytes( f_ptr.get(), &buff, &len );
if( rc != CASS_OK )
{
throw cassandra_exception_impl( "Cannot extract value blob!", rc );
}
return QByteArray( reinterpret_cast<const char *>(buff), len );
}
bool value::get_bool() const
{
if(f_ptr == nullptr)
{
return false;
}
cass_bool_t b = cass_false;
CassError rc = cass_value_get_bool( f_ptr.get(), &b );
if( rc != CASS_OK )
{
throw cassandra_exception_impl( "Cannot extract value!", rc );
}
return b == cass_true;
}
float value::get_float() const
{
if(f_ptr == nullptr)
{
return 0.0f;
}
cass_float_t f = 0.0f;
CassError rc = cass_value_get_float( f_ptr.get(), &f );
if( rc != CASS_OK )
{
throw cassandra_exception_impl( "Cannot extract value!", rc );
}
return static_cast<float>(f);
}
double value::get_double() const
{
if(f_ptr == nullptr)
{
return 0.0;
}
cass_double_t d = 0.0;
CassError rc = cass_value_get_double( f_ptr.get(), &d );
if( rc != CASS_OK )
{
throw cassandra_exception_impl( "Cannot extract value!", rc );
}
return static_cast<double>(d);
}
int8_t value::get_int8() const
{
if(f_ptr == nullptr)
{
return 0;
}
cass_int8_t i = 0;
CassError rc = cass_value_get_int8( f_ptr.get(), &i );
if( rc != CASS_OK )
{
throw cassandra_exception_impl( "Cannot extract value!", rc );
}
return static_cast<int8_t>(i);
}
int16_t value::get_int16() const
{
if(f_ptr == nullptr)
{
return 0;
}
cass_int16_t i = 0;
CassError rc = cass_value_get_int16( f_ptr.get(), &i );
if( rc != CASS_OK )
{
throw cassandra_exception_impl( "Cannot extract value!", rc );
}
return static_cast<int16_t>(i);
}
int32_t value::get_int32() const
{
if(f_ptr == nullptr)
{
return 0;
}
cass_int32_t i = 0;
CassError rc = cass_value_get_int32( f_ptr.get(), &i );
if( rc != CASS_OK )
{
throw cassandra_exception_impl( "Cannot extract value!", rc );
}
return static_cast<int32_t>(i);
}
int64_t value::get_int64() const
{
if(f_ptr == nullptr)
{
return 0;
}
cass_int64_t i = 0;
CassError rc = cass_value_get_int64( f_ptr.get(), &i );
if( rc != CASS_OK )
{
throw cassandra_exception_impl( "Cannot extract value!", rc );
}
return static_cast<qlonglong>(i);
}
QString value::get_uuid() const
{
if(f_ptr == nullptr)
{
return 0;
}
CassUuid uuid = CassUuid();
CassError rc = cass_value_get_uuid( f_ptr.get(), &uuid );
if( rc == CASS_OK )
{
char str[CASS_UUID_STRING_LENGTH+1];
cass_uuid_string( uuid, str );
return QString(str);
}
return QString();
}
qulonglong value::get_uuid_timestamp() const
{
if(f_ptr == nullptr)
{
return 0;
}
CassUuid uuid = CassUuid();
CassError rc = cass_value_get_uuid( f_ptr.get(), &uuid );
if( rc == CASS_OK )
{
return static_cast<qulonglong>(cass_uuid_timestamp( uuid ));
}
return 0;
}
QString value::get_inet() const
{
if(f_ptr == nullptr)
{
return QString();
}
CassInet inet = CassInet();
CassError rc = cass_value_get_inet( f_ptr.get(), &inet );
if( rc == CASS_OK )
{
char str[CASS_UUID_STRING_LENGTH + 1];
cass_inet_string( inet, str );
return QString(str);
}
return QString();
}
}
// namespace casswrapper
// vim: ts=4 sw=4 et
|
f387063136c7ed8b62b82cf635faf28f33d9cf72
|
8ac181aa59bbc34aa457ed90273b56763269859d
|
/Additional/Matrix_Exponentiation.cpp
|
e58562a511a365fae44545ff0fb8e8468bf3dc6d
|
[] |
no_license
|
mohitmp9107/Competitive-Programming-
|
d8a85d37ad6eccb1c70e065f592f46961bdb21cf
|
d42ef49bfcd80ebfc87a75b544cf9d7d5afcc968
|
refs/heads/master
| 2021-07-11T11:09:14.808893
| 2020-10-03T08:15:36
| 2020-10-03T08:15:36
| 206,331,473
| 0
| 4
| null | 2020-10-03T08:15:38
| 2019-09-04T13:54:46
|
C++
|
UTF-8
|
C++
| false
| false
| 807
|
cpp
|
Matrix_Exponentiation.cpp
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
void multiply(int A[2][2], int M[2][2])
{
int fvalue=A[0][0]*M[0][0]+A[0][1]*M[1][0];
int svalue=A[0][0]*M[0][1]+A[0][1]*M[1][1];
int tvalue=A[1][0]*M[0][0]+A[1][1]*M[1][0];
int lvalue=A[1][0]*M[0][1]+A[1][1]*M[1][1];
A[0][0]=fvalue;A[0][1]=svalue;A[1][0]=tvalue;
A[1][1]=lvalue;
}
void power(int A[2][2], int n)
{
if(n==0 or n==1) return;
power(A,n/2);
multiply(A,A); // Multiplying A^n/2 with A^n/2
if(n&2){
int M[2][2]={{1,1},{1,0}};
multiply(A,M);
}
}
int fib(int n)
{
int A[2][2]={{1,1},{1,0}};
if(!n) return 0;
power(A,n-1);
return A[0][0];
}
int main()
{
//This gives fibonacci sequence in o(log(n))
ll n; cin >> n;
cout << fib(n) << endl;
}
|
2b659bc65b1edcf00b08a3da40f5b16d88e577c5
|
19ded9a8a236bf86c4f39dc397b50adf94f4c1b3
|
/ui/NovaFX/NovaVariables.h
|
2f1ce73e52e5eb5d0077569c01ac97386d4eef7d
|
[
"MIT"
] |
permissive
|
vakuras/moleculardynamics
|
622b2dbe76279b79eac59f8dfb2539e64926f990
|
f9c6b03db7df8e429f72fa17b5ccfd98d08ee272
|
refs/heads/master
| 2021-01-02T23:10:38.961894
| 2017-08-06T11:54:08
| 2017-08-06T11:54:08
| 99,483,198
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,275
|
h
|
NovaVariables.h
|
///
/// NovaFX Variables Header
///
/// Written by Vadim Kuras. 2010.
///
#ifndef NOVAVARS_H
#define NOVAVARS_H
#include <Windows.h>
#include <gl\GL.h>
#include <gl\GLU.h>
#include <cmath>
namespace NovaFX
{
struct Nfloat3
{
GLfloat x;
GLfloat y;
GLfloat z;
Nfloat3() {}
Nfloat3(GLfloat x, GLfloat y, GLfloat z);
Nfloat3 operator+(const Nfloat3 & other);
Nfloat3 operator-(const Nfloat3 & other);
Nfloat3 operator*(const GLfloat & other);
GLfloat operator*(const Nfloat3 & other);
GLfloat Length(Nfloat3 * v);
Nfloat3 CrossProduct(const Nfloat3 & other);
Nfloat3 Normalize();
};
struct Nfloat4
{
GLfloat x;
GLfloat y;
GLfloat z;
GLfloat w;
};
struct GLRGBA
{
GLfloat r;
GLfloat g;
GLfloat b;
GLfloat a;
GLRGBA(){}
GLRGBA(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
};
struct NSphere
{
Nfloat4 * pos;
GLuint slices;
GLuint stacks;
GLRGBA color;
NSphere();
~NSphere();
};
struct NCylinder
{
Nfloat4 * pos;
Nfloat3 * left;
Nfloat3 * up;
Nfloat3 * forward;
GLuint slices;
GLuint stacks;
GLfloat baseRadius;
GLfloat topRadius;
GLRGBA color;
NCylinder();
~NCylinder();
};
}
#endif
|
40d0305e77e4a5e18c4bf86bbd17c40ce3694c74
|
2f78e134c5b55c816fa8ee939f54bde4918696a5
|
/code/physics/xmlinterfaces.h
|
7c5bdd5c1dde5d5a88581bbe3b523a30a5ce333d
|
[] |
no_license
|
narayanr7/HeavenlySword
|
b53afa6a7a6c344e9a139279fbbd74bfbe70350c
|
a255b26020933e2336f024558fefcdddb48038b2
|
refs/heads/master
| 2022-08-23T01:32:46.029376
| 2020-05-26T04:45:56
| 2020-05-26T04:45:56
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 40,951
|
h
|
xmlinterfaces.h
|
//---------------------------------------------------------------------------------------------------------
//!
//! \file physics/system.h
//!
//! DYNAMICS COMPONENT:
//! The system encapsulate the physical representation of an entity.
//!
//! Author: Mustapha Bismi (mustapha.bismi@ninjatheory.com)
//! Created: 2005.07.11
//!
//---------------------------------------------------------------------------------------------------------
#ifndef _DYNAMICS_XML_INTERFACES_INC
#define _DYNAMICS_XML_INTERFACES_INC
#include "config.h"
#include <hkbase\config\hkConfigVersion.h>
#include "anim/hierarchy.h"
#include "game/entity.h"
#include "game/entity.inl"
#include "anim/hierarchy.h"
#include "rigidbody.h"
#include "maths_tools.h"
#include "world.h"
#include "core/exportstruct_clump.h"
#include "meshshape.h"
#ifndef _PS3_RUN_WITHOUT_HAVOK_BUILD
#include <hkdynamics/entity/hkRigidBody.h>
#include <hkutilities/collide/hkShapeShrinker.h>
#include <hkcollide/shape/capsule/hkCapsuleShape.h>
#include <hkcollide/shape/sphere/hkSphereShape.h>
#include <hkcollide/shape/box/hkBoxShape.h>
#include <hkcollide/shape/cylinder/hkCylinderShape.h>
#include <hkcollide/shape/heightfield/hkHeightFieldShape.h>
#include <hkcollide/shape/list/hkListShape.h>
#include <hkcollide/shape/mesh/hkMeshShape.h>
#include <hkcollide/shape/transform/hkTransformShape.h>
#include <hkcollide/shape/convextransform/hkConvexTransformShape.h>
#include <hkcollide/shape/convexvertices/hkConvexVerticesShape.h>
#include <hkcollide/shape/convexlist/hkConvexListShape.h>
#include <hkinternal/preprocess/convexhull/hkGeometryUtility.h>
#include <hkutilities/inertia/hkinertiatensorcomputer.h>
#include <hkdynamics\constraint\bilateral\hinge\hkHingeConstraintData.h>
#include <hkdynamics\constraint\hkConstraintInstance.h>
#include <hkdynamics/constraint/motor/hkConstraintMotor.h>
#include <hkdynamics\constraint\motor\position\hkPositionConstraintMotor.h>
#include <hkdynamics\constraint\motor\velocity\hkVelocityConstraintMotor.h>
#include <hkdynamics\constraint\motor\springdamper\hkSpringDamperConstraintMotor.h>
#include <hkdynamics\constraint\bilateral\ballandsocket\hkBallAndSocketConstraintData.h>
#include <hkdynamics\constraint\bilateral\limitedhinge\hkLimitedHingeConstraintData.h>
#include <hkdynamics\constraint\bilateral\prismatic\hkPrismaticConstraintData.h>
#include <hkdynamics\constraint\bilateral\stiffspring\hkStiffSpringConstraintData.h>
#include <hkdynamics\constraint\bilateral\wheel\hkWheelConstraintData.h>
#include <hkdynamics\constraint\breakable\hkBreakableConstraintData.h>
#include <hkdynamics\constraint\malleable\hkMalleableConstraintData.h>
#include <hkinternal/dynamics/constraint/bilateral/ragdoll/hkRagdollConstraintData.h>
#include <hkutilities/actions/spring/hkSpringAction.h>
#include <hkcollide/shape/mopp/hkMoppUtility.h>
#include <hkcollide/shape/mopp/hkMoppBvTreeShape.h>
#endif
#include "physicsLoader.h"
enum MOTION_TYPE {
STATIC = 0,
KEYFRAMED,
DYNAMIC,
};
enum QUALITY {
HS_COLLIDABLE_QUALITY_FIXED = 0,
HS_COLLIDABLE_QUALITY_KEYFRAMED,
HS_COLLIDABLE_QUALITY_DEBRIS,
HS_COLLIDABLE_QUALITY_MOVING,
HS_COLLIDABLE_QUALITY_CRITICAL,
HS_COLLIDABLE_QUALITY_BULLET
};
#define EXTRA_RADIUS_FOR_CONVEX 0.02f // see hkConvexShape::setRadius
// True if shape type was inhereted from hkConvexShape
inline bool IsConvex(hkShape * shape)
{
switch (shape->getType())
{
case HK_SHAPE_CONVEX :
case HK_SHAPE_SPHERE :
case HK_SHAPE_CYLINDER :
case HK_SHAPE_TRIANGLE :
case HK_SHAPE_BOX :
case HK_SHAPE_CAPSULE :
case HK_SHAPE_CONVEX_VERTICES :
case HK_SHAPE_CONVEX_PIECE :
case HK_SHAPE_CONVEX_TRANSLATE :
case HK_SHAPE_CONVEX_TRANSFORM :
return true;
default:
return false;
}
}
inline bool AreConvex(hkShape ** shape, int n)
{
for(int i = 0; i < n; i++)
if (!IsConvex(shape[i]))
return false;
return true;
}
// Returns true if shapes can be added into one hkConvexListShape
inline bool AreReadyForConvexListShape(hkShape ** shape, int n)
{
if (!AreConvex(shape,n))
return false;
float radius = static_cast<hkConvexShape *>(shape[0])->getRadius();
for(int i = 1; i < n; i++)
if (fabs(static_cast<hkConvexShape *>(shape[i])->getRadius() - radius) > 0.01f)
return false;
return true;
}
//Creates hkConvexListShape if it is possible, hkListShape otherwise.
hkShape * CreateListShape(hkShape ** list, int n);
//Creates hkConvexTransformShape if shape is convex, hkTransformShape otherwise.
// BEWARE: function also removeReference() from input shape.
hkShape * CreateTransformShape(hkShape *shape, const hkTransform& trf);
class psShape
{
public:
//! Data. --------------------------------------------------------------------
uint32_t m_iMaterialId;
//! Accessors. ---------------------------------------------------------------
uint32_t GetMaterialId( void ) const { return m_iMaterialId; };
void SetMaterialId( const uint32_t &iMaterialId ) { m_iMaterialId = iMaterialId; };
virtual ~psShape() {};
#ifndef _PS3_RUN_WITHOUT_HAVOK_BUILD
virtual hkShape* BuildShape() {return NULL;};
virtual hkShape* BuildStaticShape() {return BuildShape();};
#endif
};
class psShapeTrfLink
{
public:
int m_trfIndex;
psShape * m_shape;
};
inline bool TransformWouldBeIdentity( const CQuat &rotation, const CPoint &translation )
{
ntError( rotation.IsNormalised() );
if ( !rotation.IsNormalised() )
{
// This is just a default pass through - shouldn't ever be here though.
return false;
}
if ( fabsf( rotation.W() - 1.0f ) < 0.001f && translation.Length() < 0.001f )
{
return true;
}
return false;
}
// ---------------------------------------------------------------
// This class is used by the xml parser to load the physics data.
// ---------------------------------------------------------------
class psBoxShape : public psShape
{
public:
//! Data. --------------------------------------------------------------------
CPoint m_fTranslation;
CQuat m_fRotation;
CVector m_obHalfExtent;
//! Accessors. ---------------------------------------------------------------
CPoint GetPosition( void ) const { return m_fTranslation; }
void SetPosition( const CPoint &obPoint ) { m_fTranslation = obPoint; }
CQuat GetRotation( void ) const { return m_fRotation; }
void SetRotation( const CQuat& obRot ) { m_fRotation = obRot; }
CVector GetHalfExtent( void ) const { return m_obHalfExtent; }
void SetHalfExtent( const CVector &obPoint ) { m_obHalfExtent = obPoint; }
#ifndef _PS3_RUN_WITHOUT_HAVOK_BUILD
virtual hkShape* BuildShape()
{
m_fRotation.Normalise();
hkBoxShape* shape = HK_NEW hkBoxShape( Physics::MathsTools::CVectorTohkVector( m_obHalfExtent ) );
shape->setRadius( EXTRA_RADIUS_FOR_CONVEX );
// EEKK! this was only being done on the PC build which means all our collision have been different between
// the two... this really needs to be done on export
hkShapeShrinker::shrinkByConvexRadius( shape, 0 );
Physics::PhysicsMaterialTable& matTable = Physics::PhysicsMaterialTable::Get();
#if HAVOK_SDK_VERSION_MAJOR == 4 && HAVOK_SDK_VERSION_MINOR == 0
shape->setUserData(matTable.GetMaterialFromId(m_iMaterialId));
#else
shape->setUserData((hkUlong) matTable.GetMaterialFromId( m_iMaterialId));
#endif // HAVOK_SDK_VERSION_MAJOR
if ( TransformWouldBeIdentity( m_fRotation, m_fTranslation ) )
{
return shape;
}
hkTransform trf = hkTransform( Physics::MathsTools::CQuatTohkQuaternion( m_fRotation ) ,
Physics::MathsTools::CPointTohkVector( m_fTranslation ) );
hkShape* s = HK_NEW hkConvexTransformShape( shape, trf );
s->setUserData(shape->getUserData());
shape->removeReference();
return s;
}
#endif
};
// ---------------------------------------------------------------
// This class is used by the xml parser to load the physics data.
// ---------------------------------------------------------------
class psCapsuleShape : public psShape
{
public:
//! Data. --------------------------------------------------------------------
CPoint m_fTranslation;
CQuat m_fRotation;
CVector m_obVertexA;
CVector m_obVertexB;
float m_fRadius;
//! Accessors. ---------------------------------------------------------------
CPoint GetPosition( void ) const { return m_fTranslation; }
void SetPosition( const CPoint &obPoint ) { m_fTranslation = obPoint; }
CQuat GetRotation( void ) const { return m_fRotation; }
void SetRotation( const CQuat& obRot ) { m_fRotation = obRot; }
CVector GetVertexA( void ) const { return m_obVertexA; }
void SetVertexA( const CVector &obPoint ) { m_obVertexA = obPoint; }
void SetVertexB( const CVector &obPoint ) { m_obVertexB = obPoint; }
CVector GetVertexB( void ) const { return m_obVertexB; }
#ifndef _PS3_RUN_WITHOUT_HAVOK_BUILD
virtual hkShape* BuildShape()
{
m_fRotation.Normalise();
hkCapsuleShape* shape = HK_NEW hkCapsuleShape( Physics::MathsTools::CVectorTohkVector(m_obVertexA),
Physics::MathsTools::CVectorTohkVector(m_obVertexB),
m_fRadius );
Physics::PhysicsMaterialTable& matTable = Physics::PhysicsMaterialTable::Get();
#if HAVOK_SDK_VERSION_MAJOR == 4 && HAVOK_SDK_VERSION_MINOR == 0
shape->setUserData(matTable.GetMaterialFromId(m_iMaterialId));
#else
shape->setUserData((hkUlong) matTable.GetMaterialFromId( m_iMaterialId));
#endif //HAVOK_SDK_VERSION_MINOR;
// Don't apply a transform is we don't need one.
if ( TransformWouldBeIdentity( m_fRotation, m_fTranslation ) )
{
return shape;
}
hkTransform trf = hkTransform( Physics::MathsTools::CQuatTohkQuaternion( m_fRotation ) ,
Physics::MathsTools::CPointTohkVector( m_fTranslation ) );
hkShape * s = HK_NEW hkConvexTransformShape( shape, trf );
s->setUserData(shape->getUserData());
shape->removeReference();
return s;
}
#endif
};
// ---------------------------------------------------------------
// This class is used by the xml parser to load the physics data.
// ---------------------------------------------------------------
class psCylinderShape : public psShape
{
public:
//! Data. --------------------------------------------------------------------
CPoint m_fTranslation;
CQuat m_fRotation;
CVector m_obVertexA;
CVector m_obVertexB;
float m_fRadius;
//! Accessors. ---------------------------------------------------------------
CPoint GetPosition( void ) const { return m_fTranslation; }
void SetPosition( const CPoint &obPoint ) { m_fTranslation = obPoint; }
CQuat GetRotation( void ) const { return m_fRotation; }
void SetRotation( const CQuat& obRot ) { m_fRotation = obRot; }
CVector GetVertexA( void ) const { return m_obVertexA; }
void SetVertexA( const CVector &obPoint ) { m_obVertexA = obPoint; }
void SetVertexB( const CVector &obPoint ) { m_obVertexB = obPoint; }
CVector GetVertexB( void ) const { return m_obVertexB; }
#ifndef _PS3_RUN_WITHOUT_HAVOK_BUILD
virtual hkShape* BuildShape()
{
m_fRotation.Normalise();
hkCylinderShape* shape = HK_NEW hkCylinderShape( Physics::MathsTools::CVectorTohkVector(m_obVertexA),
Physics::MathsTools::CVectorTohkVector(m_obVertexB),
m_fRadius );
Physics::PhysicsMaterialTable& matTable = Physics::PhysicsMaterialTable::Get();
#if HAVOK_SDK_VERSION_MAJOR == 4 && HAVOK_SDK_VERSION_MINOR == 0
shape->setUserData(matTable.GetMaterialFromId(m_iMaterialId));
#else
shape->setUserData((hkUlong) matTable.GetMaterialFromId( m_iMaterialId));
#endif //HAVOK_SDK_VERSION_MINOR
shape->setRadius( EXTRA_RADIUS_FOR_CONVEX);
// EEKK! this was only being done on the PC build which means all our collision have been different between
// the two... this really needs to be done on export
hkShapeShrinker::shrinkByConvexRadius( shape, 0 );
if ( TransformWouldBeIdentity( m_fRotation, m_fTranslation ) )
{
return shape;
}
hkTransform trf = hkTransform( Physics::MathsTools::CQuatTohkQuaternion( m_fRotation ) ,
Physics::MathsTools::CPointTohkVector( m_fTranslation ) );
hkShape* s = HK_NEW hkConvexTransformShape( shape, trf );
s->setUserData(shape->getUserData());
shape->removeReference();
return s;
}
#endif
};
// ---------------------------------------------------------------
// This class is used by the xml parser to load the physics data.
// ---------------------------------------------------------------
class psSphereShape : public psShape
{
public:
//! Data. --------------------------------------------------------------------
CPoint m_fTranslation;
CQuat m_fRotation;
float m_fRadius;
//! Accessors. ---------------------------------------------------------------
CPoint GetPosition( void ) const { return m_fTranslation; }
void SetPosition( const CPoint &obPoint ) { m_fTranslation = obPoint; }
CQuat GetRotation( void ) const { return m_fRotation; }
void SetRotation( const CQuat& obRot ) { m_fRotation = obRot; }
#ifndef _PS3_RUN_WITHOUT_HAVOK_BUILD
virtual hkShape* BuildShape()
{
m_fRotation.Normalise();
hkSphereShape* shape = HK_NEW hkSphereShape( m_fRadius );
Physics::PhysicsMaterialTable& matTable = Physics::PhysicsMaterialTable::Get();
#if HAVOK_SDK_VERSION_MAJOR == 4 && HAVOK_SDK_VERSION_MINOR == 0
shape->setUserData(matTable.GetMaterialFromId(m_iMaterialId));
#else
shape->setUserData((hkUlong) matTable.GetMaterialFromId( m_iMaterialId));
#endif //HAVOK_SDK_VERSION_MINOR
// Don't apply a transform is we don't need one.
if ( TransformWouldBeIdentity( m_fRotation, m_fTranslation ) )
{
return shape;
}
hkTransform trf = hkTransform( Physics::MathsTools::CQuatTohkQuaternion( m_fRotation ) ,
Physics::MathsTools::CPointTohkVector( m_fTranslation ) );
hkShape* s = HK_NEW hkConvexTransformShape( shape, trf );
s->setUserData(shape->getUserData());
shape->removeReference();
return s;
}
#endif
};
// ---------------------------------------------------------------
// This class is used by the xml parser to load the physics data.
// ---------------------------------------------------------------
class psListShape : public psShape
{
public:
//! Data. --------------------------------------------------------------------
typedef ntstd::List<void*,MC_PHYSICS> ShapeGuidList;
ShapeGuidList m_shapesGuids;
#ifndef _PS3_RUN_WITHOUT_HAVOK_BUILD
virtual hkShape* BuildShape()
{
hkShape** shapeArray = NT_NEW_ARRAY_CHUNK ( MC_PHYSICS ) hkShape*[m_shapesGuids.size()];
ShapeGuidList::iterator it = m_shapesGuids.begin();
for( unsigned int i = 0; i < m_shapesGuids.size(); i++ )
{
void* shapeptr = *it;
psShape* shape = (psShape*)shapeptr;
shapeArray[i] = shape->BuildShape();
++it;
}
hkShape* shape = CreateListShape( shapeArray, m_shapesGuids.size());
NT_DELETE_ARRAY_CHUNK( MC_PHYSICS, shapeArray );
return shape;
};
#endif
};
// ---------------------------------------------------------------
// This class is used by the xml parser to load the physics data.
// ---------------------------------------------------------------
class psConvexVerticesShape : public psShape
{
public:
//! Data. --------------------------------------------------------------------
CPoint m_fTranslation;
CQuat m_fRotation;
int m_eStride;
int m_iNumVertices;
ntstd::List<float, MC_PHYSICS> m_obVertexBuffer;
//! Accessors. ---------------------------------------------------------------
CPoint GetPosition( void ) const { return m_fTranslation; };
void SetPosition( const CPoint &obPoint ) { m_fTranslation = obPoint; };
CQuat GetRotation( void ) const { return m_fRotation; };
void SetRotation( const CQuat& obRot ) { m_fRotation = obRot; };
#ifndef _PS3_RUN_WITHOUT_HAVOK_BUILD
virtual hkShape* BuildShape()
{
m_fRotation.Normalise();
float* vertices = NT_NEW_ARRAY_CHUNK ( MC_PHYSICS ) float[m_iNumVertices*4];
ntstd::List<float, MC_PHYSICS>::iterator it = m_obVertexBuffer.begin();
for( int i = 0; i < m_iNumVertices*4; i++ )
{
vertices[i] = (*it);
it++;
}
hkConvexVerticesShape* shape;
hkArray<hkVector4> planeEquations;
hkGeometry geom;
hkStridedVertices stridedVerts;
stridedVerts.m_numVertices = m_iNumVertices;
stridedVerts.m_striding = m_eStride;
stridedVerts.m_vertices = vertices;
hkGeometryUtility::createConvexGeometry( stridedVerts, geom, planeEquations );
stridedVerts.m_numVertices = geom.m_vertices.getSize();
stridedVerts.m_striding = sizeof(hkVector4);
stridedVerts.m_vertices = &(geom.m_vertices[0](0));
shape = HK_NEW hkConvexVerticesShape(stridedVerts, planeEquations);
NT_DELETE_ARRAY( vertices );
shape->setRadius( EXTRA_RADIUS_FOR_CONVEX );
Physics::PhysicsMaterialTable& matTable = Physics::PhysicsMaterialTable::Get();
#if HAVOK_SDK_VERSION_MAJOR == 4 && HAVOK_SDK_VERSION_MINOR == 0
shape->setUserData(matTable.GetMaterialFromId(m_iMaterialId));
#else
shape->setUserData((hkUlong) matTable.GetMaterialFromId( m_iMaterialId));
#endif //HAVOK_SDK_VERSION_MINOR
if ( TransformWouldBeIdentity( m_fRotation, m_fTranslation ) )
{
return shape;
}
//hkConvexVerticesShape* shape = NT_NEW hkConvexVerticesShape( m_fRadius );
hkTransform trf = hkTransform( Physics::MathsTools::CQuatTohkQuaternion( m_fRotation ) ,
Physics::MathsTools::CPointTohkVector( m_fTranslation ) );
hkShape * s = HK_NEW hkConvexTransformShape( shape, trf );
s->setUserData(shape->getUserData());
shape->removeReference();
return s;
};
#endif
};
// ---------------------------------------------------------------
// This class is used by the xml parser to load the physics data.
// ---------------------------------------------------------------
//static int s_MemoryInStaticShapes = 0;
class psMeshShape : public psShape
{
public:
//! Data. --------------------------------------------------------------------
CPoint m_fTranslation;
CQuat m_fRotation;
int m_eStride;
int m_iNumVertices;
int m_iIndices;
ntstd::List<int, MC_PHYSICS> m_obIndexBuffer;
ntstd::List<float, MC_PHYSICS> m_obVertexBuffer;
ntstd::List<uint32_t, MC_PHYSICS> m_obMaterialBuffer;
//! Accessors. ---------------------------------------------------------------
CPoint GetPosition( void ) const { return m_fTranslation; };
void SetPosition( const CPoint &obPoint ) { m_fTranslation = obPoint; };
CQuat GetRotation( void ) const { return m_fRotation; };
void SetRotation( const CQuat& obRot ) { m_fRotation = obRot; };
psMeshShape(){};
virtual ~psMeshShape() {};
#ifndef _PS3_RUN_WITHOUT_HAVOK_BUILD
virtual hkShape* BuildShape()
{
m_fRotation.Normalise();
float* vertices = 0;
hkInt16* indexes = 0;
hkUint8* materialIndexes = 0;
Physics::hsMeshMaterial* materialBase =0;
int numMaterials = 0;
vertices = NT_NEW_CHUNK( MC_PHYSICS ) float[m_iNumVertices*3];
//s_MemoryInStaticShapes += sizeof(float) * m_iNumVertices * 3;
ntstd::List<float, MC_PHYSICS>::iterator it = m_obVertexBuffer.begin();
for( int i = 0; i < m_iNumVertices; i++ )
{
vertices[i*3] = (*it);
it++;
vertices[i*3+1] = (*it);
it++;
vertices[i*3+2] = (*it);
it++;
it++;
}
indexes = NT_NEW_CHUNK( MC_PHYSICS ) hkInt16[m_iIndices];
//s_MemoryInStaticShapes += sizeof(hkInt16) * m_iIndices;
ntstd::List<int, MC_PHYSICS>::iterator it2 = m_obIndexBuffer.begin();
for( int i = (m_iIndices-1); i >= 0; i-- )
{
indexes[i] = (hkInt16)(*it2);
it2++;
}
if (m_obMaterialBuffer.size() > 0)
{
// Materials, get materials IDs and create mapping between mech material table and IDs.
ntstd::Set<uint32_t> mapping;
for( ntstd::List<uint32_t, MC_PHYSICS>::iterator it = m_obMaterialBuffer.begin(); it != m_obMaterialBuffer.end(); ++it)
{
++it; // skip triangle number
mapping.insert( *it);
}
ntAssert(mapping.size() < 256); //havok supports only 256 materials for subpart
numMaterials = mapping.size() + 1;
// Create mesh materials. The first one is "dummy" means no material for triangle was set
materialBase = NT_NEW_CHUNK( MC_PHYSICS ) Physics::hsMeshMaterial[mapping.size() + 1];
//s_MemoryInStaticShapes += sizeof( Physics::hsMeshMaterial) * (mapping.size() + 1);
Physics::PhysicsMaterialTable& matTable = Physics::PhysicsMaterialTable::Get();
ntstd::Set<uint32_t>::iterator it = mapping.begin();
for(unsigned int i = 0 ; i < mapping.size(); i++, ++it)
{
materialBase[i+1].SetMaterial(matTable.GetMaterialFromId(*it));
}
// Allocate memory for material indexes
materialIndexes = NT_NEW_CHUNK( MC_PHYSICS ) hkUint8[m_iIndices / 3]; // number of triangles is m_iIndices / 3
//s_MemoryInStaticShapes += sizeof( hkUint8) * (m_iIndices / 3);
memset(materialIndexes, 0x0, m_iIndices / 3 * sizeof(*materialIndexes));
for( ntstd::List<uint32_t, MC_PHYSICS>::iterator it = m_obMaterialBuffer.begin(); it != m_obMaterialBuffer.end(); ++it)
{
uint32_t triangleId = *it;
++it; // skip triangle number
materialIndexes[triangleId] = (hkUint8) distance(mapping.begin(),mapping.find(*it)) + 1;
}
}
else
numMaterials = 0;
Physics::hsMeshShape* shape = HK_NEW Physics::hsMeshShape();
shape->setRadius( 0.0f );
{
hkMeshShape::Subpart part;
//m_obVertexBuffer._Myhead
//ntstd::List<float>::iterator it = m_obVertexBuffer.begin();
part.m_vertexBase = vertices;
part.m_vertexStriding = sizeof(float) * 3;
part.m_numVertices = m_iNumVertices * 3;
part.m_indexBase = indexes;
part.m_indexStriding = sizeof(hkInt16) * 3;
part.m_numTriangles = m_iIndices / 3;
part.m_stridingType = hkMeshShape::INDICES_INT16;
if (numMaterials > 0)
{
part.m_materialIndexStridingType = hkMeshShape::MATERIAL_INDICES_INT8;
part.m_materialIndexStriding = sizeof(hkUint8);
part.m_materialIndexBase = materialIndexes;
part.m_materialStriding = sizeof(Physics::hsMeshMaterial);
part.m_materialBase = materialBase;
part.m_numMaterials = numMaterials;
}
else
{
part.m_materialIndexBase = HK_NULL;
part.m_materialBase = HK_NULL;
part.m_numMaterials = 0;
}
shape->addSubpart( part );
}
hkMoppFitToleranceRequirements obMft;
hkMoppCode* pobMoppCode = hkMoppUtility::buildCode( shape, obMft );
hkShape* ss = HK_NEW hkMoppBvTreeShape( shape, pobMoppCode );
shape->removeReference();
ss->setUserData(INVALID_MATERIAL);
//NT_DELETE_ARRAY( vertices );
// Don't apply a transform is we don't need one.
if ( m_fTranslation.Length() < 0.001f && ( CVector( m_fRotation ) - CVector( 0.0f, 0.0f, 0.0f, 1.0f ) ).Length() < 0.001f )
{
return ss;
}
hkTransform trf = hkTransform( Physics::MathsTools::CQuatTohkQuaternion( m_fRotation ) ,
Physics::MathsTools::CPointTohkVector( m_fTranslation ) );
hkShape * s = HK_NEW hkTransformShape( ss, trf );
ss->removeReference();
s->setUserData(INVALID_MATERIAL);
return s;
};
virtual hkShape* BuildStaticShape()
{
m_fRotation.Normalise();
float* vertices = 0;
hkInt16* indexes = 0;
hkUint8* materialIndexes = 0;
Physics::hsMeshMaterial* materialBase =0;
int numMaterials = 0;
vertices = NT_NEW_CHUNK( MC_PHYSICS ) float[m_iNumVertices*3];
//s_MemoryInStaticShapes += m_iNumVertices*3 * sizeof(float);
ntstd::List<float, MC_PHYSICS>::iterator it = m_obVertexBuffer.begin();
for( int i = 0; i < m_iNumVertices; i++ )
{
vertices[i*3] = (*it);
it++;
vertices[i*3+1] = (*it);
it++;
vertices[i*3+2] = (*it);
it++;
it++;
}
CMatrix trf( m_fRotation, m_fTranslation );
for( int i = 0; i < m_iNumVertices; i++ )
{
int vert = i*3;
CVector vertx( vertices[vert], vertices[vert + 1], vertices[vert + 2], 1.0f );
vertx = vertx * trf;
vertices[vert] = vertx.X();
vertices[vert+1] = vertx.Y();
vertices[vert+2] = vertx.Z();
}
indexes = NT_NEW_CHUNK( MC_PHYSICS ) hkInt16[m_iIndices];
//s_MemoryInStaticShapes += m_iIndices * sizeof(hkInt16);
ntstd::List<int, MC_PHYSICS>::iterator it2 = m_obIndexBuffer.begin();
for( int i = (m_iIndices-1); i >= 0; i-- )
{
indexes[i] = (hkInt16)(*it2);
it2++;
}
if (m_obMaterialBuffer.size() > 0)
{
// Materials, get materials IDs and create mapping between mech material table and IDs.
ntstd::Set<uint32_t> mapping;
for( ntstd::List<uint32_t, MC_PHYSICS>::iterator it = m_obMaterialBuffer.begin(); it != m_obMaterialBuffer.end(); ++it)
{
++it; // skip triangle number
mapping.insert( *it);
}
ntAssert(mapping.size() < 256); //havok supports only 256 materials for subpart
numMaterials = mapping.size() + 1;
// Create mesh materials. The first one is "dummy" means no material for triangle was set
materialBase = NT_NEW_CHUNK( MC_PHYSICS ) Physics::hsMeshMaterial[mapping.size() + 1];
//s_MemoryInStaticShapes += sizeof( Physics::hsMeshMaterial) * (mapping.size() + 1);
Physics::PhysicsMaterialTable& matTable = Physics::PhysicsMaterialTable::Get();
ntstd::Set<uint32_t>::iterator it = mapping.begin();
for(unsigned int i = 0 ; i < mapping.size(); i++, ++it)
{
materialBase[i+1].SetMaterial(matTable.GetMaterialFromId(*it));
}
// Allocate memory for material indexes
materialIndexes = NT_NEW_CHUNK( MC_PHYSICS ) hkUint8[m_iIndices / 3]; // number of triangles is m_iIndices / 3
//s_MemoryInStaticShapes += sizeof(hkUint8) * (m_iIndices / 3);
memset(materialIndexes, 0x0, m_iIndices / 3 * sizeof(*materialIndexes));
for( ntstd::List<uint32_t, MC_PHYSICS>::iterator it = m_obMaterialBuffer.begin(); it != m_obMaterialBuffer.end(); ++it)
{
uint32_t triangleId = *it;
++it; // skip triangle number
materialIndexes[triangleId] = (hkUint8) distance(mapping.begin(),mapping.find(*it)) + 1;
}
}
else
numMaterials = 0;
Physics::hsMeshShape* shape = HK_NEW Physics::hsMeshShape();
shape->setRadius( 0.0f );
{
hkMeshShape::Subpart part;
//m_obVertexBuffer._Myhead
//ntstd::List<float>::iterator it = m_obVertexBuffer.begin();
part.m_vertexBase = vertices;
part.m_vertexStriding = sizeof(float) * 3;
part.m_numVertices = m_iNumVertices * 3;
part.m_indexBase = indexes;
part.m_indexStriding = sizeof(hkInt16) * 3;
part.m_numTriangles = m_iIndices / 3;
part.m_stridingType = hkMeshShape::INDICES_INT16;
if (numMaterials > 0)
{
part.m_materialIndexStridingType = hkMeshShape::MATERIAL_INDICES_INT8;
part.m_materialIndexStriding = sizeof(hkUint8);
part.m_materialIndexBase = materialIndexes;
part.m_materialStriding = sizeof(Physics::hsMeshMaterial);
part.m_materialBase = materialBase;
part.m_numMaterials = numMaterials;
}
else
{
part.m_materialIndexBase = HK_NULL;
part.m_materialBase = HK_NULL;
part.m_numMaterials = 0;
}
shape->addSubpart( part );
}
//ntPrintf("s_MemoryInStaticShapes %d\n", s_MemoryInStaticShapes);
hkMoppFitToleranceRequirements obMft;
hkMoppCode* pobMoppCode = hkMoppUtility::buildCode( shape, obMft );
hkShape* s = HK_NEW hkMoppBvTreeShape( shape, pobMoppCode );
shape->removeReference();
s->setUserData(INVALID_MATERIAL);
return s;
//shape->setUserData(INVALID_MATERIAL);
//return shape;
};
#endif
};
// ---------------------------------------------------------------
// This class is used by the xml parser to load the physics data.
// ---------------------------------------------------------------
class psRigidBody
{
public:
hkRigidBody* m_associatedRigid;
psRigidBody()
{
m_associatedRigid = 0;
}
//! Data. --------------------------------------------------------------------
Physics::BodyCInfo m_info;
psShape* m_shape;
unsigned int m_uiTransformHash;
// MOTION_DYNAMIC = 2 MOTION_KEYFRAMED = 1 MOTION_FIXED = 0
int m_eMotionType;
int m_eQualityType;
CPoint m_fTranslation;
CQuat m_fRotation;
CPoint m_fMassCenterOffset;
float m_fMaxLinearVelocity;
float m_fMaxAngularVelocity;
// Unused rigid body properties
//ntstd::List<float> m_obInertia;
//bool m_bInactive;
//bool m_bDisabled;
//bool m_bBoundingVolume;
//int m_iNumShapes;
//int m_iCollisionFilter_I_Am;
//int m_iCollisionFilter_I_Collide_With;
//ntstd::String m_pcMaterialName;
//! Accessors. ---------------------------------------------------------------
CPoint GetPosition( void ) const { return m_fTranslation; };
void SetPosition( const CPoint &obPoint ) { m_fTranslation = obPoint; };
CQuat GetRotation( void ) const { return m_fRotation; };
void SetRotation( const CQuat& obRot ) { m_fRotation = obRot; };
CPoint GetMassCenterOffset( void ) const { return m_fMassCenterOffset; };
void SetMassCenterOffset( const CPoint &obMassCenter ) { m_fMassCenterOffset = obMassCenter; };
Physics::BodyCInfo GetBodyInfo(const char* name, CHierarchy* hierarchy, hkRigidBodyCinfo * info = NULL);
Physics::BodyCInfo GetStaticBodyInfo(const char* name, CHierarchy* hierarchy);
};
class psConstraint
{
public:
psConstraint() {
m_bUseRagdollHierarchy = false;
};
virtual ~psConstraint() {};
#ifndef _PS3_RUN_WITHOUT_HAVOK_BUILD
virtual hkConstraintInstance * BuildConstraint( CEntity* pentity ) = 0;
hkConstraintInstance* m_pobHavokConstraint;
#endif
bool m_bUseRagdollHierarchy;
};
class psConstraint_Hinge : public psConstraint
{
public:
#ifndef _PS3_RUN_WITHOUT_HAVOK_BUILD
//! Data. --------------------------------------------------------------------
psRigidBody* m_BodyA;
psRigidBody* m_BodyB;
CPoint m_fPivotA;
CPoint m_fPivotB;
CVector m_vAxisA;
CVector m_vAxisB;
CVector m_vPerpAxisA;
CVector m_vPerpAxisB;
bool m_bIsLimited;
bool m_bBreakable;
float m_fLinearBreakingStrength;
float m_FRange;
float m_fMaxLimitAngleA;
//! Accessors. ---------------------------------------------------------------
CPoint GetPivotA( void ) const { return m_fPivotA; };
void SetPivotA( const CPoint &obPoint ) { m_fPivotA = obPoint; };
CPoint GetPivotB( void ) const { return m_fPivotB; };
void SetPivotB( const CPoint &obPoint ) { m_fPivotB = obPoint; };
CVector GetAxisA( void ) const { return m_vAxisA; };
void SetAxisA( const CVector &obPoint ) { m_vAxisA = obPoint; };
CVector GetAxisB( void ) const { return m_vAxisB; };
void SetAxisB( const CVector &obPoint ) { m_vAxisB = obPoint; };
CVector GetPerpAxisA( void ) const { return m_vPerpAxisA; };
void SetPerpAxisA( const CVector &obPoint ) { m_vPerpAxisA = obPoint; };
CVector GetPerpAxisB( void ) const { return m_vPerpAxisB; };
void SetPerpAxisB( const CVector &obPoint ) { m_vPerpAxisB = obPoint; };
virtual hkConstraintInstance* BuildConstraint( CEntity* pentity );
#endif
};
class psConstraint_P2P : public psConstraint
{
public:
#ifndef _PS3_RUN_WITHOUT_HAVOK_BUILD
//! Data. --------------------------------------------------------------------
psRigidBody* m_BodyA;
psRigidBody* m_BodyB;
CPoint m_fPivotA;
CPoint m_fPivotB;
bool m_bBreakable;
float m_fLinearBreakingStrength;
int m_iType;
//! Accessors. ---------------------------------------------------------------
CPoint GetPivotA( void ) const { return m_fPivotA; };
void SetPivotA( const CPoint &obPoint ) { m_fPivotA = obPoint; };
CPoint GetPivotB( void ) const { return m_fPivotB; };
void SetPivotB( const CPoint &obPoint ) { m_fPivotB = obPoint; };
virtual hkConstraintInstance* BuildConstraint( CEntity* pentity )
{
hkConstraintData* data;
hkBallAndSocketConstraintData* data2 = HK_NEW hkBallAndSocketConstraintData;
#ifdef CONSTRAINT_CLUMP_SPACE
/*data2->setInBodySpace ( Physics::MathsTools::CPointTohkVector(m_fPivotA),
Physics::MathsTools::CPointTohkVector(m_fPivotB)); */
CPoint pivot = m_fPivotA + m_fPivotB;
pivot *= 0.5f;
CMatrix m2;
m2.SetFromQuat( pentity->GetHierarchy()->GetBindPoseJointRotation( 0 ) );
m2.SetTranslation( pentity->GetHierarchy()->GetBindPoseJointTranslation( 0 ) );
m2 = m2.GetFullInverse();
pivot = pivot * m2;
CMatrix m = pentity->GetHierarchy()->GetRootTransform()->GetWorldMatrix();
pivot = pivot * m;
//pivot -= pentity->GetHierarchy()->GetRootTransform()->GetWorldMatrix().GetTranslation();
hkTransform transformOutA;
m_BodyA->m_associatedRigid->approxTransformAt( Physics::CPhysicsWorld::Get().GetFrameTime(), transformOutA );
hkTransform transformOutB;
m_BodyB->m_associatedRigid->approxTransformAt( Physics::CPhysicsWorld::Get().GetFrameTime(), transformOutB );
data2->setInWorldSpace( transformOutA,
transformOutB,
Physics::MathsTools::CPointTohkVector(pivot) );
/*if( m_bBreakable )
{
hkBreakableConstraintData* breaker = NT_NEW hkBreakableConstraintData( data, Physics::CPhysicsWorld::Get().GetHavokWorldP() );
breaker->setThreshold( m_fLinearBreakingStrength );
breaker->setRemoveWhenBroken(true);
data = breaker;
}*/
#else
data2->setInBodySpace(Physics::MathsTools::CPointTohkVector(m_fPivotA),
Physics::MathsTools::CPointTohkVector(m_fPivotB));
#endif
data = data2;
/* What is it for?
if( m_BodyA->m_associatedRigid->hasProperty( 1000 ) == false )
{
if( m_BodyA->m_associatedRigid->getMass() != 0.0f )
{
hkMatrix3 m;
m_BodyA->m_associatedRigid->getInertiaLocal(m);
m.mul( 10.0f );
m_BodyA->m_associatedRigid->setInertiaLocal( m );
hkPropertyValue val;
val.setInt( 1 );
m_BodyA->m_associatedRigid->addProperty( 1000, val );
}
}
if( m_BodyB->m_associatedRigid->hasProperty( 1000 ) == false )
{
if( m_BodyB->m_associatedRigid->getMass() != 0.0f )
{
hkMatrix3 m;
m_BodyB->m_associatedRigid->getInertiaLocal(m);
m.mul( 10.0f );
m_BodyB->m_associatedRigid->setInertiaLocal( m );
hkPropertyValue val;
val.setInt( 1 );
m_BodyB->m_associatedRigid->addProperty( 1000, val );
}
}*/
m_pobHavokConstraint = HK_NEW hkConstraintInstance( m_BodyA->m_associatedRigid, m_BodyB->m_associatedRigid, data );
return m_pobHavokConstraint;
}
#endif
};
class psConstraint_Spring : public psConstraint
{
public:
#ifndef _PS3_RUN_WITHOUT_HAVOK_BUILD
//! Data. --------------------------------------------------------------------
psRigidBody* m_BodyA;
psRigidBody* m_BodyB;
CPoint m_fPivotA;
CPoint m_fPivotB;
float m_fRestLength;
float m_fStiffness;
float m_fDamping;
bool m_bActOnCompression;
bool m_bActOnExtension;
//! Accessors. ---------------------------------------------------------------
CPoint GetPivotA( void ) const { return m_fPivotA; };
void SetPivotA( const CPoint &obPoint ) { m_fPivotA = obPoint; };
CPoint GetPivotB( void ) const { return m_fPivotB; };
void SetPivotB( const CPoint &obPoint ) { m_fPivotB = obPoint; };
virtual hkConstraintInstance* BuildConstraint( CEntity* pentity )
{
hkSpringAction * action = HK_NEW hkSpringAction( m_BodyA->m_associatedRigid, m_BodyB->m_associatedRigid );
CMatrix m2;
m2.SetFromQuat( pentity->GetHierarchy()->GetBindPoseJointRotation( 0 ) );
m2.SetTranslation( pentity->GetHierarchy()->GetBindPoseJointTranslation( 0 ) );
m2 = m2.GetFullInverse();
m_fPivotA = m_fPivotA * m2;
m_fPivotB = m_fPivotB * m2;
CMatrix m = pentity->GetHierarchy()->GetRootTransform()->GetWorldMatrix();
m_fPivotA = m_fPivotA * m;
m_fPivotB = m_fPivotB * m;
action->setPositionsInWorldSpace( Physics::MathsTools::CPointTohkVector(m_fPivotA), Physics::MathsTools::CPointTohkVector(m_fPivotB) );
action->setDamping( m_fDamping );
action->setOnCompression( m_bActOnCompression );
action->setOnExtension( m_bActOnExtension );
action->setRestLength ( m_fRestLength );
action->setStrength( m_fStiffness );
Physics::CPhysicsWorld::Get().AddAction( action );
action = HK_NEW hkSpringAction( m_BodyB->m_associatedRigid, m_BodyA->m_associatedRigid );
action->setPositionsInWorldSpace( Physics::MathsTools::CPointTohkVector(m_fPivotB), Physics::MathsTools::CPointTohkVector(m_fPivotA) );
action->setDamping( m_fDamping );
action->setOnCompression( m_bActOnCompression );
action->setOnExtension( m_bActOnExtension );
action->setRestLength ( m_fRestLength );
action->setStrength( m_fStiffness );
Physics::CPhysicsWorld::Get().AddAction( action );
m_pobHavokConstraint = 0;
return m_pobHavokConstraint;
}
#endif
};
class psConstraint_StiffSpring : public psConstraint
{
public:
#ifndef _PS3_RUN_WITHOUT_HAVOK_BUILD
//! Data. --------------------------------------------------------------------
psRigidBody* m_BodyA;
psRigidBody* m_BodyB;
CPoint m_fPivotA;
CPoint m_fPivotB;
bool m_bBreakable;
float m_fLinearBreakingStrength;
float m_fRestLength;
//! Accessors. ---------------------------------------------------------------
CPoint GetPivotA( void ) const { return m_fPivotA; };
void SetPivotA( const CPoint &obPoint ) { m_fPivotA = obPoint; };
CPoint GetPivotB( void ) const { return m_fPivotB; };
void SetPivotB( const CPoint &obPoint ) { m_fPivotB = obPoint; };
virtual hkConstraintInstance* BuildConstraint( CEntity* pentity )
{
hkConstraintData* data;
hkStiffSpringConstraintData* data2 = HK_NEW hkStiffSpringConstraintData;
#ifdef CONSTRAINT_CLUMP_SPACE
CMatrix m2;
m2.SetFromQuat( pentity->GetHierarchy()->GetBindPoseJointRotation( 0 ) );
m2.SetTranslation( pentity->GetHierarchy()->GetBindPoseJointTranslation( 0 ) );
m2 = m2.GetFullInverse();
m_fPivotA = m_fPivotA * m2;
m_fPivotB = m_fPivotB * m2;
CMatrix m = pentity->GetHierarchy()->GetRootTransform()->GetWorldMatrix();
m_fPivotA = m_fPivotA * m;
m_fPivotB = m_fPivotB * m;
hkTransform transformOutA;
m_BodyA->m_associatedRigid->approxTransformAt( Physics::CPhysicsWorld::Get().GetFrameTime(), transformOutA );
hkTransform transformOutB;
m_BodyB->m_associatedRigid->approxTransformAt( Physics::CPhysicsWorld::Get().GetFrameTime(), transformOutB );
data2->setInWorldSpace( transformOutA,
transformOutB,
Physics::MathsTools::CPointTohkVector(m_fPivotA),
Physics::MathsTools::CPointTohkVector(m_fPivotB));
#else
#if HAVOK_SDK_VERSION_MAJOR >= 4 && HAVOK_SDK_VERSION_MINOR >= 1
data2->setInBodySpace( Physics::MathsTools::CPointTohkVector(m_fPivotA),
Physics::MathsTools::CPointTohkVector(m_fPivotB),
m_fRestLength);
#else
data2->setInBodySpace(hkTransform(),
hkTransform(),
Physics::MathsTools::CPointTohkVector(m_fPivotA),
Physics::MathsTools::CPointTohkVector(m_fPivotB)); // transform are only used to determine spring lenght but we know it
#endif
#endif
data2->setSpringLength( m_fRestLength );
data = data2;
if( m_bBreakable )
{
hkBreakableConstraintData* breaker = HK_NEW hkBreakableConstraintData( data, Physics::CPhysicsWorld::Get().GetHavokWorldP() );
breaker->setThreshold( m_fLinearBreakingStrength );
breaker->setRemoveWhenBroken(true);
data = breaker;
}
m_pobHavokConstraint = HK_NEW hkConstraintInstance( m_BodyA->m_associatedRigid, m_BodyB->m_associatedRigid, data );
return m_pobHavokConstraint;
}
#endif
};
class psConstraint_Ragdoll : public psConstraint
{
public:
#ifndef _PS3_RUN_WITHOUT_HAVOK_BUILD
//! Data. --------------------------------------------------------------------
psRigidBody* m_BodyA;
psRigidBody* m_BodyB;
CPoint m_fPivotA;
CPoint m_fPivotB;
CVector m_vTwistAxisA;
CVector m_vTwistAxisB;
CVector m_vPlaneAxisA;
CVector m_vPlaneAxisB;
bool m_bBreakable;
float m_fLinearBreakingStrength;
float m_fTwistMin;
float m_fTwistMax;
float m_fConeMin;
float m_fConeMax;
float m_fPlaneMin;
float m_fPlaneMax;
float m_fFriction;
//! Accessors. ---------------------------------------------------------------
CPoint GetPivotA( void ) const { return m_fPivotA; };
void SetPivotA( const CPoint &obPoint ) { m_fPivotA = obPoint; };
CPoint GetPivotB( void ) const { return m_fPivotB; };
void SetPivotB( const CPoint &obPoint ) { m_fPivotB = obPoint; };
CVector GetTwistA( void ) const { return m_vTwistAxisA; };
void SetTwistA( const CVector &obPoint ) { m_vTwistAxisA = obPoint; };
CVector GetTwistB( void ) const { return m_vTwistAxisB; };
void SetTwistB( const CVector &obPoint ) { m_vTwistAxisB = obPoint; };
CVector GetPlaneAxisA( void ) const { return m_vPlaneAxisA; };
void SetPlaneAxisA( const CVector &obPoint ) { m_vPlaneAxisA = obPoint; };
CVector GetPlaneAxisB( void ) const { return m_vPlaneAxisB; };
void SetPlaneAxisB( const CVector &obPoint ) { m_vPlaneAxisB = obPoint; };
virtual hkConstraintInstance* BuildConstraint( CEntity* pentity );
#endif
};
#endif // _DYNAMICS_XML_INTERFACES_INC
|
8be2146bb5bd3d0cfcc21adb73f8daa17ad0e056
|
20fc280069c03893e6dc1104694d78a9aa3884a5
|
/test/compiletest/hypercomplex_test.cpp
|
2102a79b713aec49be38c632f3f918b805d12432
|
[
"BSD-2-Clause"
] |
permissive
|
latte0/omniclid
|
b21122036f5b6aa5c4c104eed032e3b4b38fb2c9
|
b83314a963fdac98e47f470d21178028b4bd2cc3
|
refs/heads/master
| 2021-01-10T09:14:47.292133
| 2017-10-23T08:33:39
| 2017-10-23T08:33:39
| 76,851,869
| 6
| 2
| null | 2017-02-01T15:58:30
| 2016-12-19T10:20:13
|
C++
|
UTF-8
|
C++
| false
| false
| 2,319
|
cpp
|
hypercomplex_test.cpp
|
#include "../../src/HyperComplex/HyperComplex.h"
#include "../../src/HyperComplex/imagine_map.h"
using namespace omniclid;
namespace{
constexpr std::pair<int,int> a = std::make_pair(2,4);
}
int main()
{
using R = typename decltype(make_hypercomplex<0,double>())::type;
using I = typename decltype(make_hypercomplex<1,double>())::type;
using J = typename decltype(make_hypercomplex<2>())::type;
using K = typename decltype(make_hypercomplex<3>())::type;
R test(2.0);
R test2(3);
test += 2;
HyperComplex<quaternion_map> admin{1,2,3,4};
HyperComplex<quaternion_map> admin2{1,2,3,4};
admin2 += admin;
K admintest(3);
admintest *= 10.5;
std::cout << admin2.get<3>().get_value() << std::endl;
admin2 += admintest;
test += test2;
std::cout << test.get_value() << std::endl;
std::cout << admin2.get<3>().get_value() << std::endl;
std::cout << quaternion_map::opmap::get<5>::val << std::endl;
I i(2);
J j(2);
auto a = i * j;
auto a2 = j * i;
std::cout << i.dim << j.dim << a.dim << a2.dim << std::endl;
std::cout << i.get_value() << j.get_value() << a.get_value() << a2.get_value() << std::endl;
HyperComplex<quaternion_map> newadmin(a2);
std::cout << newadmin.get<1>().get_value() << std::endl;
std::cout << newadmin.get<3>().get_value() << std::endl;
std::cout << quaternion_map::get_dy_opmap(7) << std::endl;
HyperComplex<quaternion_map> admin3{1,2,3,4};
HyperComplex<quaternion_map> admin4{1,2,3,4};
admin3 *= admin4;
std::cout << admin3.get<2>().get_value() << std::endl;
auto&& mu = mult_seq(1,2,3,4);
std::cout << mu << std::endl;
std::cout << meta_vec_multiplyer<2,1>::template get<10, 3>::val << std::endl;
std::cout << quaternion_map::opdivmap::get<12>::val << std::endl;
std::cout << "aa"<< std::endl;
std::cout <<admin4.get<3>().get_value() << std::endl;
admin4 += a2;
std::cout << admin4.get<3>().get_value() << std::endl;
auto newadmin2 = a - a2;
std::cout << newadmin2.get<3>().get_value() << std::endl;
using IR = typename decltype(make_hypercomplex<0,double,imagine_map>())::type;
using II = typename decltype(make_hypercomplex<1,double,imagine_map>())::type;
HyperComplex<imagine_map> imagine1{2,3};
HyperComplex<imagine_map> imagine2{4,5};
auto imagine3 = imagine1/imagine2;
std::cout << imagine3 << std::endl;
return 0;
}
|
a9db82886c4cb32773bf949d1770ed1741e5ac6c
|
a3d6556180e74af7b555f8d47d3fea55b94bcbda
|
/chrome/browser/ash/power/auto_screen_brightness/utils.cc
|
05dfb75d1ae4f03faf26c4302a0973e4a89086a4
|
[
"BSD-3-Clause"
] |
permissive
|
chromium/chromium
|
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
|
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
|
refs/heads/main
| 2023-08-24T00:35:12.585945
| 2023-08-23T22:01:11
| 2023-08-23T22:01:11
| 120,360,765
| 17,408
| 7,102
|
BSD-3-Clause
| 2023-09-10T23:44:27
| 2018-02-05T20:55:32
| null |
UTF-8
|
C++
| false
| false
| 844
|
cc
|
utils.cc
|
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ash/power/auto_screen_brightness/utils.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/stringprintf.h"
namespace ash {
namespace power {
namespace auto_screen_brightness {
void LogParameterError(ParameterError error) {
UMA_HISTOGRAM_ENUMERATION("AutoScreenBrightness.ParameterError", error);
}
void LogDataError(DataError error) {
UMA_HISTOGRAM_ENUMERATION("AutoScreenBrightness.DataError", error);
}
double ConvertToLog(double value) {
return std::log(1 + value);
}
std::string FormatToPrint(double value) {
return base::StringPrintf("%.4f", value) + "%";
}
} // namespace auto_screen_brightness
} // namespace power
} // namespace ash
|
a510b866d3d970ba75595c534f8c7229e860c286
|
5d4a4951c5720e9871a38fd87fec08be084e8dd2
|
/Luke/SDL/SDLWindowImpl.cpp
|
4920ded393dd6de3663cc04d994e3a8f8c1fe531
|
[] |
no_license
|
mokafolio/Luke
|
f24a3dfe43a5bf1e0bef2c500bbe893bf353781d
|
330f2c4c76538cc107d3f10f063a33d4e969486d
|
refs/heads/master
| 2021-05-16T12:47:19.650367
| 2019-06-14T00:08:19
| 2019-06-14T00:08:19
| 105,333,183
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 33,993
|
cpp
|
SDLWindowImpl.cpp
|
#include <Luke/KeyEvents.hpp>
#include <Luke/SDL/SDLDisplayImpl.hpp>
#include <Luke/SDL/SDLInitializer.hpp>
#include <Luke/SDL/SDLWindowImpl.hpp>
#include <Luke/TextInputEvent.hpp>
#include <Luke/WindowEvents.hpp>
#include <Stick/Maybe.hpp>
#include <cmath> //for std::isnan
#include <GL/gl3w.h>
//@TODO Proper error code
#define RETURN_SDL_ERROR(_item) \
do \
{ \
if (!_item) \
{ \
return Error(ec::InvalidOperation, sdlError(), STICK_FILE, STICK_LINE); \
} \
} while (0)
namespace luke
{
namespace detail
{
using namespace stick;
static const String sdlError()
{
String ret;
const char * error = SDL_GetError();
if (*error != '\0')
{
ret = String::formatted("SDL Error: %s\n", error);
SDL_ClearError();
}
return ret;
}
//@TODO: We might want to lock this for thread safety/portability reasons
static DynamicArray<WindowImpl *> g_sdlWindows;
static MouseState g_mouseState;
static Maybe<MouseButton> g_initialDragButton;
WindowImpl::WindowImpl(Window * _window) :
m_sdlWindow(NULL),
m_sdlGLContext(NULL),
m_window(_window),
m_bShouldClose(false),
m_sdlWindowID(0)
{
}
WindowImpl::~WindowImpl()
{
deallocateSDLWindowAndContext();
}
void WindowImpl::deallocateSDLWindowAndContext()
{
if (m_sdlWindow)
{
SDL_GL_DeleteContext(m_sdlGLContext);
SDL_DestroyWindow(m_sdlWindow);
auto it = stick::find(g_sdlWindows.begin(), g_sdlWindows.end(), this);
if (it != g_sdlWindows.end())
g_sdlWindows.remove(it);
m_sdlGLContext = NULL;
m_sdlWindow = NULL;
for (Size i = 0; i < m_cursors.count(); ++i)
{
SDL_FreeCursor(m_cursors[i]);
}
m_sdlWindowID = 0;
}
}
Error WindowImpl::open(const WindowSettings & _settings, WindowImpl * _shared)
{
SDLInitializer::instance();
//@TODO: for now we simply cache the settings that were passed in...
m_settings = _settings;
deallocateSDLWindowAndContext();
SDL_SetHint(SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK, "1");
//@TODO allow to pass in opengl version in the settings and only default to this on OSX
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, _settings.depthPrecision());
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, _settings.stencilPrecision());
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, _settings.colorPrecision());
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, _settings.colorPrecision());
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, _settings.colorPrecision());
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, _settings.alphaPrecision());
SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1);
if (_settings.sampleCount() > 1)
{
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, _settings.sampleCount());
}
UInt32 flags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI;
if (_settings.isResizeable())
flags |= SDL_WINDOW_RESIZABLE;
if (!_settings.isDecorated())
flags |= SDL_WINDOW_BORDERLESS;
//@TODO take settings poistion into account
m_sdlWindow =
SDL_CreateWindow(_settings.title().length() ? _settings.title().cString() : "Luke Window",
std::isnan(_settings.x()) ? SDL_WINDOWPOS_CENTERED : _settings.x(),
std::isnan(_settings.y()) ? SDL_WINDOWPOS_CENTERED : _settings.y(),
_settings.width(),
_settings.height(),
flags);
RETURN_SDL_ERROR(m_sdlWindow);
m_sdlGLContext = SDL_GL_CreateContext(m_sdlWindow);
RETURN_SDL_ERROR(m_sdlGLContext);
g_sdlWindows.append(this);
m_bShouldClose = false;
// create the default cursors
static_assert(CursorArray::capacity() == (Size)CursorType::_Count - 1,
"Not all default cursors satisfied!");
m_cursors[(Size)CursorType::Cursor] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW);
m_cursors[(Size)CursorType::TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_IBEAM);
m_cursors[(Size)CursorType::ResizeAll] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEALL);
m_cursors[(Size)CursorType::ResizeNS] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENS);
m_cursors[(Size)CursorType::ResizeEW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEWE);
m_cursors[(Size)CursorType::ResizeNESW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENESW);
m_cursors[(Size)CursorType::ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENWSE);
m_sdlWindowID = SDL_GetWindowID(m_sdlWindow);
if (gl3wInit())
{
return Error(stick::ec::InvalidOperation, "Failed to initialize OpenGL", STICK_FILE, STICK_LINE);
}
return Error();
}
void WindowImpl::close()
{
STICK_ASSERT(m_sdlWindow);
deallocateSDLWindowAndContext();
}
void WindowImpl::setShouldClose(bool _b)
{
STICK_ASSERT(m_sdlWindow);
m_bShouldClose = _b;
}
bool WindowImpl::shouldClose() const
{
return m_bShouldClose;
}
void WindowImpl::move(Float32 _x, Float32 _y)
{
STICK_ASSERT(m_sdlWindow);
SDL_SetWindowPosition(m_sdlWindow, _x, _y);
}
void WindowImpl::moveToCenter()
{
STICK_ASSERT(m_sdlWindow);
SDL_SetWindowPosition(m_sdlWindow, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
}
void WindowImpl::show()
{
STICK_ASSERT(m_sdlWindow);
SDL_ShowWindow(m_sdlWindow);
}
void WindowImpl::hide()
{
STICK_ASSERT(m_sdlWindow);
SDL_HideWindow(m_sdlWindow);
}
void WindowImpl::resize(Float32 _width, Float32 _height)
{
STICK_ASSERT(m_sdlWindow);
SDL_SetWindowSize(m_sdlWindow, _width, _height);
}
void WindowImpl::maximize()
{
STICK_ASSERT(m_sdlWindow);
SDL_MaximizeWindow(m_sdlWindow);
}
void WindowImpl::focus()
{
STICK_ASSERT(m_sdlWindow);
SDL_RaiseWindow(m_sdlWindow);
}
Error WindowImpl::enableRenderContext()
{
STICK_ASSERT(m_sdlWindow);
int res = SDL_GL_MakeCurrent(m_sdlWindow, m_sdlGLContext);
RETURN_SDL_ERROR(res);
return Error();
}
void WindowImpl::swapBuffers()
{
// STICK_ASSERT(m_sdlWindow);
SDL_GL_SwapWindow(m_sdlWindow);
}
void WindowImpl::setVerticalSync(bool _b)
{
STICK_ASSERT(m_sdlWindow);
SDL_GL_SetSwapInterval(_b);
}
//@TODO: Merge the code for both enter fullscreen functions into a helper
Error WindowImpl::enterFullscreen(FullscreenMode _mode, const Display & _display)
{
STICK_ASSERT(m_sdlWindow);
SDL_SetWindowFullscreen(m_sdlWindow,
_mode == FullscreenMode::Borderless ? SDL_WINDOW_FULLSCREEN_DESKTOP
: SDL_WINDOW_FULLSCREEN);
return Error();
}
Error WindowImpl::enterFullscreen(const DisplayMode & _mode, const Display & _display)
{
STICK_ASSERT(m_sdlWindow);
SDL_SetWindowFullscreen(m_sdlWindow, SDL_WINDOW_FULLSCREEN);
return Error();
}
Error WindowImpl::exitFullscreen()
{
STICK_ASSERT(m_sdlWindow);
int res = SDL_SetWindowFullscreen(m_sdlWindow, 0);
RETURN_SDL_ERROR(res);
return Error();
}
void WindowImpl::setCursor(CursorType _cursor)
{
STICK_ASSERT((Size)_cursor < m_cursors.count());
SDL_SetCursor(m_cursors[(Size)_cursor]);
}
void WindowImpl::hideCursor()
{
STICK_ASSERT(m_sdlWindow);
SDL_ShowCursor(SDL_DISABLE);
}
void WindowImpl::showCursor()
{
STICK_ASSERT(m_sdlWindow);
SDL_ShowCursor(SDL_ENABLE);
}
void WindowImpl::setTitle(const String & _str)
{
STICK_ASSERT(m_sdlWindow);
SDL_SetWindowTitle(m_sdlWindow, _str.cString());
}
bool WindowImpl::isVisible() const
{
STICK_ASSERT(m_sdlWindow);
return (SDL_GetWindowFlags(m_sdlWindow) & SDL_WINDOW_FULLSCREEN) == SDL_WINDOW_SHOWN;
}
bool WindowImpl::isFocussed() const
{
STICK_ASSERT(m_sdlWindow);
return (SDL_GetWindowFlags(m_sdlWindow) & SDL_WINDOW_FULLSCREEN) == SDL_WINDOW_INPUT_FOCUS;
}
const WindowSettings & WindowImpl::settings() const
{
return m_settings;
}
bool WindowImpl::isCursorVisible() const
{
return SDL_ShowCursor(SDL_QUERY) == SDL_ENABLE;
}
bool WindowImpl::verticalSync() const
{
return SDL_GL_GetSwapInterval();
}
bool WindowImpl::isFullscreen() const
{
STICK_ASSERT(m_sdlWindow);
return (SDL_GetWindowFlags(m_sdlWindow) & SDL_WINDOW_FULLSCREEN) == SDL_WINDOW_FULLSCREEN;
}
const String & WindowImpl::title() const
{
STICK_ASSERT(m_sdlWindow);
m_title = SDL_GetWindowTitle(m_sdlWindow);
return m_title;
}
Float32 WindowImpl::backingScaleFactor() const
{
return widthInPixels() / width();
}
Float32 WindowImpl::width() const
{
if (m_sdlWindow)
{
int w;
SDL_GetWindowSize(m_sdlWindow, &w, NULL);
return w;
}
return 0;
}
Float32 WindowImpl::height() const
{
if (m_sdlWindow)
{
int h;
SDL_GetWindowSize(m_sdlWindow, NULL, &h);
return h;
}
return 0;
}
Float32 WindowImpl::widthInPixels() const
{
if (m_sdlWindow)
{
int w;
SDL_GL_GetDrawableSize(m_sdlWindow, &w, NULL);
return w;
}
return 0;
}
Float32 WindowImpl::heightInPixels() const
{
if (m_sdlWindow)
{
int h;
SDL_GL_GetDrawableSize(m_sdlWindow, NULL, &h);
return h;
}
return 0;
}
Float32 WindowImpl::x() const
{
if (m_sdlWindow)
{
int x;
SDL_GetWindowPosition(m_sdlWindow, &x, NULL);
return x;
}
return 0;
}
Float32 WindowImpl::y() const
{
if (m_sdlWindow)
{
int y;
SDL_GetWindowPosition(m_sdlWindow, NULL, &y);
return y;
}
return 0;
}
Display WindowImpl::display() const
{
if (m_sdlWindow)
{
int idx = SDL_GetWindowDisplayIndex(m_sdlWindow);
if (idx >= 0)
{
Display ret;
ret.m_pimpl->m_displayID = idx;
return ret;
}
}
return Display();
}
UInt32 WindowImpl::sdlWindowID() const
{
return m_sdlWindowID;
}
static WindowImpl * windowForEvent(SDL_Event * _event)
{
auto it = g_sdlWindows.begin();
for (; it != g_sdlWindows.end(); ++it)
{
if ((*it)->sdlWindowID() == _event->window.windowID)
return *it;
}
return nullptr;
}
static void handleWindowEvent(SDL_Event * _event)
{
STICK_ASSERT(_event->type == SDL_WINDOWEVENT);
WindowImpl * window = windowForEvent(_event);
if (!window)
return;
switch (_event->window.event)
{
case SDL_WINDOWEVENT_SHOWN:
// SDL_Log("Window %d shown", _event->window.windowID);
break;
case SDL_WINDOWEVENT_HIDDEN:
// SDL_Log("Window %d hidden", _event->window.windowID);
break;
case SDL_WINDOWEVENT_EXPOSED:
// SDL_Log("Window %d exposed", _event->window.windowID);
// this should not be necessary but on osx the window flickers after
// exitting from fullscreen unless we move it (or force a refresh somehow)
break;
case SDL_WINDOWEVENT_MOVED:
// SDL_Log("Window %d moved to %d,%d",
// _event->window.windowID, _event->window.data1,
// _event->window.data2);
window->m_window->publish(WindowMoveEvent(_event->window.data1, _event->window.data2),
true);
break;
// case SDL_WINDOWEVENT_RESIZED:
case SDL_WINDOWEVENT_SIZE_CHANGED:
// SDL_Log("Window %d resized to %dx%d",
// _event->window.windowID, _event->window.data1,
// _event->window.data2);
window->m_window->publish(WindowResizeEvent(_event->window.data1, _event->window.data2),
true);
break;
case SDL_WINDOWEVENT_MINIMIZED:
// SDL_Log("Window %d minimized", _event->window.windowID);
window->m_window->publish(WindowIconifyEvent(), true);
break;
case SDL_WINDOWEVENT_MAXIMIZED:
// SDL_Log("Window %d maximized", _event->window.windowID);
break;
case SDL_WINDOWEVENT_RESTORED:
// SDL_Log("Window %d restored", _event->window.windowID);
window->m_window->publish(WindowRestoreEvent(), true);
break;
case SDL_WINDOWEVENT_ENTER:
// SDL_Log("Mouse entered window %d",
// _event->window.windowID);
break;
case SDL_WINDOWEVENT_LEAVE:
// SDL_Log("Mouse left window %d", _event->window.windowID);
break;
case SDL_WINDOWEVENT_FOCUS_GAINED:
// SDL_Log("Window %d gained keyboard focus",
// _event->window.windowID);
window->m_window->publish(WindowFocusEvent(), true);
break;
case SDL_WINDOWEVENT_FOCUS_LOST:
// SDL_Log("Window %d lost keyboard focus",
// _event->window.windowID);
window->m_window->publish(WindowLostFocusEvent(), true);
break;
case SDL_WINDOWEVENT_CLOSE:
// SDL_Log("Window %d closed", _event->window.windowID);
window->m_bShouldClose = true;
window->hide();
break;
default:
// SDL_Log("Window %d got unknown event %d",
// _event->window.windowID, _event->window.event);
break;
}
}
static void handkeKeyEvent(SDL_Event * _event)
{
STICK_ASSERT(_event->type == SDL_KEYDOWN || _event->type == SDL_KEYUP);
WindowImpl * window = windowForEvent(_event);
if (!window)
return;
KeyCode code;
switch (_event->key.keysym.sym)
{
case SDLK_0:
code = KeyCode::Zero;
break;
case SDLK_1:
code = KeyCode::One;
break;
case SDLK_2:
code = KeyCode::Two;
break;
case SDLK_3:
code = KeyCode::Three;
break;
case SDLK_4:
code = KeyCode::Four;
break;
case SDLK_5:
code = KeyCode::Five;
break;
case SDLK_6:
code = KeyCode::Six;
break;
case SDLK_7:
code = KeyCode::Seven;
break;
case SDLK_8:
code = KeyCode::Eight;
break;
case SDLK_9:
code = KeyCode::Nine;
break;
case SDLK_a:
code = KeyCode::A;
break;
case SDLK_b:
code = KeyCode::B;
break;
case SDLK_c:
code = KeyCode::C;
break;
case SDLK_d:
code = KeyCode::D;
break;
case SDLK_e:
code = KeyCode::E;
break;
case SDLK_f:
code = KeyCode::F;
break;
case SDLK_g:
code = KeyCode::G;
break;
case SDLK_h:
code = KeyCode::H;
break;
case SDLK_i:
code = KeyCode::I;
break;
case SDLK_j:
code = KeyCode::J;
break;
case SDLK_k:
code = KeyCode::K;
break;
case SDLK_l:
code = KeyCode::L;
break;
case SDLK_m:
code = KeyCode::M;
break;
case SDLK_n:
code = KeyCode::N;
break;
case SDLK_o:
code = KeyCode::O;
break;
case SDLK_p:
code = KeyCode::P;
break;
case SDLK_q:
code = KeyCode::Q;
break;
case SDLK_r:
code = KeyCode::R;
break;
case SDLK_s:
code = KeyCode::S;
break;
case SDLK_t:
code = KeyCode::T;
break;
case SDLK_u:
code = KeyCode::U;
break;
case SDLK_v:
code = KeyCode::V;
break;
case SDLK_w:
code = KeyCode::W;
break;
case SDLK_x:
code = KeyCode::X;
break;
case SDLK_y:
code = KeyCode::Y;
break;
case SDLK_z:
code = KeyCode::Z;
break;
case SDLK_RETURN:
code = KeyCode::Return;
break;
case SDLK_ESCAPE:
code = KeyCode::Escape;
break;
case SDLK_BACKSPACE:
code = KeyCode::Backspace;
break;
case SDLK_TAB:
code = KeyCode::Tab;
break;
case SDLK_SPACE:
code = KeyCode::Space;
break;
case SDLK_MINUS:
code = KeyCode::Subtract;
break;
case SDLK_EQUALS:
code = KeyCode::Equal;
break;
case SDLK_LEFTBRACKET:
code = KeyCode::LeftBracket;
break;
case SDLK_RIGHTBRACKET:
code = KeyCode::RightBracket;
break;
case SDLK_BACKSLASH:
code = KeyCode::Backslash;
break;
case SDLK_SEMICOLON:
code = KeyCode::Semicolon;
break;
case SDLK_QUOTE:
code = KeyCode::Apostrophe;
break;
case SDLK_BACKQUOTE:
code = KeyCode::GraveAccent; // Not sure about this one
break;
case SDLK_COMMA:
code = KeyCode::Comma;
break;
case SDLK_PERIOD:
code = KeyCode::Period;
break;
case SDLK_SLASH:
code = KeyCode::Slash;
break;
case SDLK_CAPSLOCK:
code = KeyCode::CapsLock;
break;
case SDLK_F1:
code = KeyCode::F1;
break;
case SDLK_F2:
code = KeyCode::F2;
break;
case SDLK_F3:
code = KeyCode::F3;
break;
case SDLK_F4:
code = KeyCode::F4;
break;
case SDLK_F5:
code = KeyCode::F5;
break;
case SDLK_F6:
code = KeyCode::F6;
break;
case SDLK_F7:
code = KeyCode::F7;
break;
case SDLK_F8:
code = KeyCode::F8;
break;
case SDLK_F9:
code = KeyCode::F9;
break;
case SDLK_F10:
code = KeyCode::F10;
break;
case SDLK_F11:
code = KeyCode::F11;
break;
case SDLK_F12:
code = KeyCode::F12;
break;
case SDLK_F13:
code = KeyCode::F13;
break;
case SDLK_F14:
code = KeyCode::F14;
break;
case SDLK_F15:
code = KeyCode::F15;
break;
case SDLK_F16:
code = KeyCode::F16;
break;
case SDLK_INSERT:
code = KeyCode::Insert;
break;
case SDLK_HOME:
code = KeyCode::Home;
break;
case SDLK_PAGEUP:
code = KeyCode::PageUp;
break;
case SDLK_DELETE:
code = KeyCode::Delete;
break;
case SDLK_END:
code = KeyCode::End;
break;
case SDLK_PAGEDOWN:
code = KeyCode::PageDown;
break;
case SDLK_LCTRL:
code = KeyCode::LeftControl;
break;
case SDLK_LSHIFT:
code = KeyCode::LeftShift;
break;
case SDLK_LALT:
code = KeyCode::LeftAlt;
break;
case SDLK_LGUI:
code = KeyCode::LeftCommand;
break;
case SDLK_RCTRL:
code = KeyCode::RightControl;
break;
case SDLK_RSHIFT:
code = KeyCode::RightShift;
break;
case SDLK_RALT:
code = KeyCode::RightAlt;
break;
case SDLK_RGUI:
code = KeyCode::RightCommand;
break;
case SDLK_RIGHT:
code = KeyCode::Right;
break;
case SDLK_LEFT:
code = KeyCode::Left;
break;
case SDLK_DOWN:
code = KeyCode::Down;
break;
case SDLK_UP:
code = KeyCode::Up;
break;
case SDLK_KP_DIVIDE:
code = KeyCode::KPDivide;
break;
case SDLK_KP_MULTIPLY:
code = KeyCode::KPMultiply;
break;
case SDLK_KP_MINUS:
code = KeyCode::KPSubtract;
break;
case SDLK_KP_PLUS:
code = KeyCode::KPAdd;
break;
case SDLK_KP_ENTER:
code = KeyCode::KPReturn;
break;
case SDLK_KP_1:
code = KeyCode::KPOne;
break;
case SDLK_KP_2:
code = KeyCode::KPTwo;
break;
case SDLK_KP_3:
code = KeyCode::KPThree;
break;
case SDLK_KP_4:
code = KeyCode::KPFour;
break;
case SDLK_KP_5:
code = KeyCode::KPFive;
break;
case SDLK_KP_6:
code = KeyCode::KPSix;
break;
case SDLK_KP_7:
code = KeyCode::KPSeven;
break;
case SDLK_KP_8:
code = KeyCode::KPEight;
break;
case SDLK_KP_9:
code = KeyCode::KPNine;
break;
case SDLK_KP_0:
code = KeyCode::KPZero;
break;
case SDLK_KP_EQUALS:
code = KeyCode::KPEqual;
break;
default:
code = KeyCode::Unknown;
}
if (_event->type == SDL_KEYUP)
window->m_window->publish(KeyUpEvent(code, _event->key.keysym.scancode), true);
else
window->m_window->publish(
KeyDownEvent(code, _event->key.repeat > 0, _event->key.keysym.scancode), true);
}
static void handleMouseEvent(SDL_Event * _event)
{
STICK_ASSERT(_event->type == SDL_MOUSEMOTION || _event->type == SDL_MOUSEWHEEL ||
_event->type == SDL_MOUSEBUTTONDOWN || _event->type == SDL_MOUSEBUTTONUP);
WindowImpl * window = windowForEvent(_event);
if (!window)
return;
if (_event->type == SDL_MOUSEBUTTONDOWN || _event->type == SDL_MOUSEBUTTONUP)
{
MouseButton btn;
switch (_event->button.button)
{
case SDL_BUTTON_LEFT:
btn = MouseButton::Left;
break;
case SDL_BUTTON_RIGHT:
btn = MouseButton::Right;
break;
case SDL_BUTTON_MIDDLE:
btn = MouseButton::Middle;
break;
case SDL_BUTTON_X1:
btn = MouseButton::Button3;
break;
case SDL_BUTTON_X2:
btn = MouseButton::Button4;
break;
//@TODO: We should mostly still propagate the button value as
// something implementation dependant
default:
btn = MouseButton::None;
}
if (_event->type == SDL_MOUSEBUTTONDOWN)
{
g_mouseState.setButtonBitMask(g_mouseState.buttonBitMask() | (UInt32)btn);
window->m_window->publish(MouseDownEvent(g_mouseState, btn), true);
if (!g_initialDragButton)
{
g_initialDragButton = btn;
SDL_CaptureMouse(SDL_TRUE);
}
}
else
{
g_mouseState.setButtonBitMask(g_mouseState.buttonBitMask() & ~(UInt32)btn);
window->m_window->publish(MouseUpEvent(g_mouseState, btn), true);
if (g_initialDragButton && btn == *g_initialDragButton)
{
g_initialDragButton.reset();
SDL_CaptureMouse(SDL_FALSE);
}
}
}
else if (_event->type == SDL_MOUSEMOTION)
{
g_mouseState.setPosition(_event->motion.x, _event->motion.y);
window->m_window->publish(MouseMoveEvent(g_mouseState), true);
}
else if (_event->type == SDL_MOUSEWHEEL)
{
window->m_window->publish(MouseScrollEvent(g_mouseState, _event->wheel.x, _event->wheel.y),
true);
}
}
static void handleTextInputEvent(SDL_Event * _event)
{
STICK_ASSERT(_event->type == SDL_TEXTEDITING || _event->type == SDL_TEXTINPUT);
WindowImpl * window = windowForEvent(_event);
if (!window)
return;
window->m_window->publish(TextInputEvent(_event->text.text), true);
}
Error WindowImpl::pollEvents()
{
SDL_Event e;
while (SDL_PollEvent(&e) != 0)
{
switch (e.type)
{
case SDL_QUIT:
for (WindowImpl * wnd : g_sdlWindows)
wnd->setShouldClose(true);
break;
case SDL_WINDOWEVENT:
handleWindowEvent(&e);
break;
case SDL_KEYDOWN:
case SDL_KEYUP:
handkeKeyEvent(&e);
break;
case SDL_MOUSEMOTION:
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
case SDL_MOUSEWHEEL:
handleMouseEvent(&e);
break;
case SDL_TEXTINPUT:
// case SDL_TEXTEDITING:
handleTextInputEvent(&e);
break;
}
}
return Error();
}
Error WindowImpl::setClipboardText(const char * _text)
{
int res = SDL_SetClipboardText(_text);
RETURN_SDL_ERROR(res);
return Error();
}
const char * WindowImpl::clipboardText()
{
return SDL_GetClipboardText();
}
bool WindowImpl::hasClipboardText()
{
return SDL_HasClipboardText();
}
const MouseState & WindowImpl::mouseState()
{
return g_mouseState;
}
bool WindowImpl::isKeyDown(KeyCode _code)
{
int code;
switch (_code)
{
case KeyCode::Zero:
code = SDL_SCANCODE_0;
break;
case KeyCode::One:
code = SDL_SCANCODE_1;
break;
case KeyCode::Two:
code = SDL_SCANCODE_2;
break;
case KeyCode::Three:
code = SDL_SCANCODE_3;
break;
case KeyCode::Four:
code = SDL_SCANCODE_4;
break;
case KeyCode::Five:
code = SDL_SCANCODE_5;
break;
case KeyCode::Six:
code = SDL_SCANCODE_6;
break;
case KeyCode::Seven:
code = SDL_SCANCODE_7;
break;
case KeyCode::Eight:
code = SDL_SCANCODE_8;
break;
case KeyCode::Nine:
code = SDL_SCANCODE_9;
break;
case KeyCode::A:
code = SDL_SCANCODE_A;
break;
case KeyCode::B:
code = SDL_SCANCODE_B;
break;
case KeyCode::C:
code = SDL_SCANCODE_C;
break;
case KeyCode::D:
code = SDL_SCANCODE_D;
break;
case KeyCode::E:
code = SDL_SCANCODE_E;
break;
case KeyCode::F:
code = SDL_SCANCODE_F;
break;
case KeyCode::G:
code = SDL_SCANCODE_G;
break;
case KeyCode::H:
code = SDL_SCANCODE_H;
break;
case KeyCode::I:
code = SDL_SCANCODE_I;
break;
case KeyCode::J:
code = SDL_SCANCODE_J;
break;
case KeyCode::K:
code = SDL_SCANCODE_K;
break;
case KeyCode::L:
code = SDL_SCANCODE_L;
break;
case KeyCode::M:
code = SDL_SCANCODE_M;
break;
case KeyCode::N:
code = SDL_SCANCODE_N;
break;
case KeyCode::O:
code = SDL_SCANCODE_O;
break;
case KeyCode::P:
code = SDL_SCANCODE_P;
break;
case KeyCode::Q:
code = SDL_SCANCODE_Q;
break;
case KeyCode::R:
code = SDL_SCANCODE_R;
break;
case KeyCode::S:
code = SDL_SCANCODE_S;
break;
case KeyCode::T:
code = SDL_SCANCODE_T;
break;
case KeyCode::U:
code = SDL_SCANCODE_U;
break;
case KeyCode::V:
code = SDL_SCANCODE_V;
break;
case KeyCode::W:
code = SDL_SCANCODE_W;
break;
case KeyCode::X:
code = SDL_SCANCODE_X;
break;
case KeyCode::Y:
code = SDL_SCANCODE_Y;
break;
case KeyCode::Z:
code = SDL_SCANCODE_Z;
break;
case KeyCode::Return:
code = SDL_SCANCODE_RETURN;
break;
case KeyCode::Escape:
code = SDL_SCANCODE_ESCAPE;
break;
case KeyCode::Backspace:
code = SDL_SCANCODE_BACKSPACE;
break;
case KeyCode::Tab:
code = SDL_SCANCODE_TAB;
break;
case KeyCode::Space:
code = SDL_SCANCODE_SPACE;
break;
case KeyCode::Subtract:
code = SDL_SCANCODE_MINUS;
break;
case KeyCode::Equal:
code = SDL_SCANCODE_EQUALS;
break;
case KeyCode::LeftBracket:
code = SDL_SCANCODE_LEFTBRACKET;
break;
case KeyCode::RightBracket:
code = SDL_SCANCODE_RIGHTBRACKET;
break;
case KeyCode::Backslash:
code = SDL_SCANCODE_BACKSLASH;
break;
case KeyCode::Semicolon:
code = SDL_SCANCODE_SEMICOLON;
break;
case KeyCode::Apostrophe:
code = SDL_SCANCODE_APOSTROPHE;
break;
case KeyCode::GraveAccent:
code = SDL_SCANCODE_GRAVE;
break;
case KeyCode::Comma:
code = SDL_SCANCODE_COMMA;
break;
case KeyCode::Period:
code = SDL_SCANCODE_PERIOD;
break;
case KeyCode::Slash:
code = SDL_SCANCODE_SLASH;
break;
case KeyCode::CapsLock:
code = SDL_SCANCODE_CAPSLOCK;
break;
case KeyCode::F1:
code = SDL_SCANCODE_F1;
break;
case KeyCode::F2:
code = SDL_SCANCODE_F2;
break;
case KeyCode::F3:
code = SDL_SCANCODE_F3;
break;
case KeyCode::F4:
code = SDL_SCANCODE_F4;
break;
case KeyCode::F5:
code = SDL_SCANCODE_F5;
break;
case KeyCode::F6:
code = SDL_SCANCODE_F6;
break;
case KeyCode::F7:
code = SDL_SCANCODE_F7;
break;
case KeyCode::F8:
code = SDL_SCANCODE_F8;
break;
case KeyCode::F9:
code = SDL_SCANCODE_F9;
break;
case KeyCode::F10:
code = SDL_SCANCODE_F10;
break;
case KeyCode::F11:
code = SDL_SCANCODE_F11;
break;
case KeyCode::F12:
code = SDL_SCANCODE_F12;
break;
case KeyCode::F13:
code = SDL_SCANCODE_F13;
break;
case KeyCode::F14:
code = SDL_SCANCODE_F14;
break;
case KeyCode::F15:
code = SDL_SCANCODE_F15;
break;
case KeyCode::F16:
code = SDL_SCANCODE_F16;
break;
case KeyCode::Insert:
code = SDL_SCANCODE_INSERT;
break;
case KeyCode::Home:
code = SDL_SCANCODE_HOME;
break;
case KeyCode::PageUp:
code = SDL_SCANCODE_PAGEUP;
break;
case KeyCode::Delete:
code = SDL_SCANCODE_DELETE;
break;
case KeyCode::End:
code = SDL_SCANCODE_END;
break;
case KeyCode::PageDown:
code = SDL_SCANCODE_PAGEDOWN;
break;
case KeyCode::LeftControl:
code = SDL_SCANCODE_LCTRL;
break;
case KeyCode::LeftShift:
code = SDL_SCANCODE_LSHIFT;
break;
case KeyCode::LeftAlt:
code = SDL_SCANCODE_LALT;
break;
case KeyCode::LeftCommand:
code = SDL_SCANCODE_LGUI;
break;
case KeyCode::RightControl:
code = SDL_SCANCODE_RCTRL;
break;
case KeyCode::RightShift:
code = SDL_SCANCODE_RSHIFT;
break;
case KeyCode::RightAlt:
code = SDL_SCANCODE_RALT;
break;
case KeyCode::RightCommand:
code = SDL_SCANCODE_RGUI;
break;
case KeyCode::Right:
code = SDL_SCANCODE_RIGHT;
break;
case KeyCode::Left:
code = SDL_SCANCODE_LEFT;
break;
case KeyCode::Down:
code = SDL_SCANCODE_DOWN;
break;
case KeyCode::Up:
code = SDL_SCANCODE_UP;
break;
case KeyCode::KPDivide:
code = SDL_SCANCODE_KP_DIVIDE;
break;
case KeyCode::KPMultiply:
code = SDL_SCANCODE_KP_MULTIPLY;
break;
case KeyCode::KPSubtract:
code = SDL_SCANCODE_KP_MINUS;
break;
case KeyCode::KPAdd:
code = SDL_SCANCODE_KP_PLUS;
break;
case KeyCode::KPReturn:
code = SDL_SCANCODE_KP_ENTER;
break;
case KeyCode::KPOne:
code = SDL_SCANCODE_KP_1;
break;
case KeyCode::KPTwo:
code = SDL_SCANCODE_KP_2;
break;
case KeyCode::KPThree:
code = SDL_SCANCODE_KP_3;
break;
case KeyCode::KPFour:
code = SDL_SCANCODE_KP_4;
break;
case KeyCode::KPFive:
code = SDL_SCANCODE_KP_5;
break;
case KeyCode::KPSix:
code = SDL_SCANCODE_KP_6;
break;
case KeyCode::KPSeven:
code = SDL_SCANCODE_KP_7;
break;
case KeyCode::KPEight:
code = SDL_SCANCODE_KP_8;
break;
case KeyCode::KPNine:
code = SDL_SCANCODE_KP_9;
break;
case KeyCode::KPZero:
code = SDL_SCANCODE_KP_0;
break;
case KeyCode::KPEqual:
code = SDL_SCANCODE_KP_EQUALS;
break;
default:
code = -1;
}
if (code == -1)
return false;
const Uint8 * state = SDL_GetKeyboardState(NULL);
return state[code];
}
UInt32 WindowImpl::modifiers()
{
UInt32 ret = 0;
SDL_Keymod mods = SDL_GetModState();
if (mods & KMOD_LSHIFT)
{
ret |= (UInt32)KeyModifier::LeftShift;
}
else if (mods & KMOD_RSHIFT)
{
ret |= (UInt32)KeyModifier::RightShift;
}
else if (mods & KMOD_LGUI)
{
ret |= (UInt32)KeyModifier::LeftCommand;
}
else if (mods & KMOD_RGUI)
{
ret |= (UInt32)KeyModifier::RightCommand;
}
else if (mods & KMOD_LCTRL)
{
ret |= (UInt32)KeyModifier::LeftControl;
}
else if (mods & KMOD_RCTRL)
{
ret |= (UInt32)KeyModifier::RightControl;
}
else if (mods & KMOD_LALT)
{
ret |= (UInt32)KeyModifier::LeftAlt;
}
else if (mods & KMOD_RALT)
{
ret |= (UInt32)KeyModifier::RightAlt;
}
else if (mods & KMOD_CAPS)
{
ret |= (UInt32)KeyModifier::CapsLock;
}
else if (mods & KMOD_NUM)
{
ret |= (UInt32)KeyModifier::Numbers;
}
return ret;
}
bool WindowImpl::modifier(KeyModifier _mod)
{
return (modifiers() & (UInt32)_mod) != 0;
}
} // namespace detail
} // namespace luke
|
1df115b729f0b9f643cb79bcff25fc0f73b28518
|
4fc4700061284933f67e8c5a710437342c53db9a
|
/queue/queue.tpp
|
c42d75928f352e1e11884d4961afb5350f5d1c76
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
gefjon/data_structures
|
99f0bbe1beb69f5aa8c93e953e554dfa72e0c767
|
9bf9f35272e168ffc7ffb30fa44e87761773b845
|
refs/heads/master
| 2020-03-20T21:37:21.041816
| 2018-06-24T16:19:37
| 2018-06-24T16:19:37
| 137,750,815
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,539
|
tpp
|
queue.tpp
|
namespace Queue {
template< class T >
bool Queue< T >::head_is_defined() {
return (this->head_) ? true : false;
}
template< class T >
bool Queue< T >::tail_is_defined() {
return (this->tail_) ? true : false;
}
template< class T >
void Queue< T >::assert_defined() {
assert(this->head_is_defined());
assert(this->tail_is_defined());
}
template< class T >
Queue< T >::Queue() {};
template< class T >
Queue< T >::Queue(const Queue< T >& other) = default;
template< class T >
Queue< T >::~Queue() = default;
template< class T >
void Queue< T >::Enqueue(T to_enqueue) {
auto node = std::make_shared< LinkedList::Node< T > >(std::move(to_enqueue));
if (this->length_ == 0) {
this->head_ = node;
this->tail_ = node;
} else {
this->assert_defined();
this->tail_->next_ = node;
this->tail_ = node;
}
this->length_ += 1;
}
template< class T >
T Queue< T >::Dequeue() {
if (this->length_ == 0) {
throw new UnderflowException();
}
this->assert_defined();
this->length_ -= 1;
auto new_head = this->head_->Cdr();
T to_return = std::move(this->head_->Car());
this->head_ = new_head;
return to_return;
}
template< class T >
T& Queue< T >::Peek() {
if (this->length_ == 0) {
throw new UnderflowException();
}
this->assert_defined();
return this->head_->Car();
}
template< class T >
unsigned int Queue< T >::Length() {
return this->length_;
}
}
|
7c11b67dd881651ae88749108592ea06c5aec19b
|
36183993b144b873d4d53e7b0f0dfebedcb77730
|
/GameDevelopment/Game Programming Gems 3/Source Code/02 Mathematics/05 Weber/CoralTree/ew/event.cc
|
23b2f43c145b9be17970131495a8cdee4e27f3c7
|
[
"Artistic-2.0",
"Intel",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
alecnunn/bookresources
|
b95bf62dda3eb9b0ba0fb4e56025c5c7b6d605c0
|
4562f6430af5afffde790c42d0f3a33176d8003b
|
refs/heads/master
| 2020-04-12T22:28:54.275703
| 2018-12-22T09:00:31
| 2018-12-22T09:00:31
| 162,790,540
| 20
| 14
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 15,320
|
cc
|
event.cc
|
/******************************************************************************
Coral Tree ew/event.cc
Copyright (C) 1998 Infinite Monkeys Incorporated
This program is free software; you can redistribute it and/or modify
it under the terms of the Artistic License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Artistic License for more details.
You should have received a copy of the Artistic License along with
this program (see meta/ART_LICE); if not, write to coral@imonk.com.
******************************************************************************/
#include "ew.h"
#define EW_EVENT_PRINTSOURCE (EW_EVENT_ANY) // events reported by EW_Event::Print() try EW_EVENT_ANY or EW_EVENT_COMMON
#define EW_EVENT_QUEUE_DEBUG FALSE
/******************************************************************************
EW_Event::EW_Event(void)
******************************************************************************/
EW_Event::EW_Event(void)
{
clipregion=NULL;
Reset();
}
/******************************************************************************
EW_Event::~EW_Event(void)
******************************************************************************/
EW_Event::~EW_Event(void)
{
if(clipregion)
delete clipregion;
}
/******************************************************************************
void EW_Event::Reset(void)
******************************************************************************/
void EW_Event::Reset(void)
{
destination=NULL;
source=EW_EVENT_NONE;
item=EW_ITEM_NONE;
state=EW_STATE_NULL;
choice=NULL;
lastchoice=NULL;
mx= -1;
my= -1;
mousebuttons=0;
widget_flags=0;
time=0;
repetition=0;
dislocated=FALSE;
used=FALSE;
if(clipregion)
{
delete clipregion;
clipregion=NULL;
}
}
/******************************************************************************
void EW_Event::CopyFrom(EW_Event *other)
******************************************************************************/
void EW_Event::CopyFrom(EW_Event *other)
{
destination=other->destination;
source=other->source;
item=other->item;
state=other->state;
choice=other->choice;
lastchoice=other->lastchoice;
mx=other->mx;
my=other->my;
mousebuttons=other->mousebuttons;
widget_flags=other->widget_flags;
time=other->time;
repetition=other->repetition;
used=other->used;
if(clipregion)
{
delete clipregion;
clipregion=NULL;
}
if(other->clipregion)
{
clipregion= new EW_ClipRegion;
clipregion->CopyFrom(other->clipregion);
}
}
/******************************************************************************
long EW_Event::IsKeyOfState(long key,long state)
******************************************************************************/
long EW_Event::IsKeyOfState(long key,long state)
{
long mod=item;
long item2= (item&EW_KEY_NO_MOD_MASK);
long key2= (key&EW_KEY_NO_MOD_MASK);
if(mod>='A' && mod<='Z')
mod|=EW_KEY_SHIFT;
if(key>='A' && key<='Z')
key|=EW_KEY_SHIFT;
long same_nonindexed= ( (item2>=EW_KEY_INDEXED_KEYS || key2>=EW_KEY_INDEXED_KEYS) && (item2&key2));
long same_mod= ( (mod&EW_KEY_MOD_MASK) == (key&EW_KEY_MOD_MASK) || mod==EW_KEY_ALL || key==EW_KEY_ALL);
// printf("mod=0x%x key=0x%x same_nonindexed=%d same_mod=%d\n",mod,key,same_nonindexed,same_mod);
return (Is(EW_EVENT_KEYBOARD,EW_ITEM_ALL,state) && ((item2==key2 || same_nonindexed) && same_mod) );
}
/******************************************************************************
void EW_Event::MapControlCharacters(void)
map control codes into just original character plus control bit
******************************************************************************/
void EW_Event::MapControlCharacters(void)
{
// EW_PRINT(EW_WINDOW,EW_LOG,"source=0x%x",source);
if(GetSource()!=EW_EVENT_KEYBOARD)
return;
// convert carriage-return's to '\n'
if(GetItem()==EW_KEY_CR)
SetItem(EW_KEY_RETURN);
long item= GetItem();
long ascii= (item&EW_KEY_ALL_ASCII);
// EW_PRINT(EW_WINDOW,EW_LOG,"ascii=%d",ascii);
// leave recognized keys alone
if(ascii==EW_KEY_BACKSPACE || ascii==EW_KEY_RETURN || ascii==EW_KEY_CR || ascii==EW_KEY_ESC || ascii==EW_KEY_DELETE )
return;
if(item&EW_KEY_NON_ASCII_FLAG)
return;
// zero is OK only if not a cursor or F-key
if(ascii==0x00 && (item & (EW_KEY_F_KEYS|EW_KEY_ANY_CURSOR)) )
return;
// control codes
if(ascii<0x20)
{
if(ascii<0x1b) // `a-z
ascii+='`';
else if(ascii<0x1e) // [\]
ascii+='@';
else if(ascii==0x1e) // ~/
ascii='~';
else // 0x1f
ascii='/';
// make sure shifted chars are uppercase
if((item&(EW_KEY_SHIFT|EW_KEY_CAPS_LOCK)) && ascii>='a' && ascii<='z')
ascii += ('A'-'a');
item &= EW_KEY_ASCII_NOT;
item |= EW_KEY_CONTROL;
item |= ascii;
// EW_PRINT(EW_WINDOW,EW_LOG," to %d item=0x%x",ascii,item);
SetItem(item);
}
}
/******************************************************************************
long EW_Event::Print(long hexcode)
print event data for debugging
returns TRUE if printed (not masked out)
Keywords:
******************************************************************************/
long EW_Event::Print(long hexcode)
{
char ew_print_message[1024];
char source_note[64];
char item_note[64];
char state_note[64];
char used_note[64];
char widget_note[64];
char mouse_note[64];
char temp[256];
source_note[0]=0;
item_note[0]=0;
state_note[0]=0;
used_note[0]=0;
widget_note[0]=0;
mouse_note[0]=0;
EW_Event mask;
mask.SetSISW(EW_EVENT_PRINTSOURCE,EW_ITEM_ALL,EW_STATE_ANY,EW_WIDGET_FLAGS_ALL);
if(!Intersects(&mask))
return FALSE;
if(item==EW_ITEM_ALL)
sprintf(item_note,"ALL");
else
sprintf(item_note,"???");
if(state==EW_STATE_ANY)
sprintf(state_note,"ANY");
else if(source&EW_EVENT_COMMON)
{
if(state==EW_STATE_NULL)
sprintf(state_note,"NULL");
else if(state==EW_STATE_PRESS)
sprintf(state_note,"PRESS");
else if(state==EW_STATE_REPEAT)
sprintf(state_note,"REPEAT");
else if(state==EW_STATE_RELEASE)
sprintf(state_note,"RELEASE");
}
if(source==EW_EVENT_NONE)
sprintf(source_note,"NONE");
else if(source==EW_EVENT_MOUSEPOSITION)
{
sprintf(source_note,"POS");
if( (item&EW_KEY_NO_MOD_MASK) == (EW_ITEM_X|EW_ITEM_Y) )
sprintf(item_note,"XY");
}
else if(source==EW_EVENT_MOUSEBUTTON)
{
sprintf(source_note,"BUTTON");
if((item&EW_KEY_NO_MOD_MASK)==EW_ITEM_LEFT)
sprintf(item_note,"LEFT");
else if((item&EW_KEY_NO_MOD_MASK)==EW_ITEM_MIDDLE)
sprintf(item_note,"MIDDLE");
else if((item&EW_KEY_NO_MOD_MASK)==EW_ITEM_RIGHT)
sprintf(item_note,"RIGHT");
else if((item&EW_KEY_NO_MOD_MASK)==EW_ITEM_WHEEL)
{
sprintf(item_note,"WHEEL");
if(state>0)
sprintf(state_note,"UP");
else if(state<0)
sprintf(state_note,"DOWN");
}
}
else if(source==EW_EVENT_KEYBOARD)
{
sprintf(source_note,"KEY");
long item2= (item&EW_KEY_NO_MOD_MASK);
if(item==EW_KEY_ALL)
sprintf(item_note,"ALL_KEYS");
else if(item2==EW_KEY_BACKSPACE)
sprintf(item_note,"BS");
else if(item2==EW_KEY_RETURN)
sprintf(item_note,"RET");
else if(item2==EW_KEY_CR)
sprintf(item_note,"CR (warning!)");
else if(item2==EW_KEY_ESC)
sprintf(item_note,"ESC");
else if(item2==EW_KEY_DELETE)
sprintf(item_note,"DEL");
else if(item2==EW_KEY_ALL_ASCII)
sprintf(item_note,"ALL_ASCII");
else if(item2==EW_KEY_HOME)
sprintf(item_note,"HOME");
else if(item2==EW_KEY_END)
sprintf(item_note,"END");
else if(item2==EW_KEY_INSERT)
sprintf(item_note,"INSERT");
else if(item2==EW_KEY_TAB)
sprintf(item_note,"TAB");
else if(item2==EW_KEY_PAUSE)
sprintf(item_note,"PAUSE");
else if(item2==EW_KEY_PAGE_UP)
sprintf(item_note,"PgUp");
else if(item2==EW_KEY_PAGE_DOWN)
sprintf(item_note,"PgDn");
else if(item2==EW_KEY_F_KEYS)
sprintf(item_note,"F-KEYS");
else if(item2&EW_KEY_F_KEYS && (item2>>EW_KEY_F_KEY_SHIFT)>0 && (item2>>EW_KEY_F_KEY_SHIFT)<17 )
sprintf(item_note,"F%d",(int)(item2>>EW_KEY_F_KEY_SHIFT));
else if(item2==EW_KEY_CURSOR_UP)
sprintf(item_note,"UP");
else if(item2==EW_KEY_CURSOR_DOWN)
sprintf(item_note,"DOWN");
else if(item2==EW_KEY_CURSOR_LEFT)
sprintf(item_note,"LEFT");
else if(item2==EW_KEY_CURSOR_RIGHT)
sprintf(item_note,"RIGHT");
else if(item2==EW_KEY_ANY_CURSOR)
sprintf(item_note,"ANY_CURSOR");
else if(item&EW_KEY_UNUSED_MASK)
sprintf(item_note,"UNUSED_MASK?");
else if(item2&EW_KEY_ANY_CURSOR)
sprintf(item_note,"CURSOR");
else if(item2<128)
sprintf(item_note,"%c",(char)(item));
else
sprintf(item_note,"MASK?");
}
else if(source==EW_EVENT_FOCUS)
{
sprintf(source_note,"FOCUS");
if(item==EW_ITEM_FOCUSCHANGE)
{
sprintf(item_note,"CHANGE");
EW_Window *target=(EW_Window *)state;
if(target)
sprintf(state_note,"(%s)",target->GetTitle());
else
sprintf(state_note,"LEAVE");
}
else if(item==EW_ITEM_IDLEMOUSE)
sprintf(item_note,"IDLE");
}
else if(source==EW_EVENT_CLIPBOARD)
{
sprintf(source_note,"CLIPBOARD");
if(item==EW_ITEM_CLIPBOARD_READY)
sprintf(item_note,"READY");
else if(item==EW_ITEM_CLIPBOARD_FAIL)
sprintf(item_note,"FAIL");
}
else if(source==EW_EVENT_PERIODIC)
{
sprintf(source_note,"PERIODIC");
if(item==EW_ITEM_WORK)
sprintf(item_note,"WORK");
else if(item==EW_ITEM_TIMER)
sprintf(item_note,"TIMER");
}
else if(source==EW_EVENT_SYSTEM)
{
sprintf(source_note,"SYS");
if(item==EW_ITEM_CLOSEWINDOW)
sprintf(item_note,"CLOSE");
else if(item==EW_ITEM_QUIT_APP)
sprintf(item_note,"QUIT_APP");
else if(item==EW_ITEM_EXPOSURE)
{
sprintf(item_note,"EXPO");
EW_Window *target=(EW_Window *)state;
if(target)
sprintf(state_note,"(%s)",target->GetTitle());
}
}
else if(source&EW_EVENT_INTERNAL)
{
sprintf(source_note,"MASK");
}
else
{
if(source==EW_EVENT_WIDGET)
sprintf(source_note,"WIDGET");
else if(source==EW_EVENT_APPLICATION)
sprintf(source_note,"APP");
else if(source==EW_EVENT_ANY)
sprintf(source_note,"ANY");
else
sprintf(source_note,"MASK?");
}
if(source==EW_EVENT_KEYBOARD || source==EW_EVENT_MOUSEBUTTON || source==EW_EVENT_MOUSEPOSITION)
{
if(item!=EW_KEY_ALL)
{
strcpy(temp,item_note);
sprintf(item_note,"%s%s%s%s%s", (item&EW_KEY_SHIFT)? "S":"",
(item&EW_KEY_CAPS_LOCK)? "L":"",
(item&EW_KEY_CONTROL)? "C":"",
(item&(EW_KEY_SHIFT|EW_KEY_CAPS_LOCK|EW_KEY_CONTROL))? " ":"",
temp);
}
}
if(used==EW_USED_NONE)
strcat(used_note,"NONE");
else if(used==EW_USED_TRUE)
strcat(used_note,"TRUE");
else if(used==EW_USED_ALL)
strcat(used_note,"ALL");
else
{
if(used&EW_USED_GRABX && used&EW_USED_DRAGX)
strcat(used_note,"ax");
else if(used&EW_USED_GRABX)
strcat(used_note,"gx");
else if(used&EW_USED_DRAGX)
strcat(used_note,"dx");
if(used&EW_USED_GRABY && used&EW_USED_DRAGY)
strcat(used_note,"ay");
else if(used&EW_USED_GRABY)
strcat(used_note,"gy");
else if(used&EW_USED_DRAGY)
strcat(used_note,"dy");
}
// officially, EW knows nothing about these, but this is really convenient
if(widget_flags)
{
// WDS_BYPASS_EVENT
if(widget_flags&0x00000001)
strcat(widget_note,"Bypass");
// WDS_BYPASS_TAKE_LOST
if(widget_flags&0x00000002)
strcat(widget_note,"Lost");
// WDS_BYPASS_IN_FOCUS
if(widget_flags&0x00000004)
strcat(widget_note,"Focus");
strcat(widget_note,"?");
}
if(mousebuttons)
{
if(mousebuttons&0x01)
strcat(mouse_note,"L");
if(mousebuttons&0x02)
strcat(mouse_note,"M");
if(mousebuttons&0x04)
strcat(mouse_note,"R");
}
if(source_note[0])
{
strcpy(temp,source_note);
sprintf(source_note," %s%s%s",ewColorCode(EW_CODE_RED),temp,ewColorCode(EW_CODE_WHITE));
}
if(item_note[0])
{
strcpy(temp,item_note);
sprintf(item_note," %s%s%s",ewColorCode(EW_CODE_GREEN),temp,ewColorCode(EW_CODE_WHITE));
}
if(state_note[0])
{
strcpy(temp,state_note);
sprintf(state_note," %s%s%s",ewColorCode(EW_CODE_YELLOW),temp,ewColorCode(EW_CODE_WHITE));
}
if(used_note[0])
{
strcpy(temp,used_note);
sprintf(used_note," %s%s%s",ewColorCode(EW_CODE_MAGENTA),temp,ewColorCode(EW_CODE_WHITE));
}
if(widget_note[0])
{
strcpy(temp,widget_note);
sprintf(widget_note," %s%s%s",ewColorCode(EW_CODE_CYAN),temp,ewColorCode(EW_CODE_WHITE));
}
if(mouse_note[0])
{
strcpy(temp,mouse_note);
sprintf(mouse_note," %s%s%s",ewColorCode(EW_CODE_RED),temp,ewColorCode(EW_CODE_WHITE));
}
sprintf(ew_print_message,"%sEVENT:src=0x%x%s item=0x%x%s state=0x%x%s used=0x%x%s widget_flags=0x%x%s time=%d%s",
ewColorCode(EW_CODE_WHITE),
(unsigned int)(source),source_note,(unsigned int)(item),item_note,
(unsigned int)state,state_note,(unsigned int)used,used_note,
(unsigned int)widget_flags,widget_note,(int)time,
ewColorCode(EW_CODE_NORMAL));
EW_PRINT(EW_EVENT,EW_LOG,ew_print_message);
sprintf(ew_print_message,"%s rep=%s%d%s choice=0x%x/0x%x mouse=(%d,%d)0x%x%s code=0x%x for 0x%x (%s)%s",
ewColorCode(EW_CODE_WHITE),
repetition? ewColorCode(EW_CODE_GREEN): "",
(int)repetition,ewColorCode(EW_CODE_WHITE),
(int)choice,(int)lastchoice,(int)mx,(int)my,(int)mousebuttons,mouse_note,(int)hexcode,
(int)destination,destination? destination->GetTitle(): "",
ewColorCode(EW_CODE_NORMAL));
EW_PRINT(EW_EVENT,EW_LOG,ew_print_message);
if(clipregion)
{
sprintf(ew_print_message,"%sClip:%s",ewColorCode(EW_CODE_YELLOW),ewColorCode(EW_CODE_NORMAL));
EW_Rectangle *node;
long x,y,sx,sy;
clipregion->ToHead();
while( (node=clipregion->PostIncrement()) != NULL )
{
node->GetGeometry(&x,&y,&sx,&sy);
sprintf(temp," (%d,%d %d,%d)",(int)x,(int)y,(int)sx,(int)sy);
strcat(ew_print_message,temp);
}
EW_PRINT(EW_EVENT,EW_LOG,ew_print_message);
}
return TRUE;
}
/******************************************************************************
void EW_EventQueue::AppendCopyOf(EW_Event *other)
******************************************************************************/
void EW_EventQueue::AppendCopyOf(EW_Event *other)
{
EW_Event *event=new EW_Event;
event->CopyFrom(other);
AppendNode(event);
}
/******************************************************************************
void EW_EventQueue::ProcessAllEvents(void)
******************************************************************************/
void EW_EventQueue::ProcessAllEvents(void)
{
if(!GetNumberNodes())
return;
EW_Event *event;
EW_Window *target;
#if EW_EVENT_QUEUE_DEBUG
// EW_PRINT(EW_EVENT,EW_LOG,"%sEW_EventQueue::ProcessAllEvents()%s begin",ewColorCode(4),ewColorCode(EW_CODE_NORMAL));
#endif
long m=0;
while( (event=ToHead()) != NULL)
{
#if EW_EVENT_QUEUE_DEBUG
EW_PRINT(EW_EVENT,EW_LOG,"%sEW_EventQueue::ProcessAllEvents()%s processing %d/%d",
ewColorCode(EW_CODE_BLUE),ewColorCode(EW_CODE_NORMAL),m+1,GetNumberNodes());
event->Print(m);
#endif
if((target=event->GetDestination()))
target->ProcessEvent(event,TRUE);
RemoveNode(event);
delete event;
m++;
}
#if EW_EVENT_QUEUE_DEBUG
// EW_PRINT(EW_EVENT,EW_LOG,"%sEW_EventQueue::ProcessAllEvents()%s complete",ewColorCode(4),ewColorCode(EW_CODE_NORMAL));
#endif
}
|
acd3d43aa6feae982c996aa2b8df18b6b86b6671
|
7a7b308f025070c29681c419f8a247451c7f1521
|
/Recursion/src/towers.cpp
|
307ce4255ad867703a5176334183cc79e85d71be
|
[] |
no_license
|
arnottkid/CS140
|
15416ab29bcbb1da0498c7b2edde67ffc174309d
|
a2b37d02c8a2c9073d3854cb42d7a282cc119d0b
|
refs/heads/master
| 2022-12-31T06:11:22.583466
| 2020-09-05T15:06:43
| 2020-09-05T15:06:43
| 305,836,921
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,584
|
cpp
|
towers.cpp
|
#include "towers.hpp"
#include <cstdio>
#include <iostream>
using namespace std;
/* The constructor puts all of the disks onto tower 0.
The front of the deque is the top of the tower */
Towers::Towers(int n)
{
int i;
if (n <= 0) throw ((string) "Towers::Towers() - Bad value of n");
for (i = 1; i <= n; i++) T[0].push_back(i);
}
/* Moving is mostly a matter of error checking. If all is ok,
we remove the disk from the front of the "from" tower and
add it to the front of the "to" tower. */
string Towers::Move(int from, int to, bool print)
{
int disk;
/* Error checking */
if (from < 0 || from > 2) return "Bad source tower";
if (to < 0 || to > 2) return "Bad destiniation tower";
if (T[from].empty()) return "Source tower is empty";
if (!T[to].empty() && T[from][0] > T[to][0]) {
return "Disk on the source tower is bigger than the top of the destination tower";
}
/* Move the disk and return success */
disk = T[from][0];
T[to].push_front(disk);
T[from].pop_front();
if (print) printf("Moving disk of size %d from tower %d to tower %d\n", disk, from, to);
return "";
}
/* Print() creates ASCII art of the towers. Since we want them to have their
bases line up, we have to put in a little effort to print the right values
in the right places. */
void Towers::Print() const
{
int max_disk, dots, spaces;
size_t max_height, i, index;
int j, k;
/* Calculate the maximum size disk, and the height of the tallest tower. */
max_disk = T[0].size() + T[1].size() + T[2].size();
max_height = T[0].size();
if (T[1].size() > max_height) max_height = T[1].size();
if (T[2].size() > max_height) max_height = T[2].size();
/* Now, go from top to bottom, then left to right, and for each row and
tower, first figure out if you are printing a disk. If so, you set
"dots" to be the size of the disk. If there is no disk, "dots" is zero.
Then you'll print "dots" dots, and (max_disk-dots+1) spaces (the extra space
is to put spaces between the towers. */
for (i = 0; i < max_height; i++) {
index = max_height - i - 1;
for (j = 0; j < 3; j++) {
if (T[j].size() > index) {
dots = T[j][T[j].size()-index-1];
} else {
dots = 0;
}
spaces = max_disk - dots + 1;
for (k = 0; k < dots; k++) printf(".");
for (k = 0; k < spaces; k++) printf(" ");
}
printf("\n");
}
/* Finally, print the bases of the towers */
for (j = 0; j < 3; j++) {
for (k = 0; k < max_disk; k++) printf("-");
printf(" ");
}
printf("\n");
}
|
06182deb237d934fb06015d5f402f8e9c8444763
|
d20c13b335583458c5e6e668545a8cfa91dd732a
|
/Include/Media/Bmp.cpp
|
6a7342a2a551508b46c4847d5dc755a49847b97b
|
[] |
no_license
|
Litutu/LiongPlus
|
2b9a122c68553165a84edffe59b7e8e914ad3b27
|
6eda1702b6c1bee214ff33fd7f6f447517d440bd
|
refs/heads/master
| 2020-04-08T14:41:30.788602
| 2016-06-17T13:11:06
| 2016-06-17T13:11:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,642
|
cpp
|
Bmp.cpp
|
// File: Bmp.cpp
// Author: Rendong Liang (Liong)
#include "Media/Bmp.hpp"
namespace LiongPlus
{
namespace Media
{
// Public
Bmp::Bmp(Image& instance)
: _Bitmap(instance.Interpret(PixelType::Bgr), instance.GetSize(), instance.GetPixelType())
{
}
Bmp::Bmp(Buffer& buffer)
: _Bitmap(Init(buffer))
{
}
Bmp::~Bmp()
{
}
/* TextureRef Bmp::ToTexture(_L_Char *path, Flag option)
{
Log << L"Bmp: Try loading " << path << L"...";
if (stream.is_open())
stream.close();
stream.open(path, stream.in | stream.binary | stream._Nocreate);
TextureRef ref;
Size size;
long dataLength;
if (InitHeader(size, dataLength))
{
Byte* data = ReadData(dataLength);
if (!data)
return TextureRef();
ref = TextureManager.NewTexture(dataLength, data, size, Texture::PixelFormat::BGR, Texture::ByteSize::UByte);
if ((option & FileReadOption::NoGenerate) == FileReadOption::None)
ref.lock()->Generate();
}
else
{
Log.Log((L"Bmp: Failed in loading " + w_L_String(path) + L"!").c_str(), Logger::WarningLevel::Warn);
return TextureRef();
}
if ((option & FileReadOption::NoClose) == FileReadOption::None)
stream.close();
Log << L"Bmp: Succeeded!";
return ref;
}*/
// Derived from [intFramework::Media::Image]
Buffer Bmp::GetChunk(Point position, Size size) const
{
return _Bitmap.GetChunk(position, size);
}
size_t Bmp::GetInterpretedLength(PixelType pixelType) const
{
return _Bitmap.GetInterpretedLength(pixelType);
}
Buffer Bmp::GetPixel(Point position) const
{
return _Bitmap.GetPixel(position);
}
PixelType Bmp::GetPixelType() const
{
return _Bitmap.GetPixelType();
}
Size Bmp::GetSize() const
{
return _Bitmap.GetSize();
}
bool Bmp::IsEmpty() const
{
return _Bitmap.IsEmpty();
}
Buffer Bmp::Interpret(PixelType pixelType) const
{
return _Bitmap.Interpret(pixelType);
}
// Private
Bitmap Bmp::Init(Buffer& buffer)
{
assert(buffer.Length() < 54, "Incomplete header.");
assert(buffer[0] != 'B' || buffer[1] != 'M', "Unsupported bmp format.");
assert(*((unsigned short*)(buffer.Field() + 28)) != 24, "Unsupported pixel type."); // Bits per pixel.
unsigned int offset = *((unsigned int*)(buffer.Field() + 10));
Size size = { *((int*)(buffer.Field() + 18)), *((int*)(buffer.Field() + 22)) };
size_t length = buffer.Length() - offset;
Buffer pixels(length);
memcpy(pixels.Field(), buffer.Field() + offset, buffer.Length() - offset);
return Bitmap(buffer.Field() + offset, size, PixelType::Bgr);
}
}
}
|
e5e33f4e7d6f55d0f3d69b6e8eff7f8af7f42369
|
3dd6db3ad15c2c2738c512678bd274fff04e8c35
|
/WatchDog/WatchDog.cpp
|
37586870143079b6c9c76007d331c148116feda4
|
[] |
no_license
|
howardxu4/Wijet2
|
4935f1bb942cca5651e006cbd57c52c64ce73334
|
a0e157302a0fd9b9d7dc1e8a4a40b115dd6b22c4
|
refs/heads/master
| 2021-01-19T19:35:40.031496
| 2015-05-18T21:03:38
| 2015-05-18T21:03:38
| 35,842,190
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,093
|
cpp
|
WatchDog.cpp
|
#include "WatchDog.h"
#include <pthread.h>
/**
* The WatchDog class
*
* @author Howard Xu
* @version 2.5
*/
void* syscall(void *p)
{
system((char*)p);
pthread_exit(0);
}
void* invoke(void *p)
{
WatchDog* wd = (WatchDog*)p;
wd->loop();
pthread_exit(0);
}
WatchDog::WatchDog()
{
m_burn = false;
m_mount = false;
m_continue = 1;
m_Log = new LogTrace("WatchDog");
setLog();
}
WatchDog::~WatchDog()
{
if (m_continue == 0) {
// setLED(6);
setWiJET(false); // stop wijet
setNetwork(false); // stop network
}
else {
m_Log->log(LogTrace::ERROR, "System will shutdown!");
system("shutdown -g 1");
}
}
/**
* setLog method
*/
void WatchDog::setLog()
{
char* f = NULL;
getProperty gP(gP.P_OTC);
int i = LogTrace::ERROR;
if (gP.getInt("MODULES") & 8) { // ST 1: AI 2: MD 4: WD 8
i = gP.getInt("DEBUG");
if (i != 0) f = "/www/log/watchdog";
}
m_Log->setLog(i, f);
}
void WatchDog::callSys(char *cmd)
{
pthread_t myThread;
pthread_create( &myThread, NULL, syscall, (void*)cmd);
}
void WatchDog::dump()
{
printf("State = %d\n", m_shmm->State);
printf("Debug = %d\n", m_shmm->Debug);
printf("moderatorIP = %lu\n", m_shmm->moderatorIP);
printf("grantedIP = %lu\n", m_shmm->grantedIP);
printf("Mode = %d\n", m_shmm->Mode);
printf("changes = %d\n", m_shmm->Changes);
printf("status = %d\n", m_shmm->status);
printf("burnTimes=%d\n", m_shmm->BurnTimes);
printf("SNumber=%s\n", m_shmm->SNumber);
}
bool WatchDog::ckHW()
{
char SN[10];
strcpy(SN, "000000");
ShMemory shm;
if (checkHW(SN) != 0) {
m_Log->log(LogTrace::ERROR, "Check Hardware DOM fails");
return false;
}
shm.setSNumber(SN);
return true;
}
int WatchDog::init(int n)
{
ShMemory shm;
m_shmm = shm.getShmp();
if (m_shmm == NULL) {
m_Log->log(LogTrace::ERROR, "Shared Memory module fails");
return false;
}
m_shmm->SNumber[0] = 0; // initial to empty
if (n == 1 && checkIR() != EXIT_SUCCESS) {
m_Log->log(LogTrace::ERROR, "Check Hardware IR fails");
if (checkIR() != EXIT_SUCCESS) {
m_Log->log(LogTrace::ERROR, "Check Hardware IR fails");
if (checkIR() != EXIT_SUCCESS) {
m_Log->log(LogTrace::ERROR, "IR fatal failure");
return -1;
}
}
}
initBurn();
updtXorg();
updtXine();
setXwindow(true);
#ifdef USEDEBUG
dump();
#endif
return 0;
}
void WatchDog::start()
{
pthread_t myThread;
pthread_create( &myThread, NULL, invoke, (void*)this);
// check application periodically
m_Log->log(LogTrace::DEBUG,"check application periodically");
int count = m_shmm->BurnTimes;
while(m_continue) {
sleep(5);
if (m_burn) setBurn( ++count );
// Check APPs
}
if (m_burn) setBurn( ++count, true );
}
void WatchDog::loop()
{
// check system periodically
m_Log->log(LogTrace::DEBUG," check system periodically");
int count = 0;
while(m_continue) {
sleep(5);
count++;
if (!m_shmm->SNumber[0] && !(count%5)) // Do it each 5th time
if (!ckHW()) {
m_Log->log(LogTrace::ERROR," check hardware failed");
if (count > 15)
process(ShMemory::M_REST);
else if (count > 10)
callSys( "xwinfo \"The hardware checking failed;CYNALYNX can't perform correctly;If this is found again;the system will be shutdown soon\" 2");
}
else tellOther("aip", ShMemory::M_CONF);
sysCheck();
}
}
void WatchDog::setLED(int n)
{
enum { LED_OFF,
LED_GREEN,
LED_YELLOW,
LED_RED
};
int i = LED_OFF;
char cmd[40];
switch (m_shmm->State) {
case 0: // IDLE
i = LED_GREEN;
break;
case 1: // LOCAL
i = LED_YELLOW;
break;
case 6: // EXIT
break;
default: // CONNECT
i = LED_RED;
break;
}
sprintf(cmd, "setled %d", i);
system(cmd);
}
void WatchDog::setBurn(int n, bool last)
{
#define BURN_FILE "/etc/burn.tst"
FILE *fp = fopen(BURN_FILE, "w");
if (fp != NULL) {
fprintf(fp, "BurnTimes=%d\n", n);
fclose(fp);
m_shmm->BurnTimes = n;
if (last) system( "date >> /etc/burn.tst");
if (m_shmm->State == 0)
tellOther("bn", ShMemory::M_DEBG);
}
}
void WatchDog::initBurn()
{
m_shmm->BurnTimes = 0;
FILE *fp = fopen(BURN_FILE, "r");
if (fp != NULL) {
fscanf(fp, "BurnTimes=%d", &m_shmm->BurnTimes);
fclose(fp);
}
}
void WatchDog::sysCheck()
{
// Check USB
struct stat fstat;
if (stat("/dev/sda1", &fstat) < 0) {
if (m_mount & 1) usbMount(1, false);
}
else if ((m_mount & 1) == 0) usbMount(1, true);
if (stat("/dev/sdb1", &fstat) < 0) {
if (m_mount & 2) usbMount(2, false);
}
else if ((m_mount & 2) == 0) usbMount(2, true);
// Check Memory
}
void WatchDog::process(int n)
{
switch(n) {
case ShMemory::M_STAT:
m_shmm->State = m_shmm->Changes;
m_Log->log(LogTrace::DEBUG, "Process %d State = %d", n, m_shmm->State);
setLED(m_shmm->State);
break;
case ShMemory::M_AIP:
if (m_shmm->State == 0)
tellOther("bn", ShMemory::M_CONF);
break;
case ShMemory::M_VDS:
break;
case ShMemory::M_CONF:
m_Log->log(LogTrace::DEBUG, "Process %d Changes = %d", n, m_shmm->Changes);
// State::S_IDLE and BANNERSHOW changes
if (m_shmm->State == 0 && (m_shmm->Changes & 1))
tellOther("bn", ShMemory::M_CONF);
// AIPENABLED changes
if (m_shmm->Changes & 2)
tellOther("aip", ShMemory::M_CONF);
// XORG.CONF
if (m_shmm->Changes & 4)
updtXorg();
// XINE config
if (m_shmm->Changes & 8)
updtXine();
break;
case ShMemory::M_DEBG:
if (m_shmm->Changes & 1) m_burn = true;
if (m_shmm->Changes & 8) { // clean
m_Log->stopLog();
tellOther("aip", SIGUSR1);
tellOther("vds", SIGUSR1);
tellOther("w2", SIGUSR1);
system("rm -f /www/log/*");
}
if (m_shmm->Changes & 14) { // changes
setLog();
tellOther("aip", n);
tellOther("vds", n);
tellOther("w2", n);
}
break;
case ShMemory::M_REST:
if (m_shmm->Changes & 1) system("reset");
system("xwinfo \"System is shutting down...\" 1");
setLED(6);
system("ka 1"); // REBOOT
m_Log->log(LogTrace::DEBUG, "Process %d to Reboot system", n);
stop();
break;
case ShMemory::M_MISC:
break;
case ShMemory::M_WRLS:
m_Log->log(LogTrace::DEBUG, "process WPA setup");
// wpa auto setup
// system("startUp WPA UPDATE &");
break;
case ShMemory::M_LOG:
uploadIMG(); // process upload image
break;
case ShMemory::M_APPL:
m_Log->log(LogTrace::DEBUG, "process DHCP service setup");
// if (m_shmm->Changes == 0) setNetwork(true); // from xinit
dhcpSvr(); // update conf | up
// if (m_shmm->Changes == 0) setWiJET(true); // from xinit
break;
case ShMemory::M_STOP:
case ShMemory::M_TERM:
m_Log->log(LogTrace::DEBUG, "Process %d to Stop WatchDog\n", n);
stop();
default:
break;
}
m_shmm->Changes = 0;
}
|
772032e05a258d7144fec10ceb6364678abe5f85
|
9e679a417f0ebee7cb2c013aa6815d314dbcf530
|
/programs/sensor_sound/sensor_sound.ino
|
b570f25530ceee93ed43d56f78972d71ca1c767d
|
[] |
no_license
|
realgwyn/arduino
|
3ad9339e925cd9a439d93a3b6dd7cd516312a765
|
1dde3cdc33668a244997e489a76020e06a4fd3f8
|
refs/heads/master
| 2021-01-21T13:26:38.445288
| 2016-04-19T19:31:14
| 2016-04-19T19:31:14
| 49,122,268
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,255
|
ino
|
sensor_sound.ino
|
/*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.
Most Arduinos have an on-board LED you can control. On the Uno and
Leonardo, it is attached to digital pin 13. If you're unsure what
pin the on-board LED is connected to on your Arduino model, check
the documentation at http://www.arduino.cc
This example code is in the public domain.
modified 8 May 2014
by Scott Fitzgerald
*/
#define RELAY1 7
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin 13 as an output.
pinMode(13, OUTPUT);
pinMode(RELAY1, OUTPUT);
Serial.begin(9600);
digitalWrite(RELAY1,LOW);
delay(50);
digitalWrite(RELAY1,HIGH);
delay(50);
digitalWrite(RELAY1,LOW);
delay(300);
Serial.println("\n\nCalibrating Treshold...");
}
int sound;
int treshold = 802;
int filter = 2;
String msg = "";
double sum = 0;
double average = 0;
int count=0;
// the loop function runs over and over again forever
void loop() {
if(count < 1000){
sum += analogRead(5);
count++;
delay(1);
if(count==1000){
digitalWrite(RELAY1,HIGH);
Serial.println("Average: ");
average = sum / count;
Serial.println(average);
delay(100);
treshold = (int)average;
Serial.println("Treshold: ");
Serial.println(treshold);
digitalWrite(RELAY1, LOW);
delay(100);
Serial.println("Hi-Lo Pass Filter: ");
Serial.println(filter);
digitalWrite(RELAY1,HIGH);
delay(500);
}
}else{
sound = analogRead(5);
if(sound > treshold + filter || sound < treshold - filter){
Serial.println(sound);
digitalWrite(RELAY1,HIGH);
delay(50);
digitalWrite(RELAY1,LOW);
delay(20);
}
delay(1);
}
/*
if(sound < tresholdNegative || sound > tresholdPositive){
digitalWrite(RELAY1,LOW);
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
delay(100); // wait for a second
digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
digitalWrite(RELAY1,HIGH);
delay(30); // wait for a second
}else{
delay(100);
}
*/
}
|
8819deebe821e7ba019de307695a398a2ce3d67a
|
8832890474249f27a9a860f03217ecac3eac013e
|
/EP3/EixoEstatico.h
|
97deef64b5937938071c99f219c939a62cc9bdfd
|
[] |
no_license
|
doug-nicihoka/PCS3111-EP-Douglas-e-Andre
|
abeaa0b3f1d829e30f272fe5b66ce9455c991041
|
551cdf5d2fd676a3829eee5c9ed1ac3806e4d0f4
|
refs/heads/master
| 2021-08-19T22:36:47.585332
| 2017-11-27T16:29:14
| 2017-11-27T16:29:14
| null | 0
| 0
| null | null | null | null |
ISO-8859-1
|
C++
| false
| false
| 523
|
h
|
EixoEstatico.h
|
#ifndef EIXOESTATICO_H
#define EIXOESTATICO_H
#include "Eixo.h"
class EixoEstatico : public Eixo {
public:
/**
* Cria um EixoEstatico informando o título, o mínimo, o máximo e
* a orientação (true se for horizontal e false se for vertical).
* @throw runtime_error caso o minimo >= maximo.
*/
EixoEstatico(std::string titulo, double minimo, double maximo, bool orientacaoHorizontal);
virtual ~EixoEstatico();
};
#endif // EIXOESTATICO_H
|
4f0d17c6f5cde08a2f29177e66b7fb94a42ac5d0
|
7cadfb5dc49a7720a98cfca764aa163c41b20228
|
/include/RegisteredObject.h
|
166154c74e61a7e77a7471f12ec852fc0985c819
|
[] |
no_license
|
ricfehr3/glgameengine
|
18f12862a4cbc23ba447720404f5184a87461ca1
|
8ac290e15734db87f64d44dbdde95bb2aa943179
|
refs/heads/master
| 2020-12-29T11:38:52.856056
| 2019-08-15T20:44:28
| 2019-08-15T20:44:28
| 238,594,827
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 595
|
h
|
RegisteredObject.h
|
#ifndef REGISTEREDOBJECT_H
#define REGISTEREDOBJECT_H
#include <string>
#include <exception>
#include <Logger.h>
class nonameexception : public std::exception
{
virtual const char* what() const throw()
{
return "Derived RegisteredObject name is empty";
}
};
class RegisteredObject
{
public:
std::string getName()
{
if(m_name.empty())
{
GLOG_ERROR("Derived RegisteredObject has empty name");
throw nameex;
}
return m_name;
}
protected:
std::string m_name;
nonameexception nameex;
};
#endif
|
01ea2ddec1a1fe38b2e99229c1b2d74edfd35e72
|
018290c372092183346172599757ee187192e771
|
/libraries/SafetySam/SafetySam.h
|
c43dd7bdc2ef284a0a2b8f5f1051e64198ff4cc6
|
[] |
no_license
|
hugmehugyouorg/Hug-Community-Therapeutic-Companion
|
dfec028be783982cb98dfe0e0a3e72d56fc15dfe
|
7d13fe4a95cbc79d7eae481b17b0152044eca9db
|
refs/heads/master
| 2021-01-10T22:10:18.771566
| 2015-03-12T02:12:09
| 2015-03-12T02:12:09
| 14,120,759
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 998
|
h
|
SafetySam.h
|
#ifndef SAFETY_SAM_H
#define SAFETY_SAM_H
#include <Arduino.h>
#include "../SafetySamVoice/SafetySamVoice.h"
#include "../Emotion/Emotion.h"
#include "../PlayMessages/PlayMessages.h"
#include "../ServerProxy/ServerProxy.h"
#include "../Battery/Battery.h"
class SafetySam {
public:
SafetySam(SafetySamVoice *voice, Emotion *emotion, PlayMessages *playMessages, ServerProxy *proxy, Battery *battery, Stream *debug = NULL);
void begin();
void update();
boolean isProcessing();
//------------------------------------------------------------------------------
private:
boolean watchDawgBit();
SafetySamVoice *_voice;
Emotion *_emotion;
PlayMessages *_playMessages;
ServerProxy *_proxy;
Battery *_battery;
Stream *_debug;
boolean _readyToPlay;
//THE NUMBER OF BITS IN THE STATE
static const uint8_t STATE_BITS = 6;
//WATCHDAWG
static const unsigned long WATCHDAWG_SHOULD_BITE = 299000; //30000 = 30 seconds, 300000 = 5 minutes
};
#endif // SAFETY_SAM_H
|
a26e6d60ee27f9c9f9710540cfee0e4907dd3bcc
|
e4f8e759fc17876fa3f77f2055bc6b8bdf6df784
|
/web/speller/edit/test.cc
|
1bee9c181c16a8b68b808e57c8e87264cddc470f
|
[] |
no_license
|
amumu/nokuno
|
df46e164a557ef00a467df27f56fd91d43186bd7
|
419fe65421c894d2e7bb2f3fae4c83c1b92029d8
|
refs/heads/master
| 2016-09-06T05:39:49.437244
| 2011-09-15T08:59:54
| 2011-09-15T08:59:54
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 142
|
cc
|
test.cc
|
#include "edit.h"
#define LIMIT (100000)
int main() {
string line;
while (getline(cin, line)) {
run(line, LIMIT);
}
return 0;
}
|
2c5461268a96d73b84a10c325b66cc13a2c78667
|
49ceaa00d7ef126ca94aab0f6f667ae14f81ca1b
|
/src/EasyLog.cpp
|
5662f547fb312dbe71ab8257a50b463b3aa63574
|
[] |
no_license
|
garfieldhahu/EasyLog
|
0d78e0f8c6f091e2ec5c3e320df090682bbf2b96
|
11aee5a560e44940873ebaa2554e7f1ae565cb90
|
refs/heads/master
| 2021-07-23T03:57:43.824126
| 2018-10-20T06:37:39
| 2018-10-20T06:37:39
| 134,063,327
| 10
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,667
|
cpp
|
EasyLog.cpp
|
#include <stdarg.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include "EasyLog.h"
namespace easylog
{
LogLevel EasyLog::log_level_ = INFO;
pthread_mutex_t EasyLog::mutex_ = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t EasyLog::cond_ = PTHREAD_COND_INITIALIZER;
EasyLog* EasyLog::ins_ = NULL;
pthread_once_t EasyLog::once_ = PTHREAD_ONCE_INIT;
__thread pid_t EasyLog::tid_ = 0;
__thread char* EasyLog::str_ = NULL;
__thread time_t EasyLog::last_second_ = 0;
//char EasyLog::log_path_[kLogPathLenMax] = "/tmp/EasyLog";
//char EasyLog::log_name_[kLogNameLenMax];
char EasyLog::log_path_[512] = "/tmp/EasyLog";
char EasyLog::log_name_[128];
char EasyLog::log_full_name_[512];
int EasyLog::buf_num_ = kBufferNum;
int EasyLog::buf_size_ = kBufferLen;
void EasyLog::init()
{
head_ = new LogBuffer(buf_size_);
if(!head_)
{
fprintf(stderr, "no space to allocate LogBuffer\n");
exit(1);
}
LogBuffer* cur;
LogBuffer* pre = head_;
for(int i = 1; i < buf_num_; ++i)
{
cur = new LogBuffer(buf_size_);
if(!cur)
{
fprintf(stderr, "no space to allocate LogBuffer\n");
exit(1);
}
cur->set_pre(pre);
pre->set_next(cur);
pre = cur;
}
pre->set_next(head_);
head_->set_pre(pre);
tail_ = head_;
init_log_file();
if(signal(SIGSEGV, signal_exit))
{
fprintf(stderr, "redirect SIGSEGV signal failed\n");
exit(1);
}
}
void EasyLog::start()
{
if(pthread_create(&dump_thread_tid_, NULL, background_function, NULL))
{
fprintf(stderr, "EasyLog backgroud dmup thrad create failed\n");
exit(1);
}
running_ = true;
}
void EasyLog::dump_background()
{
while(running_)
{
pthread_mutex_lock(&mutex_);
if(tail_->is_empty(THIS_HOUR) && tail_->is_empty(NEXT_HOUR))
{
struct timespec abstime;
struct timeval now;
gettimeofday(&now, NULL);
abstime.tv_sec = now.tv_sec;
abstime.tv_nsec = now.tv_usec * 1000;//nanoseconds
abstime.tv_sec += kDumpLoopMaxTime;
pthread_cond_timedwait(&cond_, &mutex_, &abstime);
}
if(tail_->get_buffer_stat() == FREE)
{
//assert(tail_ == head_);
head_ = head_->get_next();
}
//pthread_mutex_unlock(&mutex_);
tail_->dump(log_fd_, THIS_HOUR);
if(unlikely(!tail_->is_empty(NEXT_HOUR)))
{
roll_log();
tail_->dump(log_fd_, NEXT_HOUR);
}
//pthread_mutex_lock(&mutex_);
tail_->clear();
tail_ = tail_->get_next();
pthread_mutex_unlock(&mutex_);
}
}
void EasyLog::stop()
{
running_ = false;
pthread_mutex_lock(&mutex_);
dump_all();
pthread_mutex_unlock(&mutex_);
pthread_join(dump_thread_tid_, NULL);
}
void EasyLog::roll_log()
{
struct timeval s_tv;
gettimeofday(&s_tv, NULL);
time_t second = s_tv.tv_sec;
struct tm s_tm;
localtime_r(&second, &s_tm);
log_roll_hour_ = s_tm.tm_hour;
char file_time[10];
sprintf(file_time, "%04d%02d%02d%02d", s_tm.tm_year + 1900, s_tm.tm_mon + 1, s_tm.tm_mday, s_tm.tm_hour);
memcpy(log_name_ + 3, file_time, 10);
close(log_fd_);
open_file();
}
void EasyLog::dump_tail()
{
tail_->dump(log_fd_, THIS_HOUR);
if(unlikely(!tail_->is_empty(NEXT_HOUR)))
{
roll_log();
tail_->dump(log_fd_, NEXT_HOUR);
tail_ = tail_->get_next();
}
}
void EasyLog::dump_all()
{
while(tail_ != head_)
dump_tail();
}
void EasyLog::open_file()
{
memset(log_full_name_, '\0', 512);
strncat(log_full_name_, log_path_, sizeof(log_full_name_));
strncat(log_full_name_, "/", sizeof(log_full_name_));
strncat(log_full_name_, log_name_, sizeof(log_full_name_));
log_fd_ = open(log_full_name_, O_CREAT | O_APPEND | O_RDWR, 0640);
if(-1 == log_fd_)
{
fprintf(stderr, "EasyLog open fail, file name: %s, error: %s\n", log_full_name_, strerror(errno));
exit(1);
}
}
void EasyLog::init_log_file()
{
mkdir(log_path_, 0777);
if(access(log_path_, F_OK | W_OK) == -1)
{
fprintf(stderr, "EasyLog ins create fail, log path: %s, error: %s\n", log_path_, strerror(errno));
exit(1);
}
struct timeval s_tv;
gettimeofday(&s_tv, NULL);
time_t second = s_tv.tv_sec;
struct tm s_tm;
localtime_r(&second, &s_tm);
log_roll_hour_ = s_tm.tm_hour;
char buf[kLogNameLenMax];
if(!strlen(log_name_))
{
int len = readlink("/proc/self/exe", buf, sizeof(buf));
buf[len] = '\0';
char* index = strrchr(buf, '/');
if(unlikely(NULL == index))
sprintf(log_name_, "log%04d%02d%02d%02d-%s.txt", s_tm.tm_year + 1900, s_tm.tm_mon + 1, s_tm.tm_mday, s_tm.tm_hour, buf);
else
sprintf(log_name_, "log%04d%02d%02d%02d-%s.txt", s_tm.tm_year + 1900, s_tm.tm_mon + 1, s_tm.tm_mday, s_tm.tm_hour, index + 1);
}
else
{
strncpy(buf, log_name_, kLogNameLenMax);
sprintf(log_name_, "log%04d%02d%02d%02d-%s.txt", s_tm.tm_year + 1900, s_tm.tm_mon + 1, s_tm.tm_mday, s_tm.tm_hour, buf);
}
open_file();
}
void EasyLog::dump_before_exit()
{
LOG_FATAL("program got SIGSEGV, will exit after log dump\n");
stop();
exit(1);
}
void EasyLog::log(LogLevel level,const char* file, const char* function, int line, const char* fmt, ...)
{
if(unlikely(0 == get_tid()))
init_tid();
if(unlikely(NULL == str_))
str_ = new char[kMessageMsgLenMax];
strncpy(str_, LevelMap[level], 6);
struct timeval s_tv;
gettimeofday(&s_tv, NULL);
time_t second = s_tv.tv_sec;
int usecond = s_tv.tv_usec;
struct tm s_tm;
if(likely(second == last_second_))
{
sprintf(str_ + 24, "%06d", usecond);
}
else
{
last_second_ = second;
localtime_r(&last_second_, &s_tm);
snprintf(str_ + 6, kTimeLen, kTimeFormat, s_tm.tm_year + 1900, s_tm.tm_mon + 1, s_tm.tm_mday, s_tm.tm_hour, s_tm.tm_min, s_tm.tm_sec, usecond);
}
int pre_len = sprintf(str_ + kHeadLen, " %ld %s:%s(%d) - ", get_tid(), file, function, line);
int base_len = kHeadLen + pre_len;
int remain_len = kMessageMsgLenMax - base_len;
va_list args;
va_start(args, fmt);
int body_len = vsnprintf(str_ + kHeadLen + pre_len, remain_len, fmt, args);
va_end(args);
// truncate if the single log is too long
if(remain_len == body_len)
str_[kMessageMsgLenMax - 1] = '\n';
int log_len = base_len + body_len;
bool raise_signal = false;
int buf_index = THIS_HOUR;
pthread_mutex_lock(&mutex_);
//if it comes into another hour ,roll the log
if(unlikely(s_tm.tm_hour != log_roll_hour_))
buf_index = NEXT_HOUR;
//head_ may not have enough space
if(unlikely(log_len > head_->avail_size(buf_index)))
{
raise_signal = true;
head_->set_buffer_stat(FULL);
if(unlikely(head_->get_next() == tail_))
{
LogBuffer* tmp = new LogBuffer(head_, tail_, buf_size_);
++buf_num_;
head_ = tmp;
LOG_WARN("EasyLog new another buffer, current buffer num:%d, total size:%ldMB\n", buf_num_, (kBufferLen >> 20) * buf_num_ * BUFFER_INDEX_NUM);
}
else
{
head_ = head_->get_next();
}
}
head_->append(str_, body_len + base_len, buf_index);
pthread_mutex_unlock(&mutex_);
if(raise_signal)
pthread_cond_signal(&cond_);
}
}// namespace easylog
|
28f89ca8befdf9593a360203dbdcd484a65ceefc
|
0290c8cb8b9eff9349dd07644c6d1a1fc4cec142
|
/C++ code/exp2/stdafx.h
|
4dcc6e6d14985fb554e0d18e740fddb394e7db15
|
[] |
no_license
|
ivanliu1989/Helping-Santas-Helpers
|
c03799023952651be0e950fe77c4a31cd4303215
|
4287946489d2faa7d44297f6169d312b9a548f01
|
refs/heads/master
| 2021-01-02T09:33:26.783676
| 2015-01-03T23:41:37
| 2015-01-03T23:41:37
| 27,221,218
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 680
|
h
|
stdafx.h
|
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
#include <time.h>
#include <string.h>
#include <iomanip>
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <queue>
#include <fstream>
#include <map>
using std::string;
using std::ifstream;
using std::stringstream;
using std::priority_queue;
using std::map;
using std::cin;
using std::cout;
using std::cerr;
using std::endl;
|
f3d0a710364b265a0c48b0108b580068b7b668ef
|
bfdde87839922ea0980365667f65fe3c0b75f566
|
/homework/Assignment 4/Gaddis_8ThEd_chap5_prob6/main.cpp
|
dd1003b33d6954ef5f45bba38604edba68340294
|
[] |
no_license
|
nick625/Gamez_nicolas_csc5-_42829
|
085af3603a55c29ad9b1fa30a19aae0c9eb67b71
|
d3dcbcd2672b839a991e13adb83aaa03711cd00b
|
refs/heads/master
| 2021-01-21T04:53:47.888787
| 2016-06-06T14:47:45
| 2016-06-06T14:47:45
| 52,460,969
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 809
|
cpp
|
main.cpp
|
/*
* File: main.cpp
* Author: nicolas gamez
* Created on April 1, 2016, 6:45 PM
*/
//system libraries
#include <iostream>
using namespace std;
//user libraries
//Global constants
//function prototypes
//execution begins here
int main(int argc, char** argv) {
float speed;//how fasted
int time;//time diver
float dis;//distance travel
while(speed<=0)
{
cout<<"how fast is the car going in mpg";
cin>>speed;
}
while(time<1)
{
cout<<"how long did the car dive for";
cin>>time;
}
cout<<"\nhour\tDistance Traveled\n";
cout<<"----------------------------\n";
for(int i=1;i<=time;i++)
{
dis=speed*i;
cout<<i<<"\t\t"<<dis<<endl;
}
return 0;
}
|
80f2570fb3d2ce391c37850464969ca0b81dd313
|
6667ed48d4de491fb7fd333daa262b73ab84d13e
|
/Array/22_Factorial_of_Large_Number.cpp
|
0f0cf8f2655b4eb668800b2c77e7a87fd8bcc351
|
[] |
no_license
|
DSA-Problems/Problem_Solving-1
|
7998cd14340360c78efed5c35f1532e744e35af0
|
0edbb7065b5fe36f7300ef5939192c2e1bd52bd3
|
refs/heads/main
| 2023-08-14T06:28:29.572766
| 2021-10-02T05:07:34
| 2021-10-02T05:07:34
| 412,695,882
| 1
| 0
| null | 2021-10-02T05:07:08
| 2021-10-02T05:07:07
| null |
UTF-8
|
C++
| false
| false
| 2,284
|
cpp
|
22_Factorial_of_Large_Number.cpp
|
#include<bits/stdc++.h>
using namespace std;
/*
|| Problem : Factorial Of large Number ||
factorial(n)
1) Create an array fac[]’ of MAX size where MAX is number of maximum digits in output.
2) Initialize value stored in ‘fac[]’ as 1 and initialize ‘fac_size’ (size of fac[]’) as 1.
3) Do following for all numbers from x = 2 to n.
a) Multiply x with fac[] and update fac[] and fac_size to store the multiplication result.
multiply(fac[], x)
1) Initialize carry as 0.
2) Do following for i = 0 to fac_size – 1
….a) Find value of fac[i] * x + carry. Let this value be prod.
….b) Update fac[i] by storing last digit of prod in it.
….c) Update carry by storing remaining digits in carry.
3) Put all digits of carry in fac[] and increase fac_size by number of digits in carry.
*/
//Function to multiply the number with every number
int Multiply(int n,int fac[],int fac_size)
{
int carry = 0; //Stor Carry
//Traverse and applying arithmetic Multiplication
for(int i = 0;i<fac_size;i++)
{
//temp --> sotre multiplication
int temp = n*fac[i]+carry;
//Update Array
fac[i] = temp%10;
//Carry
carry = temp/10;
}
//Storing carry to new block of array
while(carry)
{
fac[fac_size] = carry%10;
carry = carry/10;
fac_size++;
}
return fac_size;
}
//factorial
void Factorial(int n)
{
int fac[100000]; //store ans
//Factorial of 0 is = 1
fac[0] = 1;
int fac_size = 1; //size of factorial
//multiplying every number of factorial i.e = 5! = 5*4*3*2*1 = 120 a[2] = 1 ,a[1] = 2 , a[0] = 0
for(int i=2;i<=n;i++)
{
fac_size = Multiply(i,fac,fac_size);
}
//Print Output
cout<<"--> Factorial is : ";
for(int i = fac_size-1;i>=0;i--)
{
cout<<fac[i];
}
}
main()
{
int n;
cout<<"--> Enter the number : ";
cin>>n;
Factorial(n);
}
|
21d7446300f0c7ae2a9cf23c8dec481d757a69ad
|
f8f7fb205ffb21290f114f2b73a254cb6130c0e6
|
/Cliente.cpp
|
8a4a9bc7807b16226f51650a77d1581496c1ab70
|
[] |
no_license
|
Oswal-Fuentes/Oswal-Fuentes-Lab-9
|
fb0df288cb84a965cec027e4660c3ad7efb2ef86
|
6ce999d31b992b64ca988831484c864f47632b89
|
refs/heads/master
| 2021-04-15T09:43:23.409936
| 2017-06-17T00:07:34
| 2017-06-17T00:07:34
| 94,573,335
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 442
|
cpp
|
Cliente.cpp
|
#include "Cliente.h"
Cliente::Cliente(string username,string contrasena,string membresia){
this->username=username;
this->contrasena=contrasena;
this->membresia=membresia;
}
Cliente::Cliente(){
}
void Cliente::setMembresia(string membresia){
this-> membresia=membresia;
}
string Cliente::getMembresia(){
return membresia;
}
void Cliente::mostrar(){
cout<<"Cliente"<<endl;
Usuario::mostrar();
cout<<"Membresia: "<<membresia<<endl;
}
|
78817f8374e4b0c755dda2461578537e4fc973e4
|
5f5f02150cf6830ca4d0c6e2d4dd111e6baf9abe
|
/include/SearchAlgorithms.h
|
9c17b541995488c043f1d4e5df851dd04f6b943c
|
[] |
no_license
|
Italo-Vieira/ai-algorithms
|
9d5ec1f83683926e29c133727e007e1a12095ceb
|
baaeee35a740526db6e362a3c084a89930693018
|
refs/heads/master
| 2021-05-14T01:53:40.282806
| 2018-02-14T18:07:34
| 2018-02-14T18:07:34
| 116,579,975
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 415
|
h
|
SearchAlgorithms.h
|
#include <iostream>
#include "State.h"
#include "Path.h"
#define lesser(X,Y) (X>Y) ? Y : X
typedef list<State*>::iterator iterator;
class SearchAlgorithms{
public:
static Path* BFS(State*);
static Path* DFS(State*);
private:
/*
Remove from 'from' any state that is also present in 'in'
*/
static void removeEquals(list<State*> &from, list<State*> &in);
static void freeList(list<State*>&);
};
|
336b6dce52c65f115a641ef2b39245442fc4bc36
|
ffdc77394c5b5532b243cf3c33bd584cbdc65cb7
|
/mindspore/ccsrc/ps/core/communicator/tcp_client.cc
|
fa8367e5c78e4a3f49c44a693cba45ee79e1844a
|
[
"Apache-2.0",
"LicenseRef-scancode-proprietary-license",
"MPL-1.0",
"OpenSSL",
"LGPL-3.0-only",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause-Open-MPI",
"MIT",
"MPL-2.0-no-copyleft-exception",
"NTP",
"BSD-3-Clause",
"GPL-1.0-or-later",
"0BSD",
"MPL-2.0",
"LicenseRef-scancode-free-unknown",
"AGPL-3.0-only",
"Libpng",
"MPL-1.1",
"IJG",
"GPL-2.0-only",
"BSL-1.0",
"Zlib",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-python-cwi",
"BSD-2-Clause",
"LicenseRef-scancode-gary-s-brown",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"Python-2.0",
"LicenseRef-scancode-mit-nagy",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense"
] |
permissive
|
mindspore-ai/mindspore
|
ca7d5bb51a3451c2705ff2e583a740589d80393b
|
54acb15d435533c815ee1bd9f6dc0b56b4d4cf83
|
refs/heads/master
| 2023-07-29T09:17:11.051569
| 2023-07-17T13:14:15
| 2023-07-17T13:14:15
| 239,714,835
| 4,178
| 768
|
Apache-2.0
| 2023-07-26T22:31:11
| 2020-02-11T08:43:48
|
C++
|
UTF-8
|
C++
| false
| false
| 13,624
|
cc
|
tcp_client.cc
|
/**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* 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 "ps/core/communicator/tcp_client.h"
#include <arpa/inet.h>
#include <event2/buffer.h>
#include <event2/buffer_compat.h>
#include <event2/bufferevent.h>
#include <event2/event.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/socket.h>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
#include <utility>
namespace mindspore {
namespace ps {
namespace core {
event_base *TcpClient::event_base_ = nullptr;
std::mutex TcpClient::event_base_mutex_;
bool TcpClient::is_started_ = false;
TcpClient::TcpClient(const std::string &address, std::uint16_t port, NodeRole peer_role)
: event_timeout_(nullptr),
buffer_event_(nullptr),
server_address_(std::move(address)),
server_port_(port),
peer_role_(peer_role),
connection_status_(-1) {
message_handler_.SetCallback(
[this](const std::shared_ptr<MessageMeta> &meta, const Protos &protos, const void *data, size_t size) {
if (message_callback_) {
message_callback_(meta, protos, data, size);
}
});
}
TcpClient::~TcpClient() {
if (buffer_event_) {
bufferevent_free(buffer_event_);
buffer_event_ = nullptr;
}
if (event_timeout_) {
event_free(event_timeout_);
event_timeout_ = nullptr;
}
}
std::string TcpClient::GetServerAddress() const { return server_address_; }
void TcpClient::set_disconnected_callback(const OnDisconnected &disconnected) { disconnected_callback_ = disconnected; }
void TcpClient::set_connected_callback(const OnConnected &connected) { connected_callback_ = connected; }
std::string TcpClient::PeerRoleName() const {
switch (peer_role_) {
case SERVER:
return "Server";
case WORKER:
return "Worker";
case SCHEDULER:
return "Scheduler";
default:
return "RoleUndefined";
}
}
bool TcpClient::WaitConnected(const uint32_t &connected_timeout) {
std::unique_lock<std::mutex> lock(connection_mutex_);
bool res = connection_cond_.wait_for(lock, std::chrono::seconds(connected_timeout),
[this] { return this->connection_status_ == 1; });
return res;
}
void TcpClient::Init() {
std::lock_guard<std::mutex> lock(connection_mutex_);
if (connection_status_ != -1) {
return;
}
connection_status_ = 0;
if (buffer_event_) {
bufferevent_free(buffer_event_);
buffer_event_ = nullptr;
}
if (!CommUtil::CheckIp(server_address_)) {
MS_LOG(EXCEPTION) << "The tcp client ip:" << server_address_ << " is illegal!";
}
int result = evthread_use_pthreads();
if (result != 0) {
MS_LOG(EXCEPTION) << "Use event pthread failed!";
}
if (event_base_ == nullptr) {
event_base_ = event_base_new();
MS_EXCEPTION_IF_NULL(event_base_);
}
if (!PSContext::instance()->enable_ssl()) {
MS_LOG(INFO) << "SSL is disable.";
buffer_event_ = bufferevent_socket_new(event_base_, -1, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_THREADSAFE);
} else {
if (!EstablishSSL()) {
MS_LOG(WARNING) << "Establish SSL failed.";
return;
}
}
MS_EXCEPTION_IF_NULL(buffer_event_);
bufferevent_setcb(buffer_event_, ReadCallback, nullptr, EventCallback, this);
if (bufferevent_enable(buffer_event_, EV_READ | EV_WRITE) == -1) {
MS_LOG(EXCEPTION) << "Buffer event enable read and write failed!";
}
if (server_port_ > 0) {
sockaddr_in sin{};
if (memset_s(&sin, sizeof(sin), 0, sizeof(sin)) != EOK) {
MS_LOG(EXCEPTION) << "Initialize sockaddr_in failed!";
}
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = inet_addr(server_address_.c_str());
sin.sin_port = htons(server_port_);
int result_code = bufferevent_socket_connect(buffer_event_, reinterpret_cast<struct sockaddr *>(&sin), sizeof(sin));
if (result_code < 0) {
MS_LOG(WARNING) << "Connect server ip:" << server_address_ << " and port: " << server_port_ << " is failed!";
}
}
}
void TcpClient::StartWithDelay(int seconds) {
std::lock_guard<std::mutex> lock(connection_mutex_);
if (buffer_event_) {
return;
}
event_base_ = event_base_new();
MS_EXCEPTION_IF_NULL(event_base_);
timeval timeout_value{};
timeout_value.tv_sec = seconds;
timeout_value.tv_usec = 0;
event_timeout_ = evtimer_new(event_base_, TimeoutCallback, this);
MS_EXCEPTION_IF_NULL(event_timeout_);
if (evtimer_add(event_timeout_, &timeout_value) == -1) {
MS_LOG(EXCEPTION) << "Event timeout failed!";
}
}
void TcpClient::Stop() {
MS_EXCEPTION_IF_NULL(event_base_);
std::lock_guard<std::mutex> lock(connection_mutex_);
if (event_base_got_break(event_base_)) {
MS_LOG(DEBUG) << "The event base has already been stopped!";
return;
}
MS_LOG(INFO) << "Stop tcp client!";
int ret = event_base_loopbreak(event_base_);
if (ret != 0) {
MS_LOG(ERROR) << "Event base loop break failed!";
}
}
void TcpClient::SetTcpNoDelay(const evutil_socket_t &fd) {
const int one = 1;
int ret = setsockopt(fd, static_cast<int>(IPPROTO_TCP), static_cast<int>(TCP_NODELAY), &one, sizeof(int));
if (ret < 0) {
MS_LOG(EXCEPTION) << "Set socket no delay failed!";
}
}
void TcpClient::TimeoutCallback(evutil_socket_t, std::int16_t, void *const arg) {
try {
MS_EXCEPTION_IF_NULL(arg);
auto tcp_client = reinterpret_cast<TcpClient *>(arg);
tcp_client->Init();
} catch (const std::exception &e) {
MS_LOG(ERROR) << "Catch exception: " << e.what();
}
}
void TcpClient::ReadCallback(struct bufferevent *bev, void *const ctx) {
try {
MS_EXCEPTION_IF_NULL(ctx);
auto tcp_client = reinterpret_cast<TcpClient *>(ctx);
tcp_client->ReadCallbackInner(bev);
} catch (const std::exception &e) {
MS_LOG(ERROR) << "Catch exception: " << e.what();
}
}
void TcpClient::ReadCallbackInner(struct bufferevent *bev) {
MS_EXCEPTION_IF_NULL(bev);
char read_buffer[kMessageChunkLength];
size_t read = 0;
while ((read = bufferevent_read(bev, &read_buffer, sizeof(read_buffer))) > 0) {
OnReadHandler(read_buffer, read);
}
}
void TcpClient::OnReadHandler(const void *buf, size_t num) {
MS_EXCEPTION_IF_NULL(buf);
if (read_callback_) {
read_callback_(buf, num);
}
message_handler_.ReceiveMessage(buf, num);
}
void TcpClient::TimerCallback(evutil_socket_t, int16_t, void *arg) {
MS_EXCEPTION_IF_NULL(arg);
auto tcp_client = reinterpret_cast<TcpClient *>(arg);
if (tcp_client->on_timer_callback_) {
tcp_client->on_timer_callback_();
}
}
void TcpClient::NotifyConnected() {
MS_LOG(INFO) << "Client connected to the server! Peer " << PeerRoleName() << " ip: " << server_address_
<< ", port: " << server_port_;
connection_status_ = 1;
connection_cond_.notify_all();
}
bool TcpClient::EstablishSSL() {
MS_LOG(INFO) << "Enable ssl support.";
SSL *ssl = SSL_new(SSLClient::GetInstance().GetSSLCtx());
MS_ERROR_IF_NULL_W_RET_VAL(ssl, false);
MS_ERROR_IF_NULL_W_RET_VAL(event_base_, false);
buffer_event_ = bufferevent_openssl_socket_new(event_base_, -1, ssl, BUFFEREVENT_SSL_CONNECTING,
BEV_OPT_CLOSE_ON_FREE | BEV_OPT_THREADSAFE);
return true;
}
void TcpClient::EventCallback(struct bufferevent *bev, std::int16_t events, void *const ptr) {
try {
MS_EXCEPTION_IF_NULL(ptr);
auto tcp_client = reinterpret_cast<TcpClient *>(ptr);
tcp_client->EventCallbackInner(bev, events);
} catch (const std::exception &e) {
MS_LOG(ERROR) << "Catch exception: " << e.what();
}
}
void TcpClient::EventCallbackInner(struct bufferevent *bev, std::int16_t events) {
MS_EXCEPTION_IF_NULL(bev);
if (events & BEV_EVENT_CONNECTED) {
// Connected
if (connected_callback_) {
connected_callback_();
}
NotifyConnected();
evutil_socket_t fd = bufferevent_getfd(bev);
SetTcpNoDelay(fd);
MS_LOG(INFO) << "Client connected! Peer " << PeerRoleName() << " ip: " << server_address_
<< ", port: " << server_port_;
} else if (events & BEV_EVENT_ERROR) {
if (PSContext::instance()->enable_ssl()) {
uint64_t err = bufferevent_get_openssl_error(bev);
const uint64_t server_not_start_err = 5;
if (err != server_not_start_err) {
MS_LOG(WARNING) << "The error number is:" << err << ", error message:" << ERR_reason_error_string(err)
<< ", the error lib:" << ERR_lib_error_string(err)
<< ", the error func:" << ERR_func_error_string(err);
return;
}
}
connection_status_ = -1;
if (disconnected_callback_) {
MS_LOG(WARNING) << "The client will retry to connect to the server! Peer " << PeerRoleName()
<< " ip: " << server_address_ << ", port: " << server_port_;
disconnected_callback_();
}
} else if (events & BEV_EVENT_EOF) {
MS_LOG(WARNING) << "Client connected end of file! Peer " << PeerRoleName() << " ip: " << server_address_
<< ", port: " << server_port_;
connection_status_ = -1;
if (disconnected_callback_) {
disconnected_callback_();
}
}
}
void TcpClient::Start() {
event_base_mutex_.lock();
if (is_started_) {
event_base_mutex_.unlock();
return;
}
is_started_ = true;
event_base_mutex_.unlock();
MS_EXCEPTION_IF_NULL(event_base_);
int ret = event_base_dispatch(event_base_);
// is_started_ should be false when finish dispatch
is_started_ = false;
MSLOG_IF(MsLogLevel::kInfo, ret == 0, NoExceptionType) << "Event base dispatch success!";
MSLOG_IF(MsLogLevel::kError, ret == 1, NoExceptionType)
<< "Event base dispatch failed with no events pending or active!";
MSLOG_IF(MsLogLevel::kError, ret == -1, NoExceptionType) << "Event base dispatch failed with error occurred!";
MSLOG_IF(MsLogLevel::kException, ret < -1, AbortedError) << "Event base dispatch with unexpected error code!";
}
void TcpClient::StartWithNoBlock() {
std::lock_guard<std::mutex> lock(connection_mutex_);
MS_LOG(INFO) << "Start tcp client with no block!";
MS_EXCEPTION_IF_NULL(event_base_);
int ret = event_base_loop(event_base_, EVLOOP_NONBLOCK);
MSLOG_IF(MsLogLevel::kInfo, ret == 0, NoExceptionType) << "Event base loop success!";
MSLOG_IF(MsLogLevel::kError, ret == 1, NoExceptionType) << "Event base loop failed with no events pending or active!";
MSLOG_IF(MsLogLevel::kError, ret == -1, NoExceptionType) << "Event base loop failed with error occurred!";
MSLOG_IF(MsLogLevel::kException, ret < -1, AbortedError) << "Event base loop with unexpected error code!";
}
void TcpClient::SetMessageCallback(const OnMessage &cb) { message_callback_ = cb; }
bool TcpClient::SendMessage(const CommMessage &message) const {
MS_EXCEPTION_IF_NULL(buffer_event_);
bufferevent_lock(buffer_event_);
bool res = true;
size_t buf_size = message.ByteSizeLong();
uint32_t meta_size = SizeToUint(message.pb_meta().ByteSizeLong());
MessageHeader header;
header.message_proto_ = Protos::PROTOBUF;
header.message_length_ = buf_size;
header.message_meta_length_ = meta_size;
if (bufferevent_write(buffer_event_, &header, sizeof(header)) == -1) {
MS_LOG(ERROR) << "Event buffer add header failed!";
res = false;
}
if (bufferevent_write(buffer_event_, message.pb_meta().SerializeAsString().data(), meta_size) == -1) {
MS_LOG(ERROR) << "Event buffer add protobuf data failed!";
res = false;
}
if (bufferevent_write(buffer_event_, message.data().data(), message.data().length()) == -1) {
MS_LOG(ERROR) << "Event buffer add protobuf data failed!";
res = false;
}
bufferevent_unlock(buffer_event_);
return res;
}
bool TcpClient::SendMessage(const std::shared_ptr<MessageMeta> &meta, const Protos &protos, const void *data,
size_t size) {
MS_EXCEPTION_IF_NULL(buffer_event_);
MS_EXCEPTION_IF_NULL(meta);
MS_EXCEPTION_IF_NULL(data);
bufferevent_lock(buffer_event_);
bool res = true;
MessageHeader header;
header.message_proto_ = protos;
header.message_meta_length_ = SizeToUint(meta->ByteSizeLong());
header.message_length_ = size + header.message_meta_length_;
if (bufferevent_write(buffer_event_, &header, sizeof(header)) == -1) {
MS_LOG(ERROR) << "Event buffer add header failed!";
res = false;
}
if (bufferevent_write(buffer_event_, meta->SerializeAsString().data(), meta->ByteSizeLong()) == -1) {
MS_LOG(ERROR) << "Event buffer add protobuf data failed!";
res = false;
}
if (bufferevent_write(buffer_event_, data, size) == -1) {
MS_LOG(ERROR) << "Event buffer add protobuf data failed!";
res = false;
}
int result = bufferevent_flush(buffer_event_, EV_READ | EV_WRITE, BEV_FLUSH);
if (result < 0) {
MS_LOG(ERROR) << "Bufferevent flush failed!";
res = false;
}
bufferevent_unlock(buffer_event_);
return res;
}
void TcpClient::set_timer_callback(const OnTimer &timer) { on_timer_callback_ = timer; }
const event_base &TcpClient::eventbase() const { return *event_base_; }
} // namespace core
} // namespace ps
} // namespace mindspore
|
3641f69670a682edf35ee9b8cb51d68de82515f4
|
8c40662e9b551e04abffe7292ccf6e6a99f6d469
|
/Insurgency/GameEntityActions.h
|
bb508005161644e3c40f5476c5e6b15bbf46c1d9
|
[] |
no_license
|
elliothatch/Insurgency
|
62e9218532766fbd338c0f73cad76045db96f6cb
|
53835081a99a712250145799b367df444b596a43
|
refs/heads/master
| 2021-01-10T19:19:30.001474
| 2013-10-18T20:34:47
| 2013-10-18T20:34:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,141
|
h
|
GameEntityActions.h
|
#pragma once
#include <set>
#include <string>
struct EntityActionID
{
enum E
{
PickUp,
Drop,
Equip,
Unequip,
Count
};
};
class GameEntityActions
{
public:
GameEntityActions();
GameEntityActions(std::set<EntityActionID::E> inventoryActions, std::set<EntityActionID::E> equippedActions,
std::set<EntityActionID::E> worldActions);
~GameEntityActions();
static std::string getActionName(EntityActionID::E id);
static int getActionSelectionStep(EntityActionID::E id);
void setInventoryActions(std::set<EntityActionID::E> actions);
void setEquippedActions(std::set<EntityActionID::E> actions);
void setWorldActions(std::set<EntityActionID::E> actions);
void addInventoryAction(EntityActionID::E action);
void addEquippedAction(EntityActionID::E action);
void addWorldAction(EntityActionID::E action);
std::set<EntityActionID::E> getInventoryActions() const;
std::set<EntityActionID::E> getEquippedActions() const;
std::set<EntityActionID::E> getWorldActions() const;
private:
std::set<EntityActionID::E> m_actionsInv;
std::set<EntityActionID::E> m_actionsEquip;
std::set<EntityActionID::E> m_actionsWorld;
};
|
50e3f24a1652affd24f13800a3eb684e71806734
|
16e130599e881b7c1782ae822f3c52d88eac5892
|
/leetcode/singleElementInASortedArray/main.cpp
|
648aec4861b14b64424e74fcfe77032763daf666
|
[] |
no_license
|
knightzf/review
|
9b40221a908d8197a3288ba3774651aa31aef338
|
8c716b13b5bfba7eafc218f29e4f240700ae3707
|
refs/heads/master
| 2023-04-27T04:43:36.840289
| 2023-04-22T22:15:26
| 2023-04-22T22:15:26
| 10,069,788
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 810
|
cpp
|
main.cpp
|
#include "header.h"
class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
int n = nums.size();
int startIdx = 0;
int endIdx = n - 1;
while(startIdx != endIdx)
{
int midIdx = (startIdx + endIdx) / 2;
if(nums[midIdx] == nums[midIdx + 1])
{
++midIdx;
}
if((midIdx - startIdx + 1) % 2 == 0)
{
startIdx = midIdx + 1;
}
else
{
if(nums[midIdx] == nums[midIdx - 1])
endIdx = midIdx - 2;
else
return nums[midIdx];
}
}
return nums[startIdx];
}
};
int main()
{
Solution s;
}
|
5f2b154a4dce8da480138875cadc4e4366827ce7
|
d5a632c3abf23785f8d7de0b88abaac16d9b6861
|
/servant/servant/Message.h
|
80b81c7f7f01a5e59ba5dafbb38629d8f842bb31
|
[
"BSD-3-Clause"
] |
permissive
|
TarsCloud/TarsCpp
|
423c317307c8839ab5bc3903702733e7de58c91c
|
3ff6359173c087473032bff35ced648fbfaa0520
|
refs/heads/master
| 2023-09-04T11:34:16.804590
| 2023-09-02T14:24:32
| 2023-09-02T14:24:32
| 147,453,621
| 507
| 300
|
BSD-3-Clause
| 2023-08-25T02:35:58
| 2018-09-05T03:20:39
|
C++
|
UTF-8
|
C++
| false
| false
| 7,127
|
h
|
Message.h
|
/**
* Tencent is pleased to support the open source community by making Tars available.
*
* Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
#ifndef __TARS_MESSAGE_H_
#define __TARS_MESSAGE_H_
#include <util/tc_network_buffer.h>
#include "util/tc_autoptr.h"
#include "util/tc_monitor.h"
#include "util/tc_loop_queue.h"
#include "servant/Global.h"
namespace tars
{
/**
* 熔断保护, 超时一定比率后进行切换, 设置超时检查参数
* 计算到某台服务器的超时率, 如果连续超时次数或者超时比例超过阀值
* 1 默认5s内, 超时调用次数>=minTimeoutInvoke, 超时比率大于=radio
* 2 超时持续时间>=minFrequenceFailTime, 且 连续超时次数>=frequenceFailInvoke, 如果frequenceFailInvoke==1, 则马上屏蔽
* 则失效
* 服务失效后, 请求将尽可能的切换到其他可能的服务器, 并每隔tryTimeInterval尝试一次, 如果成功则认为恢复
* 如果其他服务器都失效, 则随机选择一台尝试
* 如果是灰度状态的服务, 服务失效后如果请求切换, 也只会转发到相同灰度状态的服务
* @uint16_t minTimeoutInvoke, 计算的最小的超时次数, 默认2次(在checkTimeoutInterval时间内超过了minTimeoutInvoke, 才计算超时)
* @uint32_t frequenceFailInvoke, 连续失败次数
* @uint32_t minFrequenceFailTime, 最小连续超时时间间隔
* @uint32_t checkTimeoutInterval, 统计时间间隔, (默认5s)
* @float radio, 超时比例 > 该值则认为超时了 ( 0.1<=radio<=1.0 )
* @uint32_t tryTimeInterval, 重试时间间隔
*/
struct CheckTimeoutInfo
{
/*
* 构造函数
*/
CheckTimeoutInfo()
: minTimeoutInvoke(2)
, checkTimeoutInterval(5)
, frequenceFailInvoke(3)
, minFrequenceFailTime(2)
, radio(0.3f)
, tryTimeInterval(10)
, maxConnectExc(1)
{
}
/*
* 判断超时屏蔽时,计算的最小的超时次数
*/
uint16_t minTimeoutInvoke;
/*
* 判断超时屏蔽时,时间间隔
*/
uint32_t checkTimeoutInterval;
/*
* 判断因连续失败而进行屏蔽时,连续失败的次数
*/
uint32_t frequenceFailInvoke;
/*
* 判断因连续失败而进行屏蔽时,最小的时间间隔
*/
uint32_t minFrequenceFailTime;
/*
* 超时的比率
*/
float radio;
/*
* 重试间隔
*/
uint32_t tryTimeInterval;
/*
* 最大连接异常次数
*/
uint32_t maxConnectExc;
};
#define IS_MSG_TYPE(m, t) ((m & t) != 0)
#define SET_MSG_TYPE(m, t) do { (m |= t); } while (0);
#define CLR_MSG_TYPE(m, t) do { (m &=~t); } while (0);
struct ThreadPrivateData
{
/**
* hash属性,客户端每次调用都进行设置
*/
bool _hash = false; //是否普通取模hash
bool _conHash = false; //是否一致性hash
int64_t _hashCode = -1; //hash值
/**
* 染色信息
*/
bool _dyeing = false; //标识当前线程是否需要染色
string _dyeingKey; //染色的key值
/**
* 允许客户端设置接口级别的超时时间,包括同步和异步、单向
*/
int _timeout = 0; //超时时间
/**
* 保存调用后端服务的地址信息
*/
string _szHost; //调用对端地址
/**
* cookie
*/
map<string, string> _cookie; // cookie内容
};
struct ReqMonitor;
struct ReqMessage : public TC_HandleBase
{
//调用类型
enum CallType
{
SYNC_CALL = 1, //同步
ASYNC_CALL, //异步
ONE_WAY, //单向
// THREAD_EXIT //线程退出的标识
};
//请求状态
enum ReqStatus
{
REQ_REQ = 0, //状态正常,正在请求中
REQ_RSP, //请求已经发出去
REQ_TIME, //请求超时
REQ_EXC //客户端请求异常
};
/*
* 构造函数
*/
ReqMessage()
: eStatus(ReqMessage::REQ_REQ)
, eType(SYNC_CALL)
, bFromRpc(false)
, callback(NULL)
, proxy(NULL)
, pObjectProxy(NULL)
, adapter(NULL)
, pMonitor(NULL)
, iBeginTime(TNOWMS)
, iEndTime(0)
, bPush(false)
, sched(NULL)
, iCoroId(0)
{
}
/*
* 析构函数
*/
~ReqMessage();
/*
* 初始化
*/
void init(CallType eCallType, ServantProxy *proxy);
ReqStatus eStatus; //调用的状态
CallType eType; //调用类型
bool bFromRpc = false; //是否是第三方协议的rcp_call,缺省为false
RequestPacket request; //请求消息体
shared_ptr<ResponsePacket> response; //响应消息体
shared_ptr<TC_NetWorkBuffer::Buffer> sReqData; //请求消息体
ServantProxyCallbackPtr callback; //异步调用时的回调对象
ServantProxy *proxy = NULL;
ObjectProxy *pObjectProxy = NULL; //调用端的proxy对象
AdapterProxy *adapter = NULL; //调用的adapter
ReqMonitor *pMonitor = NULL; //用于同步的monitor
int64_t iBeginTime = 0; //请求时间
int64_t iEndTime = 0; //完成时间
bool bPush = false; //push back 消息
bool bTraceCall; // 是否需要调用链追踪
string sTraceKey; // 调用链key
shared_ptr<TC_CoroutineScheduler> sched;
int iCoroId = 0;
std::function<void()> deconstructor; //析构时调用
ThreadPrivateData data; //线程数据
};
/**
* 用于同步调用时的条件变量
*/
struct ReqMonitor
{
ReqMessage *msg = NULL;
std::mutex mutex;
std::condition_variable cond;
bool bMonitorFin = false; //同步请求timewait是否结束
ReqMonitor(ReqMessage *m) : msg(m) {}
void wait();
void notify();
};
typedef TC_AutoPtr<ReqMessage> ReqMessagePtr;
typedef TC_LoopQueue<ReqMessage *> ReqInfoQueue;
////////////////////////////////////////////////////////////////////////////////////////////////////
}
#endif
|
7959606c2851bc399f5bb41759a3d2b511f40c0a
|
575731c1155e321e7b22d8373ad5876b292b0b2f
|
/examples/native/ios/Pods/boost-for-react-native/boost/fusion/container/list/detail/end_impl.hpp
|
4f77b9b9f087a07e17152639fde9249f8ff0269d
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] |
permissive
|
Nozbe/zacs
|
802a84ffd47413a1687a573edda519156ca317c7
|
c3d455426bc7dfb83e09fdf20781c2632a205c04
|
refs/heads/master
| 2023-06-12T20:53:31.482746
| 2023-06-07T07:06:49
| 2023-06-07T07:06:49
| 201,777,469
| 432
| 10
|
MIT
| 2023-01-24T13:29:34
| 2019-08-11T14:47:50
|
JavaScript
|
UTF-8
|
C++
| false
| false
| 1,448
|
hpp
|
end_impl.hpp
|
/*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
Copyright (c) 2005 Eric Niebler
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)
==============================================================================*/
#if !defined(FUSION_END_IMPL_07172005_0828)
#define FUSION_END_IMPL_07172005_0828
#include <boost/fusion/support/config.hpp>
#include <boost/mpl/if.hpp>
#include <boost/type_traits/is_const.hpp>
namespace boost { namespace fusion
{
struct nil_;
struct cons_tag;
template <typename Car, typename Cdr>
struct cons;
template <typename Cons>
struct cons_iterator;
namespace extension
{
template <typename Tag>
struct end_impl;
template <>
struct end_impl<cons_tag>
{
template <typename Sequence>
struct apply
{
typedef cons_iterator<
typename mpl::if_<is_const<Sequence>, nil_ const, nil_>::type>
type;
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static type
call(Sequence&)
{
return type();
}
};
};
}
}}
#endif
|
6e9c43a71d18d819455ceef54727a650c01e9984
|
0c27d8b8a9e3d10487fd7efba22db56859bc4233
|
/StarCore/src/ShaderIO.h
|
2f87b3e9114b47b3fdbbf63a895df3d7eede2b6a
|
[
"MIT"
] |
permissive
|
NBurley93/Prometheus3D
|
f2552b46605e0ca1f79c3861d69ddfd372ffa04f
|
b09736bae108d0d0104f5fb6a1560219063008c7
|
refs/heads/master
| 2021-06-18T10:50:07.665150
| 2017-05-24T07:11:54
| 2017-05-24T07:11:54
| 92,260,094
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 286
|
h
|
ShaderIO.h
|
#pragma once
//Loads a .shader into memory
#include <string>
#include <fstream>
#include <sstream>
class ShaderIO {
public:
static void LoadFile(const std::string& filePath, std::string& attributeData, std::string& vertexData, std::string& fragmentData, std::string& geometryData);
};
|
c274db7af484d3bb34b87baf74969e8c25ceb18c
|
18307e86c085a64e64fe0671edc1ab00ab9aa1be
|
/Engine/Plugins/UnrealCS/Source/MonoPlugin/Private/GeneratedScriptLibraries/SceneCapture_script.h
|
8b9d635ad41feffd936abf8ee993f7025997818f
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
rob-ack/UnrealCS
|
b6e9fe433ba1d04094a6baa3f75a365d0dcc749c
|
16d6f4989ef2f8622363009ebc6509b67c35a57e
|
refs/heads/master
| 2021-08-04T13:50:00.090129
| 2017-09-06T20:58:36
| 2017-09-06T20:58:36
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 291
|
h
|
SceneCapture_script.h
|
//GENERATED: C++ Code
#pragma once
class ASceneCapture_
{
static UClass* _StaticClassForProxy(){return ASceneCapture::StaticClass();}
public:
static void BindFunctions()
{
mono_add_internal_call("UnrealEngine.ASceneCapture::StaticClass",(const void*)_StaticClassForProxy);
}
}
;
|
4825659b855138fcfc062620db8ce035896b6905
|
7283ed93ab16726879969eaa629f80456c00bc64
|
/src/staff.cpp
|
849f128a6e43bb68915be952a2742e2db4b31097
|
[] |
no_license
|
takayuki0528/LammpsAnalysis-cpp
|
8b8e4233e00e0b81ad62b56f1654e8fc74c5a53f
|
e19fd6c69ca339525903e5495440b52ff5e09e15
|
refs/heads/master
| 2021-01-23T08:09:33.679747
| 2017-04-09T06:16:44
| 2017-04-09T06:16:44
| 80,526,294
| 0
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,817
|
cpp
|
staff.cpp
|
/* -----------------------------------------------------------------------------
Program Name: staff.cpp
Author: Takayuki Kobayashi
Date: Dec 31, 2016
Modified Date: --- by ***
Purpose: Property Calculation
----------------------------------------------------------------------------- */
#include "utility.h"
#include "chef.h"
#include "staff.h"
#include "prop_integer.h"
#include "prop_double.h"
#include "prop_InertiaMoment.h"
#include "prop_GyrationRadius.h"
#include "prop_Orientation.h"
#include "prop_SystemDrift.h"
// include header of your property
using namespace Bistro_NS;
Staff::Staff(Bistro *bstr) : Pointers(bstr) {
// 解析に必要なプロパティを取得
property_requests = chef->get_property_requests();
// ディレクトリが指定されていればファイルからプロパティを読み込む
if (!(bstr->propdir).empty()) {
intgr = new Prop_Integer(bstr);
dble = new Prop_Double(bstr);
}
// プロパティ計算用のインスタンス生成:他のプロパティに依存するプロパティは依存先のプロパティよりも「先」に書くこと
// if (find_str(chef->property_requests,"YourProperty")) {
// yourproperty = new YourProperty(bstr);
// }
if (find_str(property_requests,"Orientation")) {
orientation = new Prop_Orientation(bstr);
add_property_request(orientation);
}
if (find_str(property_requests,"GyrationRadius")) {
gyrationR = new Prop_GyrationRadius(bstr);
add_property_request(gyrationR);
}
if (find_str(property_requests,"InertiaMoment")) {
inertiaM = new Prop_InertiaMoment(bstr);
add_property_request(inertiaM);
}
if (find_str(property_requests,"SystemDrift")) {
systemD = new Prop_SystemDrift(bstr);
add_property_request(systemD);
}
std::cout << "List of Property to be Calculated:";
for (std::string str : property_requests) { std::cout << " " << str; }
std::cout << std::endl;
}
void Staff::precook(Ingredient *ingr) {
if (!(bstr->propdir).empty()) {
intgr->calculate_property(ingr);
dble->calculate_property(ingr);
}
// プロパティ計算:他のプロパティに依存するプロパティは依存先のプロパティよりも「後」に書くこと
// if (find_str(chef->property_requests,"YourProperty")) {
// yourproperty->calculate_prop(ingr);
// }
if (find_str(property_requests,"SystemDrift")) {
systemD->calculate_property(ingr);
}
if (find_str(property_requests,"InertiaMoment")) {
inertiaM->calculate_property(ingr);
}
if (find_str(property_requests,"GyrationRadius")) {
gyrationR->calculate_property(ingr);
}
if (find_str(property_requests,"Orientation")) {
orientation->calculate_property(ingr);
}
}
Staff::~Staff() { std::cout << "<Staff> Goodbye!\n"; }
|
2187d2309be10362b543957ac8a6806de961a33a
|
2745b47783cd1b4ce249e1f14f5c5d43ed3df5db
|
/memory/main.cpp
|
c5937a3e178ad338fd950bf7e1e1e104d65f6075
|
[] |
no_license
|
Aaronlanni/OpSystem
|
7fafccda13a9c19a6ffd640703e832489b134d97
|
e20d1cc52726d6b3f6bfb1beaa0c9ad4c3f68558
|
refs/heads/master
| 2020-03-19T06:14:54.689977
| 2018-08-11T13:19:19
| 2018-08-11T13:19:19
| 136,003,648
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 219
|
cpp
|
main.cpp
|
#define _CRT_SECURE_NO_WARNINGS 1
#include"memory.h"
#include<Windows.h>
void test()
{
int* a = new int[8];
double* b = new double;
delete a;
delete b;
}
int main()
{
test();
//system("pause");
return 0;
}
|
cc595405c7d831c66bf69ac4a45ee7cbe5c62226
|
71e3cab41d04c9e4dbc25a29cd8d3322d4b17e49
|
/XenonNui/Common/AtgSessionManager.cpp
|
548d9806e7292bb0d615b1e34a938e2d39d982b7
|
[] |
no_license
|
0xdeafcafe/Yrs2013
|
2ba9d5c4476cfe7a0bf76ade5d972c0b78f02872
|
e6cd93e6cbb20b61e112a1f77cc875f746c0bc6f
|
refs/heads/master
| 2020-04-30T05:16:46.253175
| 2013-08-10T09:14:42
| 2013-08-10T09:14:42
| 11,894,832
| 2
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 64,157
|
cpp
|
AtgSessionManager.cpp
|
#include "stdafx.h"
#include "AtgUtil.h"
#include "AtgSessionManager.h"
#define DebugSpew ATG::DebugSpew
#define FatalError ATG::FatalError
#define XNKIDToInt64 ATG::XNKIDToInt64
//------------------------------------------------------------------------
// Name: SessionManager()
// Desc: Public constructor
//------------------------------------------------------------------------
SessionManager::SessionManager()
{
Reset();
}
//------------------------------------------------------------------------
// Name: Reset()
// Desc: Resets this SessionManager instance to its creation state
//------------------------------------------------------------------------
VOID SessionManager::Reset()
{
m_bIsInitialized = FALSE;
m_SessionCreationReason = SessionCreationReasonNone;
m_dwSessionFlags = 0;
m_dwOwnerController = XUSER_MAX_COUNT + 1;
m_xuidOwner = INVALID_XUID;
m_SessionState = SessionStateNone;
m_migratedSessionState = SessionStateNone;
m_bIsMigratedSessionHost = FALSE;
m_hSession = INVALID_HANDLE_VALUE;
m_qwSessionNonce = 0;
m_strSessionError = NULL;
m_bUsingQoS = FALSE;
m_pRegistrationResults = NULL;
ZeroMemory( &m_SessionInfo, sizeof( XSESSION_INFO ) );
ZeroMemory( &m_NewSessionInfo, sizeof( XSESSION_INFO ) );
ZeroMemory( &m_migratedSessionID, sizeof( XNKID ) );
}
//------------------------------------------------------------------------
// Name: ~SessionManager()
// Desc: Public destructor
//------------------------------------------------------------------------
SessionManager::~SessionManager()
{
// Close our XSession handle to clean up resources held by it
if( m_hSession != INVALID_HANDLE_VALUE &&
m_hSession != NULL )
{
XCloseHandle( m_hSession );
}
}
//------------------------------------------------------------------------
// Name: Initialize()
// Desc: Initializes this SessionManager instance
//------------------------------------------------------------------------
BOOL SessionManager::Initialize( SessionManagerInitParams initParams )
{
if( m_bIsInitialized )
{
DebugSpew( "SessionManager already initialized. Reinitializing..\n" );
}
m_SessionCreationReason = initParams.m_SessionCreationReason;
m_dwSessionFlags = initParams.m_dwSessionFlags;
m_bIsHost = initParams.m_bIsHost;
m_Slots[SLOTS_TOTALPUBLIC] = initParams.m_dwMaxPublicSlots;
m_Slots[SLOTS_TOTALPRIVATE] = initParams.m_dwMaxPrivateSlots;
m_Slots[SLOTS_FILLEDPUBLIC] = 0;
m_Slots[SLOTS_FILLEDPRIVATE] = 0;
m_Slots[SLOTS_ZOMBIEPUBLIC] = 0;
m_Slots[SLOTS_ZOMBIEPRIVATE] = 0;
m_bIsInitialized = TRUE;
return TRUE;
}
//------------------------------------------------------------------------
// Name: IsInitialized()
// Desc: Queries SessionManager initialization state
//------------------------------------------------------------------------
BOOL SessionManager::IsInitialized()
{
return m_bIsInitialized;
}
//------------------------------------------------------------------------
// Name: IsSessionDeleted()
// Desc: Returns TRUE if the XSession for this instance
// has a 0 sessionID; otherwise false
//------------------------------------------------------------------------
BOOL SessionManager::IsSessionDeleted( VOID ) const
{
static const XNKID zero = {0};
if( m_SessionState == SessionStateDeleted )
{
return TRUE;
}
BOOL bIsSessionDeleted = FALSE;
if( m_hSession == INVALID_HANDLE_VALUE || m_hSession == NULL )
{
// If the session hasn't been created yet, return false
if ( m_SessionState < SessionStateCreated )
{
bIsSessionDeleted = FALSE;
}
else
{
bIsSessionDeleted = TRUE;
}
return bIsSessionDeleted;
}
// Call XSessionGetDetails first time to get back the size
// of the results buffer we need
DWORD cbResults = 0;
DWORD ret = XSessionGetDetails( m_hSession,
&cbResults,
NULL,
NULL );
if( ( ret != ERROR_INSUFFICIENT_BUFFER ) || ( cbResults == 0 ) )
{
DebugSpew( "SessionManager::IsSessionDeleted - Failed on first call to XSessionGetDetails, hr=0x%08x\n", ret );
return FALSE;
}
XSESSION_LOCAL_DETAILS* pSessionDetails = (XSESSION_LOCAL_DETAILS*)new BYTE[ cbResults ];
if( pSessionDetails == NULL )
{
FatalError( "SessionManager::IsSessionDeleted - Failed to allocate buffer.\n" );
}
// Call second time to fill our results buffer
ret = XSessionGetDetails( m_hSession,
&cbResults,
pSessionDetails,
NULL );
if( ret != ERROR_SUCCESS )
{
DebugSpew( "SessionManager::IsSessionDeleted - XSessionGetDetails failed with error %d\n", ret );
return FALSE;
}
// Iterate through the returned results
const XNKID sessionID = pSessionDetails->sessionInfo.sessionID;
if ( !memcmp( &sessionID, &zero, sizeof( sessionID ) ) )
{
bIsSessionDeleted = TRUE;
}
if ( pSessionDetails )
{
delete [] pSessionDetails;
}
return bIsSessionDeleted;
}
//------------------------------------------------------------------------
// Name: IsPlayerInSession()
// Desc: Uses XSessionGetDetails API to determine if a player is in the session
//------------------------------------------------------------------------
BOOL SessionManager::IsPlayerInSession( const XUID xuidPlayer, const DWORD dwUserIndex ) const
{
if( m_hSession == INVALID_HANDLE_VALUE || m_hSession == NULL )
{
DebugSpew( "SessionManager::IsPlayerInSession - Session handle invalid. Perhaps session has been deleted?\n" );
return FALSE;
}
// Call XSessionGetDetails first time to get back the size
// of the results buffer we need
DWORD cbResults = 0;
DWORD ret = XSessionGetDetails( m_hSession,
&cbResults,
NULL,
NULL );
if( ( ret != ERROR_INSUFFICIENT_BUFFER ) || ( cbResults == 0 ) )
{
DebugSpew( "SessionManager::IsPlayerInSession - Failed on first call to XSessionGetDetails, hr=0x%08x\n", ret );
return FALSE;
}
// Increase our buffer size to include an estimate of the maximum number
// of players allowed in the session
const DWORD dwMaxMembers = m_Slots[SLOTS_TOTALPUBLIC] + m_Slots[SLOTS_TOTALPRIVATE];
cbResults += dwMaxMembers * sizeof(XSESSION_MEMBER);
XSESSION_LOCAL_DETAILS* pSessionDetails = (XSESSION_LOCAL_DETAILS*)new BYTE[ cbResults ];
if( pSessionDetails == NULL )
{
FatalError( "SessionManager::IsPlayerInSession - Failed to allocate buffer.\n" );
}
// Call second time to fill our results buffer
ret = XSessionGetDetails( m_hSession,
&cbResults,
pSessionDetails,
NULL );
if( ret != ERROR_SUCCESS )
{
DebugSpew( "SessionManager::IsPlayerInSession - XSessionGetDetails failed with error %d\n", ret );
return FALSE;
}
const BOOL bIsValidUserIndex = ( dwUserIndex < XUSER_MAX_COUNT );
BOOL bIsInSession = FALSE;
for ( DWORD i = 0; i < pSessionDetails->dwReturnedMemberCount; ++i )
{
if( ( bIsValidUserIndex && ( pSessionDetails->pSessionMembers[i].dwUserIndex == dwUserIndex ) ) ||
( xuidPlayer == pSessionDetails->pSessionMembers[i].xuidOnline ) )
{
bIsInSession = TRUE;
break;
}
}
if ( pSessionDetails )
{
delete [] pSessionDetails;
}
return bIsInSession;
}
//------------------------------------------------------------------------
// Name: DebugDumpSessionDetails()
// Desc: Dumps session deletes
//------------------------------------------------------------------------
VOID SessionManager::DebugDumpSessionDetails() const
{
#ifdef _DEBUG
if( m_hSession == INVALID_HANDLE_VALUE || m_hSession == NULL )
{
DebugSpew( "SessionManager::DebugDumpSessionDetails - Session handle invalid. Perhaps session has been deleted?\n" );
return;
}
// Call XSessionGetDetails first time to get back the size
// of the results buffer we need
DWORD cbResults = 0;
DWORD ret = XSessionGetDetails( m_hSession,
&cbResults,
NULL,
NULL );
if( ( ret != ERROR_INSUFFICIENT_BUFFER ) || ( cbResults == 0 ) )
{
DebugSpew( "SessionManager::DebugDumpSessionDetails - Failed on first call to XSessionGetDetails, hr=0x%08x\n", ret );
return;
}
// Increase our buffer size to include an estimate of the maximum number
// of players allowed in the session
const DWORD dwMaxMembers = m_Slots[SLOTS_TOTALPUBLIC] + m_Slots[SLOTS_TOTALPRIVATE];
cbResults += dwMaxMembers * sizeof(XSESSION_MEMBER);
XSESSION_LOCAL_DETAILS* pSessionDetails = (XSESSION_LOCAL_DETAILS*)new BYTE[ cbResults ];
if( pSessionDetails == NULL )
{
FatalError( "SessionManager::DebugDumpSessionDetails - Failed to allocate buffer.\n" );
}
// Call second time to fill our results buffer
ret = XSessionGetDetails( m_hSession,
&cbResults,
pSessionDetails,
NULL );
if( ret != ERROR_SUCCESS )
{
DebugSpew( "SessionManager::DebugDumpSessionDetails - XSessionGetDetails failed with error %d\n", ret );
return;
}
// Iterate through the returned results
DebugSpew( "***************** DebugDumpSessionDetails *****************\n" \
"instance: %p\n" \
"sessionID: %016I64X\n" \
"Matchmaking session?: %s\n" \
"m_hSession: %p\n" \
"bIsHost: %d\n" \
"sessionstate: %s\n" \
"qwSessionNonce: %I64u\n" \
"dwUserIndexHost: %d\n" \
"dwGameType: %d\n" \
"dwGameMode: %d\n" \
"dwFlags: 0x%x\n" \
"dwMaxPublicSlots: %d\n" \
"dwMaxPrivateSlots: %d\n" \
"dwAvailablePublicSlots: %d\n" \
"dwAvailablePrivateSlots: %d\n" \
"dwActualMemberCount: %d\n" \
"dwReturnedMemberCount: %d\n" \
"xnkidArbitration: %016I64X\n",
this,
GetSessionIDAsInt(),
( HasSessionFlags( XSESSION_CREATE_USES_MATCHMAKING ) ) ? "Yes" : "No",
m_hSession,
m_bIsHost,
g_astrSessionState[m_SessionState],
m_qwSessionNonce,
pSessionDetails->dwUserIndexHost,
pSessionDetails->dwGameType,
pSessionDetails->dwGameMode,
pSessionDetails->dwFlags,
pSessionDetails->dwMaxPublicSlots,
pSessionDetails->dwMaxPrivateSlots,
pSessionDetails->dwAvailablePublicSlots,
pSessionDetails->dwAvailablePrivateSlots,
pSessionDetails->dwActualMemberCount,
pSessionDetails->dwReturnedMemberCount,
XNKIDToInt64( pSessionDetails->xnkidArbitration ) );
for ( DWORD i = 0; i < pSessionDetails->dwReturnedMemberCount; ++i )
{
DebugSpew( "***************** XSESSION_MEMBER %d *****************\n" \
"Online XUID: 0x%016I64X\n" \
"dwUserIndex: %d\n" \
"dwFlags: 0x%x\n",
i,
pSessionDetails->pSessionMembers[i].xuidOnline,
pSessionDetails->pSessionMembers[i].dwUserIndex,
pSessionDetails->pSessionMembers[i].dwFlags );
}
if ( pSessionDetails )
{
delete [] pSessionDetails;
}
#endif
}
//------------------------------------------------------------------------
// Name: DebugValidateExpectedSlotCounts()
// Desc: Makes sure slot counts are consistent with what is stored with
// the XSession
//------------------------------------------------------------------------
BOOL SessionManager::DebugValidateExpectedSlotCounts( const BOOL bBreakOnDifferent ) const
{
BOOL bSlotCountsDiffer = FALSE;
assert (m_SessionState < SessionStateCount);
#ifdef _DEBUG
if( m_hSession == INVALID_HANDLE_VALUE || m_hSession == NULL )
{
DebugSpew( "SessionManager::DebugValidateExpectedSlotCounts - Session handle invalid. Perhaps session has been deleted?\n" );
return !bSlotCountsDiffer;
}
// Call XSessionGetDetails first time to get back the size
// of the results buffer we need
DWORD cbResults = 0;
DWORD ret = XSessionGetDetails( m_hSession,
&cbResults,
NULL,
NULL );
if( ( ret != ERROR_INSUFFICIENT_BUFFER ) || ( cbResults == 0 ) )
{
DebugSpew( "SessionManager::DebugValidateExpectedSlotCounts - Failed on first call to XSessionGetDetails, hr=0x%08x\n", ret );
return FALSE;
}
XSESSION_LOCAL_DETAILS* pSessionDetails = (XSESSION_LOCAL_DETAILS*)new BYTE[ cbResults ];
if( pSessionDetails == NULL )
{
FatalError( "SessionManager::DebugValidateExpectedSlotCounts - Failed to allocate buffer.\n" );
}
// Call second time to fill our results buffer
ret = XSessionGetDetails( m_hSession,
&cbResults,
pSessionDetails,
NULL );
if( ret != ERROR_SUCCESS )
{
DebugSpew( "SessionManager::DebugValidateExpectedSlotCounts - XSessionGetDetails failed with error %d\n", ret );
return FALSE;
}
const XNKID sessionID = pSessionDetails->sessionInfo.sessionID;
const DWORD dwMaxPublicSlots = m_Slots[SLOTS_TOTALPUBLIC];
const DWORD dwMaxPrivateSlots = m_Slots[SLOTS_TOTALPRIVATE];
const DWORD dwAvailablePublicSlots = m_Slots[SLOTS_TOTALPUBLIC] - m_Slots[SLOTS_FILLEDPUBLIC];
const DWORD dwAvailablePrivateSlots = m_Slots[SLOTS_TOTALPRIVATE] - m_Slots[SLOTS_FILLEDPRIVATE];
bSlotCountsDiffer = ( pSessionDetails->dwMaxPublicSlots != dwMaxPublicSlots ||
pSessionDetails->dwMaxPrivateSlots != dwMaxPrivateSlots );
// XSessionGetDetails only returns dwAvailablePublicSlots and dwAvailablePrivateSlots data
// for:
// 1. matchmaking sessions,
// 2. sessions that are joinable during gameplay,
// 3. sessions that aren't deleted
//
// Therefore it only makes sense to compare against are expected slot counts if all of
// these conditions are met
const BOOL bIsMatchmakingSession = HasSessionFlags( XSESSION_CREATE_USES_MATCHMAKING );
const BOOL bJoinable = !HasSessionFlags( XSESSION_CREATE_USES_ARBITRATION ) &&
!HasSessionFlags( XSESSION_CREATE_JOIN_IN_PROGRESS_DISABLED );
if( bIsMatchmakingSession &&
( m_SessionState != SessionStateDeleted ) &&
( ( m_SessionState != SessionStateInGame ) || ( ( m_SessionState == SessionStateInGame ) && bJoinable ) ) )
{
bSlotCountsDiffer |= ( pSessionDetails->dwAvailablePublicSlots != dwAvailablePublicSlots ||
pSessionDetails->dwAvailablePrivateSlots != dwAvailablePrivateSlots );
}
// Any differences detected?
if( !bSlotCountsDiffer )
{
goto Terminate;
}
// Spew expected/actual slot counts
DebugSpew( "***************** DebugValidateExpectedSlotCounts *****************\n" \
"instance: %p\n" \
"sessionID: %016I64X\n" \
"m_hSession: %p\n" \
"bIsHost: %d\n" \
"sessionstate: %s\n" \
"dwMaxPublicSlots expected: %d; actual: %d\n" \
"dwMaxPrivateSlots expected: %d; actual: %d\n",
this,
XNKIDToInt64( sessionID ),
m_hSession,
m_bIsHost,
g_astrSessionState[m_SessionState],
dwMaxPublicSlots, pSessionDetails->dwMaxPublicSlots,
dwMaxPrivateSlots, pSessionDetails->dwMaxPrivateSlots );
if( HasSessionFlags( XSESSION_CREATE_USES_MATCHMAKING ) )
{
DebugSpew( "dwAvailablePublicSlots expected: %d; actual: %d\n" \
"dwAvailablePrivateSlots expected: %d; actual: %d\n",
dwAvailablePublicSlots, pSessionDetails->dwAvailablePublicSlots,
dwAvailablePrivateSlots, pSessionDetails->dwAvailablePrivateSlots );
}
if( bBreakOnDifferent & bSlotCountsDiffer )
{
DebugBreak();
}
Terminate:
if ( pSessionDetails )
{
delete [] pSessionDetails;
}
#endif
return !bSlotCountsDiffer;
}
//------------------------------------------------------------------------
// Name: GetSessionCreationReason()
// Desc: Retrieves session creation reason
//------------------------------------------------------------------------
SessionCreationReason SessionManager::GetSessionCreationReason( VOID ) const
{
return m_SessionCreationReason;
}
//------------------------------------------------------------------------
// Name: GetSessionState()
// Desc: Retrieves current session state
//------------------------------------------------------------------------
SessionState SessionManager::GetSessionState( VOID ) const
{
return m_SessionState;
}
//------------------------------------------------------------------------
// Name: GetSessionStateString()
// Desc: Retrieves current session state
//------------------------------------------------------------------------
const char* SessionManager::GetSessionStateString( VOID ) const
{
return g_astrSessionState[m_SessionState];
}
//------------------------------------------------------------------------
// Name: SetSessionOwner()
// Desc: Sets current session owner
//------------------------------------------------------------------------
VOID SessionManager::SetSessionOwner( const DWORD dwOwnerController )
{
m_dwOwnerController = dwOwnerController;
XUserGetXUID( m_dwOwnerController, &m_xuidOwner );
}
//------------------------------------------------------------------------
// Name: GetSessionOwner()
// Desc: Retrieves current session owner
//------------------------------------------------------------------------
DWORD SessionManager::GetSessionOwner( VOID ) const
{
return m_dwOwnerController;
}
//------------------------------------------------------------------------
// Name: GetSessionOwner()
// Desc: Retrieves current session owner XUID
//------------------------------------------------------------------------
XUID SessionManager::GetSessionOwnerXuid( VOID ) const
{
return m_xuidOwner;
}
//------------------------------------------------------------------------
// Name: IsSessionOwner()
// Desc: Retrieves current session owner
//------------------------------------------------------------------------
BOOL SessionManager::IsSessionOwner( const DWORD dwController ) const
{
return ( dwController == m_dwOwnerController );
}
//------------------------------------------------------------------------
// Name: IsSessionOwner()
// Desc: Retrieves current session owner
//------------------------------------------------------------------------
BOOL SessionManager::IsSessionOwner( const XUID xuidOwner ) const
{
return ( xuidOwner == m_xuidOwner );
}
//------------------------------------------------------------------------
// Name: IsSessionHost()
// Desc: True if this SessionManager instance is the session host,
// else false
//------------------------------------------------------------------------
BOOL SessionManager::IsSessionHost( VOID ) const
{
return m_bIsHost;
}
//------------------------------------------------------------------------
// Name: MakeSessionHost()
// Desc: Make this SessionManager instance the session host.
//------------------------------------------------------------------------
VOID SessionManager::MakeSessionHost( VOID )
{
m_bIsHost = TRUE;
}
//------------------------------------------------------------------------
// Name: GetSessionNonce()
// Desc: Function to retrieve current session nonce
//------------------------------------------------------------------------
ULONGLONG SessionManager::GetSessionNonce( VOID ) const
{
return m_qwSessionNonce;
}
//------------------------------------------------------------------------
// Name: SetSessionNonce()
// Desc: Function to set the session nonce
// Only non-hosts should ever call this method
//------------------------------------------------------------------------
VOID SessionManager::SetSessionNonce( const ULONGLONG qwNonce )
{
if( m_bIsHost )
{
FatalError( "Only non-hosts should call this function!\n" );
}
m_qwSessionNonce = qwNonce;
DebugDumpSessionDetails();
}
//------------------------------------------------------------------------
// Name: SetHostInAddr()
// Desc: Sets the IN_ADDR of the session host
//------------------------------------------------------------------------
VOID SessionManager::SetHostInAddr( const IN_ADDR& inaddr )
{
m_HostInAddr = inaddr;
}
//------------------------------------------------------------------------
// Name: GetHostInAddr()
// Desc: Returns the IN_ADDR of the session host
//------------------------------------------------------------------------
IN_ADDR SessionManager::GetHostInAddr( VOID ) const
{
return m_HostInAddr;
}
//------------------------------------------------------------------------
// Name: GetSessionID()
// Desc: Function to retrieve current session ID
//------------------------------------------------------------------------
XNKID SessionManager::GetSessionID( VOID ) const
{
return m_SessionInfo.sessionID;
}
//------------------------------------------------------------------------
// Name: GetSessionIDAsInt()
// Desc: Function to retrieve current session ID as an __int64
//------------------------------------------------------------------------
__int64 SessionManager::GetSessionIDAsInt( VOID ) const
{
// XNKID's are big-endian. Convert to little-endian if needed.
#ifdef LIVE_ON_WINDOWS
XNKID sessionID = m_SessionInfo.sessionID;
for( BYTE i = 0; i < 4; ++i )
{
BYTE temp = (BYTE)( *( (BYTE*)&sessionID + i ) ); //temp = sessionID[ i ]
*( (BYTE*)&sessionID + i ) = (BYTE)( *( (BYTE*)&sessionID + 8 - i - 1 ) ); //sessionID[ i ] = sessionID[ 8 - i - 1 ]
*( (BYTE*)&sessionID + 8 - i - 1 ) = temp; //sessionID[ 8 - i - 1 ] = temp
}
return *(const __int64*)&sessionID;
#else
return *(const __int64*)&m_SessionInfo.sessionID;
#endif
}
//------------------------------------------------------------------------
// Name: GetMigratedSessionID()
// Desc: Function to retrieve the session ID of the session while
// it is being migrated. This method can only be called
// when this session manager instance is actively migrating a session
//------------------------------------------------------------------------
XNKID SessionManager::GetMigratedSessionID( VOID ) const
{
if( !( m_SessionState >= SessionStateMigrateHost &&
m_SessionState <= SessionStateMigratedHost ) )
{
FatalError( "GetMigratedSessionID called in state %s!\n", GetSessionStateString() );
}
return m_migratedSessionID;
}
//------------------------------------------------------------------------
// Name: SetSessionState()
// Desc: Sets current session state
//------------------------------------------------------------------------
VOID SessionManager::SetSessionState( const SessionState newState )
{
m_SessionState = newState;
}
//------------------------------------------------------------------------
// Name: CheckSessionState()
// Desc: Checks if session in the expected state
//------------------------------------------------------------------------
BOOL SessionManager::CheckSessionState( const SessionState expectedState ) const
{
SessionState actual = GetSessionState();
if( actual != expectedState )
{
FatalError( "SessionManager instance in invalid state. Expected: %d; Got: %d\n",
expectedState, actual );
}
return TRUE;
}
//------------------------------------------------------------------------
// Name: GetRegistrationResults()
// Desc: Retrieves last results from registering this client for
// arbitratrion
//------------------------------------------------------------------------
const PXSESSION_REGISTRATION_RESULTS SessionManager::GetRegistrationResults() const
{
return (const PXSESSION_REGISTRATION_RESULTS)m_pRegistrationResults;
}
//------------------------------------------------------------------------
// Name: SwitchToState()
// Desc: Changes to a new session state and performs initialization
// for the new state
//------------------------------------------------------------------------
VOID SessionManager::SwitchToState( SessionState newState )
{
// Ignore transitions to the same state
if( m_SessionState == newState )
{
return;
}
// If we're in state SessionStateMigratedHost, force a switch to
// the state we were in prior to migration
if( m_SessionState == SessionStateMigratedHost )
{
DebugSpew( "SessionManager %016I64X (instance %p): Detected to be in state SessionStateMigratedHost. " \
"Switching to correct pre-migration state\n",
XNKIDToInt64( m_SessionInfo.sessionID ),
this );
SwitchToPreHostMigrationState();
}
assert( m_SessionState < _countof( g_astrSessionState ) );
DebugSpew( "SessionManager %016I64X (instance %p): Switching from session state %s to %s\n",
XNKIDToInt64( m_SessionInfo.sessionID ),
this,
g_astrSessionState[m_SessionState],
g_astrSessionState[newState] );
// Clean up from the previous state
switch( m_SessionState )
{
case SessionStateDeleted:
//Reset();
// Clear out our slots and update our presence info
m_Slots[ SLOTS_FILLEDPUBLIC ] = 0;
m_Slots[ SLOTS_FILLEDPRIVATE ] = 0;
m_Slots[ SLOTS_ZOMBIEPUBLIC ] = 0;
m_Slots[ SLOTS_ZOMBIEPRIVATE ] = 0;
if( m_pRegistrationResults )
{
delete[] m_pRegistrationResults;
m_pRegistrationResults = NULL;
}
break;
case SessionStateMigratedHost:
m_bIsMigratedSessionHost = FALSE;
break;
case SessionStateRegistering:
case SessionStateInGame:
case SessionStateNone:
case SessionStateCreating:
case SessionStateWaitingForRegistration:
case SessionStateStarting:
case SessionStateEnding:
case SessionStateDeleting:
default:
break;
}
// Initialize the next state
switch( newState )
{
case SessionStateCreated:
if( !IsSessionHost() )
{
// Re-entering this state is a bad thing, since
// that would wipe out the session nonce
assert( m_SessionState != SessionStateCreated );
// XSessionCreate would have
// returned a 0 session nonce,
// so set our session nonce
// to a random value that we'll
// replace once we get the
// true nonce from the session host
int retVal = XNetRandom( (BYTE *)&m_qwSessionNonce, sizeof( m_qwSessionNonce ) );
if ( retVal )
{
FatalError( "XNetRandom failed: %d\n", retVal );
}
DebugDumpSessionDetails();
}
break;
case SessionStateMigratedHost:
// Copy m_NewSessionInfo into m_SessionInfo
// and zero out m_NewSessionInfo
m_SessionInfo = m_NewSessionInfo;
ZeroMemory( &m_NewSessionInfo, sizeof( XSESSION_INFO ) );
break;
case SessionStateEnded:
// If this is an arbitrated session, we might have slots occupied by zombies. Free up those slots
// and zero out our zombie slot counts
if( m_dwSessionFlags & XSESSION_CREATE_USES_ARBITRATION )
{
m_Slots[ SLOTS_FILLEDPRIVATE ] -= m_Slots[ SLOTS_ZOMBIEPRIVATE ];
m_Slots[ SLOTS_FILLEDPRIVATE ] = max( m_Slots[ SLOTS_FILLEDPRIVATE ], 0 );
m_Slots[ SLOTS_FILLEDPUBLIC ] -= m_Slots[ SLOTS_ZOMBIEPUBLIC ];
m_Slots[ SLOTS_FILLEDPUBLIC ] = max( m_Slots[ SLOTS_FILLEDPUBLIC ], 0 );
m_Slots[ SLOTS_ZOMBIEPRIVATE ] = 0;
m_Slots[ SLOTS_ZOMBIEPUBLIC ] = 0;
}
break;
case SessionStateDeleted:
if( ( m_hSession != INVALID_HANDLE_VALUE ) &&
( m_hSession != NULL ) )
{
XCloseHandle( m_hSession );
m_hSession = NULL;
}
break;
case SessionStateNone:
case SessionStateIdle:
case SessionStateWaitingForRegistration:
case SessionStateRegistered:
case SessionStateInGame:
default:
break;
}
m_SessionState = newState;
}
//------------------------------------------------------------------------
// Name: NotifyOverlappedOperationCancelled()
// Desc: Lets this instance know that the current overlapped operation
// was cancelled.
//------------------------------------------------------------------------
HRESULT SessionManager::NotifyOverlappedOperationCancelled( const XOVERLAPPED* const pXOverlapped )
{
//
// Only certain states can be rolled back to the previous state
switch( m_SessionState )
{
case SessionStateCreating:
m_SessionState = SessionStateNone;
break;
case SessionStateRegistering:
m_SessionState = SessionStateIdle;
break;
case SessionStateStarting:
m_SessionState = HasSessionFlags( XSESSION_CREATE_USES_ARBITRATION ) ? SessionStateRegistered : SessionStateIdle;
break;
case SessionStateEnding:
m_SessionState = SessionStateInGame;
break;
case SessionStateDeleting:
m_SessionState = SessionStateEnded;
break;
}
return S_OK;
}
//------------------------------------------------------------------------
// Name: SwitchToPreHostMigrationState()
// Desc: Switches the current session state back to what it was
// prior to host migration
//------------------------------------------------------------------------
VOID SessionManager::SwitchToPreHostMigrationState()
{
// We can only transition to this state from SessionStateMigratedHost
assert( m_SessionState == SessionStateMigratedHost );
// Zero out m_migratedSessionID
ZeroMemory( &m_migratedSessionID, sizeof( XNKID ) );
// Return session state to what it was before migration started
// and set m_migratedSessionState to a blank state
m_SessionState = m_migratedSessionState;
m_migratedSessionState = SessionStateNone;
m_bIsMigratedSessionHost = FALSE;
DebugDumpSessionDetails();
}
//------------------------------------------------------------------------
// Name: HasSessionFlags()
// Desc: Checks if passed-in flags are set for the current session
//------------------------------------------------------------------------
BOOL SessionManager::HasSessionFlags( const DWORD dwFlags ) const
{
BOOL bHasFlags = FALSE;
// What flags in m_dwSessionFlags and dwFlags are different?
DWORD dwDiffFlags = m_dwSessionFlags ^ dwFlags;
// If none of dwDiffFlags are in dwFlags,
// we have a match
if( ( dwDiffFlags & dwFlags ) == 0 )
{
bHasFlags = TRUE;
}
return bHasFlags;
}
//------------------------------------------------------------------------
// Name: FlipSessionFlags()
// Desc: XORs the state of the current session's
// flags with that of the passed-in flags
//------------------------------------------------------------------------
VOID SessionManager::FlipSessionFlags( const DWORD dwFlags )
{
m_dwSessionFlags ^= dwFlags;
DebugSpew( "FlipSessionFlags: New session flags: %d\n", m_dwSessionFlags );
}
//------------------------------------------------------------------------
// Name: ClearSessionFlags()
// Desc: Clear the passed-in flags for the
// current session
//------------------------------------------------------------------------
VOID SessionManager::ClearSessionFlags( const DWORD dwFlags )
{
m_dwSessionFlags &= ~dwFlags;
DebugSpew( "ClearSessionFlags: New session flags: %d\n", m_dwSessionFlags );
}
//------------------------------------------------------------------------
// Name: SetSessionInfo()
// Desc: Set session info data. This only be called outside of an
// active session
//------------------------------------------------------------------------
VOID SessionManager::SetSessionInfo( const XSESSION_INFO& session_info )
{
SessionState actual = GetSessionState();
if( m_SessionState > SessionStateCreating && m_SessionState < SessionStateDelete )
{
FatalError( "SessionManager instance in invalid state: %s\n", g_astrSessionState[actual] );
}
m_SessionInfo = session_info;
}
//------------------------------------------------------------------------
// Name: SetNewSessionInfo()
// Desc: Set session info data for the new session we will migrate this
// session to. This only be called inside of an active session
//------------------------------------------------------------------------
VOID SessionManager::SetNewSessionInfo( const XSESSION_INFO& session_info,
const BOOL bIsNewSessionHost )
{
SessionState actual = GetSessionState();
if( m_SessionState < SessionStateCreated || m_SessionState >= SessionStateDelete )
{
FatalError( "SessionManager instance in invalid state: %d\n", actual );
}
m_NewSessionInfo = session_info;
m_bIsMigratedSessionHost = bIsNewSessionHost;
// Cache current session ID for a possible host migration scenario..
memcpy( &m_migratedSessionID, &m_SessionInfo.sessionID, sizeof( XNKID ) );
}
//------------------------------------------------------------------------
// Name: SetSessionFlags()
// Desc: Set session flags. Optionally first clears all currently set
// flags. This only be called outside of an active session
//------------------------------------------------------------------------
VOID SessionManager::SetSessionFlags( const DWORD dwFlags, const BOOL fClearExisting )
{
SessionState actual = GetSessionState();
if( m_SessionState > SessionStateCreating && m_SessionState < SessionStateDelete )
{
FatalError( "SessionManager instance in invalid state: %s\n", g_astrSessionState[actual] );
}
if( fClearExisting )
{
m_dwSessionFlags = 0;
}
m_dwSessionFlags |= dwFlags;
DebugSpew( "SetSessionFlags: New session flags: %d\n", m_dwSessionFlags );
}
//------------------------------------------------------------------------
// Name: GetSessionFlags()
// Desc: Returns current session flags
//------------------------------------------------------------------------
DWORD SessionManager::GetSessionFlags() const
{
return m_dwSessionFlags;
}
//------------------------------------------------------------------------
// Name: GetSessionInfo()
// Desc: Returns current XSESSION_INFO
//------------------------------------------------------------------------
const XSESSION_INFO& SessionManager::GetSessionInfo() const
{
return m_SessionInfo;
}
//------------------------------------------------------------------------
// Name: GetMaxSlotCounts()
// Desc: Returns current maximum slot counts
//------------------------------------------------------------------------
VOID SessionManager::GetMaxSlotCounts( DWORD& dwMaxPublicSlots, DWORD& dwMaxPrivateSlots ) const
{
dwMaxPublicSlots = m_Slots[SLOTS_TOTALPUBLIC];
dwMaxPrivateSlots = m_Slots[SLOTS_TOTALPRIVATE];
// DebugValidateExpectedSlotCounts();
}
//------------------------------------------------------------------------
// Name: GetFilledSlotCounts()
// Desc: Returns current filled slot counts
//------------------------------------------------------------------------
VOID SessionManager::GetFilledSlotCounts( DWORD& dwFilledPublicSlots, DWORD& dwFilledPrivateSlots ) const
{
dwFilledPublicSlots = m_Slots[SLOTS_FILLEDPUBLIC];
dwFilledPrivateSlots = m_Slots[SLOTS_FILLEDPRIVATE];
// DebugValidateExpectedSlotCounts();
}
//------------------------------------------------------------------------
// Name: SetMaxSlotCounts()
// Desc: Sets current maximum slot counts
//------------------------------------------------------------------------
VOID SessionManager::SetMaxSlotCounts( const DWORD dwMaxPublicSlots, const DWORD dwMaxPrivateSlots )
{
#ifdef _DEBUG
DebugSpew( "SetMaxSlotCounts(%016I64X): Old: [%d, %d, %d, %d]\n",
XNKIDToInt64( m_SessionInfo.sessionID ),
m_Slots[SLOTS_TOTALPUBLIC],
m_Slots[SLOTS_TOTALPRIVATE],
m_Slots[SLOTS_FILLEDPUBLIC],
m_Slots[SLOTS_FILLEDPRIVATE]);
#endif
m_Slots[SLOTS_TOTALPUBLIC] = dwMaxPublicSlots;
m_Slots[SLOTS_TOTALPRIVATE] = dwMaxPrivateSlots;
#ifdef _DEBUG
DebugSpew( "SetMaxSlotCounts(%016I64X): New: [%d, %d, %d, %d]\n",
XNKIDToInt64( m_SessionInfo.sessionID ),
m_Slots[SLOTS_TOTALPUBLIC],
m_Slots[SLOTS_TOTALPRIVATE],
m_Slots[SLOTS_FILLEDPUBLIC],
m_Slots[SLOTS_FILLEDPRIVATE]);
#endif
}
//------------------------------------------------------------------------
// Name: SetFilledSlotCounts()
// Desc: Sets current filled slot counts
//------------------------------------------------------------------------
VOID SessionManager::SetFilledSlotCounts( const DWORD dwFilledPublicSlots, DWORD dwFilledPrivateSlots )
{
#ifdef _DEBUG
DebugSpew( "SetFilledSlotCounts(%016I64X): Old: [%d, %d, %d, %d]\n",
XNKIDToInt64( m_SessionInfo.sessionID ),
m_Slots[SLOTS_TOTALPUBLIC],
m_Slots[SLOTS_TOTALPRIVATE],
m_Slots[SLOTS_FILLEDPUBLIC],
m_Slots[SLOTS_FILLEDPRIVATE]);
#endif
m_Slots[SLOTS_FILLEDPUBLIC] = dwFilledPublicSlots;
m_Slots[SLOTS_FILLEDPRIVATE] = dwFilledPrivateSlots;
#ifdef _DEBUG
DebugSpew( "SetFilledSlotCounts(%016I64X): New: [%d, %d, %d, %d]\n",
XNKIDToInt64( m_SessionInfo.sessionID ),
m_Slots[SLOTS_TOTALPUBLIC],
m_Slots[SLOTS_TOTALPRIVATE],
m_Slots[SLOTS_FILLEDPUBLIC],
m_Slots[SLOTS_FILLEDPRIVATE]);
#endif
}
//------------------------------------------------------------------------
// Name: GetSessionError()
// Desc: Returns session error string
//------------------------------------------------------------------------
WCHAR* SessionManager::GetSessionError() const
{
return m_strSessionError;
}
//------------------------------------------------------------------------
// Name: SetSessionError()
// Desc: Sets session error string
//------------------------------------------------------------------------
VOID SessionManager::SetSessionError( WCHAR* error )
{
m_strSessionError = error;
}
//--------------------------------------------------------------------------------------
// Name: StartQoSListener()
// Desc: Turn on the Quality of Service Listener for the current session
//--------------------------------------------------------------------------------------
VOID SessionManager::StartQoSListener( BYTE* data, const UINT dataLen, const DWORD bitsPerSec )
{
DWORD flags = XNET_QOS_LISTEN_SET_DATA;
if( bitsPerSec )
{
flags |= XNET_QOS_LISTEN_SET_BITSPERSEC;
}
if( !m_bUsingQoS )
{
flags |= XNET_QOS_LISTEN_ENABLE;
}
DWORD dwRet;
dwRet = XNetQosListen( &( m_SessionInfo.sessionID ), data, dataLen, bitsPerSec, flags );
if( ERROR_SUCCESS != dwRet )
{
FatalError( "Failed to start QoS listener, error 0x%08x\n", dwRet );
}
m_bUsingQoS = TRUE;
}
//--------------------------------------------------------------------------------------
// Name: StopQoSListener()
// Desc: Turn off the Quality of Service Listener for the current session
//--------------------------------------------------------------------------------------
VOID SessionManager::StopQoSListener()
{
if( m_bUsingQoS )
{
DWORD dwRet;
dwRet = XNetQosListen( &( m_SessionInfo.sessionID ), NULL, 0, 0,
XNET_QOS_LISTEN_RELEASE );
if( ERROR_SUCCESS != dwRet )
{
DebugSpew( "Warning: Failed to stop QoS listener, error 0x%08x\n", dwRet );
}
m_bUsingQoS = FALSE;
}
}
//------------------------------------------------------------------------
// Name: CreateSession()
// Desc: Creates a session
//------------------------------------------------------------------------
HRESULT SessionManager::CreateSession( XOVERLAPPED* pXOverlapped )
{
// Make sure our instance is in the right state
SessionState actual = GetSessionState();
if( actual != SessionStateNone && actual != SessionStateDeleted )
{
FatalError( "Wrong state: %s\n", g_astrSessionState[actual] );
}
// Modify session flags if host
if( m_bIsHost )
{
m_dwSessionFlags |= XSESSION_CREATE_HOST;
}
else
{
// Turn off host bit
m_dwSessionFlags &= ~XSESSION_CREATE_HOST;
}
// If we're just in a Matchmaking session, we can only specify the
// XSESSION_CREATE_JOIN_IN_PROGRESS_DISABLED modifier
if( !( m_dwSessionFlags & XSESSION_CREATE_USES_PRESENCE ) &&
( m_dwSessionFlags & XSESSION_CREATE_USES_MATCHMAKING ) &&
( m_dwSessionFlags & XSESSION_CREATE_MODIFIERS_MASK ) )
{
// turn off all modifiers
m_dwSessionFlags &= ~XSESSION_CREATE_MODIFIERS_MASK;
// turn on XSESSION_CREATE_JOIN_IN_PROGRESS_DISABLED
m_dwSessionFlags |= XSESSION_CREATE_JOIN_IN_PROGRESS_DISABLED;
}
// Call XSessionCreate
DWORD ret = XSessionCreate( m_dwSessionFlags,
m_dwOwnerController,
m_Slots[SLOTS_TOTALPRIVATE],
m_Slots[SLOTS_TOTALPUBLIC],
&m_qwSessionNonce,
&m_SessionInfo,
pXOverlapped,
&m_hSession );
if( pXOverlapped && ( ret == ERROR_IO_PENDING ) )
{
SwitchToState( SessionStateCreating );
}
else if( !pXOverlapped )
{
SwitchToState( SessionStateCreated );
}
return HRESULT_FROM_WIN32( ret );
}
//------------------------------------------------------------------------
// Name: StartSession()
// Desc: Starts the current session
//------------------------------------------------------------------------
HRESULT SessionManager::StartSession( XOVERLAPPED* pXOverlapped )
{
DWORD ret = XSessionStart( m_hSession,
0,
pXOverlapped );
if( pXOverlapped && ( ret == ERROR_IO_PENDING ) )
{
SwitchToState( SessionStateStarting );
}
else if( !pXOverlapped )
{
SwitchToState( SessionStateInGame );
}
return HRESULT_FROM_WIN32( ret );
}
//------------------------------------------------------------------------
// Name: EndSession()
// Desc: Ends the current session
//------------------------------------------------------------------------
HRESULT SessionManager::EndSession( XOVERLAPPED* pXOverlapped )
{
DWORD ret = XSessionEnd( m_hSession, pXOverlapped );
if( pXOverlapped && ( ret == ERROR_IO_PENDING ) )
{
SwitchToState( SessionStateEnding );
}
else if( !pXOverlapped )
{
SwitchToState( SessionStateEnded );
}
return HRESULT_FROM_WIN32( ret );
}
//------------------------------------------------------------------------
// Name: DeleteSession()
// Desc: Deletes the current session
//------------------------------------------------------------------------
HRESULT SessionManager::DeleteSession( XOVERLAPPED* pXOverlapped )
{
// Make sure our instance is in the right state
SessionState actual = GetSessionState();
if( actual < SessionStateCreated )
{
FatalError( "Wrong state: %s\n", g_astrSessionState[actual] );
}
SwitchToState( SessionStateDelete );
// Stop QoS listener if it's running
StopQoSListener();
// Call XSessionDelete
DWORD ret = XSessionDelete( m_hSession, pXOverlapped );
if( pXOverlapped && ( ret == ERROR_IO_PENDING ) )
{
SwitchToState( SessionStateDeleting );
}
else if( !pXOverlapped )
{
SwitchToState( SessionStateDeleted );
}
return HRESULT_FROM_WIN32( ret );
}
//------------------------------------------------------------------------
// Name: MigrateSession()
// Desc: Migrates the current session
//------------------------------------------------------------------------
HRESULT SessionManager::MigrateSession( XOVERLAPPED* pXOverlapped )
{
// Make sure our instance is in the right state
SessionState actual = GetSessionState();
if( actual < SessionStateCreated || actual >= SessionStateDelete )
{
FatalError( "Wrong state: %s\n", g_astrSessionState[actual] );
}
m_migratedSessionState = m_SessionState;
DWORD ret = XSessionMigrateHost( m_hSession,
( m_bIsMigratedSessionHost ) ? m_dwOwnerController : XUSER_INDEX_NONE,
&m_NewSessionInfo,
pXOverlapped );
if( pXOverlapped && ( ret == ERROR_IO_PENDING ) )
{
SwitchToState( SessionStateMigratingHost );
}
else if( !pXOverlapped )
{
SwitchToState( SessionStateMigratedHost );
}
return HRESULT_FROM_WIN32( ret );
}
//------------------------------------------------------------------------
// Name: ModifySessionFlags()
// Desc: Modifies session flags
//------------------------------------------------------------------------
HRESULT SessionManager::ModifySessionFlags( const DWORD dwFlags,
const BOOL bClearFlags,
XOVERLAPPED* pXOverlapped )
{
SessionState actual = GetSessionState();
if( m_SessionState <= SessionStateCreating || m_SessionState >= SessionStateDelete )
{
FatalError( "SessionManager instance in invalid state: %s\n", g_astrSessionState[actual] );
}
DWORD dwNewFlags = dwFlags;
// If no flags in the modifiers mask are specified, do nothing
if( ( dwNewFlags & XSESSION_CREATE_MODIFIERS_MASK ) == 0 )
{
return ERROR_SUCCESS;
}
// Flags cannot be modified for arbitrated sessions
if( m_dwSessionFlags & XSESSION_CREATE_USES_ARBITRATION )
{
return ERROR_SUCCESS;
}
// Add host bit to dwFlags if host; otherwise remove
if( m_bIsHost )
{
dwNewFlags |= XSESSION_CREATE_HOST;
}
else
{
// Turn off host bit
dwNewFlags &= ~XSESSION_CREATE_HOST;
}
// Apply allowable session modifier flags to our session flags
if( bClearFlags )
{
m_dwSessionFlags ^= dwNewFlags & MODIFY_FLAGS_ALLOWED;
}
else
{
m_dwSessionFlags |= dwNewFlags & MODIFY_FLAGS_ALLOWED;
}
// Re-insert host bit if host
if( m_bIsHost )
{
m_dwSessionFlags |= XSESSION_CREATE_HOST;
}
DebugSpew( "ProcessModifySessionFlagsMessage: New session flags: %d\n", m_dwSessionFlags );
DWORD ret = XSessionModify( m_hSession,
m_dwSessionFlags,
m_Slots[SLOTS_TOTALPUBLIC],
m_Slots[SLOTS_TOTALPRIVATE],
pXOverlapped );
return HRESULT_FROM_WIN32( ret );
}
//------------------------------------------------------------------------
// Name: ModifySkill()
// Desc: Modifies TrueSkill(TM)
//------------------------------------------------------------------------
HRESULT SessionManager::ModifySkill( const DWORD dwNumXuids,
const XUID* pXuids,
XOVERLAPPED* pXOverlapped )
{
SessionState actual = GetSessionState();
if( m_SessionState <= SessionStateCreating || m_SessionState >= SessionStateDelete )
{
FatalError( "SessionManager instance in invalid state: %s\n", g_astrSessionState[actual] );
}
DWORD ret = XSessionModifySkill( m_hSession,
dwNumXuids,
pXuids,
pXOverlapped );
return HRESULT_FROM_WIN32( ret );
}
//------------------------------------------------------------------------
// Name: RegisterArbitration()
// Desc: Registers the current session for arbitration
//------------------------------------------------------------------------
HRESULT SessionManager::RegisterArbitration( XOVERLAPPED* pXOverlapped )
{
SessionState actual = GetSessionState();
if( actual < SessionStateCreated || actual >= SessionStateStarting )
{
FatalError( "Wrong state: %s\n", g_astrSessionState[actual] );
}
// Call once to determine size of results buffer
DWORD cbRegistrationResults = 0;
DWORD ret = XSessionArbitrationRegister( m_hSession,
0,
m_qwSessionNonce,
&cbRegistrationResults,
NULL,
NULL );
if( ( ret != ERROR_INSUFFICIENT_BUFFER ) || ( cbRegistrationResults == 0 ) )
{
DebugSpew( "Failed on first call to XSessionArbitrationRegister, hr=0x%08x\n", ret );
return ERROR_FUNCTION_FAILED;
}
m_pRegistrationResults = (PXSESSION_REGISTRATION_RESULTS)new BYTE[cbRegistrationResults];
if( m_pRegistrationResults == NULL )
{
DebugSpew( "Failed to allocate buffer.\n" );
return ERROR_FUNCTION_FAILED;
}
// Call second time to fill our results buffer
ret = XSessionArbitrationRegister( m_hSession,
0,
m_qwSessionNonce,
&cbRegistrationResults,
m_pRegistrationResults,
pXOverlapped );
if( pXOverlapped && ( ret == ERROR_IO_PENDING ) )
{
SwitchToState( SessionStateRegistering );
}
else if( !pXOverlapped )
{
SwitchToState( SessionStateRegistered );
}
return HRESULT_FROM_WIN32( ret );
}
//------------------------------------------------------------------------
// Name: AddLocalPlayers()
// Desc: Add local players to the session
//------------------------------------------------------------------------
HRESULT SessionManager::AddLocalPlayers( const DWORD dwUserCount,
DWORD* pdwUserIndices,
const BOOL* pfPrivateSlots,
XOVERLAPPED* pXOverlapped )
{
SessionState actual = GetSessionState();
if( actual < SessionStateCreating || actual >= SessionStateDelete )
{
FatalError( "Wrong state: %s\n", g_astrSessionState[actual] );
}
DWORD ret = ERROR_SUCCESS;
// Do nothing if the session is already deleted
if( m_SessionState == SessionStateDeleted )
{
return HRESULT_FROM_WIN32( ret );
}
for ( DWORD i = 0; i < dwUserCount; ++i )
{
XUID xuid;
XUserGetXUID( pdwUserIndices[i], &xuid );
DebugSpew( "Processing local user: index: %d; xuid: 0x%016I64X; bInvited: %d\n",
pdwUserIndices[ i ], xuid, pfPrivateSlots[ i ] );
// If xuid is already in the session, don't re-add
if( IsPlayerInSession( xuid ) )
{
pdwUserIndices[ i ] = XUSER_INDEX_NONE;
}
}
ret = XSessionJoinLocal( m_hSession,
dwUserCount,
pdwUserIndices,
pfPrivateSlots,
pXOverlapped );
// Update slot counts
for ( DWORD i = 0; i < dwUserCount; ++i )
{
m_Slots[ SLOTS_FILLEDPRIVATE ] += ( pfPrivateSlots[ i ] ) ? 1 : 0;
m_Slots[ SLOTS_FILLEDPUBLIC ] += ( pfPrivateSlots[ i ] ) ? 0 : 1;
}
if( m_Slots[ SLOTS_FILLEDPRIVATE ] > m_Slots[ SLOTS_TOTALPRIVATE ] )
{
DWORD diff = m_Slots[ SLOTS_FILLEDPRIVATE ] - m_Slots[ SLOTS_TOTALPRIVATE ];
m_Slots[ SLOTS_FILLEDPUBLIC ] += diff;
assert( m_Slots[ SLOTS_FILLEDPUBLIC ] <= m_Slots[ SLOTS_TOTALPUBLIC ] );
if( m_Slots[ SLOTS_FILLEDPUBLIC ] > m_Slots[ SLOTS_TOTALPUBLIC ] )
{
FatalError( "Too many slots filled!\n" );
}
m_Slots[ SLOTS_FILLEDPRIVATE ] = m_Slots[ SLOTS_TOTALPRIVATE ];
}
DebugDumpSessionDetails();
DebugValidateExpectedSlotCounts();
return HRESULT_FROM_WIN32( ret );
}
//------------------------------------------------------------------------
// Name: AddRemotePlayers()
// Desc: Adds remote players to the session
//------------------------------------------------------------------------
HRESULT SessionManager::AddRemotePlayers( const DWORD dwXuidCount,
XUID* pXuids,
const BOOL* pfPrivateSlots,
XOVERLAPPED* pXOverlapped )
{
SessionState actual = GetSessionState();
if( actual < SessionStateCreating || actual >= SessionStateDelete )
{
FatalError( "Wrong state: %s\n", g_astrSessionState[actual] );
}
for ( DWORD i=0; i<dwXuidCount; ++i )
{
DebugSpew( "AddRemotePlayers: 0x%016I64X; bInvited: %d\n", pXuids[ i ], pfPrivateSlots[ i ] );
}
DWORD ret = ERROR_SUCCESS;
// Do nothing if the session is already deleted
if( m_SessionState == SessionStateDeleted )
{
return HRESULT_FROM_WIN32( ret );
}
for ( DWORD i = 0; i < dwXuidCount; ++i )
{
DebugSpew( "Processing remote user: 0x%016I64X; bInvited: %d\n",
pXuids[ i ], pfPrivateSlots[ i ] );
// If msg.m_pXuids[ i ] is already in the session, don't re-add
if( IsPlayerInSession( pXuids[ i ] ) )
{
pXuids[ i ] = INVALID_XUID;
DebugSpew( "Remote user: 0x%016I64X already in the session!\n",
pXuids[ i ] );
}
}
ret = XSessionJoinRemote( m_hSession,
dwXuidCount,
pXuids,
pfPrivateSlots,
pXOverlapped );
// Update slot counts
for ( DWORD i = 0; i < dwXuidCount; ++i )
{
m_Slots[ SLOTS_FILLEDPRIVATE ] += ( pfPrivateSlots[ i ] ) ? 1 : 0;
m_Slots[ SLOTS_FILLEDPUBLIC ] += ( pfPrivateSlots[ i ] ) ? 0 : 1;
}
if( m_Slots[ SLOTS_FILLEDPRIVATE ] > m_Slots[ SLOTS_TOTALPRIVATE ] )
{
DWORD diff = m_Slots[ SLOTS_FILLEDPRIVATE ] - m_Slots[ SLOTS_TOTALPRIVATE ];
m_Slots[ SLOTS_FILLEDPUBLIC ] += diff;
assert( m_Slots[ SLOTS_FILLEDPUBLIC ] <= m_Slots[ SLOTS_TOTALPUBLIC ] );
if( m_Slots[ SLOTS_FILLEDPUBLIC ] > m_Slots[ SLOTS_TOTALPUBLIC ] )
{
FatalError( "Too many slots filled!\n" );
}
m_Slots[ SLOTS_FILLEDPRIVATE ] = m_Slots[ SLOTS_TOTALPRIVATE ];
}
DebugDumpSessionDetails();
DebugValidateExpectedSlotCounts();
return HRESULT_FROM_WIN32( ret );
}
//------------------------------------------------------------------------
// Name: RemoveLocalPlayers()
// Desc: Add local players to the session
//------------------------------------------------------------------------
HRESULT SessionManager::RemoveLocalPlayers( const DWORD dwUserCount,
const DWORD* pdwUserIndices,
const BOOL* pfPrivateSlots,
XOVERLAPPED* pXOverlapped )
{
SessionState actual = GetSessionState();
if( actual < SessionStateCreated || actual >= SessionStateDelete )
{
FatalError( "Wrong state: %s\n", g_astrSessionState[actual] );
}
DWORD ret = ERROR_SUCCESS;
// Do nothing if the session is already deleted
if( m_SessionState == SessionStateDeleted )
{
return HRESULT_FROM_WIN32( ret );
}
#ifdef _DEBUG
for( DWORD i = 0; i < dwUserCount; ++i )
{
XUID xuid;
XUserGetXUID( i, &xuid );
DebugSpew( "%016I64X: ProcessRemoveLocalPlayerMessage: 0x%016I64X\n",
GetSessionIDAsInt(),
xuid );
}
#endif
ret = XSessionLeaveLocal( m_hSession,
dwUserCount,
pdwUserIndices,
pXOverlapped );
// If the session is arbitrated and gameplay is happening, then the player will still be
// kept in the session so stats can be reported, so we don't want to modify our slot counts
const BOOL bPlayersKeptForStatsReporting = ( ( m_dwSessionFlags & XSESSION_CREATE_USES_ARBITRATION ) &&
( m_SessionState == SessionStateInGame ) );
if( !bPlayersKeptForStatsReporting )
{
for ( DWORD i = 0; i < dwUserCount; ++i )
{
m_Slots[ SLOTS_FILLEDPRIVATE ] -= ( pfPrivateSlots[ i ] ) ? 1 : 0;
m_Slots[ SLOTS_FILLEDPUBLIC ] -= ( pfPrivateSlots[ i ] ) ? 0 : 1;
m_Slots[ SLOTS_FILLEDPRIVATE ] = max( m_Slots[ SLOTS_FILLEDPRIVATE ], 0 );
m_Slots[ SLOTS_FILLEDPUBLIC ] = max( m_Slots[ SLOTS_FILLEDPUBLIC ], 0 );
}
}
else
{
DebugSpew( "%016I64X: ProcessRemoveLocalPlayerMessage: Arbitrated session, so leaving players become zombies and not updating local slot counts\n",
GetSessionIDAsInt() );
for ( DWORD i = 0; i < dwUserCount; ++i )
{
m_Slots[ SLOTS_ZOMBIEPRIVATE ] += ( pfPrivateSlots[ i ] ) ? 1 : 0;
m_Slots[ SLOTS_ZOMBIEPUBLIC ] += ( pfPrivateSlots[ i ] ) ? 0 : 1;
}
}
DebugDumpSessionDetails();
DebugValidateExpectedSlotCounts();
return HRESULT_FROM_WIN32( ret );
}
//------------------------------------------------------------------------
// Name: RemoveRemotePlayers()
// Desc: Remove remote players to the session
//------------------------------------------------------------------------
HRESULT SessionManager::RemoveRemotePlayers( const DWORD dwXuidCount,
const XUID* pXuids,
const BOOL* pfPrivateSlots,
XOVERLAPPED* pXOverlapped )
{
SessionState actual = GetSessionState();
if( actual < SessionStateCreated || actual >= SessionStateDelete )
{
FatalError( "Wrong state: %s\n", g_astrSessionState[actual] );
}
#ifdef _DEBUG
for( DWORD i = 0; i < dwXuidCount; ++i )
{
DebugSpew( "%016I64X: ProcessRemoveRemotePlayerMessage: 0x%016I64X\n",
GetSessionIDAsInt(),
pXuids[i] );
}
#endif
DWORD ret = XSessionLeaveRemote( m_hSession,
dwXuidCount,
pXuids,
pXOverlapped );
{
// If the session is arbitrated and gameplay is happening, then the player will still be
// kept in the session so stats can be reported, so we don't want to modify our slot counts
const BOOL bPlayersKeptForStatsReporting = ( ( m_dwSessionFlags & XSESSION_CREATE_USES_ARBITRATION ) &&
( m_SessionState == SessionStateInGame ) );
if( !bPlayersKeptForStatsReporting )
{
for ( DWORD i = 0; i < dwXuidCount; ++i )
{
m_Slots[ SLOTS_FILLEDPRIVATE ] -= ( pfPrivateSlots[ i ] ) ? 1 : 0;
m_Slots[ SLOTS_FILLEDPUBLIC ] -= ( pfPrivateSlots[ i ] ) ? 0 : 1;
m_Slots[ SLOTS_FILLEDPRIVATE ] = max( m_Slots[ SLOTS_FILLEDPRIVATE ], 0 );
m_Slots[ SLOTS_FILLEDPUBLIC ] = max( m_Slots[ SLOTS_FILLEDPUBLIC ], 0 );
}
}
else
{
DebugSpew( "%016I64X: ProcessRemoveRemotePlayerMessage: Arbitrated session, so leaving players become zombies and not updating local slot counts\n",
GetSessionIDAsInt() );
for ( DWORD i = 0; i < dwXuidCount; ++i )
{
m_Slots[ SLOTS_ZOMBIEPRIVATE ] += ( pfPrivateSlots[ i ] ) ? 1 : 0;
m_Slots[ SLOTS_ZOMBIEPUBLIC ] += ( pfPrivateSlots[ i ] ) ? 0 : 1;
}
}
}
DebugDumpSessionDetails();
DebugValidateExpectedSlotCounts();
return HRESULT_FROM_WIN32( ret );
}
//------------------------------------------------------------------------
// Name: WriteStats()
// Desc: Write stats for a player in the session
//------------------------------------------------------------------------
HRESULT SessionManager::WriteStats( const XUID xuid,
const DWORD dwNumViews,
const XSESSION_VIEW_PROPERTIES *pViews,
XOVERLAPPED* pXOverlapped )
{
SessionState actual = GetSessionState();
if( actual < SessionStateInGame || actual >= SessionStateEnding )
{
FatalError( "Wrong state: %s\n", g_astrSessionState[actual] );
}
DebugSpew( "%016I64X: ProcessWriteStatsMessage: 0x%016I64X\n",
GetSessionIDAsInt(),
xuid );
DWORD ret = XSessionWriteStats( m_hSession,
xuid,
dwNumViews,
pViews,
pXOverlapped );
return HRESULT_FROM_WIN32( ret );
}
|
0b8255503285fb82287ae9b0fc4fff5efde55006
|
63ed2deb4616e8d3b93a4aefccd21d327ba82245
|
/Concurrent/RunWithGUIUpdate/RunWithGUIUpdate.cpp
|
9a506542eba0d0f775c01bdead83d9f5f26f5573
|
[] |
no_license
|
drescherjm/QtExamples
|
2f49cf85b04c08c011c2c0539862bfbf613f92a5
|
129a14dabb4cda84526d2780862d32156c75ec01
|
refs/heads/master
| 2020-12-25T06:12:05.772601
| 2012-03-19T00:40:40
| 2012-03-19T00:40:40
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 426
|
cpp
|
RunWithGUIUpdate.cpp
|
#include <QApplication>
#include <QObject>
#include <QtConcurrentRun>
#include <iostream>
#include "form.h"
#include "LongFunction.h"
int main(int argc, char*argv[])
{
QApplication app(argc, argv);
Form form;
form.show();
MyClass myClass;
QObject::connect(&myClass, SIGNAL(Update()), &form, SLOT(slot_Update()));
QtConcurrent::run ( LongFunction, &myClass );
return app.exec();
}
|
21e3c1ed2e2602f37d1648fb7b0c5d49f1944ec4
|
e6ef858879c89b166ee839e5b143844ab9ceee4b
|
/enclave_tests/test_objects.cpp
|
84445e84be77f2c8c24f253cb42e7e0f92c1adad
|
[] |
no_license
|
trusted-dcr/sgx-win
|
d185b88b17c4400b7d2a888fe6e0998b8273fad1
|
3b07a6a142a1fa7bb9feefba8f6a7eb7fb66f5e9
|
refs/heads/master
| 2020-03-11T08:56:39.127560
| 2018-06-19T19:03:51
| 2018-06-19T19:03:51
| 129,896,814
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,230
|
cpp
|
test_objects.cpp
|
#include "stdafx.h"
#include "test_objects.h"
//workflows:
dcr_event simple_event(uid_t id) {
dcr_event e;
e.id = id;
e.excluded = false;
e.executed = false;
e.pending = false;
return e;
}
dcr_workflow wf_simple_condition() {
dcr_workflow wf;
dcr_event e1 = simple_event({ 0,1 });
dcr_event e2 = simple_event({ 0,2 });
wf.event_store[e1.id] = e1;
wf.event_store[e2.id] = e2;
wf.conditions_to[e1.id].push_back(e2.id);
wf.conditions_from[e2.id].push_back(e1.id);
return wf;
}
dcr_workflow wf_simple_milestone() {
dcr_workflow wf;
dcr_event e1 = simple_event({ 0,1 });
dcr_event e2 = simple_event({ 0,2 });
e1.pending = true;
wf.event_store[e1.id] = e1;
wf.event_store[e2.id] = e2;
wf.milestones_to[e1.id].push_back(e2.id);
wf.milestones_from[e2.id].push_back(e1.id);
return wf;
}
dcr_workflow wf_simple_include() {
dcr_workflow wf;
dcr_event e1 = simple_event({ 0,1 });
dcr_event e2 = simple_event({ 0,2 });
e2.excluded = true;
wf.event_store[e1.id] = e1;
wf.event_store[e2.id] = e2;
wf.includes_to[e1.id].push_back(e2.id);
return wf;
}
dcr_workflow wf_simple_exclude() {
dcr_workflow wf;
dcr_event e1 = simple_event({ 0,1 });
dcr_event e2 = simple_event({ 0,2 });
wf.event_store[e1.id] = e1;
wf.event_store[e2.id] = e2;
wf.excludes_to[e1.id].push_back(e2.id);
return wf;
}
dcr_workflow wf_simple_response() {
dcr_workflow wf;
dcr_event e1 = simple_event({ 0,1 });
dcr_event e2 = simple_event({ 0,2 });
wf.event_store[e1.id] = e1;
wf.event_store[e2.id] = e2;
wf.responses_to[e1.id].push_back(e2.id);
return wf;
}
dcr_workflow wf_DU_DE() {
dcr_workflow wf;
dcr_event propose_DU = simple_event({ 0,1 });
dcr_event propose_DE = simple_event({ 0,2 });
dcr_event accept_DU = simple_event({ 0,3 });
dcr_event accept_DE = simple_event({ 0,4 });
dcr_event hold_meeting = simple_event({ 0,5 });
accept_DU.excluded = true;
accept_DE.excluded = true;
hold_meeting.pending = true;
wf.event_store[propose_DU.id] = propose_DU;
wf.event_store[propose_DE.id] = propose_DE;
wf.event_store[accept_DU.id] = accept_DU;
wf.event_store[accept_DE.id] = accept_DE;
wf.event_store[hold_meeting.id] = hold_meeting;
wf.conditions_to[propose_DU.id].push_back(propose_DE.id);
wf.conditions_from[propose_DE.id].push_back(propose_DU.id);
wf.milestones_to[accept_DU.id].push_back(hold_meeting.id);
wf.milestones_from[hold_meeting.id].push_back(accept_DU.id);
wf.milestones_to[accept_DE.id].push_back(hold_meeting.id);
wf.milestones_from[hold_meeting.id].push_back(accept_DE.id);
wf.includes_to[propose_DU.id].push_back(accept_DE.id);
wf.includes_to[propose_DE.id].push_back(accept_DU.id);
wf.excludes_to[accept_DU.id].push_back(accept_DE.id);
wf.excludes_to[accept_DU.id].push_back(accept_DU.id);
wf.excludes_to[accept_DE.id].push_back(accept_DU.id);
wf.excludes_to[accept_DE.id].push_back(accept_DE.id);
wf.responses_to[propose_DU.id].push_back(accept_DE.id);
wf.responses_to[propose_DE.id].push_back(accept_DU.id);
return wf;
}
//simple peer map:
std::map<uid_t, uid_t, cmp_uids> one_peer_peer_map() {
std::map<uid_t, uid_t, cmp_uids> peer_map;
peer_map[{0, 1}] = { 0,1 };
return peer_map;
}
//two peer map
std::map<uid_t, uid_t, cmp_uids> one_peer_per_event_peer_map() {
std::map<uid_t, uid_t, cmp_uids> peer_map;
peer_map[{0, 1}] = { 0,2 };
peer_map[{0, 2}] = { 0,1 };
return peer_map;
}
//six peer map on three event
std::map<uid_t, uid_t, cmp_uids> six_peers_two_peer_per_event_peer_map() {
std::map<uid_t, uid_t, cmp_uids> peer_map;
peer_map[{0, 1}] = { 0,1 };
peer_map[{0, 2}] = { 0,1 };
peer_map[{0, 3}] = { 0,2 };
peer_map[{0, 4}] = { 0,2 };
peer_map[{0, 5}] = { 0,3 };
peer_map[{0, 6}] = { 0,3 };
return peer_map;
}
//ten peer map on 5 event
std::map<uid_t, uid_t, cmp_uids> ten_peers_two_peer_per_event_peer_map() {
std::map<uid_t, uid_t, cmp_uids> peer_map;
peer_map[{0, 1}] = { 0,1 };
peer_map[{0, 2}] = { 0,1 };
peer_map[{0, 3}] = { 0,2 };
peer_map[{0, 4}] = { 0,2 };
peer_map[{0, 5}] = { 0,3 };
peer_map[{0, 6}] = { 0,3 };
peer_map[{0, 7}] = { 0,4 };
peer_map[{0, 8}] = { 0,4 };
peer_map[{0, 9}] = { 0,5 };
peer_map[{0, 10}] = { 0,5 };
return peer_map;
}
command_req_t empty_command_req(uid_t target, uid_t source) {
command_req_t req = {
target,
source,
command_tag_t {{0}, CHECKPOINT},
{0,0},
{0},
};
return req;
}
command_rsp_t empty_command_rsp(uid_t target, uid_t source) {
command_rsp_t rsp = {
target,
source,
command_tag_t {{ 0 }, CHECKPOINT},
true,
source,
{ 0 }
};
return rsp;
}
append_req_t empty_append_req(uid_t target, uid_t source) {
append_req_t req = {
target,
source,
1,
0,
0,
0,
NULL,
0,
{ 0 }
};
return req;
}
append_rsp_t empty_append_rsp(uid_t target, uid_t source) {
append_rsp_t rsp1 = {
target,
source,
0,
0,
0,
true,
0,
{ 0 }
};
return rsp1;
}
election_req_t empty_election_req(uid_t target, uid_t source) {
election_req_t req = {
target,
source,
0,
0,
0,
{0}
};
return req;
}
election_rsp_t empty_election_rsp(uid_t target, uid_t source) {
election_rsp_t rsp = {
target,
source,
0,
true,
{0}
};
return rsp;
}
log_req_t empty_log_req(uid_t target, uid_t source) {
return log_req_t();
}
log_rsp_t empty_log_rsp(uid_t target, uid_t source) {
return log_rsp_t();
}
poll_req_t empty_poll_req(uid_t target, uid_t source) {
poll_req_t req1 = {
target,
source,
0,
0,
0,
{ 0 }
};
return req1;
}
poll_rsp_t empty_poll_rsp(uid_t target, uid_t source) {
poll_rsp_t rsp = {
target,
source,
0,
true,
{0}
};
return rsp;
}
entry_t* entries1() {
entry_t entries1[3];
entry_t e1 = {
0,
0,
uid_t {0,1},
{0,3},
{uid_t {0,12}, CHECKPOINT}
};
entry_t e2 = {
0,
1,
uid_t{ 0,1 },
{ 0,5 },
{ uid_t{ 0,13 }, EXEC }
};
entry_t e3 = {
0,
2,
uid_t{ 0,1 },
{ 0,7 },
{ uid_t{ 0,14 }, LOCK }
};
entries1[0] = e1;
entries1[1] = e2;
entries1[2] = e3;
return entries1;
}
|
d919c879441eeff54cf7d386b8d3aa380e038711
|
632e44fad42d04b7235b6b44798d79d8a3ab016f
|
/SalaryAssignment/include/exeptions/InvalidSSNException.h
|
90696a582e80729bab5a535099b5d9778a0a0f9f
|
[] |
no_license
|
krilliman/hopur67
|
3424b6c355b6b890973aea9b6b3a43c05815170d
|
8b32de897d0b4c08efa2f43ceaa66a8f03ea9558
|
refs/heads/master
| 2021-08-30T06:39:47.768689
| 2017-12-16T00:09:25
| 2017-12-16T00:09:25
| 112,739,321
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 124
|
h
|
InvalidSSNException.h
|
#ifndef INVALIDSSNEXCEPTION_H
#define INVALIDSSNEXCEPTION_H
class InvalidSSNException{};
#endif // INVALIDSSNEXCEPTION_H
|
5ae1424c8809e18742cffb88ad72578bb6238fdb
|
4fe8448ea1fffcf92343102a916e84d47897f065
|
/XOOF/element.C
|
4ebc9cf5f043863b5fdcee6a5a9136d5e873a0a9
|
[] |
no_license
|
usnistgov/OOF1
|
1a691b7aac20ab691415b4b5832d031cf86ba50c
|
dfaf20efffaf6b8973da673ca7e4094282bcc801
|
refs/heads/master
| 2020-06-29T06:17:17.469441
| 2015-01-21T19:07:01
| 2015-01-21T19:07:01
| 29,553,217
| 3
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,800
|
c
|
element.C
|
// -*- C++ -*-
// $RCSfile: element.C,v $
// $Revision: 1.9 $
// $Author: langer $
// $Date: 2005-02-15 22:19:50 $
/* This software was produced by NIST, an agency of the U.S. government,
* and by statute is not subject to copyright in the United States.
* Recipients of this software assume all responsibilities associated
* with its operation, modification and maintenance. However, to
* facilitate maintenance we ask that before distributing modifed
* versions of this software, you first contact the authors at
* oof_manager@ctcms.nist.gov.
*/
#include "element.h"
#include "eulerangle.h"
#include "grid.h"
#include "node.h"
#include "elementgroups.h"
#include "mvmult.h"
#include "mutableelement.h"
#include "parameters.h"
#include "readbinary.h"
#include "tocharstring.h"
// default values for element creation commands
float Element::gray_dflt = 0.5;
Vec<int> Element::nodenumber_dflt;
int Element::index_dflt;
unsigned char Element::inputformatflag(0);
int Element::cloneindex;
// Constructor for base element.
Element::Element(Grid *grid)
: index(index_dflt),
selected(0),
intrinsic_gray(gray_dflt),
current_stress(TF_FALSE),
current_elastic_strain(TF_FALSE)
#ifdef THERMAL
, current_J(TF_FALSE),
current_grad_thermal(TF_FALSE),
J_field(3),
Grad_T_field(3)
#endif
{
int order = nodenumber_dflt.capacity();
corner.resize(order);
for(int j=0; j<order; j++) {
corner[j] = grid->getnode(nodenumber_dflt[j]);
}
++grid->elements_changed; // update timestamp
}
Element::~Element() {
/* this has to be done in reverse order, since Remove removes the group
* from the element as well as removing the element from the group.
*/
for(int i=groups.capacity()-1; i>=0; i--)
groups[i]->Remove(this);
}
Element *Element::binaryread(FILE *file, TrueFalse &ok) {
ok = TF_TRUE;
if(!readbinary(file, gray_dflt)) ok = TF_FALSE;
return 0;
}
void Element::reset_defaults() {
// reset static default values used when creating elements
MutableElement::reset_defaults();
}
void Element::binarywrite(FILE *file, char) const {
writebinary(file, intrinsic_gray);
}
void Element::oof2write(ostream &os) const {
os << "(" << corner[0]->index
<< ", " << corner[1]->index
<< ", " << corner[2]->index << ")";
}
ostream& operator<<(ostream& os, const Element& elem) {
os << elem.tag() << " i=" << elem.index;
for(int i=0; i<elem.corner.capacity(); i++) {
os << " n" + to_charstring(i+1) + "=" << elem.corner[i]->index;
}
os << " gray=" << elem.intrinsic_gray;
os << elem.parameters();
return os;
}
int Element::hashfunc(const MeshCoord &where, double &dist) {
if(contains(where)) {
dist = 0.0;
return 1;
}
else {
dist = 1.0;
return 0;
}
}
void Element::not_current() {
current_stress = TF_FALSE;
current_elastic_strain = TF_FALSE;
#ifdef THERMAL
current_J = TF_FALSE;
current_grad_thermal = TF_FALSE;
#endif // THERMAL
}
//-\\-//-\\-//-\\-//-\\-//-\\-//-\\-//-\\-//-\\-//-\\-//-\\-//-\\-//
double Element::elastic_energy() {
elastic_straintensor();
stresstensor();
double e = 0;
for(int i=0; i<3; i++) {
e += stress(i,i)*elastic_strain(i,i);
int j = (i+1)%3;
e += 2*stress(i,j)*elastic_strain(i,j);
}
return 0.5*e;
}
#ifdef THERMAL
double Element::thermal_energy() {
gradient_temperature_field(); //gradT has to have the right sign!!
heat_flux_field();
double e = 0;
for(int i=0; i<3; i++) {
e += J_field(i)*Grad_T_field(i);
}
return 0.5*e;
}
#endif
//-\\-//-\\-//-\\-//-\\-//-\\-//-\\-//-\\-//-\\-//-\\-//-\\-//-\\-//
EulerAngle Element::query_orientation() const
{
return EulerAngle();
}
//---------------
CharString newPropertyName() {
static int nprops = 0;
return "property" + to_charstring(++nprops);
}
std::vector<CharString> *Element::print_properties(ostream &os) const {
std::vector<CharString> *names = new std::vector<CharString>;
CharString colorname = newPropertyName();
names->push_back("Color:"+colorname);
os << "OOF.LoadData.Property.Color(name='" << colorname
<< "', color=Gray(value=" << intrinsic_gray << "))" << endl;
return names;
}
void Element::print_material(ostream &os, const CharString &matname) const
{
std::vector<CharString> *propnames = print_properties(os);
os << "OOF.LoadData.Material(name='" << matname << "', properties=[";
for(int i=0; i<propnames->size(); i++) {
os << "'" << (*propnames)[i] << "'";
if(i < propnames->size()-1)
os << ", ";
}
os << "])" << endl;
delete propnames;
}
bool Element::same_type(const Element *other) const {
return intrinsic_gray == other->intrinsic_gray;
}
bool operator==(const Element &el1, const Element &el2) {
return el1.tag() == el2.tag() && el1.same_type(&el2);
}
|
5f93d0622ca50f904776035cf67c934e4df4d8df
|
aa73b2ca43513f1eff53f7982f3ef2feffc0b52f
|
/qsbatch/qsbatch/Emitter.cpp
|
0f22bb849591b7bc6ea20964bb399c1c8ce0ffe6
|
[] |
no_license
|
Qwerber/q-dev-libs
|
9338d300584ee5ca95bb7358874d57e9db5cd8b2
|
56336b9eece6e23f799dd184eb9bfd72e453d4e9
|
refs/heads/master
| 2021-01-23T05:35:16.275988
| 2014-05-27T20:40:22
| 2014-05-27T20:40:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,254
|
cpp
|
Emitter.cpp
|
#include "stdafx.h"
#include "Emitter.h"
#include <stdlib.h>
#include "glbatch.h"
#include <Windows.h>
namespace kc8
{
Emitter2D* createEmitter(int _maxParticles)
{
Emitter2D* ret = (Emitter2D*)malloc(sizeof(Emitter2D));
ret->numParticles = 0;
ret->insertionPoint = 0;
ret->maxParticles = _maxParticles;
ret->particles = (Particle2D*)malloc(_maxParticles * sizeof(Particle2D));
ret->particleBatch = qsb::createBatch(5, _maxParticles * 6);
qsb::batch_setProgram(ret->particleBatch,
qsb::createProgram(
qsb::createShader(
GL_VERTEX_SHADER,
"#version 130\n"
"in vec2 LVertexPos2D;"
"in vec3 color;"
"out vec3 color_v;"
"uniform mat4 gl_ModelViewMatrix;"
"void main() {"
" color_v = color;"
" gl_Position = gl_ModelViewMatrix * vec4( LVertexPos2D.x, LVertexPos2D.y, 0, 1 ); "
"}"
),
qsb::createShader(
GL_FRAGMENT_SHADER,
"#version 130\n"
"in vec3 color_v;"
"out vec4 LFragment;"
"void main() { "
" LFragment = vec4(color_v.x, color_v.y, color_v.z, 1); "
"}"
)));
qsb::batch_generateAttributeData(ret->particleBatch, "LVertexPos2D{ff}color{fff}");
qsb::batch_PrintAttributeData(ret->particleBatch);
return ret;
}
void renderEmitter(Emitter2D* _emitter)
{
unsigned int t = GetTickCount();
qsb::Batch* b = _emitter->particleBatch;
int ind = 0;
int i = _emitter->numParticles;
while (i--)
{
Vector2D p = _emitter->particles[i].position;
qsb::batch_pushVertData(b, p.x);
qsb::batch_pushVertData(b, p.y);
qsb::batch_pushVertData(b, 1);
qsb::batch_pushVertData(b, 1);
qsb::batch_pushVertData(b, 0);
qsb::batch_pushVertData(b, p.x + 20);
qsb::batch_pushVertData(b, p.y);
qsb::batch_pushVertData(b, 1);
qsb::batch_pushVertData(b, 1);
qsb::batch_pushVertData(b, 0);
qsb::batch_pushVertData(b, p.x);
qsb::batch_pushVertData(b, p.y + 20);
qsb::batch_pushVertData(b, 1);
qsb::batch_pushVertData(b, 1);
qsb::batch_pushVertData(b, 0);
qsb::batch_pushVertData(b, p.x + 20);
qsb::batch_pushVertData(b, p.y + 20);
qsb::batch_pushVertData(b, 1);
qsb::batch_pushVertData(b, 1);
qsb::batch_pushVertData(b, 0);
qsb::batch_pushQuadIndex(b);
}
printf("main: %u\n", GetTickCount() - t);
qsb::drawBatch(b);
qsb::batch_reset(b);
}
void emitParticles(Emitter2D* _emitter, int _numParticles, Vector2D _position, Vector2D _velocity)
{
{
int i = 0;
while (i < _numParticles)
{
pushParticle(_emitter, _position, _velocity);
i++;
}
}
}
void pushParticle(Emitter2D* _emitter, Vector2D _position, Vector2D _velocity)
{
int ins = _emitter->insertionPoint;
if (ins == _emitter->maxParticles)
_emitter->insertionPoint = ins = 0;
//fix this later
_emitter->particles[ins].acceleration = { 0, 0.002 };
_emitter->particles[ins].position = _position;
_emitter->particles[ins].velocity = _velocity;
_emitter->insertionPoint++;
_emitter->numParticles++;
}
void updateEmitter(Emitter2D* _emitter)
{
int i = _emitter->numParticles;
while (i--)
{
particle2d_update(&(_emitter->particles[i]));
}
}
}
|
e13680b0d715d6d80391df1b023ac8e8cf9d7053
|
2a7ae23b00e01b84c3a57db75c2727ffac916e8a
|
/editor/src/AssimpImporter.h
|
291bbafae3f31d7ef8f9d9e49ad2dc41e8cc456b
|
[] |
no_license
|
aavci1/SimpleGL
|
0675e60f5c51ddd53d2b3b87c2c4e4d58d9e7a4b
|
7f63198776eb039d8c5073966d4accfffbeac76e
|
refs/heads/master
| 2021-05-05T20:48:31.394186
| 2017-12-21T03:49:22
| 2017-12-21T03:49:22
| 115,467,532
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 197
|
h
|
AssimpImporter.h
|
#ifndef ASSIMPIMPORTER_H
#define ASSIMPIMPORTER_H
#include "Types.h"
namespace AssimpImporter {
SimpleGL::ModelPtr import(const string &name, const string &path);
}
#endif // ASSIMPIMPORTER_H
|
7ad6d7fa856e5542ccbf041987dc109ab9d3619e
|
0eff74b05b60098333ad66cf801bdd93becc9ea4
|
/second/download/squid/gumtree/squid_repos_function_1011_last_repos.cpp
|
29c967b8193812575b6b31b8e429e139049a2bd4
|
[] |
no_license
|
niuxu18/logTracker-old
|
97543445ea7e414ed40bdc681239365d33418975
|
f2b060f13a0295387fe02187543db124916eb446
|
refs/heads/master
| 2021-09-13T21:39:37.686481
| 2017-12-11T03:36:34
| 2017-12-11T03:36:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 959
|
cpp
|
squid_repos_function_1011_last_repos.cpp
|
static void
peerGetAllParents(ps_state * ps)
{
CachePeer *p;
HttpRequest *request = ps->request;
/* Add all alive parents */
for (p = Config.peers; p; p = p->next) {
/* XXX: neighbors.c lacks a public interface for enumerating
* parents to a request so we have to dig some here..
*/
if (neighborType(p, request->url) != PEER_PARENT)
continue;
if (!peerHTTPOkay(p, request))
continue;
debugs(15, 3, "peerGetAllParents: adding alive parent " << p->host);
peerAddFwdServer(&ps->servers, p, ANY_OLD_PARENT);
}
/* XXX: should add dead parents here, but it is currently
* not possible to find out which parents are dead or which
* simply are not configured to handle the request.
*/
/* Add default parent as a last resort */
if ((p = getDefaultParent(request))) {
peerAddFwdServer(&ps->servers, p, DEFAULT_PARENT);
}
}
|
3a55173872ffab2db95d9d3d7f612cdbbfaf29ce
|
86500db7a7f5b82602839c3365f2079ac6cbe8c1
|
/lattice/lattice.cpp
|
4cc7fcd6c7521dec5df8a999b8753c4131c9f143
|
[] |
no_license
|
friedvan/lattice
|
53ee1f5a452a49b149529b6ff1ca67bd2c8d324e
|
92839daab1814bad38bedca8633ef4ba7702b675
|
refs/heads/master
| 2016-09-06T06:31:59.771558
| 2014-01-14T08:33:32
| 2014-01-14T08:33:32
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,237
|
cpp
|
lattice.cpp
|
#include "lattice.h"
#include "visual.h"
node *A, *B;//[N][N], B[N][N];
node* init()
{
node *G = (node*)malloc(sizeof(node) * N * N);
if (G == NULL) {
printf("momory error\n");
exit(0);
}
for (int i=0; i<N; i++)
for (int j=0; j<N; j++) {
G[i * N + j].inter.x = i;
G[i * N + j].inter.y = j;
////set default inter node to a non-exsit node.
//G[i * N + j].inter.y = -1;
//G[i * N + j].inter.x = -1;
G[i * N + j].base[0].x = (N + i - 1) % N;
G[i * N + j].base[0].y = j;
G[i * N + j].base[1].x = (N + i + 1) % N;
G[i * N + j].base[1].y = j;
G[i * N + j].base[2].x = i;
G[i * N + j].base[2].y = (N + j - 1) % N;
G[i * N + j].base[3].x = i;
G[i * N + j].base[3].y = (N + j + 1) % N;
G[i * N + j].alive = true;
G[i * N + j].cluster = 0;
G[i * N + j].type = MONOMER;
}
return G;
}
void shuffle(point* random_list, int length)
{
point temp;
int i, j;
//srand(time(NULL));
for (i=0; i<length; i++) {
j = rand() % length;
temp = random_list[i];
random_list[i] = random_list[j];
random_list[j] = temp;
}
}
int get_rand_list(point** plist, double c)
{
bool rand_flag[N*N];
int rand_count=0;
//srand(time(NULL));
for (int i=0; i<N; i++) {
for (int j=0; j<N; j++) {
double r = (double)rand() / RAND_MAX;
if (r < c) {
rand_flag[i*N+j] = true;
rand_count ++;
} else {
rand_flag[i*N+j] = false;
}
}
}
*plist = (point*)malloc(sizeof(point) * rand_count * 2);//rand_list and rand_copy
if (*plist == NULL)
return 0;
int k = 0;
for (int i=0; i<N; i++) {
for (int j=0; j<N; j++) {
if (rand_flag[i*N+j]) {
(*plist)[k].x = i;
(*plist)[k].y = j;
k++;
}
}
}
return rand_count;
}
void release(point *list)
{
if (list != NULL) {
free(list);
list = NULL;
}
}
gcsize get_size(node *G)
{
gcsize s;
memset(&s, 0, sizeof(s));
for (int i=0; i<N; i++)
for (int j=0; j<N; j++)
{
if (G[i*N+j].alive)
{
s.maxsize++;
if (G[i*N+j].type==MONOMER)
s.monosize++;
else
s.dimersize++;
}
}
return s;
}
void network(point* rand_list, point* rand_copy, int rand_len)
{
for (int i=0; i<rand_len; i++) {
point pta, ptb;
pta = rand_list[i];
ptb = rand_copy[i];
A[pta.x * N + pta.y].inter = ptb;
A[pta.x * N + pta.y].type = DIMER;
B[ptb.x * N + ptb.y].inter = pta;
B[ptb.x * N + ptb.y].type = DIMER;
}
}
void init_attack(double p)
{
srand(rand());
for (int i=0; i<N; i++)
for (int j=0; j<N; j++) {
double r = (double)rand() / RAND_MAX;
if (r < p) {
A[i*N+j].alive = false;
point inter = A[i*N+j].inter;
//if has interdependent node
if (inter.x != -1 && inter.y != -1)
B[inter.x*N+inter.y].alive = false;
}
}
//img_print(A, true);
//img_print(B, false);
}
int dfs(node *G, point pt, int lable)
{
int size = 1;
stack st, *ps=&st;
stack_init(ps);
stack_push(ps, pt);
while (stack_len(ps) != 0) {
point tmp = *(ps->tail);
node *top = G+tmp.x*N+tmp.y;
if (!top->alive)
continue;
top->cluster = lable;
bool changed = false;
for (int i=0; i<LATTICE; i++) {
node *neighbor = G + top->base[i].x * N + top->base[i].y;
if(neighbor->alive && neighbor->cluster == 0) {//alive and not visited
neighbor->cluster = lable;
size++;
stack_push(ps, top->base[i]);
changed = true;
}
}
if (!changed)
stack_pop(ps);
}
stack_release(ps);
return size;
}
void gaint_component(node *G1, node *G2)
{
int lable = 1;
point pt;
int maxsize = 0, maxcluster = -1, size = 0;//, monosize=0, dimersize=0;
for (int i=0; i<N && size <= N*N/2+1; i++) {
for (int j=0; j<N && size <= N*N/2+1; j++) {
pt.x = i;
pt.y = j;
if (G1[i*N+j].alive && G1[i*N+j].cluster == 0) {//alive and not visited.
size = dfs(G1, pt, lable);
if (size > maxsize) {
maxcluster = lable;
maxsize = size;
}
lable++;
}
}
}
for (int i=0; i<N; i++) {
for (int j=0; j<N; j++) {
if (G1[i*N+j].alive) {
if (G1[i*N+j].cluster != maxcluster){
G1[i*N+j].alive = false;
//if has interdependent node
if (G1[i*N + j].inter.x != -1 && G1[i*N + j].inter.y != -1)
G2[G1[i*N + j].inter.x*N + G1[i*N + j].inter.y].alive = false;
//img_print(A, true);
//img_print(B, false);
}
G1[i*N+j].cluster = 0;
}
}
}
}
int main()
{
//
//img_init();
//
srand(time(NULL));
FILE *fp = fopen("data/result.dat", "w");
for (double c=0.0; c<=1.0; c+=0.1) {
for (double p=0.01; p<=1.0; p+=0.01) {
for (int k=0; k<NSAMPLE; k++) {
gcsize s;
point* rand_list = NULL;
point* rand_copy = NULL;
int rand_len = 0;
A = init();
B = init();
rand_len = get_rand_list(&rand_list, c);
rand_copy = (point*)malloc(sizeof(point) * rand_len);
memcpy(rand_copy, rand_list, sizeof(point) * rand_len);
shuffle(rand_copy, rand_len);
network(rand_list, rand_copy, rand_len);
release(rand_copy);
release(rand_list);
init_attack(p);
int pre_cluster_size = 0, cluster_size = 0;
int iter = 0;
gcsize s1, s2;
memset(&s1, 0, sizeof(s1));
memset(&s2, 0, sizeof(s2));
while (1) {
iter++;
gaint_component(A, B);
s1 = get_size(A);
s2 = get_size(B);
fprintf(fp, "%f\t%f\t%c\t%d\t%d\t%d\t%d\n", c, p, 'A', s1.dimersize, s1.maxsize, s2.dimersize , s2.maxsize);
s=get_size(A);
//img_print(A, true);
cluster_size = s.maxsize;
if (cluster_size == pre_cluster_size)
break;
pre_cluster_size = cluster_size;
gaint_component(B, A);
s1 = get_size(A);
s2 = get_size(B);
fprintf(fp, "%f\t%f\t%c\t%d\t%d\t%d\t%d\n", c, p, 'B', s1.dimersize, s1.maxsize, s2.dimersize, s2.maxsize);
//img_print(B, false);
break;
}
s=get_size(A);
//fprintf(fp, "%d\t%f\t%f\t%d\t%d\t%d\t%d\n", k, c, p, cluster_size, s.monosize, s.dimersize, iter);
free(A);
free(B);
}
printf("%.3f\t%.3f\n", c, p);
}
}
fclose(fp);
//
//img_destroy();
//
}
|
8cf245323d1690cc10d23f0dabf79c71c27bc156
|
98754ad9f9fe49a33eb370402f1bae77cf410741
|
/Sourcestream/Hackerearth/Kriti and her Birthday Gift/source.cpp
|
ee8c7e6621a9f5b19dcd5010ae7c0b59f9c07a9d
|
[] |
no_license
|
hitch-hiker42/hikes
|
1e9d0ff767e9a53de52d510a8480644322fcab3c
|
e8b78a3d5ecfe63e9e48b97edaae3a101fd304ec
|
refs/heads/master
| 2021-08-05T10:32:08.901447
| 2021-07-28T20:04:18
| 2021-07-28T20:04:18
| 242,496,162
| 4
| 3
| null | 2020-02-23T13:11:12
| 2020-02-23T10:21:14
|
C++
|
UTF-8
|
C++
| false
| false
| 1,692
|
cpp
|
source.cpp
|
//author: hitch_hiker42;
#include<bits/stdc++.h>
using namespace std;
//solution:
#define int int64_t
#define block(i) i / B
constexpr int N = 100'000, B = 316, p = 31, mod = 1000'000'009;
string a[N]; int ans[N];
struct query {
string s;
int lo, hi, idx;
query() {}
query(int lo, int hi, int idx): lo(lo), hi(hi), idx(idx) {}
bool operator < (const query& q) {
return block(lo) < block(q.lo) || (block(lo) == block(q.lo) and hi < q.hi);
}
} q[N];
int rollhash(string const& s) {
int hash = 0, x = 1;
for(const char& c: s) {
(hash += (c - 'a' + 1) * x % mod) %= mod;
x = x * p % mod;
}
return hash;
}
struct custom {
size_t operator () (const string& s) const {
return rollhash(s);
}
};
bool equal(const string& s, const string& t) {
return !(s.compare(t));
}
signed main() {
int n; cin >> n;
for(int i = 0; i < n; ++i) cin >> a[i];
int m; cin >> m;
for(int i = 0; i < m; ++i) {
cin >> q[i].lo >> q[i].hi >> q[i].s;
q[i].lo--; q[i].hi--; q[i].idx = i;
}
sort(q, q + m);
unordered_map<string, int, custom> f;
auto insert = [&](int i, string s) {
f[a[i]]++;
};
auto remove = [&](int i, string s) {
f[a[i]]--;
};
int l = 0, r = -1;
for(int i = 0; i < m; ++i) {
int lo = q[i].lo, hi = q[i].hi;
string s = q[i].s;
while(lo < l) insert(--l, s);
while(r < hi) insert(++r, s);
while(lo > l) remove(l++, s);
while(r > hi) remove(r--, s);
ans[q[i].idx] = f[s];
}
for(int i = 0; i < m; ++i) cout << ans[i] << "\n";
return 0;
} //farewell, until we meet again..
|
2aca597b04ac982880662a98dd2b0917e71b1bba
|
89fc5b243d34612ba90e1d1649387907e29d90ac
|
/Laying Cables.cpp
|
7dccf8346fd0019e9cb39cfa3caaabc3d22e778a
|
[] |
no_license
|
Misaka233/exciting
|
8a074bf0924476c067a1965c6ea9a6dc1ad77d75
|
069455bb92560ceee47add71e1743f0d36c8cd10
|
refs/heads/master
| 2020-04-12T09:01:27.313535
| 2017-02-03T08:28:37
| 2017-02-03T08:28:37
| 55,968,227
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,245
|
cpp
|
Laying Cables.cpp
|
#include<bits/stdc++.h>
using namespace std;
const int N = 1e6+20, M = 1e6+10, mod = 1e9+7, inf = 2e9;
typedef long long ll;
int n,ans[N];
struct ss{long long x,p;int id;}a[N],lefts[N],rights[N];
vector<ss> G;
bool cmp(ss s1,ss s2) {return s1.x<s2.x;}
int main(){
scanf("%d",&n);
for(int i=1;i<=n;i++) scanf("%I64d%I64d",&a[i].x,&a[i].p),a[i].id = i;
sort(a+1,a+n+1,cmp);
a[0].x=-inf, a[0].p = inf; a[0].id = -1;
G.push_back(a[0]);
for(int i=1;i<=n;i++) {
while(G.back().p<=a[i].p) G.pop_back();
lefts[i]=G.back();
G.push_back(a[i]);
}
G.clear();
a[n+1] = (ss) {inf,inf,-1};
G.push_back(a[n+1]);
for(int i=n;i>=1;i--) {
while(G.back().p<=a[i].p) G.pop_back();
rights[i]=G.back();
G.push_back(a[i]);
}
for(int i=1;i<=n;i++) {
if(abs(lefts[i].x-a[i].x)==abs(rights[i].x-a[i].x)) {
if(lefts[i].p>rights[i].p) ans[a[i].id] = lefts[i].id;
else ans[a[i].id] = rights[i].id;
}
else if(abs(lefts[i].x-a[i].x)<abs(rights[i].x-a[i].x)) {
ans[a[i].id] = lefts[i].id;
}
else ans[a[i].id] = rights[i].id;
}
for(int i=1;i<=n;i++) printf("%d ",ans[i]);
printf("\n");
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.