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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
be40cfe67bd6b5412efc5f2bb9214b9dfedc651a
|
7e48d392300fbc123396c6a517dfe8ed1ea7179f
|
/RodentVR/Intermediate/Build/Win64/RodentVR/Inc/TemplateSequence/TemplateSequenceActor.generated.h
|
7cf7d8b5f9425d9939c2beeaff5223cf8ccfc7d2
|
[] |
no_license
|
WestRyanK/Rodent-VR
|
f4920071b716df6a006b15c132bc72d3b0cba002
|
2033946f197a07b8c851b9a5075f0cb276033af6
|
refs/heads/master
| 2021-06-14T18:33:22.141793
| 2020-10-27T03:25:33
| 2020-10-27T03:25:33
| 154,956,842
| 1
| 1
| null | 2018-11-29T09:56:21
| 2018-10-27T11:23:11
|
C++
|
UTF-8
|
C++
| false
| false
| 7,406
|
h
|
TemplateSequenceActor.generated.h
|
// Copyright Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/ObjectMacros.h"
#include "UObject/ScriptMacros.h"
PRAGMA_DISABLE_DEPRECATION_WARNINGS
class AActor;
class UTemplateSequencePlayer;
class UTemplateSequence;
#ifdef TEMPLATESEQUENCE_TemplateSequenceActor_generated_h
#error "TemplateSequenceActor.generated.h already included, missing '#pragma once' in TemplateSequenceActor.h"
#endif
#define TEMPLATESEQUENCE_TemplateSequenceActor_generated_h
#define Engine_Plugins_MovieScene_TemplateSequence_Source_TemplateSequence_Public_TemplateSequenceActor_h_20_GENERATED_BODY \
friend struct Z_Construct_UScriptStruct_FTemplateSequenceBindingOverrideData_Statics; \
TEMPLATESEQUENCE_API static class UScriptStruct* StaticStruct();
template<> TEMPLATESEQUENCE_API UScriptStruct* StaticStruct<struct FTemplateSequenceBindingOverrideData>();
#define Engine_Plugins_MovieScene_TemplateSequence_Source_TemplateSequence_Public_TemplateSequenceActor_h_41_SPARSE_DATA
#define Engine_Plugins_MovieScene_TemplateSequence_Source_TemplateSequence_Public_TemplateSequenceActor_h_41_RPC_WRAPPERS \
\
DECLARE_FUNCTION(execSetBinding); \
DECLARE_FUNCTION(execGetSequencePlayer); \
DECLARE_FUNCTION(execSetSequence); \
DECLARE_FUNCTION(execLoadSequence); \
DECLARE_FUNCTION(execGetSequence);
#define Engine_Plugins_MovieScene_TemplateSequence_Source_TemplateSequence_Public_TemplateSequenceActor_h_41_RPC_WRAPPERS_NO_PURE_DECLS \
\
DECLARE_FUNCTION(execSetBinding); \
DECLARE_FUNCTION(execGetSequencePlayer); \
DECLARE_FUNCTION(execSetSequence); \
DECLARE_FUNCTION(execLoadSequence); \
DECLARE_FUNCTION(execGetSequence);
#define Engine_Plugins_MovieScene_TemplateSequence_Source_TemplateSequence_Public_TemplateSequenceActor_h_41_INCLASS_NO_PURE_DECLS \
private: \
static void StaticRegisterNativesATemplateSequenceActor(); \
friend struct Z_Construct_UClass_ATemplateSequenceActor_Statics; \
public: \
DECLARE_CLASS(ATemplateSequenceActor, AActor, COMPILED_IN_FLAGS(0 | CLASS_Config), CASTCLASS_None, TEXT("/Script/TemplateSequence"), NO_API) \
DECLARE_SERIALIZER(ATemplateSequenceActor) \
virtual UObject* _getUObject() const override { return const_cast<ATemplateSequenceActor*>(this); } \
void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override; \
enum class ENetFields_Private : uint16 \
{ \
NETFIELD_REP_START=(uint16)((int32)Super::ENetFields_Private::NETFIELD_REP_END + (int32)1), \
SequencePlayer=NETFIELD_REP_START, \
NETFIELD_REP_END=SequencePlayer }; \
NO_API virtual void ValidateGeneratedRepEnums(const TArray<struct FRepRecord>& ClassReps) const override;
#define Engine_Plugins_MovieScene_TemplateSequence_Source_TemplateSequence_Public_TemplateSequenceActor_h_41_INCLASS \
private: \
static void StaticRegisterNativesATemplateSequenceActor(); \
friend struct Z_Construct_UClass_ATemplateSequenceActor_Statics; \
public: \
DECLARE_CLASS(ATemplateSequenceActor, AActor, COMPILED_IN_FLAGS(0 | CLASS_Config), CASTCLASS_None, TEXT("/Script/TemplateSequence"), NO_API) \
DECLARE_SERIALIZER(ATemplateSequenceActor) \
virtual UObject* _getUObject() const override { return const_cast<ATemplateSequenceActor*>(this); } \
void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override; \
enum class ENetFields_Private : uint16 \
{ \
NETFIELD_REP_START=(uint16)((int32)Super::ENetFields_Private::NETFIELD_REP_END + (int32)1), \
SequencePlayer=NETFIELD_REP_START, \
NETFIELD_REP_END=SequencePlayer }; \
NO_API virtual void ValidateGeneratedRepEnums(const TArray<struct FRepRecord>& ClassReps) const override;
#define Engine_Plugins_MovieScene_TemplateSequence_Source_TemplateSequence_Public_TemplateSequenceActor_h_41_STANDARD_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API ATemplateSequenceActor(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(ATemplateSequenceActor) \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, ATemplateSequenceActor); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(ATemplateSequenceActor); \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API ATemplateSequenceActor(ATemplateSequenceActor&&); \
NO_API ATemplateSequenceActor(const ATemplateSequenceActor&); \
public:
#define Engine_Plugins_MovieScene_TemplateSequence_Source_TemplateSequence_Public_TemplateSequenceActor_h_41_ENHANCED_CONSTRUCTORS \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API ATemplateSequenceActor(ATemplateSequenceActor&&); \
NO_API ATemplateSequenceActor(const ATemplateSequenceActor&); \
public: \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, ATemplateSequenceActor); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(ATemplateSequenceActor); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(ATemplateSequenceActor)
#define Engine_Plugins_MovieScene_TemplateSequence_Source_TemplateSequence_Public_TemplateSequenceActor_h_41_PRIVATE_PROPERTY_OFFSET
#define Engine_Plugins_MovieScene_TemplateSequence_Source_TemplateSequence_Public_TemplateSequenceActor_h_34_PROLOG
#define Engine_Plugins_MovieScene_TemplateSequence_Source_TemplateSequence_Public_TemplateSequenceActor_h_41_GENERATED_BODY_LEGACY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
Engine_Plugins_MovieScene_TemplateSequence_Source_TemplateSequence_Public_TemplateSequenceActor_h_41_PRIVATE_PROPERTY_OFFSET \
Engine_Plugins_MovieScene_TemplateSequence_Source_TemplateSequence_Public_TemplateSequenceActor_h_41_SPARSE_DATA \
Engine_Plugins_MovieScene_TemplateSequence_Source_TemplateSequence_Public_TemplateSequenceActor_h_41_RPC_WRAPPERS \
Engine_Plugins_MovieScene_TemplateSequence_Source_TemplateSequence_Public_TemplateSequenceActor_h_41_INCLASS \
Engine_Plugins_MovieScene_TemplateSequence_Source_TemplateSequence_Public_TemplateSequenceActor_h_41_STANDARD_CONSTRUCTORS \
public: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#define Engine_Plugins_MovieScene_TemplateSequence_Source_TemplateSequence_Public_TemplateSequenceActor_h_41_GENERATED_BODY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
Engine_Plugins_MovieScene_TemplateSequence_Source_TemplateSequence_Public_TemplateSequenceActor_h_41_PRIVATE_PROPERTY_OFFSET \
Engine_Plugins_MovieScene_TemplateSequence_Source_TemplateSequence_Public_TemplateSequenceActor_h_41_SPARSE_DATA \
Engine_Plugins_MovieScene_TemplateSequence_Source_TemplateSequence_Public_TemplateSequenceActor_h_41_RPC_WRAPPERS_NO_PURE_DECLS \
Engine_Plugins_MovieScene_TemplateSequence_Source_TemplateSequence_Public_TemplateSequenceActor_h_41_INCLASS_NO_PURE_DECLS \
Engine_Plugins_MovieScene_TemplateSequence_Source_TemplateSequence_Public_TemplateSequenceActor_h_41_ENHANCED_CONSTRUCTORS \
public: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
template<> TEMPLATESEQUENCE_API UClass* StaticClass<class ATemplateSequenceActor>();
#undef CURRENT_FILE_ID
#define CURRENT_FILE_ID Engine_Plugins_MovieScene_TemplateSequence_Source_TemplateSequence_Public_TemplateSequenceActor_h
PRAGMA_ENABLE_DEPRECATION_WARNINGS
|
7866d68ebd2ea0c47d85077a58184aae29ae1840
|
6627d27fc69922f179b14b612b366bbf0bc4eff9
|
/old/robots/claymore/util/pwm_transcriber.h
|
a16d3b52e94f30d52cb718ffe54c69dc63a2927a
|
[] |
no_license
|
errorcodexero/newarch
|
1a4773377197174ae58b6e4ef6d670bf197c643b
|
e69a864012e09548014ad208affeb8901835a654
|
refs/heads/master
| 2021-06-03T16:28:41.840622
| 2020-03-15T18:15:08
| 2020-03-15T18:15:08
| 139,747,384
| 9
| 6
| null | 2020-01-31T05:35:34
| 2018-07-04T16:54:36
|
C++
|
UTF-8
|
C++
| false
| false
| 4,130
|
h
|
pwm_transcriber.h
|
#ifndef PWM_TRANSCRIBER_H
#define PWM_TRANSCRIBER_H
#include <map>
#include <set>
#include <iostream>
#include <cassert>
#include <cmath>
class PWM_transcriber{ //This class is used to manage conversion of a data set to unique PWM values for transmission
private:
class Transcriber_base{//This class is used to represent a transcriber of any type
private:
virtual int operator()(const void*)const = 0;
public:
virtual void print(std::ostream&)const = 0;
virtual ~Transcriber_base(){}
};
public:
template<typename T>
class Transcriber: public Transcriber_base{//This class is used to define transcription for a specific subset of data
private:
std::map<T,int> transcriptions;
int operator()(const void* key_ptr)const{//converts a value to an integer value that can later easily be mapped to a PWM value
T* typed_key_ptr = (T*)key_ptr;
T key = *typed_key_ptr;
if(transcriptions.find(key) == transcriptions.end()){
std::cout<<__FILE__<<":"<<__LINE__<<": Warning: no transcriber found with name \""<<key<<"\""<<std::endl;
}
return transcriptions.at(key);
}
public:
int operator()(const T& key)const{//converts a value to an integer value that can later easily be mapped to a PWM value
const T* key_ptr = &key;
return (*this)(key_ptr);
}
void print(std::ostream& o)const{
for(auto i = transcriptions.begin(); i != transcriptions.end(); i++){
o<<"["<<i->first<<" => "<<i->second<<"]";
auto second_to_last = transcriptions.end();
second_to_last--;
if(i != second_to_last){
o<<" ";
}
}
}
Transcriber(unsigned& highest_unassigned_value, std::set<T> keys){
for(T k: keys){
transcriptions.insert(std::pair<T,int>(k,highest_unassigned_value));
highest_unassigned_value++;
}
}
};
private:
unsigned highest_unassigned_value;//used to track values assigned to each value in a data subset and ensure that each is unique
std::map<std::string, Transcriber_base*> all_transcriptions; //stores and manages all defined transcriptions
public:
template<typename T>
int map(const std::string NAME, const T& KEY)const{//maps a value of a given subset to its assigned integer value
if(all_transcriptions.find(NAME) == all_transcriptions.end()){
std::cout<<__FILE__<<":"<<__LINE__<<": Warning: no transcriber found with name \""<<NAME<<"\""<<std::endl;
}
const Transcriber<T>* transcriber_ptr = (Transcriber<T>*)all_transcriptions.at(NAME);
Transcriber<T> transcriber = *transcriber_ptr;
return transcriber(KEY);
}
template<typename T>
double transcribe(const std::string NAME, const T& KEY)const{//transcribes a given value of a specific subset to a PWM value
int value = map(NAME, KEY);
const double PWM_RANGE = 2.0;
const double PWM_INCREMENT = PWM_RANGE / (double)highest_unassigned_value;
const double STARTING_PWM_VALUE = -1.0;
return STARTING_PWM_VALUE + PWM_INCREMENT * value; //convert the integer transmission value to a pwm valu
};
template<typename T>
void add(const std::string NAME,const std::set<T>& KEYS){//used to define a new subset of values given its name and a set of all possible values
if(all_transcriptions.find(NAME) != all_transcriptions.end()){
std::cout<<__FILE__<<":"<<__LINE__<<":"<<" Error: transcriber already set with name \""<<NAME<<"\""<<std::endl;
exit(0);
}
all_transcriptions.insert(std::pair<std::string,Transcriber_base*>(NAME, (Transcriber_base*)(new Transcriber<T>(highest_unassigned_value,KEYS))));
}
friend std::ostream& operator<<(std::ostream& o, const PWM_transcriber& a) {
o<<"{";
for(auto i = a.all_transcriptions.begin(); i != a.all_transcriptions.end(); i++){
o<<i -> first<<": ";
auto t = i -> second;
t -> print(o);
auto second_to_last = a.all_transcriptions.end();
second_to_last--;
if(i != second_to_last){
o<<", ";
}
}
o<<"}";
return o;
}
PWM_transcriber():highest_unassigned_value(0){}
};
template<typename T>
std::ostream& operator<<(std::ostream& o, const PWM_transcriber::Transcriber<T>& a){
a.print(o);
return o;
}
#endif
|
7da0fc1860a27a85007c253510f7db6d75ed4e09
|
83aca81ee006fb1b4b965e746786e5276d218cb6
|
/2018/include/maya/MStreamUtils.h
|
a568f33f3e30b77c4260293879f2390cbc0ac359
|
[] |
no_license
|
smart-tai/maya_SDK
|
cef4d73b812d294ad44e89b714b46c18929965e1
|
9549d16c028880f2c4735b7b371ca8bc427a7d0e
|
refs/heads/master
| 2023-02-23T03:25:12.113515
| 2020-03-21T08:29:17
| 2020-03-21T08:29:17
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,345
|
h
|
MStreamUtils.h
|
#ifndef _MStreamUtils
#define _MStreamUtils
//-
// ===========================================================================
// Copyright 2017 Autodesk, Inc. All rights reserved.
//
// Use of this software is subject to the terms of the Autodesk license
// agreement provided at the time of installation or download, or which
// otherwise accompanies this software in either electronic or hard copy form.
// ===========================================================================
//+
//
// CLASS: MStreamUtils
//
// ****************************************************************************
#if defined __cplusplus
// ****************************************************************************
// INCLUDED HEADER FILES
#include <maya/MIOStreamFwd.h>
#include <maya/MApiNamespace.h>
OPENMAYA_MAJOR_NAMESPACE_OPEN
// ****************************************************************************
// CLASS DECLARATION (MStreamUtils)
//! \ingroup OpenMaya
//! \brief Stream functionality.
/*!
This class provides some standard stream functionality for developers
working in C++ or script. Write methods are provided for writing to
ASCII or binary. Read methods are only binary.
*/
class OPENMAYA_EXPORT MStreamUtils
{
public:
static std::ostream& stdErrorStream();
static std::ostream& stdOutStream();
static MStatus writeChar( std::ostream& out, const char value, bool binary = false );
static MStatus writeCharBuffer( std::ostream& out, const char* value, bool binary = false );
static MStatus writeInt( std::ostream& out, const int value, bool binary = false );
static MStatus writeFloat( std::ostream& out, const float value, bool binary = false );
static MStatus writeDouble( std::ostream& out, const double value, bool binary = false );
static MStatus readChar( std::istream& in, char& value, bool binary = false );
static MStatus readCharBuffer( std::istream& in, char*& value, unsigned int length, bool binary = false );
static MStatus readInt( std::istream& in, int& value, bool binary = false );
static MStatus readFloat( std::istream& in, float& value, bool binary = false );
static MStatus readDouble( std::istream& in, double& value, bool binary = false );
protected:
// No protected members
private:
// No protected members
};
OPENMAYA_NAMESPACE_CLOSE
#endif // __cplusplus
#endif // _MStreamUtils
|
b44e7b50ecb6012baeb06186bb598a1aed2cdbf4
|
9dadd5a4d77ccf063374c758c15e4ab8c8eba76d
|
/Delays.hpp
|
a5e9dd6f8ca3c5b229ce955b219ae5722c09c02b
|
[] |
no_license
|
thomasmaters/A2B-Applicatie
|
efd1f7cb63a1fd18c685e34f994ab1d12600eb63
|
089c09b1cd8049c9207ec2938328c5e68983eb81
|
refs/heads/master
| 2021-01-10T02:35:06.692442
| 2015-10-06T13:12:16
| 2015-10-06T13:12:16
| 43,670,436
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 414
|
hpp
|
Delays.hpp
|
#ifndef DELAYS_H
#define DELAYS_H
#include <string>
#include <vector>
#include <list>
#include <iostream>
#include <assert.h>
#include "TrafficData.hpp"
class Delays : public TrafficData
{
public:
Delays():
TrafficData(),
delay(0),
startTime(0)
{};
Delays(const Delays& aDelays):
TrafficData(),
delay(0),
startTime(0)
{};
virtual ~Delays(){};
private:
long delay;
long startTime;
};
#endif
|
d195a0e0ddda40ac3868d1f0319bc634c704e3ba
|
772fa05727dab9f9ee4bf8ae7ba21226b70e7117
|
/practice/priority queue/test.cpp
|
5ee1b115ac9a6824f603ee90d58d8b103901ccc1
|
[] |
no_license
|
harshrajdhote/programs
|
b0692271dac6371211222b0a8a560df49907a23a
|
aab92d219ef353cce8cf97a36e5b8cc2f2826ab4
|
refs/heads/master
| 2021-07-10T14:13:20.251029
| 2020-11-01T15:01:11
| 2020-11-01T15:01:11
| 203,723,595
| 3
| 2
| null | 2020-08-14T08:07:16
| 2019-08-22T05:53:12
|
Python
|
UTF-8
|
C++
| false
| false
| 83
|
cpp
|
test.cpp
|
#include<stdio.h>
int main(){
while(1){
int *a = new int[1000];
}
}
|
3f4c64066151088805ee9af7a1a57a57f59cd2a2
|
0f9ca909d2aeb502a3c8368123410c29426bb4ce
|
/L_Piece.h
|
9557adb71da00497dd09e6c659bea51322a9d836
|
[] |
no_license
|
Hami0095/Tetris-Game_Console_Game
|
0f1da4effc28622fbccc2e6915db57ff2a738246
|
13b40b922370149918ee6cc0e6eba7ba8018ec1d
|
refs/heads/main
| 2023-02-13T10:46:53.560002
| 2021-01-03T19:30:26
| 2021-01-03T19:30:26
| 326,365,183
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 946
|
h
|
L_Piece.h
|
#ifndef L_PIECE_H
#define L_PIECE_H
#include<iostream>
#include"Block_Class.h"
using namespace std;
class L_Piece :
public Block
{
private:
friend class Board;
public:
L_Piece();
// _____________Completed_____________
// complete pack for the movement of the piece :)
void move(string, Board&);
//_______________
// MoveRight function
void moveRight(Board&);
void moveLeft(Board&);
void moveDown(Board&);
// Shifting PieceToBoard
void shiftPieceToBoard(Board&);
// ____________COMPLETED_______________________
// check for movements
bool canItMoveRight(Board&);
bool canItMoveLeft(Board&);
bool canItMoveDown(Board&);
// ____________ COMPLETED_______
//Last row per pohanch gya ha?
bool lastRowPerPohanchGyaHa(Board&);
// ____________ COMPLETED_______
//rotation:
void rotation(Board&);
bool canItRotate(Board&);
// ____________ COMPLETED_______
};
#endif
|
e49c73148014fd08d53276877f24f163b503688a
|
1e78e98969b6f530f7e4dcc310de957dbd805af3
|
/midistance/PeriodicityCheck.cpp
|
3c7ff20d9c8b166dcf6287ddabcead8335428922
|
[] |
no_license
|
blyw/g96x.hdf5
|
748fb90bcd5af25add4a80bf25ad99da8c887f2f
|
1a83406b05666c2e08b7b50cce0adbdef8ebdf06
|
refs/heads/master
| 2021-01-17T11:38:19.092745
| 2015-03-14T13:52:48
| 2015-03-14T13:52:48
| 32,190,211
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 15,139
|
cpp
|
PeriodicityCheck.cpp
|
#include "PeriodicityCheck.h"
PeriodicityCheck::PeriodicityCheck()
{
}
PeriodicityCheck::~PeriodicityCheck()
{
}
void PeriodicityCheck::NearestImagesFinder(Structs::FrameGeometric *framedata, Structs::GenericParameters *me, Structs::FrameoutReferenceGrids *grids)
{
std::cout << framedata->frame_id << std::endl;
//init variables
double currentDistance = 0;
//cut-off is derived from (longest bond)^2
double cut_off = me->distance_cut_off*me->distance_cut_off;
//determine where the solute molecule ends
// 1. try to get everything up to the first ion atom
// 2. try to get everything up to the first solvent atom
// 3. try to get everything up to the last COG solute atom
// 4. try to get everything up to the last solute atom
int mol_start = 1, mol_end = 1000000;
if (me->solute_cog_molecules.cols() > 0)
{
for (int xx = 0; xx < me->solute_cog_molecules.cols(); xx++)
{
if (me->solute_cog_molecules(1, xx) < mol_end)
{
mol_end = me->solute_cog_molecules(1, xx);
}
}
}
else if (me->solute_molecules.cols() > 0)
{
for (int xx = 0; xx < me->solute_molecules.cols(); xx++)
{
if (me->solute_molecules(1, xx) < mol_end)
{
mol_end = me->solute_molecules(1, xx);
}
}
}
else
{
return;
}
//after determining the end of the solute molecules, check for interaction with neighbouring copies
//std::cout << "////" << mol_start << " " << mol_end << std::endl;
Eigen::Vector3d ref1;
Eigen::Vector3d ref2;
Eigen::Vector3d ref3;
//ref3 = framedata->box_length / 4;
ref3 = (framedata->box_length.array() - me->distance_cut_off) / 3;
//std::cout << framedata->box_length.array() - me->distance_cut_off << std::endl;
ref1 = framedata->frame_cog + ref3;
ref2 = framedata->frame_cog - ref3;
//std::cout << "max\n" << ref1 << "\n"
// << "min\n" << ref2 << "\n"
// << "2/5\n" << ref3 << "\n"
// << "cog\n" << framedata->frame_cog << std::endl;
//framedata->coordinates.col(i_atom_neighbour)
for (int i_atom_check = mol_start - 1; i_atom_check < mol_end; i_atom_check++)
{
//std::cout << framedata->coordinates.col(i_atom_check) << std::endl;
//std::cout << (framedata->coordinates.col(i_atom_check).x() < ref1.x()) << std::endl;
//std::cout << (framedata->coordinates.col(i_atom_check).x() > ref2.x()) << std::endl;
//std::cout << (framedata->coordinates.col(i_atom_check).y() < ref1.y()) << std::endl;
//std::cout << (framedata->coordinates.col(i_atom_check).y() > ref2.y()) << std::endl;
//std::cout << (framedata->coordinates.col(i_atom_check).z() < ref1.z()) << std::endl;
//std::cout << (framedata->coordinates.col(i_atom_check).z() > ref2.z()) << std::endl;
if (!(
framedata->coordinates.col(i_atom_check).x() < ref1.x() &&
framedata->coordinates.col(i_atom_check).x() > ref2.x() &&
framedata->coordinates.col(i_atom_check).y() < ref1.y() &&
framedata->coordinates.col(i_atom_check).y() > ref2.y() &&
framedata->coordinates.col(i_atom_check).z() < ref1.z() &&
framedata->coordinates.col(i_atom_check).z() > ref2.z()
))
{
for (int i_atom_neighbour = (i_atom_check + 1); i_atom_neighbour < mol_end; i_atom_neighbour++)
{
if (!(
framedata->coordinates.col(i_atom_neighbour).x() < ref1.x() &&
framedata->coordinates.col(i_atom_neighbour).x() > ref2.x() &&
framedata->coordinates.col(i_atom_neighbour).y() < ref1.y() &&
framedata->coordinates.col(i_atom_neighbour).y() > ref2.y() &&
framedata->coordinates.col(i_atom_neighbour).z() < ref1.z() &&
framedata->coordinates.col(i_atom_neighbour).z() > ref2.z()
))
{
currentDistance = (((((
grids->Checkbox
).cast<double>().array().colwise() * framedata->box_length.array()
).matrix().colwise() + framedata->coordinates.col(i_atom_neighbour)
).colwise() - framedata->coordinates.col(i_atom_check)
).cwiseAbs2().colwise().sum().minCoeff()
);
//std::cout << framedata->coordinates.col(0) << std::endl;
//std::cout << framedata->box_length << std::endl << std::endl;
//std::cout << framedata->box_angle << std::endl << std::endl;
//std::cout << framedata->box_3 << std::endl << std::endl;
//std::cout << framedata->box_4 << std::endl << std::endl;
//std::cout << framedata->coordinates.col(i_atom_neighbour) << std::endl << std::endl;
//std::cout << framedata->coordinates.col(i_atom_check) << std::endl << std::endl;
//std::cout << "####" << i_atom_check << " " << i_atom_neighbour << " " << pow(currentDistance,0.5) << std::endl;
////the box with the nearest image interaction is grids->Checkbox.col(minIndex)
//whenever the current distance between two calculated atoms is shorter than the cut-off distance
//mark the atoms as interacting
if (currentDistance <= cut_off)
{
//std::cout << "##########step " << framedata->timestep << std::endl;
//std::cout << "##########chk " << i_atom_check << std::endl;
//std::cout << "##########ngh " << i_atom_neighbour << std::endl;
//std::cout << "##########dist " << currentDistance << std::endl;
std::vector<double> temp(5);
temp[0] = framedata->time;
temp[1] = framedata->timestep;
temp[2] = i_atom_check;
temp[3] = i_atom_neighbour;
temp[4] = sqrt(currentDistance);
framedata->periodic_interactions.push_back(temp);
}
}
}
}
}
}
bool sortFunction4(std::vector<double> i, std::vector<double> j) {
return (i[4] < j[4]);
}
bool sortFunction3(std::vector<double> i, std::vector<double> j) {
return (i[3] < j[3]);
}
//void PeriodicityCheck::NearestImagesFinder(Structs::FrameGeometric *framedata, Structs::GenericParameters *me, Structs::FrameoutReferenceGrids *grids, int startIndex, int endIndex)
//{
// //init variables
// double currentDistance = 0;
//
// //use a for finding minimum distances in matrix/vector
// Eigen::MatrixXd::Index minIndex;
//
// //cut-off is derived from (longest bond)^2
// double cut_off = me->distance_cut_off*me->distance_cut_off;
//
// //determine where the solute molecule ends
// // 1. try to get everything up to the first ion atom
// // 2. try to get everything up to the first solvent atom
// // 3. try to get everything up to the last COG solute atom
// // 4. try to get everything up to the last solute atom
// int mol_start = startIndex, mol_end = endIndex;
//
// //after determining the end of the solute molecules, check for interaction with neighbouring copies
// for (int i_atom_check = mol_start; i_atom_check < mol_end; i_atom_check++)
// {
// for (int i_atom_neighbour = (i_atom_check + 1); i_atom_neighbour < mol_end; i_atom_neighbour++)
// {
// currentDistance = (((((
// grids->Checkbox
// ).cast<double>().array().colwise() * framedata->box_length.array()
// ).matrix().colwise() + framedata->coordinates.col(i_atom_neighbour)
// ).colwise() - framedata->coordinates.col(i_atom_check)
// ).cwiseAbs2().colwise().sum().minCoeff(&minIndex)
// );
// //the box with the nearest image interaction is grids->Checkbox.col(minIndex)
//
// //whenever the current distance between two calculated atoms is shorter than the cut-off distance
// //mark the atoms as interacting
// if (currentDistance <= cut_off)
// {
// std::vector<double> temp (5);
// temp[0] = framedata->time;
// temp[1] = framedata->timestep;
// temp[2] = i_atom_check;
// temp[3] = i_atom_neighbour;
// temp[4] = sqrt(currentDistance);
// framedata->periodic_interactions.push_back(temp);
// }
// }
// }
//}
//void PeriodicityCheck::WriteResults(Structs::FrameGeometric *framedata, Structs::GenericParameters *me, gz::ogzstream &outfile) {
// for (int i = 0; i < framedata->periodic_interactions.size(); i++)
// {
// outfile << std::setw(9) << std::right << std::setprecision(0) << framedata->periodic_interactions[i][0] << " "
// << std::setw(12) << std::right << std::setprecision(0) << framedata->periodic_interactions[i][1] << " "
// << std::setw(6) << std::right << std::setprecision(0) << framedata->prefix[framedata->periodic_interactions[i][2]] << " "
// << std::setw(6) << std::right << std::setprecision(0) << framedata->prefix[framedata->periodic_interactions[i][3]] << " "
// << std::setw(9) << std::right << std::setprecision(4) << framedata->periodic_interactions[i][4] << std::endl;
// }
//}
void PeriodicityCheck::WriteResults(Structs::FrameGeometric *framedata, Structs::GenericParameters *me, gz::ogzstream &outfile,
std::vector<std::string> *atomNames, std::vector<long> *atomNumbers, std::vector<std::string> *chainIds, std::vector<std::string> *residueNames, std::vector<long> *residueNumber) {
int residue_number = -1;
std::vector<std::vector<double>> temp_periodic_interactions;
switch (me->verbosity)
{
case 4:
for (int i = 0; i < framedata->periodic_interactions.size(); i++)
{
int a1 = framedata->periodic_interactions[i][2];
int a2 = framedata->periodic_interactions[i][3];
outfile << std::setw(9) << std::right << std::setprecision(0) << framedata->periodic_interactions[i][0] << " "
<< std::setw(12) << std::right << std::setprecision(0) << framedata->periodic_interactions[i][1] << " || "
<< std::setw(20) << std::right << std::setprecision(0) << (*atomNumbers)[a1] << " " << (*atomNames)[a1] << " " << (*residueNames)[a1] << " " << (*residueNumber)[a1] << " " << (*chainIds)[a1] << " || "
<< std::setw(20) << std::right << std::setprecision(0) << (*atomNumbers)[a2] << " " << (*atomNames)[a2] << " " << (*residueNames)[a2] << " " << (*residueNumber)[a2] << " " << (*chainIds)[a2] << " || "
<< std::setw(9) << std::right << std::setprecision(4) << framedata->periodic_interactions[i][4] << std::endl;
}
break;
case 3:
std::stable_sort(framedata->periodic_interactions.begin(), framedata->periodic_interactions.end(), sortFunction3);
for (int i = 0; i < framedata->periodic_interactions.size(); i++)
{
if (residue_number != framedata->periodic_interactions[i][3])
{
residue_number = framedata->periodic_interactions[i][3];
if (temp_periodic_interactions.size() > 0)
{
std::stable_sort(temp_periodic_interactions.begin(), temp_periodic_interactions.end(), sortFunction4);
outfile << std::setw(9) << std::right << std::setprecision(0) << temp_periodic_interactions[0][0] << " "
<< std::setw(12) << std::right << std::setprecision(0) << temp_periodic_interactions[0][1] << " "
<< std::setw(6) << std::right << std::setprecision(0) << framedata->prefix[temp_periodic_interactions[0][2]] << " "
<< std::setw(6) << std::right << std::setprecision(0) << framedata->prefix[temp_periodic_interactions[0][3]] << " "
<< std::setw(9) << std::right << std::setprecision(4) << temp_periodic_interactions[0][4] << std::endl;
}
temp_periodic_interactions.clear();
temp_periodic_interactions.push_back(framedata->periodic_interactions[i]);
}
else
{
temp_periodic_interactions.push_back(framedata->periodic_interactions[i]);
}
}
break;
case 2:
for (int i = 0; i < framedata->periodic_interactions.size(); i++)
{
if (residue_number != framedata->periodic_interactions[i][2])
{
residue_number = framedata->periodic_interactions[i][2];
if (temp_periodic_interactions.size() > 0)
{
std::stable_sort(temp_periodic_interactions.begin(), temp_periodic_interactions.end(), sortFunction4);
outfile << std::setw(9) << std::right << std::setprecision(0) << temp_periodic_interactions[0][0] << " "
<< std::setw(12) << std::right << std::setprecision(0) << temp_periodic_interactions[0][1] << " "
<< std::setw(6) << std::right << std::setprecision(0) << framedata->prefix[temp_periodic_interactions[0][2]] << " "
<< std::setw(6) << std::right << std::setprecision(0) << framedata->prefix[temp_periodic_interactions[0][3]] << " "
<< std::setw(9) << std::right << std::setprecision(4) << temp_periodic_interactions[0][4] << std::endl;
}
temp_periodic_interactions.clear();
temp_periodic_interactions.push_back(framedata->periodic_interactions[i]);
}
else
{
temp_periodic_interactions.push_back(framedata->periodic_interactions[i]);
}
}
break;
default:
std::stable_sort(framedata->periodic_interactions.begin(), framedata->periodic_interactions.end(), sortFunction4);
if (framedata->periodic_interactions.size() > 0)
{
outfile << std::setw(9) << std::right << std::setprecision(0) << framedata->periodic_interactions[0][0] << " "
<< std::setw(12) << std::right << std::setprecision(0) << framedata->periodic_interactions[0][1] << " "
<< std::setw(6) << std::right << std::setprecision(0) << framedata->prefix[framedata->periodic_interactions[0][2]] << " "
<< std::setw(6) << std::right << std::setprecision(0) << framedata->prefix[framedata->periodic_interactions[0][3]] << " "
<< std::setw(9) << std::right << std::setprecision(4) << framedata->periodic_interactions[0][4] << std::endl;
}
break;
}
}
|
a6b0fefe6033da50e986178f98122369ba4f1607
|
e9f7c2afaff32570872f93646e2a41db39ca8c30
|
/C++_code/bingchaji23.cpp
|
adce21a36ecb9c9b26a865e303fbbac88fd2053d
|
[] |
no_license
|
czkct/My_code
|
f49ed33c73776ae4767201a9aabc6fa76f447c29
|
37b04bb5429911aeec540af988a65a3fed02d70a
|
refs/heads/master
| 2016-08-11T14:08:47.547447
| 2015-12-19T10:10:04
| 2015-12-19T10:10:04
| 47,608,222
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 1,344
|
cpp
|
bingchaji23.cpp
|
#include<iostream> //此题中并不会使各个大型集合(除了给出的一对一对的点)相互合并到一起
#include<cstring> // 所以每个集合都可以维护一个相应的 自身元素个数变量 setMAX
#include<cstdio>
#include<algorithm>
using namespace std;
const int MAXN = 10000000+10;
int setMAX[MAXN]; //初始化值都应该是 1
int pre[MAXN]; //初始化值都应该是自己
void init(){
for(int i = 1; i <= MAXN; i++) {
pre[i] = i;
setMAX[i] = 1;
}
}
int unionsearch(int root)
{
int son = root;
int temp;
while(root!=pre[root]) root = pre[root];
while(son != root) {
temp = pre[son];
pre[son] = root;
son = temp;
}
return root;
}
int root_max(int x, int y)
{
int root1 = unionsearch(x);
int root2 = unionsearch(y);
if(root1 != root2) {
pre[root1] = root2; //总是在这里犯错误 千万不要写成pre[x] = y
setMAX[root2] += setMAX[root1]; //这一句要根据上一句的顺序
}
}
int main(){
int n;
int a, b;
while(cin >> n) {
if(!n) {
printf("1\n"); //栽在这里了 当n为0时 一定要等于1
continue;
}
init();
for(int i = 0; i < n; i++){
scanf("%d%d", &a, &b);
root_max(a, b);
}
int MAX = 0;
for(int i = 0; i <= MAXN; i++)
if(setMAX[i]>MAX) MAX = setMAX[i];
cout << MAX << endl;
}
return 0;
}
|
ee56d02970c9b1989ab285ba0a50dee0f633364d
|
08b3f234d56e71e80e4cd973c25f85ab354268e8
|
/AliBazar Project Version 3.0/Password_Vali_Asterisk.h
|
98f4f7feefb0923b921ef90c2899e311513f9354
|
[] |
no_license
|
Anurag22022/cpp-projects
|
2044b8962e9e7bf3344b99631d2e9b4670c42e0e
|
9ef3d35773da4dfdc9ed37c8cdade623cbf86ca5
|
refs/heads/master
| 2023-06-10T18:57:10.009551
| 2021-06-29T07:00:21
| 2021-06-29T07:00:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,147
|
h
|
Password_Vali_Asterisk.h
|
#pragma once
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
// Global variables
string Password_Val, Change_Val; char Letter_Val; int Length_Val;
////////////////////////////////////////////////
void F_Password_Val() {
Password_Val = "";
Parol_Sign = "";
cout << "\t\t\t\t\tPassword : ";
for (int i = 0; i != 1;) {
switch (_getch()) {
case 49: {
cout << "*"; Password_Val = Password_Val + "1";
}
break;
case 50: {
cout << "*"; Password_Val = Password_Val + "2";
}
break;
case 51: {
cout << "*"; Password_Val = Password_Val + "3";
}
break;
case 52: {
cout << "*"; Password_Val = Password_Val + "4";
}
break;
case 53: {
cout << "*"; Password_Val = Password_Val + "5";
}
break;
case 54: {
cout << "*"; Password_Val = Password_Val + "6";
}
break;
case 55: {
cout << "*"; Password_Val = Password_Val + "7";
}
break;
case 56: {
cout << "*"; Password_Val = Password_Val + "8";
}
break;
case 57: {
cout << "*"; Password_Val = Password_Val + "9";
}
break;
case 48: {
cout << "*"; Password_Val = Password_Val + "0";
}
break;
case 81: {
cout << "*"; Password_Val = Password_Val + "Q";
}
break;
case 87: {
cout << "*"; Password_Val = Password_Val + "W";
}
break;
case 69: {
cout << "*"; Password_Val = Password_Val + "E";
}
break;
case 82: {
cout << "*"; Password_Val = Password_Val + "R";
}
break;
case 84: {
cout << "*"; Password_Val = Password_Val + "T";
}
break;
case 89: {
cout << "*"; Password_Val = Password_Val + "Y";
}
break;
case 85: {
cout << "*"; Password_Val = Password_Val + "U";
}
break;
case 73: {
cout << "*"; Password_Val = Password_Val + "I";
}
break;
case 79: {
cout << "*"; Password_Val = Password_Val + "O";
}
break;
case 80: {
cout << "*"; Password_Val = Password_Val + "P";
}
break;
case 65: {
cout << "*"; Password_Val = Password_Val + "A";
}
break;
case 83: {
cout << "*"; Password_Val = Password_Val + "S";
}
break;
case 68: {
cout << "*"; Password_Val = Password_Val + "D";
}
break;
case 70: {
cout << "*"; Password_Val = Password_Val + "F";
}
break;
case 71: {
cout << "*"; Password_Val = Password_Val + "G";
}
break;
case 72: {
cout << "*"; Password_Val = Password_Val + "H";
}
break;
case 74: {
cout << "*"; Password_Val = Password_Val + "J";
}
break;
case 75: {
cout << "*"; Password_Val = Password_Val + "K";
}
break;
case 76: {
cout << "*"; Password_Val = Password_Val + "L";
}
break;
case 90: {
cout << "*"; Password_Val = Password_Val + "Z";
}
break;
case 88: {
cout << "*"; Password_Val = Password_Val + "X";
}
break;
case 67: {
cout << "*"; Password_Val = Password_Val + "C";
}
break;
case 86: {
cout << "*"; Password_Val = Password_Val + "V";
}
break;
case 66: {
cout << "*"; Password_Val = Password_Val + "B";
}
break;
case 78: {
cout << "*"; Password_Val = Password_Val + "N";
}
break;
case 77: {
cout << "*"; Password_Val = Password_Val + "M";
}
break;
case 97: {
cout << "*"; Password_Val = Password_Val + "a";
}
break;
case 98: {
cout << "*"; Password_Val = Password_Val + "b";
}
break;
case 99: {
cout << "*"; Password_Val = Password_Val + "c";
}
break;
case 100: {
cout << "*"; Password_Val = Password_Val + "d";
}
break;
case 101: {
cout << "*"; Password_Val = Password_Val + "e";
}
break;
case 102: {
cout << "*"; Password_Val = Password_Val + "f";
}
break;
case 103: {
cout << "*"; Password_Val = Password_Val + "g";
}
break;
case 104: {
cout << "*"; Password_Val = Password_Val + "h";
}
break;
case 105: {
cout << "*"; Password_Val = Password_Val + "i";
}
break;
case 106: {
cout << "*"; Password_Val = Password_Val + "j";
}
break;
case 107: {
cout << "*"; Password_Val = Password_Val + "k";
}
break;
case 108: {
cout << "*"; Password_Val = Password_Val + "l";
}
break;
case 109: {
cout << "*"; Password_Val = Password_Val + "m";
}
break;
case 110: {
cout << "*"; Password_Val = Password_Val + "n";
}
break;
case 111: {
cout << "*"; Password_Val = Password_Val + "o";
}
break;
case 112: {
cout << "*"; Password_Val = Password_Val + "p";
}
break;
case 113: {
cout << "*"; Password_Val = Password_Val + "q";
}
break;
case 114: {
cout << "*"; Password_Val = Password_Val + "r";
}
break;
case 115: {
cout << "*"; Password_Val = Password_Val + "s";
}
break;
case 116: {
cout << "*"; Password_Val = Password_Val + "t";
}
break;
case 117: {
cout << "*"; Password_Val = Password_Val + "u";
}
break;
case 118: {
cout << "*"; Password_Val = Password_Val + "v";
}
break;
case 119: {
cout << "*"; Password_Val = Password_Val + "w";
}
break;
case 120: {
cout << "*"; Password_Val = Password_Val + "x";
}
break;
case 121: {
cout << "*"; Password_Val = Password_Val + "y";
}
break;
case 122: {
cout << "*"; Password_Val = Password_Val + "z";
}
break;
case 123: {
cout << "*"; Password_Val = Password_Val + "{";
}
break;
case 124: {
cout << "*"; Password_Val = Password_Val + "|";
}
break;
case 125: {
cout << "*"; Password_Val = Password_Val + "}";
}
break;
case 33: {
cout << "*"; Password_Val = Password_Val + "!";
}
break;
case 36: {
cout << "*"; Password_Val = Password_Val + "$";
}
break;
case 37: {
cout << "*"; Password_Val = Password_Val + "%";
}
break;
case 38: {
cout << "*"; Password_Val = Password_Val + "&";
}
break;
case 39: {
cout << "*"; Password_Val = Password_Val + "'";
}
break;
case 40: {
cout << "*"; Password_Val = Password_Val + "(";
}
break;
case 41: {
cout << "*"; Password_Val = Password_Val + ")";
}
break;
case 42: {
cout << "*"; Password_Val = Password_Val + "*";
}
break;
case 43: {
cout << "*"; Password_Val = Password_Val + "+";
}
break;
case 44: {
cout << "*"; Password_Val = Password_Val + ",";
}
break;
case 45: {
cout << "*"; Password_Val = Password_Val + "-";
}
break;
case 46: {
cout << "*"; Password_Val = Password_Val + ".";
}
break;
case 47: {
cout << "*"; Password_Val = Password_Val + "/";
}
break;
case 58: {
cout << "*"; Password_Val = Password_Val + ":";
}
break;
case 59: {
cout << "*"; Password_Val = Password_Val + ";";
}
break;
case 60: {
cout << "*"; Password_Val = Password_Val + "<";
}
break;
case 61: {
cout << "*"; Password_Val = Password_Val + "=";
}
break;
case 62: {
cout << "*"; Password_Val = Password_Val + ">";
}
break;
case 63: {
cout << "*"; Password_Val = Password_Val + "?";
}
break;
case 95: {
cout << "*"; Password_Val = Password_Val + "_";
}
break;
case 8: { // Deleting character
system("cls");
cout << "____________________________________________________________________________________________________ \n";
cout << " A L I B A Z A R \n";
cout << "____________________________________________________________________________________________________\n\n";
cout << "\t\t\t\t Authentication\n\n";
cout << "\t\t\t\t\tLogin : "; cout << Login_Sign << endl;
cout << "\t\t\t\t\tPassword : ";
Length_Val = Password_Val.length();
Length_Val--;
for (int j = 0; j < Length_Val; j++) {
Letter_Val = Password_Val[j];
Change_Val = Change_Val + Letter_Val;
cout << "*";
}
Password_Val = Change_Val;
Change_Val = "";
}
break;
case 13: { // Entering Password_Val
i = 1;
Change_Val = "";
}
break;
}
}
}
|
0dcc7b1d97d9ded8bc5da39e7c8755e8e7295a72
|
e274becd012db0712acf745b9aa4a911b7021d8f
|
/Linux/src/control/lightcontroller.cpp
|
7b8ff38fa9aa2b51f518cdfa879ff38ea17cc8da
|
[] |
no_license
|
Aaronyoungjs/AutoCar
|
c038858c3069b24f54239bc5f9b2330e946bd09a
|
7e4bab42ca83e77db50a304f85750ee43b2427c2
|
refs/heads/master
| 2021-05-05T09:10:26.114793
| 2016-09-21T06:28:58
| 2016-09-21T06:28:58
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 687
|
cpp
|
lightcontroller.cpp
|
#include "lightcontroller.h"
#include "config.h"
LightController::LightController()
{
setControllerName("Light Controller.");
setControllerType(Controller::MISC);
light = new LED(100, 255);
sensor = new Brightness();
light->setPin(4);
setLevel(DEF_LEVEL);
setDelay(DEF_DELAY);
start = true;
loop = new thread([&]{ autoloop(); });
}
LightController::~LightController()
{
start = false;
}
void LightController::autoloop()
{
while(start){
if(sensor->getValue() < level){
light->on();
}
else{
light->off();
}
this_thread::sleep_for(std::chrono::milliseconds(delay));
}
}
|
123878360bde363c43fbe711634d6de3ad07ebc4
|
11297b3ac40dafbd68f6cc87e83492dcd5eb9c45
|
/lib/compiler/hostfunc/wasi/fd_FdstatSetFlags.cpp
|
5b15b1aa067751ed9fc0d85603e60b1fd591da81
|
[
"BSD-3-Clause",
"CC0-1.0",
"Apache-2.0"
] |
permissive
|
ewasm-benchmarking/SSVM
|
833da9e073f7081e6c5ea3a82126b7fe5c0ba2c7
|
d0906726bd5c91568ec4c8effb82735baf364fa9
|
refs/heads/master
| 2022-10-11T18:53:13.665582
| 2020-05-06T14:33:00
| 2020-05-06T15:44:36
| 262,974,748
| 1
| 0
| null | 2020-05-11T07:48:10
| 2020-05-11T07:48:09
| null |
UTF-8
|
C++
| false
| false
| 876
|
cpp
|
fd_FdstatSetFlags.cpp
|
// SPDX-License-Identifier: Apache-2.0
#include "compiler/hostfunc/wasi/fd_FdstatSetFlags.h"
#include <algorithm>
#include <fcntl.h>
#include <unistd.h>
namespace SSVM {
namespace Compiler {
uint32_t WasiFdFdstatSetFlags::run(uint32_t Fd, uint32_t FdFlags) {
int Flags = 0;
if ((FdFlags & __WASI_FDFLAG_APPEND) != 0) {
Flags |= O_APPEND;
}
if ((FdFlags & __WASI_FDFLAG_DSYNC) != 0) {
#ifdef O_DSYNC
Flags |= O_DSYNC;
#else
Flags |= O_SYNC;
#endif
}
if ((FdFlags & __WASI_FDFLAG_NONBLOCK) != 0) {
Flags |= O_NONBLOCK;
}
if ((FdFlags & __WASI_FDFLAG_RSYNC) != 0) {
#ifdef O_RSYNC
Flags |= O_RSYNC;
#else
Flags |= O_SYNC;
#endif
}
if ((FdFlags & __WASI_FDFLAG_SYNC) != 0) {
Flags |= O_SYNC;
}
if (fcntl(Fd, F_SETFL, Flags) < 0) {
return convertErrno(errno);
}
return 0;
}
} // namespace Compiler
} // namespace SSVM
|
af8adbb5af670959aea8585ee9d8bffc00431d88
|
315f1de5835d38669c9777e8009709d80ff3d04e
|
/spatial/core/resources/chiselgen/template-level/fringeVCS/DRAMSim2/CSVWriter.h
|
e19156392b2b0a65cfc34127b998cc38a73bb522
|
[
"MIT"
] |
permissive
|
stanford-ppl/spatial-lang
|
751dcadfc38770f7a0b65e701f3e6aa5ef50e146
|
55e9a67b28f83caf3606e0c7bbead82a12cfbd2a
|
refs/heads/master
| 2023-03-08T17:55:24.007295
| 2018-11-14T22:07:39
| 2018-11-14T22:07:39
| 78,697,642
| 109
| 15
|
MIT
| 2018-04-12T10:44:07
| 2017-01-12T01:47:41
|
Verilog
|
UTF-8
|
C++
| false
| false
| 6,894
|
h
|
CSVWriter.h
|
/*********************************************************************************
* Copyright (c) 2010-2011, Elliott Cooper-Balis
* Paul Rosenfeld
* Bruce Jacob
* University of Maryland
* dramninjas [at] gmail [dot] com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*********************************************************************************/
#ifndef _CSV_WRITER_H_
#define _CSV_WRITER_H_
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <string>
#include <string.h>
using std::vector;
using std::ostream;
using std::string;
/*
* CSVWriter: Writes CSV data with headers to an underlying ofstream
* This wrapper is meant to look like an ofstream, but it captures
* the names of each field and prints it out to a header before printing
* the CSV data below.
*
* Note: the first finalize() will not print the values out, only the headers.
* One way to fix this problem would be to use a sstringstream (or something)
* to buffer out the values and flush them all in one go instead of passing them
* directly to the underlying stream as is the case now.
*
* Example usage:
*
* CSVWriter sw(cout); // send output to cout
* sw <<"Bandwidth" << 0.5; // value ignored
* sw <<"Latency" << 5; // value ignored
* sw.finalize(); // flush the header
* sw <<"Bandwidth" << 1.5; // field name ignored
* sw <<"Latency" << 15; // field name ignored
* sw.finalize(); // values printed to csv line
* sw <<"Bandwidth" << 2.5; // field name ignored
* sw <<"Latency" << 25; // field name ignored
* sw.finalize(); // values printed to csv line
*
* The output of this example will be:
*
* Bandwidth,Latency
* 1.5,15
* 2.5,25
*
*/
namespace DRAMSim {
class CSVWriter {
public :
struct IndexedName {
static const size_t MAX_TMP_STR = 64;
static const unsigned SINGLE_INDEX_LEN = 4;
string str;
// functions
static bool isNameTooLong(const char *baseName, unsigned numIndices)
{
return (strlen(baseName)+(numIndices*SINGLE_INDEX_LEN)) > MAX_TMP_STR;
}
static void checkNameLength(const char *baseName, unsigned numIndices)
{
if (isNameTooLong(baseName, numIndices))
{
ERROR("Your string "<<baseName<<" is too long for the max stats size ("<<MAX_TMP_STR<<", increase MAX_TMP_STR");
exit(-1);
}
}
IndexedName(const char *baseName, unsigned channel)
{
checkNameLength(baseName,1);
char tmp_str[MAX_TMP_STR];
snprintf(tmp_str, MAX_TMP_STR,"%s[%u]", baseName, channel);
str = string(tmp_str);
}
IndexedName(const char *baseName, unsigned channel, unsigned rank)
{
checkNameLength(baseName,2);
char tmp_str[MAX_TMP_STR];
snprintf(tmp_str, MAX_TMP_STR,"%s[%u][%u]", baseName, channel, rank);
str = string(tmp_str);
}
IndexedName(const char *baseName, unsigned channel, unsigned rank, unsigned bank)
{
checkNameLength(baseName,3);
char tmp_str[MAX_TMP_STR];
snprintf(tmp_str, MAX_TMP_STR,"%s[%u][%u][%u]", baseName, channel, rank, bank);
str = string(tmp_str);
}
};
// where the output will eventually go
ostream &output;
vector<string> fieldNames;
bool finalized;
unsigned idx;
public:
// Functions
void finalize()
{
//TODO: tag unlikely
if (!finalized)
{
for (unsigned i=0; i<fieldNames.size(); i++)
{
output << fieldNames[i] << ",";
}
output << std::endl << std::flush;
finalized=true;
}
else
{
if (idx < fieldNames.size())
{
printf(" Number of fields doesn't match values (fields=%u, values=%u), check each value has a field name before it\n", idx, (unsigned)fieldNames.size());
}
idx=0;
output << std::endl;
}
}
// Constructor
CSVWriter(ostream &_output) : output(_output), finalized(false), idx(0)
{}
// Insertion operators for field names
CSVWriter &operator<<(const char *name)
{
if (!finalized)
{
// cout <<"Adding "<<name<<endl;
fieldNames.push_back(string(name));
}
return *this;
}
CSVWriter &operator<<(const string &name)
{
if (!finalized)
{
fieldNames.push_back(string(name));
}
return *this;
}
CSVWriter &operator<<(const IndexedName &indexedName)
{
if (!finalized)
{
// cout <<"Adding "<<indexedName.str<<endl;
fieldNames.push_back(indexedName.str);
}
return *this;
}
bool isFinalized()
{
// printf("obj=%p", this);
return finalized;
}
ostream &getOutputStream()
{
return output;
}
// Insertion operators for value types
// All of the other types just need to pass through to the underlying
// ofstream, so just write this small wrapper function to make the
// whole thing less verbose
#define ADD_TYPE(T) \
CSVWriter &operator<<(T value) \
{ \
if (finalized) \
{ \
output << value <<","; \
idx++; \
} \
return *this; \
}
ADD_TYPE(int);
ADD_TYPE(unsigned);
ADD_TYPE(long);
ADD_TYPE(uint64_t);
ADD_TYPE(float);
ADD_TYPE(double);
//disable copy constructor and assignment operator
private:
CSVWriter(const CSVWriter &);
CSVWriter &operator=(const CSVWriter &);
}; // class CSVWriter
} // namespace DRAMSim
#endif // _CSV_WRITER_H_
|
32c06521ec2c2adf1712368b7b447cc624e63854
|
e4af51f2f57daa1f764f7af47e9f05fcd6a32829
|
/DeferMySponza/source/MyView.cpp
|
7c86681b35aa7311455b56b4ca53323880b15def
|
[] |
no_license
|
Patryk-Szylin/Real-Time-Graphics
|
5fea28b7c1c478f2c9400f89a4be547b75ba1931
|
d482e114df337ac6bec1d61726f10d0949f5080c
|
refs/heads/master
| 2020-03-17T06:11:19.073551
| 2018-05-14T10:38:01
| 2018-05-14T10:38:01
| 133,345,167
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 31,004
|
cpp
|
MyView.cpp
|
#include "MyView.hpp"
#include <scene/scene.hpp>
#include <tygra/FileHelper.hpp>
#include <tsl/shapes.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <iostream>
#include <cassert>
MyView::MyView()
{
}
MyView::~MyView() {
}
void MyView::setScene(const scene::Context * scene)
{
scene_ = scene;
}
void MyView::windowViewWillStart(tygra::Window * window)
{
assert(scene_ != nullptr);
_program.gBuffer = createProgram("resource:///gbuffer_vs.glsl", "resource:///gbuffer_fs.glsl");
_program.directionalLight = createProgram("resource:///directional_light_vs.glsl", "resource:///directional_light_fs.glsl");
_program.pointLight = createProgram("resource:///point_light_vs.glsl", "resource:///point_light_fs.glsl");
_program.shadowDepth = createProgram("resource:///shadow_depth_vs.glsl", "resource:///shadow_depth_fs.glsl");
_program.spotLight = createProgram("resource:///spot_light_vs.glsl", "resource:///spot_light_fs.glsl");
_program.postProcess = createProgram("resource:///post_process_vs.glsl", "resource:///post_process_fs.glsl");
// Build meshes
MeshGL();
// Build sponza's vertex buffers
glGenBuffers(1, &m_sponza.VBO);
glGenBuffers(1, &m_sponza.EBO);
glGenVertexArrays(1, &m_sponza.VAO);
setupSponzaBuffers();
// Generate objects here
glGenFramebuffers(1, &m_gBuffer.fbo);
glGenRenderbuffers(1, &m_gBuffer.depth_rbo);
glGenFramebuffers(1, &m_sBuffer.fbo);
glGenRenderbuffers(1, &m_sBuffer.depth_rbo);
glGenFramebuffers(1, &m_lBuffer.fbo);
glGenRenderbuffers(1, &m_lBuffer.colour_rbo);
glGenTextures(1, &m_gBuffer.textures[GBUFFER_POSITION_TEXTURE]);
glGenTextures(1, &m_gBuffer.textures[GBUFFER_NORMAL_TEXTURE]);
glGenTextures(1, &m_gBuffer.textures[GBUFFER_COLOUR_TEXTURE]);
glGenTextures(1, &m_sBuffer.textures[SHADOW_MAP]);
glGenTextures(1, &m_lBuffer.textures[FINAL_COLOUR]);
// Create light meshes here
// Screen quad
std::vector<glm::vec2> vertices(4);
vertices[0] = glm::vec2(-1, -1);
vertices[1] = glm::vec2(1, -1);
vertices[2] = glm::vec2(1, 1);
vertices[3] = glm::vec2(-1, 1);
glGenBuffers(1, &m_lightQuad.vertex_vbo);
glBindBuffer(GL_ARRAY_BUFFER, m_lightQuad.vertex_vbo);
glBufferData(GL_ARRAY_BUFFER,
vertices.size() * sizeof(glm::vec2),
vertices.data(),
GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glGenVertexArrays(1, &m_lightQuad.vao);
glBindVertexArray(m_lightQuad.vao);
glBindBuffer(GL_ARRAY_BUFFER, m_lightQuad.vertex_vbo);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE,
sizeof(glm::vec2), 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
// Point light
tsl::IndexedMeshPtr sphere_mesh = tsl::createSpherePtr(1.0f, 12);
sphere_mesh = tsl::cloneIndexedMeshAsTriangleListPtr(sphere_mesh.get());
m_lightSphere.element_count = sphere_mesh->indexCount();
glGenBuffers(1, &m_lightSphere.vertex_vbo);
glBindBuffer(GL_ARRAY_BUFFER, m_lightSphere.vertex_vbo);
glBufferData(GL_ARRAY_BUFFER, sphere_mesh->vertexCount() * sizeof(glm::vec3), sphere_mesh->positionArray(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glGenBuffers(1, &m_lightSphere.element_vbo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_lightSphere.element_vbo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sphere_mesh->indexCount() * sizeof(unsigned int), sphere_mesh->indexArray(), GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glGenVertexArrays(1, &m_lightSphere.vao);
glBindVertexArray(m_lightSphere.vao);
glBindBuffer(GL_ARRAY_BUFFER, m_lightSphere.vertex_vbo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_lightSphere.element_vbo);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
// Spot light
tsl::IndexedMeshPtr cone_mesh = tsl::createConePtr(1.f, 1.f, 12);
cone_mesh = tsl::cloneIndexedMeshAsTriangleListPtr(cone_mesh.get());
m_lightCone.element_count = cone_mesh->indexCount();
glGenBuffers(1, &m_lightCone.vertex_vbo);
glBindBuffer(GL_ARRAY_BUFFER, m_lightCone.vertex_vbo);
glBufferData(GL_ARRAY_BUFFER,
cone_mesh->vertexCount() * sizeof(glm::vec3),
cone_mesh->positionArray(),
GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glGenBuffers(1, &m_lightCone.element_vbo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_lightCone.element_vbo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,
cone_mesh->indexCount() * sizeof(unsigned int),
cone_mesh->indexArray(),
GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glGenVertexArrays(1, &m_lightCone.vao);
glBindVertexArray(m_lightCone.vao);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_lightCone.element_vbo);
glBindBuffer(GL_ARRAY_BUFFER, m_lightCone.vertex_vbo);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE,
sizeof(glm::vec3), 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
// Setup ubos
glGenBuffers(1, &_ubo_pointLight);
glBindBuffer(GL_UNIFORM_BUFFER, _ubo_pointLight);
glBufferData(GL_UNIFORM_BUFFER, sizeof(PerPointLightUniforms), nullptr, GL_STREAM_DRAW);
glBindBufferBase(GL_UNIFORM_BUFFER, 1, _ubo_pointLight);
glUniformBlockBinding(_program.pointLight, glGetUniformBlockIndex(_program.pointLight, "PerLightUniforms"), 1);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
glGenBuffers(1, &_ubo_spotLight);
glBindBuffer(GL_UNIFORM_BUFFER, _ubo_spotLight);
glBufferData(GL_UNIFORM_BUFFER, sizeof(PerSpotLightUniforms), nullptr, GL_STREAM_DRAW);
glBindBufferBase(GL_UNIFORM_BUFFER, 2, _ubo_spotLight);
glUniformBlockBinding(_program.spotLight, glGetUniformBlockIndex(_program.spotLight, "PerLightUniforms"), 2);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
}
void MyView::windowViewDidReset(tygra::Window * window,
int width,
int height)
{
glViewport(0, 0, width, height);
// Setup GBUFFER attachments
glBindTexture(GL_TEXTURE_RECTANGLE, m_gBuffer.textures[GBUFFER_POSITION_TEXTURE]);
glTexImage2D(GL_TEXTURE_RECTANGLE, 0, GL_RGB16F, width, height, 0, GL_RGB, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBindTexture(GL_TEXTURE_RECTANGLE, m_gBuffer.textures[GBUFFER_NORMAL_TEXTURE]);
glTexImage2D(GL_TEXTURE_RECTANGLE, 0, GL_RGB16F, width, height, 0, GL_RGB, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBindTexture(GL_TEXTURE_RECTANGLE, m_gBuffer.textures[GBUFFER_COLOUR_TEXTURE]);
glTexImage2D(GL_TEXTURE_RECTANGLE, 0, GL_RGB16F, width, height, 0, GL_RGB, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBindRenderbuffer(GL_RENDERBUFFER, m_gBuffer.depth_rbo);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height);
// Bind Gbuffer
GLenum gbuffer_status = 0;
glBindFramebuffer(GL_FRAMEBUFFER, m_gBuffer.fbo);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, m_gBuffer.depth_rbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_RECTANGLE, m_gBuffer.textures[GBUFFER_POSITION_TEXTURE], 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_RECTANGLE, m_gBuffer.textures[GBUFFER_NORMAL_TEXTURE], 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_RECTANGLE, m_gBuffer.textures[GBUFFER_COLOUR_TEXTURE], 0);
gbuffer_status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (gbuffer_status != GL_FRAMEBUFFER_COMPLETE) {
tglDebugMessage(GL_DEBUG_SEVERITY_HIGH_ARB, "GBUFFER is framebuffer not complete!");
}
GLenum gbufs[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 };
glDrawBuffers(3, gbufs);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
// Setting up LBUFFER as a colour buffer
glBindRenderbuffer(GL_RENDERBUFFER, m_lBuffer.colour_rbo);
glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA, width, height);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
glBindTexture(GL_TEXTURE_2D, m_lBuffer.textures[FINAL_COLOUR]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, width, height, 0, GL_RGB, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
GLuint lbuffer_status = 0;
glBindFramebuffer(GL_FRAMEBUFFER, m_lBuffer.fbo);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, m_gBuffer.depth_rbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_lBuffer.textures[FINAL_COLOUR], 0);
lbuffer_status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (lbuffer_status != GL_FRAMEBUFFER_COMPLETE)
tglDebugMessage(GL_DEBUG_SEVERITY_HIGH_ARB, "LBUFFER framebuffer is not complete!");
GLenum lbufs[] = { GL_COLOR_ATTACHMENT0 };
glDrawBuffers(1, lbufs);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
// Shadow framebuffer
glBindTexture(GL_TEXTURE_RECTANGLE, m_sBuffer.textures[SHADOW_MAP]);
glTexImage2D(GL_TEXTURE_RECTANGLE, 0, GL_DEPTH_COMPONENT16, 1024, 1024, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
GLfloat borderColor[] = { 1.0, 1.0, 1.0, 1.0 };
glTexParameterfv(GL_TEXTURE_RECTANGLE, GL_TEXTURE_BORDER_COLOR, borderColor);
GLenum shadowBuffer_status = 0;
glBindFramebuffer(GL_FRAMEBUFFER, m_sBuffer.fbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_RECTANGLE, m_sBuffer.textures[SHADOW_MAP], 0);
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
shadowBuffer_status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (lbuffer_status != GL_FRAMEBUFFER_COMPLETE)
tglDebugMessage(GL_DEBUG_SEVERITY_HIGH_ARB, "SHADOWBUFFER framebuffer is not complete!");
}
void MyView::windowViewDidStop(tygra::Window * window)
{
// Programs
glDeleteProgram(_program.gBuffer);
glDeleteProgram(_program.directionalLight);
glDeleteProgram(_program.pointLight);
glDeleteProgram(_program.postProcess);
glDeleteProgram(_program.shadowDepth);
glDeleteProgram(_program.spotLight);
//// Buffers
//glDeleteFramebuffers(1, &m_gBuffer.fbo);
//glDeleteFramebuffers(1, &m_lBuffer.fbo);
//glDeleteFramebuffers(1, &m_sBuffer.fbo);
//glDeleteRenderbuffers(1, &m_gBuffer.depth_rbo);
//glDeleteBuffers(1, &m_lightQuad.element_vbo);
//glDeleteBuffers(1, &m_lightQuad.vertex_vbo);
//glDeleteBuffers(1, &m_lightQuad.vao);
//glDeleteBuffers(1, &m_lightCone.element_vbo);
//glDeleteBuffers(1, &m_lightCone.vertex_vbo);
//glDeleteBuffers(1, &m_lightCone.vao);
//glDeleteBuffers(1, &m_lightSphere.element_vbo);
//glDeleteBuffers(1, &m_lightSphere.vertex_vbo);
//glDeleteBuffers(1, &m_lightSphere.vao);
//// Textures
//glDeleteTextures(NUM_TEXTURES, m_gBuffer.textures);
//glDeleteTextures(NUM_TEXTURES, m_sBuffer.textures);
//glDeleteTextures(NUM_TEXTURES, m_lBuffer.textures);
}
void MyView::windowViewRender(tygra::Window * window)
{
assert(scene_ != nullptr);
GLint viewportSize[4];
glGetIntegerv(GL_VIEWPORT, viewportSize);
const float aspectRatio = viewportSize[2] / (float)viewportSize[3];
_width = viewportSize[2];
_height = viewportSize[3];
glViewport(0, 0, _width, _height);
scene::Camera camera = scene_->getCamera();
_camera_position = (const glm::vec3&)camera.getPosition();
_camera_direction = (const glm::vec3&)camera.getDirection();
// Matrices
glm::mat4 projection_xform, view_xform;
projection_xform = glm::perspective(glm::radians(camera.getVerticalFieldOfViewInDegrees()), aspectRatio, camera.getNearPlaneDistance(), camera.getFarPlaneDistance());
view_xform = glm::lookAt(_camera_position, _camera_direction + _camera_position, (const glm::vec3 &)scene_->getUpDirection());
///////////////////////////////////////////////
// Setup Shadow map matrices
///////////////////////////////////////////////
GLfloat near_plane = 0.1f;
GLfloat far_plane = 500.0f;
const auto& allSpotLights = scene_->getAllSpotLights();
glm::vec3 light_position = (const glm::vec3&)allSpotLights[1].getPosition();
glm::vec3 light_direction = (const glm::vec3&)allSpotLights[1].getDirection();
const float light_aspectRatio = 1024.0f / 1024.0f;
glm::mat4 lightProjection = glm::perspective(glm::radians(60.0f), light_aspectRatio, near_plane, far_plane);
glm::mat4 lightView = glm::lookAt(light_position, light_position + light_direction, glm::vec3(0, 1, 0));
glm::mat4 lightSpace_xform = lightProjection * lightView;
///////////////////////////////////////////////
// Deferred Passes
///////////////////////////////////////////////
ShadowDepthPass(lightSpace_xform);
// Reset viewport back to normal after generating shadow map
glViewport(0, 0, _width, _height);
GBufferPass(projection_xform, view_xform);
DirectionalLightPass(_camera_position);
PointLightPass(projection_xform, view_xform);
glEnable(GL_STENCIL_TEST);
SpotLightPass(projection_xform, view_xform, lightSpace_xform);
PostProcess(_width, _height);
}
void MyView::StencilPass()
{
glEnable(GL_DEPTH_TEST);
glEnable(GL_STENCIL_TEST);
glDisable(GL_CULL_FACE);
glClear(GL_STENCIL_BUFFER_BIT);
glStencilFunc(GL_ALWAYS, 0, 0);
glStencilOpSeparate(GL_BACK, GL_KEEP, GL_INCR_WRAP, GL_KEEP);
glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_DECR_WRAP, GL_KEEP);
}
// DEFERRED RENDERING FUNCTIONS
void MyView::ShadowDepthPass(const glm::mat4& lightSpace_xform)
{
glEnable(GL_DEPTH_TEST);
glUseProgram(_program.shadowDepth);
glUniformMatrix4fv(glGetUniformLocation(_program.shadowDepth, "lightSpace_xform"), 1, GL_FALSE, glm::value_ptr(lightSpace_xform));
glViewport(0, 0, 1024, 1024);
glBindFramebuffer(GL_FRAMEBUFFER, m_sBuffer.fbo);
glClear(GL_DEPTH_BUFFER_BIT);
const auto& allInstances = scene_->getAllInstances();
glBindVertexArray(m_sponza.VAO);
for (GLuint i = 0; i < m_sponzaData.entries.size(); i++)
{
auto& mesh = allInstances[i];
unsigned int offset = (sizeof(unsigned int) * m_sponzaData.entries[i].base_index);
glDrawElementsInstancedBaseVertexBaseInstance(GL_TRIANGLES,
m_sponzaData.entries[i].element_count,
GL_UNSIGNED_INT,
(void*)offset,
m_sponzaData.entries[i].instance_count,
m_sponzaData.entries[i].base_vertex,
m_sponzaData.entries[i].base_xform);
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void MyView::GBufferPass(const glm::mat4& projection, const glm::mat4& view)
{
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
glDepthFunc(GL_LEQUAL);
glDisable(GL_BLEND);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glEnable(GL_STENCIL_TEST);
glStencilFunc(GL_ALWAYS, 0x00, 0xFF);
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
// Bind gbuffer for writing
glBindFramebuffer(GL_FRAMEBUFFER, m_gBuffer.fbo);
// Clear buffers
glClearDepth(1.0);
glClearStencil(128);
glClearColor(0.0f, 0.0f, 0.25f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
glUseProgram(_program.gBuffer);
glBindVertexArray(m_sponza.VAO);
glClearStencil(0);
const auto& allInstances = scene_->getAllInstances();
unsigned int obj_ID = 0;
std::vector<glm::mat4> animated_xform;
for (size_t i = 0; i < allInstances.size(); i++)
{
if (allInstances[i].getMeshId() == 300) // 300 Is the vases which have animated matrices
{
animated_xform.push_back(glm::translate(glm::mat4((const glm::mat4x3 &)allInstances[i].getTransformationMatrix()), glm::vec3(0, 0, 0)));
obj_ID++;
}
}
glBindBuffer(GL_ARRAY_BUFFER, m_sponza.instance_VBO);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(glm::mat4) * 4, animated_xform.data());
glBindBuffer(GL_ARRAY_BUFFER, 0);
glUniformMatrix4fv(glGetUniformLocation(_program.gBuffer, "projection_xform"), 1, GL_FALSE, glm::value_ptr(projection));
glUniformMatrix4fv(glGetUniformLocation(_program.gBuffer, "view_xform"), 1, GL_FALSE, glm::value_ptr(view));
for (GLuint i = 0; i < m_sponzaData.entries.size(); i++)
{
auto& mesh = allInstances[i];
const scene::MaterialId mat_id = mesh.getMaterialId();
const scene::Material material = scene_->getMaterialById(material_map[m_sponzaData.entries[i].mesh_id]);
// Fill the albedoTexture
glUniform3fv(glGetUniformLocation(_program.gBuffer, "albedo_color"), 1, glm::value_ptr((const glm::vec3&)(material.getDiffuseColour())));
glUniform1f(glGetUniformLocation(_program.gBuffer, "albedo_shininess"), material.getShininess());
//unsigned int temp = m_Entries[i].instance_count;
unsigned int offset = (sizeof(unsigned int) * m_sponzaData.entries[i].base_index);
glDrawElementsInstancedBaseVertexBaseInstance(GL_TRIANGLES,
m_sponzaData.entries[i].element_count,
GL_UNSIGNED_INT,
(void*)offset,
m_sponzaData.entries[i].instance_count,
m_sponzaData.entries[i].base_vertex,
m_sponzaData.entries[i].base_xform);
}
// Reset OpenGL Status
glDepthMask(GL_FALSE);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glDisable(GL_STENCIL_TEST);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void MyView::DirectionalLightPass(const glm::vec3& camera_position)
{
glDepthMask(GL_FALSE);
glEnable(GL_STENCIL_TEST);
glStencilFunc(GL_EQUAL, 0, ~0);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
// Bind colour buffer for writing
glBindFramebuffer(GL_FRAMEBUFFER, m_lBuffer.fbo);
// Clear buffers
glClearColor(0.f, 0.f, 0.25f, 0.f);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(_program.directionalLight);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_RECTANGLE, m_gBuffer.textures[GBUFFER_POSITION_TEXTURE]);
glUniform1i(glGetUniformLocation(_program.directionalLight, "sampler_gPosition"), 0);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_RECTANGLE, m_gBuffer.textures[GBUFFER_NORMAL_TEXTURE]);
glUniform1i(glGetUniformLocation(_program.directionalLight, "sampler_gNormal"), 1);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_RECTANGLE, m_gBuffer.textures[GBUFFER_COLOUR_TEXTURE]);
glUniform1i(glGetUniformLocation(_program.directionalLight, "sampler_gAlbedo"), 2);
glUniform3fv(glGetUniformLocation(_program.directionalLight, "camera_positio"), 1, glm::value_ptr(camera_position));
glBindVertexArray(m_lightQuad.vao);
glm::vec3 ambientlight_intensity = (glm::vec3 &)scene_->getAmbientLightIntensity();
glUniform3fv(glGetUniformLocation(_program.directionalLight, "ambient_intensity"), 1, glm::value_ptr(ambientlight_intensity));
// Draw light quad
auto& allDirectionalLights = scene_->getAllDirectionalLights();
for (size_t i = 0; i < allDirectionalLights.size(); i++)
{
glm::vec3 light_direction = (glm::vec3 &)allDirectionalLights[i].getDirection();
glm::vec3 light_intensity = (glm::vec3 &)allDirectionalLights[i].getIntensity();
glUniform3fv(glGetUniformLocation(_program.directionalLight, ("light_direction[" + std::to_string(i) + "]").c_str()), 1, glm::value_ptr(light_direction));
glUniform3fv(glGetUniformLocation(_program.directionalLight, ("light_intensity[" + std::to_string(i) + "]").c_str()), 1, glm::value_ptr(light_intensity));
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
}
glDisable(GL_STENCIL_TEST);
}
void MyView::PointLightPass(const glm::mat4& projection, const glm::mat4& view)
{
glDepthMask(GL_FALSE);
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFunc(GL_ONE, GL_ONE);
glUseProgram(_program.pointLight);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_RECTANGLE, m_gBuffer.textures[GBUFFER_POSITION_TEXTURE]);
glUniform1i(glGetUniformLocation(_program.pointLight, "sampler_gPosition"), 0);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_RECTANGLE, m_gBuffer.textures[GBUFFER_NORMAL_TEXTURE]);
glUniform1i(glGetUniformLocation(_program.pointLight, "sampler_gNormal"), 1);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_RECTANGLE, m_gBuffer.textures[GBUFFER_COLOUR_TEXTURE]);
glUniform1i(glGetUniformLocation(_program.pointLight, "sampler_gAlbedo"), 2);
glBindVertexArray(m_lightSphere.vao);
auto& allPointLights = scene_->getAllPointLights();
for (size_t i = 0; i < allPointLights.size(); i++)
{
glm::mat4 model_xform;
model_xform = glm::translate(model_xform, (glm::vec3 &)allPointLights[i].getPosition());
model_xform = glm::scale(model_xform, glm::vec3(allPointLights[i].getRange()));
glm::mat4 combined_xform = projection * view * model_xform;
m_ubo_pointLight.combined_xform = combined_xform;
m_ubo_pointLight.light_position = (glm::vec3 &)allPointLights[i].getPosition();
m_ubo_pointLight.light_intensity = (glm::vec3 &)allPointLights[i].getIntensity();
m_ubo_pointLight.light_range = allPointLights[i].getRange();
glBindBuffer(GL_UNIFORM_BUFFER, _ubo_pointLight);
glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(PerPointLightUniforms), &m_ubo_pointLight);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
glDrawElements(GL_TRIANGLES, m_lightSphere.element_count, GL_UNSIGNED_INT, 0);
}
glDisable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
glDisable(GL_STENCIL_TEST);
}
void MyView::SpotLightPass(const glm::mat4& projection, const glm::mat4& view, const glm::mat4& lightSpace_xform)
{
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFunc(GL_ONE, GL_ONE);
glStencilFunc(GL_EQUAL, 0, 0xFF);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
glUseProgram(_program.spotLight);
glUniformMatrix4fv(glGetUniformLocation(_program.spotLight, "lightSpace_xform"), 1, GL_FALSE, glm::value_ptr(lightSpace_xform));
// gBufferTextures
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_RECTANGLE, m_gBuffer.textures[GBUFFER_POSITION_TEXTURE]);
glUniform1i(glGetUniformLocation(_program.spotLight, "sampler_gPosition"), 0);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_RECTANGLE, m_gBuffer.textures[GBUFFER_NORMAL_TEXTURE]);
glUniform1i(glGetUniformLocation(_program.spotLight, "sampler_gNormal"), 1);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_RECTANGLE, m_gBuffer.textures[GBUFFER_COLOUR_TEXTURE]);
glUniform1i(glGetUniformLocation(_program.spotLight, "sampler_gAlbedo"), 2);
glActiveTexture(GL_TEXTURE3);
glBindTexture(GL_TEXTURE_RECTANGLE, m_sBuffer.textures[SHADOW_MAP]);
glUniform1i(glGetUniformLocation(_program.spotLight, "sampler_gAlbedo"), 3);
glm::vec3 ambientlight_intensity = (glm::vec3 &)scene_->getAmbientLightIntensity();
glUniform3fv(glGetUniformLocation(_program.spotLight, "ambient_intensity"), 1, glm::value_ptr(ambientlight_intensity));
glBindVertexArray(m_lightCone.vao);
auto& allSpotLights = scene_->getAllSpotLights();
for (size_t i = 0; i < allSpotLights.size(); i++)
{
glm::mat4 model_xform;
bool castShadow = allSpotLights[i].getCastShadow() == true ? true : false;
glUniform1i(glGetUniformLocation(_program.spotLight, "castShadow"), castShadow);
model_xform = glm::translate(model_xform, glm::vec3(0, 0, -1));
glm::vec3 scaling_factors;
glm::mat4 scale_xform;
scaling_factors.z = allSpotLights[i].getRange();
// Calculate cone's base area
float half_angle = allSpotLights[i].getConeAngleDegrees() / 2; // 30 : 45
float tangentVal = glm::tan(glm::degrees(half_angle)); // 0.5735 : 1.61977
float tan = half_angle == 45 ? 1 : tangentVal;
float radius = tan * scaling_factors.z;
scaling_factors.y = scaling_factors.x = radius;
scale_xform = glm::scale(scale_xform, scaling_factors);
model_xform = glm::inverse(glm::lookAt((const glm::vec3 &)allSpotLights[i].getPosition(),
(const glm::vec3 &)allSpotLights[i].getDirection() +
(const glm::vec3 &)allSpotLights[i].getPosition(),
(const glm::vec3 &)scene_->getUpDirection())) * scale_xform * model_xform;
glm::mat4 combined_xform = projection * view * model_xform;
m_ubo_spotLight.combined_xform = combined_xform;
m_ubo_spotLight.light_position = (glm::vec3 &)allSpotLights[i].getPosition();
m_ubo_spotLight.light_intensity = (glm::vec3 &)allSpotLights[i].getIntensity();
m_ubo_spotLight.light_direction = (glm::vec3 &)allSpotLights[i].getDirection();
m_ubo_spotLight.light_range = allSpotLights[i].getRange();
m_ubo_spotLight.light_angle = allSpotLights[i].getConeAngleDegrees();
glBindBuffer(GL_UNIFORM_BUFFER, _ubo_spotLight);
glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(PerSpotLightUniforms), &m_ubo_spotLight);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
glDrawElements(GL_TRIANGLES, m_lightCone.element_count, GL_UNSIGNED_INT, 0);
}
glDisable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
glDisable(GL_STENCIL_TEST);
}
void MyView::PostProcess(int textureWidth, int textureHeight)
{
glUseProgram(_program.postProcess);
glBindFramebuffer(GL_READ_FRAMEBUFFER, m_lBuffer.fbo);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_lBuffer.textures[FINAL_COLOUR]);
glUniform1i(glGetUniformLocation(_program.postProcess, "screen_tex"), 0);
glm::vec2 resolution = glm::vec2(textureWidth, textureHeight);
glUniform2fv(glGetUniformLocation(_program.postProcess, "resolution"), 1, glm::value_ptr(resolution));
glBindVertexArray(m_lightQuad.vao);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
}
GLuint MyView::createProgram(std::string vertex_shader, std::string fragment_shader)
{
GLuint program_vs, program_fs;
GLint compile_status = 0;
GLuint programID;
std::string program_vs_string = tygra::createStringFromFile(vertex_shader);
const char* program_vs_code = program_vs_string.c_str();
program_vs = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(program_vs, 1, &program_vs_code, NULL);
glCompileShader(program_vs);
glGetShaderiv(program_vs, GL_COMPILE_STATUS, &compile_status);
if (compile_status != GL_TRUE)
{
const int string_length = 1024;
GLchar log[string_length] = "";
glGetShaderInfoLog(program_vs, string_length, NULL, log);
std::cerr << log << std::endl;
}
std::string program_fs_string = tygra::createStringFromFile(fragment_shader);
const char* program_fs_code = program_fs_string.c_str();
program_fs = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(program_fs, 1, &program_fs_code, NULL);
glCompileShader(program_fs);
glGetShaderiv(program_fs, GL_COMPILE_STATUS, &compile_status);
if (compile_status != GL_TRUE)
{
const int string_length = 1024;
GLchar log[string_length] = "";
glGetShaderInfoLog(program_fs, string_length, NULL, log);
std::cerr << log << std::endl;
}
// Use function's program variable to create program
programID = glCreateProgram();
glAttachShader(programID, program_vs);
glAttachShader(programID, program_fs);
glLinkProgram(programID);
GLint link_status = 0;
glGetProgramiv(programID, GL_LINK_STATUS, &link_status);
if (link_status != GL_TRUE) {
const int string_length = 1024;
GLchar log[string_length] = "";
glGetProgramInfoLog(programID, string_length, NULL, log);
std::cerr << log << std::endl;
}
return programID;
}
void MyView::MeshGL()
{
// Fill data
scene::GeometryBuilder builder;
const auto& allMeshes = builder.getAllMeshes();
const auto& allInstances = scene_->getAllInstances();
for (size_t i = 0; i < allMeshes.size(); i++)
{
const scene::Mesh mesh = allMeshes[i];
Mesh new_mesh;
const auto& mesh_positions = mesh.getPositionArray();
const auto& mesh_normals = mesh.getNormalArray();
const auto& mesh_elements = mesh.getElementArray();
const auto& mesh_texCoords = mesh.getTextureCoordinateArray();
new_mesh.element_count = mesh_elements.size();
new_mesh.mesh_id = mesh.getId();
new_mesh.base_index = m_sponzaData.indices.size();
new_mesh.base_vertex = m_sponzaData.vertices.size();
new_mesh.base_xform = m_sponzaData.modelMatrices.size();
std::vector<Vertex> mesh_vertexData(mesh_positions.size());
for (size_t j = 0; j < mesh_positions.size(); j++)
{
Vertex currentVertex;
currentVertex.Position = (glm::vec3&)mesh_positions[j];
currentVertex.Normal = (glm::vec3&)mesh_normals[j];
if (mesh_texCoords.size() == 0)
{
currentVertex.TexCoords = glm::vec2(0, 0);
}
else
{
currentVertex.TexCoords = (glm::vec2&)mesh_texCoords[j];
}
mesh_vertexData[j] = currentVertex;
}
int instanceIndex;
for (size_t j = 0; j < allInstances.size(); j++)
{
auto& currentInstance = allInstances[j];
//modelMatrices = new glm::mat4[allInstances.size()];
glm::mat4 model_xform;
if (currentInstance.getMeshId() == mesh.getId())
{
instanceIndex = j;
model_xform = glm::translate(glm::mat4((const glm::mat4x3 &) currentInstance.getTransformationMatrix()), glm::vec3(0, 0, 0));
m_sponzaData.modelMatrices.push_back(model_xform);
new_mesh.instance_count++;
}
}
m_sponzaData.vertices.insert(m_sponzaData.vertices.end(), mesh_vertexData.begin(), mesh_vertexData.end());
m_sponzaData.indices.insert(m_sponzaData.indices.end(), mesh_elements.begin(), mesh_elements.end());
m_sponzaData.entries.push_back(new_mesh);
mesh_map[mesh.getId()] = new_mesh;
material_map[mesh.getId()] = allInstances[instanceIndex].getMaterialId();
}
}
void MyView::setupSponzaBuffers()
{
// Fill Buffers
glBindBuffer(GL_ARRAY_BUFFER, m_sponza.VBO);
glBufferData(GL_ARRAY_BUFFER, m_sponzaData.vertices.size() * sizeof(Vertex), m_sponzaData.vertices.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_sponza.EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_sponzaData.indices.size() * sizeof(unsigned int), m_sponzaData.indices.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindVertexArray(m_sponza.VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_sponza.EBO);
glBindBuffer(GL_ARRAY_BUFFER, m_sponza.VBO);
// Position attribute
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), TGL_BUFFER_OFFSET(0));
// Normals attribute
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), TGL_BUFFER_OFFSET(sizeof(float) * 3));
// TexCoords attribute
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), TGL_BUFFER_OFFSET(sizeof(float) * 6));
glGenBuffers(1, &m_sponza.instance_VBO);
glBindBuffer(GL_ARRAY_BUFFER, m_sponza.instance_VBO);
glBufferData(GL_ARRAY_BUFFER, m_sponzaData.modelMatrices.size() * sizeof(glm::mat4), m_sponzaData.modelMatrices.data(), GL_STATIC_DRAW);
// Set appropriate attrib pointers for instance buffer
for (GLint i = 0; i < 4; i++)
{
glEnableVertexAttribArray(3 + i);
glVertexAttribPointer(3 + i, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), TGL_BUFFER_OFFSET(sizeof(float) * i * 4));
glVertexAttribDivisor(3 + i, 1);
}
// Unbind VAO
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
|
8be4fb3a93b78e326cf8ab6aa5e8991f7937fb4c
|
98e7b300f79707cc2151b2b1da991c8559270bca
|
/src/world.cpp
|
9f746325188f3a6d2e5c915ea359d44ba7cf39f7
|
[] |
no_license
|
qnope/TutorialPhotonMapCPU
|
8849373547f71f2dd0a2b4b5b1540132a93c31ef
|
5d1ea7b2052af6c7d012752b302f901badcb3a36
|
refs/heads/master
| 2016-09-06T15:09:03.339513
| 2015-09-06T20:59:11
| 2015-09-06T20:59:11
| 41,703,734
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,421
|
cpp
|
world.cpp
|
#include "include/world.hpp"
World World::world;
Random Random::random(1'000'000);
using namespace std;
using namespace glm;
vec3 getRadianceFromNearest(Ray const &_ray) {
Ray ray = _ray;
auto nearest = World::world.findNearest(ray);
if(get<0>(nearest) != nullptr) {
ray.distMax = get<1>(nearest);
ray.origin += ray.direction * ray.distMax;
return get<0>(nearest)->getReflectedRadiance(ray);
}
return vec3();
}
void tracePhoton(Photon const &_photon) {
Photon photon = _photon;
Ray ray(photon.position + photon.direction * RAY_EPSILON, photon.direction);
auto nearest = World::world.findNearest(ray);
if(get<0>(nearest) != nullptr) {
photon.position += photon.direction * get<1>(nearest);
get<0>(nearest)->bouncePhoton(photon);
}
}
void traceShadowPhoton(const Photon &_photon) {
Photon photon = _photon;
Ray ray(photon.position + photon.direction * RAY_EPSILON, photon.direction);
photon.flux = -photon.flux;
auto nearest = World::world.findNearest(ray);
while(get<0>(nearest) != nullptr) {
ray.origin += ray.direction * get<1>(nearest);
photon.position = ray.origin;
if(dot(ray.direction, get<0>(nearest)->getNormal(ray.origin)) < 0.f)
World::world.addPhoton(photon);
ray.origin += RAY_EPSILON * ray.direction;
nearest = World::world.findNearest(ray);
}
}
|
529b91ff51f9e17e970e423b8b8e016ef7f9f0fb
|
db92a3f5f885a6733b385531f0109bfdb2cdca72
|
/src/application/Component/button/graphics/tlgraphicspushbutton.cpp
|
fae9c67a32419ff0f952fd9fe98cf7de6542521c
|
[] |
no_license
|
zb872676223/QtFor2048
|
fa850329fc8102088bc2cd375af849ca40a47a91
|
b31dff79294e9ffeb2298a0bb7982883b6987bba
|
refs/heads/master
| 2022-12-18T20:15:57.280852
| 2020-09-29T15:01:34
| 2020-09-29T15:01:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 725
|
cpp
|
tlgraphicspushbutton.cpp
|
#include "tlgraphicspushbutton.h"
#include <QPainter>
TLGraphicsPushButton::TLGraphicsPushButton(QGraphicsObject *parent)
: TLGraphicsBaseControl(parent)
{
}
void TLGraphicsPushButton::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
painter->setRenderHint(QPainter::Antialiasing);
drawButtonStuff(painter, dragMode(), this->rect().toRect(), getDevicePixelRatio(), m_bHover);
// if(!m_Image.isNull()){
// drawFixImage(painter, this->rect().toRect(), m_Image, devicePixelRatio());
// }
// if(!m_strText.isEmpty()){
// painter->setPen(pen());
// painter->setFont(this->font());
// painter->drawText(rect(), m_nAlign, m_strText);
// }
}
|
7b38ea2628afe94288d0ea0a2d94e8e6754db527
|
6b2a8dd202fdce77c971c412717e305e1caaac51
|
/solutions_5708921029263360_0/C++/AlexAlvarez/solution.cc
|
ce8f41971f79cc788dab33954931cad60e5d4135
|
[] |
no_license
|
alexandraback/datacollection
|
0bc67a9ace00abbc843f4912562f3a064992e0e9
|
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
|
refs/heads/master
| 2021-01-24T18:27:24.417992
| 2017-05-23T09:23:38
| 2017-05-23T09:23:38
| 84,313,442
| 2
| 4
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,044
|
cc
|
solution.cc
|
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
using ll = long long;
struct Triple
{
Triple() { }
Triple(int xx, int yy, ll mmask) : x(xx), y(yy), mask(mmask) { }
bool operator<(Triple const& other) const
{
if (x == other.x)
return y == other.y ? mask < other.mask : y < other.y;
return x < other.x;
}
int x, y;
ll mask;
};
int a, b, c, k;
map<Triple, int> M;
map<Triple, int> movement;
ll fix(ll mask, int qtt)
{
vector<int> v(c);
for (int i = 0; i < c; ++i)
{
v[i] = mask % 11;
mask /= 11;
}
for (int i = 0; i < qtt; ++i)
{
if (++v[i] > k)
return -1;
}
sort(v.begin(), v.end(), std::greater<int>());
ll res = 0;
for (int i = 0; i < c; ++i)
{
res *= 11;
res += v[i];
}
return res;
}
ll fix_mask(ll mask, int qtt, vector<int>& hint)
{
vector<pair<int, int> > v(c);
for (int i = 0; i < c; ++i)
{
v[i].first = mask % 11;
v[i].second = hint[i];
mask /= 11;
}
for (int i = 0; i < qtt; ++i)
{
if (++v[i].first > k)
return -1;
}
sort(v.begin(), v.end(), std::greater<pair<int, int> >());
ll res = 0;
for (int i = 0; i < c; ++i)
{
res *= 11;
res += v[i].first;
}
reverse(v.begin(), v.end());
for (int i = 0; i < c; ++i)
hint[i] = v[i].second;
return res;
}
ostream& operator<<(ostream& out, Triple t)
{
out << t.x << " " << t.y << " [";
for (int i = 0; i < c; ++i)
{
out << " " << t.mask % 11;
t.mask /= 11;
}
out << " ]";
return out;
}
int dp(Triple t)
{
if (t.x == a + 1)
return 0;
if (t.y == b + 1)
return dp(Triple(t.x + 1, 1, 0));
map<Triple, int>::iterator it = M.find(t);
if (it == M.end())
{
int res = -1;
for (int i = 0; i <= min(k, c); ++i)
{
ll new_mask = fix(t.mask, i);
if (new_mask >= 0)
{
int candidate = dp(Triple(t.x, t.y + 1, new_mask)) + i;
if (candidate > res)
{
//cerr << t << endl;
//cerr << " " << i << " " << Triple(t.x, t.y + 1, new_mask) << endl;
res = candidate;
movement[t] = i;
}
}
}
M[t] = res;
return res;
}
return it->second;
}
void print_solution(Triple t, vector<int>& hint)
{
if (t.x == a + 1)
return;
if (t.y == b + 1)
{
for (int i = 1; i <= c; ++i)
hint[i - 1] = i;
print_solution(Triple(t.x + 1, 1, 0), hint);
return;
}
int best = movement[t];
for (int i = 0; i < best; ++i)
cout << t.x << " " << t.y << " " << hint[i] << endl;
ll mask = fix_mask(t.mask, best, hint);
print_solution(Triple(t.x, t.y + 1, mask), hint);
}
void solve()
{
cin >> a >> b >> c >> k;
M.clear();
movement.clear();
cout << dp(Triple(1, 1, 0)) << endl;
vector<int> hint(c);
for (int i = 1; i <= c; ++i)
hint[i - 1] = i;
print_solution(Triple(1, 1, 0), hint);
}
int main()
{
int cases;
cin >> cases;
for (int cas = 1; cas <= cases; ++cas)
{
cout << "Case #" << cas << ": ";
solve();
}
}
|
3da202ce9b79e806bc39f36be8a12fe80e9bb547
|
6dd2d01228723a70bf245fd726ad640a0b800c95
|
/include/inter.h
|
da3515dee7af4cded42103444bcf3eeea626db3f
|
[] |
no_license
|
kederiku/RTS
|
63d2b810139f75d07718c1c7b97359346d7fa480
|
806dbaad5928e72584e01fc90ff465469ed6fec2
|
refs/heads/master
| 2021-01-19T08:20:29.521411
| 2013-02-07T10:36:30
| 2013-02-07T10:36:30
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,164
|
h
|
inter.h
|
#ifndef __INTER_H__
#define __INTER_H__
#include "info.h"
#include "Lib2D.h"
#include "enums.h"
class Building;
class Player;
class Unit;
class Ressources;
struct t_products
{
Lib2D::Container* container;
t_cost* cost;
};
class Inter : public Lib2D::Container
{
Lib2D::Image* __building;
Lib2D::Label* __name;
t_products __unit;
Building* __id_building;
public:
Inter();
virtual ~Inter();
bool Init_Interface(Lib2D::Image** img, const char* name, Player* player, Building* building, Unit* unit);
bool Head_Inter_Building(Lib2D::Image* img, const char* name, Building* building);
bool Head_Inter_Unit(Lib2D::Image* img, const char* name, Unit* unit);
bool Head_Inter_Ressource(Lib2D::Image* img, const char* name, Ressources* ressource);
bool Head_Inter(Lib2D::Image* img, char* hp, const char* name);
void Delete_Interface(void);
bool Init_Production(Player* player);
bool Launch_product(Lib2D::Control* control, void* data);
bool Minus(Lib2D::Control* control, void* data);
bool Plus(Lib2D::Control* control, void* data);
bool Add_Label(Unit* unit);
bool Add_Icon(e_ressource image, int y);
};
#endif
|
07d628c087515ac546989293ccc6a2a18e2e5a67
|
832c996f157f15f09b699c5d4659be63cf568d64
|
/入门综合练习1/三连击升级版.cpp
|
7a95c296c2284d8b76db2ae791e2a5614fb56e91
|
[] |
no_license
|
lzh66666/luogu
|
c94d1296da4ec3b96fe19d05bc44397f19be3a9c
|
216b242d717df4c53ca468436a3cc772f3c2be19
|
refs/heads/master
| 2020-07-16T16:46:25.304856
| 2020-01-14T10:53:45
| 2020-01-14T10:53:45
| 205,826,912
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 721
|
cpp
|
三连击升级版.cpp
|
#include<stdio.h>
#include<string.h>
int a[10];
int count = 0;
int main(){
int d,e,f;
scanf("%d%d%d",&d,&e,&f);
for (int x=1;x<=1000/f;x++){
int i=x*d,j=x*e,k=x*f;
if(j>999 || k>999)
break;
int o=i,p=j,q=k;
int flag=0;
memset(a,0,sizeof(a));
while(i>0){
a[i%10]++;
i/=10;
}
while(j>0){
a[j%10]++;
j/=10;
}
while(k>0){
a[k%10]++;
k/=10;
}
for (int w=1;w<=9;w++){
if(a[w]!=1) flag=1;
}
if(flag==0){
printf("%d %d %d\n",o,p,q);
count++;
}
}
if(!count)
printf("No!!!");
return 0;
}
|
25b3d2467f54dac5597a9f4af353e60d5ccd1faf
|
aea4d46a9150efdc502453b275f014a5a9b6c04d
|
/config_proc.h
|
e04332655cf2dbc8d392ec13bad0705ec03fcd7d
|
[
"MIT"
] |
permissive
|
JetLinWork/qt_xml_in_dir
|
9f34f90609b61eceef68de65e6562e6dedd9b974
|
e122a6c7df2fe6dd29bcc1dea267810e04c4a94b
|
refs/heads/main
| 2023-03-16T02:19:04.215874
| 2021-03-06T07:46:11
| 2021-03-06T07:46:11
| 345,027,716
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,462
|
h
|
config_proc.h
|
#ifndef CONFIG_PROC_H
#define CONFIG_PROC_H
# include <stdio.h>
# include <stdlib.h>
#include <QDomDocument>
#include <QFile>
#include <QTextStream>
#include <QTextCodec>
#include <QMessageBox>
#include <QFileInfo>
#include <QDir>
#include <QFileDialog>
#include <QDebug>
namespace Ui {
class ConfigProc;
class AppfsVerProc;
}
class AppfsVer
{
public:
AppfsVer();
~AppfsVer();
struct TAppfsVerTag
{
int major_ver;
int minor_ver;
int rev_ver;
int sub_ver;
};
typedef struct TAppfsVerTag TAppfsVer;
public:
bool ReadFile(QString file_path);
bool SaveFile(TAppfsVer &version_save);
QString &VersionStr() { return ver_string_; }
TAppfsVer &Version() { return version_; }
private:
QString file_path_;
QString content_;
QString ver_string_;
TAppfsVer version_;
};
class MainWindow;
class ConfigProc
{
public:
ConfigProc(MainWindow* win) : winodow((QObject*)win) {}
~ConfigProc() {}
public:
enum TFileTypeTag
{
kXmlFileType = 0,
kTxtFileType,
kCfgFileType,
kMkFileType,
kIniFileType,
kFileTypeMax,
};
typedef enum TFileTypeTag TFileType;
public:
bool LoadHmi(const QString &file_path);
bool LoadDir(const QString dir);
bool FindElement(const QString &file, const QString &path, QDomElement &target_element);
QString QueryElement(const QString &file, const QString &path, const QString attr = "value");
bool SetElement(const QString &file, const QString &path, const QString value = "", const QString attr = "value");
bool RemoveElement(const QString &file, const QString &path);
bool RemoveElementAttr(const QString &file, const QString &path, const QString attr = "value");
bool AddElement(const QString &file, const QString &path, const QString &name);
bool SaveXML(const QString &file);
AppfsVer &AppVer() { return appfs_ver_; }
private:
bool ScanFile(const QString &dir_name, const QStringList &filters, TFileType f_type);
bool LoadXmlDoc(QStringList &file_list);
bool LoadMkDoc(QStringList &file_list);
QString XmlFilePath(const QString &file);
QDomDocument *XmlDom(const QString &file);
private:
QObject* winodow;
QStringList file_path_list_[kFileTypeMax];
QStringList file_name_list_[kFileTypeMax];
QList<QDomDocument> xml_list_;
QDomDocument hmi_config_;
AppfsVer appfs_ver_;
};
#endif // CONFIG_PROC_H
|
6c0db6cdff0c60ea191c4e2662d74ad742c57635
|
db0da227137c5819bdff6da365c3dff7ad484092
|
/training contest (NEERC)/题解/neerc-2015-archive/adjustment/adjustment_pkun.cpp
|
d12d23a1a8f5870d85ed501498e20c548ad2a090
|
[] |
no_license
|
hzy9819/ICPC-Problem-Code-Solution
|
79351c4a86c113742ab4431ab3581691a87274eb
|
7e6ffc0019cc40291456c129f0b541f7e58137a3
|
refs/heads/main
| 2023-03-30T05:26:55.686854
| 2021-04-10T09:52:56
| 2021-04-10T09:52:56
| 356,527,484
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,152
|
cpp
|
adjustment_pkun.cpp
|
//#include <iostream>
#include <fstream>
#include <vector>
#include <set>
#include <map>
#include <cstring>
#include <string>
#include <cmath>
#include <cassert>
#include <ctime>
#include <algorithm>
#include <sstream>
#include <list>
#include <queue>
#include <deque>
#include <stack>
#include <cstdlib>
#include <cstdio>
#include <iterator>
#include <functional>
#include <bitset>
#define mp make_pair
#define pb push_back
#ifdef LOCAL
#define eprintf(...) fprintf(stderr,__VA_ARGS__)
#else
#define eprintf(...)
#endif
#define TIMESTAMP(x) eprintf("["#x"] Time : %.3lf s.\n", clock()*1.0/CLOCKS_PER_SEC)
#define TIMESTAMPf(x,...) eprintf("[" x "] Time : %.3lf s.\n", __VA_ARGS__, clock()*1.0/CLOCKS_PER_SEC)
#if ( ( _WIN32 || __WIN32__ ) && __cplusplus < 201103L)
#define LLD "%I64d"
#else
#define LLD "%lld"
#endif
using namespace std;
#define TASKNAME "adjustment"
#ifdef LOCAL
static struct __timestamper {
string what;
__timestamper(const char* what) : what(what){};
__timestamper(const string& what) : what(what){};
~__timestamper(){
TIMESTAMPf("%s", what.data());
}
} __TIMESTAMPER("end");
#else
struct __timestamper {};
#endif
typedef long long ll;
typedef long double ld;
int main(){
assert(freopen(TASKNAME".in","r",stdin));
assert(freopen(TASKNAME".out","w",stdout));
int n, q;
scanf("%d%d",&n,&q);
long long totr, totc;
int cntr, cntc;
totr = totc = cntr = cntc = 0;
set<int> sc, sr;
for (int i = 0; i < q; i++) {
char c; int id;
scanf(" %c %d", &c, &id);
long long ans = ll(n) * ll(n+1) / 2;
if (c == 'R') {
if (sr.find(id) == sr.end()) {
ans += ll(n - cntc) * id;
ans -= totc;
totr += id;
cntr++;
sr.insert(id);
} else {
ans = 0;
}
} else {
if (sc.find(id) == sc.end()) {
ans += ll(n - cntr) * id;
ans -= totr;
totc += id;
cntc++;
sc.insert(id);
} else {
ans = 0;
}
}
printf("%lld\n", ans);
}
return 0;
}
|
c3006b18b01900cb7028e429db201bac1a09cb5c
|
3401f7be14ae1f4a7b94bf765f286de8cac76097
|
/Board.h
|
2518c444442147f142f63233d14a213493a76a85
|
[] |
no_license
|
KockataEPich/Chess
|
32809a416f52e583a145ae5593fb027f67c1e5cb
|
a2b1b855db0e55a5e8fe62346bf64f2e67a6fe7e
|
refs/heads/master
| 2023-08-03T03:53:29.806590
| 2021-07-03T17:44:07
| 2021-07-03T17:44:07
| 369,745,036
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 991
|
h
|
Board.h
|
#pragma once
#include "Square.h"
#include "Move.h"
#include "Player.h"
#include "PlayerEnum.h"
#include <vector>
#include <memory>
class Square;
class Move;
typedef std::shared_ptr<Square> shr_sqr;
typedef std::vector<shr_sqr> sqr_vec;
typedef std::vector<sqr_vec*> board_vec;
typedef std::vector<std::shared_ptr<ChessPiece>> piece_vec;
typedef std::shared_ptr<ChessPiece> shr_piece;
class Board{
private:
board_vec* board;
piece_vec* whitePieces;
piece_vec* blackPieces;
bool gameIsOver = false;
std::string winner;
public:
Board();
Board(board_vec* board);
~Board();
board_vec* getBoard();
std::string getWinner();
bool isOver();
piece_vec* getPieceList(PlayerSide side);
shr_sqr operator()(int x, int y);
void makeMove(Move* move);
void removePiece(shr_piece pieceToDelete);
void checkPieceAndDeleteIfNecessary(shr_piece newPiece, Move* move);
void checkForCastleUp(Move* move, shr_sqr newSquare);
void handlePiecePromotion(shr_sqr newSquare, Move* move);
};
|
69d4f785873579f2f59011c16ecaca5adc1b6b00
|
019a9c2de0eeccb4f31eecbeb0e91cc2db5404c2
|
/LeetCode/1207. Unique Number of Occurances.cpp
|
d68331722ded6a69a5e02fd217874c1e55632f71
|
[] |
no_license
|
Prakhar-FF13/Competitive-Programming
|
4e9bd1944a55b0b89ff21537e0960f058f1693fd
|
3f0937475d2985da323e5ceb65b20dc458155e74
|
refs/heads/master
| 2023-01-09T05:09:27.574518
| 2023-01-04T11:32:01
| 2023-01-04T11:32:01
| 133,995,411
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,386
|
cpp
|
1207. Unique Number of Occurances.cpp
|
#include<iostream>
#include<cstdio>
#include<string.h>
#include<climits>
#include<sstream>
#include<vector>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<unordered_map>
#include<unordered_set>
#include<cmath>
#include<algorithm>
#include<numeric>
#include<functional>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<pii> vii;
typedef vector<pll> vll;
#define rep(i,a,b) for(int i=a;i<b;i++)
#define fsi ios_base::sync_with_stdio(false);cin.tie(0);
#define RW() freopen("read.txt","r",stdin);freopen("write.txt","w",stdout);
#define MOD 1000000007
#define tt() int t;cin>>t;while(t--)
#define pb push_back
#define mp make_pair
#define ms memset
#define all(v) v.begin(),v.end()
#define pob pop_back
class Solution {
public:
bool uniqueOccurrences(vector<int>& arr) {
int numbCount[2005];
memset(numbCount, 0, sizeof(numbCount));
set<int> Uniquenums;
for(int i = 0; i < arr.size() ; i++){
numbCount[arr[i] + 1000]++;
Uniquenums.insert(arr[i]);
}
set<int> Uniquecount;
for(int i = 0 ; i < 2002 ; i++)
if(numbCount[i] != 0)
Uniquecount.insert(numbCount[i]);
return (Uniquecount.size() == Uniquenums.size());
}
};
int main(){
return 0;
}
|
9f70161c3c25801cae05dffb85bc16e079509065
|
ec9ae74d76b85fc732919e08a29a0cebf8fc77dd
|
/src/XDxCoreLibrary/XSRVManager.cpp
|
307841b20d3d4992ec5c8efa81f3ae6992003e28
|
[] |
no_license
|
shkuk88/MapTool
|
681759d38d55b87637a458c6e651e7c6fee8ac12
|
b9ff8691eccae9e4e6b385964fe14d9bbae8b61a
|
refs/heads/master
| 2020-04-09T11:03:38.434647
| 2019-01-18T02:10:32
| 2019-01-18T02:10:32
| 160,293,868
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 749
|
cpp
|
XSRVManager.cpp
|
#include "XSRVManager.h"
TString XSRVManager::Add(ID3D11Device* pd3dDevice, TString szTexture)
{
TString sz = szTexture;
for (auto iter : m_SRVList)
{
if (iter.first == szTexture)
return iter.first;
}
ComPtr<ID3D11ShaderResourceView> pSRV = NULL;
hr = D3DX11CreateShaderResourceViewFromFile(pd3dDevice, szTexture.c_str(), NULL, NULL, pSRV.GetAddressOf(), NULL);
m_SRVList.insert(make_pair(szTexture, pSRV));
return szTexture;
}
ComPtr<ID3D11ShaderResourceView> XSRVManager::Find(TString szTexture)
{
if(szTexture.c_str()==_T("none")) return nullptr;
auto iter = m_SRVList.find(szTexture);
return iter->second;
}
void XSRVManager::Clear()
{
m_SRVList.clear();
}
XSRVManager::XSRVManager()
{
}
XSRVManager::~XSRVManager()
{
}
|
e385efc9541c064c60f4248629f423c3c1d791ac
|
cd2e59f2fd3a1c0eb5fa6f58288a046118f6bce6
|
/squirrel_recognition/src/test_recognizer2d.cpp
|
b69b8b42963bfc61b5a251e92cff5c8fd690fc5c
|
[] |
no_license
|
squirrel-project/squirrel_perception
|
2b1834f33aca3367b9a8f7288ed3db271558d4dd
|
0fdfd1f2753daf4fe97955a88cc65021b64249f2
|
refs/heads/indigo_dev
| 2021-01-20T10:46:22.646839
| 2018-03-15T15:50:12
| 2018-03-15T15:50:12
| 19,309,285
| 1
| 7
| null | 2018-04-03T08:14:02
| 2014-04-30T09:51:59
|
C++
|
UTF-8
|
C++
| false
| false
| 4,725
|
cpp
|
test_recognizer2d.cpp
|
/*
* main.cpp
*
* Created on: Feb 20, 2014
* Author: Thomas Faeulhammer
*/
#include <ros/ros.h>
#include <sensor_msgs/Image.h>
#include <std_msgs/String.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <v4r/common/pcl_opencv.h>
#include <v4r/io/filesystem.h>
#include <squirrel_object_perception_msgs/Recognize2d.h>
class Recognizer2dDemo
{
private:
typedef pcl::PointXYZRGB PointT;
ros::NodeHandle *n_;
ros::ServiceClient sv_rec_client_;
ros::Subscriber sub_pc_;
std::string directory_;
std::string topic_;
bool called_service_;
sensor_msgs::Image::ConstPtr scene;
public:
Recognizer2dDemo()
{
called_service_ = false;
}
void callSvRecognizerUsingCam(const sensor_msgs::Image::ConstPtr& msg)
{
std::cout << "Received camera image.\n" << std::endl;
squirrel_object_perception_msgs::Recognize2d srv_rec;
srv_rec.request.image = *msg;
if (sv_rec_client_.call(srv_rec)) {
std::cout << "Call done..." << std::endl;
std::cout << "found " << srv_rec.response.ids.size() << " objects:\n";
for(size_t i = 0; i < srv_rec.response.ids.size(); i++)
{
std::cout << " ID: " << srv_rec.response.ids[i] << " with confidence " << srv_rec.response.confidences[i] <<
"\n position: " << srv_rec.response.transforms[i].translation << std::endl;
}
}
else
ROS_ERROR("Failed to call service");
called_service_ = true;
}
bool callSvRecognizerUsingFiles()
{
std::vector<std::string> test_image = v4r::io::getFilesInDirectory(directory_, ".*.png", false);
for(size_t i=0; i < test_image.size(); i++)
{
cv::Mat image = cv::imread(directory_ + "/" + test_image[i], 1);
std::cout<< "Opening file " << test_image[i] << std::endl;
cv_bridge::CvImage out_msg;
out_msg.header.frame_id = "/kinect_rgb_optical_frame";
out_msg.header.stamp = ros::Time::now();
out_msg.encoding = sensor_msgs::image_encodings::BGR8;
out_msg.image = image;
squirrel_object_perception_msgs::Recognize2d srv_rec;
srv_rec.request.image = *out_msg.toImageMsg();
if (sv_rec_client_.call(srv_rec))
{
std::cout << "found " << srv_rec.response.ids.size() << " objects:\n";
for(size_t i = 0; i < srv_rec.response.ids.size(); i++)
{
std::cout << " ID: " << srv_rec.response.ids[i] << " with confidence " << srv_rec.response.confidences[i] <<
"\n position: " << srv_rec.response.transforms[i].translation << std::endl;
}
}
else
{
ROS_ERROR("Error calling recognition service. ");
return false;
}
}
return true;
}
bool initialize(int argc, char ** argv)
{
ros::init (argc, argv, "test_recognizer2d");
n_ = new ros::NodeHandle ( "~" );
std::cout << "You can either select a topic param 'topic' or "
" test pcd files from a directory by specifying param 'directory'." << std::endl;
std::string service_name_sv_rec = "/squirrel_recognize_objects_2d";
sv_rec_client_ = n_->serviceClient<squirrel_object_perception_msgs::Recognize2d>(service_name_sv_rec);
if(n_->getParam ( "directory", directory_ ) && !directory_.empty())
{
std::cout << "Opening directory " << directory_ << std::endl;
callSvRecognizerUsingFiles();
}
else
{
if(!n_->getParam ( "topic", topic_ ))
{
topic_ = "/kinect/rgb/image_rect_color";
}
std::cout << "Connecting to camera on topic " << topic_ << std::endl;
//for (int i = 0; i < 10; i++) {
// scene = ros::topic::waitForMessage<sensor_msgs::Image>(topic_, *n_, ros::Duration(20));
// //}
// callSvRecognizerUsingCam(scene);
ros::Subscriber sub_pc = n_->subscribe (topic_, 1, &Recognizer2dDemo::callSvRecognizerUsingCam, this);
ros::Rate loop_rate (1);
// poll until we did receive a point cloud
sleep(2);
while(!called_service_)
{
ros::spinOnce ();
loop_rate.sleep ();
}
}
return true;
}
};
int
main (int argc, char ** argv)
{
Recognizer2dDemo m;
m.initialize(argc, argv);
return 0;
}
|
a1feaab2f1cab3f2fe07acca4ef4fca863ea9b2b
|
ed9d316a879bbdcbc221ef5e36423e086dddc08e
|
/src/npgsl/npRandom.h
|
c68b1fb292a65b53f2b5bd9ed5f29742b60b69f0
|
[] |
no_license
|
npadmana/nputils
|
005d2bcbf96c3ef245ebde01082849b1af207888
|
c7ddb580be2dd949b581ae2db93e32c1452bd496
|
refs/heads/master
| 2021-01-18T17:25:12.947905
| 2013-02-02T04:58:36
| 2013-02-02T04:58:36
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,942
|
h
|
npRandom.h
|
/*
* npRandom.h
*
* Created on: Jul 20, 2012
* Author: npadmana
*/
#ifndef NPRANDOM_H_
#define NPRANDOM_H_
#include <gsl/gsl_rng.h>
#include <gsl/gsl_qrng.h>
#include <vector>
#include <Eigen/Core>
/** Wrapper around the GSL random number generators
*
* Automatically switches to using the Mersenne Twister
*
* NOTE : This class cannot be copied or assigned.
*/
class npRandom {
public:
/** Constructor
*
* @param seed (unsigned long int)
*/
npRandom(unsigned long int seed);
/// Destructor
~npRandom();
/// Returns a random number in [0,1)
double operator()();
/** Fill an n-dimensional vector with random numbers in [0,1)
*
* @param n (integer)
* returns vector<double>
*/
std::vector<double> operator()(int n);
/** Returns a random 3D direction
*
* returns Eigen::Vector3d(x,y,z)
* such that sqrt(x^2 + y^2 + z^2) = 1.
*/
Eigen::Vector3d dir3d();
private :
// Disable copy and assignment
npRandom(const npRandom& x);
npRandom& operator=(const npRandom& x);
// Random number engine
gsl_rng *ran;
};
/** Wrapper around the GSL quasi-random number generators
*
* The default here is the Niederreiter sequence, but Sobol, Halton, and
* reverse Halton sequences are also available.
*
* These are gsl_qrng_niederreiter_2, gsl_qrng_sobol, gsl_qrng_halton, and
* gsl_qrng_reversehalton.
*
* NOTE : This class cannot be copied or assigned.
*/
class npQuasiRandom {
public:
/** Constructor
*
* @param dim (int)
*/
npQuasiRandom(int _dim, const gsl_qrng_type *type= gsl_qrng_niederreiter_2);
/// Destructor
~npQuasiRandom();
/// Returns the next quasi-random number in [0,1)^dim
std::vector<double> operator()();
private :
// Disable copy and assignment
npQuasiRandom(const npQuasiRandom& x);
npQuasiRandom& operator=(const npQuasiRandom& x);
// Random number engine
gsl_qrng *qran;
// Dimension
int dim;
};
#endif /* NPRANDOM_H_ */
|
2204b03f3e9ef2cd7b0d2ff596320dc387f05aa2
|
6d54a7b26d0eb82152a549a6a9dfde656687752c
|
/examples/android/CHIPTool/app/src/main/cpp/native-lib.cpp
|
4a0235adbff06ec2f6c10a60a71a643179c0165e
|
[
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
project-chip/connectedhomeip
|
81a123d675cf527773f70047d1ed1c43be5ffe6d
|
ea3970a7f11cd227ac55917edaa835a2a9bc4fc8
|
refs/heads/master
| 2023-09-01T11:43:37.546040
| 2023-09-01T08:01:32
| 2023-09-01T08:01:32
| 244,694,174
| 6,409
| 1,789
|
Apache-2.0
| 2023-09-14T20:56:31
| 2020-03-03T17:05:10
|
C++
|
UTF-8
|
C++
| false
| false
| 1,406
|
cpp
|
native-lib.cpp
|
/*
* Copyright (c) 2020 Project CHIP Authors
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// TODO: Build this out with native code to perform tasks with CHIP stack
// QRCode parsing
// Echo request/response processing
// On/Off request/response processing
#include <Base38.h>
#include <SetupPayload.h>
#include <jni.h>
#include <lib/support/CodeUtils.h>
// This is just a sample function to demonstrate end-to-end calling in/out of CHIP stack
// is working.
std::string base38Encode(void)
{
const uint8_t buf[] = { 0, 1, 2, 3, 4, 5 };
size_t size = ArraySize(buf);
return chip::base38Encode(&buf[0], size);
}
extern "C" JNIEXPORT jstring JNICALL Java_com_google_chip_chiptool_CHIPNativeBridge_base38Encode(JNIEnv * env, jobject thiz)
{
std::string s = base38Encode();
return env->NewStringUTF(s.c_str());
}
|
3f5d0ccfb9f0b49d9e920620dd4d3a8bda93d17d
|
5a7d3db1f4dc544d47430dcecf9de5ae2990fe88
|
/.emacs.d/undohist/!home!sirogami!programming!compe!AtCoder!ARC!059!d2.cc
|
84b905db7953007d522b5e833a2495cfd31bc45a
|
[] |
no_license
|
sirogamichandayo/emacs_sirogami
|
d990da25e5b83b23799070b4d1b5c540b12023b9
|
c646cfd1c4a69cef2762432ba4492e32c2c025c8
|
refs/heads/master
| 2023-01-24T12:38:56.308764
| 2020-12-07T10:42:35
| 2020-12-07T10:42:35
| 245,687,325
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,569
|
cc
|
!home!sirogami!programming!compe!AtCoder!ARC!059!d2.cc
|
((digest . "98d19acffa406b2ade6c020bc7de48ec") (undo-list nil (440 . 441) nil (432 . 440) nil (427 . 432) nil (412 . 413) nil ("2" . -412) ((marker . 441) . -1) 413 nil (409 . 414) nil (407 . 409) nil (406 . 407) nil (404 . 405) (403 . 405) ("\"" . -403) (403 . 404) ("\"" . -403) (402 . 404) nil (400 . 402) nil (396 . 400) nil (408 . 409) nil (404 . 408) nil (402 . 404) nil (398 . 402) nil (396 . 398) nil (395 . 396) nil (393 . 395) nil (388 . 393) nil (379 . 383) (" " . 379) (386 . 387) (379 . 382) (" " . 379) ((marker . 441) . -4) (386 . 387) nil (383 . 386) nil (379 . 383) (378 . 383) nil (374 . 377) (" " . 374) ((marker . 441) . -4) (378 . 380) ("{" . -378) (378 . 379) nil (373 . 378) nil (369 . 371) nil (368 . 369) (367 . 369) ("[" . -367) (366 . 368) nil (362 . 366) nil (360 . 361) (359 . 361) ("[" . -359) (358 . 360) nil (357 . 359) ("(" . -357) (357 . 358) nil (354 . 357) nil (476 . 477) nil (470 . 475) (469 . 471) ("\"" . -469) (469 . 470) ("\"" . -469) (469 . 470) nil ("1" . -469) ((marker . 441) . -1) 470 nil (469 . 470) nil (481 . 482) nil (477 . 481) nil (475 . 477) nil (471 . 475) nil (469 . 471) nil (468 . 469) nil (466 . 468) nil (461 . 466) nil (455 . 456) (" " . 455) (460 . 461) (455 . 456) (" " . 455) ((marker . 441) . -1) (459 . 460) nil (456 . 459) nil (454 . 456) (" " . 454) ((marker . 441) . -1) 455 nil (453 . 455) nil (445 . 446) nil (437 . 445) nil (433 . 437) (t 24271 15756 84174 180000) nil (416 . 420) nil (415 . 416) nil (413 . 415) nil (412 . 413) nil (410 . 411) (409 . 411) ("\"" . -409) (409 . 410) ("\"" . -409) (408 . 410) nil (406 . 408) nil (402 . 406) nil (414 . 415) nil (410 . 414) nil (408 . 410) nil (404 . 408) nil (402 . 404) nil (401 . 402) nil (399 . 401) nil (394 . 399) nil (386 . 389) (" " . 386) (392 . 393) (386 . 388) (" " . 386) ((marker . 441) . -3) ((marker . 478) . -3) ((marker . 478) . -3) ((marker . 478) . -3) (392 . 393) nil (389 . 392) (t 24271 15739 176360 754000) nil (386 . 389) (385 . 389) nil (382 . 384) (" " . 382) ((marker . 441) . -3) (385 . 387) ("{" . -385) (385 . 386) nil (381 . 385) nil (376 . 379) (375 . 377) ("[" . -375) (370 . 376) nil (368 . 369) (367 . 369) ("[" . -367) (366 . 368) nil (365 . 367) ("(" . -365) (365 . 366) nil (362 . 365) nil (359 . 362) (" " . 359) ((marker . 441) . -2) 361 nil (358 . 361) nil (351 . 354) (350 . 354) nil (347 . 349) (" " . 347) ((marker . 441) . -3) ((marker . 347) . -3) (350 . 352) ("{" . -350) (350 . 351) nil (346 . 350) nil (339 . 345) nil ("+" . -339) ((marker . 441) . -1) ("=" . -340) ((marker . 441) . -1) (" " . -341) ((marker . 441) . -1) 342 nil (337 . 342) nil ("N" . -337) ((marker . 441) . -1) 338 nil (337 . 338) nil (336 . 338) ("(" . -336) (336 . 337) nil (333 . 336) nil (331 . 333) (330 . 333) nil (328 . 329) (" " . 328) (330 . 332) ("{" . -330) (330 . 331) nil (327 . 330) nil (323 . 326) nil (322 . 323) nil (321 . 322) nil (320 . 321) nil (")" . -320) (320 . 321) (")" . -320) (320 . 321) (319 . 321) ("(" . -319) (319 . 320) nil (316 . 319) nil (312 . 314) nil (311 . 312) nil (309 . 311) ("(" . -309) (309 . 310) nil (296 . 309) nil (295 . 296) (t 24271 15684 840961 285000) nil ("b" . -297) ((marker . 441) . -1) 298 nil (297 . 298) (t 24271 15659 81246 534000) nil (295 . 297) (" " . 295) ((marker . 441) . -1) 296 nil (294 . 296) nil (293 . 294) nil (291 . 293) nil (289 . 291) nil (284 . 289) nil (283 . 284) nil (275 . 283) nil ("S" . -275) ((marker . 441) . -1) 276 nil (275 . 276) (t 24271 15609 41801 756000) nil (274 . 275) (" " . 274) nil (1 . 278) nil undo-tree-canary))
|
0ef11e7d0f830c7cfdf3edd18cb486b2090c10ba
|
addaa6d642e791808c50c5b7b1671d9ba5ce9314
|
/src/gui/votedialog.hpp
|
70995b50c3a4880caa1850ac06667b89bceeda9a
|
[] |
no_license
|
JRandomHacker/CS429-Avalon
|
2418c1a852e44029d920d8628602b1e1e669526a
|
6daa935a111ce7238ba7bc8b2b32f03a33a6811a
|
refs/heads/master
| 2021-01-19T17:44:41.187161
| 2015-05-04T03:22:44
| 2015-05-04T03:22:44
| 30,218,515
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 283
|
hpp
|
votedialog.hpp
|
#ifndef VOTEDIALOG_H
#define VOTEDIALOG_H
#include <QDialog>
namespace Ui {
class VoteDialog;
}
class VoteDialog : public QDialog
{
Q_OBJECT
public:
explicit VoteDialog(QWidget *parent = 0);
~VoteDialog();
private:
Ui::VoteDialog *ui;
};
#endif // VOTEDIALOG_H
|
1073f32f315b1e4eb1e9a5da51a8bd9669d0c7f6
|
97086e933088f069c92a53443e63585be06a1630
|
/include/details/inventory.hh
|
6d5d9bf59952198691aef074a1d8271036cefff6
|
[] |
no_license
|
light0222/BotUI
|
20e1f9668f420680840356d6b8d9a1709e31189a
|
9b8e2b5dc7eaf0b2d1d428f51b4951ad0df56969
|
refs/heads/master
| 2021-08-19T08:26:14.743472
| 2017-11-25T13:21:31
| 2017-11-25T13:21:31
| 112,004,483
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 337
|
hh
|
inventory.hh
|
#ifndef DETAILS_INVENTORY_HH
#define DETAILS_INVENTORY_HH
#include <QWidget>
namespace Ui {
class DetailsInventory;
}
class DetailsInventory : public QWidget
{
Q_OBJECT
public:
explicit DetailsInventory(QWidget *parent = 0);
~DetailsInventory();
private:
Ui::DetailsInventory *ui;
};
#endif // DETAILS_INVENTORY_HH
|
1fdc80ff3a46d70d4556a420168f500f67eb7a1b
|
61884c6d039daaee7c6d43aa59448d4684dafa37
|
/include/callStack.h
|
371196982735a1e548dcb3f3b1094e2c0945edd1
|
[] |
no_license
|
erimsa/call-stack-logger
|
f4d42b9b616770258d144ce62b5b21efdd4909fa
|
a26027f051fc343132ee736ea40cb9ba306259e5
|
refs/heads/master
| 2023-08-31T13:53:35.101374
| 2021-10-10T23:55:28
| 2021-10-10T23:55:28
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,148
|
h
|
callStack.h
|
// Xerus - A General Purpose Tensor Library
// Copyright (C) 2014-2017 Benjamin Huber and Sebastian Wolf.
//
// Xerus is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// Xerus 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Xerus. If not, see <http://www.gnu.org/licenses/>.
//
// For further information on Xerus visit https://libXerus.org
// or contact us at contact@libXerus.org.
/**
* @file
* @brief Header file for the call-stack functionality.
*/
/*
[Tomasz Augustyn] Changes for own usage:
14-03-2021:
* change namespace names,
* add `resolve` standalone function,
* add `__attribute__((no_instrument_function))` to exclude from instrumentation,
* split `bfdResolver` struct to declaration (.h) and definition (.cpp),
* initialize static members `s_bfds` and `s_bfd_initialized` inside the class during
declaration (c++17),
* extract `check_bfd_initialized` function,
* add `ensure_actual_executable` function,
* divide resolving into 2 parts: `resolve_function_name` and `resolve_filename_and_line`
as they use different addresses,
* add `NO_INSTRUMENT` macro,
* get rid of `get_range_of_section` function,
* use `std::optional` in resolving functions,
* make `resolve` function return `ResolvedFrame` struct instead of already formatted
std::string.
*/
#pragma once
#include "types.h"
#include <bfd.h>
#include <dlfcn.h>
#include <map>
#include <memory>
#include <optional>
#include <string>
#include <vector>
#ifndef NO_INSTRUMENT
#define NO_INSTRUMENT __attribute__((no_instrument_function))
#endif
namespace instrumentation {
/**
* @brief class to load symbols and resolve address pointers
* @details uses binutils to interpret bfds. caches the bfd data to only read them once per run of the
* application for the use of dladdr see also
* https://sourceware.org/git/?p=glibc.git;a=blob;f=debug/backtracesyms.c
*/
struct bfdResolver {
public:
/// @brief relevant information belonging to a single bfd
struct storedBfd {
typedef bfd_boolean(deleter_t)(bfd*);
std::unique_ptr<bfd, deleter_t*> abfd;
std::unique_ptr<asymbol*[]> symbols;
intptr_t offset;
storedBfd(bfd* _abfd, deleter_t* _del) : abfd(_abfd, _del) {}
};
NO_INSTRUMENT
static bool ensure_bfd_loaded(Dl_info& _info);
NO_INSTRUMENT
static std::optional<ResolvedFrame> resolve(void* callee_address, void* caller_address);
private:
NO_INSTRUMENT
static std::optional<std::string> resolve_function_name(void* callee_address);
NO_INSTRUMENT
static std::pair<std::string, std::optional<unsigned int>> resolve_filename_and_line(
void* caller_address);
NO_INSTRUMENT
static void check_bfd_initialized();
NO_INSTRUMENT
static std::string get_argv0();
NO_INSTRUMENT
static void ensure_actual_executable(Dl_info& symbol_info);
inline static std::map<void*, storedBfd> s_bfds = {};
inline static bool s_bfd_initialized = false;
inline static std::string s_argv0 = get_argv0();
};
/**
* @brief Returns a string representation of the current call-stack (excluding the function itself).
* @details Per default this uses the binutils library to get the following information:
* [address .section] filename:line (function)
* if all of these are available.
*/
NO_INSTRUMENT
std::vector<std::optional<ResolvedFrame>> get_call_stack();
/**
* @brief Returns std::string with human-readable information about the function which pointer is passed.
*/
NO_INSTRUMENT
std::optional<ResolvedFrame> resolve(void* callee_address, void* caller_address);
} // namespace instrumentation
|
4c825c506ce70ca284f8a4115492095b4ebebcaf
|
984c3e0cecb3c6d579bbd4bfd6d451ef82a8930b
|
/C++ - Object Oriented Programming/trimino/trimino.cc
|
454c4f898b2091446dd3e5a0b3b7218e172663d4
|
[] |
no_license
|
SalloxWave/UniversityPortfolio
|
3675ec18afbafcd042c028bf1cea511551c95c1a
|
6bdadfb36a5d8469a3d166e7f22c68fc1d2a9eb1
|
refs/heads/master
| 2020-03-19T01:57:00.697160
| 2018-06-23T18:45:02
| 2018-06-23T18:45:02
| 135,585,439
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,560
|
cc
|
trimino.cc
|
#include <fstream>
#include <iostream>
#include <exception>
#include <string>
#include <sstream>
#include <array>
#include <vector>
using namespace std;
class Trimino
{
public:
Trimino(int n1, int n2, int n3)
{
numbers = {n1, n2, n3};
}
Trimino(array<int, 3> arr)
: numbers {arr}
{}
bool valid_interval(array<int, 2> interval) const
{
/// Check if all trimino numbers are in correct specified interval.
/// This is done by going through all numbers and check if number
/// is inside of the interval
/// If not all are correct, return false.
for (int i {0}; i < numbers.size(); ++i)
{
if (numbers[i] < interval[0]
|| numbers[i] > interval[1])
{
return false;
}
}
return true;
}
bool valid_order() const
{
/// Check if trimino numbers are rising in clock order.
/// If not, return false.
return (numbers[0] <= numbers[1] && numbers[1] <= numbers[2]
|| numbers[0] >= numbers[1] && numbers[1] <= numbers[2]
|| numbers[0] <= numbers[1] && numbers[1] >= numbers[2]);
}
private:
array<int, 3> numbers;
};
string get_filename();
array<int, 2> get_interval();
bool valid_args(int argc, char* argv[], bool read_from_file = true);
bool valid_file(string const& filename);
bool validate_interval_arg(string const& low, string const& high);
vector<Trimino> get_triminos(istream & input_stream,
array<int, 2> const& interval,
string const& filename = "");
void print_trimino_error(string const& filename,
int file_row, string const& msg,
bool read_from_file = true);
void print_running_instructions(string const& program_name,
bool read_from_file = true);
int main(int argc, char* argv[])
{
//Declare wanted variables
bool read_from_file {true};
ifstream trimino_file;
string filename;
vector<Trimino> trimino_lst;
array<int, 2> interval;
//No arguments given->user manually inputs arguments
if (argc == 1)
{
//Get wanted trimino interval
interval = get_interval();
if (read_from_file)
{
//Get valid filename
string filename = get_filename();
//Open file for reading
trimino_file.open(filename, ifstream::in);
//Get triminos
trimino_lst = get_triminos(trimino_file, interval, filename);
}
else
{
cout << "Input trimino numbers and press enter" << endl;
cout << "Input \"q\" to stop inputting triminos" << endl;
//Make sure cin is empty before using it
cin.ignore(10000,'\n');
cin.clear();
//Get file from console input
trimino_lst = get_triminos(cin, interval);
}
}
//Wrong amount of arguments
else if( (read_from_file && argc != 4)
|| (!read_from_file && argc !=3) )
{
string prog_name (argv[0]);
print_running_instructions(prog_name, read_from_file);
return 1;
}
//Arguments is correct
else if(valid_args(argc, argv, read_from_file))
{
//Triminos should be read from file
if (read_from_file)
{
//Open the file with triminos
filename = string(argv[1]);
trimino_file.open(filename, ifstream::in);
//Get interval from arguments
interval[0] = stoi(argv[2]);
interval[1] = stoi(argv[3]);
//Get the triminos from trimino file
trimino_lst = get_triminos(trimino_file, interval, filename);
}
//Triminos should be read from console input
else
{
cout << "Input trimino numbers and press enter" << endl;
cout << "Input \"q\" to stop inputting triminos" << endl;
//Get interval from arguments
interval[0] = stoi(argv[1]);
interval[1] = stoi(argv[2]);
//Get file from console input
trimino_lst = get_triminos(cin, interval);
}
}
return 0;
}
string get_filename()
{
/// Asks the user for filename.
/// If the inputted filename isn't valid
/// print the error and let user input new filename.
/// This is repeated until the filename is correct.
string filename;
cout << "Input filename to triminos: ";
cin >> filename;
//While inputted filename was not valid
while ( !valid_file(filename) )
{
cout << "Could not find file " << filename << endl;
cout << "Input filename: ";
//Get filename from console input
cin >> filename;
}
return filename;
}
array<int, 2> get_interval()
{
/// Asks the user for low and high interval
/// for the triminos.
/// If the interval wasn't correct, print what was wrong
/// let user input again.
/// This is repeated until the user is correct.
//Declare wanted variables
array<int, 2> interval;
string low;
string high;
cout << "Input high and low interval separated with space: ";
cin >> low >> high;
//While inputted interval was not valid
while ( !validate_interval_arg(low, high) )
{
cout << "\nInput high and low interval separated with space: ";
//Get low and high interval from console input
cin >> low >> high;
}
//Set the correct interval values
interval[0] = stoi(low);
interval[1] = stoi(high);
return interval;
}
bool valid_args(int argc, char* argv[], bool read_from_file)
{
/// Validate and return if the inputted arguments
/// were correct or not.
/// This is done by validating the filename
/// (if filename should be obtained from a file)
/// and the interval.
//Position in argument list for high and low interval
int low_index {1};
int high_index {2};
//Trimino should be read from file
if (read_from_file)
{
//Open file by filename from argument
string filename(argv[1]);
//Filename wasn't valid
if (!valid_file(filename))
{
cout << "Could not find file " << filename << endl;
return false;
}
//Low and high interval is inputted after the filename
low_index = 2;
high_index = 3;
}
//Get interval from argument
string interval_low(argv[low_index]);
string interval_high(argv[high_index]);
//Interval was not valid
return validate_interval_arg(interval_low, interval_high);
}
bool valid_file(string const& filename)
{
/// Opens file from filename and returns
/// if the file could be opened or not
ifstream file;
file.open(filename, ifstream::in);
//File could not be opened
if (!file)
{
return false;
}
return true;
}
bool validate_interval_arg(string const& low, string const& high)
{
/// Validates if the interval inputted in string
/// is correct or not.
/// The interval is not correct if:
/// 1: The interval couldn't be converted to integer
/// 2: Lower interval is greater or equal than higher interval.
/// If the interval is not correct, print what wasn't correct
/// and return false.
int interval_low;
int interval_high;
try
{
//Try to convert interval into integer
interval_low = stoi(low);
interval_high = stoi(high);
if (interval_low > interval_high)
{
cerr << "Higher interval must be higher than lower interval" << "\n";
return false;
}
}
//Could not convert interval into integer
catch(invalid_argument e)
{
cerr << "\"" << low << "\" to \"" << high << "\""
<< " is not a valid interval!\n"
<< "Interval must be inputted <low interval> <high interval>\n";
return false;
}
return true;
}
vector<Trimino> get_triminos(istream & input_stream,
array<int, 2> const& interval,
string const& filename)
{
/// Read triminos from either file or console input.
/// If a trimono was not valid, print the error and
/// continue reading next trimino.
/// Then return a list of all valid triminos.
//Filename has default value means you should not read from file
bool read_from_file = (filename.size() != 0);
vector<Trimino> trimino_lst;
string line;
int line_count {1};
// Read line by line from input stream until there isn't
// anything more to read
while ( getline(input_stream, line) )
{
//User wanted to quit inputting triminos
if ( !read_from_file && line == "q")
{
break;
}
array<int, 3> tri_numbers;
//Convert string to istringstream
istringstream ss_line (line);
string column;
int i {0};
try
{
//Read column by column
for (; ss_line >> column;)
{
//Stop loop when there have been found three trimino numbers
if (i == 3)
{
break;
}
//Try to get trimino number from column in file
tri_numbers[i] = stoi(column);
++i;
}
//Create a trimino with found numbers
Trimino tri{tri_numbers};
//Trimino doesn't have three numbers
if ( i != 3)
{
string msg = "Trimino needs 3 numbers! ";
msg+=to_string(i) + " was found";
print_trimino_error(filename, line_count, msg, read_from_file);
}
//Trimino numbers are not in correct order (rising clockwise)
else if (!tri.valid_order())
{
string msg = "Trimino numbers are not rising in clock order";
print_trimino_error(filename, line_count, msg, read_from_file);
}
//Trimino numbers are out of range, not in selected interval
else if(!tri.valid_interval(interval))
{
string msg = "One or more trimino numbers are out of range!";
print_trimino_error(filename, line_count, msg, read_from_file);
}
//Fully valid trimino! :D
else
{
cout << "Successfully created a trimino\n" << endl;
trimino_lst.push_back(tri);
}
}
//Failed to get (convert) trimino number
catch(invalid_argument e)
{
string msg = "\"" + column + "\" is not a valid number";
print_trimino_error(filename, line_count, msg, read_from_file);
}
++line_count;
}
return trimino_lst;
}
void print_running_instructions(string const& program_name,
bool read_from_file)
{
/// Print how to run the program depending on
/// if trimino numbers should be read from
/// file or console input
//Triminos wanted to be read from file
if (read_from_file)
{
cerr << "How to run program:\n"
<< "\"" << program_name << "\""
<< " <filename> <lowest interval> <highest interval>\n"
<< "...or use no arguments to manually enter values\n";
}
//Triminos wanted to be read from console input
else
{
cerr << "How to run program:\n"
<< "\"" << program_name << "\""
<< " <lowest interval> <highest interval>\n"
<< "...or use no arguments to manually enter values\n";
}
}
void print_trimino_error(string const& filename,
int file_row, string const& msg,
bool read_from_file)
{
/// Print error saying what was wrong with a trimino.
/// If the trimino was read from a file, also print
/// the filename and which line trimino was found.
//Triminos wanted to be read from file
if (read_from_file)
{
cerr << "Error in file " << filename
<< " on row " << to_string(file_row)
<< ":\n" << msg << "\n""\n";
}
//Triminos wanted to be read from console input
else
{
cerr << "Error: " << msg << "\n""\n";
}
}
|
cc77f8ab6fad53e7ba0a4b6244448ed2d29cd5eb
|
742df0a389fa897534605a67d13a1185e40886a2
|
/Labs_Cpp/lab5_Cpp/mainwindow.cpp
|
9f5b48155991b2dd12ba0003caba3df4fdecf01b
|
[] |
no_license
|
Rariramz/Labs_term2
|
a5f654b64a8eea36c8847c527fb7bb80d3be22fc
|
be075c63216a63c9c70fdfe5001979e25666dfa8
|
refs/heads/main
| 2023-05-13T01:25:54.725912
| 2021-05-31T20:49:19
| 2021-05-31T20:49:19
| 372,625,063
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,210
|
cpp
|
mainwindow.cpp
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
queue = new RandomQueue();
}
MainWindow::~MainWindow()
{
delete ui;
}
// ------------------------------------------------------------------ Обновление ListView
void MainWindow::update()
{
QStringListModel *model = new QStringListModel(this);
QStringList List;
Node *current = queue->first;
while (current != nullptr)
{
List << QString::number(current->value);
current = current->next;
}
model->setStringList(List);
ui->listView->setModel(model);
}
// ------------------------------------------------------------------ Добавление элемента в очередь
void MainWindow::on_pushButtonAdd_clicked()
{
queue->push(ui->lineEditAdd->text().toInt());
ui->lineEditAdd->clear();
update();
}
// ------------------------------------------------------------------ Добавление элемента в очередь
void MainWindow::on_pushButtonRemove_clicked()
{
queue->pop();
update();
}
// ------------------------------------------------------------------ Создание новой рандомной очереди
void MainWindow::on_pushButtonNewRandomQueue_clicked()
{
int count = ui->lineEditAmount->text().toInt();
int lowerBound = ui->lineEditMin->text().toInt();
int upperBound = ui->lineEditMax->text().toInt();
queue = new RandomQueue(count, lowerBound, upperBound);
ui->lineEditAmount->clear();
ui->lineEditMax->clear();
ui->lineEditMin->clear();
update();
}
// ------------------------------------------------------------------ Удаление элемента из очереди
void MainWindow::on_pushButtonDeleteBetwMaxMin_clicked()
{
queue->clearBetweenMinAndMax();
update();
}
void MainWindow::on_lineEditAdd_textChanged(const QString &arg1)
{
if (ui->lineEditAdd->text() != "")
ui->pushButtonAdd->setEnabled(true);
else
ui->pushButtonAdd->setEnabled(false);
}
|
ab49bc3f73830c12e51f01de9b489677440cee90
|
0ae61467dc21f997e868d31eb5a555b59c463cd4
|
/21days_CPlusPlus/chapter10/10.8_protected_inheritance.cpp
|
cb5c33ee57c2201be497a247c4cab00efb5d6f71
|
[] |
no_license
|
eoGqzPzYlN/C-and-C-plus-plus
|
c9ed101c7da1e3d8525c003d900640cc12db0f02
|
30a5838f9b9641b7cb67bfa322d355cc50826bc7
|
refs/heads/master
| 2023-07-26T01:36:02.854345
| 2021-09-06T05:43:45
| 2021-09-06T05:43:45
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,493
|
cpp
|
10.8_protected_inheritance.cpp
|
#include <iostream>
class Motor
{
public:
void SwitchIgnition()
{
std::cout << "Ignition ON" << std::endl;
}
void PumpFuel()
{
std::cout << "Fuel in cylinders" << std::endl;
}
void FireCylinders()
{
std::cout << "Vroooom" << std::endl;
}
};
// 保护继承
// has-a 关系
// 派生类能够访问基类的所有公共和保护成员
// 在继承层次结构外,不能通过派生类实例访问基类的公有成员
// 当且仅当必要的时候,才采用私有或者保护继承,否则会出现兼容性瓶颈
class Car: protected Motor
{
public:
void Move()
{
SwitchIgnition();
PumpFuel();
FireCylinders();
}
};
// 保护继承
class RaceCar: protected Car
{
public:
void Move()
{
SwitchIgnition();
PumpFuel();
FireCylinders();
FireCylinders();
FireCylinders();
}
};
int main(int argc, char** argv)
{
RaceCar myDereamCar;
myDereamCar.Move();
// 切除问题
// 派生类对象复制给基类对象,无论通过显示复制,还是参数传递,
// 编译器都只是复制部分数据,这种无意间的裁剪数据,导致派生类变为基类的行为称之为切除 slicing
// 避免 slicing 的方法就是,不要以值传递的方式传递参数,
// 而是使用指向基类的指针或者const引用的方式传递
return 0;
}
// $ g++ -o main 10.8_protected_inheritance.cpp
// $ ./main.exe
// Ignition ON
// Fuel in cylinders
// Vroooom
// Vroooom
// Vroooom
|
49fc96910ae8538b4d27c7b4e64bffbf95be4e7d
|
2cbd0c2b589d146d0c884e4a7baa18cb4f86e089
|
/SEPTEMBER LONG CHALLENGE/SecondSolution_ADAMAT.cpp
|
3624312c455d3294dde3e49567ac03e9289ce9e4
|
[] |
no_license
|
arjunsingh64/CODECHEF
|
fb818a5a355ba6fa3ff4b800bf87f192059d2afc
|
dcb4bc5fe7fefe692aecc7c70f9f181444522e3b
|
refs/heads/master
| 2022-12-23T03:43:11.439500
| 2020-09-18T11:54:35
| 2020-09-18T11:54:35
| 296,272,208
| 0
| 1
| null | 2020-09-30T18:37:03
| 2020-09-17T08:56:12
|
C++
|
UTF-8
|
C++
| false
| false
| 735
|
cpp
|
SecondSolution_ADAMAT.cpp
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
int tc;
cin>>tc;
while(tc--)
{
int count=0;
int N,i,j;
cin>>N;
int arr[N][N];
for(i=0;i<N;++i)
{
for(j=0;j<N;++j)
{
cin>>arr[i][j];
}
}
bool array[1][N];
int cnt=1;
for(i=0;i<1;++i)
{
for(j=1;j<N;++j)
{
++cnt;
if(arr[i][j]==cnt)
{
array[i][j]=true;
}else
{
array[i][j]=false;
}
}
}
int u;
for(i=0;i<1;++i)
{
for(j=N-1;j>0;--j)
{
if(array[i][j]==false)
{
++count;
array[i][j]=true;
for(u=N-2;u>0;--u)
{
if(array[i][u]==true)
array[i][u]=false;
else
array[i][u]=true;
}
}
}
}
cout<<count<<"\n";
}
}
|
bcdc7f0efd26e1c8cab28be5681790f6037be8ea
|
7de867ace1fdedb9060245e7ea02f3612021cdf3
|
/C++/Linearr_Search.cpp
|
e832d29dc0140c328beb871e08a787467af7bf63
|
[
"MIT"
] |
permissive
|
Ravitejavelamuri/DataStruture-and-algroithms-program
|
3f19c83d4a8debc74dcad4cf618b63717b85f35d
|
f5707a78c477f07d349ae78c08f1a8731f0dc90f
|
refs/heads/main
| 2023-08-25T01:09:02.109055
| 2021-10-07T16:43:19
| 2021-10-07T16:43:19
| 414,692,635
| 1
| 0
|
MIT
| 2021-10-30T04:14:58
| 2021-10-07T17:13:28
| null |
UTF-8
|
C++
| false
| false
| 777
|
cpp
|
Linearr_Search.cpp
|
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cout<<"Enter the length of the Array : ";
cin>>n;
cout<<endl;
int a[n];
cout<<"Enter the elements in the array : "<<endl;
for (int i = 0; i < n; i++)
{
cout<<"a["<<i<<"] = ";
cin>>a[i];
cout<<endl;
}
int search,pos,check=0;
cout<<"Enter the Element to be searched : ";
cin>>search;
cout<<endl;
for(int i=0; i<n; i++)
{
if(a[i]==search)
{
pos = i;
check = 1;
break;
}
}
if(check==1){
cout<<"Element '"<<search<<"' is found at position '"<<pos+1<<"'"<<endl;
}
else{
cout<<"Element not found!!"<<endl;
}
return 0;
}
|
3b1cbe18e3743d0a6f35beb49593d12edf4df80e
|
75d8a8031744f63d699e1b1b2e4b30c5b3383752
|
/cf/training/ArabellaCPC2019/M.cpp
|
71b9e7d79546ae4ac7656ab5d735891b64aaac5d
|
[] |
no_license
|
pedrodiogo219/competitiveProgramming
|
9d80ebb347b34423f09e3304101560a3903d59d6
|
0e8297a8ded46d2021d0ab3d94ea611464793d77
|
refs/heads/master
| 2021-07-24T04:06:25.726703
| 2021-07-12T12:08:03
| 2021-07-12T12:08:03
| 189,424,835
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 426
|
cpp
|
M.cpp
|
#include <bits/stdc++.h>
using namespace std;
int main(){
string str;
cin >> str;
sort(str.begin(), str.end(), greater < char >());
for (int i=0; i<26; i++){
string ans;
for (int i=0; i<str.size(); i++){
if(i+1 < str.size() && str[i] == str[i+1] && str[i] != 'z'){
ans.push_back(str[i]+1);
i++;
}
else ans.push_back(str[i]);
}
str = ans;
}
cout << str << endl;
}
|
7fc039af1fc8a4ccf515ce0e60c559f8623eba0e
|
475897accc433baa4ab4b681b40193fa80276d6f
|
/Assignment-11/bt47/Source.cpp
|
8245a2e06a5de830e9c7057f864acd1aaa49e7b0
|
[] |
no_license
|
DangNguyen146/WeCode
|
aa1a136408df33510a4f3c677bbce629d557048a
|
08f8fbe03f046aa3af29477af81a42a295dde557
|
refs/heads/master
| 2022-11-18T22:15:51.598818
| 2020-07-07T17:32:12
| 2020-07-07T17:32:12
| 277,856,916
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,238
|
cpp
|
Source.cpp
|
#include<iostream>
using namespace std;
struct tNode
{
int key;
tNode* tLeft;
tNode* tRight;
};
typedef tNode* Tree;
tNode* CreateNode(int x)
{
tNode* p = new tNode;
p->key = x;
p->tLeft = NULL;
p->tRight = NULL;
return p;
}
int InsertTree(Tree& T, int x)
{
if (T)
{
if (T->key == x)
return 0;
if (T->key > x)
return InsertTree(T->tLeft, x);
if (T->key < x)
return InsertTree(T->tRight, x);
}
T = new tNode;
T->key = x;
T->tLeft = T->tRight = NULL;
return 1;
}
//Độ dài cây
int DoDaiCay(Tree T)
{
if (T == NULL)
return 0;
int leLeft = DoDaiCay(T->tLeft);
int leRight = DoDaiCay(T->tRight);
if (leLeft > leRight)
return leLeft + 1;
else
return leRight + 1;
}
//Duyệt cây theo mức
void InTheoMuc(Tree a, int i, int m, int& dem)
{
if (a == NULL)
return;
if (i == m)
dem++;
InTheoMuc(a->tLeft, i + 1, m, dem);
InTheoMuc(a->tRight, i + 1, m, dem);
}
void Xuat(Tree T)
{
for (int i = 0; i < DoDaiCay(T); i++)
{
int dem = 0;
InTheoMuc(T, 0, i, dem);
cout << "So node muc " << i << " cua cay la: " << dem;
cout << endl;
}
}
int main()
{
Tree T = NULL;
int n;
int x;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> x;
InsertTree(T, x);
}
Xuat(T);
return 0;
}
|
7742efbe7ddb3e8cbe2233d3c4d9aea9a81dc255
|
f7c0f54e93f561b8d09d8293435bdc2695d31e6f
|
/L4_IO/pixy/pixy_brain.hpp
|
162fad5de01bc55dc95eb9a7751f5bf74266e024
|
[] |
no_license
|
alexanderkoumis/lpc1758_freertos
|
0eb275bdf37641576a8227334e7f8e57acfc3cfa
|
cd22ed6e8d449d7dea7d2f78485e17df4b5cff05
|
HEAD
| 2016-09-06T11:03:03.253120
| 2015-10-03T10:46:20
| 2015-10-03T10:46:20
| 32,504,481
| 0
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,581
|
hpp
|
pixy_brain.hpp
|
#ifndef PIXY_BRAIN_HPP
#define PIXY_BRAIN_HPP
#include <algorithm>
#include <iostream>
#include <memory>
#include <queue>
#include <vector>
#include <stack>
#include "storage.hpp"
#include "pixy.hpp"
#include "pixy/pixy_eyes.hpp"
#include "pixy/common.hpp"
#include "pixy/common/board.hpp"
#include "pixy/common/block.hpp"
namespace team9
{
namespace pixy
{
class PixyBrain_t
{
public:
PixyBrain_t(ChipColor_t eColorCalib_arg, uint32_t ulChipsToCalib_arg) :
pBoard(new Board_t),
eColorCalib(eColorCalib_arg),
lLastInsertCol(0),
ulChipsToCalib(ulChipsToCalib_arg),
usCamRows(200), usCamCols(320),
usCamRowsHalf(usCamRows/2),
usCamColsHalf(usCamCols/2)
{}
void vEMAAlphaUp()
{
pBoard->vAdjustEMAAlpha(true);
}
void vEMAAlphaDown()
{
pBoard->vAdjustEMAAlpha(false);
}
float xGetAlpha()
{
return pBoard->xGetAlpha();
}
void vCalibCorners(PixyEyes_t* pPixyEyes, Corners_t& xCorners)
{
uint32_t ulChips = 0;
uint32_t ulCalibChips = 0;
while (ulChips < ulChipsToCalib)
{
std::vector<Block_t> xBlocks;
int lSeenBlocks = pPixyEyes->lSeenBlocks(xBlocks);
if (lSeenBlocks < 0)
{
continue;
}
ulChips += lSeenBlocks;
for (auto& xBlock : xBlocks)
{
if (xBlock.usSignature == eColorCalib)
{
ulCalibChips++;
Quadrant_t xQuadrant = xComputeQuadrant(xBlock.xPoint);
if (xQuadrant < 4)
{
xCorners.vUpdate(xQuadrant, xBlock);
}
}
}
}
}
int lSampleChips(PixyEyes_t* pPixyEyes)
{
std::vector<Block_t> xBlocks;
std::vector<std::pair<int, ChipColor_t>> xSeenChips;
if (pPixyEyes->lSeenBlocks(xBlocks) < 0)
{
return -1;
}
this->pBoard->vCalcSeenChips(xBlocks, xSeenChips);
this->xLastSeen = xSeenChips;
this->pBoard->vUpdate(xSeenChips);
int lLastChipInserted = this->pBoard->lColChanged();
return lLastChipInserted;
}
int lBotInsert(PixyCmd_t& xInsertCmd)
{
int lNewRow = pBoard->lInsert(xInsertCmd);
if (lNewRow == -1)
{
xErrorQueue.push("Row overflowing!");
}
if (lNewRow == -2)
{
xErrorQueue.push("Column value out of bounds");
}
return lNewRow;
}
void vPrintChips(Board_t::PrintMode_t xPrintMode,
bool bPrintLastSeen = false)
{
std::vector<std::pair<int, ChipColor_t>> xSeenChips;
if (bPrintLastSeen)
{
xSeenChips = this->xLastSeen;
}
switch (xPrintMode)
{
case Board_t::LOCATION: pBoard->vLocationPrint(); break;
case Board_t::COLOR: pBoard->vColorPrint(xSeenChips, false); break;
case Board_t::OPENCV_META: pBoard->vOpenCVPrint(); break;
}
}
void vPrintCorners(Board_t::PrintMode_t xPrintMode)
{
pBoard->vPrintChips(xPrintMode);
}
std::string xGetErrors()
{
size_t xErrIdx = 0;
std::ostringstream oss;
while (!xErrorQueue.empty())
{
oss << "Error #" << xErrIdx++ << ": "
<< xErrorQueue.front() << "\n";
xErrorQueue.pop();
}
return oss.str();
}
std::unique_ptr<Board_t> pBoard;
ChipColor_t eColorCalib;
private:
inline Quadrant_t xComputeQuadrant(Point_t<uint16_t>& xPoint)
{
uint16_t& xY = xPoint.xY;
uint16_t& xX = xPoint.xX;
if (xY < 0 || xX < 0 || xY >= usCamRows || xX >= usCamCols)
{
xErrorQueue.push("Chip out of bounds: " + xPoint.xStr());
return ERROR;
}
else if (xY <= usCamRowsHalf && xX <= usCamColsHalf)
{
return TOP_LEFT;
}
else if (xY > usCamRowsHalf && xX <= usCamColsHalf)
{
return BOT_LEFT;
}
else if (xY <= usCamRowsHalf && xX > usCamColsHalf)
{
return TOP_RIGHT;
}
else if (xY > usCamRowsHalf && xX > usCamColsHalf)
{
return BOT_RIGHT;
}
xErrorQueue.push("Point was not in any quadrant or out of bounds?");
return ERROR;
}
std::queue<std::string> xErrorQueue;
std::queue<int> xUpdateQueue;
std::stack<int> xColUpdate;
std::vector<std::pair<int, ChipColor_t>> xLastSeen;
Corners_t xLastCorners;
int lLastInsertCol;
uint32_t ulChipsToCalib;
uint16_t usCamRows;
uint16_t usCamCols;
uint16_t usCamRowsHalf;
uint16_t usCamColsHalf;
std::string sLastError;
};
} // namespace pixy
} // namespace team9
#endif
|
68a1d1ecb141643fcb8af617c8cd0c71d5b967ff
|
da1500e0d3040497614d5327d2461a22e934b4d8
|
/cobalt/cssom/property_value_visitor.h
|
6dfc7d1bb25c833c8e34fdfa9fb6edf1019cc6d2
|
[
"Apache-2.0",
"BSD-3-Clause"
] |
permissive
|
youtube/cobalt
|
34085fc93972ebe05b988b15410e99845efd1968
|
acefdaaadd3ef46f10f63d1acae2259e4024d383
|
refs/heads/main
| 2023-09-01T13:09:47.225174
| 2023-09-01T08:54:54
| 2023-09-01T08:54:54
| 50,049,789
| 169
| 80
|
BSD-3-Clause
| 2023-09-14T21:50:50
| 2016-01-20T18:11:34
| null |
UTF-8
|
C++
| false
| false
| 6,404
|
h
|
property_value_visitor.h
|
// Copyright 2014 The Cobalt Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef COBALT_CSSOM_PROPERTY_VALUE_VISITOR_H_
#define COBALT_CSSOM_PROPERTY_VALUE_VISITOR_H_
#include "base/compiler_specific.h"
namespace cobalt {
namespace cssom {
class AbsoluteURLValue;
class CalcValue;
class FilterFunctionListValue;
class FontStyleValue;
class FontWeightValue;
class IntegerValue;
class KeywordValue;
class LengthValue;
class LinearGradientValue;
class LocalSrcValue;
class MediaFeatureKeywordValue;
class NumberValue;
class PercentageValue;
class PropertyKeyListValue;
class PropertyListValue;
class PropertyValue;
class RadialGradientValue;
class RatioValue;
class ResolutionValue;
class RGBAColorValue;
class ShadowValue;
class StringValue;
class TimeListValue;
class TimingFunctionListValue;
class TransformPropertyValue;
class UnicodeRangeValue;
class URLValue;
class UrlSrcValue;
// Type-safe branching on a class hierarchy of CSS property values,
// implemented after a classical GoF pattern (see
// http://en.wikipedia.org/wiki/Visitor_pattern#Java_example).
class PropertyValueVisitor {
public:
virtual void VisitAbsoluteURL(AbsoluteURLValue* url_value) = 0;
virtual void VisitCalc(CalcValue* calc_value) = 0;
virtual void VisitFilterFunctionList(FilterFunctionListValue*) = 0;
virtual void VisitFontStyle(FontStyleValue* font_style_value) = 0;
virtual void VisitFontWeight(FontWeightValue* font_weight_value) = 0;
virtual void VisitInteger(IntegerValue* integer_value) = 0;
virtual void VisitKeyword(KeywordValue* keyword_value) = 0;
virtual void VisitLength(LengthValue* length_value) = 0;
virtual void VisitLinearGradient(
LinearGradientValue* linear_gradient_value) = 0;
virtual void VisitLocalSrc(LocalSrcValue* local_src_value) = 0;
virtual void VisitMediaFeatureKeywordValue(
MediaFeatureKeywordValue* media_feature_keyword_value) = 0;
virtual void VisitNumber(NumberValue* number_value) = 0;
virtual void VisitPercentage(PercentageValue* percentage_value) = 0;
virtual void VisitPropertyKeyList(
PropertyKeyListValue* property_key_list_value) = 0;
virtual void VisitPropertyList(PropertyListValue* property_list_value) = 0;
virtual void VisitRadialGradient(
RadialGradientValue* radial_gradient_value) = 0;
virtual void VisitRatio(RatioValue* ratio_value) = 0;
virtual void VisitResolution(ResolutionValue* resolution_value) = 0;
virtual void VisitRGBAColor(RGBAColorValue* color_value) = 0;
virtual void VisitShadow(ShadowValue* shadow_value) = 0;
virtual void VisitString(StringValue* string_value) = 0;
virtual void VisitTimeList(TimeListValue* time_list_value) = 0;
virtual void VisitTimingFunctionList(
TimingFunctionListValue* timing_function_list_value) = 0;
virtual void VisitTransformPropertyValue(
TransformPropertyValue* transform_property_value) = 0;
virtual void VisitUnicodeRange(UnicodeRangeValue* unicode_range_value) = 0;
virtual void VisitURL(URLValue* url_value) = 0;
virtual void VisitUrlSrc(UrlSrcValue* url_src_value) = 0;
protected:
~PropertyValueVisitor() {}
};
// A convenience class that forwards all methods to |VisitDefault|, thus one can
// derive from this class, implement only the value types that they care about,
// and handle every other value type generically.
class DefaultingPropertyValueVisitor : public PropertyValueVisitor {
public:
void VisitAbsoluteURL(AbsoluteURLValue* url_value) override;
void VisitCalc(CalcValue* calc_value) override;
void VisitFilterFunctionList(
FilterFunctionListValue* filter_function_list_value) override;
void VisitFontStyle(FontStyleValue* font_style_value) override;
void VisitFontWeight(FontWeightValue* font_weight_value) override;
void VisitKeyword(KeywordValue* keyword_value) override;
void VisitInteger(IntegerValue* integer_value) override;
void VisitLength(LengthValue* length_value) override;
void VisitLinearGradient(LinearGradientValue* linear_gradient_value) override;
void VisitLocalSrc(LocalSrcValue* local_src_value) override;
void VisitMediaFeatureKeywordValue(
MediaFeatureKeywordValue* media_feature_keyword_value) override;
void VisitNumber(NumberValue* number_value) override;
void VisitPercentage(PercentageValue* percentage_value) override;
void VisitPropertyKeyList(
PropertyKeyListValue* property_key_list_value) override;
void VisitPropertyList(PropertyListValue* property_list_value) override;
void VisitRadialGradient(RadialGradientValue* radial_gradient_value) override;
void VisitRatio(RatioValue* ratio_value) override;
void VisitResolution(ResolutionValue* resolution_value) override;
void VisitRGBAColor(RGBAColorValue* color_value) override;
void VisitShadow(ShadowValue* shadow_value) override;
void VisitString(StringValue* string_value) override;
void VisitTimeList(TimeListValue* time_list_value) override;
void VisitTimingFunctionList(
TimingFunctionListValue* timing_function_list_value) override;
void VisitTransformPropertyValue(
TransformPropertyValue* transform_property_value) override;
void VisitUnicodeRange(UnicodeRangeValue* unicode_range_value) override;
void VisitURL(URLValue* url_value) override;
void VisitUrlSrc(UrlSrcValue* url_src_value) override;
protected:
virtual void VisitDefault(PropertyValue* property_value) = 0;
};
// A convenience class that implements PropertyValueVisitor with NOTREACHED()
// for each method, thus one can derive from this class, implement only the
// value types that they care about, and then every other value type will
// result in an error.
class NotReachedPropertyValueVisitor : public DefaultingPropertyValueVisitor {
protected:
void VisitDefault(PropertyValue* property_value) override;
};
} // namespace cssom
} // namespace cobalt
#endif // COBALT_CSSOM_PROPERTY_VALUE_VISITOR_H_
|
efb28d0a30b6afd238d24fd3a0abd59c785f4b72
|
09a8182e2ff8d3fd0f5fe5e0cb9acb96f648f788
|
/Elevator/MyForm.h
|
1455f64b5300da6bbad98eea6457cff555b3b25d
|
[] |
no_license
|
chang-chih-yao/University_Project
|
cf617d92b7da764a4c71718a79a5626312d3db0c
|
b81a6c53a9702983e15c5384119738346bfc302f
|
refs/heads/master
| 2020-04-27T17:08:52.877741
| 2019-03-09T14:26:45
| 2019-03-09T14:26:45
| 174,506,390
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,922
|
h
|
MyForm.h
|
#pragma once
#include <iostream>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <opencv2\opencv.hpp>
#include <opencv\highgui.h>
#include <opencv\cv.h>
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/video/tracking.hpp"
#include "opencv2/gpu/gpu.hpp"
#include "opencv2/ml/ml.hpp"
#include "opencv/cv.h"
#include <Windows.h>
#include <fstream>
#include <chrono>
#include <msclr\marshal_cppstd.h>
#include "Allview.h"
#include "information.h"
#include "VideoWall.h"
#include <queue>
#define MAX_SEM_COUNT 100
#define THREADCOUNT 12
#define file_path "hb.txt"
using namespace std;
using namespace cv;
DWORD WINAPI threadfunc(int tik);
extern void train();
static string video[100];
static string videos[100];
static int ledside[100];
static int ledcolor[100];
static string backpic[100];
namespace Elevator_Scan {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
/// <summary>
/// MyForm 的摘要
/// </summary>
public ref class MyForm : public System::Windows::Forms::Form
{
public:
MyForm(void)
{
InitializeComponent();
//
//TODO: 在此加入建構函式程式碼
//
}
protected:
/// <summary>
/// 清除任何使用中的資源。
/// </summary>
~MyForm()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ button1;
protected:
private: System::Windows::Forms::Button^ button2;
private: System::Windows::Forms::ListBox^ listBox1;
private: System::Windows::Forms::Button^ button3;
private: System::Windows::Forms::Label^ label1;
private: System::Windows::Forms::Label^ label2;
private: System::Windows::Forms::Label^ label3;
private: System::Windows::Forms::Button^ button4;
private: System::Windows::Forms::Label^ label4;
private:
/// <summary>
/// 設計工具所需的變數。
/// </summary>
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
/// <summary>
/// 此為設計工具支援所需的方法 - 請勿使用程式碼編輯器
/// 修改這個方法的內容。
/// </summary>
void InitializeComponent(void)
{
this->button1 = (gcnew System::Windows::Forms::Button());
this->button2 = (gcnew System::Windows::Forms::Button());
this->listBox1 = (gcnew System::Windows::Forms::ListBox());
this->button3 = (gcnew System::Windows::Forms::Button());
this->label1 = (gcnew System::Windows::Forms::Label());
this->label2 = (gcnew System::Windows::Forms::Label());
this->label3 = (gcnew System::Windows::Forms::Label());
this->button4 = (gcnew System::Windows::Forms::Button());
this->label4 = (gcnew System::Windows::Forms::Label());
this->SuspendLayout();
//
// button1
//
this->button1->Font = (gcnew System::Drawing::Font(L"新細明體", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(136)));
this->button1->Location = System::Drawing::Point(31, 70);
this->button1->Name = L"button1";
this->button1->Size = System::Drawing::Size(94, 42);
this->button1->TabIndex = 0;
this->button1->Text = L"新增";
this->button1->UseVisualStyleBackColor = true;
this->button1->Click += gcnew System::EventHandler(this, &MyForm::button1_Click);
//
// button2
//
this->button2->Font = (gcnew System::Drawing::Font(L"新細明體", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(136)));
this->button2->Location = System::Drawing::Point(364, 399);
this->button2->Name = L"button2";
this->button2->Size = System::Drawing::Size(102, 54);
this->button2->TabIndex = 1;
this->button2->Text = L"執行";
this->button2->UseVisualStyleBackColor = true;
this->button2->Click += gcnew System::EventHandler(this, &MyForm::button2_Click);
//
// listBox1
//
this->listBox1->FormattingEnabled = true;
this->listBox1->ItemHeight = 12;
this->listBox1->Location = System::Drawing::Point(192, 70);
this->listBox1->Name = L"listBox1";
this->listBox1->Size = System::Drawing::Size(449, 304);
this->listBox1->TabIndex = 2;
//
// button3
//
this->button3->Font = (gcnew System::Drawing::Font(L"新細明體", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(136)));
this->button3->Location = System::Drawing::Point(31, 152);
this->button3->Name = L"button3";
this->button3->Size = System::Drawing::Size(94, 42);
this->button3->TabIndex = 3;
this->button3->Text = L"更改輸入設定";
this->button3->UseVisualStyleBackColor = true;
this->button3->Click += gcnew System::EventHandler(this, &MyForm::button3_Click);
//
// label1
//
this->label1->AutoSize = true;
this->label1->Font = (gcnew System::Drawing::Font(L"新細明體", 12, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(136)));
this->label1->Location = System::Drawing::Point(12, 227);
this->label1->Name = L"label1";
this->label1->Size = System::Drawing::Size(76, 16);
this->label1->TabIndex = 4;
this->label1->Text = L"當前設定:";
//
// label2
//
this->label2->AutoSize = true;
this->label2->Font = (gcnew System::Drawing::Font(L"新細明體", 11.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(136)));
this->label2->Location = System::Drawing::Point(28, 265);
this->label2->Name = L"label2";
this->label2->Size = System::Drawing::Size(122, 15);
this->label2->TabIndex = 5;
this->label2->Text = L"LED位置 : 右上方";
//
// label3
//
this->label3->AutoSize = true;
this->label3->Font = (gcnew System::Drawing::Font(L"新細明體", 11.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(136)));
this->label3->Location = System::Drawing::Point(28, 308);
this->label3->Name = L"label3";
this->label3->Size = System::Drawing::Size(107, 15);
this->label3->TabIndex = 6;
this->label3->Text = L"LED顏色 : 紅色";
//
// button4
//
this->button4->Font = (gcnew System::Drawing::Font(L"新細明體", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(136)));
this->button4->Location = System::Drawing::Point(690, 70);
this->button4->Name = L"button4";
this->button4->Size = System::Drawing::Size(94, 42);
this->button4->TabIndex = 7;
this->button4->Text = L"分類器訓練";
this->button4->UseVisualStyleBackColor = true;
this->button4->Click += gcnew System::EventHandler(this, &MyForm::button4_Click);
//
// label4
//
this->label4->AutoSize = true;
this->label4->Font = (gcnew System::Drawing::Font(L"新細明體", 11.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(136)));
this->label4->Location = System::Drawing::Point(687, 141);
this->label4->Name = L"label4";
this->label4->Size = System::Drawing::Size(0, 15);
this->label4->TabIndex = 8;
//
// MyForm
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 12);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(813, 495);
this->Controls->Add(this->label4);
this->Controls->Add(this->button4);
this->Controls->Add(this->label3);
this->Controls->Add(this->label2);
this->Controls->Add(this->label1);
this->Controls->Add(this->button3);
this->Controls->Add(this->listBox1);
this->Controls->Add(this->button2);
this->Controls->Add(this->button1);
this->Name = L"MyForm";
this->Text = L"大量電梯監視器影像事件辨識平行處理系統";
this->Load += gcnew System::EventHandler(this, &MyForm::MyForm_Load);
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
Allview^ check = gcnew Allview();;
Elevator_Scan::VideoWall form1;
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
OpenFileDialog^ openFileDialog1 = gcnew OpenFileDialog;
if (openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK){
listBox1->Items->Add(openFileDialog1->FileName);
ledside[listBox1->Items->Count - 1] = check->get_side();
ledcolor[listBox1->Items->Count - 1] = check->get_color();
backpic[listBox1->Items->Count - 1] = check->get_back();
}
}
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) {
clock_t start, end;
form1.Show();
Elevator_Scan::information form2;
HANDLE aThread[100];
DWORD ThreadID;
//viewall = gcnew Allview();
memset(change, 0, 100);
start = clock();
for (int i = 0; i < listBox1->Items->Count; i++){
std::string str = msclr::interop::marshal_as<std::string>(listBox1->Items[i]->ToString());
char *strrr = new char[str.length() + 1];
strcpy(strrr, str.c_str());
video[i] = strrr;
videos[i] = strrr;
aThread[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)threadfunc, (LPVOID)i, 0, &ThreadID);
form2.comboBox1->Items->Add(listBox1->Items[i]->ToString());
}
form1.setlocation(listBox1->Items->Count);
form1.func(listBox1->Items->Count);
WaitForMultipleObjects(listBox1->Items->Count, aThread, TRUE, INFINITE);
for (int i = 0; i < listBox1->Items->Count; i++){
CloseHandle(aThread[i]);
}
end = clock();
cout << (end - start)/CLOCKS_PER_SEC << endl;
form2.ShowDialog();
}
private: System::Void MyForm_Load(System::Object^ sender, System::EventArgs^ e) {
}
private: System::Void button3_Click(System::Object^ sender, System::EventArgs^ e) {
check->ShowDialog();
if (check->get_side() == 1)
label2->Text = "LED位置 : 右上方";
else if (check->get_side() == 2)
label2->Text = "LED位置 : 左上方";
if (check->get_color() == 1)
label3->Text = "LED顏色 : 紅色";
else if (check->get_color() == 2)
label3->Text = "LED顏色 : 黃色";
}
private: System::Void button4_Click(System::Object^ sender, System::EventArgs^ e) {
train();
label4->Text = "已訓練完畢!";
}
};
}
|
461480608428e12ee55e17b35a4536d9075e3997
|
524a15b1e3454baae34acc324f56a717d747ed5e
|
/ContainerLibrary/libs/containers/include/Queue/Queue.hpp
|
06c3ef3faed2daefd61aac016887889d7a258d27
|
[
"MIT"
] |
permissive
|
intrepid249/Bootstrap-ShooterGame
|
3afd919b794b987750cd6c050aad7cb1088c2629
|
789ec52ce8139fef3172be7a4a0dff0c958ae384
|
refs/heads/master
| 2020-12-30T13:07:43.621995
| 2017-07-16T23:30:02
| 2017-07-16T23:30:02
| 91,321,851
| 0
| 0
| null | 2017-06-12T14:09:46
| 2017-05-15T09:49:21
|
C
|
UTF-8
|
C++
| false
| false
| 919
|
hpp
|
Queue.hpp
|
#pragma once
#include <LinkedList\LinkedList.hpp>
#include <memory>
#include <functional>
template <class T>
class Queue {
public:
Queue() {}
Queue(Queue const &) = delete;
Queue &operator =(Queue const &) = delete;
Queue(Queue &&o) : m_data(std::move(o.m_data)) {}
Queue &operator =(Queue &&o) {
if (this != &o)
m_data = std::move(o.m_data);
return *this;
}
~Queue() {}
void push(const T& _item) {
// Insert an item to the front of the queue
m_data.insert(_item, 0);
}
void pop() {
assert((size() > 0 && m_data.size() > 0) && "Cannot pop from empty container");
//m_data.erase(end() - 1);
}
/** Return the element at the front of the queue*/
T front() {
return m_data[0];
}
/** Return the element at the back of the queue*/
T back() {
return m_data[size() - 1];
}
bool empty() { return m_data.empty(); }
int size() { return m_data.size(); }
private:
LinkedList<T> m_data;
};
|
4b07fdd66b16feadfca3695b18ed67209aee45d4
|
372911494ee90af6e412086c0628d66856dab634
|
/threading/exception_thread.cc
|
7abe2ef37c5c59084d069cd9ee287c3d32f5b150
|
[] |
no_license
|
blacktrain/cplusplus
|
4a07b58b669c2db9b50d6416a6fe701d758c0957
|
d66dfcce845fd4ced9e8e9f45436e8731f2c0132
|
refs/heads/master
| 2018-11-06T01:57:17.323844
| 2018-10-08T11:37:14
| 2018-10-08T11:37:14
| 103,897,013
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 872
|
cc
|
exception_thread.cc
|
#include <iostream>
#include <thread>
#include <chrono>
struct func{
int& i;
func(int i_):i(i_){}
void operator() (){
using namespace std::chrono_literals;
for(unsigned j = 0;j < 10000000;j++){
i = j;
std::cout << i << std::endl;
std::this_thread::sleep_for(1s);
}
}
};
void do_something_in_current_thread(){
throw 1;
}
struct thread_guard{
std::thread& t;
thread_guard(std::thread& t_):t(t_){};
~thread_guard(){
std::cout << "~thread_guard\n";
if(t.joinable()){
std::cout << "~thread_guard\n";
t.join();
}
}
};
void oops(){
int local_value;
std::thread my_thread{func{local_value}};
thread_guard guard{my_thread};
std::cout << "oops\n";
do_something_in_current_thread();
std::cout << "oops1\n";
}
int main(){
try{
oops();
}
catch(...){
std::cout << "catch block\n";
}
std::cout << "continue\n";
return 0;
}
|
13918c439867b7083f40caf5f678e93f654e0495
|
9e7e1400eca1d85e87b5058adc016ccb19f6c0bc
|
/export/windows/cpp/obj/include/Player.h
|
592b28d9340e8a0a172bdaca73baa32d0b119350
|
[] |
no_license
|
sam2/sandbox
|
af16de13cbe4b9cf6773ee57ef2c0991e3a2d6db
|
a8eba4c37d81fc36fc5b9ee922e2a9c7f0311e86
|
refs/heads/master
| 2021-01-20T05:04:55.715042
| 2013-11-22T04:52:05
| 2013-11-22T04:52:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,609
|
h
|
Player.h
|
#ifndef INCLUDED_Player
#define INCLUDED_Player
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
#include <Character.h>
HX_DECLARE_CLASS0(Character)
HX_DECLARE_CLASS0(Enemy)
HX_DECLARE_CLASS0(Player)
HX_DECLARE_CLASS1(flixel,FlxBasic)
HX_DECLARE_CLASS1(flixel,FlxObject)
HX_DECLARE_CLASS1(flixel,FlxSprite)
HX_DECLARE_CLASS1(flixel,IDestroyable)
HX_DECLARE_CLASS2(flixel,util,FlxPoint)
HX_DECLARE_CLASS2(flixel,util,FlxTimer)
class HXCPP_CLASS_ATTRIBUTES Player_obj : public ::Character_obj{
public:
typedef ::Character_obj super;
typedef Player_obj OBJ_;
Player_obj();
Void __construct(::String Name,hx::Null< Float > __o_X,hx::Null< Float > __o_Y,::String JsonPath,Dynamic SimpleGraphic);
public:
static hx::ObjectPtr< Player_obj > __new(::String Name,hx::Null< Float > __o_X,hx::Null< Float > __o_Y,::String JsonPath,Dynamic SimpleGraphic);
static Dynamic __CreateEmpty();
static Dynamic __Create(hx::DynamicArray inArgs);
~Player_obj();
HX_DO_RTTI;
static void __boot();
static void __register();
void __Mark(HX_MARK_PARAMS);
void __Visit(HX_VISIT_PARAMS);
::String __ToString() const { return HX_CSTRING("Player"); }
virtual Void attackHit( ::flixel::FlxSprite attackk,::Enemy enemy);
Dynamic attackHit_dyn();
virtual Void attackFinished( ::flixel::util::FlxTimer Timer);
Dynamic attackFinished_dyn();
virtual Void attack( );
Dynamic attack_dyn();
bool attackDone;
::flixel::util::FlxTimer attackTimer;
virtual Void update( );
::flixel::util::FlxPoint attkPos;
::flixel::FlxSprite attk;
bool controllable;
};
#endif /* INCLUDED_Player */
|
b0d59fae147fd50b7f220be3b13322804c89ed82
|
91181534c2601ef99023cfcea801a545563a2ace
|
/android/app/src/main/cpp/LMDBJNI.cpp
|
fcc98b0ef387093bfe45dc9d231824ca93ac713d
|
[] |
no_license
|
followmeeapp/BlueCode
|
9b658aa882e05aa3a57e3689e87316d5f8eed822
|
7df6cccad283cf1390617e7c6e5c4de721d48b69
|
refs/heads/master
| 2021-01-09T05:41:56.984135
| 2017-02-03T17:42:02
| 2017-02-03T17:42:02
| 80,864,531
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,644
|
cpp
|
LMDBJNI.cpp
|
//
// Created by Erik van der Tier on 02/02/2017.
//
// super simplified JNI based lmdb class
//
#include <liblmdb/src/lmdb.h>
#include <jni.h>
#include <string>
#include <android/log.h>
#define LOGI(...) \
((void)__android_log_print(ANDROID_LOG_INFO, "lmdbJNI::", __VA_ARGS__))
#ifdef __cplusplus
extern "C" {
#endif
// create an lmdb env and return a long, so its 'pointer' can be held on to on the java side
jlong Java_com_followme_blue_LMDBJava_openEnv(
JNIEnv *env,
jobject /* this */, jstring dir) {
MDB_env *lenv;
std::string dbFile = std::string(env->GetStringUTFChars(dir, nullptr));
LOGI("Starting");
int res = mdb_env_create(&lenv);
LOGI("Created env: %d", res);
res = mdb_env_set_maxreaders(lenv, 4);
LOGI("set max readers: %d", res);
res = mdb_env_set_mapsize(lenv, 10485760);
LOGI("set mapsize: %d", res);
LOGI("dbfile: %s", dbFile.c_str());
res = mdb_env_open(lenv, dbFile.c_str(), MDB_NOSYNC, 0664);
LOGI("env_open: %d", res);
return reinterpret_cast<jlong>(lenv);
}
// get rid of the env
void Java_com_followme_blue_LMDBJava_closeEnv(
JNIEnv *env,
jobject /* this */, jlong lenv_ptr) {
MDB_env *lenv = reinterpret_cast<MDB_env *>(lenv_ptr);
mdb_env_close(lenv);
}
jlong Java_com_followme_blue_LMDBJava_openDBI(
JNIEnv *env,
jobject /* this */, jlong lenv_ptr) {
MDB_env *lenv = reinterpret_cast<MDB_env *>(lenv_ptr);
MDB_txn *txn;
MDB_dbi dbi;
LOGI("openDBI start");
int res = mdb_txn_begin(lenv, NULL, 0, &txn);
LOGI("txn_begin: %d", res);
res = mdb_dbi_open(txn, NULL, 0, &dbi);
LOGI("dbi_open: %d", res);
LOGI("openDBI end: %ld", (long)dbi);
res = mdb_txn_commit(txn);
return (jlong) dbi;
}
void Java_com_followme_blue_LMDBJava_closeDBI(
JNIEnv *env,
jobject /* this */, jlong lenv_ptr, jlong dbi) {
LOGI("closeDBI start");
MDB_env *lenv = reinterpret_cast<MDB_env *>(lenv_ptr);
mdb_dbi_close(lenv, (MDB_dbi) dbi);
LOGI("closeDBI end");
}
jint Java_com_followme_blue_LMDBJava_put(
JNIEnv *env, jobject obj, jlong lenv_ptr, jlong dbi, jint key, jstring jvalue) {
MDB_env *lenv = reinterpret_cast<MDB_env *>(lenv_ptr);
// MDB_dbi dbi;
LOGI("put start");
MDB_val valkey, data;
MDB_txn *txn;
int res = mdb_txn_begin(lenv, NULL, 0, &txn);
LOGI("put txn begin: %d", res);
if (res != 0) return res;
std::string value = std::string(env->GetStringUTFChars(jvalue, nullptr));
LOGI("value: %s of size: %ld", value.c_str(), value.size());
data.mv_size = value.size();
data.mv_data = (void *) value.c_str();
valkey.mv_size = sizeof(key);
valkey.mv_data = (void *)&key;
res = mdb_put(txn, (MDB_dbi) dbi, &valkey, &data, 0);
LOGI("put: %d", res);
if (res != 0) {
mdb_txn_abort(txn);
return res;
}
res = mdb_txn_commit(txn);
LOGI("put end %d", res);
return res;
}
jstring
Java_com_followme_blue_LMDBJava_get(
JNIEnv *env, jobject obj, jlong lenv_ptr, jlong dbi, jint key) {
MDB_env *lenv = reinterpret_cast<MDB_env *>(lenv_ptr);
LOGI("get start");
//MDB_dbi dbi;
MDB_val valkey, result;
MDB_txn *txn;
int res = mdb_txn_begin(lenv, NULL, MDB_RDONLY, &txn);
if (res != 0) return env->NewStringUTF("error");
valkey.mv_size = sizeof(key);
valkey.mv_data = (void *) &key;
res = mdb_get(txn, (MDB_dbi) dbi, &valkey, &result);
LOGI("get: %d", res);
if (res != 0) {
mdb_txn_abort(txn);
return env->NewStringUTF("error");
}
jstring jresult = env->NewStringUTF((char *) result.mv_data);
LOGI("result: %s", (char*)result.mv_data);
mdb_txn_commit(txn);
LOGI("get end");
return jresult;
}
}
|
66a21e6088b2601c3b6f4e629ab53e757f10d925
|
2e276b78c0996bf2819fa93183f7ee7639a92551
|
/jni/gcpe/world/gen/NewFeature.h
|
4da078d4def2b241010d26eb83b4676aa96a71ee
|
[] |
no_license
|
EEEEEEEEEEEEEEEEEEEIEEEEEEEEEEEEEEEEEE/Galacticraft-pocket-edition
|
a795cd58651f28c461a01f94792d4f2911ed2f65
|
3636a79eb31c252845743746224d59dccf2bb150
|
refs/heads/master
| 2020-06-12T06:19:20.835411
| 2017-02-07T09:18:35
| 2017-02-07T09:18:35
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 145
|
h
|
NewFeature.h
|
#pragma once
#include "mcpe/level/gen/Feature.h"
class NewFeature : public Feature
{
public:
NewFeature(BlockSource *, BlockPos const&);
};
|
ea10a84264070bd4b54b9ee6599926c208d794a6
|
1240cab345c126566291f8e461d063cb6430396f
|
/src/openms/source/TRANSFORMATIONS/FEATUREFINDER/FeatureFinderAlgorithmPicked.cpp
|
60d1dfd3e8fc5c5acc90fc68fe6beffc2756af9a
|
[
"BSD-3-Clause",
"BSL-1.0"
] |
permissive
|
OpenMS/OpenMS
|
05cd6c9a2b8f3004ef47755305711a6631c13340
|
15e8641e9b6fad76e8314448a808d68231a93088
|
refs/heads/develop
| 2023-08-18T03:44:50.273261
| 2023-08-17T19:45:27
| 2023-08-17T19:45:27
| 15,763,403
| 443
| 312
|
NOASSERTION
| 2023-09-14T13:29:36
| 2014-01-09T10:15:13
|
C++
|
UTF-8
|
C++
| false
| false
| 86,203
|
cpp
|
FeatureFinderAlgorithmPicked.cpp
|
// --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2023.
//
// This software is released under a three-clause BSD license:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm, Tom Lukas Lankenau $
// --------------------------------------------------------------------------
#include <OpenMS/TRANSFORMATIONS/FEATUREFINDER/FeatureFinderAlgorithmPicked.h>
#include <OpenMS/TRANSFORMATIONS/FEATUREFINDER/EGHTraceFitter.h>
#include <OpenMS/TRANSFORMATIONS/FEATUREFINDER/GaussTraceFitter.h>
#include <OpenMS/FORMAT/MzMLFile.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/FORMAT/TextFile.h>
#include <OpenMS/MATH/STATISTICS/StatisticFunctions.h>
#include <OpenMS/MATH/MISC/MathFunctions.h>
#include <OpenMS/CHEMISTRY/Element.h>
#include <OpenMS/CHEMISTRY/ElementDB.h>
#include <OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/IsotopeDistribution.h>
#include <OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/CoarseIsotopePatternGenerator.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <QtCore/QDir>
#include <boost/math/special_functions/fpclassify.hpp> // isnan
#ifdef _OPENMP
#include <omp.h>
#endif
namespace OpenMS
{
FeatureFinderAlgorithmPicked::FeatureFinderAlgorithmPicked() :
FeatureFinderAlgorithm(),
map_(),
log_()
{
//debugging
defaults_.setValue("debug", "false", "When debug mode is activated, several files with intermediate results are written to the folder 'debug' (do not use in parallel mode).");
defaults_.setValidStrings("debug", {"true","false"});
//intensity
defaults_.setValue("intensity:bins", 10, "Number of bins per dimension (RT and m/z). The higher this value, the more local the intensity significance score is.\nThis parameter should be decreased, if the algorithm is used on small regions of a map.");
defaults_.setMinInt("intensity:bins", 1);
defaults_.setSectionDescription("intensity", "Settings for the calculation of a score indicating if a peak's intensity is significant in the local environment (between 0 and 1)");
//mass trace search parameters
defaults_.setValue("mass_trace:mz_tolerance", 0.03, "Tolerated m/z deviation of peaks belonging to the same mass trace.\nIt should be larger than the m/z resolution of the instrument.\nThis value must be smaller than that 1/charge_high!");
defaults_.setMinFloat("mass_trace:mz_tolerance", 0.0);
defaults_.setValue("mass_trace:min_spectra", 10, "Number of spectra that have to show a similar peak mass in a mass trace.");
defaults_.setMinInt("mass_trace:min_spectra", 1);
defaults_.setValue("mass_trace:max_missing", 1, "Number of consecutive spectra where a high mass deviation or missing peak is acceptable.\nThis parameter should be well below 'min_spectra'!");
defaults_.setMinInt("mass_trace:max_missing", 0);
defaults_.setValue("mass_trace:slope_bound", 0.1, "The maximum slope of mass trace intensities when extending from the highest peak.\nThis parameter is important to separate overlapping elution peaks.\nIt should be increased if feature elution profiles fluctuate a lot.");
defaults_.setMinFloat("mass_trace:slope_bound", 0.0);
defaults_.setSectionDescription("mass_trace", "Settings for the calculation of a score indicating if a peak is part of a mass trace (between 0 and 1).");
//Isotopic pattern search parameters
defaults_.setValue("isotopic_pattern:charge_low", 1, "Lowest charge to search for.");
defaults_.setMinInt("isotopic_pattern:charge_low", 1);
defaults_.setValue("isotopic_pattern:charge_high", 4, "Highest charge to search for.");
defaults_.setMinInt("isotopic_pattern:charge_high", 1);
defaults_.setValue("isotopic_pattern:mz_tolerance", 0.03, "Tolerated m/z deviation from the theoretical isotopic pattern.\nIt should be larger than the m/z resolution of the instrument.\nThis value must be smaller than that 1/charge_high!");
defaults_.setMinFloat("isotopic_pattern:mz_tolerance", 0.0);
defaults_.setValue("isotopic_pattern:intensity_percentage", 10.0, "Isotopic peaks that contribute more than this percentage to the overall isotope pattern intensity must be present.", {"advanced"});
defaults_.setMinFloat("isotopic_pattern:intensity_percentage", 0.0);
defaults_.setMaxFloat("isotopic_pattern:intensity_percentage", 100.0);
defaults_.setValue("isotopic_pattern:intensity_percentage_optional", 0.1, "Isotopic peaks that contribute more than this percentage to the overall isotope pattern intensity can be missing.", {"advanced"});
defaults_.setMinFloat("isotopic_pattern:intensity_percentage_optional", 0.0);
defaults_.setMaxFloat("isotopic_pattern:intensity_percentage_optional", 100.0);
defaults_.setValue("isotopic_pattern:optional_fit_improvement", 2.0, "Minimal percental improvement of isotope fit to allow leaving out an optional peak.", {"advanced"});
defaults_.setMinFloat("isotopic_pattern:optional_fit_improvement", 0.0);
defaults_.setMaxFloat("isotopic_pattern:optional_fit_improvement", 100.0);
defaults_.setValue("isotopic_pattern:mass_window_width", 25.0, "Window width in Dalton for precalculation of estimated isotope distributions.", {"advanced"});
defaults_.setMinFloat("isotopic_pattern:mass_window_width", 1.0);
defaults_.setMaxFloat("isotopic_pattern:mass_window_width", 200.0);
defaults_.setValue("isotopic_pattern:abundance_12C", 98.93, "Rel. abundance of the light carbon. Modify if labeled.", {"advanced"});
defaults_.setMinFloat("isotopic_pattern:abundance_12C", 0.0);
defaults_.setMaxFloat("isotopic_pattern:abundance_12C", 100.0);
defaults_.setValue("isotopic_pattern:abundance_14N", 99.632, "Rel. abundance of the light nitrogen. Modify if labeled.", {"advanced"});
defaults_.setMinFloat("isotopic_pattern:abundance_14N", 0.0);
defaults_.setMaxFloat("isotopic_pattern:abundance_14N", 100.0);
defaults_.setSectionDescription("isotopic_pattern", "Settings for the calculation of a score indicating if a peak is part of a isotopic pattern (between 0 and 1).");
//Seed settings
defaults_.setValue("seed:min_score", 0.8, "Minimum seed score a peak has to reach to be used as seed.\nThe seed score is the geometric mean of intensity score, mass trace score and isotope pattern score.\nIf your features show a large deviation from the averagene isotope distribution or from an gaussian elution profile, lower this score.");
defaults_.setMinFloat("seed:min_score", 0.0);
defaults_.setMaxFloat("seed:min_score", 1.0);
defaults_.setSectionDescription("seed", "Settings that determine which peaks are considered a seed");
//Fitting settings
defaults_.setValue("fit:max_iterations", 500, "Maximum number of iterations of the fit.", {"advanced"});
defaults_.setMinInt("fit:max_iterations", 1);
defaults_.setSectionDescription("fit", "Settings for the model fitting");
//Feature settings
defaults_.setValue("feature:min_score", 0.7, "Feature score threshold for a feature to be reported.\nThe feature score is the geometric mean of the average relative deviation and the correlation between the model and the observed peaks.");
defaults_.setMinFloat("feature:min_score", 0.0);
defaults_.setMaxFloat("feature:min_score", 1.0);
defaults_.setValue("feature:min_isotope_fit", 0.8, "Minimum isotope fit of the feature before model fitting.", {"advanced"});
defaults_.setMinFloat("feature:min_isotope_fit", 0.0);
defaults_.setMaxFloat("feature:min_isotope_fit", 1.0);
defaults_.setValue("feature:min_trace_score", 0.5, "Trace score threshold.\nTraces below this threshold are removed after the model fitting.\nThis parameter is important for features that overlap in m/z dimension.", {"advanced"});
defaults_.setMinFloat("feature:min_trace_score", 0.0);
defaults_.setMaxFloat("feature:min_trace_score", 1.0);
defaults_.setValue("feature:min_rt_span", 0.333, "Minimum RT span in relation to extended area that has to remain after model fitting.", {"advanced"});
defaults_.setMinFloat("feature:min_rt_span", 0.0);
defaults_.setMaxFloat("feature:min_rt_span", 1.0);
defaults_.setValue("feature:max_rt_span", 2.5, "Maximum RT span in relation to extended area that the model is allowed to have.", {"advanced"});
defaults_.setMinFloat("feature:max_rt_span", 0.5);
defaults_.setValue("feature:rt_shape", "symmetric", "Choose model used for RT profile fitting. If set to symmetric a gauss shape is used, in case of asymmetric an EGH shape is used.", {"advanced"});
defaults_.setValidStrings("feature:rt_shape", {"symmetric","asymmetric"});
defaults_.setValue("feature:max_intersection", 0.35, "Maximum allowed intersection of features.", {"advanced"});
defaults_.setMinFloat("feature:max_intersection", 0.0);
defaults_.setMaxFloat("feature:max_intersection", 1.0);
defaults_.setValue("feature:reported_mz", "monoisotopic", "The mass type that is reported for features.\n'maximum' returns the m/z value of the highest mass trace.\n'average' returns the intensity-weighted average m/z value of all contained peaks.\n'monoisotopic' returns the monoisotopic m/z value derived from the fitted isotope model.");
defaults_.setValidStrings("feature:reported_mz", {"maximum","average","monoisotopic"});
defaults_.setSectionDescription("feature", "Settings for the features (intensity, quality assessment, ...)");
//user-specified seed settings
defaults_.setValue("user-seed:rt_tolerance", 5.0, "Allowed RT deviation of seeds from the user-specified seed position.");
defaults_.setMinFloat("user-seed:rt_tolerance", 0.0);
defaults_.setValue("user-seed:mz_tolerance", 1.1, "Allowed m/z deviation of seeds from the user-specified seed position.");
defaults_.setMinFloat("user-seed:mz_tolerance", 0.0);
defaults_.setValue("user-seed:min_score", 0.5, "Overwrites 'seed:min_score' for user-specified seeds. The cutoff is typically a bit lower in this case.");
defaults_.setMinFloat("user-seed:min_score", 0.0);
defaults_.setMaxFloat("user-seed:min_score", 1.0);
defaults_.setSectionDescription("user-seed", "Settings for user-specified seeds.");
//debug settings
defaults_.setValue("debug:pseudo_rt_shift", 500.0, "Pseudo RT shift used when .", {"advanced"});
defaults_.setMinFloat("debug:pseudo_rt_shift", 1.0);
this->defaultsToParam_();
}
void FeatureFinderAlgorithmPicked::setSeeds(const FeatureMap& seeds)
{
seeds_ = seeds;
}
void FeatureFinderAlgorithmPicked::run()
{
//-------------------------------------------------------------------------
// General initialization
//---------------------------------------------------------------------------
//quality estimation
double min_feature_score = param_.getValue("feature:min_score");
// charges to look at
SignedSize charge_low = (Int)param_.getValue("isotopic_pattern:charge_low");
SignedSize charge_high = (Int)param_.getValue("isotopic_pattern:charge_high");
//fitting settings
UInt max_iterations = param_.getValue("fit:max_iterations");
Size max_isotopes = 20;
//check if non-natural isotopic abundances are set. If so modify
double abundance_12C = param_.getValue("isotopic_pattern:abundance_12C");
double abundance_14N = param_.getValue("isotopic_pattern:abundance_14N");
const Element* carbon_const = ElementDB::getInstance()->getElement("Carbon");
Element* carbon = const_cast<Element*>(carbon_const);
if (param_.getValue("isotopic_pattern:abundance_12C") != defaults_.getValue("isotopic_pattern:abundance_12C"))
{
max_isotopes += 1000; // Why?
IsotopeDistribution isotopes;
isotopes.insert(12, abundance_12C / 100.0);
isotopes.insert(13, 1.0 - (abundance_12C / 100.0));
carbon->setIsotopeDistribution(isotopes);
}
const Element* nitrogen_const = ElementDB::getInstance()->getElement("Nitrogen");
Element* nitrogen = const_cast<Element*>(nitrogen_const);
if (param_.getValue("isotopic_pattern:abundance_14N") != defaults_.getValue("isotopic_pattern:abundance_14N"))
{
max_isotopes += 1000; // Why?
IsotopeDistribution isotopes;
isotopes.insert(14, abundance_14N / 100.0);
isotopes.insert(15, 1.0 - (abundance_14N / 100.0));
nitrogen->setIsotopeDistribution(isotopes);
}
// initialize trace fitter parameters here to avoid
// https://github.com/OpenMS/OpenMS/issues/147
Param trace_fitter_params;
trace_fitter_params.setValue("max_iteration", max_iterations);
//copy the input map
map_ = *(FeatureFinderAlgorithm::map_);
//flag for user-specified seed mode
bool user_seeds = (!seeds_.empty());
if (user_seeds)
{
seeds_.sortByMZ();
}
double user_rt_tol = param_.getValue("user-seed:rt_tolerance");
double user_mz_tol = param_.getValue("user-seed:mz_tolerance");
double user_seed_score = param_.getValue("user-seed:min_score");
//reserve space for calculated scores
UInt charge_count = charge_high - charge_low + 1;
for (auto& s : map_)
{
Size scan_size = s.size();
s.getFloatDataArrays().resize(3 + 2 * charge_count);
s.getFloatDataArrays()[0].setName("trace_score");
s.getFloatDataArrays()[0].assign(scan_size, 0.0);
s.getFloatDataArrays()[1].setName("intensity_score");
s.getFloatDataArrays()[1].assign(scan_size, 0.0);
s.getFloatDataArrays()[2].setName("local_max");
s.getFloatDataArrays()[2].assign(scan_size, 0.0);
//create isotope pattern score arrays
UInt charge = charge_low;
for (Size i = 3; i < 3 + charge_count; ++i)
{
s.getFloatDataArrays()[i].setName(String("pattern_score_") + charge);
s.getFloatDataArrays()[i].assign(scan_size, 0.0);
++charge;
}
//create overall score arrays
charge = charge_low;
for (Size i = 3 + charge_count; i < 3 + 2 * charge_count; ++i)
{
s.getFloatDataArrays()[i].setName(String("overall_score_") + charge);
s.getFloatDataArrays()[i].assign(scan_size, 0.0);
++charge;
}
}
debug_ = param_.getValue("debug").toBool();
//clean up / create folders for debug information
if (debug_)
{
QDir dir(".");
dir.mkpath("debug/features");
log_.open("debug/log.txt");
}
//---------------------------------------------------------------------------
// Step 1:
// Precalculate intensity scores for peaks
//---------------------------------------------------------------------------
if (debug_) log_ << "Precalculating intensity thresholds ..." << std::endl;
//new scope to make local variables disappear
{
ff_->startProgress(0, intensity_bins_ * intensity_bins_, "Precalculating intensity scores");
double rt_start = map_.getMinRT();
double mz_start = map_.getMinMZ();
intensity_rt_step_ = (map_.getMaxRT() - rt_start) / (double)intensity_bins_;
intensity_mz_step_ = (map_.getMaxMZ() - mz_start) / (double)intensity_bins_;
intensity_thresholds_.resize(intensity_bins_);
for (Size rt = 0; rt < intensity_bins_; ++rt)
{
intensity_thresholds_[rt].resize(intensity_bins_);
double min_rt = rt_start + rt * intensity_rt_step_;
double max_rt = rt_start + (rt + 1) * intensity_rt_step_;
std::vector<double> tmp;
for (Size mz = 0; mz < intensity_bins_; ++mz)
{
ff_->setProgress(rt * intensity_bins_ + mz);
double min_mz = mz_start + mz * intensity_mz_step_;
double max_mz = mz_start + (mz + 1) * intensity_mz_step_;
//std::cout << "rt range: " << min_rt << " - " << max_rt << std::endl;
//std::cout << "mz range: " << min_mz << " - " << max_mz << std::endl;
tmp.clear();
for (MapType::ConstAreaIterator it = map_.areaBeginConst(min_rt, max_rt, min_mz, max_mz); it != map_.areaEndConst(); ++it)
{
tmp.push_back(it->getIntensity());
}
//init vector
intensity_thresholds_[rt][mz].assign(21, 0.0);
//store quantiles (20)
if (!tmp.empty())
{
std::sort(tmp.begin(), tmp.end());
for (Size i = 0; i < 21; ++i)
{
Size index = (Size)std::floor(0.05 * i * (tmp.size() - 1));
intensity_thresholds_[rt][mz][i] = tmp[index];
}
}
}
}
//store intensity score in PeakInfo
for (Size s = 0; s < map_.size(); ++s)
{
for (Size p = 0; p < map_[s].size(); ++p)
{
map_[s].getFloatDataArrays()[1][p] = intensityScore_(s, p);
}
}
ff_->endProgress();
}
//---------------------------------------------------------------------------
// Step 2:
// Precalculate mass trace scores and local trace maximum for each peak
//---------------------------------------------------------------------------
//new scope to make local variables disappear
{
Size end_iteration = map_.size() - std::min((Size)min_spectra_, map_.size());
ff_->startProgress(min_spectra_, end_iteration, "Precalculating mass trace scores");
// skip first and last scans since we cannot extend the mass traces there
for (Size s = min_spectra_; s < end_iteration; ++s)
{
ff_->setProgress(s);
SpectrumType& spectrum = map_[s];
//iterate over all peaks of the scan
for (Size p = 0; p < spectrum.size(); ++p)
{
double trace_score = 0.0;
double pos = spectrum[p].getMZ();
float intensity = spectrum[p].getIntensity();
//if(debug_) log_ << std::endl << "Peak: " << pos << std::endl;
bool is_max_peak = true; // checking the maximum intensity peaks -> use them later as feature seeds.
for (Size i = 1; i <= min_spectra_; ++i)
{
SpectrumType& next_spectrum = map_[s + i];
if (!next_spectrum.empty()) // There are peaks in the spectrum
{
Size spec_index = next_spectrum.findNearest(pos);
double position_score = positionScore_(pos, next_spectrum[spec_index].getMZ(), trace_tolerance_);
if (position_score > 0 && next_spectrum[spec_index].getIntensity() > intensity) is_max_peak = false;
trace_score += position_score;
}
}
for (Size i = 1; i <= min_spectra_; ++i)
{
SpectrumType& next_spectrum = map_[s - i];
if (!next_spectrum.empty()) // There are peaks in the spectrum
{
Size spec_index = next_spectrum.findNearest(pos);
double position_score = positionScore_(pos, next_spectrum[spec_index].getMZ(), trace_tolerance_);
if (position_score > 0 && next_spectrum[spec_index].getIntensity() > intensity)
{
is_max_peak = false;
}
trace_score += position_score;
}
}
//Calculate a consensus score out of the scores calculated before
trace_score /= 2 * min_spectra_;
//store final score for later use
spectrum.getFloatDataArrays()[0][p] = trace_score;
spectrum.getFloatDataArrays()[2][p] = is_max_peak;
}
}
ff_->endProgress();
}
//---------------------------------------------------------------------------
// Step 2.5:
// Precalculate isotope distributions for interesting mass ranges
//---------------------------------------------------------------------------
//new scope to make local variables disappear
{
double max_mass = map_.getMaxMZ() * charge_high;
Size num_isotopes = std::ceil(max_mass / mass_window_width_) + 1;
ff_->startProgress(0, num_isotopes, "Precalculating isotope distributions");
//reserve enough space
isotope_distributions_.resize(num_isotopes);
//calculate distribution if necessary
for (Size index = 0; index < num_isotopes; ++index)
{
//if(debug_) log_ << "Calculating iso dist for mass: " << 0.5*mass_window_width_ + index * mass_window_width_ << std::endl;
CoarseIsotopePatternGenerator solver(max_isotopes);
auto d = solver.estimateFromPeptideWeight(0.5 * mass_window_width_ + index * mass_window_width_);
//trim left and right. And store the number of isotopes on the left, to reconstruct the monoisotopic peak
Size size_before = d.size();
d.trimLeft(intensity_percentage_optional_);
isotope_distributions_[index].trimmed_left = size_before - d.size();
d.trimRight(intensity_percentage_optional_);
for (auto& peak : d)
{
isotope_distributions_[index].intensity.push_back(peak.getIntensity());
//if(debug_) log_ << " - " << it->second << std::endl;
}
//determine the number of optional peaks at the beginning/end
Size begin = 0;
Size end = 0;
bool is_begin = true;
bool is_end = false;
for (double i : isotope_distributions_[index].intensity)
{
if (i < intensity_percentage_)
{
if (!is_end && !is_begin)
{
is_end = true;
}
if (is_begin)
{
++begin;
}
else if (is_end)
{
++end;
}
}
else if (is_begin)
{
is_begin = false;
}
}
isotope_distributions_[index].optional_begin = begin;
isotope_distributions_[index].optional_end = end;
//scale the distribution to a maximum of 1
double max = 0.0;
for (double i : isotope_distributions_[index].intensity)
{
if (i > max)
{
max = i;
}
}
isotope_distributions_[index].max = max;
for (double& i : isotope_distributions_[index].intensity)
{
i /= max;
}
//if(debug_) log_ << " - optional begin/end:" << begin << " / " << end << std::endl;
}
ff_->endProgress();
}
//-------------------------------------------------------------------------
// Step 3:
// Charge loop (create seeds and features for each charge separately)
//-------------------------------------------------------------------------
Int plot_nr_global = -1; // counter for the number of plots (debug info)
Int feature_nr_global = 0; // counter for the number of features (debug info)
for (SignedSize c = charge_low; c <= charge_high; ++c)
{
UInt meta_index_isotope = 3 + c - charge_low;
UInt meta_index_overall = 3 + charge_count + c - charge_low;
Size feature_candidates = 0;
std::vector<Seed> seeds;
//-----------------------------------------------------------
// Step 3.1: Precalculate IsotopePattern score
//-----------------------------------------------------------
ff_->startProgress(0, map_.size(), String("Calculating isotope pattern scores for charge ") + String(c));
for (Size s = 0; s < map_.size(); ++s)
{
ff_->setProgress(s);
const SpectrumType& spectrum = map_[s];
for (Size p = 0; p < spectrum.size(); ++p)
{
double mz = spectrum[p].getMZ();
//get isotope distribution for this mass
const TheoreticalIsotopePattern& isotopes = getIsotopeDistribution_(mz * c);
//determine highest peak in isotope distribution
Size max_isotope = std::max_element(isotopes.intensity.begin(), isotopes.intensity.end()) - isotopes.intensity.begin();
//Look up expected isotopic peaks (in the current spectrum or adjacent spectra)
Size peak_index = spectrum.findNearest(mz - ((double)(isotopes.size() + 1) / c));
IsotopePattern pattern(isotopes.size());
for (Size i = 0; i < isotopes.size(); ++i)
{
double isotope_pos = mz + ((double)i - max_isotope) / c;
findIsotope_(isotope_pos, s, pattern, i, peak_index);
}
double pattern_score = isotopeScore_(isotopes, pattern, true);
//update pattern scores of all contained peaks (if necessary)
if (pattern_score > 0.0)
{
for (Size i = 0; i < pattern.peak.size(); ++i)
{
if (pattern.peak[i] >= 0 && pattern_score > map_[pattern.spectrum[i]].getFloatDataArrays()[meta_index_isotope][pattern.peak[i]])
{
map_[pattern.spectrum[i]].getFloatDataArrays()[meta_index_isotope][pattern.peak[i]] = pattern_score;
}
}
}
}
}
ff_->endProgress();
//-----------------------------------------------------------
// Step 3.2:
// Find seeds for this charge
//-----------------------------------------------------------
Size end_of_iteration = map_.size() - std::min((Size)min_spectra_, map_.size());
ff_->startProgress(min_spectra_, end_of_iteration, String("Finding seeds for charge ") + String(c));
double min_seed_score = param_.getValue("seed:min_score");
//do nothing for the first few and last few spectra as the scans required to search for traces are missing
for (Size s = min_spectra_; s < end_of_iteration; ++s)
{
ff_->setProgress(s);
//iterate over peaks
for (Size p = 0; p < map_[s].size(); ++p)
{
FloatDataArrays& meta = map_[s].getFloatDataArrays();
double overall_score = std::pow(meta[0][p] * meta[1][p] * meta[meta_index_isotope][p], 1.0f / 3.0f);
meta[meta_index_overall][p] = overall_score;
//add seed to vector if certain conditions are fulfilled
if (meta[2][p] != 0.0) // local maximum of mass trace is prerequisite for all features
{
//automatic seeds: overall score greater than the min seed score
if (!user_seeds && overall_score >= min_seed_score)
{
Seed seed;
seed.spectrum = s;
seed.peak = p;
seed.intensity = map_[s][p].getIntensity();
seeds.push_back(seed);
}
//user-specified seeds: overall score greater than USER min seed score
else if (user_seeds && overall_score >= user_seed_score)
{
//only consider seeds, if they are near a user-specified seed
Feature tmp;
tmp.setMZ(map_[s][p].getMZ() - user_mz_tol);
for (FeatureMap::const_iterator it = std::lower_bound(seeds_.begin(), seeds_.end(), tmp, Feature::MZLess()); it < seeds_.end(); ++it)
{
if (it->getMZ() > map_[s][p].getMZ() + user_mz_tol)
{
break;
}
if (fabs(it->getMZ() - map_[s][p].getMZ()) < user_mz_tol && fabs(it->getRT() - map_[s].getRT()) < user_rt_tol)
{
Seed seed;
seed.spectrum = s;
seed.peak = p;
seed.intensity = map_[s][p].getIntensity();
seeds.push_back(seed);
break;
}
}
}
}
}
}
//sort seeds according to intensity
std::sort(seeds.rbegin(), seeds.rend());
//create and store seeds map and selected peak map
if (debug_)
{
//seeds
FeatureMap seed_map;
seed_map.reserve(seeds.size());
for (auto& seed : seeds)
{
Size spectrum = seed.spectrum;
Size peak = seed.peak;
const FloatDataArrays& meta = map_[spectrum].getFloatDataArrays();
Feature tmp;
tmp.setIntensity(seed.intensity);
tmp.setOverallQuality(meta[meta_index_overall][peak]);
tmp.setRT(map_[spectrum].getRT());
tmp.setMZ(map_[spectrum][peak].getMZ());
tmp.setMetaValue("intensity_score", meta[1][peak]);
tmp.setMetaValue("pattern_score", meta[meta_index_isotope][peak]);
tmp.setMetaValue("trace_score", meta[0][peak]);
seed_map.push_back(tmp);
}
FileHandler().storeFeatures(String("debug/seeds_") + String(c) + ".featureXML", seed_map);
}
ff_->endProgress();
std::cout << "Found " << seeds.size() << " seeds for charge " << c << "." << std::endl;
//------------------------------------------------------------------
// Step 3.3:
// Extension of seeds
//------------------------------------------------------------------
// We do not want to store features whose seeds lie within other
// features with higher intensity. We thus store this information in
// the map seeds_in_features which contains for each seed i a vector
// of other seeds that are contained in the corresponding feature i.
//
// The features are stored in an temporary feature map until it is
// decided whether they are contained within a seed of higher
// intensity.
std::map<Size, std::vector<Size>> seeds_in_features;
typedef std::map<Size, Feature> FeatureMapType;
FeatureMapType tmp_feature_map;
int gl_progress = 0;
ff_->startProgress(0, seeds.size(), String("Extending seeds for charge ") + String(c));
#pragma omp parallel for
for (SignedSize i = 0; i < (SignedSize)seeds.size(); ++i)
{
//------------------------------------------------------------------
// Step 3.3.1:
// Extend all mass traces
//------------------------------------------------------------------
const SpectrumType& spectrum = map_[seeds[i].spectrum];
const PeakType& peak = spectrum[seeds[i].peak];
IF_MASTERTHREAD
{
ff_->setProgress(gl_progress++);
if (debug_)
{
log_ << std::endl << "Seed " << i << ":" << std::endl;
//If the intensity is zero this seed is already uses in another feature
log_ << " - Int: " << peak.getIntensity() << std::endl;
log_ << " - RT: " << spectrum.getRT() << std::endl;
log_ << " - MZ: " << peak.getMZ() << std::endl;
}
}
//----------------------------------------------------------------
//Find best fitting isotope pattern for this charge (using averagine)
IsotopePattern best_pattern(0);
double isotope_fit_quality = findBestIsotopeFit_(seeds[i], c, best_pattern);
if (isotope_fit_quality < min_isotope_fit_)
{
abort_(seeds[i], "Could not find good enough isotope pattern containing the seed");
continue;
}
//extend the convex hull in RT dimension (starting from the trace peaks)
MassTraces traces;
traces.reserve(best_pattern.peak.size());
extendMassTraces_(best_pattern, traces, meta_index_overall);
//check if the traces are still valid
double seed_mz = map_[seeds[i].spectrum][seeds[i].peak].getMZ();
if (!traces.isValid(seed_mz, trace_tolerance_))
{
abort_(seeds[i], "Could not extend seed");
continue;
}
//------------------------------------------------------------------
// Step 3.3.2:
// Gauss/EGH fit (first fit to find the feature boundaries)
//------------------------------------------------------------------
Int plot_nr = -1;
#pragma omp critical(FeatureFinderAlgorithmPicked_PLOTNR)
{
plot_nr = ++plot_nr_global;
}
//------------------------------------------------------------------
//TODO try fit with baseline term once more
//baseline estimate
traces.updateBaseline();
traces.baseline = 0.75 * traces.baseline;
traces[traces.max_trace].updateMaximum();
//choose fitter
double egh_tau = 0.0;
std::shared_ptr<TraceFitter> fitter = chooseTraceFitter_(egh_tau);
fitter->setParameters(trace_fitter_params);
fitter->fit(traces);
#if 0
TraceFitter<PeakType>* alt_fitter = new GaussTraceFitter<PeakType>();
Param alt_p;
alt_p.setValue("max_iteration", max_iterations);
alt_fitter->setParameters(alt_p);
alt_fitter->fit(traces);
OPENMS_LOG_DEBUG << "EGH: " << fitter->getCenter() << " " << fitter->getHeight() << std::endl;
OPENMS_LOG_DEBUG << "GAUSS: " << alt_fitter->getCenter() << " " << alt_fitter->getHeight() << std::endl;
#endif
// what should come out
// left "sigma"
// right "sigma"
// x0 .. "center" position of RT fit
// height .. "height" of RT fit
//------------------------------------------------------------------
//------------------------------------------------------------------
// Step 3.3.3:
// Crop feature according to RT fit (2.5*sigma) and remove badly fitting traces
//------------------------------------------------------------------
MassTraces new_traces;
cropFeature_(fitter, traces, new_traces);
//------------------------------------------------------------------
// Step 3.3.4:
// Check if feature is ok
//------------------------------------------------------------------
String error_msg = "";
double fit_score = 0.0;
double correlation = 0.0;
double final_score = 0.0;
int number_of_datapoints = 0;
bool feature_ok = checkFeatureQuality_(fitter, new_traces, seed_mz, min_feature_score, error_msg, fit_score, correlation, final_score);
{
//write debug output of feature
if (debug_)
{
#pragma omp critical(FeatureFinderAlgorithmPicked_DEBUG)
writeFeatureDebugInfo_(fitter, traces, new_traces, feature_ok, error_msg, final_score, plot_nr, peak);
}
}
//validity output
if (!feature_ok)
{
abort_(seeds[i], error_msg);
continue;
}
traces = new_traces;
//------------------------------------------------------------------
// Step 3.3.5:
// Feature creation
//------------------------------------------------------------------
Feature f;
//set label
f.setMetaValue(3, plot_nr);
f.setCharge(c);
f.setOverallQuality(final_score);
f.setMetaValue("score_fit", fit_score);
f.setMetaValue("score_correlation", correlation);
f.setRT(fitter->getCenter());
f.setWidth(fitter->getFWHM());
// metavalue num_of_datapoints
for (size_t t = 0; t < traces.size(); ++t)
{
number_of_datapoints += traces[t].peaks.size();
}
f.setMetaValue(Constants::UserParam::NUM_OF_DATAPOINTS, number_of_datapoints);
//Extract some of the model parameters.
if (egh_tau != 0.0)
{
egh_tau = (std::dynamic_pointer_cast<EGHTraceFitter>(fitter))->getTau();
f.setMetaValue("EGH_tau", egh_tau);
f.setMetaValue("EGH_height", (std::dynamic_pointer_cast<EGHTraceFitter>(fitter))->getHeight());
f.setMetaValue("EGH_sigma", (std::dynamic_pointer_cast<EGHTraceFitter>(fitter))->getSigma());
}
//Calculate the mass of the feature: maximum, average, monoisotopic
if (reported_mz_ == "maximum")
{
f.setMZ(traces[traces.getTheoreticalmaxPosition()].getAvgMZ());
}
else if (reported_mz_ == "average")
{
double total_intensity = 0.0;
double average_mz = 0.0;
for (Size t = 0; t < traces.size(); ++t)
{
for (auto& p : traces[t].peaks)
{
average_mz += p.second->getMZ() * p.second->getIntensity();
total_intensity += p.second->getIntensity();
}
}
average_mz /= total_intensity;
f.setMZ(average_mz);
}
else if (reported_mz_ == "monoisotopic")
{
double mono_mz = traces[traces.getTheoreticalmaxPosition()].getAvgMZ();
mono_mz -= (Constants::PROTON_MASS_U / c) * (traces.getTheoreticalmaxPosition() + best_pattern.theoretical_pattern.trimmed_left);
f.setMZ(mono_mz);
}
// Calculate intensity based on model only
// - the model does not include the baseline, so we ignore it here
// - as we scaled the isotope distribution to
f.setIntensity(fitter->getArea() / getIsotopeDistribution_(f.getMZ()).max);
//add convex hulls of mass traces
for (Size j = 0; j < traces.size(); ++j)
{
f.getConvexHulls().push_back(traces[j].getConvexhull());
}
#pragma omp critical(FeatureFinderAlgorithmPicked_TMPFEATUREMAP)
{
tmp_feature_map[i] = f;
}
//----------------------------------------------------------------
//Remember all seeds that lie inside the convex hull of the new feature
DBoundingBox<2> bb = f.getConvexHull().getBoundingBox();
for (Size j = i + 1; j < seeds.size(); ++j)
{
double rt = map_[seeds[j].spectrum].getRT();
double mz = map_[seeds[j].spectrum][seeds[j].peak].getMZ();
if (bb.encloses(rt, mz) && f.encloses(rt, mz))
{
#pragma omp critical(FeatureFinderAlgorithmPicked_SEEDSINFEATURES)
{
seeds_in_features[i].push_back(j);
}
}
}
} //end of OPENMP over seeds
// Here we have to evaluate which seeds are already contained in
// features of seeds with higher intensities. Only if the seed is not
// used in any feature with higher intensity, we can add it to the
// features_ list.
std::vector<Size> seeds_contained;
for (auto& f : tmp_feature_map)
{
Size seed_nr = f.first;
bool is_used = false;
for (Size i : seeds_contained)
{
if (seed_nr == i)
{
is_used = true;
break;
}
}
if (!is_used)
{
++feature_candidates;
//re-set label
f.second.setMetaValue(3, feature_nr_global);
++feature_nr_global;
features_->push_back(f.second);
std::vector<Size> curr_seed = seeds_in_features[seed_nr];
for (Size k : curr_seed)
{
seeds_contained.push_back(k);
}
}
}
IF_MASTERTHREAD ff_->endProgress();
std::cout << "Found " << feature_candidates << " feature candidates for charge " << c << "." << std::endl;
}
// END OPENMP
//------------------------------------------------------------------
//Step 4:
//Resolve contradicting and overlapping features
//------------------------------------------------------------------
ff_->startProgress(0, features_->size() * features_->size(), "Resolving overlapping features");
if (debug_) log_ << "Resolving intersecting features (" << features_->size() << " candidates)" << std::endl;
//sort features according to m/z in order to speed up the resolution
features_->sortByMZ();
//precalculate BBs and maximum mz span
std::vector<DBoundingBox<2> > bbs(features_->size());
double max_mz_span = 0.0;
for (Size i = 0; i < features_->size(); ++i)
{
bbs[i] = (*features_)[i].getConvexHull().getBoundingBox();
if (bbs[i].height() > max_mz_span)
{
max_mz_span = bbs[i].height();
}
}
Size removed(0);
//intersect
for (Size i = 0; i < features_->size(); ++i)
{
Feature& f1((*features_)[i]);
for (Size j = i + 1; j < features_->size(); ++j)
{
ff_->setProgress(i * features_->size() + j);
Feature& f2((*features_)[j]);
//features that are more than 2 times the maximum m/z span apart do not overlap => abort
if (f2.getMZ() - f1.getMZ() > 2.0 * max_mz_span)
{
break;
}
//do nothing if one of the features is already removed
if (f1.getIntensity() == 0.0 || f2.getIntensity() == 0.0)
{
continue;
}
//do nothing if the overall convex hulls do not overlap
if (!bbs[i].intersects(bbs[j]))
{
continue;
}
//act depending on the intersection
double intersection = intersection_(f1, f2);
if (intersection >= max_feature_intersection_)
{
++removed;
if (debug_)
{
log_ << " - Intersection (" << (i + 1) << "/" << (j + 1) << "): " << intersection << std::endl;
}
if (f1.getCharge() == f2.getCharge())
{
if (f1.getIntensity() * f1.getOverallQuality() > f2.getIntensity() * f2.getOverallQuality())
{
if (debug_)
{
log_ << " - same charge -> removing duplicate " << (j + 1) << std::endl;
}
f1.getSubordinates().push_back(f2);
f2.setIntensity(0.0);
}
else
{
if (debug_)
{
log_ << " - same charge -> removing duplicate " << (i + 1) << std::endl;
}
f2.getSubordinates().push_back(f1);
f1.setIntensity(0.0);
}
}
else if (f2.getCharge() % f1.getCharge() == 0)
{
if (debug_)
{
log_ << " - different charge (one is the multiple of the other) -> removing lower charge " << (i + 1) << std::endl;
}
f2.getSubordinates().push_back(f1);
f1.setIntensity(0.0);
}
else if (f1.getCharge() % f2.getCharge() == 0)
{
if (debug_)
{
log_ << " - different charge (one is the multiple of the other) -> removing lower charge " << (i + 1) << std::endl;
}
f1.getSubordinates().push_back(f2);
f2.setIntensity(0.0);
}
else
{
if (f1.getOverallQuality() > f2.getOverallQuality())
{
if (debug_)
{
log_ << " - different charge -> removing lower score " << (j + 1) << std::endl;
}
f1.getSubordinates().push_back(f2);
f2.setIntensity(0.0);
}
else
{
if (debug_)
{
log_ << " - different charge -> removing lower score " << (i + 1) << std::endl;
}
f2.getSubordinates().push_back(f1);
f1.setIntensity(0.0);
}
}
}
}
}
OPENMS_LOG_INFO << "Removed " << removed << " overlapping features." << std::endl;
// finally remove features with intensity 0
FeatureMap tmp;
tmp.reserve(features_->size());
for (Size i = 0; i < features_->size(); ++i)
{
if (features_->operator[](i).getIntensity() != 0.0)
{
tmp.push_back(features_->operator[](i));
}
}
tmp.swapFeaturesOnly(*features_);
// sort features by intensity
features_->sortByIntensity(true);
ff_->endProgress();
// Abort reasons
OPENMS_LOG_INFO << '\n';
OPENMS_LOG_INFO << "Info: reasons for not finalizing a feature during its construction:\n";
for (const auto& reason : aborts_)
{
OPENMS_LOG_INFO << " - " << reason.first << ": " << reason.second << " times\n";
}
OPENMS_LOG_INFO << "\n" << features_->size() << " features found." << std::endl;
if (debug_)
{
//store map of abort reasons for failed seeds
FeatureMap abort_map;
abort_map.reserve(abort_reasons_.size());
Size counter = 0;
for (std::map<Seed, String>::iterator it2 = abort_reasons_.begin(); it2 != abort_reasons_.end(); ++it2, ++counter)
{
Feature f;
f.setRT(map_[it2->first.spectrum].getRT());
f.setMZ(map_[it2->first.spectrum][it2->first.peak].getMZ());
f.setIntensity(map_[it2->first.spectrum][it2->first.peak].getIntensity());
f.setMetaValue("label", it2->second);
f.setUniqueId(counter); // ID = index
abort_map.push_back(f);
}
abort_map.setUniqueId();
FileHandler().storeFeatures("debug/abort_reasons.featureXML", abort_map);
//store input map with calculated scores (without overall score)
for (auto& s : map_)
{
s.getFloatDataArrays().erase(s.getFloatDataArrays().begin() + 2);
}
MzMLFile().store("debug/input.mzML", map_);
}
}
FeatureFinderAlgorithm* FeatureFinderAlgorithmPicked::create()
{
return new FeatureFinderAlgorithmPicked();
}
const String FeatureFinderAlgorithmPicked::getProductName()
{
return "centroided";
}
void FeatureFinderAlgorithmPicked::updateMembers_()
{
pattern_tolerance_ = param_.getValue("mass_trace:mz_tolerance");
trace_tolerance_ = param_.getValue("isotopic_pattern:mz_tolerance");
min_spectra_ = (UInt) std::floor((double)param_.getValue("mass_trace:min_spectra") * 0.5);
max_missing_trace_peaks_ = param_.getValue("mass_trace:max_missing");
slope_bound_ = param_.getValue("mass_trace:slope_bound");
intensity_percentage_ = (double)param_.getValue("isotopic_pattern:intensity_percentage") / 100.0;
intensity_percentage_optional_ = (double)param_.getValue("isotopic_pattern:intensity_percentage_optional") / 100.0;
optional_fit_improvement_ = (double)param_.getValue("isotopic_pattern:optional_fit_improvement") / 100.0;
mass_window_width_ = param_.getValue("isotopic_pattern:mass_window_width");
intensity_bins_ = param_.getValue("intensity:bins");
min_isotope_fit_ = param_.getValue("feature:min_isotope_fit");
min_trace_score_ = param_.getValue("feature:min_trace_score");
min_rt_span_ = param_.getValue("feature:min_rt_span");
max_rt_span_ = param_.getValue("feature:max_rt_span");
max_feature_intersection_ = param_.getValue("feature:max_intersection");
reported_mz_ = param_.getValue("feature:reported_mz").toString();
}
/// Writes the abort reason to the log file and counts occurrences for each reason
void FeatureFinderAlgorithmPicked::abort_(const Seed& seed, const String& reason)
{
if (debug_)
{
log_ << "Abort: " << reason << std::endl;
}
aborts_[reason]++;
if (debug_)
{
abort_reasons_[seed] = reason;
}
}
double FeatureFinderAlgorithmPicked::intersection_(const Feature& f1, const Feature& f2) const
{
//calculate the RT range sum of feature 1
double s1 = 0.0;
const std::vector<ConvexHull2D>& hulls1 = f1.getConvexHulls();
for (const auto& i : hulls1)
{
s1 += i.getBoundingBox().width();
}
//calculate the RT range sum of feature 2
double s2 = 0.0;
const std::vector<ConvexHull2D>& hulls2 = f2.getConvexHulls();
for (const auto& j : hulls2)
{
s2 += j.getBoundingBox().width();
}
//calculate overlap
double overlap = 0.0;
for (const auto& i : hulls1)
{
DBoundingBox<2> bb1 = i.getBoundingBox();
for (const auto& j : hulls2)
{
DBoundingBox<2> bb2 = j.getBoundingBox();
if (bb1.intersects(bb2))
{
if (bb1.minPosition()[0] <= bb2.minPosition()[0] &&
bb1.maxPosition()[0] >= bb2.maxPosition()[0]) //bb1 contains bb2
{
overlap += bb2.width();
}
else if (bb2.minPosition()[0] <= bb1.minPosition()[0] &&
bb2.maxPosition()[0] >= bb1.maxPosition()[0]) //bb2 contains bb1
{
overlap += bb1.width();
}
else if (bb1.minPosition()[0] <= bb2.minPosition()[0] &&
bb1.maxPosition()[0] <= bb2.maxPosition()[0]) //the end of bb1 overlaps with bb2
{
overlap += bb1.maxPosition()[0] - bb2.minPosition()[0];
}
else if (bb2.minPosition()[0] <= bb1.minPosition()[0] &&
bb2.maxPosition()[0] <= bb1.maxPosition()[0]) //the end of bb2 overlaps with bb1
{
overlap += bb2.maxPosition()[0] - bb1.minPosition()[0];
}
}
}
}
return overlap / std::min(s1, s2);
}
const FeatureFinderAlgorithmPickedHelperStructs::TheoreticalIsotopePattern& FeatureFinderAlgorithmPicked::getIsotopeDistribution_(double mass) const
{
//calculate index in the vector
Size index = (Size) std::floor(mass / mass_window_width_);
if (index >= isotope_distributions_.size())
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "IsotopeDistribution not precalculated. Maximum allowed index is " + String(isotope_distributions_.size()), String(index));
}
//Return distribution
return isotope_distributions_[index];
}
double FeatureFinderAlgorithmPicked::findBestIsotopeFit_(const Seed& center, UInt charge, IsotopePattern& best_pattern) const
{
if (debug_)
{
log_ << "Testing isotope patterns for charge " << charge << ": " << std::endl;
}
const SpectrumType& spectrum = map_[center.spectrum];
const TheoreticalIsotopePattern& isotopes = getIsotopeDistribution_(spectrum[center.peak].getMZ() * charge);
if (debug_)
{
log_ << " - Seed: " << center.peak << " (mz:" << spectrum[center.peak].getMZ() << ")" << std::endl;
}
//Find m/z boundaries of search space (linear search as this is local and we have the center already)
double mass_window = (double)(isotopes.size() + 1) / (double)charge;
if (debug_)
{
log_ << " - Mass window: " << mass_window << std::endl;
}
Size end = center.peak;
while (end < spectrum.size() &&
spectrum[end].getMZ() < spectrum[center.peak].getMZ() + mass_window)
{
++end;
}
--end;
//search begin
SignedSize begin = center.peak;
while (begin >= 0 &&
spectrum[begin].getMZ() > spectrum[center.peak].getMZ() - mass_window)
{
--begin;
}
++begin;
if (debug_)
{
log_ << " - Begin: " << begin << " (mz:" << spectrum[begin].getMZ() << ")" << std::endl;
}
if (debug_)
{
log_ << " - End: " << end << " (mz:" << spectrum[end].getMZ() << ")" << std::endl;
}
//fit isotope distribution to peaks
double max_score = 0.0;
for (Size start = begin; start <= end; ++start)
{
//find isotope peaks for the current start peak
Size peak_index = start;
IsotopePattern pattern(isotopes.size());
if (debug_)
{
log_ << " - Fitting at " << start << " (mz:" << spectrum[start].getMZ() << ")" << std::endl;
}
for (Size iso = 0; iso < isotopes.size(); ++iso)
{
double pos = spectrum[start].getMZ() + iso / (double)charge;
findIsotope_(pos, center.spectrum, pattern, iso, peak_index);
}
//check if the seed is contained, otherwise abort
bool seed_contained = false;
for (Size iso = 0; iso < pattern.peak.size(); ++iso)
{
if (pattern.peak[iso] == (Int)center.peak && pattern.spectrum[iso] == center.spectrum)
{
seed_contained = true;
break;
}
}
if (!seed_contained)
{
if (debug_)
{
log_ << " - aborting: seed is not contained!" << std::endl;
}
continue;
}
double score = isotopeScore_(isotopes, pattern, false);
//check if the seed is still contained, otherwise abort
seed_contained = false;
for (Size iso = 0; iso < pattern.peak.size(); ++iso)
{
if (pattern.peak[iso] == (Int)center.peak &&
pattern.spectrum[iso] == center.spectrum)
{
seed_contained = true;
break;
}
}
if (!seed_contained)
{
if (debug_)
{
log_ << " - aborting: seed was removed during isotope fit!" << std::endl;
}
continue;
}
if (debug_)
{
log_ << " - final score: " << score << std::endl;
}
if (score > max_score)
{
max_score = score;
best_pattern = pattern;
}
}
if (debug_)
{
log_ << " - best score : " << max_score << std::endl;
}
best_pattern.theoretical_pattern = isotopes;
return max_score;
}
void FeatureFinderAlgorithmPicked::extendMassTraces_(const IsotopePattern& pattern, MassTraces& traces, Size meta_index_overall) const
{
//find index of the trace with the maximum intensity
double max_int = 0.0;
Size max_trace_index = 0;
for (Size p = 0; p < pattern.peak.size(); ++p)
{
if (pattern.peak[p] < 0)
{
continue; //skip missing and removed traces
}
if (map_[pattern.spectrum[p]][pattern.peak[p]].getIntensity() > max_int)
{
max_int = map_[pattern.spectrum[p]][pattern.peak[p]].getIntensity();
max_trace_index = p;
}
}
//extend the maximum intensity trace to determine the boundaries in RT dimension
Size start_index = pattern.spectrum[max_trace_index];
const PeakType* start_peak = &(map_[pattern.spectrum[max_trace_index]][pattern.peak[max_trace_index]]);
double start_mz = start_peak->getMZ();
double start_rt = map_[start_index].getRT();
if (debug_)
{
log_ << " - Trace " << max_trace_index << " (maximum intensity)" << std::endl;
}
if (debug_)
{
log_ << " - extending from: " << map_[start_index].getRT() << " / " << start_mz << " (int: " << start_peak->getIntensity() << ")" << std::endl;
}
//initialize the trace and extend
MassTrace max_trace;
max_trace.peaks.emplace_back(start_rt, start_peak);
extendMassTrace_(max_trace, start_index, start_mz, false, meta_index_overall);
extendMassTrace_(max_trace, start_index, start_mz, true, meta_index_overall);
double rt_max = max_trace.peaks.back().first;
double rt_min = max_trace.peaks.begin()->first;
if (debug_)
{
log_ << " - rt bounds: " << rt_min << "-" << rt_max << std::endl;
}
//Abort if too few peak were found
if (!max_trace.isValid() || max_trace.peaks.size() < 2 * min_spectra_ - max_missing_trace_peaks_)
{
if (debug_)
{
log_ << " - could not extend trace with maximum intensity => abort" << std::endl;
}
return;
}
for (Size p = 0; p < pattern.peak.size(); ++p)
{
if (debug_)
{
log_ << " - Trace " << p << std::endl;
}
if (p == max_trace_index)
{
if (debug_)
{
log_ << " - previously extended maximum trace" << std::endl;
}
traces.push_back(std::move(max_trace));
traces.back().theoretical_int = pattern.theoretical_pattern.intensity[p];
traces.max_trace = traces.size() - 1;
continue;
}
Seed starting_peak;
starting_peak.spectrum = pattern.spectrum[p];
starting_peak.peak = pattern.peak[p];
if (pattern.peak[p] == -2)
{
if (debug_)
{
log_ << " - removed during isotope fit" << std::endl;
}
continue;
}
else if (pattern.peak[p] == -1)
{
if (debug_)
{
log_ << " - missing" << std::endl;
}
continue;
}
starting_peak.intensity = map_[starting_peak.spectrum][starting_peak.peak].getIntensity();
if (debug_) log_ << " - trace seed: " << map_[starting_peak.spectrum].getRT() << " / " << map_[starting_peak.spectrum][starting_peak.peak].getMZ() << " (int: " << map_[starting_peak.spectrum][starting_peak.peak].getIntensity() << ")" << std::endl;
//search for nearby maximum of the mass trace as the extension assumes that it starts at the maximum
Size begin = std::max((Size)0, starting_peak.spectrum - min_spectra_);
Size end = std::min(starting_peak.spectrum + min_spectra_, (Size)map_.size());
double mz = map_[starting_peak.spectrum][starting_peak.peak].getMZ();
double inte = map_[starting_peak.spectrum][starting_peak.peak].getIntensity();
for (Size spectrum_index = begin; spectrum_index < end; ++spectrum_index)
{
//find better seeds (no-empty scan/low mz diff/higher intensity)
SignedSize peak_index = -1;
if (!map_[spectrum_index].empty())
{
peak_index = map_[spectrum_index].findNearest(map_[starting_peak.spectrum][starting_peak.peak].getMZ());
}
if (peak_index < 0 ||
map_[spectrum_index][peak_index].getIntensity() <= inte ||
std::fabs(mz - map_[spectrum_index][peak_index].getMZ()) >= pattern_tolerance_
)
{
continue;
}
starting_peak.spectrum = spectrum_index;
starting_peak.peak = peak_index;
inte = map_[spectrum_index][peak_index].getIntensity();
}
if (debug_)
{
log_ << " - extending from: " << map_[starting_peak.spectrum].getRT() << " / " << map_[starting_peak.spectrum][starting_peak.peak].getMZ() << " (int: " << map_[starting_peak.spectrum][starting_peak.peak].getIntensity() << ")" << std::endl;
}
//------------------------------------------------------------------
//Extend seed to a mass trace
MassTrace trace;
const PeakType* seed = &(map_[starting_peak.spectrum][starting_peak.peak]);
//initialize trace with seed data and extend
trace.peaks.emplace_back(map_[starting_peak.spectrum].getRT(), seed);
extendMassTrace_(trace, starting_peak.spectrum, seed->getMZ(), false, meta_index_overall, rt_min, rt_max);
extendMassTrace_(trace, starting_peak.spectrum, seed->getMZ(), true, meta_index_overall, rt_min, rt_max);
//check if enough peaks were found
if (!trace.isValid())
{
if (debug_)
{
log_ << " - could not extend trace " << std::endl;
}
//Missing traces in the middle of a pattern are not acceptable => fix this
if (p < traces.max_trace)
{
traces.clear(); //remove earlier traces
continue;
}
else if (p > traces.max_trace)
{
break; //no more traces are possible
}
}
traces.push_back(trace);
traces.back().theoretical_int = pattern.theoretical_pattern.intensity[p];
}
}
void FeatureFinderAlgorithmPicked::extendMassTrace_(MassTrace& trace, SignedSize spectrum_index, double mz, bool increase_rt, Size meta_index_overall, double min_rt, double max_rt) const
{
//Reverse peaks if we run the method for the second time (to keep them in chronological order)
if (increase_rt)
{
++spectrum_index;
std::reverse(trace.peaks.begin(), trace.peaks.end());
}
else
{
--spectrum_index;
}
//check if boundaries are set
bool boundaries = false;
if (max_rt != min_rt)
{
boundaries = true;
}
//Relax slope threshold if there is a hard boundary for the extension
double current_slope_bound = (1.0 + (double)boundaries) * slope_bound_;
Size delta_count = min_spectra_;
std::vector<double> deltas(delta_count - 1, 0);
double last_observed_intensity = trace.peaks.back().second->getIntensity();
UInt missing_peaks = 0;
Size peaks_before_extension = trace.peaks.size();
String abort_reason = "";
while ((!increase_rt && spectrum_index >= 0) || (increase_rt && spectrum_index < (SignedSize)map_.size()))
{
if (boundaries &&
((!increase_rt && map_[spectrum_index].getRT() < min_rt) ||
(increase_rt && map_[spectrum_index].getRT() > max_rt))
)
{
abort_reason = "Hit upper/lower boundary";
break;
}
SignedSize peak_index = -1;
if (!map_[spectrum_index].empty())
{
peak_index = map_[spectrum_index].findNearest(mz);
}
// check if the peak is "missing"
if (
peak_index < 0 // no peak found
|| map_[spectrum_index].getFloatDataArrays()[meta_index_overall][peak_index] < 0.01 // overall score is to low
|| positionScore_(mz, map_[spectrum_index][peak_index].getMZ(), trace_tolerance_) == 0.0 // deviation of mz is too big
)
{
++missing_peaks;
if (missing_peaks > max_missing_trace_peaks_)
{
abort_reason = "too many peaks missing";
break;
}
}
else
{
missing_peaks = 0;
//add found peak to trace
trace.peaks.emplace_back(map_[spectrum_index].getRT(), &(map_[spectrum_index][peak_index]));
//update deltas and intensities
deltas.push_back((map_[spectrum_index][peak_index].getIntensity() - last_observed_intensity) / last_observed_intensity);
last_observed_intensity = map_[spectrum_index][peak_index].getIntensity();
//Abort if the average delta is too big (as intensity increases then)
double average_delta = std::accumulate(deltas.end() - delta_count, deltas.end(), 0.0) / (double)delta_count;
if (average_delta > current_slope_bound)
{
abort_reason = String("Average delta above threshold: ") + average_delta + "/" + current_slope_bound;
//remove last peaks as we extended too far
Size remove = std::min((Size)(trace.peaks.size() - peaks_before_extension), delta_count - 1);
trace.peaks.erase(trace.peaks.end() - remove, trace.peaks.end());
break;
}
}
//increase/decrease scan index
if (increase_rt)
{
++spectrum_index;
}
else
{
--spectrum_index;
}
}
if (debug_)
{
log_ << " - Added " << (trace.peaks.size() - peaks_before_extension) << " peaks (abort: " << abort_reason << ")" << std::endl;
}
}
Size FeatureFinderAlgorithmPicked::nearest_(double pos, const MSSpectrum& spec, Size start) const
{
Size index = start;
double distance = std::fabs(pos - spec[index].getMZ());
++index;
while (index < spec.size())
{
double new_distance = std::fabs(pos - spec[index].getMZ());
if (new_distance < distance)
{
distance = new_distance;
++index;
}
else
{
break;
}
}
return --index;
}
void FeatureFinderAlgorithmPicked::findIsotope_(double pos, Size spectrum_index, IsotopePattern& pattern, Size pattern_index, Size& peak_index) const
{
if (debug_)
{
log_ << " - Isotope " << pattern_index << ": ";
}
double intensity = 0.0;
double pos_score = 0.0;
UInt matches = 0;
//search in the center spectrum
const SpectrumType& spectrum = map_[spectrum_index];
peak_index = nearest_(pos, spectrum, peak_index);
double this_mz_score = positionScore_(pos, spectrum[peak_index].getMZ(), pattern_tolerance_);
pattern.theoretical_mz[pattern_index] = pos;
if (this_mz_score != 0.0)
{
if (debug_)
{
log_ << String::number(spectrum[peak_index].getIntensity(), 1) << " ";
}
pattern.peak[pattern_index] = peak_index;
pattern.spectrum[pattern_index] = spectrum_index;
intensity += spectrum[peak_index].getIntensity();
pos_score += this_mz_score;
++matches;
}
//previous spectrum
if (spectrum_index != 0 && !map_[spectrum_index - 1].empty())
{
const SpectrumType& spectrum_before = map_[spectrum_index - 1];
Size index_before = spectrum_before.findNearest(pos);
double mz_score = positionScore_(pos, spectrum_before[index_before].getMZ(), pattern_tolerance_);
if (mz_score != 0.0)
{
if (debug_) log_ << String::number(spectrum_before[index_before].getIntensity(), 1) << "b ";
intensity += spectrum_before[index_before].getIntensity();
pos_score += mz_score;
++matches;
if (pattern.peak[pattern_index] == -1)
{
pattern.peak[pattern_index] = index_before;
pattern.spectrum[pattern_index] = spectrum_index - 1;
}
}
}
//next spectrum
if (spectrum_index != map_.size() - 1 && !map_[spectrum_index + 1].empty())
{
const SpectrumType& spectrum_after = map_[spectrum_index + 1];
Size index_after = spectrum_after.findNearest(pos);
double mz_score = positionScore_(pos, spectrum_after[index_after].getMZ(), pattern_tolerance_);
if (mz_score != 0.0)
{
if (debug_) log_ << String::number(spectrum_after[index_after].getIntensity(), 1) << "a ";
intensity += spectrum_after[index_after].getIntensity();
pos_score += mz_score;
++matches;
if (pattern.peak[pattern_index] == -1)
{
pattern.peak[pattern_index] = index_after;
pattern.spectrum[pattern_index] = spectrum_index + 1;
}
}
}
//no isotope found
if (matches == 0)
{
if (debug_)
{
log_ << " missing" << std::endl;
}
pattern.peak[pattern_index] = -1;
pattern.mz_score[pattern_index] = 0.0;
pattern.intensity[pattern_index] = 0.0;
}
else
{
if (debug_)
{
log_ << "=> " << intensity / matches << std::endl;
}
pattern.mz_score[pattern_index] = pos_score / matches;
pattern.intensity[pattern_index] = intensity / matches;
}
}
double FeatureFinderAlgorithmPicked::positionScore_(double pos1, double pos2, double allowed_deviation) const
{
double diff = fabs(pos1 - pos2);
if (diff <= 0.5 * allowed_deviation)
{
return 0.1 * (0.5 * allowed_deviation - diff) / (0.5 * allowed_deviation) + 0.9;
}
else if (diff <= allowed_deviation)
{
return 0.9 * (allowed_deviation - diff) / (0.5 * allowed_deviation);
}
return 0.0;
}
/// Calculates a score between 0 and 1 for the correlation between theoretical and found isotope pattern
double FeatureFinderAlgorithmPicked::isotopeScore_(const TheoreticalIsotopePattern& isotopes, IsotopePattern& pattern, bool consider_mz_distances) const
{
if (debug_) log_ << " - fitting " << pattern.intensity.size() << " peaks" << std::endl;
//Abort if a core peak is missing
for (Size iso = 0 + isotopes.optional_begin; iso < pattern.peak.size() - isotopes.optional_end; ++iso)
{
if (pattern.peak[iso] == -1)
{
if (debug_)
{
log_ << " - aborting: core peak is missing" << std::endl;
}
return 0.0;
}
}
//Find best isotope fit
// - try to leave out optional isotope peaks to improve the fit
// - do not allow gaps inside the pattern
double best_int_score = 0.01; //Not 0 as this would result in problems when checking for the percental improvement
Size best_begin = 0;
for (Size i = isotopes.optional_begin; i > 0; --i)
{
if (pattern.peak[i - 1] == -1)
{
best_begin = i;
break;
}
}
Size best_end = 0;
for (Size i = isotopes.optional_end; i > 0; --i)
{
if (pattern.peak[pattern.peak.size() - i] == -1)
{
best_end = i;
break;
}
}
if (debug_)
{
log_ << " - best_begin/end: " << best_begin << "/" << best_end << std::endl;
}
for (Size b = best_begin; b <= isotopes.optional_begin; ++b)
{
for (Size e = best_end; e <= isotopes.optional_end; ++e)
{
//Make sure we have more than 2 peaks (unless in the first loop iteration, there we allow two points)
if (isotopes.size() - b - e > 2 || (b == best_begin &&
e == best_end &&
isotopes.size() - b - e > 1))
{
double int_score = Math::pearsonCorrelationCoefficient(isotopes.intensity.begin() + b, isotopes.intensity.end() - e, pattern.intensity.begin() + b, pattern.intensity.end() - e);
if (std::isnan(int_score))
{
int_score = 0.0;
}
if (isotopes.size() - b - e == 2 && int_score > min_isotope_fit_)
{
int_score = min_isotope_fit_; //special case for the first loop iteration (otherwise the score is 1)
}
if (debug_)
{
log_ << " - fit (" << b << "/" << e << "): " << int_score;
}
if (int_score / best_int_score >= 1.0 + optional_fit_improvement_)
{
if (debug_)
{
log_ << " - new best fit ";
}
best_int_score = int_score;
best_begin = b;
best_end = e;
}
if (debug_)
{
log_ << std::endl;
}
}
}
}
//if the best fit is empty, abort
if (pattern.mz_score.size() - best_begin - best_end == 0)
{
return 0.0;
}
//remove left out peaks from the beginning
for (Size i = 0; i < best_begin; ++i)
{
pattern.peak[i] = -2;
pattern.intensity[i] = 0.0;
pattern.mz_score[i] = 0.0;
}
//remove left out peaks from the end
for (Size i = 0; i < best_end; ++i)
{
pattern.peak[isotopes.size() - 1 - i] = -2;
pattern.intensity[isotopes.size() - 1 - i] = 0.0;
pattern.mz_score[isotopes.size() - 1 - i] = 0.0;
}
//calculate m/z score (if required)
if (consider_mz_distances)
{
best_int_score *= std::accumulate(pattern.mz_score.begin() + best_begin, pattern.mz_score.end() - best_end, 0.0) / (pattern.mz_score.size() - best_begin - best_end);
}
//return final score
OPENMS_POSTCONDITION(best_int_score >= 0.0, (String("Internal error: Isotope score (") + best_int_score + ") should be >=0.0").c_str())
OPENMS_POSTCONDITION(best_int_score <= 1.0, (String("Internal error: Isotope score (") + best_int_score + ") should be <=1.0").c_str())
return best_int_score;
}
double FeatureFinderAlgorithmPicked::intensityScore_(Size spectrum, Size peak) const
{
// calculate (half) bin numbers
double intensity = map_[spectrum][peak].getIntensity();
double rt = map_[spectrum].getRT();
double mz = map_[spectrum][peak].getMZ();
double rt_min = map_.getMinRT();
double mz_min = map_.getMinMZ();
UInt rt_bin = std::min(2 * intensity_bins_ - 1, (UInt) std::floor((rt - rt_min) / intensity_rt_step_ * 2.0));
UInt mz_bin = std::min(2 * intensity_bins_ - 1, (UInt) std::floor((mz - mz_min) / intensity_mz_step_ * 2.0));
// determine mz bins
UInt ml, mh;
if (mz_bin == 0 || mz_bin == 2 * intensity_bins_ - 1)
{
ml = mz_bin / 2;
mh = mz_bin / 2;
}
else if (Math::isOdd(mz_bin))
{
ml = mz_bin / 2;
mh = mz_bin / 2 + 1;
}
else
{
ml = mz_bin / 2 - 1;
mh = mz_bin / 2;
}
// determine rt bins
UInt rl, rh;
if (rt_bin == 0 || rt_bin == 2 * intensity_bins_ - 1)
{
rl = rt_bin / 2;
rh = rt_bin / 2;
}
else if (Math::isOdd(rt_bin))
{
rl = rt_bin / 2;
rh = rt_bin / 2 + 1;
}
else
{
rl = rt_bin / 2 - 1;
rh = rt_bin / 2;
}
// calculate distances to surrounding bin centers (normalized to [0,1])
double drl = std::fabs(rt_min + (0.5 + rl) * intensity_rt_step_ - rt) / intensity_rt_step_;
double drh = std::fabs(rt_min + (0.5 + rh) * intensity_rt_step_ - rt) / intensity_rt_step_;
double dml = std::fabs(mz_min + (0.5 + ml) * intensity_mz_step_ - mz) / intensity_mz_step_;
double dmh = std::fabs(mz_min + (0.5 + mh) * intensity_mz_step_ - mz) / intensity_mz_step_;
// Calculate weights for the intensity scores based on the distances to the
// bin center(the nearer to better)
double d1 = std::sqrt(std::pow(1.0 - drl, 2) + std::pow(1.0 - dml, 2));
double d2 = std::sqrt(std::pow(1.0 - drh, 2) + std::pow(1.0 - dml, 2));
double d3 = std::sqrt(std::pow(1.0 - drl, 2) + std::pow(1.0 - dmh, 2));
double d4 = std::sqrt(std::pow(1.0 - drh, 2) + std::pow(1.0 - dmh, 2));
double d_sum = d1 + d2 + d3 + d4;
// Final score .. intensityScore in the surrounding bins, weighted by the distance of the
// bin center to the peak
double final = intensityScore_(rl, ml, intensity) * (d1 / d_sum)
+ intensityScore_(rh, ml, intensity) * (d2 / d_sum)
+ intensityScore_(rl, mh, intensity) * (d3 / d_sum)
+ intensityScore_(rh, mh, intensity) * (d4 / d_sum);
OPENMS_POSTCONDITION(final >= 0.0, (String("Internal error: Intensity score (") + final + ") should be >=0.0").c_str())
OPENMS_POSTCONDITION(final <= 1.0001, (String("Internal error: Intensity score (") + final + ") should be <=1.0").c_str())
return final;
}
std::unique_ptr<TraceFitter> FeatureFinderAlgorithmPicked::chooseTraceFitter_(double& tau)
{
// choose fitter
if (param_.getValue("feature:rt_shape") == "asymmetric")
{
OPENMS_LOG_DEBUG << "use asymmetric rt peak shape" << std::endl;
tau = -1.0;
return std::make_unique<EGHTraceFitter>();
}
else // if (param_.getValue("feature:rt_shape") == "symmetric")
{
OPENMS_LOG_DEBUG << "use symmetric rt peak shape" << std::endl;
return std::make_unique<GaussTraceFitter>();
}
}
double FeatureFinderAlgorithmPicked::intensityScore_(Size rt_bin, Size mz_bin, double intensity) const
{
// interpolate score value according to quantiles(20)
const std::vector<double>& quantiles20 = intensity_thresholds_[rt_bin][mz_bin];
// get iterator pointing to quantile that is >= intensity
std::vector<double>::const_iterator it = std::lower_bound(quantiles20.begin(), quantiles20.end(), intensity);
// bigger than the biggest value => return 1.0
if (it == quantiles20.end())
{
return 1.0;
}
// interpolate inside the bin
double bin_score = 0.0;
if (it == quantiles20.begin())
{
bin_score = 0.05 * intensity / *it;
}
else
{
// (intensity - vigintile_low) / (vigintile_high - vigintile_low)
bin_score = 0.05 * (intensity - *(it - 1)) / (*it - *(it - 1));
}
double final = bin_score +
0.05 * ((it - quantiles20.begin()) - 1.0); // determine position of lower bound in the vector
//fix numerical problems
if (final < 0.0)
{
final = 0.0;
}
if (final > 1.0)
{
final = 1.0;
}
// final = 1/20 * [ index(vigintile_low) + (intensity-vigintile_low) / (vigintile_high - vigintile_low) ]
return final;
}
void FeatureFinderAlgorithmPicked::cropFeature_(const std::shared_ptr<TraceFitter>& fitter,
const MassTraces& traces,
MassTraces& new_traces)
{
double low_bound = fitter->getLowerRTBound();
double high_bound = fitter->getUpperRTBound();
if (debug_)
{
log_ << " => RT bounds: " << low_bound << " - " << high_bound << std::endl;
}
std::vector<double> v_theo, v_real;
for (Size t = 0; t < traces.size(); ++t)
{
const MassTrace& trace = traces[t];
if (debug_)
{
log_ << " - Trace " << t << ": (" << trace.theoretical_int << ")" << std::endl;
}
MassTrace new_trace;
//compute average relative deviation and correlation
double deviation = 0.0;
v_theo.clear();
v_real.clear();
for (Size k = 0; k < trace.peaks.size(); ++k)
{
//consider peaks when inside RT bounds only
if (trace.peaks[k].first >= low_bound && trace.peaks[k].first <= high_bound)
{
new_trace.peaks.push_back(trace.peaks[k]);
double theo = traces.baseline + fitter->computeTheoretical(trace, k);
v_theo.push_back(theo);
double real = trace.peaks[k].second->getIntensity();
v_real.push_back(real);
deviation += std::fabs(real - theo) / theo;
}
}
double fit_score = 0.0;
double correlation = 0.0;
double final_score = 0.0;
if (!new_trace.peaks.empty())
{
fit_score = deviation / new_trace.peaks.size();
correlation = std::max(0.0, Math::pearsonCorrelationCoefficient(v_theo.begin(), v_theo.end(), v_real.begin(), v_real.end()));
final_score = std::sqrt(correlation * std::max(0.0, 1.0 - fit_score));
}
if (debug_)
{
log_ << " - peaks: " << new_trace.peaks.size() << " / " << trace.peaks.size() << " - relative deviation: " << fit_score << " - correlation: " << correlation << " - final score: " << correlation << std::endl;
}
//remove badly fitting traces
if (!new_trace.isValid() || final_score < min_trace_score_)
{
if (t < traces.max_trace)
{
new_traces = MassTraces();
if (debug_)
{
log_ << " - removed this and previous traces due to bad fit" << std::endl;
}
new_traces.clear(); //remove earlier traces
continue;
}
else if (t == traces.max_trace)
{
new_traces = MassTraces();
if (debug_)
{
log_ << " - aborting (max trace was removed)" << std::endl;
}
break;
}
else if (t > traces.max_trace)
{
if (debug_)
{
log_ << " - removed due to bad fit => omitting the rest" << std::endl;
}
break; //no more traces are possible
}
}
//add new trace
else
{
new_trace.theoretical_int = trace.theoretical_int;
new_traces.push_back(new_trace);
if (t == traces.max_trace)
{
new_traces.max_trace = new_traces.size() - 1;
}
}
}
new_traces.baseline = traces.baseline;
}
bool FeatureFinderAlgorithmPicked::checkFeatureQuality_(const std::shared_ptr<TraceFitter>& fitter,
MassTraces& feature_traces,
const double& seed_mz, const double& min_feature_score,
String& error_msg, double& fit_score, double& correlation, double& final_score)
{
//check if the sigma fit was ok (if it is larger than 'max_rt_span')
// 5.0 * sigma > max_rt_span_ * region_rt_span
if (fitter->checkMaximalRTSpan(max_rt_span_))
{
error_msg = "Invalid fit: Fitted model is bigger than 'max_rt_span'";
return false;
}
//check if the feature is valid
if (!feature_traces.isValid(seed_mz, trace_tolerance_))
{
error_msg = "Invalid feature after fit - too few traces or peaks left";
return false;
}
//check if x0 is inside feature bounds
{
std::pair<double, double> rt_bounds = feature_traces.getRTBounds();
if (fitter->getCenter() < rt_bounds.first || fitter->getCenter() > rt_bounds.second)
{
error_msg = "Invalid fit: Center outside of feature bounds";
return false;
}
}
//check if the remaining traces fill out at least 'min_rt_span' of the RT span
{
std::pair<double, double> rt_bounds = feature_traces.getRTBounds();
if (fitter->checkMinimalRTSpan(rt_bounds, min_rt_span_))
{
error_msg = "Invalid fit: Less than 'min_rt_span' left after fit";
return false;
}
}
//check if feature quality is high enough (average relative deviation and correlation of the whole feature)
{
std::vector<double> v_theo, v_real;
double deviation = 0.0;
for (Size t = 0; t < feature_traces.size(); ++t)
{
MassTrace& trace = feature_traces[t];
for (Size k = 0; k < trace.peaks.size(); ++k)
{
// was double theo = new_traces.baseline + trace.theoretical_int * height * exp(-0.5 * pow(trace.peaks[k].first - x0, 2) / pow(sigma, 2) );
double theo = feature_traces.baseline + fitter->computeTheoretical(trace, k);
v_theo.push_back(theo);
double real = trace.peaks[k].second->getIntensity();
v_real.push_back(real);
deviation += std::fabs(real - theo) / theo;
}
}
fit_score = std::max(0.0, 1.0 - (deviation / feature_traces.getPeakCount()));
correlation = std::max(0.0, Math::pearsonCorrelationCoefficient(v_theo.begin(), v_theo.end(), v_real.begin(), v_real.end()));
final_score = std::sqrt(correlation * fit_score);
//quality output
if (debug_)
{
log_ << "Quality estimation:" << std::endl;
log_ << " - relative deviation: " << fit_score << std::endl;
log_ << " - correlation: " << correlation << std::endl;
log_ << " => final score: " << final_score << std::endl;
}
if (final_score < min_feature_score)
{
error_msg = "Feature quality too low after fit";
return false;
}
}
return true;
}
void FeatureFinderAlgorithmPicked::writeFeatureDebugInfo_(const std::shared_ptr<TraceFitter>& fitter,
const MassTraces& traces,
const MassTraces& new_traces,
bool feature_ok, const String& error_msg, const double final_score, const Int plot_nr, const PeakType& peak,
const String& path)
{
double pseudo_rt_shift = param_.getValue("debug:pseudo_rt_shift");
String script;
{
TextFile tf;
//gnuplot script
script = String("plot \"") + path + plot_nr + ".dta\" title 'before fit (RT: " + String::number(fitter->getCenter(), 2) + " m/z: " + String::number(peak.getMZ(), 4) + ")' with points 1";
//feature before fit
for (Size k = 0; k < traces.size(); ++k)
{
for (Size j = 0; j < traces[k].peaks.size(); ++j)
{
tf.addLine(String(pseudo_rt_shift * k + traces[k].peaks[j].first) + "\t" + traces[k].peaks[j].second->getIntensity());
}
}
tf.store(path + plot_nr + ".dta");
}
{
//fitted feature
if (new_traces.getPeakCount() != 0)
{
TextFile tf_new_trace;
for (Size k = 0; k < new_traces.size(); ++k)
{
for (Size j = 0; j < new_traces[k].peaks.size(); ++j)
{
tf_new_trace.addLine(String(pseudo_rt_shift * k + new_traces[k].peaks[j].first) + "\t" + new_traces[k].peaks[j].second->getIntensity());
}
}
tf_new_trace.store(path + plot_nr + "_cropped.dta");
script = script + ", \"" + path + plot_nr + "_cropped.dta\" title 'feature ";
if (!feature_ok)
{
script = script + " - " + error_msg;
}
else
{
script = script + (features_->size() + 1) + " (score: " + String::number(final_score, 3) + ")";
}
script = script + "' with points 3";
}
}
{
//fitted functions
TextFile tf_fitted_func;
for (Size k = 0; k < traces.size(); ++k)
{
char fun = 'f';
fun += (char)k;
tf_fitted_func.addLine(fitter->getGnuplotFormula(traces[k], fun, traces.baseline, pseudo_rt_shift * k));
//tf.push_back(String(fun)+"(x)= " + traces.baseline + " + " + fitter->getGnuplotFormula(traces[k], pseudo_rt_shift * k));
script = script + ", " + fun + "(x) title 'Trace " + k + " (m/z: " + String::number(traces[k].getAvgMZ(), 4) + ")'";
}
//output
tf_fitted_func.addLine("set xlabel \"pseudo RT (mass traces side-by-side)\"");
tf_fitted_func.addLine("set ylabel \"intensity\"");
tf_fitted_func.addLine("set samples 1000");
tf_fitted_func.addLine(script);
tf_fitted_func.addLine("pause -1");
tf_fitted_func.store(path + plot_nr + ".plot");
}
}
}
|
fb4c1682c1a507df918af582dbe4b9e5b7627651
|
7e59e2bdd5cdceb8a5fca7dae38b6348becd3547
|
/src/component/yijinjing/journal/Timer.cpp
|
f7438d534581d70ce63a3a382a2c4ebffb73f44e
|
[
"MIT"
] |
permissive
|
therealtylerli/ft
|
21176bea548d23d0dff7b960786fe41b03265f16
|
d19ab11be108aa536f92c1e92782938857e297c4
|
refs/heads/master
| 2023-09-05T04:23:48.153742
| 2021-11-17T06:25:55
| 2021-11-17T06:25:55
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,228
|
cpp
|
Timer.cpp
|
/*****************************************************************************
* Copyright [2017] [taurus.ai]
*
* 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.
*****************************************************************************/
/**
* Timer for kungfu system.
* @Author cjiang (changhao.jiang@taurus.ai)
* @since March, 2017
* Provide basic nano time and time transformation
*/
#include "ft/component/yijinjing/journal/Timer.h"
#include <array>
#include <chrono>
#include "ft/component/yijinjing/journal/PageProvider.h"
USING_YJJ_NAMESPACE
std::shared_ptr<NanoTimer> NanoTimer::m_ptr = std::shared_ptr<NanoTimer>(nullptr);
NanoTimer *NanoTimer::getInstance() {
if (m_ptr.get() == nullptr) {
m_ptr = std::shared_ptr<NanoTimer>(new NanoTimer());
}
return m_ptr.get();
}
inline std::chrono::steady_clock::time_point get_time_now() {
#if defined __linux__
timespec tp;
clock_gettime(CLOCK_MONOTONIC, &tp);
return std::chrono::steady_clock::time_point(std::chrono::steady_clock::duration(
std::chrono::seconds(tp.tv_sec) + std::chrono::nanoseconds(tp.tv_nsec)));
#else
return std::chrono::steady_clock::now();
#endif
}
inline int64_t get_local_diff() {
int unix_second_num = std::chrono::seconds(std::time(NULL)).count();
int tick_second_num =
std::chrono::duration_cast<std::chrono::seconds>(get_time_now().time_since_epoch()).count();
return (unix_second_num - tick_second_num) * NANOSECONDS_PER_SECOND;
}
NanoTimer::NanoTimer() { secDiff = get_local_diff(); }
int64_t NanoTimer::getNano() const {
int64_t _nano =
std::chrono::duration_cast<std::chrono::nanoseconds>(get_time_now().time_since_epoch())
.count();
return _nano + secDiff;
}
|
09cca1939a9c66a6570f7f9aa9827d104ce73404
|
840faa97d44492f7435ba042e2c1312de99f4ea3
|
/src/kudu/master/mini_master.cc
|
e8bb0571ff2aefdf7dfd7d08034848e939496c59
|
[
"OpenSSL",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-ssleay-windows",
"LicenseRef-scancode-google-patent-license-webrtc",
"LicenseRef-scancode-unknown-license-reference",
"dtoa",
"MIT",
"BSL-1.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown"
] |
permissive
|
apache/kudu
|
c05fad4ea1cf48a650e99b2fb6917f19a790bd3d
|
ecb51af801bd1bf40d0216b0697bf7e5765461d5
|
refs/heads/master
| 2023-08-31T23:18:23.205496
| 2023-08-28T21:54:50
| 2023-08-29T19:16:49
| 50,647,838
| 1,757
| 698
|
Apache-2.0
| 2023-08-17T13:36:43
| 2016-01-29T08:00:06
|
C++
|
UTF-8
|
C++
| false
| false
| 4,500
|
cc
|
mini_master.cc
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "kudu/master/mini_master.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <gflags/gflags_declare.h>
#include <glog/logging.h>
#include "kudu/fs/fs_manager.h"
#include "kudu/gutil/strings/substitute.h"
#include "kudu/master/master.h"
#include "kudu/master/master_options.h"
#include "kudu/server/rpc_server.h"
#include "kudu/server/webserver_options.h"
#include "kudu/util/cache.h"
#include "kudu/util/env.h"
#include "kudu/util/env_util.h"
#include "kudu/util/net/net_util.h"
#include "kudu/util/net/sockaddr.h"
#include "kudu/util/path_util.h"
#include "kudu/util/status.h"
using std::string;
using std::unique_ptr;
using std::vector;
using strings::Substitute;
DECLARE_bool(enable_minidumps);
DECLARE_bool(rpc_server_allow_ephemeral_ports);
namespace kudu {
namespace master {
MiniMaster::MiniMaster(string fs_root, HostPort rpc_bind_addr, int num_data_dirs)
: fs_root_(std::move(fs_root)),
rpc_bind_addr_(std::move(rpc_bind_addr)) {
// Disable minidump handler (we allow only one per process).
FLAGS_enable_minidumps = false;
HostPort web_bind_addr(rpc_bind_addr_.host(), /*port=*/ 0);
opts_.rpc_opts.rpc_bind_addresses = rpc_bind_addr_.ToString();
opts_.rpc_opts.rpc_reuseport = true;
opts_.webserver_opts.bind_interface = web_bind_addr.host();
opts_.webserver_opts.port = web_bind_addr.port();
opts_.set_block_cache_metrics_policy(Cache::ExistingMetricsPolicy::kKeep);
if (num_data_dirs == 1) {
opts_.fs_opts.wal_root = fs_root_;
opts_.fs_opts.data_roots = { fs_root_ };
} else {
vector<string> fs_data_dirs;
for (int dir = 0; dir < num_data_dirs; dir++) {
fs_data_dirs.emplace_back(JoinPathSegments(fs_root_, Substitute("data-$0", dir)));
}
opts_.fs_opts.wal_root = JoinPathSegments(fs_root_, "wal");
opts_.fs_opts.data_roots = fs_data_dirs;
}
}
MiniMaster::~MiniMaster() {
Shutdown();
}
void MiniMaster::SetMasterAddresses(vector<HostPort> master_addrs) {
CHECK(!master_);
opts_.SetMasterAddressesForTests(std::move(master_addrs));
}
Status MiniMaster::Start() {
CHECK(!master_);
if (!opts_.IsDistributed()) {
FLAGS_rpc_server_allow_ephemeral_ports = true;
}
// In case the wal dir and data dirs are subdirectories of the root directory,
// ensure the root directory exists.
RETURN_NOT_OK(env_util::CreateDirIfMissing(Env::Default(), fs_root_));
unique_ptr<Master> master(new Master(opts_));
RETURN_NOT_OK(master->Init());
RETURN_NOT_OK(master->StartAsync());
master_.swap(master);
// Wait for the catalog manager to be ready if we only have a single master.
if (!opts_.IsDistributed()) {
return master_->WaitForCatalogManagerInit();
}
return Status::OK();
}
Status MiniMaster::Restart() {
CHECK(!master_);
opts_.rpc_opts.rpc_bind_addresses = bound_rpc_.ToString();
opts_.webserver_opts.bind_interface = bound_http_.host();
opts_.webserver_opts.port = bound_http_.port();
Shutdown();
return Start();
}
void MiniMaster::Shutdown() {
if (master_) {
bound_rpc_ = bound_rpc_addr();
bound_http_ = bound_http_addr();
master_->Shutdown();
master_.reset();
}
}
Status MiniMaster::WaitForCatalogManagerInit() const {
return master_->WaitForCatalogManagerInit();
}
const Sockaddr MiniMaster::bound_rpc_addr() const {
return master_->first_rpc_address();
}
const Sockaddr MiniMaster::bound_http_addr() const {
return master_->first_http_address();
}
std::string MiniMaster::permanent_uuid() const {
return DCHECK_NOTNULL(master_->fs_manager())->uuid();
}
std::string MiniMaster::bound_rpc_addr_str() const {
return bound_rpc_addr().ToString();
}
} // namespace master
} // namespace kudu
|
5cc127939f5c4c8d27538c7ce4e64268a6dfc00e
|
073b36993a750623f001a366f4faf5854ea75fb1
|
/PWFusion_SHT3X.h
|
593c788d6893fcd041f8e9b1229e46d69bf7738e
|
[] |
no_license
|
PlayingWithFusion/PWFusion_SHT3X
|
7a85a685ce6ef583efa217e4d2317b42f5e11628
|
c66f3d4fff2853ad2914637966375d3aa6db2fc6
|
refs/heads/master
| 2021-01-22T22:21:10.801787
| 2017-03-20T04:19:36
| 2017-03-20T04:19:36
| 85,534,490
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,266
|
h
|
PWFusion_SHT3X.h
|
/***************************************************************************
* File Name: SEN-37002_SHT31D_HumTemp.ino
* Processor/Platform: Arduino Uno R3 (tested)
* Development Environment: Arduino 1.6.5
*
* Designed for use with with Playing With Fusion SHT31-DIS-B and SHT31-DIS-F
* Humidity and Temperature Sensor Breakouts: SEN-37002
*
* SEN-37002 (universal applications)
* ---> http://www.playingwithfusion.com/productview.php?pdid=81 B, no filter
* ---> F, with filter
* Note: This will aslo work with other SHT3X sensors (SHT35, for instance)
*
* Copyright © 2017 Playing With Fusion, Inc.
* SOFTWARE LICENSE AGREEMENT: This code is released under the MIT License.
*
* 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.
* **************************************************************************
* REVISION HISTORY:
* Author Date Comments
* J. Steinlage 2017Feb Original version
*
* Playing With Fusion, Inc. invests time and resources developing open-source
* code. Please support Playing With Fusion and continued open-source
* development by buying products from Playing With Fusion!
*
* **************************************************************************/
#ifndef PWF_SHT3X_H
#define PWF_SHT3X_H
#include "Arduino.h"
#include "Wire.h"
#include "PWFusion_SHT3X_STRUCT.h"
// REGISTER DEFINITIONS
#define SING_SHOT_HIGHREP 0x2400 // single shot measurement, high repeatability, no clock stretching
#define SING_SHOT_MEDREP 0x240B // single shot measurement, medium repeatability, no clock stretching
#define SING_SHOT_LOWHREP 0x2416 // single shot measurement, low repeatability, no clock stretching
#define SHT3X_RESET 0x30A2 // soft reset the SHT3X device
#define SHT3X_HEATER_EN 0x306D // command to enable heater
#define SHT3X_HEATER_DIS 0x3066 // command to disable heater
class PWFusion_SHT3X
{
public:
PWFusion_SHT3X();
void begin(uint8_t address);
void sht3x_heat_en(uint8_t en_flag);
void write_cmd(uint16_t cmd);
boolean SHT3X_update(var_SHT3X *hum_sns);
private:
void sht3x_reset(void);
uint8_t crc8(uint8_t *datptr, uint8_t len);
uint8_t _dev_add;
};
#endif // PWF_SHT3X_H
|
0898cca772a983651218d626665bc51db8d83da3
|
d4fae6eafcc99a335267c04e61293e42e3f28097
|
/OpenEDA.TPI/includes/Testpoint.hpp
|
11ad6ec6e0330a3be1ba6368ede85a35a3e70d7f
|
[] |
no_license
|
icexxx/OpenEDA
|
dc944b17a32ea3ce477b2388ab18dd5a1ce71028
|
9499943bf720d07de35ec7e4d662f3bd11af017f
|
refs/heads/master
| 2022-02-04T12:44:56.483907
| 2019-08-06T15:03:21
| 2019-08-06T15:03:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,779
|
hpp
|
Testpoint.hpp
|
/**
* @file Testpoint.h
* @author Spencer Millican (millican@auburn.edu)
* @version 0.1
* @date 2019-02-05
*
* @copyright Copyright (c) 2019
*
*/
#ifndef Testpoint_h
#define Testpoint_h
#include "Circuit.h"
#include "FaultStructures.hpp"
#include "Value.h"
/*
* An object capible of modifying a circuit when activated.
*
* This class is pure virtual. Other methods must define the actions
* corresponding to activation.
*
* A testpoint is "valued" in the sense that it will return value of its
* location (presuming it is active).
*
* @parameter _primitive The data primitive of simulation.
* @parameter _nodeType When new needs are created, what kind of node should be created?
* @parameter _lineType When new lines are created, what kind of line should be created?
*/
template <class _primitive, class _nodeType, class _lineType>
class Testpoint : virtual public Valued<_primitive> {
public:
/*
* Create a testpoint on a given Line.
*
* The testpoint will not be activated (i.e., no circuit modification will be
* done.
*
* @param _location The location of the testpoint
* @param (optional) _value The "value" of this testpoint.
*/
Testpoint(_lineType* _location, Value<_primitive> _value = Value<_primitive>()) {
this->location_ = _location;
}
/*
* Two Testpoints are equal if they are on the same location.
*
* @param _other The other Testpoint being compared to.
* @return True if both are on the same location.
*/
virtual bool operator == (const Testpoint<_primitive, _nodeType, _lineType>& _other) const {
return (this->location_ == _other.location());
}
/*
* See the overloaded operator "==", as this is the logical opposite.
* @param _other The other Testpoint being compared to.
* @return True if the Testpoints are different.
*/
virtual bool operator != (const Testpoint<_primitive, _nodeType, _lineType>& _other) const {
return !(*this == _other);
}
/*
* Compaitor function (needed for sorted hashes of faults).
*
* The first "priotiry" of the sort is the pointer to the location.
*
* @param _other The other Testpoints being compared to.
*/
virtual bool operator < (const Testpoint<_primitive, _nodeType, _lineType>& _other) const {
return (this->location_ < _other.location());
}
/*
* Activate the Testpoint by modifying the circuit.
*
* Lines may be created by this function.
*
* @param (optional) _circuit The circuit which (may) be modified (extra
* nodes/pis/pos may be added/removed). If no circuit is given, then no
* circuit will be modified. This can be useful if adding/removing
* nodes to the circuit is not necessary.
* @return A set of new nodes created during activation.
*/
virtual std::unordered_set<_nodeType*> activate(Circuit* _circuit = nullptr) = 0;
/*
* Deactivate the Testpoint by modifying the circuit.
*
* Lines may be deleted by this function.
*
* @param (optional) _circuit The circuit which (may) be modified (extra
* nodes/pis/pos may be added/removed). If no circuit is given, then no
* circuit will be modified. This can be useful if adding/removing
* nodes to the circuit is not necessary.
* @return A set of node whichs should be (but was not) deleted.
*/
virtual std::unordered_set<_nodeType*> deactivate(Circuit* _circuit = nullptr) = 0;
/*
* The location of the TP.
*
* @return The location of the TP.
*/
_lineType* location() const {
return this->location_;
}
protected:
/*
* The location of the Testpoint.
*
* @return The location of the Testpoint.
*/
_lineType* location_;
};
#endif
|
f71bde778c35e0d7b4ab881ea98ec0980c9d9dc6
|
44b98554e6ea51babba2f20f68d05bf9d5635cd9
|
/app/ipcam/cameraserver/utils/Pdu.h
|
52e80c55a41b5093801901d677e3ae0ae19054bb
|
[] |
no_license
|
pengdu/bbam
|
8550688d1aa6dda680fbe953439e595efc1b7107
|
afc307dc04fffe89a111a0f1b5ef6376f52e194c
|
refs/heads/master
| 2015-08-10T03:58:11.792991
| 2013-10-24T06:23:54
| 2013-10-24T06:23:54
| 16,098,118
| 5
| 8
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,019
|
h
|
Pdu.h
|
#ifndef __GMPDU_H_
#define __GMPDU_H_
#include "GmDefines.h"
#include <string>
#define KBYTE_2_BYTE(n) ( ( n ) << 10 )
#define BYTE_2_KBYTE(n) ( ( ( n ) >> 10 ) + ( ( ( n ) & ( ( 1 << 10 ) - 1 ) ) ? 1 : 0 ) )
#define UINT_TO_BYTES(u, bytes) uint2bytes((u), (bytes))
#define BYTES_TO_UINT(bytes) bytes2uint((bytes))
#define MIN_VALUE_OF_SIGNED(type) ((type)(1 << ((sizeof(type) << 3) - 1)))
#define MAX_VALUE_OF_SIGNED(type) ((type)(~MIN_VALUE_OF_SIGNED(type)))
#define MIN_VALUE_OF_UNSIGNED(type) ((unsigned type)0)
#define MAX_VALUE_OF_UNSIGNED(type) ((unsigned type)(~0))
#define GM_PDU_BYTES_ALIGN 4
#define LENGTH_OF_BYTES_ALIGN(l, n) ((n) ? ((l) + (((l) % (n)) ? (n) - ((l) % (n)) : 0)) : (l))
static inline void uint2bytes(UINT u, LPBYTE bytes, UINT length = GM_PDU_BYTES_ALIGN)
{
for ( UINT i = 0; i < length; ++ i ) bytes[i] = ((u >> (i << 3)) & 0xff);
}
static inline UINT bytes2uint(const LPCBYTE bytes, UINT length = GM_PDU_BYTES_ALIGN)
{
UINT sum = 0;
for ( UINT i = 0; i < length; ++ i ) sum |= (bytes[i] << (i << 3));
return sum;
}
class CGmBuffer
{
private:
LPBYTE m_buffer;
DWORD m_bufferLength;
DWORD m_realBufferLength;
public:
CGmBuffer() : m_buffer(NULL), m_bufferLength(0), m_realBufferLength(0) {}
CGmBuffer(const LPCBYTE buffer, const DWORD bufferLength)
{
if ( NULL == buffer || 0 == bufferLength)
{
m_buffer = NULL;
m_bufferLength = 0;
m_realBufferLength = 0;
}
else
{
m_bufferLength = KBYTE_2_BYTE(BYTE_2_KBYTE(bufferLength));
m_buffer = new BYTE[m_bufferLength];
memcpy(m_buffer, buffer, bufferLength);
m_realBufferLength = bufferLength;
}
}
~CGmBuffer() { if (m_buffer) delete [] m_buffer; }
void Assign(const LPCBYTE buffer, const DWORD bufferLength)
{
if ( NULL == buffer || 0 == bufferLength )
{
m_realBufferLength = 0;
}
else
{
if ( bufferLength > m_bufferLength )
{
if ( m_buffer ) delete [] m_buffer;
m_bufferLength = KBYTE_2_BYTE(BYTE_2_KBYTE(bufferLength));
m_buffer = new BYTE[m_bufferLength];
}
memcpy(m_buffer, buffer, bufferLength);
m_realBufferLength = bufferLength;
}
}
operator LPCBYTE () const { return m_buffer; }
operator LPBYTE () const { return m_buffer; }
DWORD Length() const { return m_realBufferLength; }
};
class CGmPdu
{
private:
LPBYTE m_buffer;
DWORD m_bufferLength;
DWORD m_pushOffset;
DWORD m_popOffset;
public:
enum {
eNone = 0,
eNumeric,
eString,
eBuffer,
ePdu,
};
class DataUnit
{
private:
DWORD m_dataType;
DWORD m_dataLength;
BYTE m_dataBuffer[GM_PDU_BYTES_ALIGN];
LPCBYTE m_dataBufferPtr;
public:
DataUnit(const DWORD dataType, const DWORD dataLength, LPCBYTE dataBufferPtr)
: m_dataType(dataType), m_dataLength(dataLength), m_dataBufferPtr(dataBufferPtr) {}
#define DEFINE_CONSTRUCTOR_DataUnit(type) \
DataUnit(const type &data) : m_dataType(eNumeric), m_dataLength(GM_PDU_BYTES_ALIGN), m_dataBufferPtr(m_dataBuffer) \
{ UINT u = (UINT)data; UINT_TO_BYTES(u, m_dataBuffer); }
DEFINE_CONSTRUCTOR_DataUnit( signed char);
DEFINE_CONSTRUCTOR_DataUnit(unsigned char);
DEFINE_CONSTRUCTOR_DataUnit( signed short);
DEFINE_CONSTRUCTOR_DataUnit(unsigned short);
DEFINE_CONSTRUCTOR_DataUnit( signed int);
DEFINE_CONSTRUCTOR_DataUnit(unsigned int);
DEFINE_CONSTRUCTOR_DataUnit( signed long);
DEFINE_CONSTRUCTOR_DataUnit(unsigned long);
#undef DEFINE_CONSTRUCTOR_DataUnit
/*
if we do not add "const char* const" type support, then system will construct "std::string" in constructor
of "DataUnit", then release the "std::string" after finishing construction of "DataUnit". So when we use the
"DataUnit.m_dataBufferPtr", the "std::string.c_str()" is released, then program will crash.
bug found by Gao Ran, fixed by syhuang 2011.8.18
*/
DataUnit(const char* const &data) : m_dataType(eString), m_dataLength(strlen(data)), m_dataBufferPtr((LPCBYTE)data) {}
DataUnit(const std::string &data) : m_dataType(eString), m_dataLength(data.length()), m_dataBufferPtr((LPCBYTE)data.c_str()) {}
DataUnit(const CGmBuffer &data) : m_dataType(eBuffer), m_dataLength(data.Length()), m_dataBufferPtr((LPCBYTE)data) {}
DataUnit(const CGmPdu &data) : m_dataType(ePdu) , m_dataLength(data.Length()), m_dataBufferPtr((LPCBYTE)data) {}
~DataUnit() {};
#define DEFINE_CONVERTER_TO_SIGNED_NUMERIC(type) \
BOOL ConvertTo(type &data) const \
{ \
if ( m_dataType != eNumeric ) return FALSE; \
INT num = (INT)BYTES_TO_UINT(m_dataBufferPtr); \
if ( num < MIN_VALUE_OF_SIGNED(type) || num > MAX_VALUE_OF_SIGNED(type) ) return FALSE; \
data = (type)num; return TRUE; \
}
DEFINE_CONVERTER_TO_SIGNED_NUMERIC(char);
DEFINE_CONVERTER_TO_SIGNED_NUMERIC(short);
DEFINE_CONVERTER_TO_SIGNED_NUMERIC(int);
DEFINE_CONVERTER_TO_SIGNED_NUMERIC(long);
#undef DEFINE_CONVERTER_TO_SIGNED_NUMERIC
#define DEFINE_CONVERTER_TO_UNSIGNED_NUMERIC(type) \
BOOL ConvertTo(unsigned type &data) const \
{ \
if ( m_dataType != eNumeric ) return FALSE; \
UINT num = (UINT)BYTES_TO_UINT(m_dataBufferPtr); \
if ( num < MIN_VALUE_OF_UNSIGNED(type) || num > MAX_VALUE_OF_UNSIGNED(type) ) return FALSE; \
data = (unsigned type)num; return TRUE; \
}
DEFINE_CONVERTER_TO_UNSIGNED_NUMERIC(char);
DEFINE_CONVERTER_TO_UNSIGNED_NUMERIC(short);
DEFINE_CONVERTER_TO_UNSIGNED_NUMERIC(int);
DEFINE_CONVERTER_TO_UNSIGNED_NUMERIC(long);
#undef DEFINE_CONVERTER_TO_UNSIGNED_NUMERIC
BOOL ConvertTo(std::string &data) const
{
if ( m_dataType != eString ) return FALSE;
if ( 0 == m_dataLength || NULL == m_dataBufferPtr || '\0' == m_dataBufferPtr[0] ) data = "";
else data.assign((LPCSTR)m_dataBufferPtr, m_dataLength);
return TRUE;
}
BOOL ConvertTo(CGmPdu &data) const
{
if ( m_dataType != ePdu ) return FALSE;
data.Assign(m_dataBufferPtr, m_dataLength); return TRUE;
}
BOOL ConvertTo(CGmBuffer &data) const
{
if ( m_dataType != eBuffer && m_dataType != ePdu && m_dataType != eString ) return FALSE;
data.Assign(m_dataBufferPtr, m_dataLength); return TRUE;
}
BOOL ConvertTo(DataUnit &data) const { data = (*this); return TRUE; }
DWORD Length() const
{
DWORD length = LENGTH_OF_BYTES_ALIGN(m_dataLength, GM_PDU_BYTES_ALIGN);
return GM_PDU_BYTES_ALIGN + GM_PDU_BYTES_ALIGN + length;
}
DWORD GetDataType() const { return m_dataType; }
DWORD GetDataLength() const { return m_dataLength; }
LPCBYTE GetDataBufferPtr() const { return m_dataBufferPtr; }
};
CGmPdu() : m_buffer(NULL), m_bufferLength(0), m_pushOffset(0), m_popOffset(0) {}
CGmPdu(const LPBYTE buffer, DWORD bufferLength) : m_popOffset(0)
{
if ( NULL == buffer || 0 == bufferLength)
{
m_buffer = NULL;
m_bufferLength = 0;
m_pushOffset = 0;
}
else
{
m_bufferLength = KBYTE_2_BYTE(BYTE_2_KBYTE(bufferLength));
m_buffer = new BYTE[m_bufferLength];
memcpy(m_buffer, buffer, bufferLength);
m_pushOffset = bufferLength;
}
}
~CGmPdu() { if (m_buffer) delete [] m_buffer; }
void Assign(LPCBYTE buffer, const DWORD bufferLength)
{
if ( NULL == buffer || 0 == bufferLength )
{
m_pushOffset = 0;
}
else
{
if ( bufferLength > m_bufferLength )
{
if ( m_buffer ) delete [] m_buffer;
m_bufferLength = KBYTE_2_BYTE(BYTE_2_KBYTE(bufferLength));
m_buffer = new BYTE[m_bufferLength];
}
memcpy(m_buffer, buffer, bufferLength);
m_pushOffset = bufferLength;
}
m_popOffset = 0;
}
CGmPdu &Join(const CGmPdu &pdu)
{
if (m_pushOffset + pdu.m_pushOffset > m_bufferLength) { Resize(m_pushOffset + pdu.m_pushOffset); }
memcpy(m_buffer + m_pushOffset, pdu.m_buffer, pdu.m_pushOffset);
m_pushOffset += pdu.m_pushOffset;
return (*this);
}
template<typename T> CGmPdu& operator << (const T& data) { PushData(data); return *this; }
template<typename T> CGmPdu& operator >> (T& data) { PopData(data); return *this; }
operator LPCBYTE () const { return m_buffer; }
operator LPBYTE () const { return m_buffer; }
DWORD Length() const { return m_pushOffset; }
void PrepareToPopData() { m_popOffset = 0; }
BOOL IsPopEnd() const { return ( m_popOffset >= m_pushOffset ? TRUE : FALSE ); }
DataUnit GetNextDataUnit() const
{
if (IsPopEnd()) return DataUnit(eNone, 0, NULL);
DWORD offset = m_popOffset;
DWORD dataType = BYTES_TO_UINT(m_buffer + offset);
offset += GM_PDU_BYTES_ALIGN;
DWORD dataLength = BYTES_TO_UINT(m_buffer + offset);
offset += GM_PDU_BYTES_ALIGN;
LPCBYTE dataBufferPtr = ((dataLength > 0) ? (m_buffer + offset) : NULL);
return DataUnit(dataType, dataLength, dataBufferPtr);
}
DWORD GetNextDataType() const { return GetNextDataUnit().GetDataType(); }
DWORD GetNextDataLength() const { return GetNextDataUnit().GetDataLength(); }
void SkipNextData() { m_popOffset += GetNextDataUnit().Length(); }
void Clear() { m_pushOffset = m_popOffset = 0; }
private:
inline void Resize(const DWORD newBufferLength)
{
if ( newBufferLength < m_bufferLength ) return;
LPBYTE oldBuffer = m_buffer;
m_bufferLength = KBYTE_2_BYTE(BYTE_2_KBYTE(newBufferLength));
m_buffer = new BYTE[m_bufferLength];
if ( m_buffer ) { memcpy(m_buffer, oldBuffer, m_pushOffset); delete [] oldBuffer; }
}
template<typename T> void PushData(const T& data)
{
DataUnit unit(data);
Resize(m_pushOffset + unit.Length());
DWORD offset = m_pushOffset;
UINT_TO_BYTES(unit.GetDataType(), m_buffer + offset);
offset += GM_PDU_BYTES_ALIGN;
UINT_TO_BYTES(unit.GetDataLength(), m_buffer + offset);
offset += GM_PDU_BYTES_ALIGN;
if ( unit.GetDataLength() > 0 && unit.GetDataBufferPtr() )
{
memcpy(m_buffer + offset, unit.GetDataBufferPtr(), unit.GetDataLength());
}
m_pushOffset += unit.Length();
}
template<typename T> void PopData(T& data)
{
DataUnit unit = GetNextDataUnit();
if ( unit.ConvertTo(data) ) m_popOffset += unit.Length();
}
};
enum {
ePTZ_CMD_SET_XY_ABS = 41, //41
ePTZ_CMD_GET_XY_ABS,
ePTZ_CMD_SET_XY_REL,
ePTZ_CMD_GET_MANU_INFO,
ePTZ_CMD_GET_HAND_SPEED,//45
ePTZ_CMD_SET_PRESET_SPEED,
ePTZ_CMD_GET_PRESET_SPEED,
} ;
static const int ptz_x_rel_min = -35999;
static const int ptz_x_rel_max = 35999;
static const int ptz_y_rel_min = -9000;
static const int ptz_y_rel_max = 9000;
static const int ptz_x_abs_min = 0;
static const int ptz_x_abs_max = 35999;
static const int ptz_y_abs_min = 0;
static const int ptz_y_abs_max = 9000;
class PtzPosPdu {
public:
int x;
int y;
int cmd;
};
class PtzSpeedPdu {
public:
unsigned int pan_speed;
unsigned int tilt_speed;
int cmd;
};
class PtzZoomPdu {
public:
unsigned int zoom; //>0
unsigned int zoom_speed; //0~100
};
#endif // __PDU_H__
|
cac5fc0456d73b5f672b76e632b05e1a725e0c1c
|
dd289eb872ca37d70121ecd59d9dd5f9c0b80934
|
/Algorithms/Sort/InsertionSort.cpp
|
d8ad35a6c317a954c8b2684788905f698790096d
|
[] |
no_license
|
samarsault/competitive-programming
|
02190ff34f86c45c769c68bd4e2bde347156dee0
|
5755523021b76a47444e97f9360dae7eb5b7d4ca
|
refs/heads/master
| 2022-01-11T23:18:16.074183
| 2019-05-05T22:18:24
| 2019-05-05T22:18:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 540
|
cpp
|
InsertionSort.cpp
|
#include <stdio.h>
int incount = 0;
void insertion_sort(int A[], int n)
{
for (int i = 1;i < n;i++)
{
int key = A[i];
int j = i - 1;
while (j >= 0 && A[j] > key)
{
A[j + 1] = A[j];
incount++;
j--;
}
A[j + 1] = key;
}
}
int main(int argc, const char *argv[])
{
int arr[] = { 2, 3, 8, 6, 1 };
int len = sizeof(arr) / sizeof(int);
insertion_sort(arr, len);
for (int i = 0; i < len; i++) {
printf("%d ", arr[i]);
}
putchar('\n');
printf("%d\n", incount);
return 0;
}
|
439720c178a593b38591d25e36d6a93e8a49ef49
|
dbcad7e55a9ccda9822383bb79eba2746cfe07bd
|
/Project/Project/RocketFactory.cpp
|
23381abd092ab85ba8f17cc4d02c11e409a0908d
|
[] |
no_license
|
Smaugmuel/SpaceSimulation
|
53f9c6515cf45d3516f3af56bf0387e0a7969cfa
|
bd1645d4ccf82c4e757f71a13bd1b7f87889ca8c
|
refs/heads/master
| 2021-07-15T00:58:50.106413
| 2017-10-14T15:23:11
| 2017-10-14T15:23:11
| 105,751,795
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 621
|
cpp
|
RocketFactory.cpp
|
#include "RocketFactory.hpp"
#include "Planet.hpp"
#include "Rocket.hpp"
#include "Input.hpp"
#include "SystemInformation.hpp"
Rocket * RocketFactory::CreateRocket(Planet * startPlanet)
{
Vector2d mousePos = Input::Get()->MousePositionDouble() * (1.0 / PX_PER_M);
Vector2d rocketPos = startPlanet->GetPosition();
Vector2d rocketToMouse = mousePos - rocketPos;
Vector2d toPlanetSurface = rocketToMouse.Normalized() * startPlanet->GetRadius();
Vector2d startPosition = rocketPos + toPlanetSurface;
Vector2d startVelocity = rocketToMouse * 5.0e-7;
Rocket* r = new Rocket(startPosition, startVelocity);
return r;
}
|
7dc8c88f7aa745dc61aea271de5facac1bd002f9
|
41b8833fa2b47640b84284b09b25f1915dba7564
|
/YaoPlayer/YaoPlayer.cpp
|
c41e65956b057f9edddf807609d118655a0117cb
|
[] |
no_license
|
820209232/YaoPlayer
|
15d67ca52659174622101cb65a5ed588e9e2681c
|
4bd157eed0efd3b01258037470e22f300dfac6f5
|
refs/heads/master
| 2022-10-09T08:07:45.141356
| 2020-06-12T09:40:58
| 2020-06-12T09:40:58
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 628
|
cpp
|
YaoPlayer.cpp
|
#include "YaoPlayer.h"
YaoPlayer::YaoPlayer(std::string _path)
{
path = _path;
}
YaoPlayer::~YaoPlayer()
{
}
int YaoPlayer::open(double time)
{
if (playerCtr == nullptr) {
playerCtr = new YaoPlayerCtr(time);
playerCtr->start();
return 0;
}
return -1;
}
int YaoPlayer::stop()
{
if (playerCtr != nullptr) {
playerCtr->stop();
delete playerCtr;
playerCtr = nullptr;
}
return 0;
}
int YaoPlayer::play()
{
return playerCtr->play();
}
int YaoPlayer::pause()
{
return playerCtr->pause();
}
int YaoPlayer::seek(double time)
{
stop();
open(time);
return 0;
}
|
1b38b9b40053225b8f924558fdae872906cd86f8
|
c91ac9497c7ef59b8171805a54c78e5d1ad688e9
|
/tests/test.cpp
|
4d1172ddab5e0e4825142f0da408d7d2a1449460
|
[
"MIT"
] |
permissive
|
4Rjee/lab03sharedptr
|
c39579846090bd6ce7479e72f513cd0da3962a8d
|
80a4413d00f9ff011310e073f50bfefb9708977a
|
refs/heads/master
| 2023-02-13T09:52:26.498428
| 2021-01-21T02:56:34
| 2021-01-21T02:56:34
| 330,815,065
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,126
|
cpp
|
test.cpp
|
// Copyright 2020 Kochurin Nikita kochurin.nikita@gmail.com
#include <gtest/gtest.h>
#include <string>
#include "shared_ptr.hpp"
TEST(SharedPtr, EmptySharedPtr) {
SharedPtr<std::string> r;
ASSERT_EQ(r.get(), nullptr);
}
TEST(SharedPtr, InitializationSharedPtr) {
SharedPtr<std::string> r(new std::string{"Hello"});
ASSERT_EQ(*r, "Hello");
ASSERT_EQ(r.use_count(), 1);
}
TEST(SharedPtr, CopyConstructor) {
const SharedPtr<std::string> r(new std::string{"Nikita"});
SharedPtr<std::string> p(r);
ASSERT_EQ(*p, "Nikita");
ASSERT_EQ(p.use_count(), 2);
}
TEST(SharedPtr, MoveConstructor) {
SharedPtr<std::string> r(new std::string{"Kochurin"});
SharedPtr<std::string> p(std::move(r));
ASSERT_EQ(*p, "Kochurin");
ASSERT_EQ(p.use_count(), 1);
ASSERT_EQ(r.get(), nullptr);
SharedPtr<std::string> q(SharedPtr<std::string>(new std::string{"C++"}));
ASSERT_EQ(*q, "C++");
ASSERT_EQ(q.use_count(), 1);
}
TEST(SharedPtr, CopyAssignment) {
SharedPtr<std::string> r(new std::string{"SharedPtr"});
SharedPtr<std::string> p(r);
ASSERT_EQ(*p, "SharedPtr");
ASSERT_EQ(p.use_count(), 2);
ASSERT_EQ(r.use_count(), 2);
SharedPtr<std::string> q(new std::string{"ScopedPtr"});
ASSERT_EQ(q.use_count(), 1);
p = q;
ASSERT_EQ(*p, "ScopedPtr");
ASSERT_EQ(p.use_count(), 2);
ASSERT_EQ(r.use_count(), 1);
ASSERT_EQ(q.use_count(), 2);
SharedPtr<std::string> *ptr_ = &p;
p = *ptr_;
ASSERT_EQ(*p, "ScopedPtr");
ASSERT_EQ(p.use_count(), 2);
}
TEST(SharedPtr, MoveAssignment) {
SharedPtr<std::string> r(new std::string{"SharedPtr"});
SharedPtr<std::string> p(r);
ASSERT_EQ(*p, "SharedPtr");
ASSERT_EQ(p.use_count(), 2);
ASSERT_EQ(r.use_count(), 2);
SharedPtr<std::string> q(new std::string{"ScopedPtr"});
SharedPtr<std::string> z(q);
ASSERT_EQ(*z, "ScopedPtr");
ASSERT_EQ(z.use_count(), 2);
ASSERT_EQ(q.use_count(), 2);
q = std::move(p);
ASSERT_EQ(p.operator bool(), false);
ASSERT_EQ(r.use_count(), 2);
ASSERT_EQ(z.use_count(), 1);
SharedPtr<std::string> *ptr_ = &q;
q = std::move(*ptr_);
ASSERT_EQ(*q, "SharedPtr");
ASSERT_EQ(q.use_count(), 2);
}
TEST(SharedPtr, Reset) {
SharedPtr<std::string> r(new std::string{"Reset"});
ASSERT_EQ(*r, "Reset");
ASSERT_EQ(r.use_count(), 1);
r.reset();
ASSERT_EQ(r.operator bool(), false);
}
TEST(SharedPtr, ResetPointer) {
SharedPtr<std::string> r(new std::string{"ResetPointer"});
ASSERT_EQ(*r, "ResetPointer");
ASSERT_EQ(r.use_count(), 1);
r.reset(new std::string{"New"});
ASSERT_EQ(*r, "New");
ASSERT_EQ(r.use_count(), 1);
}
TEST(SharedPtr, Swap) {
SharedPtr<std::string> r(new std::string{"One"});
ASSERT_EQ(*r, "One");
ASSERT_EQ(r.use_count(), 1);
SharedPtr<std::string> p(new std::string{"Two"});
ASSERT_EQ(*p, "Two");
ASSERT_EQ(p.use_count(), 1);
r.swap(p);
ASSERT_EQ(*p, "One");
ASSERT_EQ(p.use_count(), 1);
ASSERT_EQ(*r, "Two");
ASSERT_EQ(r.use_count(), 1);
r.swap(r);
}
TEST(SharedPtr, IsMoveConstructible) {
EXPECT_TRUE(std ::is_move_constructible<SharedPtr<int>>());
EXPECT_TRUE(std ::is_move_constructible<SharedPtr<std ::string>>());
}
TEST(SharedPtr, IsMoveAssignable) {
EXPECT_TRUE(std ::is_move_assignable<SharedPtr<int>>());
EXPECT_TRUE(std ::is_move_assignable<SharedPtr<std ::string>>());
}
|
472c02fd29a25a6595f8fd889a5c68580fe104c2
|
aecef693df48abb893627f4762f8f46a83040787
|
/2015/CS2420/a7/main.cpp
|
cdf34a6e8845a0e83f75107f3143d5285552a8dd
|
[] |
no_license
|
adamtew/USU
|
6f269ec6d28b81eb1f64370dc57e57a8da6e7f19
|
b4cc88c996f2841ee3776405f1d606b2bd1a1b4e
|
refs/heads/master
| 2021-01-21T05:59:07.492786
| 2017-09-24T06:40:55
| 2017-09-24T06:40:55
| 28,891,531
| 2
| 0
| null | 2016-01-25T04:59:30
| 2015-01-07T01:06:26
|
C++
|
UTF-8
|
C++
| false
| false
| 2,016
|
cpp
|
main.cpp
|
#include <iostream>
#include "Graph.h"
#include <fstream>
using namespace std;
void play();
Graph g;
int main() {
// ifstream fin("/Users/at/gitSchool/usu/2015/CS2420/a7/digraph1.txt");
// ifstream fin("/Users/at/gitSchool/usu/2015/CS2420/a7/digraph2.txt");
// ifstream fin("/Users/at/gitSchool/usu/2015/CS2420/a7/digraph3.txt");
// Input files
// ifstream fin("digraph1.txt");
ifstream fin("digraph2.txt");
// ifstream fin("digraph3.txt");
if(!fin.is_open())
{
cout << "Error with input file";
return 0;
}
int nodes;
int edges;
int node;
int parent;
fin >> nodes;
fin >> edges;
cout << "There are " << nodes << " nodes and " << edges << " paths in this file\n";
switch(node)
{
1: cout << "one";
}
// Create the graph and load the nodes into it.
// Graph g(nodes);
g.makeGraph(nodes);
while(!fin.eof())
{
fin >> node;
fin >> parent;
g.insert(node, parent);
}
cout << g.toString();
// Traverse the graph
// g.traverse(5, false);
// Part I
cout << "\n\n-------------------\n";
cout << "Part I";
cout << "\n-------------------\n";
g.SCA(2, 8);
// Part II
cout << "\n\n-------------------\n";
cout << "Part II";
cout << "\n-------------------\n";
int set1[3] = {13, 23, 24};
int set2[3] = {16, 17, 6};
g.SCA(set1, set2);
// User Interface for single path travesal
cout << "\n\n-----------------\n";
cout << "Runner";
cout << "\n-----------------\n";
play();
return 0;
}
void play()
{
int first = 0;
int second = 0;
while(true)
{
cout << g.toString();
cout << "-1 to quit\n";
cout << "Enter the nodes you want visited\n";
cout << "First: ";
cin >> first;
if(first < 0)break;
cout << "Second: ";
cin >> second;
if(second < 0)break;
g.SCA(first, second);
}
cout << "\nThanks for playing";
}
|
7e41ea99367d7e2c0321a0f16ba8449ccd9e836b
|
650afd54ad6e3a5fb2ad62a25b56b8640c6c8ec3
|
/V2/Klijent.cpp
|
5bcaf924766b3e66a2658f2c09865ddeec1c7555
|
[] |
no_license
|
al0cam/MR2
|
29b55e7cb107082b419da04604c859df83eb48ce
|
4d15dfa34634be92fcd77931d31420e97659e498
|
refs/heads/main
| 2023-02-17T21:57:15.852007
| 2021-01-21T10:45:51
| 2021-01-21T10:45:51
| 331,597,597
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,667
|
cpp
|
Klijent.cpp
|
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <iostream>
#include <cstdlib>
/* IPV4 makro konstanta navodi IPV4 adresu na koju se klijent povezuje */
#define IPV4 "127.0.0.1"
/* PORT makro navodi broj TCP porta na koji se klijent povezuje */
#define PORT "7890"
/* maksimalna velicina poruke koju klijent moze prihvatiti od servera */
#define VELICINA 40
int main(int argc, char **argv) {
struct addrinfo upute; /* struktura za parametriziranje getaddrinfo poziva (u engl. literaturi obicno 'hints') */
struct addrinfo *rezultat; /* struktura koja ce sadrzavati popunjene informacije o loopback adresi servera */
int opisnik; /* socket descriptor klijenta */
int procitano; /* broj procitanih okteta koje nam je server poslao */
char medjuspremnik[VELICINA] = {'\0'}; /* medjuspremnik za pohranu poruke sa servera */
char poruka;
/* dohvacanje adrese servera */
memset(&upute, 0, sizeof(struct addrinfo));
upute.ai_family = AF_INET;
upute.ai_socktype = SOCK_STREAM;
getaddrinfo(IPV4, PORT, &upute, &rezultat);
/* kreiranje prikljucnice (socket-a) */
opisnik = socket(rezultat->ai_family, rezultat->ai_socktype, rezultat->ai_protocol);
/* povezivanje na server */
connect(opisnik, rezultat->ai_addr, rezultat->ai_addrlen);
char message[40] = "SIMPLE TIME";
send(opisnik, message, 40, 0);
/* ucitavanje poruke sa servera u lokalni medjuspremnik */
procitano = recv(opisnik, medjuspremnik, VELICINA, 0);
if(procitano > 0 && procitano < VELICINA) {
medjuspremnik[procitano] = '\0';
}
printf("%s\n", medjuspremnik);
close(opisnik);
return 0;
}
|
43774845a9a27a82721b7ae2d4caaff906f32c02
|
fce13eff25af401c650de31220a08727f9669d87
|
/parser/mpFuncCmplx.h
|
345584bcf8ea9e146a546722c65c38cd35873a28
|
[
"BSD-2-Clause"
] |
permissive
|
beltoforion/muparserx
|
d75d41afe1e1805d13c4e0dd6dc134bcf6bea12a
|
9074157b22e7d2b3fcc0ab210751b9daaee19914
|
refs/heads/master
| 2023-08-24T19:57:32.625165
| 2023-06-06T19:18:46
| 2023-06-06T19:18:46
| 32,697,483
| 126
| 64
|
BSD-2-Clause
| 2023-03-21T21:44:10
| 2015-03-22T21:54:18
|
C++
|
UTF-8
|
C++
| false
| false
| 9,159
|
h
|
mpFuncCmplx.h
|
/** \file
\brief Definition of functions for complex valued operations.
<pre>
__________ ____ ___
_____ __ _\______ \_____ _______ ______ __________\ \/ /
/ \| | \ ___/\__ \\_ __ \/ ___// __ \_ __ \ /
| Y Y \ | / | / __ \| | \/\___ \\ ___/| | \/ \
|__|_| /____/|____| (____ /__| /____ >\___ >__| /___/\ \
\/ \/ \/ \/ \_/
Copyright (C) 2023 Ingo Berg
All rights reserved.
muParserX - A C++ math parser library with array and string support
Copyright (C) 2023, Ingo Berg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
</pre>
*/
#ifndef MUP_COMPLEX_FUNCTIONS_H
#define MUP_COMPLEX_FUNCTIONS_H
#include "mpICallback.h"
MUP_NAMESPACE_START
//-----------------------------------------------------------------------
/** \brief Parser callback object for returning the real part of a complex number.
\ingroup functions
*/
class FunCmplxReal : public ICallback
{
public:
FunCmplxReal();
virtual ~FunCmplxReal();
virtual void Eval(ptr_val_type& ret, const ptr_val_type* a_pArg, int a_iArgc) override;
virtual const char_type* GetDesc() const override;
virtual IToken* Clone() const override;
};
//-----------------------------------------------------------------------
/** \brief Parser callback object for returning the imaginary part of a complex number.
\ingroup functions
*/
class FunCmplxImag : public ICallback
{
public:
FunCmplxImag();
virtual void Eval(ptr_val_type& ret, const ptr_val_type* a_pArg, int a_iArgc) override;
virtual const char_type* GetDesc() const override;
virtual IToken* Clone() const override;
};
//-----------------------------------------------------------------------
/** \brief Parser callback object for returning the complex conjugate of
the complex number.
\ingroup functions
*/
class FunCmplxConj : public ICallback
{
public:
FunCmplxConj();
virtual void Eval(ptr_val_type& ret, const ptr_val_type* a_pArg, int a_iArgc) override;
virtual const char_type* GetDesc() const override;
virtual IToken* Clone() const override;
};
//-----------------------------------------------------------------------
/** \brief Parser callback object for returning the phase angle
(or angular component) of a complex number, expressed in radians.
\ingroup functions
*/
class FunCmplxArg : public ICallback
{
public:
FunCmplxArg();
virtual void Eval(ptr_val_type& ret, const ptr_val_type* a_pArg, int a_iArgc) override;
virtual const char_type* GetDesc() const override;
virtual IToken* Clone() const override;
};
//-----------------------------------------------------------------------
/** \brief Parser callback object for returning the norm value of the
complex number phase angle.
\ingroup functions
*/
class FunCmplxNorm : public ICallback
{
public:
FunCmplxNorm();
virtual void Eval(ptr_val_type& ret, const ptr_val_type* a_pArg, int a_iArgc) override;
virtual const char_type* GetDesc() const override;
virtual IToken* Clone() const override;
};
//-----------------------------------------------------------------------
class FunCmplxCos : public ICallback
{
public:
FunCmplxCos();
virtual void Eval(ptr_val_type& ret, const ptr_val_type* a_pArg, int a_iArgc) override;
virtual const char_type* GetDesc() const override;
virtual IToken* Clone() const override;
};
//-----------------------------------------------------------------------
class FunCmplxSin : public ICallback
{
public:
FunCmplxSin();
virtual void Eval(ptr_val_type& ret, const ptr_val_type* a_pArg, int a_iArgc) override;
virtual const char_type* GetDesc() const override;
virtual IToken* Clone() const override;
};
//-----------------------------------------------------------------------
class FunCmplxCosH : public ICallback
{
public:
FunCmplxCosH();
virtual void Eval(ptr_val_type& ret, const ptr_val_type* a_pArg, int a_iArgc) override;
virtual const char_type* GetDesc() const override;
virtual IToken* Clone() const override;
};
//-----------------------------------------------------------------------
class FunCmplxSinH : public ICallback
{
public:
FunCmplxSinH();
virtual void Eval(ptr_val_type& ret, const ptr_val_type* a_pArg, int a_iArgc) override;
virtual const char_type* GetDesc() const override;
virtual IToken* Clone() const override;
};
//-----------------------------------------------------------------------
class FunCmplxTan : public ICallback
{
public:
FunCmplxTan();
virtual void Eval(ptr_val_type& ret, const ptr_val_type* a_pArg, int a_iArgc) override;
virtual const char_type* GetDesc() const override;
virtual IToken* Clone() const override;
};
//-----------------------------------------------------------------------
class FunCmplxTanH : public ICallback
{
public:
FunCmplxTanH();
virtual void Eval(ptr_val_type& ret, const ptr_val_type* a_pArg, int a_iArgc) override;
virtual const char_type* GetDesc() const override;
virtual IToken* Clone() const override;
};
//-----------------------------------------------------------------------
class FunCmplxSqrt : public ICallback
{
public:
FunCmplxSqrt();
virtual void Eval(ptr_val_type& ret, const ptr_val_type* a_pArg, int a_iArgc) override;
virtual const char_type* GetDesc() const override;
virtual IToken* Clone() const override;
};
//-----------------------------------------------------------------------
class FunCmplxExp : public ICallback
{
public:
FunCmplxExp();
virtual void Eval(ptr_val_type& ret, const ptr_val_type* a_pArg, int a_iArgc) override;
virtual const char_type* GetDesc() const override;
virtual IToken* Clone() const override;
};
//-----------------------------------------------------------------------
class FunCmplxLn : public ICallback
{
public:
FunCmplxLn();
virtual void Eval(ptr_val_type& ret, const ptr_val_type* a_pArg, int a_iArgc) override;
virtual const char_type* GetDesc() const override;
virtual IToken* Clone() const override;
};
//-----------------------------------------------------------------------
class FunCmplxLog : public ICallback
{
public:
FunCmplxLog();
virtual void Eval(ptr_val_type& ret, const ptr_val_type* a_pArg, int a_iArgc) override;
virtual const char_type* GetDesc() const override;
virtual IToken* Clone() const override;
};
//-----------------------------------------------------------------------
class FunCmplxLog10 : public ICallback
{
public:
FunCmplxLog10();
virtual void Eval(ptr_val_type& ret, const ptr_val_type* a_pArg, int a_iArgc) override;
virtual const char_type* GetDesc() const override;
virtual IToken* Clone() const override;
};
//-----------------------------------------------------------------------
class FunCmplxLog2 : public ICallback
{
public:
FunCmplxLog2();
virtual void Eval(ptr_val_type& ret, const ptr_val_type* a_pArg, int a_iArgc) override;
virtual const char_type* GetDesc() const override;
virtual IToken* Clone() const override;
};
//-----------------------------------------------------------------------
class FunCmplxAbs : public ICallback
{
public:
FunCmplxAbs();
virtual void Eval(ptr_val_type& ret, const ptr_val_type* a_pArg, int a_iArgc) override;
virtual const char_type* GetDesc() const override;
virtual IToken* Clone() const override;
};
//-----------------------------------------------------------------------
class FunCmplxPow : public ICallback
{
public:
FunCmplxPow();
virtual void Eval(ptr_val_type& ret, const ptr_val_type* a_pArg, int a_iArgc) override;
virtual const char_type* GetDesc() const override;
virtual IToken* Clone() const override;
};
} // namespace mu
#endif
|
620a523e0e1d68780f5793aebde9e8a615b0950f
|
0f1157c33b1e5cca6f76b1c6a779bc824913c631
|
/Arnab_goal.cpp
|
0ba6a601ecaab0b58378ce6c2a5f2b6c237f3917
|
[] |
no_license
|
lohith9/skills_solutions.cpp
|
56f883c475c819939d22d75449d2b0fb95f4cadc
|
3d1e7eac8446ec310e9f47e987e817aae3cc400b
|
refs/heads/master
| 2020-03-24T10:15:09.281182
| 2018-07-28T06:40:13
| 2018-07-28T06:40:13
| 142,651,485
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 357
|
cpp
|
Arnab_goal.cpp
|
#include <iostream>
using namespace std;
int main() {
int t;
cin>>t;
while(t--){
int x,y,z;
cin>>x>>y>>z;
int count1=0,count2=0;
while(z>1){
if(x%z==0){
count1++;
x--;
}
if(y%z==0){
count2++;
y--;
}
z--;
}
cout<<count1<<" "<<count2<<endl;
}
}
|
cd5bf8e57f5ce1c4f99b234d92868d4da0ad4bdd
|
0aff1a2e7229802de192735ca01c4470f3635333
|
/Fool 2019/a.cpp
|
5ceef78f0b7697846ac7f7a402dda259d8ad1b2d
|
[] |
no_license
|
mn619/cf-practise
|
70d7706bb6c1e8459158ec947b1ebcd359701a17
|
0d68239bd4fabd55d0dd40e1506d8c01a2e241f1
|
refs/heads/master
| 2022-09-12T14:42:49.156257
| 2020-05-28T18:53:01
| 2020-05-28T18:53:01
| 190,338,201
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 698
|
cpp
|
a.cpp
|
#include<bits/stdc++.h>
#define FLASH cin.tie(0); cout.tie(0); ios_base::sync_with_stdio(false);
#define pb push_back
#define int long long
#define fr(i,a,b) for(int i=a;i<b;i++)
#define mod 1000000007
#define FILEIO freopen("/home/aman/Desktop/Kachda/input.txt", "r", stdin); freopen("/home/aman/Desktop/Kachda/output.txt", "w", stdout);
using namespace std;
int a[17];
int solve(int l, int r)
{
bool ok = 1;
fr(i, l + 1, r + 1)
if(a[i] < a[i - 1]) ok = 0;
if(ok) return r - l + 1;
int mid = (l + r)/2;
return max(solve(l, mid), solve(mid + 1, r));
}
signed main()
{
#ifndef ONLINE_JUDGE
FILEIO
#endif
FLASH
int n;
cin>>n;
fr(i, 1, n + 1) cin>>a[i];
cout<<solve(1, n);
}
|
c7ecaf6a270d2376606d648d6ed4a53b9076bc3b
|
cf49fcf8108f84e03ad503c0e496aa007b950700
|
/spike/GUI/GameEngine.hpp
|
400d64f51655c6ac2c8bdc09bc6e8f7405e79201
|
[
"MIT"
] |
permissive
|
KaceCottam/UltimateBattleship
|
3cae1528c5a355344c71aa92562a1129e099eca6
|
d45f4df2d880fcb4aaca3bf22f017b7df71ea3db
|
refs/heads/master
| 2020-05-09T10:41:10.639373
| 2019-04-24T17:11:24
| 2019-04-24T17:11:24
| 181,052,358
| 0
| 1
|
MIT
| 2019-04-14T08:29:52
| 2019-04-12T17:17:53
|
C++
|
UTF-8
|
C++
| false
| false
| 1,664
|
hpp
|
GameEngine.hpp
|
#pragma once
#include <map>
#include <SFML/Graphics.hpp>
#include <fmt/format.h>
#include <spdlog/spdlog.h>
#include "Scene.hpp"
#include "../SFMLUtil/BadIndexError.hpp"
namespace GUI {
using namespace sf;
using namespace fmt;
using namespace spdlog;
class Game {
public:
using SceneId = std::size_t;
Game(RenderWindow& window) : window_{window} {}
void AddScene(Scene *scene) { scenes_[scenes_.size()] = scene; }
bool Play() {
LoadScene(current_id_);
while (window_.isOpen()) {
Event event;
while (window_.pollEvent(event)) {
if (event.type == Event::Closed) window_.close();
auto result = scenes_[current_id_]->HandleEvent(event);
try {
if (result != current_id_) LoadScene(result);
} catch(const SFMLUtil::BadIndexError &e) {
warn("Disregard error if index == size!");
if (result == scenes_.size()) window_.close();
else throw e;
}
}
window_.clear();
window_.draw(*scenes_[current_id_]);
window_.display();
}
UnloadScene();
return EXIT_SUCCESS;
}
private:
void LoadScene(const SceneId id) {
try {
scenes_.at(id)->LoadResources();
} catch (const std::exception &e) {
error(format("Scene ID {} does not exist!", id));
throw SFMLUtil::BadIndexError(id, scenes_.size());
} catch (...) {
error("Unknown error occured while loading scene.");
}
UnloadScene();
current_id_ = id;
}
void UnloadScene() { scenes_[current_id_]->UnloadResources(); }
std::map<SceneId, Scene *> scenes_;
SceneId current_id_;
RenderWindow &window_;
};
} // namespace GUI
|
ce9fbe439220e570d03e0e39eef47cfa072f3484
|
633a78599aefa7ab8b6a282c13e475af5a15d793
|
/src/classwork/10_assign/sales_employee.h
|
5c17316f486080af88d718871fca13384d19fe0c
|
[
"MIT"
] |
permissive
|
acc-cosc-1337-summer-2020-classroom/acc-cosc-1337-summer-2020-Gabe-Cpp
|
291c25bf226e49c118831a3e07d0f18951292623
|
f5b7d8610054c975b67ff04a41a7a054325e3c7e
|
refs/heads/master
| 2022-11-22T14:53:47.483892
| 2020-07-26T19:10:58
| 2020-07-26T19:10:58
| 268,946,885
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 493
|
h
|
sales_employee.h
|
//sales_employee.h
#include "employee.h"
#ifndef SALES_EMPLOYEE_H
#define SALES_EMPLOYEE_H
class SalesEmployee: public Employee{
public:
SalesEmployee() : Employee(){}
SalesEmployee(double hours, double rate, double commission) :Employee(hours, rate, commission){
num_hours = hours;
pay_rate = rate;
commission_amount = commission;
}
double get_pay();
double num_hours, pay_rate, commission_amount;
};
#endif
|
ce0636af26fa175a38e8a51cfc3456393f2e5525
|
d110fa80f2ae305c52b449872fd93152038f8a73
|
/QPRecordModel/syslogtype.cpp
|
596be191c53c67a67dc98b71611a5345fbd39d53
|
[] |
no_license
|
iamgeniuswei/QPlatform
|
6fd98dae5576a7dd85ea9800404375fa784907fe
|
05cba523571287f551dc20c6211203988e820be3
|
refs/heads/master
| 2020-04-06T07:12:35.796750
| 2016-07-22T01:12:59
| 2016-07-22T01:12:59
| 56,820,817
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 528
|
cpp
|
syslogtype.cpp
|
#include "syslogtype.h"
int SysLogType::getLogTypeId() const
{
return logTypeId;
}
void SysLogType::setLogTypeId(int value)
{
logTypeId = value;
}
QString SysLogType::getLogTypeName() const
{
return logTypeName;
}
void SysLogType::setLogTypeName(const QString &value)
{
logTypeName = value;
}
QString SysLogType::getLogTypeDescription() const
{
return logTypeDescription;
}
void SysLogType::setLogTypeDescription(const QString &value)
{
logTypeDescription = value;
}
|
9026c895d02d8a9400abadf54da772b9da5c82be
|
8b127cab5c35c1b5a754fc152118baec7df74003
|
/Accelerated-Cpp/ch_5/ex_5-1/src/rotate.cpp
|
2633ff2f8fe50590873f8affc0b2b2bfac7e7c91
|
[] |
no_license
|
arshjot/Cpp-Practice
|
76cb07c30b02a110fbe1fba9b65045402f3818df
|
0463d6f1c5fcb60967e7e3be88717e566dbcf984
|
refs/heads/master
| 2020-12-19T20:04:43.343339
| 2020-03-06T15:10:58
| 2020-03-06T15:10:58
| 235,838,197
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,016
|
cpp
|
rotate.cpp
|
#include <string>
#include <vector>
#include <numeric>
#include "rotate.h"
#include "split.h"
using std::string;
using std::accumulate;
using std::vector;
using std::copy;
// function to define the comparison of splitted strings
// comparison to be done in lowercase
bool compare(const Rotated_line& x, const Rotated_line& y)
{
return x.second_half < y.second_half;
}
vector<Rotated_line> rotate(const vector<string>& lines)
{
vector<string> line;
vector<Rotated_line> rot_lines;
// Loop over all the lines
for (vector<string>::size_type li=0; li!=lines.size(); ++li) {
// Split the line into words
line = split(lines[li]);
// Rotate the line and split each instance into two halves
for (vector<string>::size_type wi=0; wi!=line.size(); ++wi) {
Rotated_line rot;
rot.first_half.insert(rot.first_half.begin(), line.begin(), line.begin() + wi);
rot.second_half.insert(rot.second_half.begin(), line.begin() + wi, line.end());
rot_lines.push_back(rot);
}
}
return rot_lines;
}
|
08e4f991db7587201f4f8ef8b6be4492e010c829
|
51005c0d28f07eddb703702c1464bd09940981fc
|
/services/call/include/ims_call.h
|
164a2707d8771e51eb5f05427a48dabc1147d487
|
[
"Apache-2.0"
] |
permissive
|
openharmony-sig-ci/telephony_call_manager
|
aa57c18764da0ebe762b9780b4e9fbcac56cf970
|
440ac87630239cd495ec8d52e4ec3da1e37ca704
|
refs/heads/master
| 2023-08-03T15:46:52.923035
| 2021-09-08T09:49:15
| 2021-09-08T09:49:15
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,925
|
h
|
ims_call.h
|
/*
* Copyright (C) 2021 Huawei Device 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.
*/
#ifndef IMS_CALL_H
#define IMS_CALL_H
#include "carrier_call.h"
#include "net_call_base.h"
namespace OHOS {
namespace Telephony {
class IMSCall : public CarrierCall, public NetCallBase {
public:
IMSCall();
~IMSCall();
void OutCallInit(const CallReportInfo &info, AppExecFwk::PacMap &extras, int32_t callId);
void InCallInit(const CallReportInfo &info, int32_t callId);
int32_t DialingProcess() override;
int32_t AnswerCall(int32_t videoState) override;
int32_t RejectCall(bool isSendSms, std::string &content) override;
int32_t HangUpCall() override;
int32_t HoldCall() override;
int32_t UnHoldCall() override;
int32_t SwitchCall() override;
void GetCallAttributeInfo(CallAttributeInfo &info) override;
int32_t CombineConference() override;
int32_t CanCombineConference() override;
int32_t SubCallCombineToConference() override;
int32_t SubCallSeparateFromConference() override;
int32_t CanSeparateConference() override;
int32_t GetMainCallId() override;
std::vector<std::u16string> GetSubCallIdList() override;
std::vector<std::u16string> GetCallIdListForConference() override;
private:
sptr<CallBase> conferenceHost_;
sptr<CallBase> conferencePartner_;
};
} // namespace Telephony
} // namespace OHOS
#endif // IMS_CALL_H
|
2f874e9a7af6dd834fe2b17c7a4bab81e034655f
|
6226d6aed3629aa4069c46971ffe764bb6c743f6
|
/Myway/RenderSystem/MWSceneRenderUniform.h
|
44bcaa44ea376549d64a9fcdd367d1331c91fab3
|
[] |
no_license
|
Myway3D/Myway3D
|
83c30258f1e3eae90e619269406acd0ddeac7887
|
39cf569993f62fc648cbba49ebf74b3f8a64e46a
|
refs/heads/master
| 2020-04-22T20:24:15.817427
| 2014-03-09T14:25:23
| 2014-03-09T14:25:23
| 170,640,096
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,019
|
h
|
MWSceneRenderUniform.h
|
#pragma once
#include "MWSceneRender.h"
#include "MWRenderTarget.h"
#include "MWShadowRender.h"
#include "MWSceneNode.h"
namespace Myway
{
enum RenderUniformStage
{
RUS_DIFFUSE,
RUS_PROJECTION,
MW_ALIGN_ENUM(RenderUniformStage)
};
class MW_ENTRY SceneRenderUniform : public SceneRender
{
DECLARE_SINGLETON(SceneRenderUniform)
public:
SceneRenderUniform();
virtual ~SceneRenderUniform();
virtual void RenderScene(Camera * cam);
void SetScheme(RenderUniformStage stage, const String & scheme);
const String & GetScheme(RenderUniformStage stage);
protected:
void RenderToCBuffer();
void RenderProjection();
void AddRenderQueue(SceneNode * node);
void HDR_Init();
void HDR_DeInit();
void HDR_Render();
void HDR_Bloom();
void HDR_Lum();
void HDR_ToneMap();
protected:
String m_diffuse_scheme;
String mroj_scheme;
Camera * m_camera;
};
}
|
e725d895a434dbb68e1f37f66cadac914fe3e378
|
90fabd6f58ab3ffb12549f1c6daada17113d5199
|
/application/data_loader.h
|
fe4c45ce488f6fb60675159584a65abe75c2ce09
|
[] |
no_license
|
tmandry/db-team15-test
|
1e877ad8fc3b8ac60899091b94d2305280a36772
|
1e81d582ba5c9743417503eeda4ab29fccc028ae
|
refs/heads/master
| 2021-01-22T13:57:46.987235
| 2013-03-01T05:40:42
| 2013-03-01T05:40:42
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 427
|
h
|
data_loader.h
|
#pragma once
#include <string>
#include <array>
#include <utility>
using namespace std;
#include "Table.h"
class Database;
// Class to load data from CSV files into a database.
class DataLoader
{
public:
DataLoader(string data_dir);
~DataLoader();
Database* load();
private:
template<typename D>
void load_table(string filename, string table_name, const D& descriptor);
Database *db_;
string data_dir_;
};
|
81c6c76ef91771921a2a93e24526c290ca460e62
|
70deb8b7b31f17c2a308738e0abf037dc4d22604
|
/TC++PL/ch2/Game.h
|
447e8cbacdb924ed5d54cc6c884d8f473183c0c6
|
[] |
no_license
|
jmanders85/stroustrup
|
b254039a3964ab835ea98dcca53d7495d4ec9971
|
203506b23168bfe8a53ed80728dc779122a1c556
|
refs/heads/master
| 2021-09-03T12:05:53.031877
| 2018-01-08T23:43:53
| 2018-01-08T23:43:53
| 115,728,293
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 130
|
h
|
Game.h
|
class Game {
public:
Game(char* name);
void play();
void printPlayCount();
private:
int p;
char* name;
};
|
03d39a7d60c460db9b6f012cc5e918d003b6a9e3
|
2d9eadcfbe46c99772a4bd20fb4a81da42a44c62
|
/AVBase/MediaMuxer/wlock.cpp
|
f4dfb33079fbd89e9069425a1ee81be7f1b99e73
|
[] |
no_license
|
open-vp/AVLib
|
fc1a1eac219d74f0ecf258819a371716b5770893
|
581209939d9d61ff9b35e02942717058aa1ee297
|
refs/heads/master
| 2020-03-27T20:49:26.384940
| 2018-09-03T01:23:40
| 2018-09-03T01:23:40
| 147,095,763
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,219
|
cpp
|
wlock.cpp
|
// WLock.cpp: implementation of the WLock class.
//
//////////////////////////////////////////////////////////////////////
#include "wlock.h"
using namespace OPENVP;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
WLock::WLock()
{
pthread_mutexattr_init( &m_attr );
pthread_mutexattr_settype( &m_attr,PTHREAD_MUTEX_RECURSIVE );
int rc = pthread_mutex_init( &m_Lock,&m_attr );
}
WLock::~WLock()
{
int rc = 0;
rc = pthread_mutex_destroy( &m_Lock );
pthread_mutexattr_destroy(&m_attr);
}
void WLock::Lock()
{
int rc;
do {
rc = pthread_mutex_lock( &m_Lock );
} while ( rc== EINTR );
}
void WLock::UnLock()
{
int rc;
do {
rc = pthread_mutex_unlock( &m_Lock );
} while ( rc== EINTR );
}
bool WLock::TryLock()
{
int rc;
do {
rc = pthread_mutex_trylock( &m_Lock );
} while ( rc== EINTR );
bool bResult = ( rc == 0 );
return bResult;
}
WAutoLock::WAutoLock(WLock* pLock) :m_pLock(pLock)
{
if (m_pLock)
m_pLock->Lock();
}
WAutoLock::~WAutoLock()
{
if (m_pLock)
m_pLock->UnLock();
}
|
592f6f4fb062d46f3687e59e2ffea64864acf8dc
|
7eeec50de5a1ce6884f11e1b97b47aec8fe6ffc9
|
/myProject/netxy/examples/TuntuClient.cpp
|
9896d41dca56e7dea44b0f25d6188f724913db13
|
[] |
no_license
|
okokokok123/proall
|
854a0e70b163d20d71db73f3226e0c9ffa34b021
|
a58d62e330a4677f360882cfd6aefe9c86f5a154
|
refs/heads/master
| 2020-03-24T21:18:49.459526
| 2018-07-31T14:27:16
| 2018-07-31T14:27:16
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,338
|
cpp
|
TuntuClient.cpp
|
/*************************************************************************
> File Name: TuntuClient.cpp
> Author: ma6174
> Mail: 17704623602@163.com
> Created Time: Wed Nov 15 17:55:13 2017
************************************************************************/
#include<netxy/base/TimeStamp.h>
#include<netxy/net/TcpClient.h>
#include<iostream>
using namespace std;
using namespace netxy::base;
using namespace netxy::net;
class TuntuClient{
public:
typedef shared_ptr<ConnectSocketManager> ConnectSocketManagerPtr;
TuntuClient(){
tc.setMessageCallback(std::bind(&TuntuClient::onMessage,this,_1));
}
TuntuClient(int threadCount):tc(threadCount){
tc.setMessageCallback(std::bind(&TuntuClient::onMessage,this,_1));
}
~TuntuClient(){
}
void connect(const char* ip,int port){
csmp=tc.connect(ip,port);
if(!csmp){
cout<<"连接失败"<<endl;
exit(0);
}
}
void send(int n){
string str(n,'a');
cout<<str<<endl;
if(csmp){
while(true)
csmp->send(str);
}
}
void onMessage(ConnectSocketManager*csm){
}
private:
int64_t oldTime;
int64_t newTime;
TcpClient tc;
ConnectSocketManagerPtr csmp;
};
int main(){
int n;
TuntuClient dc(1);
dc.connect("127.0.0.1",9999);
cout<<"请输入每次发送的字节数:";
cin>>n;
dc.send(n);
cout<<"end"<<endl;
}
|
896cada8ea3a07c8dd6d612f98bedcf16626fe4d
|
09e5cfe06e437989a2ccf2aeecb9c73eb998a36c
|
/modules/clipper/clipper/contrib/skeleton.cpp
|
bff10496032f03fb69d5dd29d17c52e8a00f9293
|
[
"LGPL-2.1-only",
"BSD-3-Clause"
] |
permissive
|
jorgediazjr/dials-dev20191018
|
b81b19653624cee39207b7cefb8dfcb2e99b79eb
|
77d66c719b5746f37af51ad593e2941ed6fbba17
|
refs/heads/master
| 2020-08-21T02:48:54.719532
| 2020-01-25T01:41:37
| 2020-01-25T01:41:37
| 216,089,955
| 0
| 1
|
BSD-3-Clause
| 2020-01-25T01:41:39
| 2019-10-18T19:03:17
|
Python
|
UTF-8
|
C++
| false
| false
| 13,378
|
cpp
|
skeleton.cpp
|
/* skeleton.cpp: Skeletonisation implementation */
//C Copyright (C) 2000-2004 Kevin Cowtan and University of York
//C Copyright (C) 2000-2005 Kevin Cowtan and University of York
//L
//L This library is free software and is distributed under the terms
//L and conditions of version 2.1 of the GNU Lesser General Public
//L Licence (LGPL) with the following additional clause:
//L
//L `You may also combine or link a "work that uses the Library" to
//L produce a work containing portions of the Library, and distribute
//L that work under terms of your choice, provided that you give
//L prominent notice with each copy of the work that the specified
//L version of the Library is used in it, and that you include or
//L provide public access to the complete corresponding
//L machine-readable source code for the Library including whatever
//L changes were used in the work. (i.e. If you make changes to the
//L Library you must distribute those, but you do not need to
//L distribute source or object code to those portions of the work
//L not covered by this licence.)'
//L
//L Note that this clause grants an additional right and does not impose
//L any additional restriction, and so does not affect compatibility
//L with the GNU General Public Licence (GPL). If you wish to negotiate
//L other terms, please contact the maintainer.
//L
//L You can redistribute it and/or modify the library under the terms of
//L the GNU Lesser General Public License as published by the Free Software
//L Foundation; either version 2.1 of the License, or (at your option) any
//L later version.
//L
//L This library is distributed in the hope that it will be useful, but
//L WITHOUT ANY WARRANTY; without even the implied warranty of
//L MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//L Lesser General Public License for more details.
//L
//L You should have received a copy of the CCP4 licence and/or GNU
//L Lesser General Public License along with this library; if not, write
//L to the CCP4 Secretary, Daresbury Laboratory, Warrington WA4 4AD, UK.
//L The GNU Lesser General Public can also be obtained by writing to the
//L Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
//L MA 02111-1307 USA
#include "skeleton.h"
#include "../core/map_utils.h"
namespace clipper {
// Skeleton_basic
Skeleton_basic::Neighbours::Neighbours( const clipper::Xmap_base &map, const float min_distsq, const float max_distsq )
{
/*
note that thisd2 is a mesure of distance in real space
So here we look around an arbitary current point and take note if
the distance between the centre point and points one unit away from
it (all directions) is less than a certain cuttoff distance. We
are left with a list of ndn neighbouring cells that are
sufficicently close to be considered neighbours.
Typically, ndn will be 18-20 at then end of this block.
Note that body diagonals have length sqrt(3) ~= 1.73, but we passed
squared limits.
*/
clipper::Cell_descr rcd( map.cell().descr() );
clipper::Cell_descr vcd( 1.0,1.0,1.0, rcd.alpha(), rcd.beta(), rcd.gamma() );
clipper::Cell vcell( vcd );
clipper::Coord_grid g0(-1,-1,-1);
clipper::Coord_grid g1( 1, 1, 1);
clipper::Grid_sampling vgrid( 1, 1, 1 );
clipper::Coord_grid iu, iv, iw;
float thisd2;
for ( iu = g0; iu.u() <= g1.u(); iu.u()++ ) {
for ( iv = iu; iv.v() <= g1.v(); iv.v()++ ) {
for ( iw = iv; iw.w() <= g1.w(); iw.w()++ ) {
thisd2 = iw.coord_frac( vgrid ).lengthsq( vcell );
if (thisd2 > min_distsq && thisd2 < max_distsq) nlist.push_back( iw );
}
}
}
}
Skeleton_basic::NCube::NCube( const int& n )
{
m = clipper::Grid_range( clipper::Coord_grid( -n, -n, -n ),
clipper::Coord_grid( n, n, n ) );
data.resize( m.size() );
}
bool Skeleton_basic::operator() ( clipper::Xmap<int>& xskl, const clipper::Xmap<float>& xmap ) const
{
std::vector<int> index;
clipper::Xmap<float>::Map_reference_index ix;
/* now get the map in sorted order.
We only sort those points which are to be considered, i.e. non-zero */
for ( ix = xmap.first(); !ix.last(); ix.next() )
if ( xskl[ix] > 0 )
index.push_back( ix.index() );
Map_index_sort::sort_increasing( xmap, index );
/* make neighbours
The neighbours of a point are the other grid points which are
'near' it. The exact choice depends on the grid geometry. The
cutoff is chosen to give 18-20 neighbours. For a cubic grid,
these are a 3x3x3 cube without the vertices, for a hex grid they
are a hexagonal cylinder. */
Skeleton_basic::Neighbours neigh( xmap );
/* make the skeleton map. This will contain:
0 for non-skeleton grids (inter ridge spaces)
1 for untested grids
1 for skeleton grids (ridges)
(The untested and skeleton grids can have the same value,
because the untested ones are still in the index).
We loop through point in order, starting with the lowest
and decide whether each one is part of the skeleton. */
for ( int i = 0; i < index.size(); i++ )
if ( !isInSkel( xskl, xskl.coord_of(index[i]), neigh, box_ ) )
xskl.set_data( index[ i ], 0 );
return true;
}
bool Skeleton_basic::isInSkel( const clipper::Xmap<int>& xskl, const clipper::Coord_grid& c, const Skeleton_basic::Neighbours& neigh, const int& box )
{
Skeleton_basic::NCube cube( box ); // 1 or 2? Look at the results to decide.
/* Fill the cube with flags Each non-rejected grid point is given
its own number. We will the reduce these to 'region numbers', so
that each connected region takes the value of one of its
neighbours. (A performace benefit is gaine from allocating these
in decreasing order). */
clipper::Coord_grid g0 = c + cube.grid().min();
clipper::Coord_grid g1 = c + cube.grid().max();
clipper::Xmap_base::Map_reference_coord i0, iu, iv, iw;
i0 = clipper::Xmap<int>::Map_reference_coord( xskl, g0 );
int i = cube.grid().size();
for ( iu = i0; iu.coord().u() <= g1.u(); iu.next_u() )
for ( iv = iu; iv.coord().v() <= g1.v(); iv.next_v() )
for ( iw = iv; iw.coord().w() <= g1.w(); iw.next_w() )
cube[ iw.coord() - c ] = ( xskl[iw] > 0 ) ? i-- : 0;
// the centre cannot be a link - set to zero
cube[ clipper::Coord_grid(0,0,0) ] = 0;
/* The following is a simple optimisation which could be omitted.
We count the number of neightbours or the centre point which are
not yet eliminated from the skeleton. If this is more than 14 or
less than 1, then this pint cannot be part of the skeleton. */
int nneigh = 0;
for ( i = 0; i < neigh.size(); i++ )
if ( cube[neigh[i]] > 0 ) nneigh++;
if ( nneigh > 14 ) return false;
if ( nneigh < 1 ) return false;
/* Now reduce the flags to connected regions. We consider each
point in turn, and replace it with the highest value of any of
its neighbours. This is repeated until no points change. When
this occurs, each connected region will be set to the largest
value of any of its initial members. */
int val, nchg;
do {
nchg = 0;
clipper::Coord_grid u, v, w, x;
for ( u = cube.grid().min(); u.u() <= cube.grid().max().u(); u.u()++ )
for ( v = u; v.v() <= cube.grid().max().v(); v.v()++ )
for ( w = v; w.w() <= cube.grid().max().w(); w.w()++ ) {
val = cube[w];
if ( val != 0 ) {
for ( i = 0; i < neigh.size(); i++ ) {
x = w + neigh[i];
if ( cube.grid().in_grid( x ) )
if ( cube[x] > val ) val = cube[x];
}
if ( val > cube[w] ) {
cube[w] = val;
nchg++;
}
}
}
} while ( nchg > 0 );
/* The following code uses an STL set to count the number of different,
non-zero numbers in the region bordering the centre of the cube */
std::set<int> uniqnbrs;
for ( i = 0; i < neigh.size(); i++ ) {
const int& val = cube[neigh[i]];
if ( val > 0 ) uniqnbrs.insert( val );
}
return (uniqnbrs.size() > 1);
}
// Skeleton_fast
template <class T1, class T2> Skeleton_fast<T1,T2>::Neighbours::Neighbours( const clipper::Xmap_base &map, const float min_distsq, const float max_distsq )
{
/*
note that thisd2 is a mesure of distance in real space
So here we look around an arbitary current point and take note if
the distance between the centre point and points one unit away from
it (all directions) is less than a certain cuttoff distance. We
are left with a list of ndn neighbouring cells that are
sufficicently close to be considered neighbours.
Typically, ndn will be 18-20 at then end of this block.
Note that body diagonals have length sqrt(3) ~= 1.73, but we passed
squared limits.
*/
clipper::Cell_descr rcd( map.cell().descr() );
clipper::Cell_descr vcd( 1.0,1.0,1.0, rcd.alpha(), rcd.beta(), rcd.gamma() );
clipper::Cell vcell( vcd );
clipper::Coord_grid g0(-1,-1,-1);
clipper::Coord_grid g1( 1, 1, 1);
clipper::Grid_sampling vgrid( 1, 1, 1 );
clipper::Coord_grid iu, iv, iw;
float thisd2;
for ( iu = g0; iu.u() <= g1.u(); iu.u()++ ) {
for ( iv = iu; iv.v() <= g1.v(); iv.v()++ ) {
for ( iw = iv; iw.w() <= g1.w(); iw.w()++ ) {
thisd2 = iw.coord_frac( vgrid ).lengthsq( vcell );
if (thisd2 > min_distsq && thisd2 < max_distsq) nlist.push_back( iw );
}
}
}
}
template<class T1, class T2> bool Skeleton_fast<T1,T2>::operator() ( clipper::Xmap<T1>& xskl, const clipper::Xmap<T2>& xmap ) const
{
std::vector<int> index;
Xmap_base::Map_reference_index ix;
/* now get the map in sorted order.
We only sort those points which are to be considered, i.e. non-zero */
for ( ix = xmap.first(); !ix.last(); ix.next() )
if ( xskl[ix] > 0 )
index.push_back( ix.index() );
Map_index_sort::sort_increasing( xmap, index );
/* make neighbours
The neighbours of a point are the other grid points which are
'near' it. The exact choice depends on the grid geometry. The
cutoff is chosen to give 18-20 neighbours. For a cubic grid,
these are a 3x3x3 cube without the vertices, for a hex grid they
are a hexagonal cylinder. */
neigh = Neighbours( xmap );
/* make the skeleton map. This will contain:
0 for non-skeleton grids (inter ridge spaces)
1 for untested grids
1 for skeleton grids (ridges)
(The untested and skeleton grids can have the same value,
because the untested ones are still in the index).
We loop through point in order, starting with the lowest
and decide whether each one is part of the skeleton. */
for ( int i = 0; i < index.size(); i++ )
if ( !isInSkel( xskl, xskl.coord_of(index[i]) ) )
xskl.set_data( index[ i ], 0 );
return true;
}
template<class T1, class T2> bool Skeleton_fast<T1,T2>::isInSkel( const clipper::Xmap<T1>& xskl, const clipper::Coord_grid& c ) const
{
int dx, dy, dz;
/* Fill the cube with flags Each non-rejected grid point is given
its own number. We will the reduce these to 'region numbers', so
that each connected region takes the value of one of its
neighbours. (A performace benefit is gaine from allocating these
in decreasing order). */
clipper::Xmap_base::Map_reference_index ix( xskl, c );
for ( dz = 0; dz < 3; dz++ )
for ( dy = 0; dy < 3; dy++ )
for ( dx = 0; dx < 3; dx++ )
cube[dx][dy][dz] = xskl.get_data( ix.index_offset( dx-1, dy-1, dz-1 ) );
// the centre cannot be a link - set to zero
cube[1][1][1] = 0;
/* The following is a simple optimisation which could be omitted.
We count the number of neightbours or the centre point which are
not yet eliminated from the skeleton. If this is more than 14 or
less than 1, then this pint cannot be part of the skeleton. */
int nneigh = 0;
for ( int i = 0; i < neigh.size(); i++ ) {
dx = neigh[i].u()+1;
dy = neigh[i].v()+1;
dz = neigh[i].w()+1;
if ( cube[dx][dy][dz] > 0 ) nneigh++;
}
if ( nneigh > 14 ) return false;
if ( nneigh < 1 ) return false;
/* Now alter flags for one connected region. If all flags are
altered, then this point is not part of the skeleton. */
for ( int i = 0; i < neigh.size(); i++ ) {
dx = neigh[i].u()+1;
dy = neigh[i].v()+1;
dz = neigh[i].w()+1;
if ( cube[dx][dy][dz] > 0 ) break;
}
flood_cube( dx, dy, dz );
bool res2 = false;
for ( int i = 0; i < neigh.size(); i++ ) {
dx = neigh[i].u()+1;
dy = neigh[i].v()+1;
dz = neigh[i].w()+1;
if ( cube[dx][dy][dz] > 0 ) return true;
}
return false;
}
template<class T1, class T2> void Skeleton_fast<T1,T2>::flood_cube( const int x, const int y, const int z ) const
{
cube[x][y][z] = -1;
for ( int i = 0; i < neigh.size(); i++ ) {
int dx = x + neigh[i].u();
if ( dx >= 0 && dx < 3 ) {
int dy = y + neigh[i].v();
if ( dy >= 0 && dy < 3 ) {
int dz = z + neigh[i].w();
if ( dz >= 0 && dz < 3 )
if ( cube[dx][dy][dz] > 0 )
flood_cube( dx, dy, dz );
}
}
}
}
// template instantiations
template class Skeleton_fast<char,float>;
template class Skeleton_fast<char,double>;
template class Skeleton_fast<short,float>;
template class Skeleton_fast<short,double>;
template class Skeleton_fast<int,float>;
template class Skeleton_fast<int,double>;
} // namespace clipper
|
b602e14c5f6a93219251f73378c298a53bbeb1d6
|
536b21ab1ebacc907a2435c667756240f48a0cb2
|
/C&C++ Project File/OnlineJudge/OnlineJudge/BAEKJOON/Step by Step/[9] Sort/[5] SortInside.cpp
|
4acb01526c0cff2dd65e994ffe22d9ffdf3d3e79
|
[] |
no_license
|
IRONAGE-Park/online-judge
|
e3d9f37cc93182b81a16912efae912fe46a7cc9e
|
724a7a301ecd6226fe78b916662c44b88866d9c0
|
refs/heads/master
| 2022-03-09T22:19:18.947225
| 2019-01-20T19:05:17
| 2019-01-20T19:05:17
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 401
|
cpp
|
[5] SortInside.cpp
|
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
bool compare(int a, int b) {
return a > b;
}
int main() {
string num;
cin >> num;
vector<int> array;
for (int i = 0; i < num.length(); i++) {
array.push_back(num[i] - 48);
}
sort(array.begin(), array.end(), compare);
for (int i = 0; i < array.size(); i++) {
cout << array[i];
}
return 0;
}
|
ffbb55dec61ddef41859b4c4cb393c3278a019da
|
540bf26df5570f7dfe9f3dca52769bdc594dbaa5
|
/src/game/server/in/director_battery_spawn.cpp
|
2ecfbf4b7cb9552736034adee15ec9008617064a
|
[] |
no_license
|
InfoSmart/InSource-Singleplayer
|
c7a8e0de648c4fafcebc4d7ec78e46ad8afd742c
|
55e6fb30252d5ff4d19fb7c9d146bfec56055ad4
|
refs/heads/master
| 2021-01-17T05:46:39.867026
| 2013-07-07T06:13:41
| 2013-07-07T06:13:41
| 7,018,102
| 2
| 0
| null | null | null | null |
ISO-8859-1
|
C++
| false
| false
| 3,149
|
cpp
|
director_battery_spawn.cpp
|
//=====================================================================================//
//
// Creador de baterias
//
// Entidad que trabajara en conjunto con Director para la creación de baterias según
// el nivel y estres del jugador.
//
// Inspiración: Left 4 Dead 2
// InfoSmart 2013. Todos los derechos reservados.
//=====================================================================================//
#include "cbase.h"
#include "director_base_spawn.h"
#include "director_battery_spawn.h"
#include "director.h"
#include "items.h"
#include "in_utils.h"
#include "tier0/memdbgon.h"
//=========================================================
// Definición de variables de configuración.
//=========================================================
ConVar director_min_energy_tospawn_battery("director_min_energy_tospawn_battery", "80", 0, "Energia minima para la creación de baterias.");
#define ITEM_NAME "director_battery"
#define MINHEALTH_EASY director_min_energy_tospawn_battery.GetInt()
#define MINHEALTH_MEDIUM ( MINHEALTH_EASY - 20 )
#define MINHEALTH_HARD ( MINHEALTH_MEDIUM - 10 )
//=========================================================
// Guardado y definición de datos
//=========================================================
LINK_ENTITY_TO_CLASS( director_battery_spawn, CDirectorBatterySpawn );
BEGIN_DATADESC( CDirectorBatterySpawn )
END_DATADESC();
//=========================================================
// Guardar los objetos necesarios en caché.
//=========================================================
void CDirectorBatterySpawn::Precache()
{
UTIL_PrecacheOther("item_battery");
BaseClass::Precache();
}
//=========================================================
//=========================================================
void CDirectorBatterySpawn::Make()
{
// Desactivado.
if ( Disabled )
return;
if ( !MaySpawn() )
return;
// Creamos la bateria.
CItem *pItem = (CItem *)CreateEntityByName("item_battery");
// Hubo un problema al crear el objeto.
if ( !pItem )
{
DevWarning("[DIRECTOR BATTERY MAKER] Ha ocurrido un problema al crear la bateria.");
return;
}
Vector origin;
if ( !CanSpawn(pItem, &origin) )
return;
QAngle angles = GetAbsAngles();
// Lugar de creación.
pItem->SetAbsOrigin(origin);
// Nombre de la entidad.
pItem->SetName(MAKE_STRING(ITEM_NAME));
pItem->SetAbsAngles(angles);
// Creamos la bateria, le decimos quien es su dios (creador) y lo activamos.
DispatchSpawn(pItem);
pItem->SetOwnerEntity(this);
pItem->Activate();
}
//=========================================================
//=========================================================
bool CDirectorBatterySpawn::MaySpawn()
{
CDirector *pDirector = Director();
switch ( GameRules()->GetSkillLevel() )
{
// Fácil
case SKILL_EASY:
if ( UTIL_GetPlayersBattery() < MINHEALTH_EASY )
return true;
break;
// Normal
case SKILL_MEDIUM:
if ( UTIL_GetPlayersBattery() < MINHEALTH_MEDIUM )
return true;
break;
// Dificil
case SKILL_HARD:
if ( UTIL_GetPlayersBattery() < MINHEALTH_HARD )
return true;
break;
}
return false;
}
|
e7c5c809be728c18516121561aa975d3ba3469e5
|
bdc9b0972c241b12637abc8602c59ae1bffcde44
|
/apps/sfbds/statehash.h
|
35397f9632645a5f2452407063450b56645aa9be
|
[
"MIT"
] |
permissive
|
carolyn-y/hog2
|
eb0a3361b0d9247d1b7a4891fc1e1095b3eabf44
|
96616b40f4173959b127011c76f3e649688e1a99
|
refs/heads/master
| 2023-07-09T05:28:49.342432
| 2015-08-19T22:00:37
| 2015-08-19T22:00:37
| 277,397,436
| 0
| 0
|
MIT
| 2020-08-13T16:17:02
| 2020-07-05T23:02:04
| null |
UTF-8
|
C++
| false
| false
| 623
|
h
|
statehash.h
|
// definition of hash functions for a state, i.e. a tuple of vertices
#ifndef SFBDS_STATE_HASH
#define SFBDS_STATE_HASH
/*
notes:
- define SFBDS_LITTLE_ENDIAN if you have an akward machine
- for state=graphState we support a maximum of 2^32 vertices
- for state=xyLoc we support maximal dimensions of 2^16 x 2^16
- for state=PancakePuzzleState up to a maximal size of 12 pancakes
*/
//#define SFBDS_LITTLE_ENDIAN
#include <stdint.h>
template<class state>
uint64_t sfbds_state_hash( state s1, state s2 );
template<class state>
uint64_t regular_state_hash( state s1 );
uint64_t factorial( int val );
#endif
|
29a9ed34cf09b0c444d477e706dfc14f24e339d5
|
1bac5efd5fddd18d3dc6260669e4299cd9f4adb0
|
/CS 235/Lab 4/Lab 04/LinkedList.h
|
3815769e44e495b6f356fcdd8b86eeb42200f207
|
[] |
no_license
|
dnybodan/Projects
|
832946405b7d0d1aced2497563e65c49f1dde61c
|
734b4647753577172a0b50e2d4f5e1cf678d45f0
|
refs/heads/master
| 2023-02-26T15:56:24.060380
| 2021-02-04T02:30:56
| 2021-02-04T02:30:56
| 211,124,642
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,270
|
h
|
LinkedList.h
|
#ifndef LINKED_LIST_H
#define LINKED_LIST_H
#include "LinkedListInterface.h"
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
template <typename T>
class LinkedList : public LinkedListInterface <T>
{
private:
public:
struct Node
{
//the data contained in the node
T data;
//pointer to next node
Node* next;
//creates a new node
// @param data is the data stored
Node(const T& d) : data(d), next(nullptr) {}
// Creates a new Node that points to another Node
// @param data the data stored
// @param nextPtr pointer to next node
//Node(const T& data, Node* nextPtr = nullptr) : data(data), next(nextPtr) {}
};
size_t listSize = 0;
Node* head = nullptr;
LinkedList()
{
listSize = 0;
head = nullptr;
}
virtual ~LinkedList() { clear(); }
//Check if there is a duplicate node in linked list
//@param value is the value to check against existing nodes
//return bool true if duplicate found, return false if no duplicate is found
bool checkDuplicate(T value)
{
Node* temp = nullptr;
temp = head;
while (temp->data != value)
{
if (temp->next == nullptr)
{
return false;
}
temp = temp->next;
}
return true;
}
/** Insert Node at beginning of linked list (no duplicates) */
//@param value is value is the data to be instantiated with the new head
virtual bool insertHead(T value)
{
if (listSize == 0)
{
Node* newNode = new Node(value);
newNode->next = nullptr;
head = newNode;
listSize++;
return true;
}
if (listSize > 0)
{
if (checkDuplicate(value))
{
return false;
}
else
{
Node* newNode = new Node(value);
newNode->next = head;
head = newNode;
listSize++;
return true;
}
}
return false; //fixme
}
/** Insert Node at end of linked list (no duplicates) */
virtual bool insertTail(T value)
{
if (listSize == 0)
{
Node* newNode = new Node(value);
head = newNode;
head->next = nullptr;
listSize++;
return true;
}
if (listSize > 0)
{
if (checkDuplicate(value))
{
return false;
}
else
{
Node* temp = nullptr;
temp = head;
while (temp != nullptr)
{
if (temp->next == nullptr)
{
Node* newNode = new Node(value);
temp->next = newNode;
newNode->next = nullptr;
listSize++;
return true;
}
temp = temp->next;
}
}
}
return false;
}
/** Insert node after matchNode (no duplicates) */
virtual bool insertAfter(T matchNode, T node)
{
Node* temp = nullptr;
temp = head;
if (listSize == 0)
{
return false;
}
if (!(checkDuplicate(node)))
{
while (temp != nullptr)
{
if (temp->data == matchNode)
{
Node* newNode = new Node(node);
newNode->next = temp->next;
temp->next = newNode;
listSize++;
return true;
}
temp = temp->next;
}
}
return false;/*fixme*/
}
/** Remove Node from linked list */
virtual bool remove(T value)
{
Node *curr;
Node *prev;
curr = head;
prev = nullptr;
if (listSize == 0)
{
return false;
}
if (checkDuplicate(value))
{
while (curr != nullptr)
{
if (curr->data == value)
{
if (head == curr)
{
head = head->next;
//curr->next = NULL;
delete curr;
listSize--;
return true;
}
else
{
prev->next = curr->next;
curr->next = nullptr;
delete curr;
listSize--;
return true;
}
}
prev = curr;
curr = curr->next;
}
if (listSize == 1)
{
head->next = nullptr;
delete head;
listSize--;
return true;
}
if (listSize == 0)
{
head = nullptr;
}
return false;
}
return false;
}
/** Remove all Nodes from linked list */
virtual bool clear()
{
Node* temp = nullptr;
Node* prev = nullptr;
if (listSize == 0)
{
return true;
}
temp = head;
while (temp->next != nullptr)
{
prev = temp;
temp = temp->next;
delete prev;
}
delete temp;
head = nullptr;
listSize = 0;
return true;
}
/** Return Node at index (0 based) via value parameter
NOTE: STL list does NOT support the at accessor. */
virtual bool at(size_t index, std::string& value)
{
Node* curr = nullptr;
curr = head;
if (index >= (listSize) || index < 0)
{
throw out_of_range("Invalid Index");
return false;
}
for (size_t i = 0; i < index; i++)
{
curr = curr->next;
}
ostringstream os;
os << curr->data;
value = os.str();
return true;
}
/** Returns the number of nodes in the linked list */
virtual size_t size() const
{
return listSize;
}
/** Return a level order traversal of a Linked List as a string */
virtual std::string toString() const
{
ostringstream os;
Node* temp = nullptr;
temp = head;
if (listSize == 0)
{
return os.str();
}
os << temp->data;
temp = temp->next;
if (listSize == 1)
{
return os.str();
}
while (temp != nullptr)
{
os << " " << temp->data;
temp = temp->next;
}
return os.str();
}
/* return the toString() method whenever (<<) is used*/
friend ostream& operator<<(ostream& os, const LinkedList& LL)
{
os << LL.toString();
return os;
}
};
#endif //Linked List
|
2f682da983af3d7a0e161814800af123b6c3857e
|
0ba0b1d779fc9e4e3a06c0b78c4f7df0b9463bf4
|
/Source/Logic/Private/Scene/RenderView.cpp
|
31145066049bf15cc33c304fade841d7f7f9c200
|
[] |
no_license
|
xtozero/SSR
|
b2516297382940eb7d44500c0c5a331fe56a592b
|
7c4c3fb40154cbca794cac8486fc9da3c0cd4afb
|
refs/heads/master
| 2023-08-16T20:05:50.069134
| 2020-03-09T14:53:20
| 2020-03-09T14:53:20
| 32,936,541
| 21
| 1
| null | 2023-07-22T13:51:14
| 2015-03-26T15:45:06
|
C++
|
UTF-8
|
C++
| false
| false
| 1,807
|
cpp
|
RenderView.cpp
|
#include "stdafx.h"
#include "Scene/RenderView.h"
#include "common.h"
#include "Core/GameLogic.h"
#include "Render/IRenderer.h"
#include "Scene/ConstantBufferDefine.h"
using namespace DirectX;
void CRenderView::SetViewPort( IRenderer& renderer, const Viewport* viewPorts, int count )
{
renderer.SetViewports( viewPorts, count );
}
void CRenderView::SetScissorRects( IRenderer& renderer, const RECT* rects, int count )
{
renderer.SetScissorRects( rects, count );
}
void CRenderView::CreatePerspectiveFovLHMatrix( float fov, float aspect, float zNear, float zFar )
{
m_fov = fov;
m_aspect = aspect;
m_zNear = zNear;
m_zFar = zFar;
m_projectionMatrix = XMMatrixPerspectiveFovLH( fov, aspect, zNear, zFar );
}
void CRenderView::CreatePerspectiveFovRHMatrix( float fov, float aspect, float zNear, float zFar )
{
m_fov = fov;
m_aspect = aspect;
m_zNear = zNear;
m_zFar = zFar;
m_projectionMatrix = XMMatrixPerspectiveFovRH( fov, aspect, zNear, zFar );
}
void CRenderView::UpdataView( CGameLogic& gameLogic, RE_HANDLE viewProjBuffer )
{
IRenderer& renderer = gameLogic.GetRenderer( );
if ( ViewProjectionTrasform* pData = static_cast<ViewProjectionTrasform*>( renderer.LockBuffer( viewProjBuffer ) ) )
{
pData->m_view = XMMatrixTranspose( m_viewMatrix );
pData->m_projection = XMMatrixTranspose( m_projectionMatrix );
pData->m_invView = XMMatrixTranspose( XMMatrixInverse( nullptr, m_viewMatrix ) );
pData->m_invProjection = XMMatrixTranspose( XMMatrixInverse( nullptr, m_projectionMatrix ) );
renderer.UnLockBuffer( viewProjBuffer );
renderer.BindConstantBuffer( SHADER_TYPE::VS, static_cast<int>( VS_CONSTANT_BUFFER::VIEW_PROJECTION ), 1, &viewProjBuffer );
}
}
CRenderView::CRenderView( )
{
m_viewMatrix = XMMatrixIdentity( );
m_projectionMatrix = XMMatrixIdentity( );
}
|
c617bddaae1c514feca3ae8f9fe24a1355330124
|
2aa2aaa234b24a494b6cb77b74016e727e0f9e0c
|
/17.03/simple_class_inheritance.cpp
|
fe417dad0fd7350a82ce0f5c46c194bdc5460b19
|
[] |
no_license
|
mstfzbn/sdp-pm14
|
ad1191e066e51d49653ef423c9b0d09f7b48539e
|
ecbcfe7120670563f65baea955f9a5e2a757ab66
|
refs/heads/master
| 2020-04-06T04:39:10.293600
| 2014-06-04T05:21:24
| 2014-06-04T05:21:24
| 47,319,296
| 1
| 0
| null | 2015-12-03T08:43:02
| 2015-12-03T08:43:02
| null |
UTF-8
|
C++
| false
| false
| 1,201
|
cpp
|
simple_class_inheritance.cpp
|
#include<iostream>
#include<string>
#include <vector>
using namespace std;
class Person {
char name[100],gender[1];
int egn;
protected:
void hello(){cout<<"HELLO"<<endl;}
public:
Person(){cout<<"EMPTY"<<endl;}
Person(int e){
egn = e;
strcpy(name , "HELLO ! ");
strcpy(gender , " ");
}
Person(char *n, int e, char *g) {
strcpy(name , n);
egn = e;
strcpy(gender ,g);
}
char* get_name(){return name;}
void set_name(char * n) { strcpy(name , n);}
void set_egn(int e) {egn = e;}
int get_egn(){return egn;}
};
class Employee : public Person {
char job[100];
int income;
public:
Employee(char *n,int egn,char *g,char *j, int inc):Person(n,egn,g){
strcpy(job , j);
income =inc;
this->hello();
}
};
class Firm
{
public:
void add_employee(Employee *new_employee){
staff.push_back(new_employee);
}
private:
vector<Employee*> staff;
};
int main(){
char name[7] = "dancho" ;
char gender[2] = "m";
char job[8] = "teacher";
//Person me(name,921020,gender);
Employee me2(name,921020,gender,job,0);
Firm myFirm;
for(int i=0; i<4;i++){
Employee me3(name,921020,gender,job,i);
myFirm.add_employee(&me3);}
cout<<me2.get_egn()<<" "<<me2.get_name();
return 0;
}
|
a8af6fc407141f57bde99aee36319122572a250e
|
27721e886795df3e467756b8e0480f7afd6e66c4
|
/xtt/lib/glow/src/glow_conclass.h
|
1690a058b1352056fcf02c415254649abd387ab9
|
[] |
no_license
|
brunad-coder/proview
|
88722029f3614d0febc4a8e9e6dea4859cc87363
|
4d75b942c649b1da8797323fa40f7f20cff634f8
|
refs/heads/master
| 2020-07-15T14:52:59.275163
| 2020-03-02T23:40:11
| 2020-03-02T23:40:11
| 205,586,528
| 0
| 0
| null | 2019-08-31T19:15:34
| 2019-08-31T19:15:34
| null |
UTF-8
|
C++
| false
| false
| 4,548
|
h
|
glow_conclass.h
|
/*
* ProviewR Open Source Process Control.
* Copyright (C) 2005-2018 SSAB EMEA AB.
*
* This file is part of ProviewR.
*
* 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, either version 2 of
* the License, or (at your option) any later version.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with ProviewR. If not, see <http://www.gnu.org/licenses/>
*
* Linking ProviewR statically or dynamically with other modules is
* making a combined work based on ProviewR. Thus, the terms and
* conditions of the GNU General Public License cover the whole
* combination.
*
* In addition, as a special exception, the copyright holders of
* ProviewR give you permission to, from the build function in the
* ProviewR Configurator, combine ProviewR with modules generated by the
* ProviewR PLC Editor to a PLC program, regardless of the license
* terms of these modules. You may copy and distribute the resulting
* combined work under the terms of your choice, provided that every
* copy of the combined work is accompanied by a complete copy of
* the source code of ProviewR (the version used to produce the
* combined work), being distributed under the terms of the GNU
* General Public License plus this exception.
*/
#ifndef glow_conclass_h
#define glow_conclass_h
#include "glow_rect.h"
/*! \file glow_conclass.h
\brief Contains the GlowConClass class. */
/*! \addtogroup Glow */
/*@{*/
//! Class object for connections.
/*! The GlowConClass object contains the definition of a connection style.
Every GlowCon connection belongs to a connection class, which the color,
linewidth,
cornerstyle for the connection.
*/
class GlowConClass : public GlowArrayElem {
public:
//! Constructor
/*!
\param glow_ctx Glow context.
\param name Conclass name.
\param contype Type of connection.
\param cornertype Type of corner, rounded or straight.
\param d_type Color.
\param line_w Line width.
\param arrow_w Width of arrow.
\param arrow_l Length of arrow.
\param round_corner_amnt The size of the arcs in rounded corners.
\param grp Group a connection is a member of.
*/
GlowConClass(GrowCtx* glow_ctx, const char* name, glow_eConType contype,
glow_eCorner cornertype, glow_eDrawType d_type, int line_w,
double arrow_w = 0, double arrow_l = 0, double round_corner_amnt = 0.5,
glow_eConGroup grp = glow_eConGroup_Common);
friend std::ostream& operator<<(std::ostream& o, const GlowConClass cc);
void zoom(){}
void nav_zoom(){}
void print_zoom(){}
void traverse(int x, int y){}
void get_borders(double pos_x, double pos_y, double* x_right, double* x_left,
double* y_high, double* y_low, void* node){}
int event_handler(void* pos, glow_eEvent event, int x, int y, void* node)
{
return 0;
}
void print(GlowPoint* pos, void* node){}
//! Save the content of the object to file.
/*!
\param fp Ouput file.
\param mode Not used.
*/
void save(std::ofstream& fp, glow_eSaveMode mode);
//! Read the content of the object from file.
/*!
\param fp Input file.
*/
void open(std::ifstream& fp);
void draw(GlowPoint* pos, int highlight, int hot, void* node){}
void nav_draw(GlowPoint* pos, int highlight, void* node){}
void erase(GlowPoint* pos, int hot, void* node){}
void nav_erase(GlowPoint* pos, void* node){}
//! Get the object type
/*!
\return The type of the object.
*/
glow_eObjectType type()
{
return glow_eObjectType_ConClass;
}
//! Conversion between different versions of Glow
/*!
\param version Version to convert to.
*/
void convert(glow_eConvert version);
GrowCtx* ctx; //!< Glow ctx.
GlowPoint zero;
glow_eConType con_type; //!< Connection type.
glow_eCorner corner; //!< Type of corners, rounded or straight.
glow_eDrawType draw_type; //!< Connection color.
int line_width; //!< Line width.
double arrow_width; //!< Width of arrow.
double arrow_length; //!< Length of arrow.
double round_corner_amount; //!< The size of the arcs in rounded corners.
glow_eConGroup group; //!< The group a connection belongs to.
};
/*@}*/
#endif
|
633adc99eb253603470c3eb87ef7dc31e8fdb2fd
|
180330a85e885300a260cccc3ffd7b39ec67d98d
|
/DontTouch.ino
|
3f761a547ff578a2e0385d7ee6acd38d630315fb
|
[] |
no_license
|
kahodesu/DontTouch
|
ad6c9ce8a297a0a38ca703d18b1c871a7431826e
|
537c5e616c7a8006d3f3b320bb317bf6d56a7979
|
refs/heads/master
| 2021-01-01T15:54:48.986727
| 2014-12-06T05:30:54
| 2014-12-06T05:30:54
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,553
|
ino
|
DontTouch.ino
|
/////////////////////////////////////////
/// Glove Code for Don't Touch game ///
/// by Ramsey Nasser & Kaho for ///
/// 3D Leap Motion Game Jam 2014 ///
/////////////////////////////////////////
/*
Based on following examples:
-- String to Integer conversion by Tom Igoe
*/
////////////////LIBRARIES////////////////
#include <Adafruit_NeoPixel.h>
////////////////VAIRABLES////////////////
#define PIN 6
Adafruit_NeoPixel strip = Adafruit_NeoPixel(23, PIN, NEO_GRB + NEO_KHZ800);
String inString = ""; // string to hold input
int val;
int row1[] = {
0,1,2};
int row2[] = {
3,7,11,15,19};
int row3[] = {
4,8,12,16,20};
int row4[] = {
5,9,13,17,21};
int row5[] = {
6,10,14,18,22};
////////////////SET UP////////////////
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
// send an intro:
// Serial.println("\n\nString toInt():");
// Serial.println();
strip.begin();
strip.show(); // Initialize all pixels to 'off'
}
////////////////LOOPY SHIT////////////////
void loop() {
strip.show();
// colorWipe(strip.Color(0, 0, 255), 50, 20); // Blue
// Read serial input:
while (Serial.available() > 0) {
int inChar = Serial.read();
// if you get a newline, print the string,
// then the string's value:
if (inChar == '\n') {
val = 0;
val = inString.toInt();
inString = "";
} else {
inString += (char)inChar;
}
}
if (val > 0 && val <= 50) {
for (int i = 0; i<3; i++){
colorWipe(strip.Color(0, 0, map(val,1, 50, 0, 255)), 50, row1[i]); // Blue
}
for (int i = 0; i<5; i++){
colorWipe(strip.Color(0, 0, 0), 50, row2[i]); // Blue
}
for (int i = 0; i<5; i++){
colorWipe(strip.Color(0, 0, 0), 50, row3[i]); // Blue
}
for (int i = 0; i<5; i++){
colorWipe(strip.Color(0, 0, 0), 50, row4[i]); // Blue
}
for (int i = 0; i<5; i++){
colorWipe(strip.Color(0, 0, 0), 50, row5[i]); // Blue
}
}
else if (val> 50 && val <= 101) {
for (int i = 0; i<3; i++){
colorWipe(strip.Color(0, 0, 255), 50, row1[i]); // Blue
}
for (int i = 0; i<5; i++){
colorWipe(strip.Color(0, 0, map(val, 51, 101, 0, 255)), 50, row2[i]); // Blue
}
for (int i = 0; i<5; i++){
colorWipe(strip.Color(0, 0, 0), 50, row3[i]); // Blue
}
for (int i = 0; i<5; i++){
colorWipe(strip.Color(0, 0, 0), 50, row4[i]); // Blue
}
for (int i = 0; i<5; i++){
colorWipe(strip.Color(0, 0, 0), 50, row5[i]); // Blue
}
}
else if (val> 101 && val <= 152) {
for (int i = 0; i<3; i++){
colorWipe(strip.Color(0, 0, 255), 50, row1[i]); // Blue
}
for (int i = 0; i<5; i++){
colorWipe(strip.Color(0, 0, 255), 50, row2[i]); // Blue
}
for (int i = 0; i<5; i++){
colorWipe(strip.Color(0, 0, map(val,102, 152, 0, 255)), 50, row3[i]); // Blue
}
for (int i = 0; i<5; i++){
colorWipe(strip.Color(0, 0, 0), 50, row4[i]); // Blue
}
for (int i = 0; i<5; i++){
colorWipe(strip.Color(0, 0, 0), 50, row5[i]); // Blue
}
}
else if (val> 152 && val <= 203) {
for (int i = 0; i<3; i++){
colorWipe(strip.Color(0, 0, 255), 50, row1[i]); // Blue
}
for (int i = 0; i<5; i++){
colorWipe(strip.Color(0, 0, 255), 50, row2[i]); // Blue
}
for (int i = 0; i<5; i++){
colorWipe(strip.Color(0, 0, 255), 50, row3[i]); // Blue
}
for (int i = 0; i<5; i++){
colorWipe(strip.Color(0, 0, map(val,153, 203, 0, 255)), 50, row4[i]); // Blue
}
for (int i = 0; i<5; i++){
colorWipe(strip.Color(0, 0, 0), 50, row5[i]); // Blue
}
}
else if (val> 203 && val <= 255) {
for (int i = 0; i<3; i++){
colorWipe(strip.Color(0, 0, 255), 50, row1[i]); // Blue
}
for (int i = 0; i<5; i++){
colorWipe(strip.Color(0, 0, 255), 50, row2[i]); // Blue
}
for (int i = 0; i<5; i++){
colorWipe(strip.Color(0, 0, 255), 50, row3[i]); // Blue
}
for (int i = 0; i<5; i++){
colorWipe(strip.Color(0, 0, 255), 50, row4[i]); // Blue
}
for (int i = 0; i<5; i++){
colorWipe(strip.Color(0, 0, map(val,204, 255, 0, 255)),50 , row5[i]); // Blue
}
}
}
void colorWipe(uint32_t c, uint8_t wait, int i) {
strip.setPixelColor(i, c);
strip.show();
//delay(10);
}
|
703d7af2799bd28bb9a297cdd475015a58945e1b
|
514e453348f579457270c70b71eab1abfeaea1b3
|
/src/config/rgb-led-lighting-shield-conf.hpp
|
4178f7258e43b0a3e9fcbcc5213604b1f0e75912
|
[
"MIT"
] |
permissive
|
Infineon/rgb-led-lighting-shield
|
78418804823fcd6f5f34201f4213510ebe4ce779
|
cc8d00b339cecf8dac0b599e3b5ebfd1c9095e34
|
refs/heads/master
| 2023-05-09T07:23:40.879100
| 2021-06-02T12:53:52
| 2021-06-02T12:53:52
| 317,917,558
| 1
| 0
|
MIT
| 2021-06-02T12:53:53
| 2020-12-02T16:10:33
|
C++
|
UTF-8
|
C++
| false
| false
| 669
|
hpp
|
rgb-led-lighting-shield-conf.hpp
|
/**
* @file rgb-led-lighting-shield-conf.hpp
* @brief RGB LED LIGHTING SHIELD Library Configuration
* @date November 2020
* @copyright Copyright (c) 2020 Infineon Technologies AG
*
* SPDX-License-Identifier: MIT
*/
#ifndef RGB_LED_LIGHTING_SHIELD_CONF_HPP_
#define RGB_LED_LIGHTING_SHIELD_CONF_HPP_
#include "rgb-led-lighting-shield-opts.hpp"
/**
* @addtogroup rgbFramework
* @{
*/
#ifndef RGB_LED_LIGHTING_SHIELD_FRAMEWORK
#define RGB_LED_LIGHTING_SHIELD_FRAMEWORK RGB_LED_LIGHTING_SHIELD_FRMWK_ARDUINO
#endif
#include "rgb-led-lighting-shield-conf-dfl.hpp"
/**
* @}
*/
#endif /** RGB_LED_LIGHTING_SHIELD_CONF_HPP_ **/
|
d991b19c1c1830bc695284b89c048ddb33603f90
|
da31c36c03476c3b5db7deef1de7c29f3a4f7cab
|
/POO ed_prat_01-09-2020/main.cpp
|
852737611cb0888a56b16ec19e8895a813780a16
|
[] |
no_license
|
erickfigueiredo/praticas-estrutura-dados
|
58c4f593248f4b8ba456aab9c7366e84ff23f76d
|
b7bbfbe78d63a7934c70d3936f5fa66a6671a811
|
refs/heads/main
| 2023-02-04T21:18:46.590539
| 2020-12-21T18:15:12
| 2020-12-21T18:15:12
| 302,192,223
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,223
|
cpp
|
main.cpp
|
#include "Agenda.h"
int main()
{
int numCompromissos, numConsultas;
cin >> numCompromissos >> numConsultas;
Agenda ag;
//cerr << numCompromissos << numConsultas << endl;
//Le os compromissos
for (int i = 0; i < numCompromissos; i++)
{
string compr;
cin.ignore();
getline(cin, compr);
Data d;
Horario h;
cin >> d >> h;
//abaixo declaramos versoes constantes dos objetos data/horario e item agenda
//com o objetivo de testar se os metodos que nao deveriam modificar tais dados
//realmente estao funcionando com objetos constantes
const Data d2 = d;
const Horario h2 = h;
const ItemAgenda ia = ItemAgenda(compr, d2, h2);
//cerr << dia << mes << ano << hora << min << sec << compr << endl;
ag.inserirItem(ia);
}
//Como as consultas nao modificam o objeto da classe agenda, o codigo abaixo
//deve compilar e executar sem erros
const Agenda ag2 = ag;
for (int i = 0; i < numConsultas; i++)
{
Data d;
cin >> d;
const Data d2 = d;
cout << d2 << endl;
ag2.compromissosData(d2);
cout << endl;
}
return 0;
}
|
015b0e0197167a4f4ff3b7859e3aab85fb157ec6
|
b4d1fc90b1c88f355c0cc165d73eebca4727d09b
|
/tests/ceftests/test_request.h
|
904a00df8492b52d681d9ae63135355ecbf70849
|
[
"BSD-3-Clause"
] |
permissive
|
chromiumembedded/cef
|
f03bee5fbd8745500490ac90fcba45616a29be6e
|
f808926fbda17c7678e21f1403d6f996e9a95138
|
refs/heads/master
| 2023-09-01T20:37:38.750882
| 2023-08-31T17:16:46
| 2023-08-31T17:28:27
| 87,006,077
| 2,600
| 454
|
NOASSERTION
| 2023-07-21T11:39:49
| 2017-04-02T18:19:23
|
C++
|
UTF-8
|
C++
| false
| false
| 3,139
|
h
|
test_request.h
|
// Copyright (c) 2020 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#ifndef CEF_TESTS_CEFTESTS_TEST_REQUEST_H_
#define CEF_TESTS_CEFTESTS_TEST_REQUEST_H_
#pragma once
#include <string>
#include "include/base/cef_callback.h"
#include "include/cef_cookie.h"
#include "include/cef_frame.h"
#include "include/cef_request.h"
#include "include/cef_request_context.h"
#include "include/cef_resource_handler.h"
#include "include/cef_response.h"
namespace test_request {
// Stores all state passed to CefURLRequestClient.
struct State {
public:
// Number of times each callback is executed.
int upload_progress_ct_ = 0;
int download_progress_ct_ = 0;
int download_data_ct_ = 0;
int auth_credentials_ct_ = 0;
int request_complete_ct_ = 0;
// From OnUploadProgress.
int64_t upload_total_ = 0;
// From OnDownloadProgress.
int64_t download_total_ = 0;
// From OnDownloadData.
std::string download_data_;
// From OnRequestComplete.
CefRefPtr<CefRequest> request_;
cef_urlrequest_status_t status_ = UR_UNKNOWN;
cef_errorcode_t error_code_ = ERR_NONE;
CefRefPtr<CefResponse> response_;
bool response_was_cached_ = false;
};
using RequestDoneCallback = base::OnceCallback<void(const State& state)>;
struct SendConfig {
// Send using |frame_| or |request_context_| if non-nullptr.
// Sends using the global request context if both are nullptr.
CefRefPtr<CefFrame> frame_;
CefRefPtr<CefRequestContext> request_context_;
// The request to send.
CefRefPtr<CefRequest> request_;
// Returned via GetAuthCredentials if |has_credentials_| is true.
bool has_credentials_ = false;
std::string username_;
std::string password_;
};
// Send a request. |callback| will be executed on the calling thread after the
// request completes.
void Send(const SendConfig& config, RequestDoneCallback callback);
// Removes query and/or fragment components from |url|.
std::string GetPathURL(const std::string& url);
// Creates a new resource handler that returns the specified response.
CefRefPtr<CefResourceHandler> CreateResourceHandler(
CefRefPtr<CefResponse> response,
const std::string& response_data);
using CookieVector = std::vector<CefCookie>;
using CookieDoneCallback =
base::OnceCallback<void(const CookieVector& cookies)>;
// Retrieves all cookies from |manager| and executes |callback| upon completion.
// If |deleteCookies| is true the cookies will also be deleted.
void GetAllCookies(CefRefPtr<CefCookieManager> manager,
bool deleteCookies,
CookieDoneCallback callback);
// Retrieves URL cookies from |manager| and executes |callback| upon completion.
// If |deleteCookies| is true the cookies will also be deleted.
void GetUrlCookies(CefRefPtr<CefCookieManager> manager,
const CefString& url,
bool includeHttpOnly,
bool deleteCookies,
CookieDoneCallback callback);
} // namespace test_request
#endif // CEF_TESTS_CEFTESTS_TEST_REQUEST_H_
|
290e819ad48f23336c7dbdbac6c96718997e578c
|
a8a252e6f994981db99063915d68a11074cf4745
|
/Chart/ClientChart.h
|
f25b3f8bf36b6688f0d40cfdb15b46aaa23796c0
|
[] |
no_license
|
jhluo/EFM_Server
|
7f38716f62de8a84a4e016f81b601510cb977fc8
|
70dd7c67b54067f046d2ee3b773d65f17ac183fa
|
refs/heads/master
| 2021-01-12T08:26:11.237838
| 2017-03-14T21:43:29
| 2017-03-14T21:43:29
| 76,579,078
| 0
| 0
| null | 2016-12-21T02:33:56
| 2016-12-15T16:59:56
|
C++
|
UTF-8
|
C++
| false
| false
| 882
|
h
|
ClientChart.h
|
#ifndef CLIENTCHART_H
#define CLIENTCHART_H
#include <QObject>
#include <QChartView>
#include <QtCharts>
class AClient;
class ClientChart : public QChartView
{
Q_OBJECT
public:
ClientChart(AClient *pClient, QWidget *pParent=0);
~ClientChart();
private:
void createChart();
void mousePressEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void wheelEvent(QWheelEvent *event);
AClient *m_pClient;
QChart *m_pChart;
QLineSeries *m_pDataSeries;
bool m_CenterChart;
//these are used for mouse dragging
bool m_isMousePressed;
QPoint m_MousePressedPosition;
private slots:
void updateChart(const QDateTime &time, const int value);
void showContextMenu(const QPoint &pos);
void onCenterChartToggled(const bool enabled);
};
#endif // CLIENTCHART_H
|
d104f7fd4eef065be61e213fb1a25cb7cf820262
|
0ef4c8732fad76359494b0017a9aec17afdc0f08
|
/src/modelo/entidadUbicada/FactoryEntidadUbicada.h
|
0f6c849c1a0448e3be28c11ded101af746f7b3a3
|
[] |
no_license
|
nachonitz/Eclipsados-Servidor
|
c60e95f535dc130a40dc5c56848f90bb34a546a1
|
052afdc13368cdcb1e719af185b6b25a0fa5679a
|
refs/heads/master
| 2020-08-14T16:29:58.079813
| 2019-12-12T04:04:58
| 2019-12-12T04:04:58
| 215,198,713
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,241
|
h
|
FactoryEntidadUbicada.h
|
/*
* FactoryEntidadUbicada.h
*
* Created on: Sep 9, 2019
* Author: franco
*/
#ifndef SRC_MODELO_ENTIDADUBICADA_FACTORYENTIDADUBICADA_H_
#define SRC_MODELO_ENTIDADUBICADA_FACTORYENTIDADUBICADA_H_
#include "EntidadUbicada.h"
#include "dibujable/Personaje.h"
#include "dibujable/Enemigo.h"
#include "dibujable/elemento/Barril.h"
#include "dibujable/elemento/Caja.h"
#include "dibujable/elemento/CanioMetalico.h"
#include "dibujable/elemento/Cuchillo.h"
class FactoryEntidadUbicada {
public:
FactoryEntidadUbicada();
virtual ~FactoryEntidadUbicada();
EntidadUbicada* crearEntidadConPersonaje();
EntidadUbicada* crearEntidadConEnemigo(float horizontal, float vertical, int tipoEnemigo);
EntidadUbicada* crearEntidadConBoss(float horizontalLocal, float verticalLocal,float horizontalGlobal, float verticalGlobal);
EntidadUbicada* crearEntidadConBarril();
EntidadUbicada* crearEntidadConBarril(float horizontal, float vertical);
EntidadUbicada* crearEntidadConCuchillo(float horizontal, float vertical);
EntidadUbicada* crearEntidadConCanio(float horizontal, float vertical);
EntidadUbicada* crearEntidadConCaja(float horizontal, float vertical);
};
#endif /* SRC_MODELO_ENTIDADUBICADA_FACTORYENTIDADUBICADA_H_ */
|
4a9790c275bb4bcda9aa2691302a0750eeb88d38
|
7eefe46d8ffcc9e039f2b2bdf54f8099b8a3e486
|
/src/liboslexec/wide/wide_optrigonometric.cpp
|
6a8adb157bddec2dc4197199b7c22dfa6c4cd6f6
|
[
"BSD-3-Clause",
"CC-BY-4.0"
] |
permissive
|
luyatshimbalanga/OpenShadingLanguage
|
955b19cdae0648e4a46ea396ee98f8c613701a21
|
2120647911af732f0d12d70e2f7f4e1ebe8fadcb
|
refs/heads/master
| 2023-08-24T04:36:43.728182
| 2021-11-05T06:29:54
| 2021-11-05T06:29:54
| 410,814,717
| 0
| 0
|
BSD-3-Clause
| 2021-11-05T07:12:41
| 2021-09-27T09:06:43
|
C++
|
UTF-8
|
C++
| false
| false
| 15,903
|
cpp
|
wide_optrigonometric.cpp
|
// Copyright Contributors to the Open Shading Language project.
// SPDX-License-Identifier: BSD-3-Clause
// https://github.com/AcademySoftwareFoundation/OpenShadingLanguage
/////////////////////////////////////////////////////////////////////////
/// \file
///
/// Shader interpreter implementation of Trigonometric operations
/// NOTE: many functions are left as LLVM IR, but some are better to
/// execute from the library to take advantage of compiler's small vector
/// math library versions.
///
/////////////////////////////////////////////////////////////////////////
#include <cmath>
#include <OSL/oslconfig.h>
#include <OSL/batched_shaderglobals.h>
#include <OSL/dual.h>
#include <OSL/dual_vec.h>
#include <OSL/sfmath.h>
#include <OSL/wide.h>
#include <OpenImageIO/fmath.h>
OSL_NAMESPACE_ENTER
namespace __OSL_WIDE_PVT {
OSL_USING_DATA_WIDTH(__OSL_WIDTH)
#include "define_opname_macros.h"
#if OSL_FAST_MATH
// OIIO::fast_sin & OIIO::fast_cos are not vectorizing (presumably madd is interfering)
// so use regular sin which compiler should replace with its own fast version
#define __OSL_XMACRO_ARGS (sin , OIIO::fast_sin , OSL::fast_sin )
#include "wide_opunary_per_component_xmacro.h"
#define __OSL_XMACRO_ARGS (cos , OIIO::fast_cos , OSL::fast_cos )
#include "wide_opunary_per_component_xmacro.h"
#define __OSL_XMACRO_ARGS (tan , OIIO::fast_tan , OSL::fast_tan )
#include "wide_opunary_per_component_xmacro.h"
#define __OSL_XMACRO_ARGS (asin , OIIO::fast_asin , OSL::fast_asin)
#include "wide_opunary_per_component_xmacro.h"
#define __OSL_XMACRO_ARGS (acos , OIIO::fast_acos , OSL::fast_acos)
#include "wide_opunary_per_component_xmacro.h"
#define __OSL_XMACRO_ARGS (atan , OIIO::fast_atan , OSL::fast_atan)
#include "wide_opunary_per_component_xmacro.h"
#define __OSL_XMACRO_ARGS (atan2, OIIO::fast_atan2, OSL::fast_atan2)
#include "wide_opbinary_per_component_xmacro.h"
#define __OSL_XMACRO_ARGS (sinh , OIIO::fast_sinh , OSL::fast_sinh)
#include "wide_opunary_per_component_xmacro.h"
#define __OSL_XMACRO_ARGS (cosh , OIIO::fast_cosh , OSL::fast_cosh)
#include "wide_opunary_per_component_xmacro.h"
#define __OSL_XMACRO_ARGS (tanh , OIIO::fast_tanh , OSL::fast_tanh)
#include "wide_opunary_per_component_xmacro.h"
#else
// try it out and compare performance, maybe compile time flag
#define __OSL_XMACRO_ARGS (sin , sinf , OSL::sin )
#include "wide_opunary_per_component_xmacro.h"
#define __OSL_XMACRO_ARGS (cos , cosf , OSL::cos )
#include "wide_opunary_per_component_xmacro.h"
#define __OSL_XMACRO_ARGS (tan , tanf , OSL::tan )
#include "wide_opunary_per_component_xmacro.h"
#define __OSL_XMACRO_ARGS (asin , safe_asin , OSL::safe_asin )
#include "wide_opunary_per_component_xmacro.h"
#define __OSL_XMACRO_ARGS (acos , safe_acos , OSL::safe_acos )
#include "wide_opunary_per_component_xmacro.h"
#define __OSL_XMACRO_ARGS (atan , atanf , OSL::atan )
#include "wide_opunary_per_component_xmacro.h"
#define __OSL_XMACRO_ARGS (atan2, atan2f , OSL::atan2)
#include "wide_opbinary_per_component_xmacro.h"
#define __OSL_XMACRO_ARGS (sinh , sinhf , OSL::sinh )
#include "wide_opunary_per_component_xmacro.h"
#define __OSL_XMACRO_ARGS (cosh , coshf , OSL::cosh )
#include "wide_opunary_per_component_xmacro.h"
#define __OSL_XMACRO_ARGS (tanh , tanhf , OSL::tanh )
#include "wide_opunary_per_component_xmacro.h"
#endif
static OSL_FORCEINLINE void impl_sincos (float theta, float &rsine, float &rcosine) {
#if OSL_FAST_MATH
OIIO::fast_sincos(theta, &rsine, &rcosine);
#else
OIIO::sincos(theta, &rsine, &rcosine);
#endif
}
static OSL_FORCEINLINE void impl_sincos (Vec3 theta, Vec3 &rsine, Vec3 &rcosine) {
impl_sincos(theta.x, rsine.x, rcosine.x);
impl_sincos(theta.y, rsine.y, rcosine.y);
impl_sincos(theta.z, rsine.z, rcosine.z);
}
OSL_BATCHOP void
__OSL_OP3(sincos,Wf,Wf,Wf)
(void *theta_, void *rsine_, void *rcosine_)
{
OSL_FORCEINLINE_BLOCK
{
Wide<const float> wtheta(theta_);
Wide<float> wrsine(rsine_);
Wide<float> wrcosine(rcosine_);
OSL_OMP_PRAGMA(omp simd simdlen(__OSL_WIDTH))
for(int lane=0; lane < __OSL_WIDTH; ++lane) {
float theta = wtheta[lane];
float rsine;
float rcosine;
impl_sincos(theta, rsine, rcosine);
wrsine[lane] = rsine;
wrcosine[lane] = rcosine;
}
}
}
OSL_BATCHOP void
__OSL_MASKED_OP3(sincos,Wf,Wf,Wf)
(void *theta_, void *rsine_, void *rcosine_, unsigned int mask_value)
{
OSL_FORCEINLINE_BLOCK
{
Wide<const float> wtheta(theta_);
Masked<float> wrsine(rsine_, Mask(mask_value));
Masked<float> wrcosine(rcosine_, Mask(mask_value));
OSL_OMP_PRAGMA(omp simd simdlen(__OSL_WIDTH))
for(int lane=0; lane < __OSL_WIDTH; ++lane) {
float theta = wtheta[lane];
if (wrsine.mask()[lane]) {
float rsine;
float rcosine;
impl_sincos(theta, rsine, rcosine);
wrsine[ActiveLane(lane)] = rsine;
wrcosine[ActiveLane(lane)] = rcosine;
}
}
}
}
OSL_BATCHOP void
__OSL_OP3(sincos,Wdf,Wdf,Wf)
(void *theta_, void *rsine_, void *rcosine_)
{
OSL_FORCEINLINE_BLOCK
{
Wide<const Dual2<float>> wtheta(theta_);
Wide<Dual2<float>> wrsine(rsine_);
Wide<float> wrcosine(rcosine_);
OSL_OMP_PRAGMA(omp simd simdlen(__OSL_WIDTH))
for(int lane=0; lane < __OSL_WIDTH; ++lane) {
Dual2<float> theta = wtheta[lane];
float rsine;
float rcosine;
impl_sincos(theta.val(), rsine, rcosine);
wrsine[lane] = Dual2<float>(rsine, rcosine * theta.dx(), rcosine * theta.dy());
wrcosine[lane] = rcosine;
}
}
}
OSL_BATCHOP void
__OSL_MASKED_OP3(sincos,Wdf,Wdf,Wf)
(void *theta_, void *rsine_, void *rcosine_, unsigned int mask_value)
{
OSL_FORCEINLINE_BLOCK
{
Wide<const Dual2<float>> wtheta(theta_);
Masked<Dual2<float>> wrsine(rsine_, Mask(mask_value));
Masked<float> wrcosine(rcosine_, Mask(mask_value));
OSL_OMP_PRAGMA(omp simd simdlen(__OSL_WIDTH))
for(int lane=0; lane < __OSL_WIDTH; ++lane) {
Dual2<float> theta = wtheta[lane];
if (wrsine.mask()[lane]) {
float rsine;
float rcosine;
impl_sincos(theta.val(), rsine, rcosine);
wrsine[ActiveLane(lane)] = Dual2<float>(rsine, rcosine * theta.dx(), rcosine * theta.dy());
wrcosine[ActiveLane(lane)] = rcosine;
}
}
}
}
OSL_BATCHOP void
__OSL_OP3(sincos,Wdf,Wf,Wdf)
(void *theta_, void *rsine_, void *rcosine_)
{
OSL_FORCEINLINE_BLOCK
{
Wide<const Dual2<float>> wtheta(theta_);
Wide<float> wrsine(rsine_);
Wide<Dual2<float>> wrcosine(rcosine_);
OSL_OMP_PRAGMA(omp simd simdlen(__OSL_WIDTH))
for(int lane=0; lane < __OSL_WIDTH; ++lane) {
Dual2<float> theta = wtheta[lane];
float rsine;
float rcosine;
impl_sincos(theta.val(), rsine, rcosine);
wrsine[lane] = rsine;
wrcosine[lane] = Dual2<float>(rcosine, -rsine * theta.dx(), -rsine * theta.dy());
}
}
}
OSL_BATCHOP void
__OSL_MASKED_OP3(sincos,Wdf,Wf,Wdf)
(void *theta_, void *rsine_, void *rcosine_, unsigned int mask_value)
{
OSL_FORCEINLINE_BLOCK
{
Wide<const Dual2<float>> wtheta(theta_);
Masked<float> wrsine(rsine_, Mask(mask_value));
Masked<Dual2<float>> wrcosine(rcosine_, Mask(mask_value));
OSL_OMP_PRAGMA(omp simd simdlen(__OSL_WIDTH))
for(int lane=0; lane < __OSL_WIDTH; ++lane) {
Dual2<float> theta = wtheta[lane];
if (wrsine.mask()[lane]) {
float rsine;
float rcosine;
impl_sincos(theta.val(), rsine, rcosine);
wrsine[ActiveLane(lane)] = rsine;
wrcosine[ActiveLane(lane)] = Dual2<float>(rcosine, -rsine * theta.dx(), -rsine * theta.dy());
}
}
}
}
OSL_BATCHOP void
__OSL_OP3(sincos,Wdf,Wdf,Wdf)
(void *theta_, void *rsine_, void *rcosine_)
{
OSL_FORCEINLINE_BLOCK
{
Wide<const Dual2<float>> wtheta(theta_);
Wide<Dual2<float>> wrsine(rsine_);
Wide<Dual2<float>> wrcosine(rcosine_);
OSL_OMP_PRAGMA(omp simd simdlen(__OSL_WIDTH))
for(int lane=0; lane < __OSL_WIDTH; ++lane) {
Dual2<float> theta = wtheta[lane];
float rsine;
float rcosine;
impl_sincos(theta.val(), rsine, rcosine);
wrsine[lane] = Dual2<float>(rsine, rcosine * theta.dx(), rcosine * theta.dy());
wrcosine[lane] = Dual2<float>(rcosine, -rsine * theta.dx(), -rsine * theta.dy());
}
}
}
OSL_BATCHOP void
__OSL_MASKED_OP3(sincos,Wdf,Wdf,Wdf)
(void *theta_, void *rsine_, void *rcosine_, unsigned int mask_value)
{
OSL_FORCEINLINE_BLOCK
{
Wide<const Dual2<float>> wtheta(theta_);
Masked<Dual2<float>> wrsine(rsine_, Mask(mask_value));
Masked<Dual2<float>> wrcosine(rcosine_, Mask (mask_value));
OSL_OMP_PRAGMA(omp simd simdlen(__OSL_WIDTH))
for(int lane=0; lane < __OSL_WIDTH; ++lane) {
Dual2<float> theta = wtheta[lane];
if (wrsine.mask()[lane]) {
float rsine;
float rcosine;
impl_sincos(theta.val(), rsine, rcosine);
wrsine[ActiveLane(lane)] = Dual2<float>(rsine, rcosine * theta.dx(), rcosine * theta.dy());
wrcosine[ActiveLane(lane)] = Dual2<float>(rcosine, -rsine * theta.dx(), -rsine * theta.dy());
}
}
}
}
OSL_BATCHOP void
__OSL_OP3(sincos,Wv,Wv,Wv)
(void *theta_, void *rsine_, void *rcosine_)
{
OSL_FORCEINLINE_BLOCK
{
Wide<const Vec3> wtheta(theta_);
Wide<Vec3> wrsine(rsine_);
Wide<Vec3> wrcosine(rcosine_);
OSL_OMP_PRAGMA(omp simd simdlen(__OSL_WIDTH))
for(int lane=0; lane < __OSL_WIDTH; ++lane) {
Vec3 theta = wtheta[lane];
Vec3 rsine;
Vec3 rcosine;
impl_sincos(theta, rsine, rcosine);
wrsine[lane] = rsine;
wrcosine[lane] = rcosine;
}
}
}
OSL_BATCHOP void
__OSL_MASKED_OP3(sincos,Wv,Wv,Wv)
(void *theta_, void *rsine_, void *rcosine_, unsigned int mask_value)
{
OSL_FORCEINLINE_BLOCK
{
Wide<const Vec3> wtheta(theta_);
Masked<Vec3> wrsine(rsine_, Mask(mask_value));
Masked<Vec3> wrcosine(rcosine_, Mask(mask_value));
OSL_OMP_PRAGMA(omp simd simdlen(__OSL_WIDTH))
for(int lane=0; lane < __OSL_WIDTH; ++lane) {
Vec3 theta = wtheta[lane];
if (wrsine.mask()[lane]) {
Vec3 rsine;
Vec3 rcosine;
impl_sincos(theta, rsine, rcosine);
wrsine[ActiveLane(lane)] = rsine;
wrcosine[ActiveLane(lane)] = rcosine;
}
}
}
}
OSL_BATCHOP void
__OSL_OP3(sincos,Wdv,Wdv,Wv)
(void *theta_, void *rsine_, void *rcosine_)
{
OSL_FORCEINLINE_BLOCK
{
Wide<const Dual2<Vec3>> wtheta(theta_);
Wide<Dual2<Vec3>> wrsine(rsine_);
Wide<Vec3> wrcosine(rcosine_);
OSL_OMP_PRAGMA(omp simd simdlen(__OSL_WIDTH))
for(int lane=0; lane < __OSL_WIDTH; ++lane) {
Dual2<Vec3> theta = wtheta[lane];
Vec3 rsine;
Vec3 rcosine;
impl_sincos(theta.val(), rsine, rcosine);
wrsine[lane] = Dual2<Vec3>(rsine, rcosine * theta.dx(), rcosine * theta.dy());;
wrcosine[lane] = rcosine;
}
}
}
OSL_BATCHOP void
__OSL_MASKED_OP3(sincos,Wdv,Wdv,Wv)
(void *theta_, void *rsine_, void *rcosine_, unsigned int mask_value)
{
OSL_FORCEINLINE_BLOCK
{
Wide<const Dual2<Vec3>> wtheta(theta_);
Masked<Dual2<Vec3>> wrsine(rsine_, Mask(mask_value));
Masked<Vec3> wrcosine(rcosine_, Mask(mask_value));
OSL_OMP_PRAGMA(omp simd simdlen(__OSL_WIDTH))
for(int lane=0; lane < __OSL_WIDTH; ++lane) {
Dual2<Vec3> theta = wtheta[lane];
if (wrsine.mask()[lane]) {
Vec3 rsine;
Vec3 rcosine;
impl_sincos(theta.val(), rsine, rcosine);
wrsine[ActiveLane(lane)] = Dual2<Vec3>(rsine, rcosine * theta.dx(), rcosine * theta.dy());;
wrcosine[ActiveLane(lane)] = rcosine;
}
}
}
}
OSL_BATCHOP void
__OSL_OP3(sincos,Wdv,Wv,Wdv)
(void *theta_, void *rsine_, void *rcosine_)
{
OSL_FORCEINLINE_BLOCK
{
Wide<const Dual2<Vec3>> wtheta(theta_);
Wide<Vec3> wrsine(rsine_);
Wide<Dual2<Vec3>> wrcosine(rcosine_);
OSL_OMP_PRAGMA(omp simd simdlen(__OSL_WIDTH))
for(int lane=0; lane < __OSL_WIDTH; ++lane) {
Dual2<Vec3> theta = wtheta[lane];
Vec3 rsine;
Vec3 rcosine;
impl_sincos(theta.val(), rsine, rcosine);
wrsine[lane] = rsine;
wrcosine[lane] = Dual2<Vec3>(rcosine, -rsine * theta.dx(), -rsine * theta.dy());
}
}
}
OSL_BATCHOP void
__OSL_MASKED_OP3(sincos,Wdv,Wv,Wdv)
(void *theta_, void *rsine_, void *rcosine_, unsigned int mask_value)
{
OSL_FORCEINLINE_BLOCK
{
Wide<const Dual2<Vec3>> wtheta(theta_);
Masked<Vec3> wrsine(rsine_, Mask(mask_value));
Masked<Dual2<Vec3>> wrcosine(rcosine_, Mask(mask_value));
OSL_OMP_PRAGMA(omp simd simdlen(__OSL_WIDTH))
for(int lane=0; lane < __OSL_WIDTH; ++lane) {
Dual2<Vec3> theta = wtheta[lane];
if (wrsine.mask()[lane]) {
Vec3 rsine;
Vec3 rcosine;
impl_sincos(theta.val(), rsine, rcosine);
wrsine[ActiveLane(lane)] = rsine;
wrcosine[ActiveLane(lane)] = Dual2<Vec3>(rcosine, -rsine * theta.dx(), -rsine * theta.dy());
}
}
}
}
OSL_BATCHOP void
__OSL_OP3(sincos,Wdv,Wdv,Wdv)
(void *theta_, void *rsine_, void *rcosine_)
{
OSL_FORCEINLINE_BLOCK
{
Wide<const Dual2<Vec3>> wtheta(theta_);
Wide<Dual2<Vec3>> wrsine(rsine_);
Wide<Dual2<Vec3>> wrcosine(rcosine_);
OSL_OMP_PRAGMA(omp simd simdlen(__OSL_WIDTH))
for(int lane=0; lane < __OSL_WIDTH; ++lane) {
Dual2<Vec3> theta = wtheta[lane];
Vec3 rsine;
Vec3 rcosine;
impl_sincos(theta.val(), rsine, rcosine);
wrsine[lane] = Dual2<Vec3>(rsine, rcosine * theta.dx(), rcosine * theta.dy());;
wrcosine[lane] = Dual2<Vec3>(rcosine, -rsine * theta.dx(), -rsine * theta.dy());
}
}
}
OSL_BATCHOP void
__OSL_MASKED_OP3(sincos,Wdv,Wdv,Wdv)
(void *theta_, void *rsine_, void *rcosine_, unsigned int mask_value)
{
OSL_FORCEINLINE_BLOCK
{
Wide<const Dual2<Vec3>> wtheta(theta_);
Masked<Dual2<Vec3>> wrsine(rsine_, Mask(mask_value));
Masked<Dual2<Vec3>> wrcosine(rcosine_, Mask(mask_value));
OSL_OMP_PRAGMA(omp simd simdlen(__OSL_WIDTH))
for(int lane=0; lane < __OSL_WIDTH; ++lane) {
Dual2<Vec3> theta = wtheta[lane];
if (wrsine.mask()[lane]) {
Vec3 rsine;
Vec3 rcosine;
impl_sincos(theta.val(), rsine, rcosine);
wrsine[ActiveLane(lane)] = Dual2<Vec3>(rsine, rcosine * theta.dx(), rcosine * theta.dy());;
wrcosine[ActiveLane(lane)] = Dual2<Vec3>(rcosine, -rsine * theta.dx(), -rsine * theta.dy());
}
}
}
}
} // namespace __OSL_WIDE_PVT
OSL_NAMESPACE_EXIT
#include "undef_opname_macros.h"
|
06e5723cec47c4a4da9315d73597501f25327938
|
753a57645d0824a750fa07176bdf7e37369940f6
|
/Engine/Plugins/UnrealCS/Source/MonoPlugin/Private/GeneratedScriptLibraries/LevelStreamingAlwaysLoaded.script.h
|
aac9ed646751310f0e2d1a1af2f8dc17310f6c61
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
marynate/UnrealCS
|
5782c4dd1b3fe6e136dcee54ce430aabd97b70a4
|
de43f7e42ca037445202d59c8114fafc30e031ec
|
refs/heads/master
| 2021-01-19T13:01:35.048880
| 2017-02-22T02:18:33
| 2017-02-22T02:18:33
| 82,354,770
| 2
| 1
| null | 2017-02-18T02:17:07
| 2017-02-18T02:17:06
| null |
UTF-8
|
C++
| false
| false
| 333
|
h
|
LevelStreamingAlwaysLoaded.script.h
|
#pragma once
namespace UnrealEngine
{
class _ULevelStreamingAlwaysLoaded
{
static UClass* StaticClass(){return ULevelStreamingAlwaysLoaded::StaticClass();}
public:
static void BindFunctions()
{
mono_add_internal_call("UnrealEngine.ULevelStreamingAlwaysLoaded::StaticClass",(const void*)StaticClass);
}
}
;
}
|
140e8c50459236c1f8802432f36c98f21a5f57ca
|
8e4a3464a9cfb59466f7ce80b276e7ba87044bc7
|
/Code Storage/Windows/ComlayerUsage/TestComlayer/libraries/LibComLayer/LangLabEvent.h
|
10b4e86530b5296915ee87d416dcb6ce18e3f0b9
|
[] |
no_license
|
lilingshui/code-refrence
|
875daf6b69c6a1d0bb908e78cc718ccc967cf8e6
|
5bf07d09f12133a1fa10d8d3fb086f143f9f7c1e
|
refs/heads/master
| 2023-08-16T16:38:43.215233
| 2023-07-23T09:54:00
| 2023-07-23T09:54:00
| 26,759,907
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,475
|
h
|
LangLabEvent.h
|
#ifndef __LANGLABEVENT_H__
#define __LANGLABEVENT_H__
class CEventItem : public IEventItem
{
public:
CEventItem(DWORD cbRecycle, LPVOID lpvData, DWORD cbData) {
m_cbRecycle = cbRecycle;
m_lpvData = lpvData;
m_cbData = cbData;
}
virtual ~CEventItem(void) {
}
public:
virtual LPVOID GetData();
virtual DWORD GetLength();
DWORD GetRecycleLength();
protected:
DWORD m_cbRecycle;
LPVOID m_lpvData;
DWORD m_cbData;
};
class CEventManager : public IEventItemManager
{
public:
CEventManager(DWORD cbPoolSize);
virtual ~CEventManager(void);
public:
virtual void SetEventArrivedCallback(IEventManagerNotify* pCallback, LPVOID lpvUserValue);
virtual LONG AddRef();
virtual LONG Release();
virtual IEventItem* GetFreeEvent(DWORD cbSize);
virtual void PutPendingEvent(IEventItem* pEvent);
virtual void PutPendingEvent(LPCVOID lpcEvData, DWORD cbEventSize);
virtual IEventItem* GetPendingEvent();
virtual void RecycleEvent(IEventItem* pEvent);
protected:
IEventManagerNotify* m_pCallback;
LPVOID m_lpvUserValue;
CRITICAL_SECTION m_csCreate;
CRITICAL_SECTION m_csEvent;
CRITICAL_SECTION m_csPending;
HANDLE m_hEvent;
typedef std::list<CEventItem *> CEventList;
CEventList m_event;
LONG m_nRef;
DWORD m_cbPoolSize;
DWORD m_dwFreeSize;
DWORD m_dwGetPos;
DWORD m_dwPutPos;
LPBYTE m_pbPool;
CEventItem* GetFreeItem(DWORD cbEventSize);
void PutItem(CEventItem* pItem);
};
#endif //__LANGLABEVENT_H__
|
88447f324f1e32800ada70bcb900becd5977f6dc
|
8f8ede2d240cafa0b17f135c553a2ae64e6ea1bd
|
/voice/tts/test/ttslib/engine/nuance/TTS_PlatformAccessor_test.cpp
|
0f8f392b6f3f9282d8193b087130542b488306cc
|
[] |
no_license
|
hyCpp/MyDemo
|
176d86b720fbc9619807c2497fadb781f5dc4295
|
150c77ebe54fe7b7f60063e6488319d804a07d03
|
refs/heads/master
| 2020-03-18T05:33:37.338743
| 2019-03-10T04:21:01
| 2019-03-10T04:21:01
| 134,348,743
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,042
|
cpp
|
TTS_PlatformAccessor_test.cpp
|
/**
* Copyright @ 2014 - 2017 Suntec Software(Shanghai) Co., Ltd.
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are NOT permitted except as agreed by
* Suntec Software(Shanghai) Co., Ltd.
*
* 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.
*/
#include "stdafx.h"
#include "TTS_PlatformAccessor.h"
#include "TTS_File.h"
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "TTS_file_test.h"
#include <stdio.h>
/**
* TTS_PlatformAccessor_test
*
* The class is just for TTS_PlatformAccessor_test.
*/
class TTS_PlatformAccessor_test : public testing::Test
{
public:
virtual void SetUp()
{
m_file = new TTS_File();
m_file->Open("/tmp/tts_access.txt", "w+");
std::string strcontent = "this is a test.";
m_file->Write(strcontent.c_str(), 1, strcontent.size());
m_access = new TTS_PlatformAccessor("suntec", m_file, 10);
}
virtual void TearDown()
{
if (NULL != m_access) {
delete m_access;
m_access = NULL;
}
}
private:
TTS_PlatformAccessor* m_access;
TTS_File* m_file;
};
TEST_F(TTS_PlatformAccessor_test, destruct_p_fileNULL)
{
m_access->m_pFile->Close();
delete m_access->m_pFile;
m_access->m_pFile = NULL;
}
TEST_F(TTS_PlatformAccessor_test, Exist_bothNULL)
{
if (NULL != m_access->m_pszName) {
delete m_access->m_pszName;
m_access->m_pszName = NULL;
}
bool bret = m_access->Exist(NULL);
EXPECT_FALSE(bret);
}
TEST_F(TTS_PlatformAccessor_test, Exist_m_pszNameNULL)
{
if (NULL != m_access->m_pszName) {
delete m_access->m_pszName;
m_access->m_pszName = NULL;
}
bool bret = m_access->Exist("hello");
EXPECT_FALSE(bret);
}
TEST_F(TTS_PlatformAccessor_test, Exist_False)
{
bool bret = m_access->Exist("hello");
EXPECT_FALSE(bret);
}
TEST_F(TTS_PlatformAccessor_test, Exist_pszNameNULL)
{
// if (NULL != m_access->m_pszName) {
// delete m_access->m_pszName;
// m_access->m_pszName = NULL;
// }
bool bret = m_access->Exist(NULL);
EXPECT_FALSE(bret);
}
TEST_F(TTS_PlatformAccessor_test, Exist)
{
// if (NULL != m_access->m_pszName) {
// delete m_access->m_pszName;
// m_access->m_pszName = NULL;
// }
bool bret = m_access->Exist("suntec");
EXPECT_TRUE(bret);
}
TEST_F(TTS_PlatformAccessor_test, Map_pdwBytesZero_m_dwFileSizeSmaller_pAddrNULL)
{
m_access->m_dwFileSize = 0;
m_access->m_workBuff.m_bInit = false;
m_access->m_pFile->Close();
m_access->Map(1, 0);
}
TEST_F(TTS_PlatformAccessor_test, Map_pdwBytesZero_m_dwFileSizeBigger_pAddrNULL)
{
m_access->m_dwFileSize = 10;
m_access->m_workBuff.m_bInit = false;
m_access->m_pFile->Close();
m_access->Map(1, 0);
}
TEST_F(TTS_PlatformAccessor_test, Map_pdwBytesNotZero_m_dwFileSizeBigger_pAddrNULL)
{
m_access->m_dwFileSize = 10;
m_access->m_workBuff.m_bInit = false;
m_access->m_pFile->Close();
m_access->Map(1, 1);
}
TEST_F(TTS_PlatformAccessor_test, Map_pdwBytesNotZero_m_dwFileSizeSmaller_pAddrNULL)
{
m_access->m_dwFileSize = 0;
m_access->m_workBuff.m_bInit = false;
m_access->m_pFile->Close();
m_access->Map(1, 1);
}
TEST_F(TTS_PlatformAccessor_test, Map_pAddrNULL_offsetBigger_addBigger)
{
m_access->m_dwFileSize = 100;
m_access->m_workBuff.m_bInit = true;
m_access->m_workBuff.m_fileOffset = 10;
m_access->m_pFile->Close();
m_access->Map(1, 1);
}
TEST_F(TTS_PlatformAccessor_test, Map_pAddrNULL_offsetsmaller_addsmaller)
{
m_access->m_dwFileSize = 10001;
m_access->m_workBuff.m_bInit = true;
m_access->m_workBuff.m_fileOffset = 0;
m_access->m_pFile->Close();
m_access->Map(5000, 5000);
}
TEST_F(TTS_PlatformAccessor_test, Map_SeekFalse)
{
m_access->m_dwFileSize = 100;
m_access->m_workBuff.m_bInit = false;
m_access->m_workBuff.m_fileOffset = 0;
m_access->m_pFile->Close();
m_access->Map(1, 1);
}
TEST_F(TTS_PlatformAccessor_test, Map_pdwBytesSmaller_GetMappedZero_ReadTrue)
{
m_access->m_dwFileSize = 100;
m_access->m_workBuff.m_bInit = false;
m_access->m_workBuff.m_fileOffset = 0;
// m_access->m_pFile->Close();
m_access->Map(1, 1);
}
TEST_F(TTS_PlatformAccessor_test, Map_pdwBytesSmaller_GetMappedZero_ReadFalse)
{
m_access->m_dwFileSize = 100;
m_access->m_workBuff.m_bInit = true;
m_access->m_workBuff.m_fileOffset = 0;
size_t iread = 0;
FUNC_FAKE_SINGRET_SET(fread, iread);
m_access->Map(1, 1);
FUNC_FAKE_RESET1(fread);
}
TEST_F(TTS_PlatformAccessor_test, Map_pdwBytesBigger_GetMappedZero)
{
m_access->m_dwFileSize = 10000;
m_access->m_workBuff.m_bInit = false;
m_access->Map(10, 5000);
}
TEST_F(TTS_PlatformAccessor_test, Map_pdwBytesSmaller_GetMappedNotZero)
{
m_access->m_dwFileSize = 10000;
m_access->m_workBuff.m_bInit = false;
m_access->m_workBuff.m_mapped = 1;
m_access->Map(10, 10);
}
TEST_F(TTS_PlatformAccessor_test, Map_pdwBytesSmaller_GetMappedNotZero_ReadFailed)
{
m_access->m_dwFileSize = 10000;
m_access->m_workBuff.m_bInit = false;
m_access->m_workBuff.m_mapped = 1;
size_t iread = 0;
FUNC_FAKE_SINGRET_SET(fread, iread);
m_access->Map(10, 10);
FUNC_FAKE_RESET1(fread);
}
TEST_F(TTS_PlatformAccessor_test, Unmap_CheckInBufferTrue)
{
unsigned char* buffer= m_access->m_workBuff.m_buffer + 2;
m_access->Unmap(buffer);
}
#if 0
// not safe, so noted
TEST_F(TTS_PlatformAccessor_test, Unmap_CheckInBufferFalse)
{
unsigned char* buffer = m_access->m_workBuff.m_buffer - 2;
m_access->Unmap(buffer);
}
#endif
TEST_F(TTS_PlatformAccessor_test, Unmap_GetBufferNULL)
{
m_access->m_workBuff.m_mapped = 10;
m_access->m_workBuff.GetBuffer();
}
/* EOF */
|
71b4ddd6a9cfd20811bbee1b8c91bd89a5c3f7d1
|
fe8c119cb323de5dd8223cd631eb015244807671
|
/NairnMPM/src/Materials/ExponentialTraction.cpp
|
b8c5d806760e7f40850c964829bdf271db7bdfdc
|
[] |
no_license
|
nairnj/nairn-mpm-fea
|
a5706d97b97276c04b39ea199bfc91201bb43f69
|
bee532cf2bda16b2fbb5f935aeb5bfb3e0d249d7
|
refs/heads/master
| 2023-08-18T02:59:50.899329
| 2023-08-12T16:17:08
| 2023-08-12T16:17:08
| 40,681,568
| 89
| 38
| null | 2018-10-31T16:46:25
| 2015-08-13T21:01:25
|
C++
|
UTF-8
|
C++
| false
| false
| 6,339
|
cpp
|
ExponentialTraction.cpp
|
/********************************************************************************
ExponentialTraction.cpp
nairn-mpm-fea
Created by John Nairn on 12/22/2020.
Copyright (c) 2020 John A. Nairn, All rights reserved.
This material used the scaled exponential law allowed in Abaqus
********************************************************************************/
#include "stdafx.h"
#include "Materials/ExponentialTraction.hpp"
extern double mtime;
#pragma mark ExponentialTraction::Constructors and Destructors
// Constructor
ExponentialTraction::ExponentialTraction(char *matName,int matID) : CohesiveZone(matName,matID)
{
// user must provide positive values
alphaI = -1.;
alphaII = -1.;
}
#pragma mark ExponentialTraction::Initialization
// Read properteis (read read in super classes)
char *ExponentialTraction::InputTractionLawProperty(char *xName,int &input,double &gScaling)
{
if(strcmp(xName,"alphaI")==0)
{ input=DOUBLE_NUM;
return((char *)&alphaI);
}
else if(strcmp(xName,"alphaII")==0)
{ input=DOUBLE_NUM;
return((char *)&alphaII);
}
return CohesiveZone::InputTractionLawProperty(xName,input,gScaling);
}
// Calculate properties used in analyses - here triangular law
// Do mode I and mode II separately
const char *ExponentialTraction::VerifyAndLoadProperties(int np)
{
if(alphaI<=0.)
return "Exponential cohesive laws must specify alphaI > 0";
expalphaI = exp(-alphaI);
romexpalphaI = 1./(1.-expalphaI);
double fealphaI = 2.*(1./alphaI - expalphaI*romexpalphaI);
const char *msg=SetExponentialTractionLaw(stress1,kI1,delIc,JIc,umidI,fealphaI);
if(msg!=NULL) return msg;
//cout << "# I: " << expalphaI << "," << romexpalphaI << "," << fealphaI << endl;
if(alphaII<=0.)
return "Exponential cohesive laws must specify alphaII > 0";
expalphaII = exp(-alphaII);
romexpalphaII = 1./(1.-expalphaII);
double fealphaII = 2.*(1./alphaII - expalphaII*romexpalphaII);
msg=SetExponentialTractionLaw(stress2,kII1,delIIc,JIIc,umidII,fealphaII);
if(msg!=NULL) return msg;
//cout << "# I: " << expalphaI << "," << romexpalphaI << "," << fealphaI << endl;
// go to parent
return TractionLaw::VerifyAndLoadProperties(np);
}
// print to output window
void ExponentialTraction::PrintMechanicalProperties(void) const
{
PrintSawToothModel("I",JIc,stress1,delIc,kI1,umidI,alphaI);
PrintSawToothModel("II",JIIc,stress2,delIIc,kII1,umidII,alphaII);
PrintProperty("n",nmix,"");
cout << endl;
}
#pragma mark CohesiveZone::Basic Functions
// Return the strength for mode and current delta
// delta must be in valid range
double ExponentialTraction::Strength(int mode,double delta)
{ double arg;
if(mode==1)
{ arg = exp(-alphaI*(delta-umidI)/(delIc-umidI)); // = 1 when still elastic
return stress1*romexpalphaI*(arg-expalphaI);
}
arg = exp(-alphaII*(delta-umidII)/(delIIc-umidII)); // = 1 when still elastic
return stress2*romexpalphaII*(arg-expalphaII);
}
// Return area under the coshesive law up to u (only used in J integral)
// Assumes ue <= u <= uc
double ExponentialTraction::WorkEnergy(int mode,double u)
{ double arg;
if(mode==1)
{ arg = exp(-alphaI*(u-umidI)/(delIc-umidI));
return 0.5*stress1*( umidI + 2.*romexpalphaI*( (delIc-umidI)*(1.-arg)/alphaI
- (u-umidI)*expalphaI ) );
}
arg = exp(-alphaII*(u-umidII)/(delIIc-umidII));
return 0.5*stress2*( umidII + 2.*romexpalphaII*( (delIIc-umidII)*(1.-arg)/alphaII
- (u-umidII)*expalphaII ) );
}
// Return dissipated energy up to delta.
// delta must be in valid range (delta>umid)
double ExponentialTraction::DissipatedEnergy(int mode,double delta)
{ double arg;
if(mode==1)
{ arg = exp(-alphaI*(delta-umidI)/(delIc-umidI));
return 0.5*stress1*( umidI + romexpalphaI*( 2.*(delIc-umidI)*(1.-arg)/alphaI
- delta*(expalphaI+arg) + 2.*umidI*expalphaI ) );
}
arg = exp(-alphaII*(delta-umidII)/(delIIc-umidII));
return 0.5*stress2*( umidII + romexpalphaII*( 2.*(delIIc-umidII)*(1.-arg)/alphaII
- delta*(expalphaII+arg) + 2.*umidII*expalphaII ) );
}
// Get D from delta (needed for MixedModeTraction)
// delta must be in valid range
double ExponentialTraction::GetDFromDelta(int mode,double delta)
{ double arg;
if(mode==1)
{ arg = exp(-alphaI*(delta-umidI)/(delIc-umidI));
return 1. - (umidI/delta)*(1.-romexpalphaI*(1.-arg));
}
arg = exp(-alphaII*(delta-umidII)/(delIIc-umidII));
return 1. - (umidII/delta)*(1.-romexpalphaII*(1.-arg));
}
// Get delta from D (needed for MixedModeTraction)
double ExponentialTraction::GetDeltaFromD(int mode,double D)
{ double uea;
if(mode==1)
{ uea = umidI*romexpalphaI*expalphaI/(1.-D);
return (delIc-umidI)*gsl_sf_lambert_W0(alphaI*uea*exp(alphaI*(delIc+uea)/(delIc-umidI))/(delIc-umidI))/alphaI - uea;
}
uea = umidII*romexpalphaII*expalphaII/(1.-D);
return (delIIc-umidII)*gsl_sf_lambert_W0(alphaII*uea*exp(alphaII*(delIIc+uea)/(delIIc-umidII))/(delIIc-umidII))/alphaII - uea;
}
// Return dissipation rate function (phi(delta))
// delta must be in valid range
double ExponentialTraction::DissipationRate(int mode,double delta)
{ double arg;
if(mode==1)
{ arg = exp(-alphaI*(delta-umidI)/(delIc-umidI)); // = 1 when still elastic
return stress1*romexpalphaI*(arg*(1+alphaI*delta/(delIc-umidI))-expalphaI);
}
arg = exp(-alphaII*(delta-umidII)/(delIIc-umidII)); // = 1 when still elastic
return stress2*romexpalphaII*(arg*(1+alphaII*delta/(delIIc-umidII))-expalphaII);
}
// Return uc*dD/ddelta or ratio of damage parameter evolution to delta evolution
// delta must be in valid range, output is dimensionless
// Only needed if MixedModeTraction calls it
double ExponentialTraction::RatioFunction(int mode,double delta)
{ double varphi = ExponentialTraction::DissipationRate(mode,delta);
return mode==1 ? varphi*umidI/(kI1*delta*delta) : varphi*umidII/(kII1*delta*delta) ;
}
#pragma mark ExponentialTraction::Accessors
// return material type
const char *ExponentialTraction::MaterialType(void) const { return "Exponential Cohesive Law"; }
|
6bf2e1cc9885d0d5333757bd645b8ad27c53f437
|
fb2a45ec972b3544616a142f5df0a0ed6a3267ba
|
/operation.h
|
d7cd8146ad872c505576fc794de4b33aaa6ce3af
|
[] |
no_license
|
cyber4ron/mmo-server
|
a761729a34ca00c4e9d09f41cf0a9fcd1722f3a2
|
2cc4752f06dc7a570e0771d7c960d32837423336
|
refs/heads/master
| 2020-04-11T06:48:25.631899
| 2013-09-19T18:00:04
| 2013-09-19T18:00:04
| 12,915,191
| 1
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 1,046
|
h
|
operation.h
|
#pragma once
#include "message.h"
// 人员动作参数的枚举定义
namespace ActionParams {
enum ButtonMoveDirection { kUp = 0, kDown};
enum ValveRotateDirection { kPositive = 0, kNegative};
};
class operation
{
public:
std::string opid;
std::string sub_opid;//用于顺序
operation_type::ot op_type;
std::string personid;
std::string deviceid;
std::string operation_type;
std::vector<std::string> parameters1;
std::vector<double> parameters2;
boost::posix_time::ptime op_start_time;
boost::posix_time::ptime op_end_time;
boost::posix_time::time_duration duration_time;//for check
unsigned int temp_weather_condition;
unsigned int temp_wind_direction;
bool operator== (const operation &other) const;
bool operator!= (const operation &other) const;
bool operator% (const operation &other) const;
template <typename Archive>
void serialize(Archive& ar, const unsigned int version)
{
}
};
bool operator< (const operation& a, const operation& b);//by timestamp, for sort, 这里语义不等了
|
3fdf527d899c4e00f8a6c1136159c83a4498e5a1
|
a439c1a70f907258cd5c2d1fcfad26cffcbb4c70
|
/vlclauncher/vlclauncher.cpp
|
489708a6d0bacb72df082b275e36d6af627c7dbf
|
[] |
no_license
|
Slippy2k/vlcdemo
|
312cb07284d84a2ab65af7356d89fa86a8de96f2
|
62eed7215770c3fec641a10e91ae30171dbdbb72
|
refs/heads/master
| 2020-04-27T03:00:37.313961
| 2017-05-04T15:08:39
| 2017-05-04T15:08:39
| 174,012,219
| 1
| 0
| null | 2019-03-05T20:03:55
| 2019-03-05T20:00:38
|
C++
|
UTF-8
|
C++
| false
| false
| 3,079
|
cpp
|
vlclauncher.cpp
|
// vlclauncher.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "vlclauncher.h"
#include <conio.h>
#include <Windows.h>
#include <string>
#include <fcntl.h>
#include <io.h>
#include <ppltasks.h>
#include <Pathcch.h>
#include <Shlobj.h>
#include <iostream>
#include <fstream>
using namespace Windows::Foundation;
using namespace Windows::System;
bool LaunchVLCAds()
{
bool done = false;
auto testAppUri = ref new Uri("vlc-ads:"); // The protocol handled by the launched app
auto options = ref new LauncherOptions();
concurrency::task<bool> task(Launcher::LaunchUriAsync(testAppUri, options));
return task.get();
}
bool LaunchVLC(LPWSTR lpCmdLine)
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
wchar_t dir[MAX_PATH];
GetModuleFileName(NULL, dir, MAX_PATH);
PathCchRemoveFileSpec(dir, wcslen(dir));
std::wstring path = dir;
path += L"\\VLC\\vlc.exe";
// Need to track down vlc command line weirdness
std::wstring cmd;
if (wcslen(lpCmdLine) > 0)
{
cmd += L"\"";
cmd += path;
cmd += L"\"";
cmd += lpCmdLine;
}
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
// Start the child process.
int retvalue = CreateProcess(path.c_str(),
(LPWSTR) cmd.c_str(), // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi // Pointer to PROCESS_INFORMATION structure
);
int lastError = GetLastError();
return lastError == 0;
}
[Platform::MTAThread]
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
wchar_t buf[MAX_PATH];
SHGetFolderPathW(NULL, CSIDL_APPDATA | CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, buf);
std::wstring path = buf;
path += L"\\vlcdemo-firstrun.txt";
#ifdef ENABLE_LOG
std::wstring logPath = buf;
logPath += L"\\log.txt";
std::wofstream myfile;
myfile.open(logPath.c_str(), std::ios::app);
std::wstring cmd = lpCmdLine;
myfile << cmd.c_str() << std::endl;
myfile.close();
#endif
auto h = CreateFile2(path.c_str(), GENERIC_READ, 0, OPEN_EXISTING, NULL);
if (h != INVALID_HANDLE_VALUE)
{
CloseHandle(h);
LaunchVLC(lpCmdLine);
}
else
{
auto h = CreateFile2(path.c_str(), GENERIC_READ, 0, CREATE_ALWAYS, NULL);
if (h != INVALID_HANDLE_VALUE)
{
CloseHandle(h);
}
LaunchVLCAds();
}
return 0;
}
|
a490e2a48beebe3f3d02ef2552871e81451ea0c0
|
5759ec01a7b25272296664ed6532be5a8ea329f8
|
/sq-solver/square_equation_solver.cpp
|
dbcdc928ca04ae62a5b71e637c6769904da6659a
|
[
"MIT"
] |
permissive
|
MrKaStep/ded-2018
|
316be236c06c37d1cd6fb280da2078da3e748242
|
d6a4044864b14901ce0d87f1f6b38004d898f456
|
refs/heads/master
| 2020-03-28T12:22:47.901331
| 2018-09-27T06:06:27
| 2018-09-27T06:06:27
| 148,292,002
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,368
|
cpp
|
square_equation_solver.cpp
|
#include "square_equation_solver.h"
#include <util.h>
#include <cassert>
namespace SqSolver {
using Util::IsZero;
bool IsLinear(const Equation& equation) {
return IsZero(equation.a);
}
Result SolveLinear(const Equation& equation) {
assert(IsLinear(equation));
if (IsZero(equation.b)) {
if (IsZero(equation.c)) {
return INF_ROOTS_RESULT;
}
return Result(0);
}
return Result(1, -equation.c / equation.b, 0);
}
Result SolveSquareInternal(const Equation& equation) {
if (IsLinear(equation)) {
return SolveLinear(equation);
}
double discriminant = equation.b * equation.b - 4 * equation.a * equation.c;
if (Util::IsLessOrEqual(discriminant, 0)) {
if (IsZero(discriminant)) {
return Result(1, -equation.b / (2 * equation.a));
}
return Result(0);
}
double discriminantRoot = sqrt(discriminant);
return Result(2,
(-equation.b - discriminantRoot) / (2 * equation.a),
(-equation.b + discriminantRoot) / (2 * equation.a));
}
} /// namespace SqSolver
void SolveSquare(double a, double b, double c, size_t* rootCount, double* root1, double* root2) {
auto result = SqSolver::SolveSquareInternal({a, b, c});
*rootCount = result.RootCount;
*root1 = result.Root1;
*root2 = result.Root2;
}
|
267a8b6f0b165e5ff09047a943597fe365864b17
|
aad34ffba02900ffbe26837899eadecacb1c156d
|
/Arrays/missing.cpp
|
93c05f89156718d2ab7252744011f7a79174d769
|
[] |
no_license
|
ankithans/Data-structures-algorithms
|
20deab67923fedf117a3bf9b7218c6f41c98f604
|
bbacd78da5dfe1e243a90776ea3652e38b2a4f28
|
refs/heads/master
| 2023-01-03T09:09:07.424274
| 2020-10-02T07:09:17
| 2020-10-02T07:09:17
| 282,894,503
| 2
| 2
| null | 2020-10-08T07:33:40
| 2020-07-27T12:39:32
|
C++
|
UTF-8
|
C++
| false
| false
| 466
|
cpp
|
missing.cpp
|
#include <bits/stdc++.h>
using namespace std;
void inputOutput() {
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
int main() {
inputOutput();
cout << "hello";
return 0;
}
/*
given 2 arrays, both arrays have same elements, but second
array has 1 element missing (which is present in 1st array)
find the missing element.
[2, 3, 4, 5] 14
[2, 3, 5] 10
14 - 10 is the element
or take xor ^
*/
|
f736139e0b206ecb2b7df87fa67a0ac3feb661b2
|
adb2be7654cf31b13cc08dceb7394dda7732c6ee
|
/common.ino
|
7a4ecfe47b220dd6841b8d8b6efdd932569f380d
|
[
"MIT"
] |
permissive
|
LuckyNoS7evin/iracing-flag
|
3c33f58e49e8a41a3294cf425d177793e923476b
|
270d15a73da6d8d1bbfe485419bda5d41b249b93
|
refs/heads/main
| 2023-04-28T08:43:22.897499
| 2021-05-24T16:04:52
| 2021-05-24T16:04:52
| 363,042,684
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 290
|
ino
|
common.ino
|
void showStrip() {
strip.show();
}
void setPixel(int Pixel, byte red, byte green, byte blue) {
strip.setPixelColor(Pixel, strip.Color(red, green, blue));
}
void setAll(byte red, byte green, byte blue) {
for(int i = 0; i < NUM_LEDS; i++ ) {
setPixel(i, red, green, blue);
}
}
|
6b5f7cb27a48151c47df7ab177a6b2fadd2154e3
|
1c3d30e9ab85d548d41a525092bdadc5fe855343
|
/objects/include/Flosion/Objects/Melody.hpp
|
ff20e5a50a81e79f5af2a8db38633b953e25ace2
|
[] |
no_license
|
timstr/Flosion
|
c9cb84fdb5f6c6585b1259f21cee39cedb03c825
|
75ed5be66a7c8baaced318ef6718e19705a2db32
|
refs/heads/master
| 2021-07-11T10:04:59.578103
| 2021-04-03T16:18:32
| 2021-04-03T16:18:32
| 89,533,633
| 6
| 1
| null | 2019-12-20T04:53:51
| 2017-04-26T22:54:09
|
C++
|
UTF-8
|
C++
| false
| false
| 6,618
|
hpp
|
Melody.hpp
|
#pragma once
#include <Flosion/Core/SoundSourceTemplate.hpp>
#include <Flosion/Core/MultiSoundInput.hpp>
namespace flo {
// TODO: add a bunch of Signals for subscribing to any important sorts of changes
class Melody;
class MelodyNote;
// The state of the Melody object
class MelodyState : public ConcreteSoundState<Melody> {
public:
MelodyState(SoundNode* owner, const SoundState* dependentState);
// Resizes the queue of notes in progress.
// Maybe some notes will be dropped. Who can say?
void resizeQueue(std::size_t);
class NoteInProgress {
public:
NoteInProgress(const MelodyNote* note, std::size_t inputKey);
const MelodyNote* note() const noexcept;
SoundChunk& buffer() noexcept;
std::size_t inputKey() const noexcept;
std::size_t elapsedTime() const noexcept;
std::size_t remainingTime() const noexcept;
void advance(std::size_t samples) noexcept;
private:
const MelodyNote* const m_note;
std::size_t m_inputKey;
std::size_t m_elapsedTime;
SoundChunk m_buffer;
friend class MelodyState;
};
NoteInProgress* addNoteInProgress(const MelodyNote*);
void removeNoteInProgress(NoteInProgress*);
std::vector<std::optional<NoteInProgress>>& getNotesInProgress() noexcept;
void reset() noexcept override;
private:
std::size_t nextAvailableInputKey() const noexcept;
// NOTE: this gets resized by the Melody itself when needed
std::vector<std::optional<NoteInProgress>> m_notesInProgress;
std::size_t m_elapsedTime = 0;
friend class Melody;
};
// A note in a Melody
class MelodyNote {
public:
MelodyNote(Melody* parentMelody, std::size_t startTime, std::size_t length, double frequency);
MelodyNote(MelodyNote&&) = delete;
MelodyNote(const MelodyNote&) = delete;
MelodyNote& operator=(MelodyNote&&) = delete;
MelodyNote& operator=(const MelodyNote&) = delete;
~MelodyNote() = default;
std::size_t startTime() const noexcept;
std::size_t length() const noexcept;
double frequency() const noexcept;
void setStartTime(std::size_t) noexcept;
void setLength(std::size_t) noexcept;
void setFrequency(double) noexcept;
private:
// The Melody to which the note belongs
Melody* const m_parentMelody;
// The start time of the note, in samples
std::size_t m_startTime;
// The length of the note, in samples
std::size_t m_length;
// The frequency of the note, in Hertz
double m_frequency;
// TODO: more general frequency options:
// - constant (currently the only option)
// - spline
// - this should reuse the Spline object
// - it would be nice if spline points could snap to points in time
// as well as integer ratios of other frequencies in the same note
// or in other notes. This could be done efficiently if Signals are
// used to update values when their dependencies change
// - integer ratio of another note's frequency
// TODO: custom per-note attributes, which may be one of the following:
// - constant
// - spline
// - point along the note in time?? (this would be useful for ADSR, i.e. sustain
// time equals custom time point, release time equals note length minus custom time point)
// - fraction of the note's length?? (this may be redundant but also convenient)
};
// The state of the MultiSoundInput in a Melody object
class MelodyNoteState : public SoundState {
public:
using SoundState::SoundState;
void reset() noexcept override;
const MelodyNote* note() const noexcept;
private:
const MelodyNote* m_currentNote = nullptr;
friend class Melody;
};
// A sequence of notes, much like a midi sequence
class Melody : public WithCurrentTime<OutOfSync<ControlledSoundSource<MelodyState>>> {
public:
Melody();
MelodyNote* addNote(std::size_t startTime, std::size_t length, double frequency);
std::size_t numNotes() const noexcept;
MelodyNote* getNote(std::size_t) noexcept;
const MelodyNote* getNote(std::size_t) const noexcept;
void removeNote(const MelodyNote*);
bool looping() const noexcept;
std::size_t length() const noexcept;
void setLooping(bool);
void setLength(std::size_t);
// The MultiSoundInput which is called upon for playing notes
class Input : public MultiSoundInput<MelodyNoteState, std::size_t> {
public:
CurrentTime noteTime;
class NoteProgress : public SoundNumberSource<Input> {
public:
using SoundNumberSource::SoundNumberSource;
private:
double evaluate(const MelodyNoteState*, const SoundState*) const noexcept override;
} noteProgress;
class NoteLength : public SoundNumberSource<Input> {
public:
using SoundNumberSource::SoundNumberSource;
private:
double evaluate(const MelodyNoteState*, const SoundState*) const noexcept override;
} noteLength;
class NoteFrequency : public SoundNumberSource<Input> {
public:
using SoundNumberSource::SoundNumberSource;
private:
double evaluate(const MelodyNoteState*, const SoundState*) const noexcept override;
} noteFrequency;
private:
Input(Melody* parent);
friend class Melody;
} input;
private:
void renderNextChunk(SoundChunk&, MelodyState*) override;
double getTimeSpeed(const SoundState*) const noexcept override;
std::vector<std::unique_ptr<MelodyNote>> m_notes;
std::size_t m_length;
bool m_loopEnabled;
// computes the maximum number of notes that will
// ever be playing at the same time
std::size_t getMaximumOverlap() const noexcept;
// Allocates or deallocates queue space in each state as
// required by the current number and timing of notes.
// To be called whenever notes are modified
void updateQueueSize();
friend class MelodyNote;
};
}
|
cf48f5053e3eb5dac35f8d15d7d606c24d26e4e2
|
3866a0068c20e462470562ce42cac4b64deee954
|
/RFX/Refractor.h
|
9dae7ec7eb548529e89d410f034c9e70a694a259
|
[] |
no_license
|
BadSanta12345/RFX
|
93fa5e5c7220c473959b0be0712be8e747821e93
|
3e49dafc2200f909595d6e91bd62c2c896988044
|
refs/heads/master
| 2021-01-19T09:25:17.896722
| 2017-09-11T20:34:25
| 2017-09-11T20:34:25
| 82,108,158
| 5
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,753
|
h
|
Refractor.h
|
#pragma once
#include "bs\string_functor.h"
#include "bs\window.h"
#include "BF2Classes.h"
/*
* This file defines an easy to use interfaces for BF2 engine modders(/hackers)
* These functons are to be called only after BF2 has called create window.
*/
#include <d3d9.h>
#include <d3dx9.h>
namespace DICE
{
namespace detail
{
extern CClassManager* g_pClassManager;
extern CMainConsole* g_pMainConsole;
extern CMainConsoleObjects* g_pMainConsoleObjects;
extern CHudInformationLayer* g_pHudInformationLayer;
extern ::std::map<::std::string, ID3DXEffect*> gShaders;
void createHookedConsoleObject(bs::string_functor* pFunctor, const ::std::string& name, int minNumArgs, int maxNumArgs);
void dumpConsoleObjects(::std::ostream& os);
}
void init(bs::IWindow* pWindow);
void update();
bs::IWindow createConsoleWindow();
::std::string invoke(const ::std::string& name);
struct HudString;
namespace HudItems
{
void init();
void createBool(::std::string _name, bool* pvar = nullptr);
void createInt(::std::string _name, int* pvar = nullptr);
void createFloat(::std::string _name, float* pvar = nullptr);
void createString(::std::string _name, HudString* pvar = nullptr);
bool* getBool(::std::string _name);
int* getInt(::std::string _name);
float* getFloat(::std::string _name);
char** getString(::std::string _name);
void setBool(::std::string _name, bool _value);
void setInt(::std::string _name, int _value);
void setFloat(::std::string _name, float _value);
void setString(::std::string _name, std::string _value);
}
struct HudString
{
friend void HudItems::createString(::std::string, HudString*);
HudString();
HudString(const ::std::string& s);
~HudString();
HudString& operator= (const ::std::string& s);
size_t size();
const char* c_str();
private:
char* data;
};
namespace memory
{
using bf_free_t = void(__cdecl *)(void*); extern bf_free_t bf_free;
using bf_malloc_t = void*(__cdecl *)(size_t, int); extern bf_malloc_t bf_malloc;
using getSizeOfAllocation_t = int(__cdecl *)(void*); extern getSizeOfAllocation_t getSizeOfAllocation;
}
namespace ShaderManager
{
void init();
::std::string setFloatBySemantic(const ::std::string& shaderName, const ::std::string& semantic, float val);
::std::string setFloat2BySemantic(const ::std::string& shaderName, const ::std::string& semantic, const D3DXVECTOR2& val);
::std::string setFloat3BySemantic(const ::std::string& shaderName, const ::std::string& semantic, const D3DXVECTOR3& val);
::std::string setFloat4BySemantic(const ::std::string& shaderName, const ::std::string& semantic, const D3DXVECTOR4& val);
::std::string setMatrixBySemantic(const ::std::string& shaderName, const ::std::string& semantic, const D3DXMATRIX& val);
::std::string setTextureBySemantic(const ::std::string& shaderName, const ::std::string& semantic, IDirect3DTexture9* val);
}
/* Template functions */
template<typename TFunc, typename... TDefaultArgs>
void createConsoleObject(TFunc _func, const ::std::string& name, TDefaultArgs... _defaultArgs)
{
using traits = bs::function_traits<TFunc>;
static_assert(sizeof...(TDefaultArgs) <= traits::arity, "Too many default args for console object.");
using TFunctor = bs::basic_string_functor<TFunc, TDefaultArgs...>;
detail::createHookedConsoleObject(
//!!This is not deleted anywhere!!
// TODO: proper clean up on exit
// not very critical as windows will do the clean up anyway
new TFunctor(_func, _defaultArgs...),
name,
TFunctor::nrOfArgs - TFunctor::nrOfDefaultArgs,
TFunctor::nrOfArgs);
}
}
// Refractor style Vector stream operators
inline ::std::istream& operator >> (::std::istream& input, D3DXVECTOR2& rhs)
{
input >> rhs.x;
if (input.peek() != '/')
{
input.clear();
rhs.y = rhs.x;
return input;
}
input.ignore();
input >> rhs.y;
return input;
}
inline ::std::istream& operator >> (::std::istream& input, D3DXVECTOR3& rhs)
{
input >> rhs.x;
if (input.peek() != '/')
{
input.clear();
rhs.z = rhs.y = rhs.x;
return input;
}
input.ignore();
input >> rhs.y;
if (input.peek() != '/')
{
input.clear();
rhs.z = rhs.y;
return input;
}
input.ignore();
input >> rhs.z;
return input;
}
inline ::std::istream& operator >> (::std::istream& input, D3DXVECTOR4& rhs)
{
input >> rhs.x;
if (input.peek() != '/')
{
input.clear();
rhs.w = rhs.z = rhs.y = rhs.x;
return input;
}
input.ignore();
input >> rhs.y;
if (input.peek() != '/')
{
input.clear();
rhs.w = rhs.z = rhs.y;
return input;
}
input.ignore();
input >> rhs.z;
if (input.peek() != '/')
{
input.clear();
rhs.w = rhs.z;
return input;
}
input.ignore();
input >> rhs.w;
return input;
}
|
edc4b73601b93abef1561cfbbf844597a4a2aa8a
|
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
|
/NT/ds/security/cryptoapi/ui/cryptui/signgen.cpp
|
3603cad208447ba9b7226a6896fed0c05c4c9071
|
[] |
no_license
|
jjzhang166/WinNT5_src_20201004
|
712894fcf94fb82c49e5cd09d719da00740e0436
|
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
|
refs/heads/Win2K3
| 2023-08-12T01:31:59.670176
| 2021-10-14T15:14:37
| 2021-10-14T15:14:37
| 586,134,273
| 1
| 0
| null | 2023-01-07T03:47:45
| 2023-01-07T03:47:44
| null |
UTF-8
|
C++
| false
| false
| 35,144
|
cpp
|
signgen.cpp
|
//+-------------------------------------------------------------------------
//
// Microsoft Windows
//
// Copyright (C) Microsoft Corporation, 1997 - 1999
//
// File: signgen.cpp
//
//--------------------------------------------------------------------------
#include "global.hxx"
#include <dbgdef.h>
extern HINSTANCE HinstDll;
extern HMODULE HmodRichEdit;
static const HELPMAP helpmap[] = {
{IDC_SIGNER_GENERAL_SIGNER_NAME, IDH_SIGNERINFO_GENERAL_SIGNERNAME},
{IDC_SIGNER_GENERAL_EMAIL, IDH_SIGNERINFO_GENERAL_SIGNEREMAIL},
{IDC_SIGNER_GENERAL_SIGNING_TIME, IDH_SIGNERINFO_GENERAL_SIGNETIME},
{IDC_SIGNER_GENERAL_VIEW_CERTIFICATE, IDH_SIGNERINFO_GENERAL_VIEW_CERTIFICATE},
{IDC_SIGNER_GENERAL_COUNTER_SIGS, IDH_SIGNERINFO_GENERAL_COUNTERSIG_LIST},
{IDC_SIGNER_GENERAL_DETAILS, IDH_SIGNERINFO_GENERAL_COUNTERSIG_DETAILS}
};
//////////////////////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////////////////////
static void AddCounterSignersToList(HWND hWndListView, SIGNER_VIEW_HELPER *pviewhelp)
{
CMSG_SIGNER_INFO const *pSignerInfo;
PCMSG_SIGNER_INFO pCounterSignerInfo;
DWORD cbCounterSignerInfo;
PCCERT_CONTEXT pCertContext = NULL;
DWORD i;
WCHAR szNameText[CRYPTUI_MAX_STRING_SIZE];
WCHAR szEmailText[CRYPTUI_MAX_STRING_SIZE];
LV_ITEMW lvI;
int itemIndex = 0;
LPWSTR pszTimeText;
pSignerInfo = pviewhelp->pcvsi->pSignerInfo;
//
// set up the fields in the list view item struct that don't change from item to item
//
memset(&lvI, 0, sizeof(lvI));
lvI.mask = LVIF_TEXT | LVIF_PARAM | LVIF_STATE;
lvI.state = 0;
lvI.stateMask = 0;
//
// loop for each unauthenticated attribute and see if it is a counter sig
//
for (i=0; i<pSignerInfo->UnauthAttrs.cAttr; i++)
{
if (!(strcmp(pSignerInfo->UnauthAttrs.rgAttr[i].pszObjId, szOID_RSA_counterSign) == 0))
{
continue;
}
assert(pSignerInfo->UnauthAttrs.rgAttr[i].cValue == 1);
//
// decode the EncodedSigner info
//
cbCounterSignerInfo = 0;
pCounterSignerInfo = NULL;
if(!CryptDecodeObject(PKCS_7_ASN_ENCODING|CRYPT_ASN_ENCODING,
PKCS7_SIGNER_INFO,
pSignerInfo->UnauthAttrs.rgAttr[i].rgValue[0].pbData,
pSignerInfo->UnauthAttrs.rgAttr[i].rgValue[0].cbData,
0,
NULL,
&cbCounterSignerInfo))
{
return;
}
if (NULL == (pCounterSignerInfo = (PCMSG_SIGNER_INFO)malloc(cbCounterSignerInfo)))
{
return;
}
if(!CryptDecodeObject(PKCS_7_ASN_ENCODING|CRYPT_ASN_ENCODING,
PKCS7_SIGNER_INFO,
pSignerInfo->UnauthAttrs.rgAttr[i].rgValue[0].pbData,
pSignerInfo->UnauthAttrs.rgAttr[i].rgValue[0].cbData,
0,
pCounterSignerInfo,
&cbCounterSignerInfo))
{
free(pCounterSignerInfo);
return;
}
//
// find the signers cert
//
pCertContext = GetSignersCert(
pCounterSignerInfo,
pviewhelp->hExtraStore,
pviewhelp->pcvsi->cStores,
pviewhelp->pcvsi->rghStores);
//
// get the signers name
//
if (!(pCertContext && CertGetNameStringW(
pCertContext,
CERT_NAME_SIMPLE_DISPLAY_TYPE,
0,//CERT_NAME_ISSUER_FLAG,
NULL,
szNameText,
ARRAYSIZE(szNameText))))
{
LoadStringU(HinstDll, IDS_NOTAVAILABLE, szNameText, ARRAYSIZE(szNameText));
}
//
// get the signers email
//
if (!(pCertContext && (CertGetNameStringW(
pCertContext,
CERT_NAME_EMAIL_TYPE,
0,//CERT_NAME_ISSUER_FLAG,
NULL,
szEmailText,
ARRAYSIZE(szEmailText)) != 1)))
{
LoadStringU(HinstDll, IDS_NOTAVAILABLE, szEmailText, ARRAYSIZE(szEmailText));
}
pszTimeText = AllocAndReturnSignTime(pCounterSignerInfo, NULL, hWndListView);
//
// add the item to the list view
//
lvI.iSubItem = 0;
lvI.pszText = szNameText;
lvI.cchTextMax = wcslen(szNameText);
lvI.lParam = (LPARAM) pCounterSignerInfo;
lvI.iItem = itemIndex++;
ListView_InsertItemU(hWndListView, &lvI);
ListView_SetItemTextU(hWndListView, itemIndex-1 , 1, szEmailText);
if (pszTimeText != NULL)
{
ListView_SetItemTextU(hWndListView, itemIndex-1 , 2, pszTimeText);
free(pszTimeText);
}
else
{
LoadStringU(HinstDll, IDS_NOTAVAILABLE, szEmailText, ARRAYSIZE(szEmailText));
ListView_SetItemTextU(hWndListView, itemIndex-1 , 2, szEmailText);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////////////////////
static BOOL ValidateCertForUsageWrapper(
PCCERT_CONTEXT pCertContext,
DWORD cStores,
HCERTSTORE * rghStores,
HCERTSTORE hExtraStore,
LPCSTR pszOID)
{
if ((pszOID == NULL) ||
(!((strcmp(pszOID, szOID_PKIX_KP_TIMESTAMP_SIGNING) == 0) ||
(strcmp(pszOID, szOID_KP_TIME_STAMP_SIGNING) == 0))))
{
return (ValidateCertForUsage(
pCertContext,
NULL,
cStores,
rghStores,
hExtraStore,
pszOID));
}
else
{
return (ValidateCertForUsage(
pCertContext,
NULL,
cStores,
rghStores,
hExtraStore,
szOID_PKIX_KP_TIMESTAMP_SIGNING) ||
ValidateCertForUsage(
pCertContext,
NULL,
cStores,
rghStores,
hExtraStore,
szOID_KP_TIME_STAMP_SIGNING));
}
}
//////////////////////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////////////////////
static BOOL GetWinVTrustState(SIGNER_VIEW_HELPER *pviewhelp)
{
HCERTSTORE *rghLocalStoreArray;
DWORD i;
//
// if the private data was passed in that means WinVerifyTrust has already
// been called so just use that state to see if the cert is OK, otherwise
// call BuildWinVTrustState to build up the state
//
if (pviewhelp->pPrivate == NULL)
{
//
// make one array out of the array of hCertStores plus the extra hCertStore
//
if (NULL == (rghLocalStoreArray = (HCERTSTORE *) malloc(sizeof(HCERTSTORE) * (pviewhelp->pcvsi->cStores+1))))
{
return FALSE;
}
i=0;
while (i<pviewhelp->pcvsi->cStores)
{
rghLocalStoreArray[i] = pviewhelp->pcvsi->rghStores[i];
i++;
}
rghLocalStoreArray[i] = pviewhelp->hExtraStore;
if (NULL == (pviewhelp->pPrivate = (CERT_VIEWSIGNERINFO_PRIVATE *) malloc(sizeof(CERT_VIEWSIGNERINFO_PRIVATE))))
{
free(rghLocalStoreArray);
return FALSE;
}
if (BuildWinVTrustState(
NULL,
pviewhelp->pcvsi->pSignerInfo,
pviewhelp->pcvsi->cStores+1,
rghLocalStoreArray,
pviewhelp->pcvsi->pszOID,
pviewhelp->pPrivate,
&(pviewhelp->CryptProviderDefUsage),
&(pviewhelp->WTD)))
{
pviewhelp->fPrivateAllocated = TRUE;
pviewhelp->pPrivate->idxSigner = 0;
pviewhelp->pPrivate->fCounterSigner = FALSE;
pviewhelp->pPrivate->idxCounterSigner = 0;
pviewhelp->pPrivate->dwInheritedError = 0;
}
else
{
free(pviewhelp->pPrivate);
pviewhelp->pPrivate = NULL;
}
free(rghLocalStoreArray);
}
if (pviewhelp->pPrivate != NULL)
{
return TRUE;
}
else
{
return FALSE;
}
}
//////////////////////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////////////////////
INT_PTR APIENTRY ViewPageSignerGeneral(HWND hwndDlg, UINT msg, WPARAM wParam,
LPARAM lParam)
{
DWORD i;
PROPSHEETPAGE *ps;
SIGNER_VIEW_HELPER *pviewhelp;
HWND hWndListView;
LV_COLUMNW lvC;
WCHAR szText[CRYPTUI_MAX_STRING_SIZE];
HANDLE hGraphic;
DWORD cbText;
LPWSTR pwszText;
CMSG_SIGNER_INFO const *pSignerInfo;
LPWSTR pszTimeText;
LVITEMW lvI;
int listIndex;
CHARFORMAT chFormat;
HWND hwnd;
CRYPT_PROVIDER_DATA const *pProvData = NULL;
LPWSTR pwszErrorString;
LPNMLISTVIEW pnmv;
switch ( msg ) {
case WM_INITDIALOG:
//
// save the pviewhelp struct in DWL_USER so it can always be accessed
//
ps = (PROPSHEETPAGE *) lParam;
pviewhelp = (SIGNER_VIEW_HELPER *) (ps->lParam);
pSignerInfo = pviewhelp->pcvsi->pSignerInfo;
SetWindowLongPtr(hwndDlg, DWLP_USER, (DWORD_PTR) pviewhelp);
//
// extract the signers cert from the list of stores
//
pviewhelp->pSignersCert = GetSignersCert(
pviewhelp->pcvsi->pSignerInfo,
pviewhelp->hExtraStore,
pviewhelp->pcvsi->cStores,
pviewhelp->pcvsi->rghStores);
if (!GetWinVTrustState(pviewhelp))
{
return FALSE;
}
switch (pviewhelp->pPrivate->pCryptProviderData->dwFinalError)
{
case TRUST_E_NO_SIGNER_CERT:
pviewhelp->hIcon = LoadIcon(HinstDll, MAKEINTRESOURCE(IDI_EXCLAMATION_SIGN));
LoadStringU(HinstDll, IDS_SIGNER_UNAVAILABLE_CERT, (LPWSTR)szText, ARRAYSIZE(szText));
break;
case TRUST_E_CERT_SIGNATURE:
pviewhelp->hIcon = LoadIcon(HinstDll, MAKEINTRESOURCE(IDI_REVOKED_SIGN));
LoadStringU(HinstDll, IDS_BAD_SIGNER_CERT_SIGNATURE, (LPWSTR)szText, ARRAYSIZE(szText));
break;
case TRUST_E_BAD_DIGEST:
pviewhelp->hIcon = LoadIcon(HinstDll, MAKEINTRESOURCE(IDI_REVOKED_SIGN));
LoadStringU(HinstDll, IDS_SIGNER_INVALID_SIGNATURE, (LPWSTR)szText, ARRAYSIZE(szText));
break;
case CERT_E_CHAINING:
pviewhelp->hIcon = LoadIcon(HinstDll, MAKEINTRESOURCE(IDI_REVOKED_SIGN));
LoadStringU(HinstDll, IDS_SIGNER_CERT_NO_VERIFY, (LPWSTR)szText, ARRAYSIZE(szText));
break;
case TRUST_E_COUNTER_SIGNER:
case TRUST_E_TIME_STAMP:
pviewhelp->hIcon = LoadIcon(HinstDll, MAKEINTRESOURCE(IDI_REVOKED_SIGN));
//
// if the over-all error is a counter signer signer error, then we need to check
// whether we are currently viewing the counter signer of the original signer
//
if (pviewhelp->pPrivate->fCounterSigner)
{
PCRYPT_PROVIDER_SGNR pSigner;
//
// if we are looking at the counter signer, then get the specific error
// out of the signer structure
//
pSigner = WTHelperGetProvSignerFromChain(
pviewhelp->pPrivate->pCryptProviderData,
pviewhelp->pPrivate->idxSigner,
pviewhelp->pPrivate->fCounterSigner,
pviewhelp->pPrivate->idxCounterSigner);
if (pSigner == NULL)
{
LoadStringU(HinstDll, IDS_UKNOWN_ERROR, (LPWSTR)szText, ARRAYSIZE(szText));
}
else
{
switch (pSigner->dwError)
{
case TRUST_E_NO_SIGNER_CERT:
pviewhelp->hIcon = LoadIcon(HinstDll, MAKEINTRESOURCE(IDI_EXCLAMATION_SIGN));
LoadStringU(HinstDll, IDS_SIGNER_UNAVAILABLE_CERT, (LPWSTR)szText, ARRAYSIZE(szText));
break;
case TRUST_E_CERT_SIGNATURE:
LoadStringU(HinstDll, IDS_BAD_SIGNER_CERT_SIGNATURE, (LPWSTR)szText, ARRAYSIZE(szText));
break;
case TRUST_E_BAD_DIGEST:
case NTE_BAD_SIGNATURE:
LoadStringU(HinstDll, IDS_SIGNER_INVALID_SIGNATURE, (LPWSTR)szText, ARRAYSIZE(szText));
break;
default:
GetUnknownErrorString(&pwszErrorString, pSigner->dwError);
if ((pwszErrorString != NULL) && (wcslen(pwszErrorString)+1 < ARRAYSIZE(szText)))
{
wcscpy(szText, pwszErrorString);
}
else
{
LoadStringU(HinstDll, IDS_UKNOWN_ERROR, (LPWSTR)szText, ARRAYSIZE(szText));
}
free(pwszErrorString);
break;
}
}
}
else
{
//
// since we are viewing the original signer, just set the generic counter signer
// error problem
//
LoadStringU(HinstDll, IDS_COUNTER_SIGNER_INVALID, (LPWSTR)szText, ARRAYSIZE(szText));
}
break;
case 0:
//
// even if there is no error from the wintrust call, there may be ar
// inherited error, if that is that case then fall through to the default
// error processing
//
if ((pviewhelp->dwInheritedError == 0) && (pviewhelp->pPrivate->dwInheritedError == 0))
{
pviewhelp->hIcon = LoadIcon(HinstDll, MAKEINTRESOURCE(IDI_SIGN));
LoadStringU(HinstDll, IDS_SIGNER_VALID, (LPWSTR)szText, ARRAYSIZE(szText));
break;
}
// fall through if dwInheritedError is not 0
default:
if (pviewhelp->pPrivate->pCryptProviderData->dwFinalError != 0)
{
GetUnknownErrorString(&pwszErrorString, pviewhelp->pPrivate->pCryptProviderData->dwFinalError);
}
else
{
if (pviewhelp->dwInheritedError != 0)
{
GetUnknownErrorString(&pwszErrorString, pviewhelp->dwInheritedError);
}
else
{
GetUnknownErrorString(&pwszErrorString, pviewhelp->pPrivate->dwInheritedError);
}
}
pviewhelp->hIcon = LoadIcon(HinstDll, MAKEINTRESOURCE(IDI_REVOKED_SIGN));
if ((pwszErrorString != NULL) && (wcslen(pwszErrorString)+1 < ARRAYSIZE(szText)))
{
wcscpy(szText, pwszErrorString);
}
else
{
LoadStringU(HinstDll, IDS_UKNOWN_ERROR, (LPWSTR)szText, ARRAYSIZE(szText));
}
free(pwszErrorString);
break;
}
CryptUISetRicheditTextW(hwndDlg, IDC_SIGNER_GENERAL_VALIDITY_EDIT, szText);
LoadStringU(HinstDll, IDS_SIGNER_INFORMATION, (LPWSTR)szText, ARRAYSIZE(szText));
//
// set the header text and subclass the edit controls so they display an
// arrow cursor in their window
//
CryptUISetRicheditTextW(hwndDlg, IDC_SIGNER_GENERAL_HEADER_EDIT, szText);
CertSubclassEditControlForArrowCursor(GetDlgItem(hwndDlg, IDC_SIGNER_GENERAL_VALIDITY_EDIT));
CertSubclassEditControlForArrowCursor(GetDlgItem(hwndDlg, IDC_SIGNER_GENERAL_HEADER_EDIT));
//
// disable the "View Certificate" button if the cert was not found
//
if (pviewhelp->pSignersCert == NULL)
{
EnableWindow(GetDlgItem(hwndDlg, IDC_SIGNER_GENERAL_VIEW_CERTIFICATE), FALSE);
}
//
// get the signers name and display it
//
if (!((pviewhelp->pSignersCert) && (CertGetNameStringW(
pviewhelp->pSignersCert,
CERT_NAME_SIMPLE_DISPLAY_TYPE,
0,//CERT_NAME_ISSUER_FLAG,
NULL,
szText,
ARRAYSIZE(szText)))))
{
LoadStringU(HinstDll, IDS_NOTAVAILABLE, szText, ARRAYSIZE(szText));
}
CryptUISetRicheditTextW(hwndDlg, IDC_SIGNER_GENERAL_SIGNER_NAME, szText);
//
// get the signers email and display it
//
if (!((pviewhelp->pSignersCert) && (CertGetNameStringW(
pviewhelp->pSignersCert,
CERT_NAME_EMAIL_TYPE,
0,//CERT_NAME_ISSUER_FLAG,
NULL,
szText,
ARRAYSIZE(szText)) != 1)))
{
LoadStringU(HinstDll, IDS_NOTAVAILABLE, szText, ARRAYSIZE(szText));
}
CryptUISetRicheditTextW(hwndDlg, IDC_SIGNER_GENERAL_EMAIL, szText);
//
// get the signing time and display it
//
pszTimeText = AllocAndReturnTimeStampersTimes(
pviewhelp->pcvsi->pSignerInfo,
NULL,
GetDlgItem(hwndDlg, IDC_SIGNER_GENERAL_SIGNING_TIME));
if (pszTimeText != NULL)
{
CryptUISetRicheditTextW(hwndDlg, IDC_SIGNER_GENERAL_SIGNING_TIME, pszTimeText);
free(pszTimeText);
}
else
{
LoadStringU(HinstDll, IDS_NOTAVAILABLE, szText, ARRAYSIZE(szText));
CryptUISetRicheditTextW(hwndDlg, IDC_SIGNER_GENERAL_SIGNING_TIME, szText);
}
//
// disable the view details button since nothing is currently selected
//
EnableWindow(GetDlgItem(hwndDlg, IDC_SIGNER_GENERAL_DETAILS), FALSE);
//
// create and set the font for the signer info header information
//
memset(&chFormat, 0, sizeof(chFormat));
chFormat.cbSize = sizeof(chFormat);
chFormat.dwMask = CFM_BOLD;
chFormat.dwEffects = CFE_BOLD;
SendMessageA(GetDlgItem(hwndDlg, IDC_SIGNER_GENERAL_HEADER_EDIT), EM_SETCHARFORMAT, SCF_ALL, (LPARAM) &chFormat);
//
// get the handle of the list view control
//
hWndListView = GetDlgItem(hwndDlg, IDC_SIGNER_GENERAL_COUNTER_SIGS);
//
// initialize the columns in the list view
//
lvC.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM;
lvC.fmt = LVCFMT_LEFT; // Left-align the column.
lvC.pszText = szText; // The text for the column.
// Add the columns. They are loaded from a string table.
lvC.iSubItem = 0;
lvC.cx = 100;
LoadStringU(HinstDll, IDS_NAME, szText, ARRAYSIZE(szText));
if (ListView_InsertColumnU(hWndListView, 0, &lvC) == -1)
{
// error
}
lvC.cx = 100;
LoadStringU(HinstDll, IDS_EMAIL, szText, ARRAYSIZE(szText));
if (ListView_InsertColumnU(hWndListView, 1, &lvC) == -1)
{
// error
}
lvC.cx = 125;
LoadStringU(HinstDll, IDS_TIMESTAMP_TIME, szText, ARRAYSIZE(szText));
if (ListView_InsertColumnU(hWndListView, 2, &lvC) == -1)
{
// error
}
//
// set the style in the list view so that it highlights an entire line
//
SendMessageA(hWndListView, LVM_SETEXTENDEDLISTVIEWSTYLE, 0, LVS_EX_FULLROWSELECT);
//
// add all of the counter signers to the list box
//
AddCounterSignersToList(GetDlgItem(hwndDlg, IDC_SIGNER_GENERAL_COUNTER_SIGS), pviewhelp);
return TRUE;
case WM_NOTIFY:
pviewhelp = (SIGNER_VIEW_HELPER *) GetWindowLongPtr(hwndDlg, DWLP_USER);
pSignerInfo = pviewhelp->pcvsi->pSignerInfo;
switch (((NMHDR FAR *) lParam)->code)
{
case PSN_SETACTIVE:
break;
case PSN_APPLY:
SetWindowLongPtr(hwndDlg, DWLP_MSGRESULT, (LRESULT)TRUE);
break;
case PSN_KILLACTIVE:
SetWindowLongPtr(hwndDlg, DWLP_MSGRESULT, (LRESULT)FALSE);
return TRUE;
case PSN_RESET:
SetWindowLongPtr(hwndDlg, DWLP_MSGRESULT, (LRESULT)FALSE);
break;
case PSN_QUERYCANCEL:
pviewhelp->fCancelled = TRUE;
return FALSE;
case PSN_HELP:
pviewhelp = (SIGNER_VIEW_HELPER *) GetWindowLongPtr(hwndDlg, DWLP_USER);
if (FIsWin95) {
//WinHelpA(hwndDlg, (LPSTR) pviewhelp->pcvsi->szHelpFileName,
// HELP_CONTEXT, pviewhelp->pcvsi->dwHelpId);
}
else {
//WinHelpW(hwndDlg, pviewhelp->pcvsi->szHelpFileName, HELP_CONTEXT,
// pviewhelp->pcvsi->dwHelpId);
}
return TRUE;
case NM_DBLCLK:
switch (((NMHDR FAR *) lParam)->idFrom)
{
case IDC_SIGNER_GENERAL_COUNTER_SIGS:
if (IsWindowEnabled(GetDlgItem(hwndDlg, IDC_SIGNER_GENERAL_DETAILS)))
{
SendMessage(
hwndDlg,
WM_COMMAND,
MAKELONG(IDC_SIGNER_GENERAL_DETAILS, BN_CLICKED),
(LPARAM) GetDlgItem(hwndDlg, IDC_SIGNER_GENERAL_DETAILS));
}
break;
}
break;
case LVN_ITEMCHANGED:
if ((((NMHDR FAR *) lParam)->idFrom) != IDC_SIGNER_GENERAL_COUNTER_SIGS)
{
break;
}
//
// if an item is selected, then enable the details button, otherwise
// disable it
//
EnableWindow(
GetDlgItem(hwndDlg, IDC_SIGNER_GENERAL_DETAILS),
(ListView_GetSelectedCount(
GetDlgItem(hwndDlg,IDC_SIGNER_GENERAL_COUNTER_SIGS)) == 0) ? FALSE : TRUE);
break;
case NM_CLICK:
if ((((NMHDR FAR *) lParam)->idFrom) != IDC_SIGNER_GENERAL_COUNTER_SIGS)
{
break;
}
hWndListView = GetDlgItem(hwndDlg, IDC_SIGNER_GENERAL_COUNTER_SIGS);
//
// make sure something is selected by getting the current selection
//
listIndex = ListView_GetNextItem(
hWndListView,
-1,
LVNI_SELECTED
);
break;
case NM_SETFOCUS:
switch (((NMHDR FAR *) lParam)->idFrom)
{
case IDC_SIGNER_GENERAL_COUNTER_SIGS:
hWndListView = GetDlgItem(hwndDlg, IDC_SIGNER_GENERAL_COUNTER_SIGS);
if ((ListView_GetItemCount(hWndListView) != 0) &&
(ListView_GetNextItem(hWndListView, -1, LVNI_SELECTED) == -1))
{
memset(&lvI, 0, sizeof(lvI));
lvI.mask = LVIF_STATE;
lvI.iItem = 0;
lvI.state = LVIS_FOCUSED;
lvI.stateMask = LVIS_FOCUSED;
ListView_SetItem(hWndListView, &lvI);
}
break;
}
break;
}
break;
case WM_COMMAND:
pviewhelp = (SIGNER_VIEW_HELPER *) GetWindowLongPtr(hwndDlg, DWLP_USER);
pSignerInfo = pviewhelp->pcvsi->pSignerInfo;
switch (LOWORD(wParam))
{
case IDC_SIGNER_GENERAL_VIEW_CERTIFICATE:
if (HIWORD(wParam) == BN_CLICKED)
{
CRYPTUI_VIEWCERTIFICATE_STRUCTW cvps;
memset(&cvps,0, sizeof(cvps));
cvps.dwSize = sizeof(cvps);
cvps.pCryptProviderData = NULL;
cvps.hwndParent = hwndDlg;
cvps.pCertContext = pviewhelp->pSignersCert;
cvps.cPurposes = 1;
cvps.rgszPurposes = (LPCSTR *) &(pviewhelp->pcvsi->pszOID);
cvps.cStores = pviewhelp->pcvsi->cStores;
cvps.rghStores = pviewhelp->pcvsi->rghStores;
if (pviewhelp->pPrivate != NULL)
{
cvps.pCryptProviderData = pviewhelp->pPrivate->pCryptProviderData;
cvps.fpCryptProviderDataTrustedUsage =
pviewhelp->pPrivate->fpCryptProviderDataTrustedUsage;
cvps.idxSigner = pviewhelp->pPrivate->idxSigner;
cvps.fCounterSigner = pviewhelp->pPrivate->fCounterSigner;
cvps.idxCounterSigner = pviewhelp->pPrivate->idxCounterSigner;
}
CryptUIDlgViewCertificateW(&cvps, NULL);
}
break;
case IDC_SIGNER_GENERAL_DETAILS:
if (HIWORD(wParam) == BN_CLICKED)
{
hWndListView = GetDlgItem(hwndDlg, IDC_SIGNER_GENERAL_COUNTER_SIGS);
//
// get the selected item and its lParam which is a signer info
//
listIndex = ListView_GetNextItem(
hWndListView,
-1,
LVNI_SELECTED
);
memset(&lvI, 0, sizeof(lvI));
lvI.iItem = listIndex;
lvI.mask = LVIF_PARAM;
if (!ListView_GetItemU(hWndListView, &lvI))
{
return FALSE;
}
CRYPTUI_VIEWSIGNERINFO_STRUCTW cvsi;
CERT_VIEWSIGNERINFO_PRIVATE cvsiPrivate;
memcpy(&cvsi, pviewhelp->pcvsi, sizeof(cvsi));
cvsi.pSignerInfo = (PCMSG_SIGNER_INFO) lvI.lParam;
cvsi.pszOID = szOID_KP_TIME_STAMP_SIGNING;
cvsi.hwndParent = hwndDlg;
if (pviewhelp->pPrivate != NULL)
{
cvsiPrivate.pCryptProviderData = pviewhelp->pPrivate->pCryptProviderData;
cvsiPrivate.fpCryptProviderDataTrustedUsage =
pviewhelp->pPrivate->fpCryptProviderDataTrustedUsage;
cvsiPrivate.idxSigner = pviewhelp->pPrivate->idxSigner;
cvsiPrivate.fCounterSigner = TRUE;
cvsiPrivate.idxCounterSigner = listIndex;
cvsi.dwFlags |= CRYPTUI_VIEWSIGNERINFO_RESERVED_FIELD_IS_SIGNERINFO_PRIVATE;
cvsi.dwFlags &= ~CRYPTUI_VIEWSIGNERINFO_RESERVED_FIELD_IS_ERROR_CODE;
cvsi.dwReserved = (DWORD_PTR) &cvsiPrivate;
//
// it is possible that there is no error when validating the original
// signer info and that an error was inherited, so to allow the counter
// signer dialog to again inherit the error it must be filled in in the
// private struct
//
if (pviewhelp->pcvsi->dwFlags & CRYPTUI_VIEWSIGNERINFO_RESERVED_FIELD_IS_ERROR_CODE)
{
cvsiPrivate.dwInheritedError = (DWORD) pviewhelp->pcvsi->dwReserved;
}
else
{
cvsiPrivate.dwInheritedError = 0;
}
}
else if (pviewhelp->pcvsi->dwFlags & CRYPTUI_VIEWSIGNERINFO_RESERVED_FIELD_IS_ERROR_CODE)
{
cvsi.dwFlags |= CRYPTUI_VIEWSIGNERINFO_RESERVED_FIELD_IS_ERROR_CODE;
cvsi.dwFlags &= ~CRYPTUI_VIEWSIGNERINFO_RESERVED_FIELD_IS_SIGNERINFO_PRIVATE;
cvsi.dwReserved = pviewhelp->pcvsi->dwReserved;
}
CryptUIDlgViewSignerInfoW(&cvsi);
}
break;
case IDHELP:
if (FIsWin95) {
//WinHelpA(hwndDlg, (LPSTR) pviewhelp->pcvsi->szHelpFileName,
// HELP_CONTEXT, pviewhelp->pcvsi->dwHelpId);
}
else {
//WinHelpW(hwndDlg, pviewhelp->pcvsi->szHelpFileName, HELP_CONTEXT,
// pviewhelp->pcvsi->dwHelpId);
}
return TRUE;
}
break;
case WM_PAINT:
RECT rect;
PAINTSTRUCT paintstruct;
HDC hdc;
COLORREF colorRef;
pviewhelp = (SIGNER_VIEW_HELPER *) GetWindowLongPtr(hwndDlg, DWLP_USER);
if (GetUpdateRect(hwndDlg, &rect, FALSE))
{
hdc = BeginPaint(hwndDlg, &paintstruct);
if (hdc == NULL)
{
EndPaint(hwndDlg, &paintstruct);
break;
}
colorRef = GetBkColor(hdc);
SendMessageA(GetDlgItem(hwndDlg, IDC_SIGNER_GENERAL_VALIDITY_EDIT), EM_SETBKGNDCOLOR , 0, (LPARAM) colorRef);
SendMessageA(GetDlgItem(hwndDlg, IDC_SIGNER_GENERAL_HEADER_EDIT), EM_SETBKGNDCOLOR, 0, (LPARAM) colorRef);
if (pviewhelp->hIcon != NULL)
{
DrawIcon(
hdc,
ICON_X_POS,
ICON_Y_POS,
pviewhelp->hIcon);
}
EndPaint(hwndDlg, &paintstruct);
}
break;
case WM_DESTROY:
pviewhelp = (SIGNER_VIEW_HELPER *) GetWindowLongPtr(hwndDlg, DWLP_USER);
if (pviewhelp->pSignersCert)
{
CertFreeCertificateContext(pviewhelp->pSignersCert);
pviewhelp->pSignersCert = NULL;
}
if (pviewhelp->hIcon != NULL)
{
DeleteObject(pviewhelp->hIcon);
pviewhelp->hIcon = NULL;
}
if (pviewhelp->fPrivateAllocated)
{
FreeWinVTrustState(
NULL,
pviewhelp->pcvsi->pSignerInfo,
0,
NULL,
pviewhelp->pcvsi->pszOID,
&(pviewhelp->CryptProviderDefUsage),
&(pviewhelp->WTD));//,
//&(pviewhelp->fUseDefaultProvider));
free(pviewhelp->pPrivate);
}
//
// get all the items in the list view and free the lParam
// associated with each of them (lParam is the helper sruct)
//
hWndListView = GetDlgItem(hwndDlg, IDC_SIGNER_GENERAL_COUNTER_SIGS);
memset(&lvI, 0, sizeof(lvI));
lvI.iItem = ListView_GetItemCount(hWndListView) - 1;
lvI.mask = LVIF_PARAM;
while (lvI.iItem >= 0)
{
if (ListView_GetItemU(hWndListView, &lvI))
{
if (((void *) lvI.lParam) != NULL)
{
free((void *) lvI.lParam);
}
}
lvI.iItem--;
}
break;
case WM_HELP:
case WM_CONTEXTMENU:
if (msg == WM_HELP)
{
hwnd = GetDlgItem(hwndDlg, ((LPHELPINFO)lParam)->iCtrlId);
}
else
{
hwnd = (HWND) wParam;
}
if ((hwnd != GetDlgItem(hwndDlg, IDC_SIGNER_GENERAL_SIGNER_NAME)) &&
(hwnd != GetDlgItem(hwndDlg, IDC_SIGNER_GENERAL_EMAIL)) &&
(hwnd != GetDlgItem(hwndDlg, IDC_SIGNER_GENERAL_SIGNING_TIME)) &&
(hwnd != GetDlgItem(hwndDlg, IDC_SIGNER_GENERAL_VIEW_CERTIFICATE)) &&
(hwnd != GetDlgItem(hwndDlg, IDC_SIGNER_GENERAL_COUNTER_SIGS)) &&
(hwnd != GetDlgItem(hwndDlg, IDC_SIGNER_GENERAL_DETAILS)))
{
SetWindowLongPtr(hwndDlg, DWLP_MSGRESULT, (LRESULT)TRUE);
return TRUE;
}
else
{
return OnContextHelp(hwndDlg, msg, wParam, lParam, helpmap);
}
}
return FALSE;
}
|
568abcb9abf8e39ec3d4ee4e377c8a694aa4ab1a
|
8addbe3a0a41341ab1ea08b451376976577b9c1f
|
/Classes/GameLevelChoose.h
|
0b57059e769ca6b7e9310f07ac0af7aefa5fd624
|
[] |
no_license
|
tennysondy/PointGame_Src
|
86ec38e160ba8017df00a0a5a40162b9313bb05f
|
710f859c70fdb319150e8b2ec1857dd116f5686f
|
refs/heads/master
| 2021-01-22T04:40:32.667045
| 2014-10-20T08:32:18
| 2014-10-20T08:32:18
| 25,069,892
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 521
|
h
|
GameLevelChoose.h
|
#ifndef __GameLevelChoose__H__
#define __GameLevelChoose__H__
#define LEVEL_TAG 100
#define LEVEL_NUM 12
#include <string>
#include "cocos2d.h"
USING_NS_CC;
using namespace std;
class GameLevelChoose:public Layer
{
public:
GameLevelChoose(void);
~GameLevelChoose(void);
virtual bool init();
CREATE_FUNC(GameLevelChoose);
static Scene* createScene();
int _level;
bool _level_lock;
private:
void returnToMainMenu(Ref* pSender);
void level(Ref* pSender);
Label* createLevelTxt(string& sLv1);
};
#endif
|
d227bca856d3cbb7f7c85795461d5feb6404b406
|
5300e0494a2431b0e8390ed60a933ccec2314db0
|
/Task11/z-функция/main.cpp
|
4997aed34b4f9e2e5bb4404d83e857e13f56eef4
|
[] |
no_license
|
AlmazNasibullin/algorithms-and-data-structures
|
b92b64c36acba8370a3f0257c9aab8407e57db3d
|
1e39c1a3b04fc1269f9f03f68a4d81a9af70fc95
|
refs/heads/master
| 2016-09-03T07:19:46.284775
| 2013-02-11T14:58:33
| 2013-02-11T14:58:33
| null | 0
| 0
| null | null | null | null |
WINDOWS-1251
|
C++
| false
| false
| 2,742
|
cpp
|
main.cpp
|
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using std::string;
using std::vector;
using std::cin;
using std::cout;
using std::endl;
using std::fstream;
using std::cerr;
using std::ios;
string read_input_string() {
string s;
try {
fstream in("in.txt");
in.seekg(0, ios::end);
int length = in.tellg();
in.seekg (0, ios::beg);
if (length > 0) {
vector<char> buffer(length);
in.read(&buffer[0], length);
s = string(&buffer[0], length);
}
in.close();
} catch (...) {
cerr<<"Bad file"<<endl;
exit(1);
}
return s;
}
int calculate_z_function(const string& s, const string& sub_s, vector<int>& z) {
// параллельно находится индекс подстроки в строке
int length = static_cast<int>(s.length());
int sub_length = static_cast<int>(sub_s.length());
if (length == 0 || sub_length == 0 || length < sub_length) {
return -1;
}
z.assign(length + sub_length + 1, 0);
z[0] = length + sub_length + 1;
int r = -1;
int max = -1;
for (int i = 1; i < length + sub_length + 1; ++i) {
if (i == sub_length) { // позиция уникального символа
continue;
}
if (max <= i) {
int k = 0;
while (k + i < length + sub_length + 1 && k != sub_length && k + i != sub_length) {
if (k + i < sub_length && sub_s[k] != sub_s[k + i]) { // сравнение в строке sub_s
break;
} else if (k + i > sub_length && sub_s[k] != s[k + i - sub_length - 1]) {
// сравнение между строками sub_s и s
break;
}
++k;
}
z[i] = k;
} else {
int k = i - r;
if (z[k] < z[r] - k) {
z[i] = z[k];
continue;
}
int j = 1;
while (j + max < length + sub_length + 1 && max + j != sub_length && max - i + j != sub_length) {
if (max + j < sub_length && sub_s[max - i + j] != sub_s[max + j]) {
// сравнение в строке sub_s
break;
} else if (max - i + j < sub_length && max + j > sub_length && sub_s[max - i + j] != s[max + j - sub_length - 1]) {
// сравнение между строками sub_s и s
break;
}
++j;
}
z[i] = max - i + j;
}
if (i + z[i] - 1 > max) {
max = i + z[i] - 1;
r = i;
}
if (i > sub_length && z[i] == sub_length) { // нашли подстроку в строке
return i - sub_length - 1;
}
}
return -1;
}
int main() {
string s = read_input_string();
vector<int> z;
for (;;) {
string sub_s;
char c;
cin.get(c);
while (c != '\n') {
sub_s +=c;
cin.get(c);
}
cout<<calculate_z_function(s, sub_s, z)<<endl;
}
return 0;
}
|
3617f57f034038b7d55bc4b37c6762ea2899e4d5
|
67150e5bd016ec389842466d2e482892af7b4527
|
/src/components/NodeTest.cpp
|
d7113133bc0435024f6be5953e38c6db9cf000ce
|
[] |
no_license
|
sevenmachines/cryomesh-cute
|
fa25508f6474960baf82d6aeb5e3008874817d6a
|
0ebf7c7ef9a741cc4fa1bf00fe7978560926add2
|
refs/heads/master
| 2022-09-26T10:43:56.354061
| 2011-10-20T07:29:18
| 2011-10-20T07:29:18
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 20,153
|
cpp
|
NodeTest.cpp
|
/*
* NodeTest.cpp
*
* Created on: 19 Jan 2011
* Author: SevenMachines<SevenMachines@yahoo.co.uk>
*/
//#define NODETEST_DEBUG
#include "NodeTest.h"
#include "components/Connection.h"
#include "common/TimeKeeper.h"
namespace cryomesh {
namespace components {
NodeTest::NodeTest() {
}
NodeTest::~NodeTest() {
}
void NodeTest::runSuite() {
cute::suite s;
s.push_back(CUTE(NodeTest::testContruction));
s.push_back(CUTE(NodeTest::testUpdateImpulses));
s.push_back(CUTE(NodeTest::testEmitmpulse));
s.push_back(CUTE(NodeTest::testCheckActivation));
s.push_back(CUTE(NodeTest::testGetActivities));
s.push_back(CUTE(NodeTest::testGetSetCurrentActivity));
s.push_back(CUTE(NodeTest::testAddActivity));
s.push_back(CUTE(NodeTest::testDataObject));
s.push_back(CUTE(NodeTest::testSpacialSettings));
s.push_back(CUTE(NodeTest::testAddImpulse));
s.push_back(CUTE(NodeTest::testForceFire));
s.push_back(CUTE(NodeTest::testIsPrimary));
cute::ide_listener lis;
cute::makeRunner(lis)(s, "NodeTest");
}
void NodeTest::testContruction() {
NodeTest nt;
const Impulse & imp = *(nt.getEmittedImpulse());
ASSERT(imp.getSum() !=0);
}
void NodeTest::testUpdateImpulses() {
//check no fire but experation only
{
common::TimeKeeper & tk = common::TimeKeeper::getTimeKeeper();
boost::shared_ptr<Node> node1 = getDefaultNode();
const int LENGTH1 = 10;
boost::shared_ptr<Impulse> imp1(new Impulse(0.0001, LENGTH1));
boost::shared_ptr<Impulse> imp2(new Impulse(0.0001, LENGTH1));
const int DELAY2 = 2;
node1->addImpulse(imp1);
#ifdef NODETEST_DEBUG
std::cout << "NodeTest::testUpdateImpulses: " << "cycle: " << common::TimeKeeper::getTimeKeeper().getCycle()
<< std::endl;
std::cout << *node1 << std::endl;
std::cout << "NodeTest::testUpdateImpulses: " << "imp1: " << "(" << imp1->getFirstActiveCycle().toLInt() << ","
<< imp1->getLastActiveCycle().toLInt() << ")" << std::endl;
#endif
for (int i = 0; i < LENGTH1 + DELAY2 + 5; i++) {
tk.update();
if (i == 1) {
node1->addImpulse(imp2);
#ifdef NODETEST_DEBUG
std::cout << "NodeTest::testUpdateImpulses: " << "imp2: " << "(" << imp2->getFirstActiveCycle().toLInt()
<< "," << imp2->getLastActiveCycle().toLInt() << ")" << std::endl;
#endif
}
#ifdef NODETEST_DEBUG
std::cout << "NodeTest::testUpdateImpulses: " << i << ": " << "cycle: " << tk.getCycle().toLInt()
<< std::endl;
#endif
node1->update();
int sz = node1->getImpulses().getSize();
if (i < 10 && i >= 1) {
ASSERT_EQUAL(2, sz);
} else if (i < 12) {
// imp1 is now dropped
ASSERT_EQUAL(1, sz);
} else {
//imp2 is dropped
ASSERT_EQUAL(0, sz);
}
}
}
//check fire
#ifdef NODETEST_DEBUG
std::cout << "NodeTest::testUpdateImpulses: " << "########### FIRE ###########" << std::endl;
#endif
{
{
common::TimeKeeper & tk = common::TimeKeeper::getTimeKeeper();
boost::shared_ptr<Node> node1 = getDefaultNode();
const int LENGTH1 = 10;
boost::shared_ptr<Impulse> imp1(new Impulse(2, LENGTH1));
boost::shared_ptr<Impulse> imp2(new Impulse(4, LENGTH1));
const int DELAY2 = 2;
node1->addImpulse(imp1);
#ifdef NODETEST_DEBUG
std::cout << "NodeTest::testUpdateImpulses: " << "cycle: " << common::TimeKeeper::getTimeKeeper().getCycle()
<< std::endl;
std::cout << *node1 << std::endl;
std::cout << "NodeTest::testUpdateImpulses: " << "imp1: " << "(" << imp1->getFirstActiveCycle().toLInt()
<< "," << imp1->getLastActiveCycle().toLInt() << ")" << std::endl;
#endif
for (int i = 0; i < LENGTH1 + DELAY2 + 5; i++) {
tk.update();
if (i == 1) {
node1->addImpulse(imp2);
#ifdef NODETEST_DEBUG
std::cout << "NodeTest::testUpdateImpulses: " << "imp2: " << "("
<< imp2->getFirstActiveCycle().toLInt() << "," << imp2->getLastActiveCycle().toLInt()
<< ")" << std::endl;
#endif
}
#ifdef NODETEST_DEBUG
std::cout << "NodeTest::testUpdateImpulses: " << i << ": " << "cycle: " << tk.getCycle().toLInt() << std::endl;
#endif
node1->update();
int sz = node1->getImpulses().getSize();
if (i < 1) {
ASSERT_EQUAL(1, sz);
} else if (i < 2 && i >= 1) {
ASSERT_EQUAL(2, sz);
} else {
//imp2 is dropped
ASSERT_EQUAL(0, sz);
}
}
}
}
}
void NodeTest::testEmitmpulse() {
// test positive
{
boost::shared_ptr<Node> node1 = getDefaultNode();
bool original_positive = (node1->getEmittedImpulse()->getSum() > 0);
node1->emitImpulsePositive();
const std::map<boost::uuids::uuid, boost::shared_ptr<Connection> > & objs_in =
node1->getConnector().getInputs();
ASSERT_EQUAL(2, objs_in.size());
// forall in objs_in
{
std::map<boost::uuids::uuid, boost::shared_ptr<Connection> >::const_iterator it_objs_in = objs_in.begin();
const std::map<boost::uuids::uuid, boost::shared_ptr<Connection> >::const_iterator it_objs_in_end =
objs_in.end();
while (it_objs_in != it_objs_in_end) {
int impssz = it_objs_in->second->getImpulses().getSize();
ASSERT_EQUAL(0, impssz);
++it_objs_in;
}
}
const std::map<boost::uuids::uuid, boost::shared_ptr<Connection> > & objs_out =
node1->getConnector().getOutputs();
ASSERT_EQUAL(3, objs_out.size());
// forall in objs_out
{
int count = 0;
std::map<boost::uuids::uuid, boost::shared_ptr<Connection> >::const_iterator it_objs_out = objs_out.begin();
const std::map<boost::uuids::uuid, boost::shared_ptr<Connection> >::const_iterator it_objs_out_end =
objs_out.end();
while (it_objs_out != it_objs_out_end) {
int impssz = it_objs_out->second->getImpulses().getSize();
// std::cout << "NodeTest::testEmitmpulse: " << "count: " << count << std::endl;
ASSERT_EQUAL(1, impssz);
const boost::shared_ptr<Impulse> temppulse =
(it_objs_out->second->getImpulses().getCollection().begin()->second);
double sum = temppulse->getSum();
// std::cout << "NodeTest::testEmitmpulse: " << "sum:" << sum << std::endl;
if (original_positive == true) {
ASSERT(sum>0);
} else {
ASSERT(sum<0);
}
++count;
++it_objs_out;
}
}
}
// test negative
{
boost::shared_ptr<Node> node1 = getDefaultNode();
bool original_positive = (node1->getEmittedImpulse()->getSum() > 0);
node1->emitImpulseNegative();
const std::map<boost::uuids::uuid, boost::shared_ptr<Connection> > & objs_in =
node1->getConnector().getInputs();
ASSERT_EQUAL(2, objs_in.size());
// forall in objs_in
{
std::map<boost::uuids::uuid, boost::shared_ptr<Connection> >::const_iterator it_objs_in = objs_in.begin();
const std::map<boost::uuids::uuid, boost::shared_ptr<Connection> >::const_iterator it_objs_in_end =
objs_in.end();
while (it_objs_in != it_objs_in_end) {
int impssz = it_objs_in->second->getImpulses().getSize();
ASSERT_EQUAL(0, impssz);
++it_objs_in;
}
}
const std::map<boost::uuids::uuid, boost::shared_ptr<Connection> > & objs_out =
node1->getConnector().getOutputs();
ASSERT_EQUAL(3, objs_out.size());
// forall in objs_out
{
std::map<boost::uuids::uuid, boost::shared_ptr<Connection> >::const_iterator it_objs_out = objs_out.begin();
const std::map<boost::uuids::uuid, boost::shared_ptr<Connection> >::const_iterator it_objs_out_end =
objs_out.end();
while (it_objs_out != it_objs_out_end) {
int impssz = it_objs_out->second->getImpulses().getSize();
ASSERT_EQUAL(1, impssz);
const boost::shared_ptr<Impulse> temppulse =
(it_objs_out->second->getImpulses().getCollection().begin()->second);
double sum = temppulse->getSum();
// std::cout << "NodeTest::testEmitmpulse: " << "sum:" << sum << std::endl;
if (original_positive == true) {
ASSERT(sum<0);
} else {
ASSERT(sum>0);
}
++it_objs_out;
}
}
}
}
void NodeTest::testCheckActivation() {
// No activation -> Positive activation
{
boost::shared_ptr<Node> node1 = getDefaultNode();
boost::shared_ptr<Impulse> imp1(new Impulse(2, 10));
boost::shared_ptr<Impulse> imp2(new Impulse(2, 10));
node1->addImpulse(imp1);
node1->addImpulse(imp2);
// std::cout << "NodeTest::testCheckActivation: " << "" << std::endl;
// std::cout << node1->getImpulses() << std::endl;
Node::ActivationState act_state;
node1->update();
act_state = node1->getLastActivationState();
bool statenone = (Node::None == act_state);
ASSERT(statenone);
common::TimeKeeper & tk = common::TimeKeeper::getTimeKeeper();
for (int i = 0; i < 1; ++i) {
tk.update();
node1->updateActivity();
// std::cout << "NodeTest::testCheckActivation: " << "time:" << tk.getCycle().toLInt() << "act: "
// << node1->updateActivity() << std::endl;
}
node1->update();
act_state = node1->getLastActivationState();
statenone = (Node::None == act_state);
ASSERT(statenone);
// Positive activation
for (int i = 0; i < 3; ++i) {
tk.update();
node1->updateActivity();
// std::cout << "NodeTest::testCheckActivation: " << "time:" << tk.getCycle().toLInt() << "act: "
// << node1->updateActivity() << std::endl;
}
node1->update();
act_state = node1->getLastActivationState();
bool statepos = (Node::Positive == act_state);
ASSERT(statepos);
}
// No activation -> Negative activation
{
boost::shared_ptr<Node> node1 = getDefaultNode();
boost::shared_ptr<Impulse> imp1(new Impulse(-2, 10));
boost::shared_ptr<Impulse> imp2(new Impulse(-2, 10));
node1->addImpulse(imp1);
node1->addImpulse(imp2);
// std::cout << "NodeTest::testCheckActivation: " << "impulses:" << std::endl;
// std::cout << node1->getImpulses() << std::endl;
Node::ActivationState act_state;
node1->update();
act_state = node1->getLastActivationState();
bool statenone = (Node::None == act_state);
ASSERT(statenone);
common::TimeKeeper & tk = common::TimeKeeper::getTimeKeeper();
for (int i = 0; i < 1; ++i) {
tk.update();
node1->updateActivity();
// std::cout << "NodeTest::testCheckActivation: " << "time:" << tk.getCycle().toLInt() << "act: "
// << node1->updateActivity() << std::endl;
}
node1->update();
act_state = node1->getLastActivationState();
statenone = (Node::None == act_state);
ASSERT(statenone);
// Negative activation
for (int i = 0; i < 3; ++i) {
tk.update();
node1->updateActivity();
// std::cout << "NodeTest::testCheckActivation: " << "time:" << tk.getCycle().toLInt() << " act: "
// << node1->updateActivity() << std::endl;
}
node1->update();
act_state = node1->getLastActivationState();
bool stateneg = (Node::Negative == act_state);
ASSERT(stateneg);
}
}
void NodeTest::testGetActivities() {
NodeTest nt;
common::TimeKeeper & tk = common::TimeKeeper::getTimeKeeper();
nt.addActivity(tk.getCycle(), 1);
nt.addActivity(tk.getCycle() + 1, 2);
nt.addActivity(tk.getCycle() + 2, 3);
ASSERT_EQUAL(3, nt.getActivities().size());
}
void NodeTest::testGetSetCurrentActivity() {
common::TimeKeeper & tk = common::TimeKeeper::getTimeKeeper();
NodeTest nt;
// Can no longer set activity directly
nt.addActivity(tk.getCycle(), 1);
nt.addActivity(tk.getCycle() + 1, 2);
nt.addActivity(tk.getCycle() + 2, 3);
int act_sz = nt.getActivities().size();
ASSERT_EQUAL(3, act_sz);
ASSERT_EQUAL_DELTA(1, nt.getActivity(), 0.00001);
ASSERT_EQUAL_DELTA(3, nt.getActivity(tk.getCycle() + 2), 0.00001);
nt.setActivity(4);
ASSERT_EQUAL(3, nt.getActivities().size());
ASSERT_EQUAL_DELTA(4, nt.getActivity(), 0.00001);
}
void NodeTest::testAddActivity() {
common::TimeKeeper & tk = common::TimeKeeper::getTimeKeeper();
NodeTest nt;
// over egg
for (int i = 0; i < Node::MAX_ACTIVITIES_LENGTH + 10; i++) {
nt.addActivity(tk.getCycle() + i, 1);
}
ASSERT_EQUAL(Node::MAX_ACTIVITIES_LENGTH, nt.getActivities().size());
}
void NodeTest::testDataObject() {
boost::shared_ptr<Impulse> imp1 = Impulse::getRandom();
boost::shared_ptr<Impulse> imp2 = Impulse::getRandom();
boost::shared_ptr<Impulse> imp3 = Impulse::getRandom();
boost::shared_ptr<Impulse> imp4 = Impulse::getRandom();
boost::shared_ptr<Impulse> imp5 = Impulse::getRandom();
boost::shared_ptr<Node> node(new Node);
ASSERT(imp1!=0);
ASSERT(imp2!=0);
ASSERT(imp4!=0);
ASSERT(imp5!=0);
ASSERT(imp3!=0);
ASSERT(node !=0);
node->addImpulse(imp1);
node->addImpulse(imp2);
node->addImpulse(imp3);
node->addImpulse(imp4);
node->addImpulse(imp5);
// active logging
node->enableLogging(true);
const unsigned int MAX_COUNT = 105;
for (unsigned int i = 0; i < MAX_COUNT; i++) {
common::TimeKeeper::getTimeKeeper().update();
node->update();
}
const dataobjects::DataObject<unsigned long int, double> & datamap = node->getDataObject();
//std::cout << "NodeTest::testDataObject: " << "" << std::endl;
//std::cout << datamap << std::endl;
ASSERT_EQUAL(100, datamap.getMap().size());
}
void NodeTest::testSpacialSettings() {
boost::shared_ptr<Connection> con(new Connection);
boost::shared_ptr<Node> node1 = components::Node::getRandom();
boost::shared_ptr<Node> node2 = components::Node::getRandom();
node1->getMutableConnector().connectOutput(con);
node2->getMutableConnector().connectInput(con);
con->getMutableConnector().connectInput(node1);
con->getMutableConnector().connectOutput(node2);
int innode_count = con->getConnector().getInputs().size();
int outnode_count = con->getConnector().getOutputs().size();
ASSERT_EQUAL(1, innode_count);
ASSERT_EQUAL(1, outnode_count);
node1->setPosition(spacial::Point(10, 10, 10));
spacial::Point point1_pre = node1->getPosition();
spacial::Point point2_pre = node2->getPosition();
double distance_pre = con->getActivityTimer()->getDelay();
double dist_pre_exp = point1_pre.getDistance(point2_pre);
ASSERT_EQUAL_DELTA(dist_pre_exp, distance_pre, 0.00001);
// move
node1->setPosition(spacial::Point(50, 50, 50));
spacial::Point point1_post = node1->getPosition();
spacial::Point point2_post = node2->getPosition();
double distance_post = con->getActivityTimer()->getDelay();
double dist_post_exp = point1_post.getDistance(point2_post);
ASSERT_EQUAL(point2_pre, point2_post);
ASSERT( !(point1_pre == point1_post));
ASSERT_EQUAL(spacial::Point(50,50,50), point1_post);
ASSERT_EQUAL_DELTA(dist_post_exp, distance_post, 0.00001);
}
void NodeTest::testAddImpulse() {
const common::Cycle BASE_CYCLE = common::TimeKeeper::getTimeKeeper().getCycle();
boost::shared_ptr<Node> node1 = getDefaultNode();
boost::shared_ptr<Impulse> imp1(new Impulse(2, 10));
boost::shared_ptr<Impulse> imp2(new Impulse(4, 3));
const int DELAY1 = 2;
const int DELAY2 = 4;
const int DELAY3 = 7;
{
for (int i = 0; i < DELAY1; i++) {
common::TimeKeeper::getTimeKeeper().update();
}
node1->addImpulse(imp1);
const common::Cycle start = imp1->getFirstActiveCycle();
const common::Cycle now = common::TimeKeeper::getTimeKeeper().getCycle();
ASSERT_EQUAL(now, start);
}
{
for (int i = 0; i < DELAY2; i++) {
common::TimeKeeper::getTimeKeeper().update();
}
node1->addImpulse(imp2);
const common::Cycle start = imp2->getFirstActiveCycle();
const common::Cycle now = common::TimeKeeper::getTimeKeeper().getCycle();
ASSERT_EQUAL(now, start);
}
// with delay
const common::Cycle BASE_DELAY3(3);
boost::shared_ptr<Impulse> imp3(new Impulse(5, 2, 3));
{
for (int i = 0; i < DELAY3; i++) {
common::TimeKeeper::getTimeKeeper().update();
}
node1->addImpulse(imp3);
const common::Cycle start = imp3->getFirstActiveCycle();
const common::Cycle now = common::TimeKeeper::getTimeKeeper().getCycle();
ASSERT_EQUAL(now+BASE_DELAY3, start);
}
}
void NodeTest::testForceFire() {
common::Cycle start_cycle = common::TimeKeeper::getTimeKeeper().getCycle();
boost::shared_ptr<Node> node1 = Node::getRandom();
std::cout << "NodeTest::testForceFire: " << "start time: " << start_cycle << std::endl;
std::cout << "NodeTest::testForceFire: " << *node1 << std::endl;
ASSERT(node1->getLastActivationState() == None);
node1->forceFire();
double act1 = node1->getActivity();
common::TimeKeeper::getTimeKeeper().update();
std::cout << "NodeTest::testForceFire: " << *node1 << std::endl;
common::Cycle cycle1_cycle = common::TimeKeeper::getTimeKeeper().getCycle();
node1->update();
std::cout << "NodeTest::testForceFire: " << "cycle1 time: " << cycle1_cycle << std::endl;
double act2 = node1->getActivity();
std::cout << "NodeTest::testForceFire: " << "act1:" << act1 << " act2:" << act2 << std::endl;
bool to_fire = (node1->getLastActivationState() == Positive) || (node1->getLastActivationState() == Negative);
ASSERT(to_fire);
common::TimeKeeper::getTimeKeeper().update();
node1->update();
ASSERT_EQUAL(None, node1->getLastActivationState());
}
void NodeTest::testIsPrimary() {
// As primary in, node1
{
boost::shared_ptr<Connection> con1(new Connection);
boost::shared_ptr<Connection> con2(new Connection);
boost::shared_ptr<Node> node1 = Node::getRandom();
boost::shared_ptr<Node> node2 = Node::getRandom();
node1->connectInput(con1);
node1->connectOutput(con2);
node2->connectInput(con2);
con1->connectOutput(node1);
con2->connectInput(node1);
con2->connectOutput(node2);
ASSERT(checkConnectionCount<Connection>(con1,0,1));
ASSERT(checkConnectionCount<Connection>(con2,1,1));
ASSERT(node1->isPrimaryInputAttachedNode() == true);
ASSERT(node1->isPrimaryOutputAttachedNode() == false);
}
// As primary out, node2
{
boost::shared_ptr<Connection> con1(new Connection);
boost::shared_ptr<Connection> con2(new Connection);
boost::shared_ptr<Node> node1 = Node::getRandom();
boost::shared_ptr<Node> node2 = Node::getRandom();
node1->connectOutput(con1);
node2->connectInput(con1);
node2->connectOutput(con2);
con1->connectInput(node1);
con1->connectOutput(node2);
con2->connectInput(node2);
ASSERT(checkConnectionCount<Connection>(con1,1,1));
ASSERT(checkConnectionCount<Connection>(con2,1,0));
ASSERT(node2->isPrimaryInputAttachedNode() == false);
ASSERT(node2->isPrimaryOutputAttachedNode() == true);
}
// As neither, node2
{
boost::shared_ptr<Connection> con1(new Connection);
boost::shared_ptr<Connection> con2(new Connection);
boost::shared_ptr<Node> node1 = Node::getRandom();
boost::shared_ptr<Node> node2 = Node::getRandom();
boost::shared_ptr<Node> node3 = Node::getRandom();
node1->connectOutput(con1);
node2->connectInput(con1);
node2->connectOutput(con2);
node3->connectInput(con2);
con1->connectInput(node1);
con1->connectOutput(node2);
con2->connectInput(node2);
con2->connectOutput(node3);
ASSERT(node3->isPrimaryInputAttachedNode() == false);
ASSERT(node3->isPrimaryOutputAttachedNode() == false);
}
}
boost::shared_ptr<Node> NodeTest::getDefaultNode() {
boost::shared_ptr<Connection> con_in1(new Connection);
boost::shared_ptr<Connection> con_in2(new Connection);
boost::shared_ptr<Connection> con_out1(new Connection);
boost::shared_ptr<Connection> con_out2(new Connection);
boost::shared_ptr<Connection> con_out3(new Connection);
boost::shared_ptr<Node> node1 = Node::getRandom();
node1->getMutableConnector().connectInput(con_in1);
node1->getMutableConnector().connectInput(con_in2);
node1->getMutableConnector().connectOutput(con_out1);
node1->getMutableConnector().connectOutput(con_out2);
node1->getMutableConnector().connectOutput(con_out3);
int insz = node1->getConnector().getInputs().size();
int outsz = node1->getConnector().getOutputs().size();
ASSERT_EQUAL(2, insz);
ASSERT_EQUAL(3, outsz);
return node1;
}
template<class T>
bool NodeTest::checkConnectionCount(const boost::shared_ptr<T> obj, const int expected_in, const int expected_out) {
bool success = true;
int in_count = obj->getConnector().getInputs().size();
int out_count = obj->getConnector().getOutputs().size();
if (in_count != expected_in) {
success = false;
std::cout << "NodeTest::checkConnectionCount: " << "Input Mismatch: exp : " << expected_in << " actual: "
<< in_count << std::endl;
}
if (out_count != expected_out) {
success = false;
std::cout << "NodeTest::checkConnectionCount: " << "Output Mismatch: exp : " << expected_out << " actual: "
<< out_count << std::endl;
}
return success;
}
} // namespace
} // namespace
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.