hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3649cd645f04a2c11fa1c2be5751592c3aee5e08 | 5,748 | cpp | C++ | LoganEngine/src/lTest/TestResourceManager/HierarchyTest/TestHierarchyBuilder.cpp | sereslorant/logan_engine | a596b4128d0a58236be00f93064e276e43484017 | [
"MIT"
] | 1 | 2019-12-26T13:22:29.000Z | 2019-12-26T13:22:29.000Z | LoganEngine/src/lTest/TestResourceManager/HierarchyTest/TestHierarchyBuilder.cpp | sereslorant/logan_engine | a596b4128d0a58236be00f93064e276e43484017 | [
"MIT"
] | null | null | null | LoganEngine/src/lTest/TestResourceManager/HierarchyTest/TestHierarchyBuilder.cpp | sereslorant/logan_engine | a596b4128d0a58236be00f93064e276e43484017 | [
"MIT"
] | null | null | null |
#include <lCore/lResourceManager/lrmResourceManager/lrmResourceManager.hpp>
#include <lUtils/lJSON/lJSON.h>
#include <iostream>
#include <lUtils/lJSON/lJSON_TypeRetriever.h>
#include <fstream>
const liJSON_Object *RootObject(std::istream &in)
{
liJSON_Value *FileContent;
lJSON_Util::Parse(in,FileContent);
if(FileContent == nullptr)
{return nullptr;}
const liJSON_Object *RootObject = ToConstObject(FileContent);
if(RootObject == nullptr)
{return nullptr;}
return RootObject;
}
bool ReadDirectoryData(const liJSON_Object *directory_data_object,std::string &directory_id,std::string &directory_path)
{
if(directory_data_object == nullptr)
{
return false;
}
const liJSON_String *DirectoryId = ToConstString(
directory_data_object->GetVariable("DirectoryId")
);
if(DirectoryId != nullptr)
{
directory_id = DirectoryId->GetValue();
}
else
{
return false;
}
const liJSON_String *DirectoryPath = ToConstString(
directory_data_object->GetVariable("DirectoryPath")
);
if(DirectoryPath != nullptr)
{
directory_path = DirectoryPath->GetValue();
}
else
{
return false;
}
return true;
}
template<class ... lModuleTypes_T>
class lrmDirectoryProcessor
{
protected:
lrmResourceDirectory<lModuleTypes_T...> *NewDirectory;
public:
virtual void AddResources(const std::string &resource_type,const liJSON_Array &resource_list) = 0;
lrmDirectoryProcessor(lrmResourceDirectory<lModuleTypes_T...> *new_directory)
:NewDirectory(new_directory)
{}
virtual ~lrmDirectoryProcessor()
{}
};
template<class lDirectoryProcessor_T,class ... lModuleTypes_T>
lrmResourceDirectory<lModuleTypes_T...> *ContentDirectory(const std::string &path,char separator)
{
const std::string ManifestPath = path + separator + "Manifest.json";
std::ifstream fin(ManifestPath);
if(fin.is_open())
{
/*
* Load root node
*/
const liJSON_Object *ManifestRoot = RootObject(fin);
if(ManifestRoot == nullptr)
{return nullptr;}
lrmResourceDirectory<lModuleTypes_T...> *NewDirectory = new lrmResourceDirectory<lModuleTypes_T...>;
/*
* Load resources in the current directory
*/
const liJSON_Object *ResourceMap = ToConstObject(ManifestRoot->GetVariable("Resources"));
if(ResourceMap != nullptr)
{
lDirectoryProcessor_T DirectoryProcessor(NewDirectory);
ResourceMap->Forall(
[&DirectoryProcessor] (const std::string &key,const liJSON_Value *value)
{
const liJSON_Array *ResourceArray = ToConstArray(value);
DirectoryProcessor.AddResources(key,*ResourceArray);
}
);
}
/*
* Recursively load subdirectories
*/
const liJSON_Array *SubdirectoryArray = ToConstArray(ManifestRoot->GetVariable("Subdirectories"));
if(SubdirectoryArray != nullptr)
{
for(int i=0;i < SubdirectoryArray->Size();i++)
{
const liJSON_Object *Subdirectory = ToConstObject(SubdirectoryArray->GetElement(i));
std::string DirectoryId;
std::string DirectoryPath;
if(ReadDirectoryData(Subdirectory,DirectoryId,DirectoryPath))
{
std::string NewPath = path + separator + DirectoryPath;
lrmResourceDirectory<lModuleTypes_T...> *NewSubdirectory = ContentDirectory<lDirectoryProcessor_T,lModuleTypes_T...>(NewPath,separator);
if(NewSubdirectory != nullptr)
{
NewDirectory->AddSubdirectory(DirectoryId,NewSubdirectory);
}
}
}
}
delete ManifestRoot;
return NewDirectory;
}
else
{
return nullptr;
}
}
class TestDirectoryProcessor : public lrmDirectoryProcessor<>
{
public:
virtual void AddResources(const std::string &resource_type,const liJSON_Array &resource_list) override
{
std::cout << "Resource type added: " << resource_type << std::endl;
//lJSON_Util::Print(resource_list,std::cout);
for(unsigned int i=0;i < resource_list.Size();i++)
{
const liJSON_Object *ResourceData = ToConstObject(resource_list.GetElement(i));
std::cout << "Id = " << i << std::endl;
std::cout << "FilePath: " << ToConstString(ResourceData->GetVariable("FilePath"))->GetValue() << std::endl;
std::cout << "ResourceId: " << ToConstString(ResourceData->GetVariable("ResourceId"))->GetValue() << std::endl;
std::cout << "ResourceLoader: "<< ToConstString(ResourceData->GetVariable("ResourceLoader"))->GetValue() << std::endl;
}
}
TestDirectoryProcessor(lrmResourceDirectory<> *new_directory)
:lrmDirectoryProcessor<>(new_directory)
{}
virtual ~TestDirectoryProcessor() override
{}
};
void TestNonexistentPath()
{
lrmResourceDirectory<> *ResourceDir = ContentDirectory<TestDirectoryProcessor>("NonexistentPath",'/');
bool Success = ResourceDir == nullptr;
std::cout << "Test nonexistent directory succeeded: " << Success << std::endl;
}
void TestBadformatPath1()
{
lrmResourceDirectory<> *ResourceDir = ContentDirectory<TestDirectoryProcessor>("TestFailManifestLoad1",'/');
bool Success = ResourceDir == nullptr;
std::cout << "Test manifest load fail 1 succeeded: " << Success << std::endl;
}
void TestBadformatPath2()
{
lrmResourceDirectory<> *ResourceDir = ContentDirectory<TestDirectoryProcessor>("TestFailManifestLoad2",'/');
bool Success = ResourceDir == nullptr;
std::cout << "Test manifest load fail 2 succeeded: " << Success << std::endl;
}
void TestSuccessful()
{
lrmResourceDirectory<> *ResourceDir = ContentDirectory<TestDirectoryProcessor>("TestFolder",'/');
bool ResourceDirLoaded = ResourceDir != nullptr;
//lrmResourceManager<> ResourceManager(ResourceDir);
bool Success = ResourceDirLoaded;
delete ResourceDir;
std::cout << "Test successful read succeeded: " << Success << std::endl;
}
int main(int argc,char *argv[])
{
TestSuccessful();
TestNonexistentPath();
TestBadformatPath1();
TestBadformatPath2();
//
return 0;
}
| 26.127273 | 141 | 0.728253 | sereslorant |
3649e45161f4af8dee42d5162b531ee7ee0d8b9a | 4,747 | cpp | C++ | haxelib/native-glue/android/src/android-main.cpp | Kakise/hx-gameplay | e7fe3d4e79e0e12d439b3f3c930d85d78f2eba8d | [
"MIT"
] | 3 | 2021-07-07T08:50:41.000Z | 2021-07-15T00:53:53.000Z | haxelib/native-glue/android/src/android-main.cpp | Kakise/hx-gameplay | e7fe3d4e79e0e12d439b3f3c930d85d78f2eba8d | [
"MIT"
] | 1 | 2015-09-04T15:44:37.000Z | 2015-09-04T19:07:01.000Z | haxelib/native-glue/android/src/android-main.cpp | Kakise/hx-gameplay | e7fe3d4e79e0e12d439b3f3c930d85d78f2eba8d | [
"MIT"
] | 1 | 2017-11-01T21:03:22.000Z | 2017-11-01T21:03:22.000Z | #ifdef __ANDROID__
#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>
#include <android/log.h>
#include <android_native_app_glue.h>
#define ERROR(msg) __android_log_print(ANDROID_LOG_ERROR, "ERROR", msg)
#define DEBUG(msg) __android_log_print(ANDROID_LOG_DEBUG, "DEBUG", msg);
/**
* TODO
*/
static void *loadLibrary(const char *path, const char *library);
/**
* TODO
*/
static char *getApplicationDirectory(struct android_app* state);
/**
* Main entry point.
*/
extern "C" void android_main(struct android_app* state)
{
// Android specific : Dummy function that needs to be called to
// ensure that the native activity works properly behind the scenes.
app_dummy();
// Load the shared libraries used by the application.
//
char *appDir = getApplicationDirectory(state);
void *hndlApplication = loadLibrary(appDir, "application");
void *hndlGameplay = loadLibrary(appDir, "gameplay");
loadLibrary(appDir, "std");
loadLibrary(appDir, "regexp");
loadLibrary(appDir, "zlib");
delete [] appDir;
// Initialize and begin the application.
//
if (hndlApplication == NULL)
{
ERROR("Failed to load application's shared library.");
exit(EXIT_FAILURE);
}
if (hndlGameplay == NULL)
{
ERROR("Failed to load gameplay's shared library.");
exit(EXIT_FAILURE);
}
void (*native_setup) (struct android_app*) =
reinterpret_cast<void (*) (struct android_app*)>(dlsym(hndlGameplay, "native_setup"));
if (native_setup == NULL)
{
ERROR("Failed to locate gameplay's setup function.");
exit(EXIT_FAILURE);
}
native_setup(state);
void (*main)() =
reinterpret_cast<void (*) ()>(dlsym(hndlApplication, "hxcpp_main"));
if (main == NULL)
{
ERROR("Faiiled to locate appliction's entry point.");
exit(EXIT_FAILURE);
}
main();
// Android specific : the process needs to exit to trigger
// cleanup of global and static resources (such as the game).
exit(EXIT_SUCCESS);
}
char *getApplicationDirectory(struct android_app* state)
{
// PackageManager packetManager = getPackageManager();
// String packageName = getPackageName();
// PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0);
// String dataDir = packageInfo.applicationInfo.dataDir;
// Connect to JVM.
//
ANativeActivity* activity = state->activity;
JavaVM* jvm = state->activity->vm;
JNIEnv* env = NULL;
jvm->GetEnv((void **)&env, JNI_VERSION_1_6);
jint result = jvm->AttachCurrentThread(&env, NULL);
if (result == JNI_ERR)
{
ERROR("Failied to attach to the Java VM's current thread.");
exit(EXIT_FAILURE);
}
// Perform Java calls.
//
jclass clazz = env->GetObjectClass(activity->clazz);
jmethodID getPackageManagerID = env->GetMethodID(clazz, "getPackageManager", "()Landroid/content/pm/PackageManager;");
jmethodID getPackageNameID = env->GetMethodID(clazz, "getPackageName", "()Ljava/lang/String;");
jobject packageManager = env->CallObjectMethod(activity->clazz, getPackageManagerID);
jobject packageName = env->CallObjectMethod(activity->clazz, getPackageNameID);
clazz = env->GetObjectClass(packageManager);
jmethodID getPackageInfoID = env->GetMethodID(clazz, "getPackageInfo", "(Ljava/lang/String;I)Landroid/content/pm/PackageInfo;");
jobject packageInfo = env->CallObjectMethod(packageManager, getPackageInfoID, packageName, 0);
clazz = env->GetObjectClass(packageInfo);
jfieldID applicationInfoID = env->GetFieldID(clazz, "applicationInfo", "Landroid/content/pm/ApplicationInfo;");
jobject applicationInfo = env->GetObjectField(packageInfo, applicationInfoID);
clazz = env->GetObjectClass(applicationInfo);
jfieldID dataDirID = env->GetFieldID(clazz, "dataDir", "Ljava/lang/String;");
jstring dataDir = static_cast<jstring>(env->GetObjectField(applicationInfo, dataDirID));
// Copy string in a custom buffer.
//
char *buffer = new char[env->GetStringUTFLength(dataDir) + 1];
const char *str = env->GetStringUTFChars(dataDir, NULL);
strcpy(buffer, str);
env->ReleaseStringUTFChars(dataDir, str);
// Detach from JVM.
//
jvm->DetachCurrentThread();
return buffer;
}
void* loadLibrary(const char *path, const char *library)
{
unsigned int length = strlen(path) + strlen("/lib/lib") + strlen(library) + strlen(".so") + 1;
char *fileName = new char[length];
sprintf(fileName, "%s/lib/lib%s.so", path, library);
DEBUG(fileName);
void *result = dlopen(fileName, RTLD_GLOBAL | RTLD_LAZY);
delete [] fileName;
return result;
}
#endif
| 30.235669 | 132 | 0.679376 | Kakise |
364a56c73d6ba5d7c8023a5cc2e657d9e5f30079 | 279 | cpp | C++ | Exercises/Fractal/Fractal.cpp | WorkingFen/CppBasics | 5c27d03af723bc5bf485ae9f8c7787d1b0751f26 | [
"MIT"
] | null | null | null | Exercises/Fractal/Fractal.cpp | WorkingFen/CppBasics | 5c27d03af723bc5bf485ae9f8c7787d1b0751f26 | [
"MIT"
] | null | null | null | Exercises/Fractal/Fractal.cpp | WorkingFen/CppBasics | 5c27d03af723bc5bf485ae9f8c7787d1b0751f26 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main(){
int k=0;
double i,j,r;
for(double y=-17; y<17; ++y){
for(double x=0; x++<80; cout<<" .:-;!/>)|&IH%*#"[k & 15])
for(i=r=k=0; j=r*r-i*i-2+x/25, i=2*r*i+y/10,j*j+i*i<11 && k++ <111; r=j);
cout<<endl;
}
}
| 18.6 | 79 | 0.483871 | WorkingFen |
364adf89e74a56afb5ccd0ad9ea857e0bc2d4172 | 778 | hpp | C++ | Spiel/src/engine/util/Perf.hpp | Ipotrick/CPP-2D-Game-Engine | 9cd87c369d813904d76668fe6153c7c4e8686023 | [
"MIT"
] | null | null | null | Spiel/src/engine/util/Perf.hpp | Ipotrick/CPP-2D-Game-Engine | 9cd87c369d813904d76668fe6153c7c4e8686023 | [
"MIT"
] | null | null | null | Spiel/src/engine/util/Perf.hpp | Ipotrick/CPP-2D-Game-Engine | 9cd87c369d813904d76668fe6153c7c4e8686023 | [
"MIT"
] | null | null | null | #pragma once
#include <chrono>
#include "types/Timing.hpp"
struct PerfLogger {
public:
inline void clear() {
timeMap.clear();
timeFloatMap.clear();
}
inline void commitTimes() {
for (auto& el : timeMap) {
timeFloatMap[el.first] = micsecToFloat(el.second);
el.second = std::chrono::microseconds(0);
}
}
inline void submitTime(std::string_view str, std::chrono::microseconds time = std::chrono::microseconds(0)) {
timeMap[str] = time;
}
inline float getTime(std::string_view str) {
return timeFloatMap[str];
}
inline std::chrono::microseconds& getInputRef(std::string_view str) {
return timeMap[str];
}
private:
std::unordered_map<std::string_view, std::chrono::microseconds> timeMap;
std::unordered_map<std::string_view, float> timeFloatMap;
}; | 25.096774 | 110 | 0.712082 | Ipotrick |
3652d579b85fc97a779b03272288dfc9c7cdf8d6 | 1,999 | cc | C++ | libhcandata/data_file.cc | hcanIngo/openHCAN | 8aef7070482af7ae996755799e5d65d0d3b56553 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 21 | 2015-12-19T21:08:02.000Z | 2021-09-09T09:39:23.000Z | libhcandata/data_file.cc | RealMerlin/openHCAN | 7e15e725c3d6f2a5a36ccd55f5699685356d8287 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 10 | 2015-12-18T20:24:22.000Z | 2021-07-03T12:30:15.000Z | libhcandata/data_file.cc | RealMerlin/openHCAN | 7e15e725c3d6f2a5a36ccd55f5699685356d8287 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 6 | 2015-12-27T17:15:21.000Z | 2021-09-09T09:39:38.000Z | #include "data_file.h"
#include <libhcan++/traceable_error.h>
#include <libhcandata/file_format_v1.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <sys/mman.h>
using namespace hcan;
data_file::data_file(const std::string &filename)
{
int result = open(filename.c_str(),O_RDONLY);
if (result == -1)
throw traceable_error(strerror(errno));
m_fd = result;
struct stat statbuf;
result = fstat(m_fd, &statbuf);
if (result == -1)
throw traceable_error(strerror(errno));
m_size = statbuf.st_size;
m_data = (uint8_t *) mmap(0, m_size, PROT_READ,
MAP_PRIVATE, m_fd, 0);
if (m_data == MAP_FAILED)
throw traceable_error(strerror(errno));
// Header Block einlesen und pruefen:
data_file_header_block_v1_t *header =
(data_file_header_block_v1_t *) m_data;
if (header->magic != DATA_FILE_MAGIC_1)
throw traceable_error("wrong DATA_FILE_MAGIC_1 value");
if (header->magic2 != DATA_FILE_MAGIC_2)
throw traceable_error("wrong DATA_FILE_MAGIC_2 value");
if (header->type != data_file_type_header)
throw traceable_error("wrong header block type");
// Data Block einlesen und pruefen:
data_file_data_block_t *data =
(data_file_data_block_t *) (m_data + sizeof(data_file_header_block_v1_t));
if (data->type != data_file_type_data)
throw traceable_error("wrong data block type");
}
data_file::~data_file()
{
if (m_data)
munmap(m_data,m_size);
}
int data_file::count() const
{
return (m_size - sizeof(data_file_header_block_v1_t) -
sizeof(data_file_data_block_t)) /
sizeof(data_file_frame_entry);
}
data_file_frame_entry data_file::frame(const int idx) const
{
if ((idx < 0) || (idx > count() -1))
throw traceable_error("frame index access out of bounds");
data_file_frame_entry *frames = (data_file_frame_entry *)
(m_data + sizeof(data_file_header_block_v1_t) +
sizeof(data_file_data_block_t));
return frames[idx];
}
void data_file::dump()
{
}
| 22.977011 | 76 | 0.727864 | hcanIngo |
365917a6ae487ce893e0a904ba898fda5f5047c8 | 2,688 | hpp | C++ | include/HostManager.hpp | ARCCN/Host-Manager | f574471839f4bc404229f92f566b54d68bfcdc72 | [
"Apache-2.0"
] | null | null | null | include/HostManager.hpp | ARCCN/Host-Manager | f574471839f4bc404229f92f566b54d68bfcdc72 | [
"Apache-2.0"
] | null | null | null | include/HostManager.hpp | ARCCN/Host-Manager | f574471839f4bc404229f92f566b54d68bfcdc72 | [
"Apache-2.0"
] | 1 | 2019-10-24T17:11:07.000Z | 2019-10-24T17:11:07.000Z | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** @file */
#pragma once
#include "Loader.hpp"
#include "Application.hpp"
#include "SwitchManager.hpp"
#include "Controller.hpp"
#include "lib/ipv4addr.hpp"
#include <mutex>
#include <string>
#include <vector>
#include <unordered_map>
#include <time.h>
namespace runos {
namespace of13 = fluid_msg::of13;
/**
* Host object corresponding end host
*/
class Host {
struct HostImpl* m;
public:
uint64_t id() const;
json11::Json to_json() const;
std::string mac() const;
std::string ip() const;
uint64_t switchID() const;
uint32_t switchPort()const;
void switchID(uint64_t id);
void switchPort(uint32_t port);
void ip(std::string ip);
void ip(ipv4addr ip);
Host(std::string mac, ipv4addr ip);
~Host();
};
/**
* HostManager is looking for new hosts in the network.
* This application connects switch-manager's signal &SwitchManager::switchDiscovered
* and remember all switches and their mac addresses.
*
* Also application handles all packet_ins and if eth_src field is not belongs to switch
* it means that new end host appears in the network.
*/
class HostManager: public Application {
Q_OBJECT
SIMPLE_APPLICATION(HostManager, "host-manager")
public:
HostManager();
~HostManager();
void init(Loader* loader, const Config& config) override;
std::unordered_map<std::string, Host*> hosts();
Host* getHost(std::string mac);
Host* getHost(ipv4addr ip);
public slots:
void onSwitchDiscovered(SwitchPtr dp);
void onSwitchDown(SwitchPtr dp);
void newPort(PortPtr port);
signals:
void hostDiscovered(Host* dev);
private:
struct HostManagerImpl* m;
OFMessageHandlerPtr handler;
std::vector<std::string> switch_macs;
SwitchManager* m_switch_manager;
std::mutex mutex;
void addHost(SwitchPtr sw, ipv4addr ip, std::string mac, uint32_t port);
Host* createHost(std::string mac, ipv4addr ip);
bool findMac(std::string mac);
bool isSwitch(std::string mac);
void attachHost(std::string mac, uint64_t id, uint32_t port);
void delHostForSwitch(SwitchPtr dp);
};
} // namespace runos
| 27.151515 | 88 | 0.710565 | ARCCN |
365999a1264ae33e95c3692cd6fd175c8ba7056c | 2,989 | cpp | C++ | Source/Base/src/ResolverSelf_IP_v4.cpp | RamilGauss/MMO-Framework | c7c97b019adad940db86d6533861deceafb2ba04 | [
"MIT"
] | 27 | 2015-01-08T08:26:29.000Z | 2019-02-10T03:18:05.000Z | Source/Base/src/ResolverSelf_IP_v4.cpp | RamilGauss/MMO-Framework | c7c97b019adad940db86d6533861deceafb2ba04 | [
"MIT"
] | 1 | 2017-04-05T02:02:14.000Z | 2017-04-05T02:02:14.000Z | Source/Base/src/ResolverSelf_IP_v4.cpp | RamilGauss/MMO-Framework | c7c97b019adad940db86d6533861deceafb2ba04 | [
"MIT"
] | 17 | 2015-01-18T02:50:01.000Z | 2019-02-08T21:00:53.000Z | /*
Author: Gudakov Ramil Sergeevich a.k.a. Gauss
Гудаков Рамиль Сергеевич
Contacts: [ramil2085@mail.ru, ramil2085@gmail.com]
See for more information LICENSE.md.
*/
#include "ResolverSelf_IP_v4.h"
#include "SingletonManager.h"
#include <stdio.h>
#include <boost/asio.hpp>
#include <string.h>
#ifndef WIN32
#include <sys/types.h>
#include <ifaddrs.h>
#endif
TResolverSelf_IP_v4::TVectorDesc* TResolverSelf_IP_v4::mVecDesc = nullptr;
TResolverSelf_IP_v4::TResolverSelf_IP_v4()
{
if ( mVecDesc == nullptr )
mVecDesc = SingletonManager()->Get<TVectorDesc>();
if ( mVecDesc->size() == 0 )
GetSelfIp4( mVecDesc );
}
//----------------------------------------------------------------------------------
int TResolverSelf_IP_v4::GetCount()
{
return mVecDesc->size();
}
//----------------------------------------------------------------------------------
bool TResolverSelf_IP_v4::Get( std::string& sIP, int numNetWork )
{
if ( numNetWork >= GetCount() )
return false;
sIP = mVecDesc->operator[]( numNetWork ).s;
return true;
}
//----------------------------------------------------------------------------------
bool TResolverSelf_IP_v4::Get( unsigned int& numIP, int numNetWork )
{
if ( numNetWork >= GetCount() )
return false;
numIP = mVecDesc->operator[]( numNetWork ).ip;
return true;
}
//----------------------------------------------------------------------------------
#ifdef WIN32
void TResolverSelf_IP_v4::GetSelfIp4( TVectorDesc* pDescList )
{
using boost::asio::ip::tcp;
boost::asio::io_service io_service;
tcp::resolver resolver( io_service );
tcp::resolver::query query( boost::asio::ip::host_name(), "" );
tcp::resolver::iterator iter = resolver.resolve( query );
tcp::resolver::iterator end; // End marker.
while ( iter != end )
{
tcp::endpoint ep = *iter;
iter++;
auto address = ep.address();
if ( address.is_v4() == false )
continue;
TDescHost desc;
desc.s = ep.address().to_string();
desc.ip = ep.address().to_v4().to_uint();
pDescList->push_back( desc );
}
}
#else
// http://man7.org/linux/man-pages/man3/getifaddrs.3.html
void TResolverSelf_IP_v4::GetSelfIp4( TVectorDesc* pDescList )
{
struct ifaddrs* ifaddr, * ifa;
if ( getifaddrs( &ifaddr ) == -1 )
return;
char host[NI_MAXHOST];
for ( ifa = ifaddr; ifa != nullptr; ifa = ifa->ifa_next )
{
if ( ifa->ifa_addr == nullptr )
continue;
int family = ifa->ifa_addr->sa_family;
if ( family == AF_INET )
{
struct sockaddr* addr;
int s = getnameinfo( ifa->ifa_addr, sizeof( struct sockaddr_in ),
host, NI_MAXHOST, nullptr, 0, NI_NUMERICHOST );
if ( s != 0 )
continue;
TDescHost desc;
desc.s = host;
desc.ip = ( (sockaddr_in*)( ifa->ifa_addr ) )->sin_addr.s_addr;
pDescList->push_back( desc );
}
}
freeifaddrs( ifaddr );
}
#endif
| 28.466667 | 85 | 0.560723 | RamilGauss |
365a237c9ef04c3c69ee4c12a0bcd9dd512816b5 | 1,384 | hpp | C++ | console/console_app.hpp | BKarschat/wlanitor | e2ac42b6989d4200dc00385c2601c60e198cdc2f | [
"MIT"
] | null | null | null | console/console_app.hpp | BKarschat/wlanitor | e2ac42b6989d4200dc00385c2601c60e198cdc2f | [
"MIT"
] | null | null | null | console/console_app.hpp | BKarschat/wlanitor | e2ac42b6989d4200dc00385c2601c60e198cdc2f | [
"MIT"
] | null | null | null | /* uses ncurses to interact with user
by Bastian Karschat 5.3.2017
*/
class Print_devices;
#ifndef CONSOLE_APP_HPP
#define CONSOLE_APP_HPP
#include "../DeviceMonitor/Device_Monitor.hpp"
#include "../DeviceMonitor/bss.hpp"
#include <unistd.h>
#include <ncurses.h> /* ncurses.h includes stdio.h */
#include <string>
#include <memory>
#include <map>
#include <tins/tins.h>
#include <sstream>
typedef std::map <Tins::Dot11::address_type, std::vector<std::shared_ptr < Device>> >
router_map_type;
typedef std::map <Tins::Dot11::address_type, std::shared_ptr<Device>> device_map_type;
class Print_devices {
private:
std::map <Tins::HWAddress<6>, std::shared_ptr<Device>> _all_router_map;
std::mutex _console_mutex;
WINDOW *cur_window;
void init();
int refresh_lines(int printed_line, std::shared_ptr <Device>);
void line_to_device_mapper();
std::map<int, std::shared_ptr<Device> > line_map;
Device &get_device_from_mac(Tins::Dot11::address_type &tmp_mac);
// std::shared_ptr<router_map_type> router_map;
public:
Print_devices();
~Print_devices();
void start_printing();
void print_bss(std::shared_ptr <bss_subnet> subnet);
void print_string(std::string print);
void set_up_router_map(std::map <Tins::HWAddress<6>, std::shared_ptr<Device>> router_map_tmp);
int update_device();
};
#endif
| 23.457627 | 98 | 0.708815 | BKarschat |
365f0d2138197adc0b0f5c169285aeb8fa8bef2f | 1,762 | hpp | C++ | libs/fnd/tuple/include/bksge/fnd/tuple/inl/tuple_init_type_inl.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 4 | 2018-06-10T13:35:32.000Z | 2021-06-03T14:27:41.000Z | libs/fnd/tuple/include/bksge/fnd/tuple/inl/tuple_init_type_inl.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 566 | 2017-01-31T05:36:09.000Z | 2022-02-09T05:04:37.000Z | libs/fnd/tuple/include/bksge/fnd/tuple/inl/tuple_init_type_inl.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 1 | 2018-07-05T04:40:53.000Z | 2018-07-05T04:40:53.000Z | /**
* @file tuple_init_type_inl.hpp
*
* @brief tuple_init_type の実装
*
* @author myoukaku
*/
#ifndef BKSGE_FND_TUPLE_INL_TUPLE_INIT_TYPE_INL_HPP
#define BKSGE_FND_TUPLE_INL_TUPLE_INIT_TYPE_INL_HPP
#include <bksge/fnd/tuple/tuple_init_type.hpp>
#include <bksge/fnd/tuple/tuple_element.hpp>
#include <bksge/fnd/utility/make_index_sequence.hpp>
#include <cstddef>
namespace bksge
{
namespace detail
{
// tuple_init_type_impl_2
template <typename Tuple, typename Indices>
struct tuple_init_type_impl_2;
template <
template <typename...> class Tuple,
typename... Types,
std::size_t... Indices>
struct tuple_init_type_impl_2<
Tuple<Types...>,
bksge::index_sequence<Indices...>>
{
using type =
Tuple<
bksge::tuple_element_t<
Indices, Tuple<Types...>
>...
>;
};
// tuple_init_type_impl
template <typename Tuple, std::size_t N>
struct tuple_init_type_impl
: public tuple_init_type_impl_2<
Tuple, bksge::make_index_sequence<N - 1>
>
{};
template <typename Tuple>
struct tuple_init_type_impl<Tuple, 0>
{
using type = Tuple;
};
} // namespace detail
// tuple_init_type
template <
template <typename...> class Tuple,
typename... Types
>
struct tuple_init_type<Tuple<Types...>>
: public detail::tuple_init_type_impl<
Tuple<Types...>, sizeof...(Types)
>
{};
template <typename Tuple>
struct tuple_init_type<Tuple const>
: public tuple_init_type<Tuple> {};
template <typename Tuple>
struct tuple_init_type<Tuple volatile>
: public tuple_init_type<Tuple> {};
template <typename Tuple>
struct tuple_init_type<Tuple const volatile>
: public tuple_init_type<Tuple> {};
} // namespace bksge
#endif // BKSGE_FND_TUPLE_INL_TUPLE_INIT_TYPE_INL_HPP
| 20.729412 | 54 | 0.713394 | myoukaku |
366024cf6b599b67673c37cc4b6fcc16160d4f88 | 667 | hpp | C++ | src/Utils/str.hpp | Reewr/master | 76725548d0b6ff3ac22f5383eb0c773d2fcc2a4b | [
"MIT"
] | 4 | 2017-05-22T04:14:06.000Z | 2022-02-09T19:15:10.000Z | src/Utils/str.hpp | Reewr/master | 76725548d0b6ff3ac22f5383eb0c773d2fcc2a4b | [
"MIT"
] | null | null | null | src/Utils/str.hpp | Reewr/master | 76725548d0b6ff3ac22f5383eb0c773d2fcc2a4b | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <vector>
namespace str {
std::string toUpper(const std::string& s);
std::string toLower(const std::string& s);
std::string utf8toStr(unsigned int utf8);
std::string replace(const std::string& s,
const std::string& replaceStr,
const std::string& replaceWith);
std::string joinPath(const std::string& path1, const std::string& path2);
void rTrim(std::string& s);
void lTrim(std::string& s);
void trim(std::string& s);
std::vector<std::string> split(const std::string& s, char delimiter);
std::string join(const std::vector<std::string>& s, char delimiter);
}
| 27.791667 | 75 | 0.652174 | Reewr |
3660667fbb42bfba3160ad417b2fac58e709f355 | 5,117 | cpp | C++ | simulator/src/main.cpp | rollends/SE499 | 949b9cc85abe558b84289d906b730605c2f32c3b | [
"MIT"
] | null | null | null | simulator/src/main.cpp | rollends/SE499 | 949b9cc85abe558b84289d906b730605c2f32c3b | [
"MIT"
] | null | null | null | simulator/src/main.cpp | rollends/SE499 | 949b9cc85abe558b84289d906b730605c2f32c3b | [
"MIT"
] | null | null | null | #include <array>
#include <boost/numeric/odeint.hpp>
#include <Eigen/Geometry>
#include <iostream>
#include "rose499/sfcontrol.hpp"
#include "rose499/sylvester.hpp"
#include "rose499/trackcontrol.hpp"
using namespace Eigen;
using namespace SimulatorTypes;
void fillCampusWorld(World& world);
int main(int argc, char* argv[])
{
namespace odeint = boost::numeric::odeint;
ValueType T = 0.0;
ValueType dt = 0.0001;
// Initial Condition
DriveSystem::StateType x{ 325, 95, std::atan2(1.0, -1.0) };
auto ode45 = odeint::make_controlled( 1.0e-12 , 1.0e-12 , odeint::runge_kutta_cash_karp54<DriveSystem::StateType, ValueType>() );
World world;
DriveSystem robot;
robot.time(T);
robot.state(Map<Matrix<DriveSystem::ValueType, 3, 1>>(x.data()));
const Vector2T goal(218, 600);
const ValueType goalRadius = 5;
SylvesterController sfcontrol(robot, goal, goalRadius);
//SerretFrenetController sfcontrol(robot, goal, goalRadius);
//TrackingController sfcontrol(robot, goal, goalRadius);
sfcontrol.printHeaders(std::cout) << std::endl;
// Create World
fillCampusWorld(world);
// Plan every 200ms
constexpr double PlanTime = 0.05;
constexpr double PrintTime = 0.01;
constexpr ValueType MaxStep = 0.005;
double planningClock = 0.0;
double printingClock = 0.0;
// Prime Planning Algo
sfcontrol.updateKnownWorld(world.observeWorld(robot.viewCone()), true);
do
{
try
{
// If we fail, retry with smaller step size (hopefully it converges, eh?)
if(odeint::fail == ode45.try_step(std::reference_wrapper<DriveController>(sfcontrol), x, T, dt))
continue;
}
catch( InvalidPathException const & )
{
// Force replan.
planningClock = 0.0;
auto observedWorld = world.observeWorld(robot.viewCone());
sfcontrol.updateKnownWorld(observedWorld, true);
}
// Update current state of the robot, and enforce constraints.
robot.time(T);
robot.state(Map<Matrix<DriveSystem::ValueType, 3, 1>>(x.data()));
sfcontrol.operatingPoint(sfcontrol.path().nearestPoint(robot.state().head(2), sfcontrol.operatingPoint()));
dt = std::min( dt, MaxStep );
// If we pass store the system state to file.
if((printingClock += dt) >= PrintTime)
{
printingClock = 0;
std::cout << sfcontrol << std::endl;
}
if(
(planningClock += dt) >= PlanTime
|| (sfcontrol.operatingPoint() >= 1.0)
|| sfcontrol.hasDiverged()
)
{
planningClock = 0.0;
// Observe the world and update our 'known' (Estimated) world state
auto observedWorld = world.observeWorld(robot.viewCone());
sfcontrol.updateKnownWorld(observedWorld, sfcontrol.hasDiverged());
}
} while( (sfcontrol.goal() - Vector2T(x[0], x[1])).norm() > goalRadius );
return 0;
}
void fillCampusWorld(World& world)
{
// Scale , 64 units = 100m
// => 1 m /s = 0.64 units / s
// Really it isn't a terrible assumption to say our speed is 1 units / s as
// that is equivalent to about 1.56 m / s in real world speeds. That is
// fairly reasonable I think.
int i = 0;
world.addBoxObstacle(i++, 351, 429, 77, 200);
world.addBoxObstacle(i++, 292, 528, 40, 35);
world.addBoxObstacle(i++, 244, 525, 40, 35);
world.addBoxObstacle(i++, 258, 488, 73, 35);
world.addBoxObstacle(i++, 203, 530, 32, 31);
world.addBoxObstacle(i++, 200, 487, 37, 36);
world.addBoxObstacle(i++, 98, 542, 102, 52);
world.addBoxObstacle(i++, 60, 471, 70, 60);
world.addBoxObstacle(i++, 92, 404, 55, 61);
world.addBoxObstacle(i++, 176, 404, 40, 61);
world.addBoxObstacle(i++, 222, 455, 111, 12);
world.addBoxObstacle(i++, 227, 393, 42, 30);
world.addBoxObstacle(i++, 270, 384, 61, 67);
world.addBoxObstacle(i++, 391, 347, 36, 80);
world.addBoxObstacle(i++, 298, 294, 70, 79);
world.addBoxObstacle(i++, 250, 320, 37, 53);
world.addBoxObstacle(i++, 219, 330, 21, 57);
world.addBoxObstacle(i++, 121, 360, 62, 41);
world.addBoxObstacle(i++, 140, 294, 68, 64);
world.addBoxObstacle(i++, 121, 244, 37, 42);
world.addBoxObstacle(i++, 180, 224, 38, 38);
world.addBoxObstacle(i++, 227, 257, 63, 50);
world.addBoxObstacle(i++, 270, 227, 46, 28);
world.addBoxObstacle(i++, 294, 264, 93, 20);
world.addBoxObstacle(i++, 326, 217, 16, 51);
world.addBoxObstacle(i++, 359, 190, 40, 69);
world.addBoxObstacle(i++, 283, 197, 69, 16);
world.addBoxObstacle(i++, 333, 164, 20, 47);
world.addBoxObstacle(i++, 266, 136, 33, 53);
world.addBoxObstacle(i++, 254, 200, 17, 15);
world.addBoxObstacle(i++, 217, 139, 17, 51);
world.addBoxObstacle(i++, 177, 154, 30, 37);
world.addBoxObstacle(i++, 113, 193, 48, 23);
world.addBoxObstacle(i++, 81, 140, 84, 47);
world.addBoxObstacle(i++, 144, 86, 53, 52);
world.addBoxObstacle(i++, 85, 49, 54, 79);
}
| 35.783217 | 133 | 0.618917 | rollends |
366120a2ee4c627888859f4d4c14c5dffde31293 | 1,944 | cpp | C++ | lib/tcMenuLib/src/GfxMenuConfig.cpp | protohaus/handheld-ph-meter | 0b823daf6bd418a4cd36e50a81b573dade371143 | [
"MIT"
] | null | null | null | lib/tcMenuLib/src/GfxMenuConfig.cpp | protohaus/handheld-ph-meter | 0b823daf6bd418a4cd36e50a81b573dade371143 | [
"MIT"
] | null | null | null | lib/tcMenuLib/src/GfxMenuConfig.cpp | protohaus/handheld-ph-meter | 0b823daf6bd418a4cd36e50a81b573dade371143 | [
"MIT"
] | 1 | 2021-01-04T09:24:11.000Z | 2021-01-04T09:24:11.000Z | #include <Arduino.h>
#include "GfxMenuConfig.h"
void prepareDefaultGfxConfig(ColorGfxMenuConfig<void*>* config) {
makePadding(config->titlePadding, 5, 5, 20, 5);
makePadding(config->itemPadding, 5, 5, 3, 5);
makePadding(config->widgetPadding, 5, 10, 0, 5);
config->bgTitleColor = RGB(255, 255, 0);
config->fgTitleColor = RGB(0, 0, 0);
config->titleFont = NULL;
config->titleBottomMargin = 10;
config->bgItemColor = RGB(0, 0, 0);
config->fgItemColor = RGB(222, 222, 222);
config->itemFont = NULL;
config->bgSelectColor = RGB(0, 0, 200);
config->fgSelectColor = RGB(255, 255, 255);
config->widgetColor = RGB(30, 30, 30);
config->titleFontMagnification = 4;
config->itemFontMagnification = 2;
}
/**
* The default editing icon for approx 100-150 dpi resolution displays
*/
const uint8_t defEditingIcon[] PGM_TCM = {
0b11111111,0b11111111,
0b01111111,0b11111111,
0b00011100,0b00000000,
0b00000111,0b00000000,
0b00000001,0b1100000,
0b00000000,0b00111000,
0b00000000,0b00111000,
0b00000001,0b11000000,
0b00000111,0b00000000,
0b00011100,0b00000000,
0b01111111,0b11111111,
0b11111111,0b11111111
};
/**
* The default active icon for approx 100-150 dpi resolution displays
*/
const uint8_t defActiveIcon[] PGM_TCM = {
0b00000000,0b11100000,
0b00000000,0b11110000,
0b00000000,0b11111000,
0b00000000,0b11111100,
0b00000000,0b11111110,
0b11111111,0b11111111,
0b11111111,0b11111111,
0b00000000,0b11111110,
0b00000000,0b11111100,
0b00000000,0b11111000,
0b00000000,0b11110000,
0b00000000,0b11100000
};
/**
* The low resolution icon for editing status
*/
const uint8_t loResEditingIcon[] PROGMEM = {
0b00000000,
0b01111110,
0b00000000,
0b00000000,
0b01111110,
0b00000000,
};
/**
* The low resolution icon for indicating active status
*/
const uint8_t loResActiveIcon[] PROGMEM = {
0b00011000,
0b00011100,
0b11111110,
0b11111110,
0b00011100,
0b00011000,
};
| 22.870588 | 71 | 0.733539 | protohaus |
3661f24fb74cf75f577f454e598339f1c7af19a3 | 3,682 | cpp | C++ | Training1/YCbCr2RGB/YCbCr2RGB.cpp | MicrochipTech/fpga-hls-examples | 343e70838e97fc37d2ee4cd131a6fea0cb60ee22 | [
"MIT"
] | 8 | 2021-05-25T15:29:32.000Z | 2022-02-11T17:36:22.000Z | Training1/YCbCr2RGB/YCbCr2RGB.cpp | MicrochipTech/fpga-hls-examples | 343e70838e97fc37d2ee4cd131a6fea0cb60ee22 | [
"MIT"
] | null | null | null | Training1/YCbCr2RGB/YCbCr2RGB.cpp | MicrochipTech/fpga-hls-examples | 343e70838e97fc37d2ee4cd131a6fea0cb60ee22 | [
"MIT"
] | 1 | 2022-03-03T15:39:21.000Z | 2022-03-03T15:39:21.000Z | #include "hls/ap_int.hpp"
#include "hls/ap_fixpt.hpp"
#include "hls/streaming.hpp"
#include <iostream>
using namespace hls;
const int RGB_BITWIDTH = 8;
struct RGB {
ap_uint<RGB_BITWIDTH> R;
ap_uint<RGB_BITWIDTH> G;
ap_uint<RGB_BITWIDTH> B;
};
const int YCBCR_BITWIDTH = 8;
struct YCbCr {
ap_uint<YCBCR_BITWIDTH> Y;
ap_uint<YCBCR_BITWIDTH> Cb;
ap_uint<YCBCR_BITWIDTH> Cr;
};
// Fixed point type: Q11.7
// 11 integer bits and 7 fractional bits
typedef ap_fixpt<18, 11> fixpt_t;
void YCbCr2RGB_smarthls(hls::FIFO<YCbCr> &input_fifo,
hls::FIFO<RGB> &output_fifo) {
#pragma HLS function top
#pragma HLS function pipeline
YCbCr in = input_fifo.read();
RGB rgb;
// change divide by 256 to right shift by 8, add 0.5 for rounding
fixpt_t R = fixpt_t(-222.921) + (( fixpt_t(298.082)*in.Y + fixpt_t(408.583)*in.Cr ) >> 8) + fixpt_t(0.5);
fixpt_t G = fixpt_t( 135.576) + (( fixpt_t(298.082)*in.Y - fixpt_t(100.291)*in.Cb - fixpt_t(208.120)*in.Cr ) >> 8) + fixpt_t(0.5);
fixpt_t B = fixpt_t(-276.836) + (( fixpt_t(298.082)*in.Y + fixpt_t(516.412)*in.Cb ) >> 8) + fixpt_t(0.5);
// saturate values to [0, 255] range
rgb.R = ap_ufixpt<8, 8, AP_TRN, AP_SAT>(R);
rgb.G = ap_ufixpt<8, 8, AP_TRN, AP_SAT>(G);
rgb.B = ap_ufixpt<8, 8, AP_TRN, AP_SAT>(B);
output_fifo.write(rgb);
}
int main() {
hls::FIFO<YCbCr> input_fifo(10);
hls::FIFO<RGB> output_fifo(10);
hls::FIFO<RGB> expected_fifo(10);
YCbCr in;
RGB out, expected;
// Use an online YCbCr to RGB color converter:
// http://www.picturetopeople.org/color_converter.html
// Note: this calculator doesn't handle saturation properly in all cases
// test 1
in.Y = 0; in.Cb = 0; in.Cr = 0;
input_fifo.write(in);
expected.R = 0; expected.G = 136; expected.B = 0;
expected_fifo.write(expected);
// test 2
in.Y = 136; in.Cb = 158; in.Cr = 102;
input_fifo.write(in);
expected.R = 98; expected.G = 149; expected.B = 200;
expected_fifo.write(expected);
// test 3
in.Y = 146; in.Cb = 148; in.Cr = 108;
input_fifo.write(in);
expected.R = 119; expected.G = 160; expected.B = 192;
expected_fifo.write(expected);
// test 4
in.Y = 111; in.Cb = 143; in.Cr = 196;
input_fifo.write(in);
expected.R = 219; expected.G = 49; expected.B = 141;
expected_fifo.write(expected);
// test 5
in.Y = 147; in.Cb = 120; in.Cr = 110;
input_fifo.write(in);
expected.R = 124; expected.G = 170; expected.B = 136;
expected_fifo.write(expected);
// test 6
in.Y = 255; in.Cb = 255; in.Cr = 255;
input_fifo.write(in);
expected.R = 255; expected.G = 125; expected.B = 255;
expected_fifo.write(expected);
// test 7
in.Y = 235; in.Cb = 128; in.Cr = 128;
input_fifo.write(in);
expected.R = 255; expected.G = 255; expected.B = 255;
expected_fifo.write(expected);
while (!input_fifo.empty()) {
YCbCr2RGB_smarthls(input_fifo, output_fifo);
out = output_fifo.read();
expected = expected_fifo.read();
std::cout << "Expected: R=" << expected.R.to_string(10) << " G=" <<
expected.G.to_string(10) << " B=" << expected.B.to_string(10) <<
std::endl;
std::cout << "Actual: R=" << out.R.to_string(10) << " G=" <<
out.G.to_string(10) << " B=" << out.B.to_string(10) <<
std::endl;
if (out.R != expected.R || out.G != expected.G || out.B != expected.B) {
printf("FAIL\n");
return 1;
}
}
printf("PASS\n");
return 0;
}
| 29.456 | 134 | 0.58881 | MicrochipTech |
3669a43cdc015482eb9f121ba9da9e12832f36ef | 369 | cpp | C++ | pulsar/datastore/CacheData.cpp | pulsar-chem/BPModule | f8e64e04fdb01947708f098e833600c459c2ff0e | [
"BSD-3-Clause"
] | null | null | null | pulsar/datastore/CacheData.cpp | pulsar-chem/BPModule | f8e64e04fdb01947708f098e833600c459c2ff0e | [
"BSD-3-Clause"
] | null | null | null | pulsar/datastore/CacheData.cpp | pulsar-chem/BPModule | f8e64e04fdb01947708f098e833600c459c2ff0e | [
"BSD-3-Clause"
] | null | null | null | #include "pulsar/datastore/CacheData.hpp"
namespace pulsar {
std::set<std::string> CacheData::get_keys(void) const
{
return get_my_keys_();
}
size_t CacheData::size(void) const noexcept
{
return get_my_keys_().size();
}
size_t CacheData::erase(const std::string & key)
{
return parent_cmap_->erase(make_full_key_(key));
}
} // close namespace pulsar
| 16.043478 | 53 | 0.712737 | pulsar-chem |
366aec33097d1c95b24d1366232aa156269c98e6 | 919 | cc | C++ | src/datasrc.cc | wagnerflo/cursejay | 2a8fa80d9ab8aff1fda4cc16b2919689268c2bf4 | [
"Apache-2.0"
] | null | null | null | src/datasrc.cc | wagnerflo/cursejay | 2a8fa80d9ab8aff1fda4cc16b2919689268c2bf4 | [
"Apache-2.0"
] | null | null | null | src/datasrc.cc | wagnerflo/cursejay | 2a8fa80d9ab8aff1fda4cc16b2919689268c2bf4 | [
"Apache-2.0"
] | null | null | null | #include "datasrc.hh"
using namespace cursejay;
#define DATA_SOURCE_FLAGS \
MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE | \
MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC | \
MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM | \
MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT
datasrc::datasrc(ma_node_graph& graph, ma_resource_manager& res, const std::string& f)
: filename(f) {
ma_throw(
ma_resource_manager_data_source_init(
&res, filename.c_str(), DATA_SOURCE_FLAGS, NULL, &data_src
),
"Failed to initialize data source."
);
auto node_conf = ma_data_source_node_config_init(&data_src);
ma_throw(
ma_data_source_node_init(&graph, &node_conf, NULL, &node),
"Failed to initialize data source node."
);
}
datasrc::~datasrc() {
ma_data_source_node_uninit(&node, NULL);
ma_resource_manager_data_source_uninit(&data_src);
}
ma_node* datasrc::get_ma_node() {
return &node;
}
| 26.257143 | 86 | 0.758433 | wagnerflo |
3673f8345c9c66641d78d848686389fc0ca6a7ed | 784 | cpp | C++ | PyCommon/externalLibs/BaseLib/math/nr/cpp/recipes/rzextr.cpp | hpgit/HumanFoot | f9a1a341b7c43747bddcd5584b8c98a0d1ac2973 | [
"Apache-2.0"
] | null | null | null | PyCommon/externalLibs/BaseLib/math/nr/cpp/recipes/rzextr.cpp | hpgit/HumanFoot | f9a1a341b7c43747bddcd5584b8c98a0d1ac2973 | [
"Apache-2.0"
] | null | null | null | PyCommon/externalLibs/BaseLib/math/nr/cpp/recipes/rzextr.cpp | hpgit/HumanFoot | f9a1a341b7c43747bddcd5584b8c98a0d1ac2973 | [
"Apache-2.0"
] | 1 | 2021-07-26T15:13:55.000Z | 2021-07-26T15:13:55.000Z | #include "nr.h"
extern Vec_DP *x_p;
extern Mat_DP *d_p;
void NR::rzextr(const int iest, const DP xest, Vec_I_DP &yest, Vec_O_DP &yz,
Vec_O_DP &dy)
{
int j,k,nv;
DP yy,v,ddy,c,b1,b;
nv=yz.size();
Vec_DP fx(iest+1);
Vec_DP &x=*x_p;
Mat_DP &d=*d_p;
x[iest]=xest;
if (iest == 0)
for (j=0;j<nv;j++) {
yz[j]=yest[j];
d[j][0]=yest[j];
dy[j]=yest[j];
}
else {
for (k=0;k<iest;k++)
fx[k+1]=x[iest-(k+1)]/xest;
for (j=0;j<nv;j++) {
v=d[j][0];
d[j][0]=yy=c=yest[j];
for (k=1;k<=iest;k++) {
b1=fx[k]*v;
b=b1-c;
if (b != 0.0) {
b=(c-v)/b;
ddy=c*b;
c=b1*b;
} else
ddy=v;
if (k != iest) v=d[j][k];
d[j][k]=ddy;
yy += ddy;
}
dy[j]=ddy;
yz[j]=yy;
}
}
}
| 16.680851 | 77 | 0.446429 | hpgit |
367602db21180cd2b39643127832302dfb333ded | 6,312 | cpp | C++ | emulator/src/devices/bus/cbm2/hrg.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | 1 | 2022-01-15T21:38:38.000Z | 2022-01-15T21:38:38.000Z | emulator/src/devices/bus/cbm2/hrg.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | emulator/src/devices/bus/cbm2/hrg.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | // license:BSD-3-Clause
// copyright-holders:Curt Coder
/**********************************************************************
CBM 500/600/700 High Resolution Graphics cartridge emulation
**********************************************************************/
/*
TODO:
http://www.wfking.de/hires.htm
- version A (EF9365, 512x512 interlaced, 1 page)
- version B (EF9366, 512x256 non-interlaced, 2 pages)
- 256KB version ROM
*/
#include "emu.h"
#include "hrg.h"
#include "screen.h"
//**************************************************************************
// MACROS/CONSTANTS
//**************************************************************************
#define EF9365_TAG "ef9365"
#define EF9366_TAG EF9365_TAG
#define SCREEN_TAG "screen"
//**************************************************************************
// DEVICE DEFINITIONS
//**************************************************************************
DEFINE_DEVICE_TYPE(CBM2_HRG_A, cbm2_hrg_a_device, "cbm2_hrga", "CBM 500/600/700 High Resolution Graphics (A)")
DEFINE_DEVICE_TYPE(CBM2_HRG_B, cbm2_hrg_b_device, "cbm2_hrgb", "CBM 500/600/700 High Resolution Graphics (B)")
//-------------------------------------------------
// ROM( cbm2_hrg )
//-------------------------------------------------
ROM_START( cbm2_hrg )
ROM_REGION( 0x2000, "bank3", 0 )
ROM_LOAD( "324688-01 sw gr 600.bin", 0x0000, 0x2000, CRC(863e9ef8) SHA1(d75ffa97b2dd4e1baefe4acaa130daae866ab0e8) )
ROM_END
//-------------------------------------------------
// rom_region - device-specific ROM region
//-------------------------------------------------
const tiny_rom_entry *cbm2_hrg_device::device_rom_region() const
{
return ROM_NAME( cbm2_hrg );
}
//-------------------------------------------------
// ADDRESS_MAP( hrg_a_map )
//-------------------------------------------------
void cbm2_hrg_a_device::hrg_a_map(address_map &map)
{
map.global_mask(0x7fff);
map(0x0000, 0x7fff).ram();
}
//-------------------------------------------------
// ADDRESS_MAP( hrg_b_map )
//-------------------------------------------------
void cbm2_hrg_b_device::hrg_b_map(address_map &map)
{
map.global_mask(0x3fff);
map(0x0000, 0x3fff).ram();
}
//-------------------------------------------------
// device_add_mconfig - add device configuration
//-------------------------------------------------
MACHINE_CONFIG_START(cbm2_hrg_a_device::device_add_mconfig)
MCFG_SCREEN_ADD_MONOCHROME(SCREEN_TAG, RASTER, rgb_t::green())
MCFG_SCREEN_UPDATE_DEVICE(EF9365_TAG, ef9365_device, screen_update)
MCFG_SCREEN_SIZE(512, 512)
MCFG_SCREEN_VISIBLE_AREA(0, 512-1, 0, 512-1)
MCFG_SCREEN_REFRESH_RATE(25)
MCFG_PALETTE_ADD_MONOCHROME("palette")
MCFG_DEVICE_ADD(EF9365_TAG, EF9365, 1750000)
MCFG_VIDEO_SET_SCREEN(SCREEN_TAG)
MCFG_DEVICE_ADDRESS_MAP(0, hrg_a_map)
MCFG_EF936X_PALETTE("palette")
MCFG_EF936X_BITPLANES_CNT(1);
MCFG_EF936X_DISPLAYMODE(DISPLAY_MODE_512x512);
MACHINE_CONFIG_END
MACHINE_CONFIG_START(cbm2_hrg_b_device::device_add_mconfig)
MCFG_SCREEN_ADD_MONOCHROME(SCREEN_TAG, RASTER, rgb_t::green())
MCFG_SCREEN_UPDATE_DEVICE(EF9366_TAG, ef9365_device, screen_update)
MCFG_SCREEN_SIZE(512, 256)
MCFG_SCREEN_VISIBLE_AREA(0, 512-1, 0, 256-1)
MCFG_SCREEN_REFRESH_RATE(50)
MCFG_PALETTE_ADD_MONOCHROME("palette")
MCFG_DEVICE_ADD(EF9366_TAG, EF9365, 1750000)
MCFG_VIDEO_SET_SCREEN(SCREEN_TAG)
MCFG_DEVICE_ADDRESS_MAP(0, hrg_b_map)
MCFG_EF936X_PALETTE("palette")
MCFG_EF936X_BITPLANES_CNT(1);
MCFG_EF936X_DISPLAYMODE(DISPLAY_MODE_512x256);
MACHINE_CONFIG_END
//**************************************************************************
// LIVE DEVICE
//**************************************************************************
//-------------------------------------------------
// cbm2_hrg_device - constructor
//-------------------------------------------------
cbm2_hrg_device::cbm2_hrg_device(const machine_config &mconfig, device_type type, const char *tag, device_t *owner, uint32_t clock) :
device_t(mconfig, type, tag, owner, clock),
device_cbm2_expansion_card_interface(mconfig, *this),
m_gdc(*this, EF9366_TAG),
m_bank3(*this, "bank3")
{
}
cbm2_hrg_a_device::cbm2_hrg_a_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) :
cbm2_hrg_device(mconfig, CBM2_HRG_A, tag, owner, clock)
{
}
cbm2_hrg_b_device::cbm2_hrg_b_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) :
cbm2_hrg_device(mconfig, CBM2_HRG_B, tag, owner, clock)
{
}
//-------------------------------------------------
// device_start - device-specific startup
//-------------------------------------------------
void cbm2_hrg_device::device_start()
{
}
//-------------------------------------------------
// device_reset - device-specific reset
//-------------------------------------------------
void cbm2_hrg_device::device_reset()
{
m_gdc->reset();
}
//-------------------------------------------------
// cbm2_bd_r - cartridge data read
//-------------------------------------------------
uint8_t cbm2_hrg_device::cbm2_bd_r(address_space &space, offs_t offset, uint8_t data, int csbank1, int csbank2, int csbank3)
{
if (!csbank3)
{
if (offset < 0x7f80)
{
data = m_bank3->base()[offset & 0x1fff];
}
else if (offset == 0x7f90)
{
/*
bit description
0 light pen
1
2
3
4
5
6
7
*/
}
else if (offset == 0x7fb0)
{
// hard copy
}
else if (offset >= 0x7ff0)
{
data = m_gdc->data_r(space, offset & 0x0f);
}
}
return data;
}
//-------------------------------------------------
// cbm2_bd_w - cartridge data write
//-------------------------------------------------
void cbm2_hrg_device::cbm2_bd_w(address_space &space, offs_t offset, uint8_t data, int csbank1, int csbank2, int csbank3)
{
if (!csbank3)
{
if (offset == 0x7f80)
{
/*
bit description
0 hard copy (0=active)
1 operating page select (version B)
2
3 read-modify-write (1=active)
4 display switch (1=graphic)
5 display page select (version B)
6
7
*/
}
else if (offset >= 0x7ff0)
{
m_gdc->data_w(space, offset & 0x0f, data);
}
}
}
| 25.763265 | 133 | 0.530894 | rjw57 |
36775cb7449d0a839d06a0ed298a6b03666ce299 | 569 | cpp | C++ | src/al_image/model/entity/AlOperateScale.cpp | imalimin/FilmKilns | 2146487c4292d8c7453a53c54d1e24417902f8b7 | [
"MIT"
] | 83 | 2020-11-13T01:35:13.000Z | 2022-03-25T02:12:13.000Z | src/al_image/model/entity/AlOperateScale.cpp | mohsinnaqvi110/FilmKilns | 2146487c4292d8c7453a53c54d1e24417902f8b7 | [
"MIT"
] | 3 | 2020-03-23T07:28:29.000Z | 2020-09-11T17:16:48.000Z | src/al_image/model/entity/AlOperateScale.cpp | lmylr/hwvc | 2146487c4292d8c7453a53c54d1e24417902f8b7 | [
"MIT"
] | 32 | 2020-11-09T04:20:35.000Z | 2022-03-22T04:11:45.000Z | /*
* Copyright (c) 2018-present, aliminabc@gmail.com.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "AlOperateScale.h"
AlOperateScale::AlOperateScale(int32_t layerId, AlRational scale, AlVec2 anchor)
: AlOperateDesc(layerId), scaleX(scale), scaleY(scale), anchor(anchor) {
}
AlOperateScale::AlOperateScale(const AlOperateScale &o)
: AlOperateDesc(o.layerId), scaleX(o.scaleX), scaleY(o.scaleY), anchor(o.anchor) {
}
AlOperateScale::~AlOperateScale() {
}
| 24.73913 | 90 | 0.731107 | imalimin |
36787590687cb44f6aa8ea1f02254ff56f7bf2ac | 709 | hpp | C++ | include/RadonFramework/Threading/Scopelock.hpp | tak2004/RadonFramework | e916627a54a80fac93778d5010c50c09b112259b | [
"Apache-2.0"
] | 3 | 2015-09-15T06:57:50.000Z | 2021-03-16T19:05:02.000Z | include/RadonFramework/Threading/Scopelock.hpp | tak2004/RadonFramework | e916627a54a80fac93778d5010c50c09b112259b | [
"Apache-2.0"
] | 2 | 2015-09-26T12:41:10.000Z | 2015-12-08T08:41:37.000Z | include/RadonFramework/Threading/Scopelock.hpp | tak2004/RadonFramework | e916627a54a80fac93778d5010c50c09b112259b | [
"Apache-2.0"
] | 1 | 2015-07-09T02:56:34.000Z | 2015-07-09T02:56:34.000Z | #ifndef RF_THREADING_SCOPELOCK_HPP
#define RF_THREADING_SCOPELOCK_HPP
#if _MSC_VER > 1000
#pragma once
#endif
namespace RadonFramework::System::Threading
{
class Mutex;
}
namespace RadonFramework::Threading
{
class Scopelock
{
public:
Scopelock(System::Threading::Mutex& Ref);
~Scopelock();
protected:
System::Threading::Mutex* m_Mutex;
Scopelock() = default;
Scopelock(const Scopelock& Other);
Scopelock& operator=(const Scopelock& Other);
};
} // namespace RadonFramework::Threading
#ifndef RF_SHORTHAND_NAMESPACE_THREAD
#define RF_SHORTHAND_NAMESPACE_THREAD
namespace RF_Thread = RadonFramework::Threading;
#endif // !RF_SHORTHAND_NAMESPACE_THREAD
#endif // RF_THREADING_SCOPELOCK_HPP
| 20.257143 | 48 | 0.787024 | tak2004 |
36787d0ed9f3f2155ec8cd66c180de69135c4b21 | 22,913 | cpp | C++ | silkrpc/txpool/miner_test.cpp | enriavil1/silkrpc | 1fa2109658d4c89b6cfdd5190d919bd1324f367e | [
"Apache-2.0"
] | null | null | null | silkrpc/txpool/miner_test.cpp | enriavil1/silkrpc | 1fa2109658d4c89b6cfdd5190d919bd1324f367e | [
"Apache-2.0"
] | null | null | null | silkrpc/txpool/miner_test.cpp | enriavil1/silkrpc | 1fa2109658d4c89b6cfdd5190d919bd1324f367e | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2020-2021 The Silkrpc Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "miner.hpp"
#include <functional>
#include <memory>
#include <system_error>
#include <thread>
#include <type_traits>
#include <utility>
#include <asio/io_context.hpp>
#include <asio/co_spawn.hpp>
#include <asio/use_future.hpp>
#include <catch2/catch.hpp>
#include <evmc/evmc.hpp>
#include <gmock/gmock.h>
#include <grpcpp/grpcpp.h>
#include <silkworm/common/base.hpp>
#include <silkrpc/common/log.hpp>
#include <silkrpc/grpc/completion_runner.hpp>
#include <silkrpc/interfaces/txpool/mining.grpc.pb.h>
#include <silkrpc/interfaces/txpool/mining_mock_fix24351.grpc.pb.h>
namespace grpc {
inline bool operator==(const Status& lhs, const Status& rhs) {
return lhs.error_code() == rhs.error_code() &&
lhs.error_message() == rhs.error_message() &&
lhs.error_details() == rhs.error_details();
}
} // namespace grpc
namespace txpool {
inline bool operator==(const GetWorkReply& lhs, const GetWorkReply& rhs) {
if (lhs.headerhash() != rhs.headerhash()) return false;
if (lhs.seedhash() != rhs.seedhash()) return false;
if (lhs.target() != rhs.target()) return false;
if (lhs.blocknumber() != rhs.blocknumber()) return false;
return true;
}
} // namespace txpool
namespace silkrpc::txpool {
using Catch::Matchers::Message;
using testing::MockFunction;
using testing::Return;
using testing::_;
using evmc::literals::operator""_bytes32;
TEST_CASE("create GetWorkClient", "[silkrpc][txpool][miner]") {
SILKRPC_LOG_VERBOSITY(LogLevel::None);
class MockClientAsyncGetWorkReader final : public grpc::ClientAsyncResponseReaderInterface<::txpool::GetWorkReply> {
public:
MockClientAsyncGetWorkReader(::txpool::GetWorkReply msg, ::grpc::Status status) : msg_(std::move(msg)), status_(std::move(status)) {}
~MockClientAsyncGetWorkReader() final = default;
void StartCall() override {};
void ReadInitialMetadata(void* tag) override {};
void Finish(::txpool::GetWorkReply* msg, ::grpc::Status* status, void* tag) override {
*msg = msg_;
*status = status_;
};
private:
::txpool::GetWorkReply msg_;
grpc::Status status_;
};
SECTION("start async GetWork call, get status OK and non-empty work") {
std::unique_ptr<::txpool::Mining::StubInterface> stub{std::make_unique<::txpool::FixIssue24351_MockMiningStub>()};
grpc::CompletionQueue queue;
txpool::GetWorkClient client{stub, &queue};
::txpool::GetWorkReply reply;
reply.set_headerhash("0x209f062567c161c5f71b3f57a7de277b0e95c3455050b152d785ad7524ef8ee7");
reply.set_seedhash("0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347");
reply.set_target("0xe7536c5b61ed0e0ab7f3ce7f085806d40f716689c0c086676757de401b595658");
reply.set_blocknumber("0x00000000");
MockClientAsyncGetWorkReader mock_reader{reply, ::grpc::Status::OK};
EXPECT_CALL(*dynamic_cast<::txpool::FixIssue24351_MockMiningStub*>(stub.get()), PrepareAsyncGetWorkRaw(_, _, _)).WillOnce(Return(&mock_reader));
MockFunction<void(::grpc::Status, ::txpool::GetWorkReply)> mock_callback;
EXPECT_CALL(mock_callback, Call(grpc::Status::OK, reply));
client.async_call(::txpool::GetWorkRequest{}, mock_callback.AsStdFunction());
client.completed(true);
}
SECTION("start async GetWork call, get status OK and empty work") {
std::unique_ptr<::txpool::Mining::StubInterface> stub{std::make_unique<::txpool::FixIssue24351_MockMiningStub>()};
grpc::CompletionQueue queue;
txpool::GetWorkClient client{stub, &queue};
MockClientAsyncGetWorkReader mock_reader{::txpool::GetWorkReply{}, ::grpc::Status::OK};
EXPECT_CALL(*dynamic_cast<::txpool::FixIssue24351_MockMiningStub*>(stub.get()), PrepareAsyncGetWorkRaw(_, _, _)).WillOnce(Return(&mock_reader));
MockFunction<void(::grpc::Status, ::txpool::GetWorkReply)> mock_callback;
EXPECT_CALL(mock_callback, Call(grpc::Status::OK, ::txpool::GetWorkReply{}));
client.async_call(::txpool::GetWorkRequest{}, mock_callback.AsStdFunction());
client.completed(true);
}
SECTION("start async GetWork call and get status KO") {
std::unique_ptr<::txpool::Mining::StubInterface> stub{std::make_unique<::txpool::FixIssue24351_MockMiningStub>()};
grpc::CompletionQueue queue;
txpool::GetWorkClient client{stub, &queue};
MockClientAsyncGetWorkReader mock_reader{::txpool::GetWorkReply{}, ::grpc::Status{::grpc::StatusCode::INTERNAL, "internal error"}};
EXPECT_CALL(*dynamic_cast<::txpool::FixIssue24351_MockMiningStub*>(stub.get()), PrepareAsyncGetWorkRaw(_, _, _)).WillOnce(Return(&mock_reader));
MockFunction<void(::grpc::Status, ::txpool::GetWorkReply)> mock_callback;
EXPECT_CALL(mock_callback, Call(::grpc::Status{::grpc::StatusCode::INTERNAL, "internal error"}, ::txpool::GetWorkReply{}));
client.async_call(::txpool::GetWorkRequest{}, mock_callback.AsStdFunction());
client.completed(false);
}
}
class EmptyMiningService : public ::txpool::Mining::Service {
public:
::grpc::Status GetWork(::grpc::ServerContext* context, const ::txpool::GetWorkRequest* request, ::txpool::GetWorkReply* response) override {
return ::grpc::Status::OK;
}
::grpc::Status SubmitWork(::grpc::ServerContext* context, const ::txpool::SubmitWorkRequest* request, ::txpool::SubmitWorkReply* response) override {
return ::grpc::Status::OK;
}
::grpc::Status HashRate(::grpc::ServerContext* context, const ::txpool::HashRateRequest* request, ::txpool::HashRateReply* response) override {
return ::grpc::Status::OK;
}
::grpc::Status SubmitHashRate(::grpc::ServerContext* context, const ::txpool::SubmitHashRateRequest* request, ::txpool::SubmitHashRateReply* response) override {
return ::grpc::Status::OK;
}
::grpc::Status Mining(::grpc::ServerContext* context, const ::txpool::MiningRequest* request, ::txpool::MiningReply* response) override {
return ::grpc::Status::OK;
}
};
class ClientServerTestBox {
public:
explicit ClientServerTestBox(grpc::Service* service) : completion_runner_{queue_, io_context_} {
server_address_ << "localhost:" << 12345; // TODO(canepat): grpc_pick_unused_port_or_die
grpc::ServerBuilder builder;
builder.AddListeningPort(server_address_.str(), grpc::InsecureServerCredentials());
builder.RegisterService(service);
server_ = builder.BuildAndStart();
io_context_thread_ = std::thread([&]() { io_context_.run(); });
completion_runner_thread_ = std::thread([&]() { completion_runner_.run(); });
}
template<auto method, typename T>
auto make_method_proxy() {
const auto channel = grpc::CreateChannel(server_address_.str(), grpc::InsecureChannelCredentials());
std::unique_ptr<T> target{std::make_unique<T>(io_context_, channel, &queue_)};
return [target = std::move(target)](auto&&... args) {
return (target.get()->*method)(std::forward<decltype(args)>(args)...);
};
}
~ClientServerTestBox() {
server_->Shutdown();
io_context_.stop();
completion_runner_.stop();
if (io_context_thread_.joinable()) {
io_context_thread_.join();
}
if (completion_runner_thread_.joinable()) {
completion_runner_thread_.join();
}
}
private:
asio::io_context io_context_;
asio::io_context::work work_{io_context_};
grpc::CompletionQueue queue_;
CompletionRunner completion_runner_;
std::ostringstream server_address_;
std::unique_ptr<grpc::Server> server_;
std::thread io_context_thread_;
std::thread completion_runner_thread_;
};
template<typename T, auto method, typename R, typename ...Args>
asio::awaitable<R> test_comethod(::txpool::Mining::Service* service, Args... args) {
ClientServerTestBox test_box{service};
auto method_proxy{test_box.make_method_proxy<method, T>()};
co_return co_await method_proxy(args...);
}
auto test_get_work = test_comethod<txpool::Miner, &txpool::Miner::get_work, txpool::WorkResult>;
auto test_submit_work = test_comethod<txpool::Miner, &txpool::Miner::submit_work, bool, silkworm::Bytes, evmc::bytes32, evmc::bytes32>;
auto test_get_hashrate = test_comethod<txpool::Miner, &txpool::Miner::get_hash_rate, uint64_t>;
auto test_submit_hashrate = test_comethod<txpool::Miner, &txpool::Miner::submit_hash_rate, bool, intx::uint256, evmc::bytes32>;
auto test_get_mining = test_comethod<txpool::Miner, &txpool::Miner::get_mining, txpool::MiningResult>;
TEST_CASE("Miner::get_work", "[silkrpc][txpool][miner]") {
SILKRPC_LOG_VERBOSITY(LogLevel::None);
SECTION("call get_work and get result") {
class TestSuccessMiningService : public ::txpool::Mining::Service {
public:
::grpc::Status GetWork(::grpc::ServerContext* context, const ::txpool::GetWorkRequest* request, ::txpool::GetWorkReply* response) override {
response->set_headerhash("0x209f062567c161c5f71b3f57a7de277b0e95c3455050b152d785ad7524ef8ee7");
response->set_seedhash("0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347");
response->set_target("0xe7536c5b61ed0e0ab7f3ce7f085806d40f716689c0c086676757de401b595658");
response->set_blocknumber("0x00000000");
return ::grpc::Status::OK;
}
};
TestSuccessMiningService service;
asio::io_context io_context;
auto result{asio::co_spawn(io_context, test_get_work(&service), asio::use_future)};
io_context.run();
const auto work_result = result.get();
CHECK(work_result.header_hash == 0x209f062567c161c5f71b3f57a7de277b0e95c3455050b152d785ad7524ef8ee7_bytes32);
CHECK(work_result.seed_hash == 0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347_bytes32);
CHECK(work_result.target == 0xe7536c5b61ed0e0ab7f3ce7f085806d40f716689c0c086676757de401b595658_bytes32);
CHECK(work_result.block_number == *silkworm::from_hex("0x00000000"));
}
SECTION("call get_work and get default empty result") {
EmptyMiningService service;
asio::io_context io_context;
auto result{asio::co_spawn(io_context, test_get_work(&service), asio::use_future)};
io_context.run();
const auto work_result = result.get();
CHECK(!work_result.header_hash);
CHECK(!work_result.seed_hash);
CHECK(!work_result.target);
CHECK(work_result.block_number == *silkworm::from_hex("0x"));
}
SECTION("call get_work and get failure") {
class TestFailureMiningService : public ::txpool::Mining::Service {
public:
::grpc::Status GetWork(::grpc::ServerContext* context, const ::txpool::GetWorkRequest* request, ::txpool::GetWorkReply* response) override {
return ::grpc::Status::CANCELLED;
}
};
TestFailureMiningService service;
asio::io_context io_context;
auto result{asio::co_spawn(io_context, test_get_work(&service), asio::use_future)};
io_context.run();
CHECK_THROWS_AS(result.get(), std::system_error);
}
}
TEST_CASE("Miner::get_hashrate", "[silkrpc][txpool][miner]") {
SILKRPC_LOG_VERBOSITY(LogLevel::None);
SECTION("call get_hashrate and get result") {
class TestSuccessMiningService : public ::txpool::Mining::Service {
public:
::grpc::Status HashRate(::grpc::ServerContext* context, const ::txpool::HashRateRequest* request, ::txpool::HashRateReply* response) override {
response->set_hashrate(1234567);
return ::grpc::Status::OK;
}
};
TestSuccessMiningService service;
asio::io_context io_context;
auto result{asio::co_spawn(io_context, test_get_hashrate(&service), asio::use_future)};
io_context.run();
const auto hash_rate = result.get();
CHECK(hash_rate == 1234567);
}
SECTION("call get_hashrate and get default empty result") {
EmptyMiningService service;
asio::io_context io_context;
auto result{asio::co_spawn(io_context, test_get_hashrate(&service), asio::use_future)};
io_context.run();
const auto hash_rate = result.get();
CHECK(hash_rate == 0);
}
SECTION("call get_hashrate and get failure") {
class TestFailureMiningService : public ::txpool::Mining::Service {
public:
::grpc::Status HashRate(::grpc::ServerContext* context, const ::txpool::HashRateRequest* request, ::txpool::HashRateReply* response) override {
return ::grpc::Status::CANCELLED;
}
};
TestFailureMiningService service;
asio::io_context io_context;
auto result{asio::co_spawn(io_context, test_get_hashrate(&service), asio::use_future)};
io_context.run();
CHECK_THROWS_AS(result.get(), std::system_error);
}
}
TEST_CASE("Miner::get_mining", "[silkrpc][txpool][miner]") {
SILKRPC_LOG_VERBOSITY(LogLevel::None);
class TestSuccessMiningService : public ::txpool::Mining::Service {
public:
explicit TestSuccessMiningService(bool enabled, bool running) : enabled_(enabled), running_(running) {}
::grpc::Status Mining(::grpc::ServerContext* context, const ::txpool::MiningRequest* request, ::txpool::MiningReply* response) override {
response->set_enabled(enabled_);
response->set_running(running_);
return ::grpc::Status::OK;
}
private:
bool enabled_;
bool running_;
};
SECTION("call get_mining and get result for enabled and running") {
TestSuccessMiningService service{true, true};
asio::io_context io_context;
auto result{asio::co_spawn(io_context, test_get_mining(&service), asio::use_future)};
io_context.run();
const auto mining_result = result.get();
CHECK(mining_result.enabled);
CHECK(mining_result.running);
}
SECTION("call get_mining and get result for enabled and running") {
TestSuccessMiningService service{/*enabled=*/true, /*running=*/true};
asio::io_context io_context;
auto result{asio::co_spawn(io_context, test_get_mining(&service), asio::use_future)};
io_context.run();
const auto mining_result = result.get();
CHECK(mining_result.enabled);
CHECK(mining_result.running);
}
SECTION("call get_mining and get result for enabled and not running") {
TestSuccessMiningService service{/*enabled=*/true, /*running=*/false};
asio::io_context io_context;
auto result{asio::co_spawn(io_context, test_get_mining(&service), asio::use_future)};
io_context.run();
const auto mining_result = result.get();
CHECK(mining_result.enabled);
CHECK(!mining_result.running);
}
SECTION("call get_mining and get result for not enabled and not running") {
TestSuccessMiningService service{/*enabled=*/false, /*running=*/false};
asio::io_context io_context;
auto result{asio::co_spawn(io_context, test_get_mining(&service), asio::use_future)};
io_context.run();
const auto mining_result = result.get();
CHECK(!mining_result.enabled);
CHECK(!mining_result.running);
}
SECTION("call get_mining and get default empty result") {
EmptyMiningService service;
asio::io_context io_context;
auto result{asio::co_spawn(io_context, test_get_mining(&service), asio::use_future)};
io_context.run();
const auto mining_result = result.get();
CHECK(!mining_result.enabled);
CHECK(!mining_result.running);
}
SECTION("call get_mining and get failure") {
class TestFailureMiningService : public ::txpool::Mining::Service {
public:
::grpc::Status Mining(::grpc::ServerContext* context, const ::txpool::MiningRequest* request, ::txpool::MiningReply* response) override {
return ::grpc::Status::CANCELLED;
}
};
TestFailureMiningService service;
asio::io_context io_context;
auto result{asio::co_spawn(io_context, test_get_mining(&service), asio::use_future)};
io_context.run();
CHECK_THROWS_AS(result.get(), std::system_error);
}
}
TEST_CASE("Miner::submit_work", "[silkrpc][txpool][miner]") {
SILKRPC_LOG_VERBOSITY(LogLevel::None);
class TestSuccessMiningService : public ::txpool::Mining::Service {
public:
explicit TestSuccessMiningService(bool ok) : ok_(ok) {}
::grpc::Status SubmitWork(::grpc::ServerContext* context, const ::txpool::SubmitWorkRequest* request, ::txpool::SubmitWorkReply* response) override {
response->set_ok(ok_);
return ::grpc::Status::OK;
}
private:
bool ok_;
};
SECTION("call submit_work and get OK result") {
TestSuccessMiningService service{/*ok=*/true};
silkworm::Bytes block_nonce{}; // don't care
evmc::bytes32 pow_hash{silkworm::kEmptyHash}; // don't care
evmc::bytes32 digest{silkworm::kEmptyHash}; // don't care
asio::io_context io_context;
auto result{asio::co_spawn(io_context, test_submit_work(&service, block_nonce, pow_hash, digest), asio::use_future)};
io_context.run();
const auto ok = result.get();
CHECK(ok);
}
SECTION("call submit_work and get KO result") {
TestSuccessMiningService service{/*ok=*/false};
silkworm::Bytes block_nonce{}; // don't care
evmc::bytes32 pow_hash{silkworm::kEmptyHash}; // don't care
evmc::bytes32 digest{silkworm::kEmptyHash}; // don't care
asio::io_context io_context;
auto result{asio::co_spawn(io_context, test_submit_work(&service, block_nonce, pow_hash, digest), asio::use_future)};
io_context.run();
const auto ok = result.get();
CHECK(!ok);
}
SECTION("call submit_work and get default empty result") {
EmptyMiningService service;
silkworm::Bytes block_nonce{}; // don't care
evmc::bytes32 pow_hash{silkworm::kEmptyHash}; // don't care
evmc::bytes32 digest{silkworm::kEmptyHash}; // don't care
asio::io_context io_context;
auto result{asio::co_spawn(io_context, test_submit_work(&service, block_nonce, pow_hash, digest), asio::use_future)};
io_context.run();
const auto ok = result.get();
CHECK(!ok);
}
SECTION("call submit_work and get failure") {
class TestFailureMiningService : public ::txpool::Mining::Service {
public:
::grpc::Status HashRate(::grpc::ServerContext* context, const ::txpool::HashRateRequest* request, ::txpool::HashRateReply* response) override {
return ::grpc::Status::CANCELLED;
}
};
TestFailureMiningService service;
silkworm::Bytes block_nonce{}; // don't care
evmc::bytes32 pow_hash{silkworm::kEmptyHash}; // don't care
evmc::bytes32 digest{silkworm::kEmptyHash}; // don't care
asio::io_context io_context;
auto result{asio::co_spawn(io_context, test_submit_work(&service, block_nonce, pow_hash, digest), asio::use_future)};
io_context.run();
CHECK_THROWS_AS(result.get(), std::system_error);
}
}
TEST_CASE("Miner::submit_hash_rate", "[silkrpc][txpool][miner]") {
SILKRPC_LOG_VERBOSITY(LogLevel::None);
class TestSuccessMiningService : public ::txpool::Mining::Service {
public:
explicit TestSuccessMiningService(bool ok) : ok_(ok) {}
::grpc::Status SubmitHashRate(::grpc::ServerContext* context, const ::txpool::SubmitHashRateRequest* request, ::txpool::SubmitHashRateReply* response) override {
response->set_ok(ok_);
return ::grpc::Status::OK;
}
private:
bool ok_;
};
SECTION("call submit_hash_rate and get OK result") {
TestSuccessMiningService service{/*ok=*/true};
intx::uint256 rate{}; // don't care
evmc::bytes32 id{silkworm::kEmptyHash}; // don't care
asio::io_context io_context;
auto result{asio::co_spawn(io_context, test_submit_hashrate(&service, rate, id), asio::use_future)};
io_context.run();
const auto ok = result.get();
CHECK(ok);
}
SECTION("call submit_hash_rate and get KO result") {
TestSuccessMiningService service{/*ok=*/false};
intx::uint256 rate{}; // don't care
evmc::bytes32 id{silkworm::kEmptyHash}; // don't care
asio::io_context io_context;
auto result{asio::co_spawn(io_context, test_submit_hashrate(&service, rate, id), asio::use_future)};
io_context.run();
const auto ok = result.get();
CHECK(!ok);
}
SECTION("call submit_hash_rate and get default empty result") {
EmptyMiningService service;
intx::uint256 rate{}; // don't care
evmc::bytes32 id{silkworm::kEmptyHash}; // don't care
asio::io_context io_context;
auto result{asio::co_spawn(io_context, test_submit_hashrate(&service, rate, id), asio::use_future)};
io_context.run();
const auto ok = result.get();
CHECK(!ok);
}
SECTION("call submit_hash_rate and get failure") {
class TestFailureMiningService : public ::txpool::Mining::Service {
public:
::grpc::Status SubmitHashRate(::grpc::ServerContext* context, const ::txpool::SubmitHashRateRequest* request, ::txpool::SubmitHashRateReply* response) override {
return ::grpc::Status::CANCELLED;
}
};
TestFailureMiningService service;
intx::uint256 rate{}; // don't care
evmc::bytes32 id{silkworm::kEmptyHash}; // don't care
asio::io_context io_context;
auto result{asio::co_spawn(io_context, test_submit_hashrate(&service, rate, id), asio::use_future)};
io_context.run();
CHECK_THROWS_AS(result.get(), std::system_error);
}
}
} // namespace silkrpc::txpool
| 43.150659 | 173 | 0.672195 | enriavil1 |
367956547b77b4893d8a733a9bef7d1a6bef90c8 | 1,891 | cpp | C++ | Candy Crush/Candy Crush/SDL_Button.cpp | JoanStinson/CandyCrush | 0e1f478fbf50a1e1073f8bf955a0ef25eba527e2 | [
"MIT"
] | 2 | 2020-08-20T04:04:52.000Z | 2021-03-31T03:42:29.000Z | Candy Crush/Candy Crush/SDL_Button.cpp | JoanStinson/Candy_Crush | 0e1f478fbf50a1e1073f8bf955a0ef25eba527e2 | [
"MIT"
] | null | null | null | Candy Crush/Candy Crush/SDL_Button.cpp | JoanStinson/Candy_Crush | 0e1f478fbf50a1e1073f8bf955a0ef25eba527e2 | [
"MIT"
] | 1 | 2020-05-05T12:47:25.000Z | 2020-05-05T12:47:25.000Z | // SDL_button.c - an implementation of buttons to be used with SDL
// Author : Tim Smith (tim14smith@gmail.com)
#include "SDL_Button.h"
#include <stdbool.h>
void SDL_Button_free(SDL_Button_t *button) {
delete button->internal_surface;
delete button->location_and_size;
delete button;
}
// Get a new SDL button
SDL_Button_t* SDL_Button(SDL_Surface *surface, int x_location, int y_location, int button_width, int button_height) {
SDL_Button_t *button = new SDL_Button_t();
button->internal_surface = surface;
SDL_Rect *rect = new SDL_Rect();
rect->x = x_location;
rect->y = y_location;
rect->w = button_width;
rect->h = button_height;
button->location_and_size = rect;
return button;
}
bool mouse_on_button(SDL_Rect *button_rect, int mouse_x, int mouse_y) {
int button_x = button_rect->x;
int button_y = button_rect->y;
int button_w = button_rect->w;
int button_h = button_rect->h;
bool in_width = (mouse_x > button_x) && (mouse_x < (button_x + button_w));
bool in_height = (mouse_y > button_y) && (mouse_y < (button_y + button_h));
return (in_width && in_height);
}
bool SDL_Button_mouse_down(SDL_Button_t *button, SDL_Event *e) {
if ((e->type == SDL_MOUSEBUTTONDOWN)) {
int x = e->button.x;
int y = e->button.y;
return (mouse_on_button(button->location_and_size, x, y));
}
return false;
}
bool SDL_Button_mouse_up(SDL_Button_t *button, SDL_Event *e) {
if ((e->type == SDL_MOUSEBUTTONUP)) {
int x = e->button.x;
int y = e->button.y;
return (mouse_on_button(button->location_and_size, x, y));
}
return false;
}
bool SDL_Button_mouse_over(SDL_Button_t *button, SDL_Event *e) {
if (e->type == SDL_MOUSEMOTION) {
int x = e->motion.x;
int y = e->motion.y;
return(mouse_on_button(button->location_and_size, x, y));
}
return false;
}
bool SDL_Button_mouse_out(SDL_Button_t *button, SDL_Event *e) {
return !SDL_Button_mouse_over(button, e);
} | 27.808824 | 117 | 0.717081 | JoanStinson |
367ae162e9c19dc2a98717c7c154c55e849f8b61 | 1,908 | cpp | C++ | modules/complex-number/test/test_chernyh_daria_complex_number.cpp | splashbros30/devtools-course-practice | 4f4c987ce2ee602e835b9b94ece03f3590abbafc | [
"CC-BY-4.0"
] | 1 | 2021-03-20T18:53:08.000Z | 2021-03-20T18:53:08.000Z | modules/complex-number/test/test_chernyh_daria_complex_number.cpp | splashbros30/devtools-course-practice | 4f4c987ce2ee602e835b9b94ece03f3590abbafc | [
"CC-BY-4.0"
] | 3 | 2021-04-22T17:12:19.000Z | 2021-05-14T12:16:25.000Z | modules/complex-number/test/test_chernyh_daria_complex_number.cpp | splashbros30/devtools-course-practice | 4f4c987ce2ee602e835b9b94ece03f3590abbafc | [
"CC-BY-4.0"
] | null | null | null | // Copyright 2021 Chernyh Daria
#include <gtest/gtest.h>
#include <tuple>
#include "include/complex_number.h"
typedef testing::TestWithParam<std::tuple<double, double>>
Chernyh_Daria_ComplexNumberTest_Parametrized;
TEST_P(Chernyh_Daria_ComplexNumberTest_Parametrized,
Addition_of_conjugate) {
double numberRe = std::get<0>(GetParam());
double numberIm = std::get<1>(GetParam());
double numberIm_conj = -numberIm;
ComplexNumber number(numberRe, numberIm);
ComplexNumber number_conj(numberRe, numberIm_conj);
ComplexNumber result = number + number_conj;
double check_Re = numberRe + numberRe;
double check_Im = numberIm + numberIm_conj;
ASSERT_DOUBLE_EQ(check_Re, result.getRe());
ASSERT_DOUBLE_EQ(check_Im, result.getIm());
}
typedef testing::TestWithParam<std::tuple<double, double>>
Chernyh_Daria_ComplexNumberTest_Parametrized;
TEST_P(Chernyh_Daria_ComplexNumberTest_Parametrized,
Division_of_conjugate) {
double numberRe = std::get<0>(GetParam());
double numberIm = std::get<1>(GetParam());
double numberIm_conj = -numberIm;
ComplexNumber number(numberRe, numberIm);
ComplexNumber number_conj(numberRe, numberIm_conj);
ComplexNumber result = number / number_conj;
double check_Re = (numberRe * numberRe + numberIm * numberIm_conj)
/ (numberRe * numberRe + numberIm_conj * numberIm_conj);
double check_Im = (numberRe * numberIm - numberRe * numberIm_conj)
/ (numberRe * numberRe + numberIm_conj * numberIm_conj);
ASSERT_DOUBLE_EQ(check_Re, result.getRe());
ASSERT_DOUBLE_EQ(check_Im, result.getIm());
}
TEST(Chernyh_Daria_ComplexNumberTEST, Not_equality_of_conjugate) {
ComplexNumber number(21, 6);
ComplexNumber number_conj(21, -6);
ASSERT_NE(number, number_conj);
}
INSTANTIATE_TEST_CASE_P(/**/, Chernyh_Daria_ComplexNumberTest_Parametrized,
testing::Combine(
testing::Values(-1.0, 3.0),
testing::Values(6.0, -2.0)
));
| 32.896552 | 75 | 0.760482 | splashbros30 |
367cf251fab34c37c97ec850d41807fc4614d492 | 7,683 | cpp | C++ | TemplePlus/party.cpp | edoipi/TemplePlus | f0e552289822fea908f16daa379fa568b1bd286d | [
"MIT"
] | null | null | null | TemplePlus/party.cpp | edoipi/TemplePlus | f0e552289822fea908f16daa379fa568b1bd286d | [
"MIT"
] | null | null | null | TemplePlus/party.cpp | edoipi/TemplePlus | f0e552289822fea908f16daa379fa568b1bd286d | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "common.h"
#include "party.h"
#include "config/config.h"
#include "util/fixes.h"
#include "critter.h"
#include "obj.h"
#include "location.h"
#include "gamesystems/gamesystems.h"
#include "gamesystems/objects/objsystem.h"
#include "condition.h"
#include "combat.h"
#include "turn_based.h"
struct LegacyPartySystemAddresses : temple::AddressTable
{
GroupArray * groupNpcFollowers;
GroupArray * groupCurrentlySelected;
GroupArray * groupAiFollowers;
GroupArray * groupPcs;
GroupArray * groupList; // the entire party (PCs, NPCs and AI followers)
void(__cdecl * AddToCurrentlySelected)(objHndl objHnd);
void(*ArraySort)(void* arr, size_t arrSize, size_t elementSize, int(*sortFunc)(void*, void*));
int * partyMoney; // size 4 array containing: CP, SP, GP, PP
LegacyPartySystemAddresses()
{
rebase(AddToCurrentlySelected, 0x1002B560);
rebase(ArraySort, 0x10254750);
rebase(groupNpcFollowers, 0x11E71BE0);
rebase(groupCurrentlySelected, 0x11E71D00);
rebase(groupAiFollowers, 0x11E71E20);
rebase(groupPcs , 0x11E71F40);
rebase(groupList, 0x11E721E0);
rebase(partyMoney, 0x1080AB60);
}
} addresses;
LegacyPartySystem party;
class LegacyPartySystemHacks : TempleFix
{
public:
void SetMaxPCs(char maxPCs);
void apply() override
{
SetMaxPCs((char)config.maxPCs);
replaceFunction(0x1002BBE0, AddToPcGroup);
replaceFunction(0x1002BC40, AddToNpcGroup);
// TriggersFearfulResponse
static BOOL(__cdecl *orgFearfulResponse)(objHndl) = replaceFunction<BOOL(__cdecl)(objHndl)>(0x10080720, [](objHndl handle){
if (config.tolerantNpcs)
return FALSE;
return orgFearfulResponse(handle);
});
replaceFunction<objHndl()>(0x1002BE60, [](){
return party.GetConsciousPartyLeader();
});
}
} partyHacks;
void LegacyPartySystemHacks::SetMaxPCs(char maxPCs)
{
char * maxPCsBuffer = &maxPCs;
char maxNPCs = 8 - maxPCs;
char * maxNPCsBuffer = &maxNPCs;
//write(0x1002BBED + 2, maxPCsBuffer , 1); // replaced with AddToPcGroup
write(0x1002BC4D + 2, maxNPCsBuffer, 1);
// write(0x100B0185 + 2, maxNPCsBuffer, 1); // python follower_atmax - deprecated by python reimplementation
}
void LegacyPartySystem::SetMaxPCs(char maxPCs)
{
partyHacks.SetMaxPCs(maxPCs);
}
void LegacyPartySystem::GroupArraySort(GroupArray* groupArray)
{
if (groupArray->sortFunc)
{
addresses.ArraySort(groupArray, groupArray->GroupSize, sizeof(objHndl), groupArray->sortFunc);
}
}
int LegacyPartySystem::GetPartyAlignment()
{
return temple::GetRef<int>(0x1080ABA4);
}
int LegacyPartySystem::GetMoney() const
{
return temple::GetRef<int(__cdecl)()>(0x1002B750)();
}
void LegacyPartySystem::GiveMoneyFromItem(const objHndl& item){
auto itemObj = objSystem->GetObject(item);
if (!itemObj){
return;
}
auto moneyAmt = itemObj->GetInt32(obj_f_money_quantity);
auto moneyType = itemObj->GetInt32(obj_f_money_type);
if (moneyType < 4 && moneyType >= 0){
addresses.partyMoney[moneyType] += moneyAmt;
}
}
void LegacyPartySystem::ApplyConditionAround(const objHndl& obj, double range, const char* condName, const objHndl& obj2){
auto groupLen = GroupListGetLen();
for (auto i = 0u; i < groupLen; i++){
auto partyMem = GroupListGetMemberN(i);
if (!partyMem)
continue;
if (locSys.DistanceToObj(obj, partyMem) > range)
continue;
std::vector<int> args({ (int)obj2.GetHandleLower(), (int)obj2.GetHandleUpper() });
auto cond = conds.GetByName(condName);
for (auto i = 2u; i < cond->numArgs; i++)
args.push_back(0);
conds.AddTo(partyMem, condName, args);
}
}
uint32_t LegacyPartySystem::GetLivingPartyMemberCount()
{
auto N = GroupListGetLen();
auto result = 0u;
for (auto i=0; i < N; i++){
auto partyMem = GroupListGetMemberN(i);
if (!critterSys.IsDeadNullDestroyed(partyMem))
result++;
}
return result;
}
bool LegacyPartySystem::IsInParty(objHndl critter){
if (!critter)
return false;
return party.ObjIsInGroupArray(addresses.groupList, critter);
}
uint32_t LegacyPartySystem::AddToPCGroup(objHndl objHnd)
{
auto npcFollowers = GroupNPCFollowersLen();
auto pcs = GroupPCsLen();
if ( pcs < config.maxPCs
|| config.maxPCsFlexible && (npcFollowers + pcs < PARTY_SIZE_MAX))
{
auto v2 = ObjAddToGroupArray(addresses.groupPcs, objHnd);
if (v2)
{
v2 = ObjAddToGroupArray(addresses.groupList, objHnd);
if (v2)
{
addresses.AddToCurrentlySelected(objHnd);
}
}
return v2;
}
return 0;
}
uint32_t LegacyPartySystem::AddToNpcGroup(objHndl objHnd)
{
auto npcFollowers = GroupNPCFollowersLen();
if (npcFollowers >= 5) return 0;
auto pcs = GroupPCsLen();
if (npcFollowers < PARTY_SIZE_MAX - config.maxPCs
|| config.maxPCsFlexible && (npcFollowers + pcs < PARTY_SIZE_MAX))
{
auto v2 = ObjAddToGroupArray(addresses.groupNpcFollowers, objHnd);
if (v2)
{
v2 = ObjAddToGroupArray(addresses.groupList, objHnd);
if (v2)
{
addresses.AddToCurrentlySelected(objHnd);
}
}
return v2;
}
return 0;
}
void LegacyPartySystem::AddToCurrentlySelected(objHndl obj)
{
if (ObjIsInGroupArray(addresses.groupList, obj))
ObjAddToGroupArray(addresses.groupCurrentlySelected, obj);
}
void LegacyPartySystem::GroupArrayClearMembers(GroupArray* groupArray)
{
groupArray->GroupSize = 0;
memset(groupArray->GroupMembers, 0, sizeof(groupArray->GroupMembers));
}
void LegacyPartySystem::CurrentlySelectedClear()
{
GroupArrayClearMembers(addresses.groupCurrentlySelected);
}
uint32_t LegacyPartySystem::CurrentlySelectedNum()
{
return addresses.groupCurrentlySelected->GroupSize;
}
objHndl LegacyPartySystem::GetCurrentlySelected(int n){
if (n > (int)CurrentlySelectedNum() - 1)
return objHndl::null;
return addresses.groupCurrentlySelected->GroupMembers[n];
}
objHndl LegacyPartySystem::GetLeader()
{
objHndl leader = GroupListGetMemberN(0);
if (objects.IsNPC(leader))
{
leader = GetConsciousPartyLeader();
}
return leader;
}
objHndl LegacyPartySystem::GetConsciousPartyLeader(){
auto selectedCount = CurrentlySelectedNum();
for (auto i=0u; i < selectedCount; i++){
auto dude = GetCurrentlySelected(i);
if (!dude) continue;
if (!critterSys.IsDeadOrUnconscious(dude))
return dude;
}
/* added fix in case the leader is not currently selected and is in combat
This fixes issue with Fear'ed characters fucking up things in TB combat, because while running away they weren't selected.
Symptoms included causing an incorrect radial menu to appear for the fear'd character.
*/
if (combatSys.isCombatActive()){
auto curActor = tbSys.turnBasedGetCurrentActor();
if (IsInParty(curActor) && !critterSys.IsDeadOrUnconscious(curActor))
return curActor;
}
auto partySize = GroupListGetLen();
for (auto i=0u; i < partySize; i++){
auto dude = GroupListGetMemberN(i);
if (!dude)continue;
if (!critterSys.IsDeadOrUnconscious(dude))
return dude;
}
// still none found:
if (partySize)
return GroupListGetMemberN(0);
return objHndl::null;
}
objHndl LegacyPartySystem::PartyMemberWithHighestSkill(SkillEnum skillEnum)
{
auto highestSkillMemberGet = temple::GetRef<objHndl(__cdecl)(SkillEnum)>(0x1002BD50);
return highestSkillMemberGet(skillEnum);
}
int LegacyPartySystem::MoneyAdj(int plat, int gold, int silver, int copper)
{
auto partyMoneyAdj = temple::GetRef<int(__cdecl)(int, int, int, int)>(0x1002B7D0);
return partyMoneyAdj(plat, gold, silver, copper);
}
void LegacyPartySystem::DebitMoney(int plat, int gold, int silver, int copper){
temple::GetRef<void(int, int, int, int)>(0x1002C020)(plat, gold, silver, copper);
}
uint32_t AddToPcGroup(objHndl objHnd)
{
return party.AddToPCGroup(objHnd);
}
uint32_t AddToNpcGroup(objHndl objHnd)
{
return party.AddToNpcGroup(objHnd);
} | 25.956081 | 125 | 0.742288 | edoipi |
36803d7e72611ff0e7be48aa4911641c428805df | 2,924 | cpp | C++ | vendor/mysql-connector-c++-1.1.3/test/CJUnitTestsPort/ccpptests.cpp | caiqingfeng/libmrock | bb7c94482a105e92b6d3e8640b13f9ff3ae49a83 | [
"Apache-2.0"
] | 1 | 2015-12-01T04:16:54.000Z | 2015-12-01T04:16:54.000Z | vendor/mysql-connector-c++-1.1.3/test/CJUnitTestsPort/ccpptests.cpp | caiqingfeng/libmrock | bb7c94482a105e92b6d3e8640b13f9ff3ae49a83 | [
"Apache-2.0"
] | null | null | null | vendor/mysql-connector-c++-1.1.3/test/CJUnitTestsPort/ccpptests.cpp | caiqingfeng/libmrock | bb7c94482a105e92b6d3e8640b13f9ff3ae49a83 | [
"Apache-2.0"
] | null | null | null | /*
Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
The MySQL Connector/C++ is licensed under the terms of the GPLv2
<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
MySQL Connectors. There are special exceptions to the terms and
conditions of the GPLv2 as it is applied to this software, see the
FLOSS License Exception
<http://www.mysql.com/about/legal/licensing/foss-exception.html>.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "../framework/test_runner.h"
#include "../framework/start_options.h"
#include "../framework/test_tapOutputter.h"
#include "../framework/test_filter.h"
#include <stdlib.h>
int main(int argc, char** argv)
{
const String::value_type * unnamedStartParams[]= { "dbUrl"
, "dbUser"
, "dbPasswd"
, "dbSchema"
, NULL };
Properties defaultStringValues;
defaultStringValues.insert( Properties::value_type( "dbUrl" , "tcp://127.0.0.1:3306" ) );
defaultStringValues.insert( Properties::value_type( "dbUser" , "root" ) );
defaultStringValues.insert( Properties::value_type( "dbPasswd", "root" ) );
defaultStringValues.insert( Properties::value_type( "dbSchema", "test" ) );
defaultStringValues.insert( Properties::value_type( "filter" , "" ) );
std::map<String, bool> defaultBoolValues;
testsuite::StartOptions options( unnamedStartParams, & defaultStringValues
, & defaultBoolValues );
options.parseParams( argc, argv );
testsuite::FiltersSuperposition filter( options.getString( "filter" ) );
/*
std::cerr << "BlobTest: "
<< (filter.Admits( "BlobTest" ) ? "Admitted" : "Filtered Out" )
<< std::endl;
return 0;*/
/*std::cerr << options.getString( "dbUrl" ) << std::endl;
std::cerr << options.getString( "dbUser" ) << std::endl;
std::cerr << options.getString( "dbPasswd" ) << std::endl;
std::cerr << options.getString( "dbSchema" ) << std::endl;
std::cerr << options.getBool( "verbose" ) << std::endl;
std::cerr << options.getBool( "timer" ) << std::endl;
std::cerr << options.getBool( "dont-use-is" ) << std::endl;
return 0;*/
testsuite::TestsRunner & testsRunner=testsuite::TestsRunner::theInstance();
testsRunner.setStartOptions ( & options );
testsRunner.setTestsFilter ( filter );
return testsRunner.runTests() ? EXIT_SUCCESS : EXIT_FAILURE;
}
| 34.4 | 93 | 0.711012 | caiqingfeng |
368268d79dc1859c82846996adf835e944d4c04e | 449 | cpp | C++ | C++/CodePit/Contest0812/probD.cpp | MxBromelia/Miscelanea | 5ed09cf0be28fddc29f6f1a6f3f2105226fbc11d | [
"MIT"
] | null | null | null | C++/CodePit/Contest0812/probD.cpp | MxBromelia/Miscelanea | 5ed09cf0be28fddc29f6f1a6f3f2105226fbc11d | [
"MIT"
] | null | null | null | C++/CodePit/Contest0812/probD.cpp | MxBromelia/Miscelanea | 5ed09cf0be28fddc29f6f1a6f3f2105226fbc11d | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int cases;
int num;
int pivot;
vector<int> alt;
ios::sync_with_stdio(false);
cin.tie(NULL);
cin >> cases;
while(cases > 0)
{
cases--;
cin >> num;
while(num>0)
{
cin >> pivot;
alt.emplace_back(pivot);
num--;
}
sort(alt.begin(), alt.end());
for(int k: alt)
{
cout << k << ' ';
}
cout << '\n';
}
return 0;
} | 10.95122 | 31 | 0.556793 | MxBromelia |
36857639e24cf4649e2fb9ca19db3cf37ff3dd80 | 1,218 | hpp | C++ | mathutils/graph/util/set/set_impl.hpp | rxnew/mathutils | 2e8e8c9c99f7cfdbcc4f972f5b68e37dd1fc4f0d | [
"MIT"
] | null | null | null | mathutils/graph/util/set/set_impl.hpp | rxnew/mathutils | 2e8e8c9c99f7cfdbcc4f972f5b68e37dd1fc4f0d | [
"MIT"
] | null | null | null | mathutils/graph/util/set/set_impl.hpp | rxnew/mathutils | 2e8e8c9c99f7cfdbcc4f972f5b68e37dd1fc4f0d | [
"MIT"
] | null | null | null | #pragma once
namespace mathutils {
namespace util {
inline namespace set {
template <class T>
auto set_union(const std::unordered_set<T>& set, const T& value)
-> std::unordered_set<T> {
std::unordered_set<T> result = set;
result.insert(value);
return std::move(result);
}
template <class T>
auto set_union(const std::unordered_set<T>& lhs,
const std::unordered_set<T>& rhs)
-> std::unordered_set<T> {
std::unordered_set<T> result;
for(const auto& x : lhs) {
result.insert(x);
}
for(const auto& x : rhs) {
result.insert(x);
}
return std::move(result);
}
template <class T>
auto set_intersection(const std::unordered_set<T>& lhs,
const std::unordered_set<T>& rhs)
-> std::unordered_set<T> {
std::unordered_set<T> result;
for(const auto& x : lhs) {
if(rhs.find(x) != rhs.cend()) result.insert(x);
}
return std::move(result);
}
template <class T>
auto set_difference(const std::unordered_set<T>& lhs,
const std::unordered_set<T>& rhs)
-> std::unordered_set<T> {
std::unordered_set<T> result;
for(const auto& x : lhs) {
if(rhs.find(x) == rhs.cend()) result.insert(x);
}
return std::move(result);
}
}
}
}
| 23.423077 | 64 | 0.633005 | rxnew |
368675bb9995135c0fdd2797963671c0457ac37e | 298 | cpp | C++ | Hackerearth/linear search/counting-frog-paths.cpp | Yayady1999/Complete-coding-notes | 3236d315248e0d130b8b9c6d591d3c45577282c6 | [
"MIT"
] | 54 | 2020-07-31T14:50:23.000Z | 2022-03-14T11:03:02.000Z | Other/Hackerearth/linear search/counting-frog-paths.cpp | SahilMund/dsa | a94151b953b399ea56ff50cf30dfe96100e8b9a7 | [
"MIT"
] | null | null | null | Other/Hackerearth/linear search/counting-frog-paths.cpp | SahilMund/dsa | a94151b953b399ea56ff50cf30dfe96100e8b9a7 | [
"MIT"
] | 30 | 2020-08-15T17:39:02.000Z | 2022-03-10T06:50:18.000Z | #include <bits/stdc++.h>
#include <iostream>
using namespace std;
int main() {
int x,y,s,t,points=0;
cin >> x >> y >> s >> t;
for(int i=0, j=t; i<=t; i++, j--) {
if(j>=y && j<=y+s) {
points += min(max(0,i-x+1), s+1);
}
}
cout << points << endl;
}
| 17.529412 | 45 | 0.432886 | Yayady1999 |
3688272881c5584687aed0f95905d11f27a4d653 | 1,322 | cpp | C++ | checker.cpp | clean-code-craft-tcq-2/simple-monitor-in-cpp-cheral-bhati | 95a23c52aa0c232825d1e6fc994aebc9efbe85c0 | [
"MIT"
] | null | null | null | checker.cpp | clean-code-craft-tcq-2/simple-monitor-in-cpp-cheral-bhati | 95a23c52aa0c232825d1e6fc994aebc9efbe85c0 | [
"MIT"
] | null | null | null | checker.cpp | clean-code-craft-tcq-2/simple-monitor-in-cpp-cheral-bhati | 95a23c52aa0c232825d1e6fc994aebc9efbe85c0 | [
"MIT"
] | null | null | null | #include <assert.h>
#include <iostream>
using namespace std;
const float MAX_TEMPERATURE = 45.0;
const float MIN_TEMPERATURE = 0.0;
const float MAX_SOC = 80.0;
const float MIN_SOC = 20.0;
const float MAX_CHARGERATE = 0.8;
const float MIN_CHARGERATE = 0.0;
bool checkValueinRange(const float maxValue, const float minValue, const float ValuetoCheck)
{
if (ValuetoCheck < minValue || ValuetoCheck > maxValue )
{
return 0 ;
}
return 1;
}
bool batteryIsOk(float temperature, float soc, float chargeRate) {
bool checkTemperature = false;
bool checkSOC = false;
bool checkChargeRate = false;
checkTemperature = checkValueinRange(MAX_TEMPERATURE, MIN_TEMPERATURE, temperature);
checkSOC = checkValueinRange(MAX_SOC, MIN_SOC, soc);
checkChargeRate = checkValueinRange(MAX_CHARGERATE, MIN_CHARGERATE, chargeRate);
return checkTemperature && checkSOC && checkChargeRate;
}
int main() {
assert(batteryIsOk(25, 70, 0.7) == true);
assert(batteryIsOk(50, 60, 0.2) == false);
assert(batteryIsOk(42.5, 85, 0.2) == false);
assert(batteryIsOk(42.5, 18, 0.2) == false);
assert(batteryIsOk(-20, 50, 0.2) == false);
assert(batteryIsOk(20, 40, -1) == false);
assert(batteryIsOk(20, 40, 0.9) == false);
assert(batteryIsOk(45, 80, 0.8) == true);
assert(batteryIsOk(0, 20, 0) == true);
}
| 30.045455 | 93 | 0.706505 | clean-code-craft-tcq-2 |
3688cc4b2fc04a23bf2114ac88e9c5fb28291171 | 1,296 | cpp | C++ | amr-wind/derive/field_algebra.cpp | mchurchf/amr-wind | 4bd712966e830a7c9412b0a4ec4cd8d1e6e0582f | [
"BSD-3-Clause"
] | 40 | 2019-11-27T15:38:45.000Z | 2022-03-07T10:56:35.000Z | amr-wind/derive/field_algebra.cpp | mchurchf/amr-wind | 4bd712966e830a7c9412b0a4ec4cd8d1e6e0582f | [
"BSD-3-Clause"
] | 207 | 2019-11-07T22:53:02.000Z | 2022-03-30T21:41:57.000Z | amr-wind/derive/field_algebra.cpp | mchurchf/amr-wind | 4bd712966e830a7c9412b0a4ec4cd8d1e6e0582f | [
"BSD-3-Clause"
] | 55 | 2019-11-08T19:25:08.000Z | 2022-03-15T20:36:25.000Z | #include "amr-wind/core/FieldRepo.H"
namespace amr_wind {
template <typename FType>
void normalize_field(FType& Field)
{
const auto& repo = Field.repo();
const auto ncomp = Field.num_comp();
const int nlevels = repo.num_active_levels();
for (int lev = 0; lev < nlevels; ++lev) {
for (amrex::MFIter mfi(Field(lev)); mfi.isValid(); ++mfi) {
const auto& bx = mfi.tilebox();
const auto& field_arr = Field(lev).array(mfi);
amrex::ParallelFor(
bx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept {
amrex::Real mag = 0;
// Compute magnitude
for (int icomp = 0; icomp < ncomp; ++icomp) {
mag = mag + field_arr(i, j, k, icomp) *
field_arr(i, j, k, icomp);
}
// Normalize field
for (int icomp = 0; icomp < ncomp; ++icomp) {
field_arr(i, j, k, icomp) =
field_arr(i, j, k, icomp) / std::sqrt(mag);
}
});
}
}
}
template void normalize_field<Field>(Field&);
template void normalize_field<ScratchField>(ScratchField&);
} // namespace amr_wind
| 34.105263 | 72 | 0.490741 | mchurchf |
3689659933c4e1d734fddeedf7aa55803ead976c | 596 | cc | C++ | src/game_process.cc | neguse/hakonotaiatari | 9a9d402133abb112e31e2fd12da5b22619ee08ff | [
"Unlicense"
] | null | null | null | src/game_process.cc | neguse/hakonotaiatari | 9a9d402133abb112e31e2fd12da5b22619ee08ff | [
"Unlicense"
] | null | null | null | src/game_process.cc | neguse/hakonotaiatari | 9a9d402133abb112e31e2fd12da5b22619ee08ff | [
"Unlicense"
] | null | null | null |
#include "precompile.h"
#include "game_process.h"
#include "state.h"
void GameProcess::onInit()
{
}
void GameProcess::onUpdate(f32 dt)
{
if (m_pState) {
m_pState->onUpdate(dt);
IState* pNext = m_pState->nextState();
if (pNext) {
trans(pNext);
}
}
}
void GameProcess::onRender()
{
if (m_pState) {
m_pState->onRender();
}
}
void GameProcess::trans(IState* pState)
{
if (m_pState) m_pState->onExit();
if (pState != NULL) {
m_pState = pState;
} else {
m_pState = NULL;
}
if (m_pState != NULL) {
m_pState->onInit();
}
}
| 13.545455 | 41 | 0.583893 | neguse |
368a7b3068e8b537638bb737ae1434fe31eecbe1 | 4,682 | cpp | C++ | TommyGun/Plugins/ImageEditor/MonochromePalette/MonochromePalettePlugin.cpp | tonyt73/TommyGun | 2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36 | [
"BSD-3-Clause"
] | 34 | 2017-05-08T18:39:13.000Z | 2022-02-13T05:05:33.000Z | TommyGun/Plugins/ImageEditor/MonochromePalette/MonochromePalettePlugin.cpp | tonyt73/TommyGun | 2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36 | [
"BSD-3-Clause"
] | null | null | null | TommyGun/Plugins/ImageEditor/MonochromePalette/MonochromePalettePlugin.cpp | tonyt73/TommyGun | 2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36 | [
"BSD-3-Clause"
] | 6 | 2017-05-27T01:14:20.000Z | 2020-01-20T14:54:30.000Z | /*---------------------------------------------------------------------------
(c) 2004 Scorpio Software
19 Wittama Drive
Glenmore Park
Sydney NSW 2745
Australia
-----------------------------------------------------------------------------
$Workfile:: $
$Revision:: $
$Date:: $
$Author:: $
---------------------------------------------------------------------------*/
//---------------------------------------------------------------------------
#include "pch.h"
#pragma hdrstop
//---------------------------------------------------------------------------
using namespace Scorpio;
using namespace Interface;
using namespace Plugin;
//---------------------------------------------------------------------------
using namespace Scorpio;
using namespace MonochromePalette;
//---------------------------------------------------------------------------
// NewPluginClass
/**
* Called from ImageEditor.cpp to create a new Plugin object. The ImageEditor.cpp only uses the
* Base class reference. So this function returns a Plugin object to use of type class ZXBasePlugin.
* @return ZXBasePlugin a ZXBasePlugin compatible object
* @author KiwiWare Plugin Wizard
* @date Created 17 December 2001 by Tony Thompson
* @remarks Copyright Scorpio Software 2001
*/
//---------------------------------------------------------------------------
MonochromePalettePlugin* NewPluginClass(void)
{
RL_METHOD
// create the new plugin class object
return new MonochromePalettePlugin();
}
//---------------------------------------------------------------------------
// Constructor
/**
* Allocates resource for use by the Plugin class
* @author KiwiWare Plugin Wizard
* @date Created 17 December 2001 by Tony Thompson
* @remarks Copyright Scorpio Software 2001
*/
//---------------------------------------------------------------------------
__fastcall MonochromePalettePlugin::MonochromePalettePlugin()
{
RL_METHOD
}
//---------------------------------------------------------------------------
// Destructor
/**
* Frees the resources of the Plugin class
* @author KiwiWare Plugin Wizard
* @date Created 17 December 2001 by Tony Thompson
* @remarks Copyright Scorpio Software 2001
*/
//---------------------------------------------------------------------------
__fastcall MonochromePalettePlugin::~MonochromePalettePlugin()
{
RL_METHOD
// release our resources before dying
Release();
}
//---------------------------------------------------------------------------
// InitialisePlugin
/**
* Initialises the plugin for use
* @param PluginHandle the handle allocated to the plugin
* @return HRESULT S_OK success, S_FALSE failure
* @author KiwiWare Plugin Wizard
* @date Created 17 December 2001 by Tony Thompson
* @remarks Copyright Scorpio Software 2001
*/
//---------------------------------------------------------------------------
HRESULT __fastcall MonochromePalettePlugin::InitialisePlugin(ZXPlugin* pPlugin)
{
RL_METHOD
HRESULT hResult = S_OK;
return hResult;
}
//---------------------------------------------------------------------------
// ReleasePlugin
/**
* Releases the resources associated with the Plugin
* @return HRESULT S_OK success, S_FALSE failure
* @author KiwiWare Plugin Wizard
* @date Created 17 December 2001 by Tony Thompson
* @remarks Copyright Scorpio Software 2001
*/
//---------------------------------------------------------------------------
HRESULT __fastcall MonochromePalettePlugin::ReleasePlugin(void)
{
RL_METHOD
RL_HRESULT(S_OK)
return hResult;
}
//---------------------------------------------------------------------------
void __fastcall MonochromePalettePlugin::RegisterEvents(void)
{
// TODO: Register for the parent plugin events we need
//RegisterEvent(TZX_QUERY_DATASAVED , EventSaveQuery );
}
//---------------------------------------------------------------------------
HRESULT __fastcall MonochromePalettePlugin::GetPalette(ZXPalette*& Palette)
{
RL_METHOD
RL_HRESULT(S_OK);
Palette = &m_Palette;
return hResult;
}
//---------------------------------------------------------------------------
HRESULT __fastcall MonochromePalettePlugin::GetPalettePanel(TPanel*& Panel)
{
RL_METHOD
RL_HRESULT(S_OK);
Panel = NULL;
return hResult;
}
//---------------------------------------------------------------------------
| 36.294574 | 100 | 0.452371 | tonyt73 |
368e88dc7e3baece30fa70d8da1ec1a07e5320d3 | 3,344 | cpp | C++ | samples/sample/MainScene.cpp | zapolnov/game_engine | cd22dc0f49aeadd660eec3ea9b95b1ca2696f97a | [
"MIT",
"Unlicense"
] | null | null | null | samples/sample/MainScene.cpp | zapolnov/game_engine | cd22dc0f49aeadd660eec3ea9b95b1ca2696f97a | [
"MIT",
"Unlicense"
] | null | null | null | samples/sample/MainScene.cpp | zapolnov/game_engine | cd22dc0f49aeadd660eec3ea9b95b1ca2696f97a | [
"MIT",
"Unlicense"
] | null | null | null | /*
* Copyright (c) 2015 Nikolay Zapolnov (zapolnov@gmail.com).
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "MainScene.h"
#include "engine/core/Services.h"
#include "engine/core/Log.h"
#include <glm/gtc/matrix_transform.hpp>
using namespace B3D;
namespace Game
{
MainScene::MainScene()
{
mCamera = std::make_shared<OrbitCamera>();
mCamera->setHorizontalAngle(glm::radians(0.0f));
mCamera->setVerticalAngle(glm::radians(0.0f));
mCamera->setDepthRange(0.1f, 10.0f);
addComponent(mCamera);
mMesh = Services::resourceManager()->getStaticMesh("girl/girl.obj");
}
MainScene::~MainScene()
{
}
void MainScene::update(double)
{
mCamera->setDistance(0.7f * glm::length(mMesh->boundingBox().size()));
mCamera->setTarget(mMesh->boundingBox().center());
}
void MainScene::draw(ICanvas* canvas) const
{
glm::mat4 matrix = canvas->modelViewMatrix() * glm::translate(glm::mat4(1.0f), mCamera->target());
matrix = matrix * glm::rotate(glm::mat4(1.0f), glm::radians(-90.0f), glm::vec3(0.0f, 1.0f, 0.0f));
matrix = matrix * glm::rotate(glm::mat4(1.0f), glm::radians(-90.0f), glm::vec3(1.0f, 0.0f, 0.0f));
matrix = matrix * glm::translate(glm::mat4(1.0f), -mCamera->target());
canvas->setModelViewMatrix(matrix);
canvas->setDepthTest(true);
mMesh->render(canvas);
canvas->drawWireframeBoundingBox(mMesh->boundingBox());
}
bool MainScene::onTouchBegan(int fingerIndex, const glm::vec2& position)
{
if (fingerIndex != 0)
return false;
mPrevTouchPosition = position;
return true;
}
void MainScene::onTouchMoved(int fingerIndex, const glm::vec2& position)
{
if (fingerIndex != 0)
return;
glm::vec2 delta = position - mPrevTouchPosition;
mPrevTouchPosition = position;
mCamera->setHorizontalAngle(mCamera->horizontalAngle() + delta.x * 4.0f);
mCamera->setVerticalAngle(glm::clamp(mCamera->verticalAngle() - delta.y * 4.0f,
-glm::radians(89.0f), glm::radians(89.0f)));
}
void MainScene::onTouchEnded(int, const glm::vec2&)
{
}
void MainScene::onTouchCancelled(int, const glm::vec2&)
{
}
}
| 35.574468 | 106 | 0.666567 | zapolnov |
3691e36b8e33dfe46947810d9704b5e53f00f8bc | 4,680 | hpp | C++ | include/opcodes.hpp | mujido/moove | 380fd0ea2eb2ad59b62a27bb86079ecb8c5b783b | [
"Apache-2.0"
] | null | null | null | include/opcodes.hpp | mujido/moove | 380fd0ea2eb2ad59b62a27bb86079ecb8c5b783b | [
"Apache-2.0"
] | null | null | null | include/opcodes.hpp | mujido/moove | 380fd0ea2eb2ad59b62a27bb86079ecb8c5b783b | [
"Apache-2.0"
] | null | null | null | //Copyright (c) 2004 Kurt Stutsman. All rights reserved.
/**
* \file
* \brief Define the opcodes used for byte compilation and interpretation
*/
#ifndef MOOVE_OPCODES_HPP
#define MOOVE_OPCODES_HPP
#include "codevect.hpp"
#include "immediate.hpp"
namespace Moove {
/**
* Opcodes handled internally by the VM.
*
* \warning
* Do not forget to change the OpcodeInfo data when modifying the opcode enumerations or adding/removing immediate values.
*/
enum Opcode {
// ---------- Opcodes handled by the interpreter ----------
OP_DONE,
OP_JUMP,
OP_JUMP_FALSE,
OP_FORK,
OP_RETURN,
OP_PUSH_LITERAL,
OP_PUSH,
OP_PUT,
OP_POP,
OP_CALL_BUILTIN,
OP_GET_PROP,
OP_PUT_PROP,
OP_CALL_VERB,
OP_GET_SYSPROP,
OP_PUT_SYSPROP,
OP_CALL_SYSVERB,
OP_APPEND_LIST, ///< Append an element to a list
// ---------- Opcodes that must be overloaded for each type with OperatorPackage and OperatorMap ----------
// ===== Unary Operators =====
OP_NOT, ///< Logical NOT
OP_NEGATE, ///< Negate
// ===== Binary Operators =====
OP_OR, ///< Logical OR
OP_AND, ///< Logical AND
OP_EQ, ///< Equality comparison
OP_NE, ///< Inequality comparison
OP_LT, ///< Less-than comparison
OP_LE, ///< Less-than or equality comparison
OP_GE, ///< Greater-than or equality comparison
OP_GT, ///< Greater-than comparison
OP_IN, ///< Element-in-set test
OP_ADD, ///< Addition
OP_SUB, ///< Subtraction
OP_MUL, ///< Multiplication
OP_DIV, ///< Division
OP_MOD, ///< Modulus
OP_EXP, ///< Exponetial
// ===== Special Operators =====
OP_INDEX, ///< List index
OP_INDEX_SET, ///< Assign an element in a list
OP_RANGE, ///< Subrange a list
OP_RANGE_SET, ///< Modify a list subrange
OP_LENGTH, ///< Calculate length of a list without popping from stack
OP_SPLICE, ///< List splicing
NUM_OPCODES ///< Number of opcodes
};
class OpcodeInfo {
public:
enum FunctionalGroup {
FG_NONE = 0,
FG_ARITHMETIC = 1 << 0,
FG_COMPARISON = 1 << 1,
FG_LOGIC = 1 << 2
};
static const unsigned ALL_FUNCTIONAL_GROUPS = FG_ARITHMETIC | FG_COMPARISON | FG_LOGIC;
class Op {
private:
Opcode m_opcode;
const char* m_name;
int m_immType;
public:
Op(Opcode opcode, const char* name, int immType) : m_opcode(opcode), m_name(name), m_immType(immType)
{}
Opcode opcode()const
{ return m_opcode; }
const char* name()const
{ return m_name; }
bool hasImmediate()const
{ return m_immType != -1; }
ImmediateValue::Type immediateType()const;
bool isUnaryOp()const
{ return m_opcode == OP_NOT || m_opcode == OP_NEGATE; }
bool isBinaryOp()const
{ return m_opcode >= OP_OR && m_opcode <= OP_EXP; }
FunctionalGroup functionalGroup()const;
};
private:
static const Op s_ops[NUM_OPCODES];
public:
static bool validOp(CodeVector::Byte op)
{ return op < NUM_OPCODES; }
static const Op& getOp(Opcode op)
{ return s_ops[op]; }
};
} //namespace Moove
#endif //MOOVE_OPCODES_HPP
| 35.725191 | 122 | 0.426282 | mujido |
3692350946e751fc8e673e64d2cce889b2b423c0 | 35,893 | cpp | C++ | ajalibraries/ajantv2/src/ntv2card.cpp | DDRBoxman/ntv2 | fe2462254864fb0d6b2838e506fd905cddebfc4f | [
"MIT"
] | 9 | 2021-09-28T22:17:59.000Z | 2022-03-31T03:31:57.000Z | ajalibraries/ajantv2/src/ntv2card.cpp | DDRBoxman/ntv2 | fe2462254864fb0d6b2838e506fd905cddebfc4f | [
"MIT"
] | 5 | 2021-10-31T17:24:05.000Z | 2022-03-17T22:41:19.000Z | ajalibraries/ajantv2/src/ntv2card.cpp | DDRBoxman/ntv2 | fe2462254864fb0d6b2838e506fd905cddebfc4f | [
"MIT"
] | 8 | 2021-10-31T16:54:29.000Z | 2022-03-21T19:58:46.000Z | /* SPDX-License-Identifier: MIT */
/**
@file ntv2card.cpp
@brief Implements several CNTV2Card methods. Other implementation files are 'ntv2audio.cpp', 'ntv2dma.cpp', 'ntv2register.cpp', ...
@copyright (C) 2004-2021 AJA Video Systems, Inc.
**/
#include "ntv2devicefeatures.h"
#include "ntv2card.h"
#include "ntv2debug.h"
#include "ntv2utils.h"
#include <sstream>
#include "ajabase/common/common.h"
using namespace std;
// Default Constructor
CNTV2Card::CNTV2Card ()
{
_boardOpened = false;
#if defined (NTV2_DEPRECATE)
//InitNTV2ColorCorrection ();
#endif // defined (NTV2_DEPRECATE)
}
CNTV2Card::CNTV2Card (const UWord inDeviceIndex, const string & inHostName)
{
string hostName(inHostName);
aja::strip(hostName);
_boardOpened = false;
bool openOK = hostName.empty() ? CNTV2DriverInterface::Open(inDeviceIndex) : CNTV2DriverInterface::Open(hostName);
if (openOK)
{
if (IsBufferSizeSetBySW())
{
NTV2Framesize fbSize;
GetFrameBufferSize (NTV2_CHANNEL1, fbSize);
SetFrameBufferSize (fbSize);
}
else
{
NTV2FrameGeometry fg;
NTV2FrameBufferFormat format;
GetFrameGeometry (fg);
GetFrameBufferFormat (NTV2_CHANNEL1, format);
_ulFrameBufferSize = ::NTV2DeviceGetFrameBufferSize (GetDeviceID (), fg, format);
_ulNumFrameBuffers = ::NTV2DeviceGetNumberFrameBuffers (GetDeviceID (), fg, format);
}
}
}
#if !defined(NTV2_DEPRECATE_14_3)
CNTV2Card::CNTV2Card (const UWord boardNumber, const bool displayErrorMessage, const UWord ulBoardType, const char *hostname)
{
(void) displayErrorMessage;
(void) ulBoardType;
string hostName(hostname ? hostname : "");
aja::strip(hostName);
_boardOpened = false;
bool openOK = hostName.empty() ? CNTV2DriverInterface::Open(boardNumber) : CNTV2DriverInterface::Open(hostName);
if (openOK)
{
if (IsBufferSizeSetBySW())
{
NTV2Framesize fbSize;
GetFrameBufferSize (NTV2_CHANNEL1, fbSize);
SetFrameBufferSize (fbSize);
}
else
{
NTV2FrameGeometry fg;
NTV2FrameBufferFormat format;
GetFrameGeometry (fg);
GetFrameBufferFormat (NTV2_CHANNEL1, format);
_ulFrameBufferSize = ::NTV2DeviceGetFrameBufferSize (GetDeviceID (), fg, format);
_ulNumFrameBuffers = ::NTV2DeviceGetNumberFrameBuffers (GetDeviceID (), fg, format);
}
}
} // constructor
#endif // !defined(NTV2_DEPRECATE_14_3)
// Destructor
CNTV2Card::~CNTV2Card ()
{
if (IsOpen ())
Close ();
} // destructor
Word CNTV2Card::GetDeviceVersion (void)
{
ULWord status (0);
return ReadRegister (kRegStatus, status) ? (status & 0xF) : -1;
}
string CNTV2Card::GetDeviceVersionString (void)
{
ostringstream oss;
oss << ::NTV2DeviceIDToString(GetDeviceID());
return oss.str();
}
string CNTV2Card::GetModelName (void)
{
ostringstream oss;
oss << ::NTV2DeviceIDToString(GetDeviceID(), GetDeviceID() == DEVICE_ID_IO4KPLUS ? DeviceHasMicInput() : false);
return oss.str();
}
string CNTV2Card::GetDisplayName (void)
{
ostringstream oss;
oss << GetModelName() << " - " << GetIndexNumber();
return oss.str();
}
string CNTV2Card::GetFPGAVersionString (const NTV2XilinxFPGA inFPGA)
{
ULWord numBytes (0);
string dateStr, timeStr;
ostringstream oss;
if (inFPGA == eFPGAVideoProc && GetInstalledBitfileInfo (numBytes, dateStr, timeStr))
oss << dateStr << " at " << timeStr;
else
oss << "Unavailable";
return oss.str ();
}
Word CNTV2Card::GetPCIFPGAVersion (void)
{
ULWord status (0);
return ReadRegister (48, status) ? ((status >> 8) & 0xFF) : -1;
}
string CNTV2Card::GetPCIFPGAVersionString (void)
{
const UWord version (static_cast<UWord>(GetPCIFPGAVersion()));
ostringstream oss;
oss << hex << version;
return oss.str ();
}
string CNTV2Card::GetDriverVersionString (void)
{
static const string sDriverBuildTypes [] = {"", "b", "a", "d"};
UWord versions[4] = {0, 0, 0, 0};
ULWord versBits(0);
if (!GetDriverVersionComponents (versions[0], versions[1], versions[2], versions[3]))
return string(); // fail
if (!ReadRegister (kVRegDriverVersion, versBits))
return string(); // fail
const string & dabr (versBits ? sDriverBuildTypes[versBits >> 30] : ""); // Bits 31:30 == build type
if (!GetDriverVersionComponents (versions[0], versions[1], versions[2], versions[3]))
return string(); // fail
ostringstream oss;
oss << DEC(versions[0]) << "." << DEC(versions[1]) << "." << DEC(versions[2]);
if (dabr.empty())
oss << "." << DEC(versions[3]);
else
oss << dabr << DEC(versions[3]);
return oss.str ();
} // GetDriverVersionString
bool CNTV2Card::GetDriverVersionComponents (UWord & outMajor, UWord & outMinor, UWord & outPoint, UWord & outBuild)
{
outMajor = outMinor = outPoint = outBuild = 0;
ULWord driverVersionULWord (0);
if (!ReadRegister (kVRegDriverVersion, driverVersionULWord))
return false;
if (!driverVersionULWord) // If zero --- pre-15.0 driver?
return false;
// The normal 15.0+ way of decoding the 32-bit driver version value:
outMajor = UWord(NTV2DriverVersionDecode_Major(driverVersionULWord));
outMinor = UWord(NTV2DriverVersionDecode_Minor(driverVersionULWord));
outPoint = UWord(NTV2DriverVersionDecode_Point(driverVersionULWord));
outBuild = UWord(NTV2DriverVersionDecode_Build(driverVersionULWord));
return true;
}
ULWord CNTV2Card::GetSerialNumberLow (void)
{
ULWord serialNum (0);
return ReadRegister (54, serialNum) ? serialNum : 0; // Read EEPROM shadow of Serial Number
}
ULWord CNTV2Card::GetSerialNumberHigh (void)
{
ULWord serialNum (0);
return ReadRegister (55, serialNum) ? serialNum : 0; // Read EEPROM shadow of Serial Number
}
bool CNTV2Card::IS_CHANNEL_INVALID (const NTV2Channel inChannel) const
{
if (!NTV2_IS_VALID_CHANNEL (inChannel))
return true;
return false;
}
bool CNTV2Card::IS_OUTPUT_SPIGOT_INVALID (const UWord inOutputSpigot) const
{
if (inOutputSpigot >= ::NTV2DeviceGetNumVideoOutputs(_boardID))
{
if (NTV2DeviceCanDoWidget(_boardID, NTV2_WgtSDIMonOut1) && inOutputSpigot == 4)
return false; // Io4K Monitor Output exception
return true; // Invalid
}
return false;
}
bool CNTV2Card::IS_INPUT_SPIGOT_INVALID (const UWord inInputSpigot) const
{
if (inInputSpigot >= ::NTV2DeviceGetNumVideoInputs (_boardID))
return true;
return false;
}
uint64_t CNTV2Card::GetSerialNumber (void)
{
const uint64_t lo (GetSerialNumberLow ()), hi (GetSerialNumberHigh ());
uint64_t result ((hi << 32) | lo);
return result;
}
string CNTV2Card::SerialNum64ToString (const uint64_t inSerialNumber) // Class method
{
const ULWord serialNumHigh (inSerialNumber >> 32);
const ULWord serialNumLow (inSerialNumber & 0x00000000FFFFFFFF);
char serialNum [9];
serialNum[0] = char((serialNumLow & 0x000000FF) );
serialNum[1] = char((serialNumLow & 0x0000FF00) >> 8);
serialNum[2] = char((serialNumLow & 0x00FF0000) >> 16);
serialNum[3] = char((serialNumLow & 0xFF000000) >> 24);
serialNum[4] = char((serialNumHigh & 0x000000FF) );
serialNum[5] = char((serialNumHigh & 0x0000FF00) >> 8);
serialNum[6] = char((serialNumHigh & 0x00FF0000) >> 16);
serialNum[7] = char((serialNumHigh & 0xFF000000) >> 24);
serialNum[8] = '\0';
for (unsigned ndx(0); ndx < 8; ndx++)
{
if (serialNum[ndx] == 0)
{
if (ndx == 0)
return ""; // No characters: no serial number
break; // End of string -- stop scanning
}
// Allow only 0-9, A-Z, a-z, blank, and dash only.
if ( ! ( ( (serialNum[ndx] >= '0') && (serialNum[ndx] <= '9') ) ||
( (serialNum[ndx] >= 'A') && (serialNum[ndx] <= 'Z') ) ||
( (serialNum[ndx] >= 'a') && (serialNum[ndx] <= 'z') ) ||
(serialNum[ndx] == ' ') || (serialNum[ndx] == '-') ) )
return ""; // Invalid character -- assume no Serial Number programmed...
}
return serialNum;
} // SerialNum64ToString
bool CNTV2Card::GetSerialNumberString (string & outSerialNumberString)
{
outSerialNumberString = SerialNum64ToString(GetSerialNumber());
if (outSerialNumberString.empty())
{
outSerialNumberString = "INVALID?";
return false;
}
const NTV2DeviceID deviceID(GetDeviceID());
if (deviceID == DEVICE_ID_IO4KPLUS) // Io4K+/DNxIV?
outSerialNumberString = "5" + outSerialNumberString; // prepend with "5"
else if ((deviceID == DEVICE_ID_IOIP_2022) ||
(deviceID == DEVICE_ID_IOIP_2110) ||
(deviceID == DEVICE_ID_IOIP_2110_RGB12)) // IoIP/DNxIP?
outSerialNumberString = "6" + outSerialNumberString; // prepend with "6"
return true;
} // GetSerialNumberString
bool CNTV2Card::GetInstalledBitfileInfo (ULWord & outNumBytes, std::string & outDateStr, std::string & outTimeStr)
{
outDateStr.clear ();
outTimeStr.clear ();
outNumBytes = 0;
if (!_boardOpened)
return false; // Bail if I'm not open
BITFILE_INFO_STRUCT bitFileInfo;
::memset (&bitFileInfo, 0, sizeof (bitFileInfo));
bitFileInfo.whichFPGA = eFPGAVideoProc;
// Call the OS specific method...
if (!DriverGetBitFileInformation (bitFileInfo, NTV2_VideoProcBitFile))
return false;
// Fill in our OS independent data structure...
outDateStr = reinterpret_cast <char *> (&bitFileInfo.dateStr [0]);
outTimeStr = reinterpret_cast <char *> (&bitFileInfo.timeStr [0]);
outNumBytes = bitFileInfo.numBytes;
return true;
}
string CNTV2Card::GetBitfileInfoString (const BITFILE_INFO_STRUCT & inBitFileInfo)
{
ostringstream oss;
// format like: "date time name"
oss << inBitFileInfo.dateStr << " " << inBitFileInfo.timeStr << " ";
switch (inBitFileInfo.bitFileType)
{
#if !defined (NTV2_DEPRECATE)
case NTV2_BITFILE_XENA2_UPCVT: // DEPRECATION_CANDIDATE
case NTV2_BITFILE_MOAB_UPCVT: // DEPRECATION_CANDIDATE
oss << "UpConvert"; break;
case NTV2_BITFILE_XENA2_DNCVT: // DEPRECATION_CANDIDATE
case NTV2_BITFILE_MOAB_DNCVT: // DEPRECATION_CANDIDATE
oss << "DownConvert"; break;
case NTV2_BITFILE_XENA2_XUCVT: // DEPRECATION_CANDIDATE
case NTV2_BITFILE_MOAB_XUCVT: // DEPRECATION_CANDIDATE
oss << "Cross Convert 720->1080"; break;
case NTV2_BITFILE_XENA2_XDCVT: // DEPRECATION_CANDIDATE
case NTV2_BITFILE_MOAB_XDCVT: // DEPRECATION_CANDIDATE
oss << "Cross Convert 1080->720"; break;
case NTV2_BITFILE_XENA2_CSCVT:
oss << "AutoDesk Main"; break;
#endif // !defined (NTV2_DEPRECATE)
case NTV2_BITFILE_LHI_MAIN: oss << "LHi Main"; break;
case NTV2_BITFILE_LHI_T_MAIN: oss << "LHi T Main"; break;
case NTV2_BITFILE_IOEXPRESS_MAIN: oss << "IoExpress Main"; break;
case NTV2_BITFILE_CORVID1_MAIN: oss << "Corvid1 Main"; break;
case NTV2_BITFILE_CORVID22_MAIN: oss << "Corvid22 Main"; break;
case NTV2_BITFILE_CORVID24_MAIN: oss << "Corvid24 Main"; break;
case NTV2_BITFILE_CORVID3G_MAIN: oss << "Corvid3G Main"; break;
case NTV2_BITFILE_CORVID88: oss << "Corvid88 Main"; break;
case NTV2_BITFILE_CORVID44: oss << "Corvid44 Main"; break;
case NTV2_BITFILE_KONA3G_MAIN: oss << "Kona 3G Main"; break;
case NTV2_BITFILE_KONA3G_QUAD: oss << "Kona 3G Quad"; break;
case NTV2_BITFILE_KONALHE_PLUS: oss << "Kona LHe+"; break;
case NTV2_BITFILE_IOXT_MAIN: oss << "IoXT Main"; break;
case NTV2_BITFILE_TTAP_MAIN: oss << "T-Tap Main"; break;
case NTV2_BITFILE_IO4K_MAIN: oss << "Io4K Main"; break;
case NTV2_BITFILE_IO4KUFC_MAIN: oss << "Io4K UFC"; break;
case NTV2_BITFILE_KONA4_MAIN: oss << "Kona4 Main"; break;
case NTV2_BITFILE_KONA4UFC_MAIN: oss << "Kona4 UFC"; break;
case NTV2_BITFILE_KONAIP_2022: oss << "KonaIP 2022"; break;
case NTV2_BITFILE_KONAIP_4CH_2SFP: oss << "KonaIP 4CH 2SFP"; break;
case NTV2_BITFILE_IO4KPLUS_MAIN: oss << (DeviceIsDNxIV() ? "DNxIV" : "Io4K Plus"); break;
case NTV2_BITFILE_IOIP_2022: oss << "IoIP 2022"; break;
case NTV2_BITFILE_IOIP_2110: oss << "IoIP 2110"; break;
case NTV2_BITFILE_KONAIP_2110: oss << "KonaIP 2110"; break;
case NTV2_BITFILE_KONA1: oss << "Kona1"; break;
case NTV2_BITFILE_KONAHDMI: oss << "Kona HDMI"; break;
case NTV2_BITFILE_KONA5_MAIN: oss << "Kona5"; break;
case NTV2_BITFILE_KONA5_8K_MAIN: oss << "Kona5 8K"; break;
case NTV2_BITFILE_KONA5_8KMK_MAIN: oss << "Kona5 8KMK"; break;
case NTV2_BITFILE_KONA5_OE1_MAIN: oss << "Kona5 OE1"; break;
case NTV2_BITFILE_CORVID44_8K_MAIN: oss << "Corvid44 8K"; break;
case NTV2_BITFILE_CORVID44_8KMK_MAIN: oss << "Corvid44 8KMK"; break;
case NTV2_BITFILE_TTAP_PRO_MAIN: oss << "T-Tap Pro Main"; break;
case NTV2_BITFILE_IOX3_MAIN: oss << "IoX3 Main"; break;
default: oss << "(bad bitfile type!!!)"; break;
}
return oss.str();
}
bool CNTV2Card::IsFailSafeBitfileLoaded (bool & outIsSafeBoot)
{
outIsSafeBoot = false;
if (!::NTV2DeviceCanReportFailSafeLoaded(_boardID))
return false;
return CNTV2DriverInterface::ReadRegister(kRegCPLDVersion, outIsSafeBoot, BIT(4), 4);
}
bool CNTV2Card::CanWarmBootFPGA (bool & outCanWarmBoot)
{
outCanWarmBoot = false; // Definitely can't
if (!::NTV2DeviceCanDoWarmBootFPGA(_boardID))
return false;
ULWord version(0);
if (!ReadRegister(kRegCPLDVersion, version, BIT(0)|BIT(1)))
return false; // Fail
if (version != 3)
outCanWarmBoot = true; // Definitely can
return true;
}
NTV2BreakoutType CNTV2Card::GetBreakoutHardware (void)
{
NTV2BreakoutType result (NTV2_BreakoutNone);
ULWord audioCtlReg (0); // The Audio Control Register tells us what's connected
if (IsOpen () && ReadRegister (kRegAud1Control, audioCtlReg))
{
const bool bPhonyKBox (false); // For debugging
switch (_boardID)
{
case DEVICE_ID_KONA3G:
case DEVICE_ID_KONA3GQUAD:
case DEVICE_ID_IO4K:
case DEVICE_ID_KONA4:
case DEVICE_ID_KONA4UFC:
case DEVICE_ID_KONA5:
case DEVICE_ID_KONA5_8KMK:
case DEVICE_ID_KONA5_8K:
case DEVICE_ID_KONA5_2X4K:
case DEVICE_ID_KONA5_3DLUT:
case DEVICE_ID_KONA5_OE1:
// Do we have a K3G-Box?
if ((audioCtlReg & kK2RegMaskKBoxDetect) || bPhonyKBox)
result = NTV2_K3GBox;
else
result = NTV2_BreakoutCableBNC;
break;
case DEVICE_ID_KONALHEPLUS:
// Do we have a KL-Box?
if ((audioCtlReg & kK2RegMaskKBoxDetect) || bPhonyKBox)
result = NTV2_KLBox;
else
result = NTV2_BreakoutCableXLR; // no BNC breakout cable available
break;
case DEVICE_ID_KONALHI:
// Do we have a KLHi-Box?
if ((audioCtlReg & kK2RegMaskKBoxDetect) || bPhonyKBox)
result = NTV2_KLHiBox;
else
result = NTV2_BreakoutCableXLR; // no BNC breakout cable available
break;
default:
break;
}
}
return result;
}
////////// Device Features
bool CNTV2Card::DeviceCanDoFormat (NTV2FrameRate inFrameRate,
NTV2FrameGeometry inFrameGeometry,
NTV2Standard inStandard)
{
return ::NTV2DeviceCanDoFormat (GetDeviceID(), inFrameRate, inFrameGeometry, inStandard);
}
bool CNTV2Card::DeviceCanDo3GOut (UWord index0)
{
return ::NTV2DeviceCanDo3GOut (GetDeviceID(), index0);
}
bool CNTV2Card::DeviceCanDoLTCEmbeddedN (UWord index0)
{
return ::NTV2DeviceCanDoLTCEmbeddedN (GetDeviceID(), index0);
}
ULWord CNTV2Card::DeviceGetFrameBufferSize (void)
{
return ::NTV2DeviceGetFrameBufferSize (GetDeviceID()); // Revisit for 2MB granularity
}
ULWord CNTV2Card::DeviceGetNumberFrameBuffers (void)
{
return ::NTV2DeviceGetNumberFrameBuffers (GetDeviceID()); // Revisit for 2MB granularity
}
ULWord CNTV2Card::DeviceGetAudioFrameBuffer (void)
{
return ::NTV2DeviceGetAudioFrameBuffer (GetDeviceID()); // Revisit for 2MB granularity
}
ULWord CNTV2Card::DeviceGetAudioFrameBuffer2 (void)
{
return ::NTV2DeviceGetAudioFrameBuffer2 (GetDeviceID()); // Revisit for 2MB granularity
}
ULWord CNTV2Card::DeviceGetFrameBufferSize (const NTV2FrameGeometry inFrameGeometry, const NTV2FrameBufferFormat inFBFormat)
{
return ::NTV2DeviceGetFrameBufferSize (GetDeviceID(), inFrameGeometry, inFBFormat); // Revisit for 2MB granularity
}
ULWord CNTV2Card::DeviceGetNumberFrameBuffers (const NTV2FrameGeometry inFrameGeometry, const NTV2FrameBufferFormat inFBFormat)
{
return ::NTV2DeviceGetNumberFrameBuffers (GetDeviceID(), inFrameGeometry, inFBFormat); // Revisit for 2MB granularity
}
ULWord CNTV2Card::DeviceGetAudioFrameBuffer (const NTV2FrameGeometry inFrameGeometry, const NTV2FrameBufferFormat inFBFormat)
{
return ::NTV2DeviceGetAudioFrameBuffer (GetDeviceID(), inFrameGeometry, inFBFormat); // Revisit for 2MB granularity
}
ULWord CNTV2Card::DeviceGetAudioFrameBuffer2 (const NTV2FrameGeometry inFrameGeometry, const NTV2FrameBufferFormat inFBFormat)
{
return ::NTV2DeviceGetAudioFrameBuffer2 (GetDeviceID(), inFrameGeometry, inFBFormat); // Revisit for 2MB granularity
}
bool CNTV2Card::DeviceCanDoVideoFormat (const NTV2VideoFormat inVideoFormat)
{
return ::NTV2DeviceCanDoVideoFormat (GetDeviceID(), inVideoFormat);
}
bool CNTV2Card::DeviceCanDoFrameBufferFormat (const NTV2FrameBufferFormat inFBFormat)
{
return ::NTV2DeviceCanDoFrameBufferFormat (GetDeviceID(), inFBFormat);
}
bool CNTV2Card::DeviceCanDoWidget (const NTV2WidgetID inWidgetID)
{
return ::NTV2DeviceCanDoWidget (GetDeviceID(), inWidgetID);
}
bool CNTV2Card::DeviceCanDoConversionMode (const NTV2ConversionMode inConversionMode)
{
return ::NTV2DeviceCanDoConversionMode (GetDeviceID(), inConversionMode);
}
bool CNTV2Card::DeviceCanDoDSKMode (const NTV2DSKMode inDSKMode)
{
return ::NTV2DeviceCanDoDSKMode (GetDeviceID(), inDSKMode);
}
bool CNTV2Card::DeviceCanDoInputSource (const NTV2InputSource inInputSource)
{
return ::NTV2DeviceCanDoInputSource (GetDeviceID(), inInputSource);
}
bool CNTV2Card::DeviceCanDoAudioMixer ()
{
ULWord isMixerSupported = 0;
ReadRegister(kRegGlobalControl2, isMixerSupported, BIT(18), 18);
if(isMixerSupported == 1)
return true;
return false;
}
bool CNTV2Card::DeviceCanDoHDMIQuadRasterConversion ()
{
NTV2DeviceID deviceID = GetDeviceID();
if ((NTV2DeviceGetNumHDMIVideoInputs(deviceID) == 0) &&
(NTV2DeviceGetNumHDMIVideoOutputs(deviceID) == 0))
return false;
if (deviceID == DEVICE_ID_KONAHDMI)
return false;
if (DeviceCanDoAudioMixer())
return false;
return true;
}
bool CNTV2Card::DeviceIsDNxIV ()
{
ULWord isMicSupported = 0;
ReadRegister(kRegGlobalControl2, isMicSupported, BIT(19), 19);
if(isMicSupported == 1)
return true;
return false;
}
bool CNTV2Card::DeviceHasMicInput ()
{
ULWord isMicSupported = 0;
ReadRegister(kRegGlobalControl2, isMicSupported, BIT(19), 19);
if(isMicSupported == 1)
return true;
return false;
}
bool CNTV2Card::GetBoolParam (const NTV2BoolParamID inParamID, bool & outValue)
{
uint32_t regValue (0);
NTV2RegInfo regInfo;
outValue = false;
if (GetRegInfoForBoolParam (inParamID, regInfo))
{
if (!ReadRegister (regInfo.registerNumber, regValue, regInfo.registerMask, regInfo.registerShift))
return false;
outValue = static_cast <bool> (regValue != 0);
return true;
}
// Call old device features function...
switch (inParamID)
{
// case kDeviceCanChangeEmbeddedAudioClock: outValue = ::NTV2DeviceCanChangeEmbeddedAudioClock (GetDeviceID()); break;
case kDeviceCanChangeFrameBufferSize: outValue = ::NTV2DeviceCanChangeFrameBufferSize (GetDeviceID()); break;
case kDeviceCanDisableUFC: outValue = ::NTV2DeviceCanDisableUFC (GetDeviceID()); break;
case kDeviceCanDo2KVideo: outValue = ::NTV2DeviceCanDo2KVideo (GetDeviceID()); break;
case kDeviceCanDo3GLevelConversion: outValue = ::NTV2DeviceCanDo3GLevelConversion (GetDeviceID()); break;
case kDeviceCanDoRGBLevelAConversion: outValue = ::NTV2DeviceCanDoRGBLevelAConversion (GetDeviceID()); break;
case kDeviceCanDo425Mux: outValue = ::NTV2DeviceCanDo425Mux (GetDeviceID()); break;
case kDeviceCanDo4KVideo: outValue = ::NTV2DeviceCanDo4KVideo (GetDeviceID()); break;
case kDeviceCanDoAESAudioIn: outValue = ::NTV2DeviceCanDoAESAudioIn (GetDeviceID()); break;
case kDeviceCanDoAnalogAudio: outValue = ::NTV2DeviceCanDoAnalogAudio (GetDeviceID()); break;
case kDeviceCanDoAnalogVideoIn: outValue = ::NTV2DeviceCanDoAnalogVideoIn (GetDeviceID()); break;
case kDeviceCanDoAnalogVideoOut: outValue = ::NTV2DeviceCanDoAnalogVideoOut (GetDeviceID()); break;
// case kDeviceCanDoAudio2Channels: outValue = ::NTV2DeviceCanDoAudio2Channels (GetDeviceID()); break;
// case kDeviceCanDoAudio6Channels: outValue = ::NTV2DeviceCanDoAudio6Channels (GetDeviceID()); break;
// case kDeviceCanDoAudio8Channels: outValue = ::NTV2DeviceCanDoAudio8Channels (GetDeviceID()); break;
// case kDeviceCanDoAudio96K: outValue = ::NTV2DeviceCanDoAudio96K (GetDeviceID()); break;
// case kDeviceCanDoAudioDelay: outValue = ::NTV2DeviceCanDoAudioDelay (GetDeviceID()); break;
case kDeviceCanDoBreakoutBox: outValue = ::NTV2DeviceCanDoBreakoutBox (GetDeviceID()); break;
case kDeviceCanDoCapture: outValue = ::NTV2DeviceCanDoCapture (GetDeviceID()); break;
// case kDeviceCanDoColorCorrection: outValue = ::NTV2DeviceCanDoColorCorrection (GetDeviceID()); break;
// case kDeviceCanDoCustomAnc: outValue = ::NTV2DeviceCanDoCustomAnc (GetDeviceID()); break;
// case kDeviceCanDoDSKOpacity: outValue = ::NTV2DeviceCanDoDSKOpacity (GetDeviceID()); break;
// case kDeviceCanDoDualLink: outValue = ::NTV2DeviceCanDoDualLink (GetDeviceID()); break;
// case kDeviceCanDoDVCProHD: outValue = ::NTV2DeviceCanDoDVCProHD (GetDeviceID()); break;
// case kDeviceCanDoEnhancedCSC: outValue = ::NTV2DeviceCanDoEnhancedCSC (GetDeviceID()); break;
// case kDeviceCanDoFrameStore1Display: outValue = ::NTV2DeviceCanDoFrameStore1Display (GetDeviceID()); break;
// case kDeviceCanDoFreezeOutput: outValue = ::NTV2DeviceCanDoFreezeOutput (GetDeviceID()); break;
// case kDeviceCanDoHDMIOutStereo: outValue = ::NTV2DeviceCanDoHDMIOutStereo (GetDeviceID()); break;
// case kDeviceCanDoHDV: outValue = ::NTV2DeviceCanDoHDV (GetDeviceID()); break;
// case kDeviceCanDoHDVideo: outValue = ::NTV2DeviceCanDoHDVideo (GetDeviceID()); break;
case kDeviceCanDoIsoConvert: outValue = ::NTV2DeviceCanDoIsoConvert (GetDeviceID()); break;
case kDeviceCanDoLTC: outValue = ::NTV2DeviceCanDoLTC (GetDeviceID()); break;
case kDeviceCanDoLTCInOnRefPort: outValue = ::NTV2DeviceCanDoLTCInOnRefPort (GetDeviceID()); break;
case kDeviceCanDoMSI: outValue = ::NTV2DeviceCanDoMSI (GetDeviceID()); break;
case kDeviceCanDoMultiFormat: outValue = ::NTV2DeviceCanDoMultiFormat (GetDeviceID()); break;
case kDeviceCanDoPCMControl: outValue = ::NTV2DeviceCanDoPCMControl (GetDeviceID()); break;
case kDeviceCanDoPCMDetection: outValue = ::NTV2DeviceCanDoPCMDetection (GetDeviceID()); break;
// case kDeviceCanDoPIO: outValue = ::NTV2DeviceCanDoPIO (GetDeviceID()); break;
case kDeviceCanDoPlayback: outValue = ::NTV2DeviceCanDoPlayback (GetDeviceID()); break;
case kDeviceCanDoProgrammableCSC: outValue = ::NTV2DeviceCanDoProgrammableCSC (GetDeviceID()); break;
case kDeviceCanDoProgrammableRS422: outValue = ::NTV2DeviceCanDoProgrammableRS422 (GetDeviceID()); break;
case kDeviceCanDoProRes: outValue = ::NTV2DeviceCanDoProRes (GetDeviceID()); break;
case kDeviceCanDoQREZ: outValue = ::NTV2DeviceCanDoQREZ (GetDeviceID()); break;
case kDeviceCanDoQuarterExpand: outValue = ::NTV2DeviceCanDoQuarterExpand (GetDeviceID()); break;
// case kDeviceCanDoRateConvert: outValue = ::NTV2DeviceCanDoRateConvert (GetDeviceID()); break;
// case kDeviceCanDoRGBPlusAlphaOut: outValue = ::NTV2DeviceCanDoRGBPlusAlphaOut (GetDeviceID()); break;
// case kDeviceCanDoRP188: outValue = ::NTV2DeviceCanDoRP188 (GetDeviceID()); break;
// case kDeviceCanDoSDVideo: outValue = ::NTV2DeviceCanDoSDVideo (GetDeviceID()); break;
case kDeviceCanDoSDIErrorChecks: outValue = ::NTV2DeviceCanDoSDIErrorChecks (GetDeviceID()); break;
// case kDeviceCanDoStackedAudio: outValue = ::NTV2DeviceCanDoStackedAudio (GetDeviceID()); break;
// case kDeviceCanDoStereoIn: outValue = ::NTV2DeviceCanDoStereoIn (GetDeviceID()); break;
// case kDeviceCanDoStereoOut: outValue = ::NTV2DeviceCanDoStereoOut (GetDeviceID()); break;
case kDeviceCanDoThunderbolt: outValue = ::NTV2DeviceCanDoThunderbolt (GetDeviceID()); break;
case kDeviceCanDoVideoProcessing: outValue = ::NTV2DeviceCanDoVideoProcessing (GetDeviceID()); break;
case kDeviceCanMeasureTemperature: outValue = ::NTV2DeviceCanMeasureTemperature (GetDeviceID()); break;
case kDeviceCanReportFrameSize: outValue = ::NTV2DeviceCanReportFrameSize (GetDeviceID()); break;
case kDeviceHasBiDirectionalSDI: outValue = ::NTV2DeviceHasBiDirectionalSDI (GetDeviceID()); break;
// case kDeviceHasColorSpaceConverterOnChannel2: outValue = ::NTV2DeviceHasColorSpaceConverterOnChannel2 (GetDeviceID()); break;
case kDeviceHasNWL: outValue = ::NTV2DeviceHasNWL (GetDeviceID()); break;
case kDeviceHasPCIeGen2: outValue = ::NTV2DeviceHasPCIeGen2 (GetDeviceID()); break;
case kDeviceHasRetailSupport: outValue = ::NTV2DeviceHasRetailSupport (GetDeviceID()); break;
case kDeviceHasSDIRelays: outValue = ::NTV2DeviceHasSDIRelays (GetDeviceID()); break;
// case kDeviceHasSPIFlash: outValue = ::NTV2DeviceHasSPIFlash (GetDeviceID()); break;
// case kDeviceHasSPIFlashSerial: outValue = ::NTV2DeviceHasSPIFlashSerial (GetDeviceID()); break;
case kDeviceHasSPIv2: outValue = ::NTV2DeviceHasSPIv2 (GetDeviceID()); break;
case kDeviceHasSPIv3: outValue = ::NTV2DeviceHasSPIv3 (GetDeviceID()); break;
case kDeviceHasSPIv4: outValue = ::NTV2DeviceHasSPIv4 (GetDeviceID()); break;
// case kDeviceIs64Bit: outValue = ::NTV2DeviceIs64Bit (GetDeviceID()); break;
// case kDeviceIsDirectAddressable: outValue = ::NTV2DeviceIsDirectAddressable (GetDeviceID()); break;
case kDeviceIsExternalToHost: outValue = ::NTV2DeviceIsExternalToHost (GetDeviceID()); break;
case kDeviceIsSupported: outValue = ::NTV2DeviceIsSupported (GetDeviceID()); break;
// case kDeviceNeedsRoutingSetup: outValue = ::NTV2DeviceNeedsRoutingSetup (GetDeviceID()); break;
case kDeviceSoftwareCanChangeFrameBufferSize: outValue = ::NTV2DeviceSoftwareCanChangeFrameBufferSize (GetDeviceID()); break;
case kDeviceCanThermostat: outValue = ::NTV2DeviceCanThermostat (GetDeviceID()); break;
case kDeviceHasHEVCM31: outValue = ::NTV2DeviceHasHEVCM31 (GetDeviceID()); break;
case kDeviceHasHEVCM30: outValue = ::NTV2DeviceHasHEVCM30 (GetDeviceID()); break;
case kDeviceCanDoVITC2: outValue = ::NTV2DeviceCanDoVITC2 (GetDeviceID()); break;
case kDeviceCanDoHDMIHDROut: outValue = ::NTV2DeviceCanDoHDMIHDROut (GetDeviceID()); break;
case kDeviceCanDoJ2K: outValue = ::NTV2DeviceCanDoJ2K (GetDeviceID()); break;
default: return false; // Bad param
}
return true; // Successfully used old ::NTV2DeviceCanDo function
} // GetBoolParam
bool CNTV2Card::GetNumericParam (const NTV2NumericParamID inParamID, uint32_t & outValue)
{
uint32_t regValue (0);
NTV2RegInfo regInfo;
outValue = false;
if (GetRegInfoForNumericParam (inParamID, regInfo))
{
if (!ReadRegister (regInfo.registerNumber, regValue, regInfo.registerMask, regInfo.registerShift))
return false;
outValue = static_cast <bool> (regValue != 0);
return true;
}
// Call old device features function...
switch (inParamID)
{
case kDeviceGetActiveMemorySize: outValue = ::NTV2DeviceGetActiveMemorySize (GetDeviceID()); break;
case kDeviceGetDACVersion: outValue = ::NTV2DeviceGetDACVersion (GetDeviceID()); break;
case kDeviceGetDownConverterDelay: outValue = ::NTV2DeviceGetDownConverterDelay (GetDeviceID()); break;
case kDeviceGetHDMIVersion: outValue = ::NTV2DeviceGetHDMIVersion (GetDeviceID()); break;
case kDeviceGetLUTVersion: outValue = ::NTV2DeviceGetLUTVersion (GetDeviceID()); break;
case kDeviceGetMaxAudioChannels: outValue = ::NTV2DeviceGetMaxAudioChannels (GetDeviceID()); break;
case kDeviceGetMaxRegisterNumber: outValue = ::NTV2DeviceGetMaxRegisterNumber (GetDeviceID()); break;
case kDeviceGetMaxTransferCount: outValue = ::NTV2DeviceGetMaxTransferCount (GetDeviceID()); break;
case kDeviceGetNumDMAEngines: outValue = ::NTV2DeviceGetNumDMAEngines (GetDeviceID()); break;
case kDeviceGetNumVideoChannels: outValue = ::NTV2DeviceGetNumVideoChannels (GetDeviceID()); break;
case kDeviceGetPingLED: outValue = ::NTV2DeviceGetPingLED (GetDeviceID()); break;
case kDeviceGetUFCVersion: outValue = ::NTV2DeviceGetUFCVersion (GetDeviceID()); break;
case kDeviceGetNum4kQuarterSizeConverters: outValue = ::NTV2DeviceGetNum4kQuarterSizeConverters (GetDeviceID()); break;
case kDeviceGetNumAESAudioInputChannels: outValue = ::NTV2DeviceGetNumAESAudioInputChannels (GetDeviceID()); break;
case kDeviceGetNumAESAudioOutputChannels: outValue = ::NTV2DeviceGetNumAESAudioOutputChannels (GetDeviceID()); break;
case kDeviceGetNumAnalogAudioInputChannels: outValue = ::NTV2DeviceGetNumAnalogAudioInputChannels (GetDeviceID()); break;
case kDeviceGetNumAnalogAudioOutputChannels: outValue = ::NTV2DeviceGetNumAnalogAudioOutputChannels (GetDeviceID()); break;
case kDeviceGetNumAnalogVideoInputs: outValue = ::NTV2DeviceGetNumAnalogVideoInputs (GetDeviceID()); break;
case kDeviceGetNumAnalogVideoOutputs: outValue = ::NTV2DeviceGetNumAnalogVideoOutputs (GetDeviceID()); break;
case kDeviceGetNumAudioSystems: outValue = (::NTV2DeviceGetNumAudioSystems (GetDeviceID()) + (DeviceCanDoAudioMixer() ? 1 : 0)); break;
case kDeviceGetNumCrossConverters: outValue = ::NTV2DeviceGetNumCrossConverters (GetDeviceID()); break;
case kDeviceGetNumCSCs: outValue = ::NTV2DeviceGetNumCSCs (GetDeviceID()); break;
case kDeviceGetNumDownConverters: outValue = ::NTV2DeviceGetNumDownConverters (GetDeviceID()); break;
case kDeviceGetNumEmbeddedAudioInputChannels: outValue = ::NTV2DeviceGetNumEmbeddedAudioInputChannels (GetDeviceID()); break;
case kDeviceGetNumEmbeddedAudioOutputChannels: outValue = ::NTV2DeviceGetNumEmbeddedAudioOutputChannels (GetDeviceID()); break;
case kDeviceGetNumFrameStores: outValue = ::NTV2DeviceGetNumFrameStores (GetDeviceID()); break;
case kDeviceGetNumFrameSyncs: outValue = ::NTV2DeviceGetNumFrameSyncs (GetDeviceID()); break;
case kDeviceGetNumHDMIAudioInputChannels: outValue = ::NTV2DeviceGetNumHDMIAudioInputChannels (GetDeviceID()); break;
case kDeviceGetNumHDMIAudioOutputChannels: outValue = ::NTV2DeviceGetNumHDMIAudioOutputChannels (GetDeviceID()); break;
case kDeviceGetNumHDMIVideoInputs: outValue = ::NTV2DeviceGetNumHDMIVideoInputs (GetDeviceID()); break;
case kDeviceGetNumHDMIVideoOutputs: outValue = ::NTV2DeviceGetNumHDMIVideoOutputs (GetDeviceID()); break;
case kDeviceGetNumInputConverters: outValue = ::NTV2DeviceGetNumInputConverters (GetDeviceID()); break;
case kDeviceGetNumLUTs: outValue = ::NTV2DeviceGetNumLUTs (GetDeviceID()); break;
case kDeviceGetNumMixers: outValue = ::NTV2DeviceGetNumMixers (GetDeviceID()); break;
case kDeviceGetNumOutputConverters: outValue = ::NTV2DeviceGetNumOutputConverters (GetDeviceID()); break;
case kDeviceGetNumReferenceVideoInputs: outValue = ::NTV2DeviceGetNumReferenceVideoInputs (GetDeviceID()); break;
case kDeviceGetNumSerialPorts: outValue = ::NTV2DeviceGetNumSerialPorts (GetDeviceID()); break;
case kDeviceGetNumUpConverters: outValue = ::NTV2DeviceGetNumUpConverters (GetDeviceID()); break;
case kDeviceGetNumVideoInputs: outValue = ::NTV2DeviceGetNumVideoInputs (GetDeviceID()); break;
case kDeviceGetNumVideoOutputs: outValue = ::NTV2DeviceGetNumVideoOutputs (GetDeviceID()); break;
case kDeviceGetNum2022ChannelsSFP1: outValue = ::NTV2DeviceGetNum2022ChannelsSFP1 (GetDeviceID()); break;
case kDeviceGetNum2022ChannelsSFP2: outValue = ::NTV2DeviceGetNum2022ChannelsSFP2 (GetDeviceID()); break;
case kDeviceGetNumLTCInputs: outValue = ::NTV2DeviceGetNumLTCInputs (GetDeviceID()); break;
case kDeviceGetNumLTCOutputs: outValue = ::NTV2DeviceGetNumLTCOutputs (GetDeviceID()); break;
default: return false; // Bad param
}
return true; // Successfully used old ::NTV2DeviceGetNum function
} // GetNumericParam
bool CNTV2Card::GetRegInfoForBoolParam (const NTV2BoolParamID inParamID, NTV2RegInfo & outRegInfo)
{
(void) inParamID;
outRegInfo.MakeInvalid();
return false; // Needs implementation
}
bool CNTV2Card::GetRegInfoForNumericParam (const NTV2NumericParamID inParamID, NTV2RegInfo & outRegInfo)
{
(void) inParamID;
outRegInfo.MakeInvalid();
return false; // Needs implementation
}
/////////// Stream Operators
ostream & operator << (ostream & inOutStr, const NTV2AudioChannelPairs & inSet)
{
if (inSet.empty())
inOutStr << "(none)";
else
for (NTV2AudioChannelPairsConstIter iter (inSet.begin ()); iter != inSet.end (); ++iter)
inOutStr << (iter != inSet.begin() ? ", " : "") << ::NTV2AudioChannelPairToString (*iter, true);
return inOutStr;
}
ostream & operator << (ostream & inOutStr, const NTV2AudioChannelQuads & inSet)
{
for (NTV2AudioChannelQuadsConstIter iter (inSet.begin ()); iter != inSet.end (); ++iter)
inOutStr << (iter != inSet.begin () ? ", " : "") << ::NTV2AudioChannelQuadToString (*iter, true);
return inOutStr;
}
ostream & operator << (ostream & inOutStr, const NTV2AudioChannelOctets & inSet)
{
for (NTV2AudioChannelOctetsConstIter iter (inSet.begin ()); iter != inSet.end (); ++iter)
inOutStr << (iter != inSet.begin () ? ", " : "") << ::NTV2AudioChannelOctetToString (*iter, true);
return inOutStr;
}
ostream & operator << (ostream & inOutStr, const NTV2DoubleArray & inVector)
{
for (NTV2DoubleArrayConstIter iter (inVector.begin ()); iter != inVector.end (); ++iter)
inOutStr << *iter << endl;
return inOutStr;
}
ostream & operator << (ostream & inOutStr, const NTV2DIDSet & inDIDs)
{
for (NTV2DIDSetConstIter it (inDIDs.begin()); it != inDIDs.end(); )
{
inOutStr << xHEX0N(uint16_t(*it),2);
if (++it != inDIDs.end())
inOutStr << ", ";
}
return inOutStr;
}
#if !defined (NTV2_DEPRECATE)
bool CNTV2Card::GetBitFileInformation (ULWord & outNumBytes, string & outDateStr, string & outTimeStr, const NTV2XilinxFPGA inFPGA)
{
return inFPGA == eFPGAVideoProc ? GetInstalledBitfileInfo (outNumBytes, outDateStr, outTimeStr) : false;
}
Word CNTV2Card::GetFPGAVersion (const NTV2XilinxFPGA inFPGA)
{
(void) inFPGA;
return -1;
}
UWord CNTV2Card::GetNumNTV2Boards()
{
ULWord numBoards(0);
CNTV2Card ntv2Card;
for (ULWord boardCount(0); boardCount < NTV2_MAXBOARDS; boardCount++)
{
if (AsNTV2DriverInterfaceRef(ntv2Card).Open(boardCount))
numBoards++; // Opened, keep going
else
break; // Failed to open, we're done
}
return numBoards;
}
NTV2BoardType CNTV2Card::GetBoardType (void) const
{
return DEVICETYPE_NTV2;
}
NTV2BoardSubType CNTV2Card::GetBoardSubType (void)
{
return BOARDSUBTYPE_NONE;
}
bool CNTV2Card::SetBoard (UWord inDeviceIndexNumber)
{
return CNTV2DriverInterface::Open(inDeviceIndexNumber);
}
string CNTV2Card::GetBoardIDString (void)
{
const ULWord boardID (static_cast <ULWord> (GetDeviceID ()));
ostringstream oss;
oss << hex << boardID;
return oss.str ();
}
void CNTV2Card::GetBoardIDString(std::string & outString)
{
outString = GetBoardIDString();
}
#endif // !defined (NTV2_DEPRECATE)
NTV2_POINTER CNTV2Card::NULL_POINTER (AJA_NULL, 0);
| 40.014493 | 145 | 0.728805 | DDRBoxman |
36925b1ff375afced57867b0d20d849be95daa91 | 5,189 | cpp | C++ | Util/llvm/lib/CodeGen/ExactHazardRecognizer.cpp | ianloic/unladen-swallow | 28148f4ddbb3d519042de1f9fc9f1356fdd31e31 | [
"PSF-2.0"
] | 5 | 2020-06-30T05:06:40.000Z | 2021-05-24T08:38:33.000Z | Util/llvm/lib/CodeGen/ExactHazardRecognizer.cpp | ianloic/unladen-swallow | 28148f4ddbb3d519042de1f9fc9f1356fdd31e31 | [
"PSF-2.0"
] | null | null | null | Util/llvm/lib/CodeGen/ExactHazardRecognizer.cpp | ianloic/unladen-swallow | 28148f4ddbb3d519042de1f9fc9f1356fdd31e31 | [
"PSF-2.0"
] | 2 | 2015-10-01T18:28:20.000Z | 2020-09-09T16:25:27.000Z | //===----- ExactHazardRecognizer.cpp - hazard recognizer -------- ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This implements a a hazard recognizer using the instructions itineraries
// defined for the current target.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "post-RA-sched"
#include "ExactHazardRecognizer.h"
#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetInstrItineraries.h"
using namespace llvm;
ExactHazardRecognizer::
ExactHazardRecognizer(const InstrItineraryData &LItinData) :
ScheduleHazardRecognizer(), ItinData(LItinData)
{
// Determine the maximum depth of any itinerary. This determines the
// depth of the scoreboard. We always make the scoreboard at least 1
// cycle deep to avoid dealing with the boundary condition.
ScoreboardDepth = 1;
if (!ItinData.isEmpty()) {
for (unsigned idx = 0; ; ++idx) {
if (ItinData.isEndMarker(idx))
break;
const InstrStage *IS = ItinData.beginStage(idx);
const InstrStage *E = ItinData.endStage(idx);
unsigned ItinDepth = 0;
for (; IS != E; ++IS)
ItinDepth += IS->getCycles();
ScoreboardDepth = std::max(ScoreboardDepth, ItinDepth);
}
}
Scoreboard = new unsigned[ScoreboardDepth];
ScoreboardHead = 0;
DEBUG(errs() << "Using exact hazard recognizer: ScoreboardDepth = "
<< ScoreboardDepth << '\n');
}
ExactHazardRecognizer::~ExactHazardRecognizer() {
delete [] Scoreboard;
}
void ExactHazardRecognizer::Reset() {
memset(Scoreboard, 0, ScoreboardDepth * sizeof(unsigned));
ScoreboardHead = 0;
}
unsigned ExactHazardRecognizer::getFutureIndex(unsigned offset) {
return (ScoreboardHead + offset) % ScoreboardDepth;
}
void ExactHazardRecognizer::dumpScoreboard() {
errs() << "Scoreboard:\n";
unsigned last = ScoreboardDepth - 1;
while ((last > 0) && (Scoreboard[getFutureIndex(last)] == 0))
last--;
for (unsigned i = 0; i <= last; i++) {
unsigned FUs = Scoreboard[getFutureIndex(i)];
errs() << "\t";
for (int j = 31; j >= 0; j--)
errs() << ((FUs & (1 << j)) ? '1' : '0');
errs() << '\n';
}
}
ExactHazardRecognizer::HazardType ExactHazardRecognizer::getHazardType(SUnit *SU) {
if (ItinData.isEmpty())
return NoHazard;
unsigned cycle = 0;
// Use the itinerary for the underlying instruction to check for
// free FU's in the scoreboard at the appropriate future cycles.
unsigned idx = SU->getInstr()->getDesc().getSchedClass();
for (const InstrStage *IS = ItinData.beginStage(idx),
*E = ItinData.endStage(idx); IS != E; ++IS) {
// We must find one of the stage's units free for every cycle the
// stage is occupied. FIXME it would be more accurate to find the
// same unit free in all the cycles.
for (unsigned int i = 0; i < IS->getCycles(); ++i) {
assert(((cycle + i) < ScoreboardDepth) &&
"Scoreboard depth exceeded!");
unsigned index = getFutureIndex(cycle + i);
unsigned freeUnits = IS->getUnits() & ~Scoreboard[index];
if (!freeUnits) {
DEBUG(errs() << "*** Hazard in cycle " << (cycle + i) << ", ");
DEBUG(errs() << "SU(" << SU->NodeNum << "): ");
DEBUG(SU->getInstr()->dump());
return Hazard;
}
}
// Advance the cycle to the next stage.
cycle += IS->getNextCycles();
}
return NoHazard;
}
void ExactHazardRecognizer::EmitInstruction(SUnit *SU) {
if (ItinData.isEmpty())
return;
unsigned cycle = 0;
// Use the itinerary for the underlying instruction to reserve FU's
// in the scoreboard at the appropriate future cycles.
unsigned idx = SU->getInstr()->getDesc().getSchedClass();
for (const InstrStage *IS = ItinData.beginStage(idx),
*E = ItinData.endStage(idx); IS != E; ++IS) {
// We must reserve one of the stage's units for every cycle the
// stage is occupied. FIXME it would be more accurate to reserve
// the same unit free in all the cycles.
for (unsigned int i = 0; i < IS->getCycles(); ++i) {
assert(((cycle + i) < ScoreboardDepth) &&
"Scoreboard depth exceeded!");
unsigned index = getFutureIndex(cycle + i);
unsigned freeUnits = IS->getUnits() & ~Scoreboard[index];
// reduce to a single unit
unsigned freeUnit = 0;
do {
freeUnit = freeUnits;
freeUnits = freeUnit & (freeUnit - 1);
} while (freeUnits);
assert(freeUnit && "No function unit available!");
Scoreboard[index] |= freeUnit;
}
// Advance the cycle to the next stage.
cycle += IS->getNextCycles();
}
DEBUG(dumpScoreboard());
}
void ExactHazardRecognizer::AdvanceCycle() {
Scoreboard[ScoreboardHead] = 0;
ScoreboardHead = getFutureIndex(1);
}
| 32.030864 | 83 | 0.620929 | ianloic |
3694473bc91952aeae213fe1bb9df502c894bfcd | 1,229 | cpp | C++ | buyer-swift/xlsx/app.cpp | shakfu/buy | 7ba3c106fa7cb9e65bc88708b165e82e59e9edda | [
"Unlicense"
] | null | null | null | buyer-swift/xlsx/app.cpp | shakfu/buy | 7ba3c106fa7cb9e65bc88708b165e82e59e9edda | [
"Unlicense"
] | null | null | null | buyer-swift/xlsx/app.cpp | shakfu/buy | 7ba3c106fa7cb9e65bc88708b165e82e59e9edda | [
"Unlicense"
] | null | null | null | #include <iostream>
extern "C" {
#include "xlsxwriter.h"
}
/* Some data we want to write to the worksheet. */
struct expense {
char item[32];
int cost;
};
struct expense expenses[] = {
{"Rent", 1000},
{"Gas", 100},
{"Food", 300},
{"Gym", 50},
};
class XLWriter {
public:
int build();
};
int XLWriter::build() {
lxw_workbook *workbook = workbook_new("app.xlsx");
lxw_worksheet *worksheet = workbook_add_worksheet(workbook, NULL);
/* Start from the first cell. Rows and columns are zero indexed. */
int row = 0;
int col = 0;
/* Iterate over the data and write it out element by element. */
for (row = 0; row < 4; row++) {
worksheet_write_string(worksheet, row, col, expenses[row].item, NULL);
worksheet_write_number(worksheet, row, col + 1, expenses[row].cost, NULL);
}
/* Write a total using a formula. */
worksheet_write_string (worksheet, row, col, "Total", NULL);
worksheet_write_formula(worksheet, row, col + 1, "=SUM(B1:B4)", NULL);
/* Save the workbook and free any allocated memory. */
return workbook_close(workbook);
}
int main() {
XLWriter xl;
return xl.build();
}
| 21.561404 | 82 | 0.606184 | shakfu |
3695f4e8d8a68fbb19f75c4d585507840338a596 | 3,326 | cpp | C++ | src/org/apache/poi/hssf/record/aggregates/DataValidityTable.cpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/hssf/record/aggregates/DataValidityTable.cpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/hssf/record/aggregates/DataValidityTable.cpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | // Generated from /POI/java/org/apache/poi/hssf/record/aggregates/DataValidityTable.java
#include <org/apache/poi/hssf/record/aggregates/DataValidityTable.hpp>
#include <java/lang/Class.hpp>
#include <java/lang/ClassCastException.hpp>
#include <java/lang/NullPointerException.hpp>
#include <java/lang/Object.hpp>
#include <java/util/ArrayList.hpp>
#include <java/util/List.hpp>
#include <org/apache/poi/hssf/model/RecordStream.hpp>
#include <org/apache/poi/hssf/record/DVALRecord.hpp>
#include <org/apache/poi/hssf/record/DVRecord.hpp>
#include <org/apache/poi/hssf/record/Record.hpp>
#include <org/apache/poi/hssf/record/aggregates/RecordAggregate_RecordVisitor.hpp>
template<typename T, typename U>
static T java_cast(U* u)
{
if(!u) return static_cast<T>(nullptr);
auto t = dynamic_cast<T>(u);
if(!t) throw new ::java::lang::ClassCastException();
return t;
}
template<typename T>
static T* npc(T* t)
{
if(!t) throw new ::java::lang::NullPointerException();
return t;
}
poi::hssf::record::aggregates::DataValidityTable::DataValidityTable(const ::default_init_tag&)
: super(*static_cast< ::default_init_tag* >(0))
{
clinit();
}
poi::hssf::record::aggregates::DataValidityTable::DataValidityTable(::poi::hssf::model::RecordStream* rs)
: DataValidityTable(*static_cast< ::default_init_tag* >(0))
{
ctor(rs);
}
poi::hssf::record::aggregates::DataValidityTable::DataValidityTable()
: DataValidityTable(*static_cast< ::default_init_tag* >(0))
{
ctor();
}
void poi::hssf::record::aggregates::DataValidityTable::ctor(::poi::hssf::model::RecordStream* rs)
{
super::ctor();
_headerRec = java_cast< ::poi::hssf::record::DVALRecord* >(npc(rs)->getNext());
::java::util::List* temp = new ::java::util::ArrayList();
while (static_cast< ::java::lang::Object* >(npc(rs)->peekNextClass()) == static_cast< ::java::lang::Object* >(::poi::hssf::record::DVRecord::class_())) {
npc(temp)->add(static_cast< ::java::lang::Object* >(java_cast< ::poi::hssf::record::DVRecord* >(npc(rs)->getNext())));
}
_validationList = temp;
}
void poi::hssf::record::aggregates::DataValidityTable::ctor()
{
super::ctor();
_headerRec = new ::poi::hssf::record::DVALRecord();
_validationList = new ::java::util::ArrayList();
}
void poi::hssf::record::aggregates::DataValidityTable::visitContainedRecords(RecordAggregate_RecordVisitor* rv)
{
if(npc(_validationList)->isEmpty()) {
return;
}
npc(rv)->visitRecord(_headerRec);
for (auto i = int32_t(0); i < npc(_validationList)->size(); i++) {
npc(rv)->visitRecord(java_cast< ::poi::hssf::record::DVRecord* >(npc(_validationList)->get(i)));
}
}
void poi::hssf::record::aggregates::DataValidityTable::addDataValidation(::poi::hssf::record::DVRecord* dvRecord)
{
npc(_validationList)->add(static_cast< ::java::lang::Object* >(dvRecord));
npc(_headerRec)->setDVRecNo(npc(_validationList)->size());
}
extern java::lang::Class *class_(const char16_t *c, int n);
java::lang::Class* poi::hssf::record::aggregates::DataValidityTable::class_()
{
static ::java::lang::Class* c = ::class_(u"org.apache.poi.hssf.record.aggregates.DataValidityTable", 55);
return c;
}
java::lang::Class* poi::hssf::record::aggregates::DataValidityTable::getClass0()
{
return class_();
}
| 33.938776 | 157 | 0.69543 | pebble2015 |
369be65e03323cec46f38841022822a5cc4a82f6 | 1,266 | cc | C++ | src/simple-quic/quicsock/quicsock_alarm.cc | Hasan-Jawaheri/quic-tor | f8a5b8b93a82eb515808d381bfbb2cc662e12513 | [
"MIT"
] | null | null | null | src/simple-quic/quicsock/quicsock_alarm.cc | Hasan-Jawaheri/quic-tor | f8a5b8b93a82eb515808d381bfbb2cc662e12513 | [
"MIT"
] | null | null | null | src/simple-quic/quicsock/quicsock_alarm.cc | Hasan-Jawaheri/quic-tor | f8a5b8b93a82eb515808d381bfbb2cc662e12513 | [
"MIT"
] | null | null | null | #include "quicsock/quicsock_alarm.h"
#include "base/logging.h"
#include "net/quic/quic_time.h"
namespace quicsock {
QuicSockAlarm::QuicSockAlarm(const net::QuicClock* clock,
net::QuicAlarm::Delegate* delegate, QuicSockEventHandler *event_handler)
: net::QuicAlarm(delegate),
clock_(clock),
event_handler_(event_handler),
alarm_registered_(false),
alarm_id_(0) {}
QuicSockAlarm::~QuicSockAlarm() {
CancelImpl();
}
void QuicSockAlarm::SetImpl() {
DCHECK(deadline().IsInitialized());
DCHECK(event_handler_ != nullptr);
DCHECK(!alarm_registered_);
net::QuicTime::Delta duration = deadline().Subtract(clock_->ApproximateNow());
duration = net::QuicTime::Delta::Max(duration, net::QuicTime::Delta::Zero());
alarm_id_ = event_handler_->RegisterAlarm(duration.ToMicroseconds(), this);
alarm_registered_ = true;
}
void QuicSockAlarm::CancelImpl() {
DCHECK(!deadline().IsInitialized());
DCHECK(event_handler_ != nullptr);
// User may call cancel multiple times.
if (!alarm_registered_)
return;
event_handler_->CancelAlarm(alarm_id_);
alarm_registered_ = false;
}
void QuicSockAlarm::OnAlarm() {
if (!alarm_registered_)
return;
this->Fire();
}
} // namespace quicsock
| 24.346154 | 80 | 0.703002 | Hasan-Jawaheri |
369cdad1421e383cc31aaac0c3da8fba587bde8a | 8,730 | cpp | C++ | particle-system/particle-system-app.cpp | ddiakopoulos/sandbox | fd4aa4d0e1cd6e45459cdee44aa18d0087adb708 | [
"Unlicense"
] | 177 | 2015-09-19T19:51:57.000Z | 2021-11-08T11:25:55.000Z | particle-system/particle-system-app.cpp | ddiakopoulos/gfx_dev | fd4aa4d0e1cd6e45459cdee44aa18d0087adb708 | [
"Unlicense"
] | 1 | 2016-03-16T23:27:11.000Z | 2016-03-17T08:12:54.000Z | particle-system/particle-system-app.cpp | ddiakopoulos/gfx_dev | fd4aa4d0e1cd6e45459cdee44aa18d0087adb708 | [
"Unlicense"
] | 16 | 2016-03-16T13:06:55.000Z | 2020-06-20T04:57:04.000Z | #include "index.hpp"
#include "particle-system-app.hpp"
#include "imgui/imgui_internal.h"
using namespace avl;
constexpr const char basic_vert[] = R"(#version 330
layout(location = 0) in vec3 vertex;
uniform mat4 u_mvp;
void main()
{
gl_Position = u_mvp * vec4(vertex.xyz, 1);
}
)";
constexpr const char basic_frag[] = R"(#version 330
out vec4 f_color;
uniform vec3 u_color;
void main()
{
f_color = vec4(u_color, 1);
}
)";
UniformRandomGenerator gen;
particle_system::particle_system(size_t trailCount) : trailCount(trailCount)
{
const float2 quadCoords[] = { { 0,0 },{ 1,0 },{ 1,1 },{ 0,1 } };
glNamedBufferDataEXT(vertexBuffer, sizeof(quadCoords), quadCoords, GL_STATIC_DRAW);
}
void particle_system::add_modifier(std::unique_ptr<particle_modifier> modifier)
{
particleModifiers.push_back(std::move(modifier));
}
void particle_system::add(const float3 & position, const float3 & velocity, float size, float lifeMs)
{
particle p;
p.position = position;
p.velocity = velocity;
p.size = size;
p.lifeMs = lifeMs;
particles.push_back(std::move(p));
}
void particle_system::update(float dt, const float3 & gravityVec)
{
if (particles.size() == 0) return;
for (auto & p : particles)
{
p.position += p.velocity * dt;
p.lifeMs -= dt;
p.isDead = p.lifeMs <= 0.f;
}
for (auto & modifier : particleModifiers)
{
modifier->update(particles, dt);
}
if (!particles.empty())
{
auto it = std::remove_if(std::begin(particles), std::end(particles), [](const particle & p)
{
return p.isDead;
});
particles.erase(it, std::end(particles));
}
instances.clear();
for (auto & p : particles)
{
float3 position = p.position;
float sz = p.size;
// create a trail using instancing
for (int i = 0; i < (1 + trailCount); ++i)
{
instances.push_back({ position, sz });
position -= p.velocity * 0.001f;
sz *= 0.9f;
}
}
glNamedBufferDataEXT(instanceBuffer, instances.size() * sizeof(float4), instances.data(), GL_DYNAMIC_DRAW);
}
void particle_system::draw(const float4x4 & viewMat, const float4x4 & projMat, GlShader & shader, GlTexture2D & outerTex, GlTexture2D & innerTex, float time)
{
if (instances.size() == 0) return;
shader.bind();
{
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // one-one, additive
glDepthMask(GL_FALSE);
shader.uniform("u_modelMatrix", Identity4x4);
shader.uniform("u_viewMat", viewMat);
shader.uniform("u_viewProjMat", mul(projMat, viewMat));
shader.uniform("u_time", time);
shader.texture("s_outerTex", 0, outerTex, GL_TEXTURE_2D);
shader.texture("s_innerTex", 1, innerTex, GL_TEXTURE_2D);
// Instance buffer contains position and size
glBindBuffer(GL_ARRAY_BUFFER, instanceBuffer);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(float4), nullptr);
glVertexAttribDivisor(0, 1);
// Quad
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(float2), nullptr);
glVertexAttribDivisor(1, 0);
glDrawArraysInstanced(GL_QUADS, 0, 4, (GLsizei)instances.size());
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDepthMask(GL_TRUE);
glDisable(GL_BLEND);
}
shader.unbind();
}
shader_workbench::shader_workbench() : GLFWApp(1200, 800, "Particle System Example")
{
int width, height;
glfwGetWindowSize(window, &width, &height);
glViewport(0, 0, width, height);
igm.reset(new gui::imgui_wrapper(window));
gui::make_light_theme();
basicShader = std::make_shared<GlShader>(basic_vert, basic_frag);
particleSystem.reset(new particle_system(4));
//auto groundPlaneModifier = std::unique_ptr<ground_modifier>(new ground_modifier(Plane({ 0, 1, 0 }, 0.f)));
//particleSystem->add_modifier(std::move(groundPlaneModifier));
//auto gravityModifier = std::unique_ptr<gravity_modifier>(new gravity_modifier(float3(0, -9.8f, 0)));
//particleSystem->add_modifier(std::move(gravityModifier));
//auto dampingModifier = std::unique_ptr<damping_modifier>(new damping_modifier(0.5f));
//particleSystem->add_modifier(std::move(dampingModifier));
//auto ptGravityModifier = std::unique_ptr<point_gravity_modifier>(new point_gravity_modifier(float3(-2, 2, -2), 3.f, 0.5f, 8.f));
//particleSystem->add_modifier(std::move(ptGravityModifier));
//auto ptGravityModifier2 = std::unique_ptr<point_gravity_modifier>(new point_gravity_modifier(float3(+2, 2, +2), 3.f, 0.5f, 8.f));
//particleSystem->add_modifier(std::move(ptGravityModifier2));
//auto vortexModifier = std::unique_ptr<vortex_modifier>(new vortex_modifier(float3(0, 9, 0), float3(0, 1, -1), IM_PI / 2.f, 1.0f, 8.0f, 2.5f));
//particleSystem->add_modifier(std::move(vortexModifier));
pointEmitter.pose.position = float3(0, 4, 0);
cubeEmitter.pose.position = float3(-8, 0, 0);
sphereEmitter.pose.position = float3(0, 0, 8);
planeEmitter.pose.position = float3(0, 0, -8);
circleEmitter.pose.position = float3(+8, 0, 0);
shaderMonitor.watch("../assets/shaders/particles/particle_system_vert.glsl", "../assets/shaders/particles/particle_system_frag.glsl", [&](GlShader & shader)
{
particleShader = std::move(shader);
});
outerTex = load_image("../assets/images/particle_alt_large.png");
innerTex = load_image("../assets/images/blur_03.png");
gizmo.reset(new GlGizmo());
grid.reset(new RenderableGrid());
cam.look_at({ 0, 9.5f, -6.0f }, { 0, 0.1f, 0 });
flycam.set_camera(&cam);
timer.start();
}
shader_workbench::~shader_workbench() { timer.stop(); }
void shader_workbench::on_window_resize(int2 size) { }
void shader_workbench::on_input(const InputEvent & event)
{
igm->update_input(event);
flycam.handle_input(event);
if (event.type == InputEvent::KEY)
{
if (event.value[0] == GLFW_KEY_ESCAPE && event.action == GLFW_RELEASE) exit();
}
if (gizmo) gizmo->handle_input(event);
}
void shader_workbench::on_update(const UpdateEvent & e)
{
flycam.update(e.timestep_ms);
shaderMonitor.handle_recompile();
elapsedTime += e.timestep_ms;
lastUpdate = e;
pointEmitter.emit(*particleSystem.get());
cubeEmitter.emit(*particleSystem.get());
sphereEmitter.emit(*particleSystem.get());
planeEmitter.emit(*particleSystem.get());
circleEmitter.emit(*particleSystem.get());
}
void shader_workbench::on_draw()
{
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
int width, height;
glfwGetWindowSize(window, &width, &height);
glViewport(0, 0, width, height);
gpuTimer.start();
particleSystem->update(lastUpdate.timestep_ms, float3(0, -1, 0));
if (gizmo) gizmo->update(cam, float2(width, height));
// tinygizmo::transform_gizmo("destination", gizmo->gizmo_ctx, destination);
auto draw_scene = [this](const float3 & eye, const float4x4 & viewProjectionMatrix)
{
grid->draw(viewProjectionMatrix);
gl_check_error(__FILE__, __LINE__);
};
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // one-one, additive
float timeSeconds = timer.milliseconds().count() / 1000.f;
{
const float4x4 projectionMatrix = cam.get_projection_matrix(float(width) / float(height));
const float4x4 viewMatrix = cam.get_view_matrix();
const float4x4 viewProjectionMatrix = mul(projectionMatrix, viewMatrix);
glViewport(0, 0, width, height);
glClearColor(0.6f, 0.6f, 0.6f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
draw_scene(cam.get_eye_point(), viewProjectionMatrix);
particleSystem->draw(viewMatrix, projectionMatrix, particleShader, outerTex, innerTex, timeSeconds);
}
glDisable(GL_BLEND);
gpuTimer.stop();
igm->begin_frame();
ImGui::Text("Render Time %f ms", gpuTimer.elapsed_ms());
ImGui::Text("Global Time %f s", timeSeconds);
igm->end_frame();
if (gizmo) gizmo->draw();
gl_check_error(__FILE__, __LINE__);
glfwSwapBuffers(window);
}
IMPLEMENT_MAIN(int argc, char * argv[])
{
try
{
shader_workbench app;
app.main_loop();
}
catch (...)
{
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| 29.693878 | 161 | 0.659679 | ddiakopoulos |
369d083eda4a31a677eb9306b790174497cbbe4e | 1,117 | cpp | C++ | TCP1101 - Programming Fundamentals/Othello (Lame and Incomplete Version)/src/view/BannerView.cpp | jackwong95/MMURandomStuff | 6fa5e62528b29c173e2cf579f47f7f5a6d58120c | [
"Apache-2.0"
] | 3 | 2021-02-17T13:31:37.000Z | 2022-03-14T04:21:36.000Z | TCP1101 - Programming Fundamentals/Othello (Lame and Incomplete Version)/src/view/BannerView.cpp | jackwong95/MMURandomStuff | 6fa5e62528b29c173e2cf579f47f7f5a6d58120c | [
"Apache-2.0"
] | 1 | 2016-12-16T17:03:01.000Z | 2017-03-02T08:28:18.000Z | TCP1101 - Programming Fundamentals/Othello (Lame and Incomplete Version)/src/view/BannerView.cpp | jackwong95/MMURandomStuff | 6fa5e62528b29c173e2cf579f47f7f5a6d58120c | [
"Apache-2.0"
] | null | null | null | /**********|**********|**********|
Program: BannerView.cpp
Course: Degree In Computer Science - Game Development
Year: 2015/16 Trimester 1
Name: Wong Tiong Kiat
ID: 1132702943
Email: jackwongtiongkiat@gmail.com
Phone: 012-2321133
**********|**********|**********/
#include "BannerView.h"
//mini library I made
#include "Ultis.h"
//for system
#include <cstdlib>
//for exception handling
#include <stdexcept>
//for printing out
#include <iostream>
//for timer please dont kill me for the .h, this is built in library.. but i don't know why you need .h :3
#include <unistd.h>
//constructor of BannerView
BannerView::BannerView()
{
}
//print out starting banner
void BannerView::printView()
{
try
{
char str[] = {"Welcome to my game!"};
for(unsigned int i=0;i<sizeof(str)/sizeof(str[0]);i++) {
std::cout << str[i];
usleep(100000);
}
std::cout << "\n\n";
ultis::readAndPrint("assets/hypnotoad.txt");
system("PAUSE");
ultis::clearConsole();
}
catch(const std::exception& e)
{
std::cout << e.what() << "\n";
}
}
| 24.822222 | 106 | 0.593554 | jackwong95 |
36a4f5dda86073051037eaaf5fa0c696fde83c61 | 490 | cpp | C++ | Problems/Codeforces/CF-1200B.cpp | zhugezy/giggle | dfa50744a9fd328678b75af8135bbd770f18a6ac | [
"MIT"
] | 6 | 2019-10-12T15:14:10.000Z | 2020-02-02T11:16:00.000Z | Problems/Codeforces/CF-1200B.cpp | zhugezy/giggle | dfa50744a9fd328678b75af8135bbd770f18a6ac | [
"MIT"
] | 73 | 2019-10-11T15:09:40.000Z | 2020-09-15T07:49:24.000Z | Problems/Codeforces/CF-1200B.cpp | zhugezy/giggle | dfa50744a9fd328678b75af8135bbd770f18a6ac | [
"MIT"
] | 5 | 2019-10-14T02:57:39.000Z | 2020-06-19T09:38:34.000Z | // 1200B
#include <bits/stdc++.h>
using namespace std;
int T, n, m, k;
int h[110];
int main() {
cin >> T;
while (T--) {
cin >> n >> m >> k;
for (int i = 1; i <= n; ++i)
cin >> h[i];
bool flag = true;
for (int i = 1; i < n; ++i) {
int d = max(0, h[i + 1] - k);
if (d > h[i] + m) {
flag = false;
break;
}
m += h[i] - d;
}
if (flag)
cout << "YES" << endl;
else
cout << "NO" << endl;
}
return 0;
} | 16.333333 | 35 | 0.383673 | zhugezy |
36a51e425b65b047c00d28cc85167390e0ef0dcb | 9,244 | cpp | C++ | iptables/src/utils.cpp | trailofbits/osquery-extensions | 8a1a24a1142757579e001e4fa710e144169ab257 | [
"Apache-2.0"
] | 194 | 2017-12-14T14:00:34.000Z | 2022-03-21T23:56:06.000Z | iptables/src/utils.cpp | trailofbits/osquery-extensions | 8a1a24a1142757579e001e4fa710e144169ab257 | [
"Apache-2.0"
] | 49 | 2017-12-09T16:32:37.000Z | 2021-12-14T22:15:06.000Z | iptables/src/utils.cpp | trailofbits/osquery-extensions | 8a1a24a1142757579e001e4fa710e144169ab257 | [
"Apache-2.0"
] | 27 | 2017-12-14T23:48:39.000Z | 2022-02-25T01:54:45.000Z | /**
* Copyright (c) 2018 Trail of Bits, Inc.
*
* 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.
*
* Parts of this file are also:
*
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under both the Apache 2.0 license (found in the
* LICENSE file in the root directory of this source tree) and the GPLv2 (found
* in the COPYING file in the root directory of this source tree).
* You may select, at your option, one of the above-listed licenses.
*/
#include "utils.h"
#include <net/if.h>
#include <netdb.h>
#include <string>
#include <sys/socket.h>
#include <osquery/filesystem/filesystem.h>
#include <osquery/sdk/sdk.h>
#include <boost/algorithm/string/trim.hpp>
#include <trailofbits/extutils.h>
using namespace osquery;
namespace trailofbits {
static const std::string kIptablesSave = "/sbin/iptables-save";
static const std::string kIp6tablesSave = "/sbin/ip6tables-save";
static const std::string kIptablesNamesFile = "/proc/net/ip_tables_names";
static const std::string kIp6tablesNamesFile = "/proc/net/ip6_tables_names";
static const std::string kHexMap = "0123456789ABCDEF";
static const int kMaskHighBits = 4;
static const int kMaskLowBits = 15;
static TableList getTableNames(const std::string& filename) {
std::string content;
auto s = readFile(filename, content);
if (!s.ok()) {
TLOG << "Error reading: " << filename << ": " << s.toString();
return {};
}
auto results = SplitString(content, '\n');
for (auto& result : results) {
boost::algorithm::trim(result);
}
return results;
}
/* NOTE(ww): This function takes either iptables-save or ip6tables-save.
* It would be nice to use iptables-xml and ip6tables-xml, but ip6tables-xml
* doesn't exist yet and iptables-xml frequently hangs (during experimentation).
*/
Status genMatchMap(const std::string& ipt_cmd, MatchMap& match_map) {
ProcessOutput output;
if (!ExecuteProcess(output, ipt_cmd, {}) || output.exit_code != 0) {
return Status(1, "couldn't exec " + ipt_cmd);
}
if (output.std_output.empty()) {
return Status(1, "no output from command");
}
std::string table;
std::string chain;
for (const auto& line : SplitString(output.std_output, '\n')) {
std::string match;
std::string target;
std::string target_options;
// If the line is empty or a comment, skip it.
if (line.empty() || line.at(0) == '#') {
continue;
}
// If the line is a filter name, record it and prep our toplevel map with
// it.
if (line.at(0) == '*') {
table = line.substr(1);
match_map[table];
continue;
}
// If the line is a chain name, record it and prep our chain map with it.
if (line.at(0) == ':') {
auto stop = line.find(" ");
chain = line.substr(1, stop - 1);
match_map[table][chain];
continue;
}
// If the line is a rule, look for match entries, targets,
// and target options within it.
if (line.find("-A") == 0) {
auto start = line.find(" ");
auto stop = line.find(" ", start + 1);
chain = line.substr(start + 1, stop - start - 1);
// Matches begin with an -m.
start = line.find(" -m ");
// Targets begin with a -j or a -g.
stop = line.rfind(" -j ");
if (stop == std::string::npos) {
stop = line.rfind(" -g ");
}
// Match extraction.
if (start == std::string::npos) {
match = "";
} else {
if (stop != std::string::npos && stop < start) {
TLOG << "Oddity: -j or -g before -m: " << line;
match = "";
} else {
match = line.substr(start + 1, stop - start - 1);
}
}
// Target extraction.
if (stop == std::string::npos) {
target = "";
} else {
start = stop;
start = line.find(" ", start + 1);
stop = line.find(" ", start + 1);
target = line.substr(start + 1, stop - start - 1);
}
// Target option extraction.
if (stop == std::string::npos) {
target_options = "";
} else {
start = stop;
target_options = line.substr(start + 1);
}
match_map[table][chain].push_back(
std::make_tuple(match, target, target_options));
}
}
return Status(0);
}
TableColumns IptablesExtBase::columns() const {
return {
std::make_tuple("table_name", TEXT_TYPE, ColumnOptions::DEFAULT),
std::make_tuple("chain", TEXT_TYPE, ColumnOptions::DEFAULT),
std::make_tuple("ruleno", INTEGER_TYPE, ColumnOptions::DEFAULT),
std::make_tuple("target", TEXT_TYPE, ColumnOptions::DEFAULT),
std::make_tuple("target_options", TEXT_TYPE, ColumnOptions::DEFAULT),
std::make_tuple("match", TEXT_TYPE, ColumnOptions::DEFAULT),
std::make_tuple("protocol", TEXT_TYPE, ColumnOptions::DEFAULT),
std::make_tuple("src_port", TEXT_TYPE, ColumnOptions::DEFAULT),
std::make_tuple("dst_port", TEXT_TYPE, ColumnOptions::DEFAULT),
std::make_tuple("src_ip", TEXT_TYPE, ColumnOptions::DEFAULT),
std::make_tuple("src_mask", TEXT_TYPE, ColumnOptions::DEFAULT),
std::make_tuple("iniface", TEXT_TYPE, ColumnOptions::DEFAULT),
std::make_tuple("iniface_mask", TEXT_TYPE, ColumnOptions::DEFAULT),
std::make_tuple("dst_ip", TEXT_TYPE, ColumnOptions::DEFAULT),
std::make_tuple("dst_mask", TEXT_TYPE, ColumnOptions::DEFAULT),
std::make_tuple("outiface", TEXT_TYPE, ColumnOptions::DEFAULT),
std::make_tuple("outiface_mask", TEXT_TYPE, ColumnOptions::DEFAULT),
std::make_tuple("packets", BIGINT_TYPE, ColumnOptions::DEFAULT),
std::make_tuple("bytes", BIGINT_TYPE, ColumnOptions::DEFAULT),
};
}
void IptablesExtBase::parseProtoMatch(const xt_entry_match* match,
DynamicTableRowHolder& row) {
std::string match_name(match->u.user.name);
// NOTE(ww): ICMP can also appear here, but there's no point in handling
// it -- it doesn't have any ports to parse.
if (match_name == "tcp") {
parseTcp(match, row);
} else if (match_name == "udp") {
parseUdp(match, row);
}
}
TableColumns IptablesPoliciesBase::columns() const {
return {
std::make_tuple("table_name", TEXT_TYPE, ColumnOptions::DEFAULT),
std::make_tuple("chain", TEXT_TYPE, ColumnOptions::DEFAULT),
std::make_tuple("policy", TEXT_TYPE, ColumnOptions::DEFAULT),
std::make_tuple("packets", BIGINT_TYPE, ColumnOptions::DEFAULT),
std::make_tuple("bytes", BIGINT_TYPE, ColumnOptions::DEFAULT),
};
}
Status parseIptablesSave(MatchMap& match_map) {
return genMatchMap(kIptablesSave, match_map);
}
Status parseIp6tablesSave(MatchMap& match_map) {
return genMatchMap(kIp6tablesSave, match_map);
}
TableList getIptablesNames(void) {
return getTableNames(kIptablesNamesFile);
}
TableList getIp6tablesNames(void) {
return getTableNames(kIp6tablesNamesFile);
}
std::string ipAsString(const sockaddr* in) {
char dst[INET6_ADDRSTRLEN] = {0};
socklen_t addrlen =
in->sa_family == AF_INET ? sizeof(sockaddr_in) : sizeof(sockaddr_in6);
if (getnameinfo(in, addrlen, dst, sizeof(dst), nullptr, 0, NI_NUMERICHOST) !=
0) {
return "";
}
std::string address(dst);
boost::algorithm::trim(address);
return address;
}
std::string ipAsString(const in_addr* in) {
sockaddr_in addr;
addr.sin_addr = *in;
addr.sin_family = AF_INET;
addr.sin_port = 0;
return ipAsString(reinterpret_cast<sockaddr*>(&addr));
}
std::string ipAsString(const in6_addr* in) {
sockaddr_in6 addr;
addr.sin6_addr = *in;
addr.sin6_family = AF_INET6;
addr.sin6_port = 0;
addr.sin6_scope_id = 0;
return ipAsString(reinterpret_cast<sockaddr*>(&addr));
}
std::string ipMaskAsString(const in_addr* in) {
return ipAsString(in);
}
std::string ipMaskAsString(const in6_addr* in) {
std::string mask_str = "";
char aux_char[2] = {0};
unsigned int ncol = 0;
for (int i = 0; i < 16; i++) {
aux_char[0] = kHexMap[in->s6_addr[i] >> kMaskHighBits];
aux_char[1] = kHexMap[in->s6_addr[i] & kMaskLowBits];
mask_str += aux_char[0];
mask_str += aux_char[1];
if ((mask_str.size() - ncol) % 4 == 0) {
mask_str += ":";
ncol++;
}
}
if (mask_str.back() == ':') {
mask_str.pop_back();
}
return mask_str;
}
std::string ifaceMaskAsString(const unsigned char* iface) {
std::string iface_str = "";
char aux_char[2] = {0};
for (int i = 0; i < IFNAMSIZ && iface[i] != 0x00; i++) {
aux_char[0] = kHexMap[iface[i] >> kMaskHighBits];
aux_char[1] = kHexMap[iface[i] & kMaskLowBits];
iface_str += aux_char[0];
iface_str += aux_char[1];
}
return iface_str;
}
} // namespace trailofbits
| 29.628205 | 80 | 0.647555 | trailofbits |
36a83aaff28ec757cbd9c64c6fa654f605a947b6 | 23,645 | cc | C++ | master/kismet-2018-08-BETA1/kismet-2018-08-BETA1/legacy_code/kis_netframe.cc | AlexRogalskiy/DevArtifacts | 931aabb8cbf27656151c54856eb2ea7d1153203a | [
"MIT"
] | 4 | 2018-09-07T15:35:24.000Z | 2019-03-27T09:48:12.000Z | master/kismet-2018-08-BETA1/kismet-2018-08-BETA1/legacy_code/kis_netframe.cc | AlexRogalskiy/DevArtifacts | 931aabb8cbf27656151c54856eb2ea7d1153203a | [
"MIT"
] | 371 | 2020-03-04T21:51:56.000Z | 2022-03-31T20:59:11.000Z | master/kismet-2018-08-BETA1/kismet-2018-08-BETA1/legacy_code/kis_netframe.cc | AlexRogalskiy/DevArtifacts | 931aabb8cbf27656151c54856eb2ea7d1153203a | [
"MIT"
] | 3 | 2019-06-18T19:57:17.000Z | 2020-11-06T03:55:08.000Z | /*
This file is part of Kismet
Kismet 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.
Kismet 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 Kismet; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "config.h"
#include "util.h"
#include "configfile.h"
#include "packet.h"
#include "packetsourcetracker.h"
#include "packetchain.h"
#include "kis_netframe.h"
#include "tcpserver.h"
#include "getopt.h"
#include "dumpfile.h"
#include "phy_80211.h"
void KisNetframe_MessageClient::ProcessMessage(string in_msg, int in_flags) {
// Local messages and alerts don't go out to the world. Alerts are sent via
// the ALERT protocol.
if ((in_flags & MSGFLAG_LOCAL) || (in_flags & MSGFLAG_ALERT))
return;
STATUS_data sdata;
sdata.text = in_msg;
sdata.flags = in_flags;
// Dispatch it out to the clients
((KisNetFramework *) auxptr)->SendToAll(_NPM(PROTO_REF_STATUS), (void *) &sdata);
}
int KisNetFrame_TimeEvent(Timetracker::timer_event *evt, void *parm,
GlobalRegistry *globalreg) {
// We'll just assume we'll never fail here and that the TIME protocol
// always exists. If this isn't the case, we'll fail horribly.
time_t curtime = time(0);
globalreg->kisnetserver->SendToAll(globalreg->netproto_map[PROTO_REF_TIME],
(void *) &curtime);
return 1;
}
KisNetFramework::KisNetFramework() {
fprintf(stderr, "FATAL OOPS: KisNetFramework() called with no globalreg\n");
exit(1);
}
void KisNetFramework::Usage(char *name) {
printf(" *** Kismet Client/Server Options ***\n");
printf(" -l, --server-listen Override Kismet server listen options\n");
}
KisNetFramework::KisNetFramework(GlobalRegistry *in_globalreg) {
globalreg = in_globalreg;
netserver = NULL;
int port = 0, maxcli = 0;
char srv_proto[11], srv_bindhost[129];
TcpServer *tcpsrv;
string listenline;
next_netprotoref = 0;
valid = 0;
// Sanity check for timetracker
if (globalreg->timetracker == NULL) {
fprintf(stderr, "FATAL OOPS: KisNetFramework called without timetracker\n");
exit(1);
}
if (globalreg->kismet_config == NULL) {
fprintf(stderr, "FATAL OOPS: KisNetFramework called without kismet_config\n");
exit(1);
}
if (globalreg->messagebus == NULL) {
fprintf(stderr, "FATAL OOPS: KisNetFramework called without messagebus\n");
exit(1);
}
// Commandline stuff
static struct option netframe_long_options[] = {
{ "server-listen", required_argument, 0, 'l' },
{ 0, 0, 0, 0 }
};
int option_idx = 0;
// Hack the extern getopt index
optind = 0;
while (1) {
int r = getopt_long(globalreg->argc, globalreg->argv,
"-l:",
netframe_long_options, &option_idx);
if (r < 0) break;
switch (r) {
case 'l':
listenline = string(optarg);
break;
}
}
// Parse the config file and get the protocol and port info... ah, abusing
// evaluation shortcuts
if (listenline.length() == 0 &&
(listenline = globalreg->kismet_config->FetchOpt("listen")) == "") {
_MSG("No 'listen' config line defined for the Kismet UI server; This "
"usually means you have not upgraded your Kismet config file. Copy "
"the config file from the source directory and replace your "
"current kismet.conf (Or specify the new config file manually)",
MSGFLAG_FATAL);
globalreg->fatal_condition = 1;
return;
}
if (sscanf(listenline.c_str(),
"%10[^:]://%128[^:]:%d", srv_proto, srv_bindhost, &port) != 3) {
_MSG("Malformed 'listen' config line defined for the Kismet UI server",
MSGFLAG_FATAL);
globalreg->fatal_condition = 1;
return;
}
if (globalreg->kismet_config->FetchOpt("maxclients") == "") {
_MSG("No 'maxclients' config line defined for the Kismet UI server, "
"defaulting to 5 clients.", MSGFLAG_INFO);
maxcli = 5;
} else if (sscanf(globalreg->kismet_config->FetchOpt("maxclients").c_str(),
"%d", &maxcli) != 1) {
_MSG("Malformed 'maxclients' config line defined for the Kismet UI server",
MSGFLAG_FATAL);
globalreg->fatal_condition = 1;
return;
}
if (globalreg->kismet_config->FetchOpt("maxbacklog") == "") {
_MSG("No 'maxbacklog' config line defined for the Kismet UI server, "
"defaulting to 5000 lines", MSGFLAG_INFO);
maxbacklog = 5000;
} else if (sscanf(globalreg->kismet_config->FetchOpt("maxbacklog").c_str(),
"%d", &maxbacklog) != 1) {
_MSG("Malformed 'maxbacklog' config line defined for the Kismet UI server",
MSGFLAG_FATAL);
globalreg->fatal_condition = 1;
return;
}
if (globalreg->kismet_config->FetchOpt("allowedhosts") == "") {
_MSG("No 'allowedhosts' config line defined for the Kismet UI server",
MSGFLAG_FATAL);
globalreg->fatal_condition = 1;
return;
}
// We only know how to set up a tcp server right now
if (strncasecmp(srv_proto, "tcp", 4) == 0) {
tcpsrv = new TcpServer(globalreg);
// Expand the ring buffer size
tcpsrv->SetRingSize(100000);
tcpsrv->SetupServer(port, maxcli, srv_bindhost,
globalreg->kismet_config->FetchOpt("allowedhosts"));
netserver = tcpsrv;
server_type = 0;
} else {
server_type = -1;
_MSG("Invalid protocol in 'listen' config line for the Kismet UI server",
MSGFLAG_FATAL);
globalreg->fatal_condition = 1;
return;
}
// Register the core Kismet protocols
// Other protocols
valid = 1;
}
int KisNetFramework::Activate() {
if (server_type != 0) {
_MSG("KisNetFramework unknown server type, something didn't initialize",
MSGFLAG_FATAL);
globalreg->fatal_condition = 1;
return -1;
}
if (netserver->EnableServer() < 0 || globalreg->fatal_condition) {
_MSG("Failed to enable TCP listener for the Kismet UI server",
MSGFLAG_FATAL);
globalreg->fatal_condition = 1;
return -1;
}
netserver->RegisterServerFramework(this);
return 1;
}
KisNetFramework::~KisNetFramework() {
// Remove our message handler
globalreg->messagebus->RemoveClient(kisnet_msgcli);
}
int KisNetFramework::Accept(int in_fd) {
// Create their options
client_opt *opt = new client_opt;
client_optmap[in_fd] = opt;
char temp[512];
// Set the mandatory sentences. We don't have to do error checking here because
// it can't exist in the required vector if it isn't registered.
for (unsigned int reqprot = 0; reqprot < required_protocols.size(); reqprot++) {
int tref = required_protocols[reqprot];
vector<int> reqfields;
map<int, server_protocol *>::iterator spitr = protocol_map.find(tref);
for (unsigned int fnum = 0; fnum < spitr->second->field_vec.size(); fnum++) {
reqfields.push_back(fnum);
}
AddProtocolClient(in_fd, tref, reqfields);
}
// Send the mandatory stuff like the Kismet info
KISMET_data kdat;
kdat.version = "0.0.0";
snprintf(temp, 512, "%u", (unsigned int) globalreg->start_time);
kdat.starttime = string(temp);
kdat.servername = globalreg->servername;
kdat.timestamp = "0";
kdat.newversion = globalreg->version_major + string(",") +
globalreg->version_minor + string(",") +
globalreg->version_tiny;
kdat.uid = geteuid();
SendToClient(in_fd, globalreg->netproto_map[PROTO_REF_KISMET],
(void *) &kdat, NULL);
// Protocols
SendToClient(in_fd, globalreg->netproto_map[PROTO_REF_PROTOCOL],
(void *) &protocol_map, NULL);
_MSG("Kismet server accepted connection from " +
netserver->GetRemoteAddr(in_fd), MSGFLAG_INFO);
return 1;
}
int KisNetFramework::BufferDrained(int in_fd) {
map<int, client_opt *>::iterator opitr = client_optmap.find(in_fd);
if (opitr == client_optmap.end()) {
snprintf(errstr, 1024, "KisNetFramework::SendToClient illegal client %d.",
in_fd);
globalreg->messagebus->InjectMessage(errstr, MSGFLAG_ERROR);
return -1;
}
client_opt *opt = opitr->second;
int ret = 0;
if (opt->backlog.size() == 0)
return 0;
while (opt->backlog.size() > 0) {
string outtext = opt->backlog[0];
ret = netserver->WriteData(in_fd, (uint8_t *) outtext.c_str(),
outtext.length());
// Catch "full buffer" error and stop trying to shove more down it
if (ret == -2)
return 0;
if (ret < 0)
return ret;
opt->backlog.erase(opt->backlog.begin());
if (opt->backlog.size() == 0) {
snprintf(errstr, 1024, "Flushed protocol data backlog for Kismet "
"client %d", in_fd);
_MSG(errstr, (MSGFLAG_LOCAL | MSGFLAG_ERROR));
}
}
return 1;
}
int KisNetFramework::ParseData(int in_fd) {
int len, rlen;
char *buf;
string strbuf;
len = netserver->FetchReadLen(in_fd);
buf = new char[len + 1];
if (netserver->ReadData(in_fd, buf, len, &rlen) < 0) {
globalreg->messagebus->InjectMessage("KisNetFramework::ParseData failed to "
"fetch data from the client.",
MSGFLAG_ERROR);
delete[] buf;
return -1;
}
buf[len] = '\0';
// Parse without including partials, so we don't get a fragmented command
// out of the buffer
vector<string> inptok = StrTokenize(buf, "\n", 0);
delete[] buf;
// Bail on no useful data
if (inptok.size() < 1) {
return 0;
}
for (unsigned int it = 0; it < inptok.size(); it++) {
// No matter what we've dealt with this data block
netserver->MarkRead(in_fd, inptok[it].length() + 1);
// Handle funny trailing stuff from telnet and some other clients
if (inptok[it][inptok[it].length() - 1] == '\r') {
inptok[it] = inptok[it].substr(0, inptok[it].length() - 1);
}
vector<smart_word_token> cmdtoks = NetStrTokenize(inptok[it], " ");
if (cmdtoks.size() < 2) {
// Silently fail since there wasn't enough to deal with it
continue;
}
int cmdid;
if (sscanf(cmdtoks[0].word.c_str(), "!%d", &cmdid) != 1) {
// Silently fail if we can't figure out how to generate the error, again
continue;
}
// Nuke the first element of the command tokens (we just pulled it off to
// get the cmdid)
cmdtoks.erase(cmdtoks.begin());
// Find a command function to deal with this protocol
CLIRESP_data rdat;
rdat.cmdid = cmdid;
map<string, KisNetFramework::client_command_rec *>::iterator ccitr =
client_cmd_map.find(StrLower(cmdtoks[0].word));
if (ccitr != client_cmd_map.end()) {
// Nuke the first word again - we just pulled it off to get the command
// fprintf(stderr, "debug - ctoks '%s' %u %u %u\n", cmdtoks[0].word.c_str(), cmdtoks.size(), cmdtoks[0].end, inptok[it].length());
cmdtoks.erase(cmdtoks.begin());
// fprintf(stderr, "debug - fullcmd '%s' %u %u %u\n", cmdtoks[0].word.c_str(), cmdtoks.size(), cmdtoks[0].end, inptok[it].length());
string fullcmd =
inptok[it].substr(cmdtoks[0].end, (inptok[it].length() -
cmdtoks[0].end));
// Call the processor and return error conditions and ack
if ((*ccitr->second->cmd)
(in_fd, this, globalreg, errstr, fullcmd, &cmdtoks,
ccitr->second->auxptr) < 0) {
rdat.resptext = string(errstr);
SendToClient(in_fd, globalreg->netproto_map[PROTO_REF_ERROR],
(void *) &rdat, NULL);
_MSG("Failed Kismet client command: " + rdat.resptext, MSGFLAG_ERROR);
} else {
rdat.resptext = string("OK");
SendToClient(in_fd, globalreg->netproto_map[PROTO_REF_ACK],
(void *) &rdat, NULL);
}
} else {
rdat.resptext = string("NO SUCH COMMAND");
SendToClient(in_fd, globalreg->netproto_map[PROTO_REF_ERROR],
(void *) &rdat, NULL);
}
}
return 1;
}
int KisNetFramework::KillConnection(int in_fd) {
// Do a little testing here since we might not have an opt record
map<int, client_opt *>::iterator citr = client_optmap.find(in_fd);
if (citr != client_optmap.end()) {
// Remove all our protocols
map<int, vector<int> >::iterator clpitr;
while ((clpitr = citr->second->protocols.begin()) !=
citr->second->protocols.end()) {
DelProtocolClient(in_fd, clpitr->first);
}
/*
for (map<int, vector<int> >::iterator clpitr =
citr->second->protocols.begin();
clpitr != citr->second->protocols.end(); ++clpitr)
DelProtocolClient(in_fd, clpitr->first);
*/
client_opt *sec = citr->second;
client_optmap.erase(citr);
delete sec;
}
return 1;
}
int KisNetFramework::Shutdown() {
return ServerFramework::Shutdown();
}
int KisNetFramework::RegisterClientCommand(string in_cmdword, ClientCommand in_cmd,
void *in_auxptr) {
string lcmd = StrLower(in_cmdword);
if (in_cmdword.length() > 16) {
snprintf(errstr, 1024, "KisNetFramework::RegisterClientCommand refusing to "
"register '%s' as it is greater than 16 characters.",
in_cmdword.c_str());
globalreg->messagebus->InjectMessage(errstr, MSGFLAG_ERROR);
return -1;
}
if (client_cmd_map.find(lcmd) != client_cmd_map.end()) {
snprintf(errstr, 1024, "KisNetFramework::RegisterClientCommand refusing to "
"register command '%s', command already exists.", lcmd.c_str());
globalreg->messagebus->InjectMessage(errstr, MSGFLAG_ERROR);
return -1;
}
client_command_rec *cmdrec = new client_command_rec;
cmdrec->cmd = in_cmd;
cmdrec->auxptr = in_auxptr;
client_cmd_map[lcmd] = cmdrec;
return 1;
}
int KisNetFramework::RemoveClientCommand(string in_cmdword) {
if (client_cmd_map.find(in_cmdword) == client_cmd_map.end())
return 0;
delete client_cmd_map[in_cmdword];
client_cmd_map.erase(in_cmdword);
return 1;
}
// Create an output string based on the clients
// This looks very complex - and it is - but almost all of the "big" ops like
// find are done with integer references. They're cheap.
// This takes the struct to be sent and pumps it through the dynamic protocol/field
// system.
int KisNetFramework::SendToClient(int in_fd, int in_refnum, const void *in_data,
kis_protocol_cache *in_cache) {
// Make sure this is a valid client
map<int, client_opt *>::iterator opitr = client_optmap.find(in_fd);
if (opitr == client_optmap.end()) {
snprintf(errstr, 1024, "KisNetFramework::SendToClient illegal client %d.",
in_fd);
globalreg->messagebus->InjectMessage(errstr, MSGFLAG_ERROR);
return -1;
}
client_opt *opt = opitr->second;
// See if this client even handles this protocol...
map<int, vector<int> >::iterator clprotitr = opt->protocols.find(in_refnum);
if (clprotitr == opt->protocols.end())
return 0;
const vector<int> *fieldlist = &clprotitr->second;
// Find this protocol now - we only do this after we're sure we want to print to
// it.
map<int, server_protocol *>::iterator spitr = protocol_map.find(in_refnum);
if (spitr == protocol_map.end()) {
snprintf(errstr, 1024, "KisNetFramework::SendToClient Protocol %d not "
"registered.", in_refnum);
globalreg->messagebus->InjectMessage(errstr, MSGFLAG_ERROR);
return -1;
}
server_protocol *prot = spitr->second;
if (prot->cacheable && in_cache == NULL) {
snprintf(errstr, 1024, "KisNetFramework::SendToClient protocol %s "
"requires caching but got a NULL cache ref, fix me",
prot->header.c_str());
globalreg->messagebus->InjectMessage(errstr, MSGFLAG_ERROR);
return -1;
}
// Bounce through the printer function
string fieldtext;
if ((*prot->printer)(fieldtext, fieldlist, in_data, prot->auxptr,
in_cache, globalreg) == -1) {
snprintf(errstr, 1024, "%s", fieldtext.c_str());
return -1;
}
// Assemble a line for them:
// *HEADER: DATA\n
// 16 x 1
int ret = 0;
// Check the size
int blogsz = opt->backlog.size();
// Bail gracefully for now
if (blogsz >= maxbacklog) {
return 0;
}
int nlen = prot->header.length() + fieldtext.length() + 5; // *..: \n\0
char *outtext = new char[nlen];
snprintf(outtext, nlen, "*%s: %s\n", prot->header.c_str(), fieldtext.c_str());
// Look in the backlog vector and backlog it if we're already over-full
if (blogsz > 0) {
opt->backlog.push_back(outtext);
delete[] outtext;
return 0;
}
ret = netserver->WriteData(in_fd, (uint8_t *) outtext, strlen(outtext));
// Catch "full buffer" error
if (ret == -2) {
snprintf(errstr, 1024, "Client %d ring buffer full, storing Kismet protocol "
"data in backlog vector", in_fd);
_MSG(errstr, (MSGFLAG_LOCAL | MSGFLAG_INFO));
opt->backlog.push_back(outtext);
delete[] outtext;
return 0;
}
delete[] outtext;
if (ret < 0)
return ret;
return nlen;
}
int KisNetFramework::SendToAll(int in_refnum, const void *in_data) {
vector<int> clvec;
int nsent = 0;
if (netserver == NULL)
return 0;
kis_protocol_cache cache;
netserver->FetchClientVector(&clvec);
for (unsigned int x = 0; x < clvec.size(); x++) {
if (SendToClient(clvec[x], in_refnum, in_data, &cache) > 0)
nsent++;
}
return nsent;
}
int KisNetFramework::RegisterProtocol(string in_header, int in_required, int in_cache,
const char **in_fields,
int (*in_printer)(PROTO_PARMS),
void (*in_enable)(PROTO_ENABLE_PARMS),
void *in_auxdata) {
// First, see if we're already registered and return a -1 if we are. You can't
// register a protocol twice.
if (FetchProtocolRef(in_header) != -1) {
snprintf(errstr, 1024, "KisNetFramework::RegisterProtocol refusing to "
"register '%s' as it is already a registered protocol.",
in_header.c_str());
globalreg->messagebus->InjectMessage(errstr, MSGFLAG_ERROR);
return -1;
}
if (in_header.length() > 16) {
snprintf(errstr, 1024, "KisNetFramework::RegisterProtocol refusing to "
"register '%s' as it is greater than 16 characters.",
in_header.c_str());
globalreg->messagebus->InjectMessage(errstr, MSGFLAG_ERROR);
return -1;
}
int refnum = next_netprotoref++;
server_protocol *sen = new server_protocol;
sen->ref_index = refnum;
sen->header = in_header;
int x = 0;
while (in_fields[x] != NULL) {
sen->field_map[in_fields[x]] = x;
sen->field_vec.push_back(in_fields[x]);
x++;
}
sen->printer = in_printer;
sen->enable = in_enable;
sen->required = in_required;
sen->cacheable = in_cache;
sen->auxptr = in_auxdata;
// Put us in the map
protocol_map[refnum] = sen;
ref_map[StrLower(in_header)] = refnum;
if (in_required)
required_protocols.push_back(refnum);
return refnum;
}
int KisNetFramework::RemoveProtocol(int in_protoref) {
// Efficiency isn't the biggest deal here since it happens rarely
if (in_protoref < 0)
return 0;
if (protocol_map.find(in_protoref) == protocol_map.end())
return 0;
string cmdheader = protocol_map[in_protoref]->header;
delete protocol_map[in_protoref];
protocol_map.erase(in_protoref);
ref_map.erase(cmdheader);
for (unsigned int x = 0; x < required_protocols.size(); x++) {
if (required_protocols[x] == in_protoref) {
required_protocols.erase(required_protocols.begin() + x);
break;
}
}
return 1;
}
int KisNetFramework::FetchProtocolRef(string in_header) {
map<string, int>::iterator rmitr = ref_map.find(StrLower(in_header));
if (rmitr == ref_map.end())
return -1;
return rmitr->second;
}
KisNetFramework::server_protocol *KisNetFramework::FetchProtocol(int in_ref) {
KisNetFramework::server_protocol *ret = NULL;
map<int, KisNetFramework::server_protocol *>::iterator spi =
protocol_map.find(in_ref);
if (spi != protocol_map.end())
ret = spi->second;
return ret;
}
int KisNetFramework::FetchNumClientRefs(int in_refnum) {
map<int, int>::iterator cmpitr = client_mapped_protocols.find(in_refnum);
if (cmpitr != client_mapped_protocols.end())
return cmpitr->second;
return 0;
}
int KisNetFramework::FetchNumClients() {
return netserver->FetchNumClients();
}
void KisNetFramework::AddProtocolClient(int in_fd, int in_refnum, vector<int> in_fields) {
map<int, client_opt *>::iterator citr = client_optmap.find(in_fd);
if (citr == client_optmap.end()) {
return;
}
// Find out if it already exists and increment the use count if it does
map<int, vector<int> >::iterator clpitr = citr->second->protocols.find(in_refnum);
if (clpitr == citr->second->protocols.end())
client_mapped_protocols[in_refnum]++;
citr->second->protocols[in_refnum] = in_fields;
}
void KisNetFramework::DelProtocolClient(int in_fd, int in_refnum) {
map<int, client_opt *>::iterator citr = client_optmap.find(in_fd);
if (citr == client_optmap.end())
return;
map<int, vector<int> >::iterator clpitr = citr->second->protocols.find(in_refnum);
if (clpitr != citr->second->protocols.end()) {
citr->second->protocols.erase(clpitr);
client_mapped_protocols[in_refnum]--;
}
}
| 33.255977 | 144 | 0.602326 | AlexRogalskiy |
36a87e6e8147da72f3f3322e2eb701f5a59f668d | 7,606 | cpp | C++ | artifact/storm/src/storm/transformer/MemoryIncorporation.cpp | glatteis/tacas21-artifact | 30b4f522bd3bdb4bebccbfae93f19851084a3db5 | [
"MIT"
] | null | null | null | artifact/storm/src/storm/transformer/MemoryIncorporation.cpp | glatteis/tacas21-artifact | 30b4f522bd3bdb4bebccbfae93f19851084a3db5 | [
"MIT"
] | null | null | null | artifact/storm/src/storm/transformer/MemoryIncorporation.cpp | glatteis/tacas21-artifact | 30b4f522bd3bdb4bebccbfae93f19851084a3db5 | [
"MIT"
] | 1 | 2022-02-05T12:39:53.000Z | 2022-02-05T12:39:53.000Z | #include "MemoryIncorporation.h"
#include "storm/models/sparse/Mdp.h"
#include "storm/models/sparse/MarkovAutomaton.h"
#include "storm/models/sparse/StandardRewardModel.h"
#include "storm/storage/memorystructure/MemoryStructureBuilder.h"
#include "storm/storage/memorystructure/NondeterministicMemoryStructureBuilder.h"
#include "storm/storage/memorystructure/SparseModelMemoryProduct.h"
#include "storm/storage/memorystructure/SparseModelNondeterministicMemoryProduct.h"
#include "storm/logic/Formulas.h"
#include "storm/logic/FragmentSpecification.h"
#include "storm/modelchecker/propositional/SparsePropositionalModelChecker.h"
#include "storm/modelchecker/results/ExplicitQualitativeCheckResult.h"
#include "storm/utility/macros.h"
#include "storm/exceptions/NotImplementedException.h"
#include "storm/exceptions/NotSupportedException.h"
namespace storm {
namespace transformer {
template <class SparseModelType>
storm::storage::MemoryStructure getGoalMemory(SparseModelType const& model, storm::logic::Formula const& propositionalGoalStateFormula) {
STORM_LOG_THROW(propositionalGoalStateFormula.isInFragment(storm::logic::propositional()), storm::exceptions::NotSupportedException, "The subformula " << propositionalGoalStateFormula << " should be propositional.");
storm::modelchecker::SparsePropositionalModelChecker<SparseModelType> mc(model);
storm::storage::BitVector goalStates = mc.check(propositionalGoalStateFormula)->asExplicitQualitativeCheckResult().getTruthValuesVector();
// Check if the formula is already satisfied for all initial states. In such a case the trivial memory structure suffices.
if (model.getInitialStates().isSubsetOf(goalStates)) {
STORM_LOG_INFO("One objective is already satisfied for all initial states.");
return storm::storage::MemoryStructureBuilder<typename SparseModelType::ValueType, typename SparseModelType::RewardModelType>::buildTrivialMemoryStructure(model);
}
// Create a memory structure that stores whether a goal state has already been reached
storm::storage::MemoryStructureBuilder<typename SparseModelType::ValueType, typename SparseModelType::RewardModelType> builder(2, model);
builder.setTransition(0, 0, ~goalStates);
builder.setTransition(0, 1, goalStates);
builder.setTransition(1, 1, storm::storage::BitVector(model.getNumberOfStates(), true));
for (auto const& initState : model.getInitialStates()) {
builder.setInitialMemoryState(initState, goalStates.get(initState) ? 1 : 0);
}
return builder.build();
}
template <class SparseModelType>
storm::storage::MemoryStructure getUntilFormulaMemory(SparseModelType const& model, storm::logic::Formula const& leftSubFormula, storm::logic::Formula const& rightSubFormula) {
auto notLeftOrRight = std::make_shared<storm::logic::BinaryBooleanStateFormula>(storm::logic::BinaryBooleanStateFormula::OperatorType::Or,
std::make_shared<storm::logic::UnaryBooleanStateFormula>(storm::logic::UnaryBooleanStateFormula::OperatorType::Not, leftSubFormula.asSharedPointer()),
rightSubFormula.asSharedPointer());
return getGoalMemory<SparseModelType>(model, *notLeftOrRight);
}
template <class SparseModelType>
std::shared_ptr<SparseModelType> MemoryIncorporation<SparseModelType>::incorporateGoalMemory(SparseModelType const& model, std::vector<std::shared_ptr<storm::logic::Formula const>> const& formulas) {
storm::storage::MemoryStructure memory = storm::storage::MemoryStructureBuilder<ValueType, RewardModelType>::buildTrivialMemoryStructure(model);
for (auto const& subFormula : formulas) {
STORM_LOG_THROW(subFormula->isOperatorFormula(), storm::exceptions::NotSupportedException, "The given Formula " << *subFormula << " is not supported.");
auto const& subsubFormula = subFormula->asOperatorFormula().getSubformula();
if (subsubFormula.isEventuallyFormula()) {
memory = memory.product(getGoalMemory(model, subsubFormula.asEventuallyFormula().getSubformula()));
} else if (subsubFormula.isUntilFormula()) {
memory = memory.product(getUntilFormulaMemory(model, subsubFormula.asUntilFormula().getLeftSubformula(), subsubFormula.asUntilFormula().getRightSubformula()));
} else if (subsubFormula.isBoundedUntilFormula()) {
// For bounded formulas it is only reasonable to add the goal memory if it considers a single upper step/time bound.
auto const& buf = subsubFormula.asBoundedUntilFormula();
if (!buf.isMultiDimensional() && !buf.getTimeBoundReference().isRewardBound() && (!buf.hasLowerBound() || (!buf.isLowerBoundStrict() && storm::utility::isZero(buf.template getLowerBound<storm::RationalNumber>())))) {
memory = memory.product(getUntilFormulaMemory(model, buf.getLeftSubformula(), buf.getRightSubformula()));
}
} else if (subsubFormula.isGloballyFormula()) {
auto notPhi = std::make_shared<storm::logic::UnaryBooleanStateFormula>(storm::logic::UnaryBooleanStateFormula::OperatorType::Not, subsubFormula.asGloballyFormula().getSubformula().asSharedPointer());
memory = memory.product(getGoalMemory(model, *notPhi));
} else {
STORM_LOG_THROW(subsubFormula.isTotalRewardFormula() || subsubFormula.isCumulativeRewardFormula(), storm::exceptions::NotSupportedException, "The given Formula " << subsubFormula << " is not supported.");
}
}
storm::storage::SparseModelMemoryProduct<ValueType> product = memory.product(model);
return std::dynamic_pointer_cast<SparseModelType>(product.build());
}
template <class SparseModelType>
std::shared_ptr<SparseModelType> MemoryIncorporation<SparseModelType>::incorporateFullMemory(SparseModelType const& model, uint64_t memoryStates) {
auto memory = storm::storage::NondeterministicMemoryStructureBuilder().build(storm::storage::NondeterministicMemoryStructurePattern::Full, memoryStates);
return storm::storage::SparseModelNondeterministicMemoryProduct<SparseModelType>(model, memory).build();
}
template <class SparseModelType>
std::shared_ptr<SparseModelType> MemoryIncorporation<SparseModelType>::incorporateCountingMemory(SparseModelType const& model, uint64_t memoryStates) {
auto memory = storm::storage::NondeterministicMemoryStructureBuilder().build(storm::storage::NondeterministicMemoryStructurePattern::SelectiveCounter, memoryStates);
return storm::storage::SparseModelNondeterministicMemoryProduct<SparseModelType>(model, memory).build();
}
template class MemoryIncorporation<storm::models::sparse::Mdp<double>>;
template class MemoryIncorporation<storm::models::sparse::MarkovAutomaton<double>>;
template class MemoryIncorporation<storm::models::sparse::Mdp<storm::RationalNumber>>;
template class MemoryIncorporation<storm::models::sparse::MarkovAutomaton<storm::RationalNumber>>;
}
}
| 71.084112 | 236 | 0.705233 | glatteis |
36ac700a1898833842a0f452688ae8ae2a38a2e7 | 1,182 | cpp | C++ | DSP/extensions/WindowFunctionLib/source/TTHanningWindow.cpp | avilleret/JamomaCore | b09cfb684527980f30845f664e1f922005c24e60 | [
"BSD-3-Clause"
] | 31 | 2015-02-28T23:51:10.000Z | 2021-12-25T04:16:01.000Z | DSP/extensions/WindowFunctionLib/source/TTHanningWindow.cpp | avilleret/JamomaCore | b09cfb684527980f30845f664e1f922005c24e60 | [
"BSD-3-Clause"
] | 126 | 2015-01-01T13:42:05.000Z | 2021-07-13T14:11:42.000Z | DSP/extensions/WindowFunctionLib/source/TTHanningWindow.cpp | avilleret/JamomaCore | b09cfb684527980f30845f664e1f922005c24e60 | [
"BSD-3-Clause"
] | 14 | 2015-02-10T15:08:32.000Z | 2019-09-17T01:21:25.000Z | /** @file
*
* @ingroup dspWindowFunctionLib
*
* @brief Hanning Window Function Unit for Jamoma DSP
*
* @details This implements a window function as described @
http://local.wasp.uwa.edu.au/~pbourke/miscellaneous/windows/ @n
hanning(x) = 0.5 + 0.5*cos(2*PI*(x-0.5)) @n
*
* @authors Nils Peters, Trond Lossius, Tim Place, Nathan Wolek
*
* @copyright Copyright © 2010 by Trond Lossius @n
* This code is licensed under the terms of the "New BSD License" @n
* http://creativecommons.org/licenses/BSD/
*/
#include "TTHanningWindow.h"
#define thisTTClass HanningWindow
#define thisTTClassName "hanning"
#define thisTTClassTags "dspWindowFunctionLib, audio, processor, function, window"
TT_AUDIO_CONSTRUCTOR
{
setProcessMethod(processAudio);
setCalculateMethod(calculateValue);
}
HanningWindow::~HanningWindow()
{
;
}
// hanning(x) = 0.5 + 0.5*cos(2*PI*(x-0.5))
TTErr HanningWindow::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data)
{
y = 0.5 + 0.5*cos(kTTTwoPi*(x-0.5));
return kTTErrNone;
}
TTErr HanningWindow::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
TT_WRAP_CALCULATE_METHOD(calculateValue);
}
| 23.176471 | 94 | 0.734349 | avilleret |
a5dd2dde451be6c3336adee38561adb0ed473dfd | 2,316 | cpp | C++ | src/noui.cpp | tradecraftio/tradecraft | a014fea4d4656df67aef19e379f10322386cf6f8 | [
"MIT"
] | 10 | 2019-03-08T04:10:37.000Z | 2021-08-20T11:55:14.000Z | src/noui.cpp | tradecraftio/tradecraft | a014fea4d4656df67aef19e379f10322386cf6f8 | [
"MIT"
] | 69 | 2018-11-09T20:29:29.000Z | 2021-10-05T00:08:36.000Z | src/noui.cpp | tradecraftio/tradecraft | a014fea4d4656df67aef19e379f10322386cf6f8 | [
"MIT"
] | 7 | 2019-01-21T06:00:18.000Z | 2021-12-19T16:18:00.000Z | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Copyright (c) 2011-2021 The Freicoin Developers
//
// This program is free software: you can redistribute it and/or modify it under
// the terms of version 3 of the GNU Affero General Public License as published
// by the Free Software Foundation.
//
// 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 Affero General Public License for more
// details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <noui.h>
#include <ui_interface.h>
#include <util/system.h>
#include <cstdio>
#include <stdint.h>
#include <string>
#include <boost/signals2/connection.hpp>
bool noui_ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style)
{
bool fSecure = style & CClientUIInterface::SECURE;
style &= ~CClientUIInterface::SECURE;
std::string strCaption;
// Check for usage of predefined caption
switch (style) {
case CClientUIInterface::MSG_ERROR:
strCaption += _("Error");
break;
case CClientUIInterface::MSG_WARNING:
strCaption += _("Warning");
break;
case CClientUIInterface::MSG_INFORMATION:
strCaption += _("Information");
break;
default:
strCaption += caption; // Use supplied caption (can be empty)
}
if (!fSecure)
LogPrintf("%s: %s\n", strCaption, message);
tfm::format(std::cerr, "%s: %s\n", strCaption.c_str(), message.c_str());
return false;
}
bool noui_ThreadSafeQuestion(const std::string& /* ignored interactive message */, const std::string& message, const std::string& caption, unsigned int style)
{
return noui_ThreadSafeMessageBox(message, caption, style);
}
void noui_InitMessage(const std::string& message)
{
LogPrintf("init message: %s\n", message);
}
void noui_connect()
{
uiInterface.ThreadSafeMessageBox_connect(noui_ThreadSafeMessageBox);
uiInterface.ThreadSafeQuestion_connect(noui_ThreadSafeQuestion);
uiInterface.InitMessage_connect(noui_InitMessage);
}
| 32.619718 | 158 | 0.716753 | tradecraftio |
a5dd5ecf27213b2def0027b5f1fdbbef7412ba1f | 909 | cpp | C++ | sources/libcpp53iip_precision/iip_precision_bw_to_uchargray.cpp | Savraska2/GTS | 78c8b4d634f1379eb3e33642716717f53bf7e1ad | [
"BSD-3-Clause"
] | 61 | 2016-03-26T03:04:43.000Z | 2021-09-17T02:11:18.000Z | sources/libcpp53iip_precision/iip_precision_bw_to_uchargray.cpp | sahwar/GTS | b25734116ea81eb0d7e2eabc8ce16cdd1c8b22dd | [
"BSD-3-Clause"
] | 92 | 2016-04-10T23:40:22.000Z | 2022-03-11T21:49:12.000Z | sources/libcpp53iip_precision/iip_precision_bw_to_uchargray.cpp | sahwar/GTS | b25734116ea81eb0d7e2eabc8ce16cdd1c8b22dd | [
"BSD-3-Clause"
] | 18 | 2016-03-26T11:19:14.000Z | 2021-08-07T00:26:02.000Z | #include <limits.h> /* CHAR_BIT */
#include "pri.h"
#include "iip_precision.h"
#include "calcu_precision.h"
void iip_precision::_bw_to_uchargray( long l_width, long l_height, long l_max, unsigned char *ucharp_in_bw, unsigned char *ucharp_out_gray )
{
long xx,yy, l_in_bits;
/* カウントダウン表示始め */
if (ON == this->get_i_cv_sw()) { pri_funct_cv_start(l_height); }
for (yy = 0L; yy < l_height; ++yy) {
/* カウントダウン表示中 */
if (ON == this->get_i_cv_sw()) { pri_funct_cv_run(yy); }
for (l_in_bits = 0x80,xx = 0L; xx < l_width; ++xx) {
if (ucharp_in_bw[0] & l_in_bits) {
ucharp_out_gray[0] = (unsigned char)l_max;
} else {
ucharp_out_gray[0] = 0L;
}
if ( ((CHAR_BIT-1) == (xx%CHAR_BIT)) ||
((l_width-1) <= xx)
) {
++ucharp_in_bw;
l_in_bits = 0x80;
} else {l_in_bits >>= 1; }
++ucharp_out_gray;
}
}
/* カウントダウン表示終了 */
if (ON == this->get_i_cv_sw()) { pri_funct_cv_end(); }
}
| 23.921053 | 140 | 0.630363 | Savraska2 |
a5e0078cfa8ec368b124f379ea9a41c7a348f9e7 | 2,406 | cpp | C++ | renderer/source/graphics/vulkan/utility/DebugUtility.cpp | dushyant-shukla/voyager-renderer | a6e64647f45d652130dd946c8692c6139f9a0ec4 | [
"Apache-2.0"
] | 2 | 2022-01-24T01:10:49.000Z | 2022-01-24T01:10:53.000Z | renderer/source/graphics/vulkan/utility/DebugUtility.cpp | dushyant-shukla/voyager-renderer | a6e64647f45d652130dd946c8692c6139f9a0ec4 | [
"Apache-2.0"
] | null | null | null | renderer/source/graphics/vulkan/utility/DebugUtility.cpp | dushyant-shukla/voyager-renderer | a6e64647f45d652130dd946c8692c6139f9a0ec4 | [
"Apache-2.0"
] | 1 | 2021-08-31T19:44:25.000Z | 2021-08-31T19:44:25.000Z | #include "DebugUtility.h"
#include <vector>
namespace vr
{
VKAPI_ATTR VkBool32 VKAPI_CALL DebugUtility::DebugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, VkDebugUtilsMessageTypeFlagsEXT messageType, const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, void* pUserData)
{
switch (messageSeverity)
{
case VkDebugUtilsMessageSeverityFlagBitsEXT::VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT:
case VkDebugUtilsMessageSeverityFlagBitsEXT::VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT:
#ifdef ENABLE_DEBUG_LOGGING
RENDERER_WARN("INVALID OPERATION WARNING: {0}", pCallbackData->pMessage);
#endif
break;
case VkDebugUtilsMessageSeverityFlagBitsEXT::VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT:
RENDERER_ERROR("INVALID OPERATION: {0}", pCallbackData->pMessage);
break;
};
return VK_FALSE;
}
void DebugUtility::PopulateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& info)
{
info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
info.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
info.pfnUserCallback = DebugCallback;
info.pUserData = nullptr; // Optional
}
void DebugUtility::CreateDebugMessenger(VkDebugUtilsMessengerEXT& const messenger, VkInstance& const instance, const VkDebugUtilsMessengerCreateInfoEXT& info, VkAllocationCallbacks const* const pAllocator)
{
auto func = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT");
if (func != nullptr) {
CHECK_RESULT(func(instance, &info, pAllocator, &messenger), "RESOURCE CREATION FAILED: DEBUG MESSENGER");
}
RENDERER_DEBUG("RESOURCE CREATED: DEBUG MESSENGER");
}
void DebugUtility::DestroyDebugMessenger(VkDebugUtilsMessengerEXT& const messenger, VkInstance& const instance, VkAllocationCallbacks const* const pAllocator)
{
#ifdef ENABLE_VALIDATION
auto func = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT");
if (func != nullptr) {
func(instance, messenger, pAllocator);
}
RENDERER_DEBUG("RESOURCE DESTROYED: DEBUG MESSENGER");
#endif
}
} | 46.269231 | 236 | 0.832918 | dushyant-shukla |
a5e0621d63f479bd9cf7347e37ff70b97e0e9da0 | 21,132 | cpp | C++ | src/shared/zip.cpp | project-imprimis/libprimis | ce0c0bae6852b42709736c8e324bcc2ef26d8dc9 | [
"Zlib"
] | 30 | 2020-10-30T20:21:55.000Z | 2022-03-19T02:23:48.000Z | src/shared/zip.cpp | project-imprimis/libprimis | ce0c0bae6852b42709736c8e324bcc2ef26d8dc9 | [
"Zlib"
] | 74 | 2020-11-06T03:40:44.000Z | 2022-03-30T20:18:07.000Z | src/shared/zip.cpp | project-imprimis/libprimis | ce0c0bae6852b42709736c8e324bcc2ef26d8dc9 | [
"Zlib"
] | 5 | 2020-12-21T19:29:27.000Z | 2022-01-12T05:17:06.000Z | #include "../engine/engine.h"
#include "../engine/interface/console.h"
enum
{
Zip_LocalFileSignature = 0x04034B50,
Zip_LocalFileSize = 30,
Zip_FileSignature = 0x02014B50,
Zip_FileSize = 46,
Zip_DirectorySignature = 0x06054B50,
Zip_DirectorySize = 22
};
struct ziplocalfileheader
{
uint signature;
ushort version, flags, compression, modtime, moddate;
uint crc32, compressedsize, uncompressedsize;
ushort namelength, extralength;
};
struct zipfileheader
{
uint signature;
ushort version, needversion, flags, compression, modtime, moddate;
uint crc32, compressedsize, uncompressedsize;
ushort namelength, extralength, commentlength, disknumber, internalattribs;
uint externalattribs, offset;
};
struct zipdirectoryheader
{
uint signature;
ushort disknumber, directorydisk, diskentries, entries;
uint size, offset;
ushort commentlength;
};
struct zipfile
{
char *name;
uint header, offset, size, compressedsize;
zipfile() : name(nullptr), header(0), offset(~0U), size(0), compressedsize(0)
{
}
~zipfile()
{
DELETEA(name);
}
};
struct zipstream;
struct ziparchive
{
char *name;
FILE *data;
hashnameset<zipfile> files;
int openfiles;
zipstream *owner;
ziparchive() : name(nullptr), data(nullptr), files(512), openfiles(0), owner(nullptr)
{
}
~ziparchive()
{
DELETEA(name);
if(data)
{
fclose(data);
data = nullptr;
}
}
};
static bool findzipdirectory(FILE *f, zipdirectoryheader &hdr)
{
if(fseek(f, 0, SEEK_END) < 0)
{
return false;
}
long offset = ftell(f);
if(offset < 0)
{
return false;
}
uchar buf[1024],
*src = nullptr;
long end = std::max(offset - 0xFFFFL - Zip_DirectorySize, 0L);
size_t len = 0;
const uint signature = static_cast<uint>(Zip_DirectorySignature);
while(offset > end)
{
size_t carry = std::min(len, static_cast<size_t>(Zip_DirectorySize-1)), next = std::min(sizeof(buf) - carry, static_cast<size_t>(offset - end));
offset -= next;
memmove(&buf[next], buf, carry);
if(next + carry < Zip_DirectorySize || fseek(f, offset, SEEK_SET) < 0 || fread(buf, 1, next, f) != next)
{
return false;
}
len = next + carry;
uchar *search = &buf[next-1];
for(; search >= buf; search--)
{
if(*(uint *)search == signature)
{
break;
}
}
if(search >= buf)
{
src = search;
break;
}
}
if(!src || &buf[len] - src < Zip_DirectorySize)
{
return false;
}
hdr.signature = *(uint *)src; src += 4; //src is incremented by the size of the field (int is 4 bytes)
hdr.disknumber = *(ushort *)src; src += 2;
hdr.directorydisk = *(ushort *)src; src += 2;
hdr.diskentries = *(ushort *)src; src += 2;
hdr.entries = *(ushort *)src; src += 2;
hdr.size = *(uint *)src; src += 4;
hdr.offset = *(uint *)src; src += 4;
hdr.commentlength = *(ushort *)src; src += 2;
if(hdr.signature != Zip_DirectorySignature || hdr.disknumber != hdr.directorydisk || hdr.diskentries != hdr.entries)
{
return false;
}
return true;
}
VAR(debugzip, 0, 0, 1);
static bool readzipdirectory(const char *archname, FILE *f, int entries, int offset, uint size, std::vector<zipfile> &files)
{
uchar *buf = new uchar[size],
*src = buf;
if(!buf || fseek(f, offset, SEEK_SET) < 0 || fread(buf, 1, size, f) != size)
{
delete[] buf;
return false;
}
for(int i = 0; i < entries; ++i)
{
if(src + Zip_FileSize > &buf[size])
{
break;
}
zipfileheader hdr;
hdr.signature = *(uint *)src; src += 4; //src is incremented by the size of the field (int is 4 bytes)
hdr.version = *(ushort *)src; src += 2;
hdr.needversion = *(ushort *)src; src += 2;
hdr.flags = *(ushort *)src; src += 2;
hdr.compression = *(ushort *)src; src += 2;
hdr.modtime = *(ushort *)src; src += 2;
hdr.moddate = *(ushort *)src; src += 2;
hdr.crc32 = *(uint *)src; src += 4;
hdr.compressedsize = *(uint *)src; src += 4;
hdr.uncompressedsize = *(uint *)src; src += 4;
hdr.namelength = *(ushort *)src; src += 2;
hdr.extralength = *(ushort *)src; src += 2;
hdr.commentlength = *(ushort *)src; src += 2;
hdr.disknumber = *(ushort *)src; src += 2;
hdr.internalattribs = *(ushort *)src; src += 2;
hdr.externalattribs = *(uint *)src; src += 4;
hdr.offset = *(uint *)src; src += 4;
if(hdr.signature != Zip_FileSignature)
{
break;
}
if(!hdr.namelength || !hdr.uncompressedsize || (hdr.compression && (hdr.compression != Z_DEFLATED || !hdr.compressedsize)))
{
src += hdr.namelength + hdr.extralength + hdr.commentlength;
continue;
}
if(src + hdr.namelength > &buf[size])
{
break;
}
string pname;
int namelen = std::min(static_cast<int>(hdr.namelength), static_cast<int>(sizeof(pname)-1));
memcpy(pname, src, namelen);
pname[namelen] = '\0';
path(pname);
char *name = newstring(pname);
zipfile f;
f.name = name;
f.header = hdr.offset;
f.size = hdr.uncompressedsize;
files.push_back(f);
f.compressedsize = hdr.compression ? hdr.compressedsize : 0;
if(debugzip)
{
conoutf(Console_Debug, "%s: file %s, size %d, compress %d, flags %x", archname, name, hdr.uncompressedsize, hdr.compression, hdr.flags);
}
src += hdr.namelength + hdr.extralength + hdr.commentlength;
}
delete[] buf;
return files.size() > 0;
}
static bool readlocalfileheader(FILE *f, ziplocalfileheader &h, uint offset)
{
uchar buf[Zip_LocalFileSize];
if(fseek(f, offset, SEEK_SET) < 0 || fread(buf, 1, Zip_LocalFileSize, f) != Zip_LocalFileSize)
{
return false;
}
uchar *src = buf;
h.signature = *(uint *)src; src += 4; //src is incremented by the size of the field (int is 4 bytes e.g)
h.version = *(ushort *)src; src += 2;
h.flags = *(ushort *)src; src += 2;
h.compression = *(ushort *)src; src += 2;
h.modtime = *(ushort *)src; src += 2;
h.moddate = *(ushort *)src; src += 2;
h.crc32 = *(uint *)src; src += 4;
h.compressedsize = *(uint *)src; src += 4;
h.uncompressedsize = *(uint *)src; src += 4;
h.namelength = *(ushort *)src; src += 2;
h.extralength = *(ushort *)src; src += 2;
if(h.signature != Zip_LocalFileSignature)
{
return false;
}
// h.uncompressedsize or h.compressedsize may be zero - so don't validate
return true;
}
static vector<ziparchive *> archives;
ziparchive *findzip(const char *name)
{
for(int i = 0; i < archives.length(); i++)
{
if(!strcmp(name, archives[i]->name))
{
return archives[i];
}
}
return nullptr;
}
static bool checkprefix(std::vector<zipfile> &files, const char *prefix, int prefixlen)
{
for(uint i = 0; i < files.size(); i++)
{
if(!strncmp(files[i].name, prefix, prefixlen))
{
return false;
}
}
return true;
}
static void mountzip(ziparchive &arch, std::vector<zipfile> &files, const char *mountdir, const char *stripdir)
{
string packagesdir = "media/";
path(packagesdir);
size_t striplen = stripdir ? std::strlen(stripdir) : 0;
if(!mountdir && !stripdir)
{
for(uint i = 0; i < files.size(); i++)
{
zipfile &f = files[i];
const char *foundpackages = std::strstr(f.name, packagesdir);
if(foundpackages)
{
if(foundpackages > f.name)
{
stripdir = f.name;
striplen = foundpackages - f.name;
}
break;
}
const char *foundogz = std::strstr(f.name, ".ogz");
if(foundogz)
{
const char *ogzdir = foundogz;
while(--ogzdir >= f.name && *ogzdir != PATHDIV)
{
//(empty body)
}
if(ogzdir < f.name || checkprefix(files, f.name, ogzdir + 1 - f.name))
{
if(ogzdir >= f.name)
{
stripdir = f.name;
striplen = ogzdir + 1 - f.name;
}
if(!mountdir)
{
mountdir = "media/map/";
}
break;
}
}
}
}
string mdir = "", fname;
if(mountdir)
{
copystring(mdir, mountdir);
if(fixpackagedir(mdir) <= 1)
{
mdir[0] = '\0';
}
}
for(uint i = 0; i < files.size(); i++)
{
zipfile &f = files[i];
formatstring(fname, "%s%s", mdir, striplen && !strncmp(f.name, stripdir, striplen) ? &f.name[striplen] : f.name);
if(arch.files.access(fname))
{
continue;
}
char *mname = newstring(fname);
zipfile &mf = arch.files[mname];
mf = f;
mf.name = mname;
}
}
bool addzip(const char *name, const char *mount = nullptr, const char *strip = nullptr)
{
string pname;
copystring(pname, name);
path(pname);
size_t plen = std::strlen(pname);
if(plen < 4 || !strchr(&pname[plen-4], '.'))
{
concatstring(pname, ".zip");
}
ziparchive *exists = findzip(pname);
if(exists)
{
conoutf(Console_Error, "already added zip %s", pname);
return true;
}
FILE *f = fopen(findfile(pname, "rb"), "rb");
if(!f)
{
conoutf(Console_Error, "could not open file %s", pname);
return false;
}
zipdirectoryheader h;
std::vector<zipfile> files;
if(!findzipdirectory(f, h) || !readzipdirectory(pname, f, h.entries, h.offset, h.size, files))
{
conoutf(Console_Error, "could not read directory in zip %s", pname);
fclose(f);
return false;
}
ziparchive *arch = new ziparchive;
arch->name = newstring(pname);
arch->data = f;
mountzip(*arch, files, mount, strip);
archives.add(arch);
conoutf("added zip %s", pname);
return true;
}
bool removezip(const char *name)
{
string pname;
copystring(pname, name);
path(pname);
int plen = (int)std::strlen(pname);
if(plen < 4 || !strchr(&pname[plen-4], '.'))
{
concatstring(pname, ".zip");
}
ziparchive *exists = findzip(pname);
if(!exists)
{
conoutf(Console_Error, "zip %s is not loaded", pname);
return false;
}
if(exists->openfiles)
{
conoutf(Console_Error, "zip %s has open files", pname);
return false;
}
conoutf("removed zip %s", exists->name);
archives.removeobj(exists);
delete exists;
return true;
}
struct zipstream : stream
{
enum
{
Buffer_Size = 16384
};
ziparchive *arch;
zipfile *info;
z_stream zfile;
uchar *buf;
uint reading;
bool ended;
zipstream() : arch(nullptr), info(nullptr), buf(nullptr), reading(~0U), ended(false)
{
zfile.zalloc = nullptr;
zfile.zfree = nullptr;
zfile.opaque = nullptr;
zfile.next_in = zfile.next_out = nullptr;
zfile.avail_in = zfile.avail_out = 0;
}
~zipstream()
{
close();
}
void readbuf(uint size = Buffer_Size)
{
if(!zfile.avail_in)
{
zfile.next_in = (Bytef *)buf;
}
size = std::min(size, static_cast<uint>(&buf[Buffer_Size] - &zfile.next_in[zfile.avail_in]));
if(arch->owner != this)
{
arch->owner = nullptr;
if(fseek(arch->data, reading, SEEK_SET) >= 0)
{
arch->owner = this;
}
else
{
return;
}
}
uint remaining = info->offset + info->compressedsize - reading,
n = arch->owner == this ? fread(zfile.next_in + zfile.avail_in, 1, std::min(size, remaining), arch->data) : 0U;
zfile.avail_in += n;
reading += n;
}
bool open(ziparchive *a, zipfile *f)
{
if(f->offset == ~0U)
{
ziplocalfileheader h;
a->owner = nullptr;
if(!readlocalfileheader(a->data, h, f->header))
{
return false;
}
f->offset = f->header + Zip_LocalFileSize + h.namelength + h.extralength;
}
if(f->compressedsize && inflateInit2(&zfile, -MAX_WBITS) != Z_OK)
{
return false;
}
a->openfiles++;
arch = a;
info = f;
reading = f->offset;
ended = false;
if(f->compressedsize)
{
buf = new uchar[Buffer_Size];
}
return true;
}
void stopreading()
{
if(reading == ~0U)
{
return;
}
if(debugzip)
{
conoutf(Console_Debug, info->compressedsize ? "%s: zfile.total_out %u, info->size %u" : "%s: reading %u, info->size %u", info->name, info->compressedsize ? static_cast<uint>(zfile.total_out) : reading - info->offset, info->size);
}
if(info->compressedsize)
{
inflateEnd(&zfile);
}
reading = ~0U;
}
void close()
{
stopreading();
DELETEA(buf);
if(arch)
{
arch->owner = nullptr;
arch->openfiles--;
arch = nullptr;
}
}
offset size()
{
return info->size;
}
bool end()
{
return reading == ~0U || ended;
}
offset tell()
{
return reading != ~0U ? (info->compressedsize ? zfile.total_out : reading - info->offset) : offset(-1);
}
bool seek(offset pos, int whence)
{
if(reading == ~0U)
{
return false;
}
if(!info->compressedsize)
{
switch(whence)
{
case SEEK_END:
{
pos += info->offset + info->size;
break;
}
case SEEK_CUR:
{
pos += reading;
break;
}
case SEEK_SET:
{
pos += info->offset;
break;
}
default:
{
return false;
}
}
pos = std::clamp(pos, offset(info->offset), offset(info->offset + info->size));
arch->owner = nullptr;
if(fseek(arch->data, static_cast<int>(pos), SEEK_SET) < 0)
{
return false;
}
arch->owner = this;
reading = pos;
ended = false;
return true;
}
switch(whence)
{
case SEEK_END:
{
pos += info->size;
break;
}
case SEEK_CUR:
{
pos += zfile.total_out;
break;
}
case SEEK_SET:
{
break;
}
default:
{
return false;
}
}
if(pos >= (offset)info->size)
{
reading = info->offset + info->compressedsize;
zfile.next_in += zfile.avail_in;
zfile.avail_in = 0;
zfile.total_in = info->compressedsize;
zfile.total_out = info->size;
arch->owner = nullptr;
ended = false;
return true;
}
if(pos < 0)
{
return false;
}
if(pos >= (offset)zfile.total_out)
{
pos -= zfile.total_out;
}
else
{
if(zfile.next_in && zfile.total_in <= static_cast<uint>(zfile.next_in - buf))
{
zfile.avail_in += zfile.total_in;
zfile.next_in -= zfile.total_in;
}
else
{
arch->owner = nullptr;
zfile.avail_in = 0;
zfile.next_in = nullptr;
reading = info->offset;
}
inflateReset(&zfile);
}
uchar skip[512];
while(pos > 0)
{
size_t skipped = static_cast<size_t>(std::min(pos, (offset)sizeof(skip)));
if(read(skip, skipped) != skipped)
{
return false;
}
pos -= skipped;
}
ended = false;
return true;
}
size_t read(void *buf, size_t len)
{
if(reading == ~0U || !buf || !len)
{
return 0;
}
if(!info->compressedsize)
{
if(arch->owner != this)
{
arch->owner = nullptr;
if(fseek(arch->data, reading, SEEK_SET) < 0)
{
stopreading();
return 0;
}
arch->owner = this;
}
size_t n = fread(buf, 1, std::min(len, static_cast<size_t>(info->size + info->offset - reading)), arch->data);
reading += n;
if(n < len)
{
ended = true;
}
return n;
}
zfile.next_out = (Bytef *)buf;
zfile.avail_out = len;
while(zfile.avail_out > 0)
{
if(!zfile.avail_in)
{
readbuf(Buffer_Size);
}
int err = inflate(&zfile, Z_NO_FLUSH);
if(err != Z_OK)
{
if(err == Z_STREAM_END)
{
ended = true;
}
else
{
if(debugzip)
{
conoutf(Console_Debug, "inflate error: %s", zError(err));
}
stopreading();
}
break;
}
}
return len - zfile.avail_out;
}
};
stream *openzipfile(const char *name, const char *mode)
{
for(; *mode; mode++)
{
if(*mode=='w' || *mode=='a')
{
return nullptr;
}
}
for(int i = archives.length(); --i >=0;) //note reverse iteration
{
ziparchive *arch = archives[i];
zipfile *f = arch->files.access(name);
if(!f)
{
continue;
}
zipstream *s = new zipstream;
if(s->open(arch, f))
{
return s;
}
delete s;
}
return nullptr;
}
bool findzipfile(const char *name)
{
for(int i = archives.length(); --i >=0;) //note reverse iteration
{
ziparchive *arch = archives[i];
if(arch->files.access(name))
{
return true;
}
}
return false;
}
int listzipfiles(const char *dir, const char *ext, vector<char *> &files)
{
size_t extsize = ext ? std::strlen(ext)+1 : 0,
dirsize = std::strlen(dir);
int dirs = 0;
for(int i = archives.length(); --i >=0;) //note reverse iteration
{
ziparchive *arch = archives[i];
int oldsize = files.length();
ENUMERATE(arch->files, zipfile, f,
{
if(strncmp(f.name, dir, dirsize))
{
continue;
}
const char *name = f.name + dirsize;
if(name[0] == PATHDIV)
{
name++;
}
if(strchr(name, PATHDIV))
{
continue;
}
if(!ext)
{
files.add(newstring(name));
}
else
{
size_t namelen = std::strlen(name);
if(namelen > extsize)
{
namelen -= extsize;
if(name[namelen] == '.' && strncmp(name+namelen+1, ext, extsize-1)==0)
{
files.add(newstring(name, namelen));
}
}
}
});
if(files.length() > oldsize)
{
dirs++;
}
}
return dirs;
}
void addzipcmd(const char *name, const char *mount, const char *strip)
{
addzip(name, mount[0] ? mount : nullptr, strip[0] ? strip : nullptr);
}
COMMANDN(addzip, addzipcmd, "sss");
COMMAND(removezip, "s");
| 27.231959 | 241 | 0.479273 | project-imprimis |
a5e0fe9bd062244decd57be9785667b778b1d6f7 | 1,515 | hpp | C++ | test/arrow/arrow_test_factory.hpp | AldoMyrtaj/duckdb | 3aa4978a2ceab8df25e4b20c388bcd7629de73ed | [
"MIT"
] | 2,816 | 2018-06-26T18:52:52.000Z | 2021-04-06T10:39:15.000Z | test/arrow/arrow_test_factory.hpp | AldoMyrtaj/duckdb | 3aa4978a2ceab8df25e4b20c388bcd7629de73ed | [
"MIT"
] | 1,310 | 2021-04-06T16:04:52.000Z | 2022-03-31T13:52:53.000Z | test/arrow/arrow_test_factory.hpp | AldoMyrtaj/duckdb | 3aa4978a2ceab8df25e4b20c388bcd7629de73ed | [
"MIT"
] | 270 | 2021-04-09T06:18:28.000Z | 2022-03-31T11:55:37.000Z | #pragma once
#include "arrow/record_batch.h"
#include "duckdb/common/arrow_wrapper.hpp"
#include "arrow/array.h"
#include "catch.hpp"
#define REQUIRE_RESULT(OUT, IN) \
REQUIRE(IN.ok()); \
OUT = IN.ValueUnsafe();
struct SimpleFactory {
/// All materialized batches
arrow::RecordBatchVector batches;
/// The schema
std::shared_ptr<arrow::Schema> schema;
SimpleFactory(arrow::RecordBatchVector batches, std::shared_ptr<arrow::Schema> schema)
: batches(std::move(batches)), schema(std::move(schema)) {
}
static std::unique_ptr<duckdb::ArrowArrayStreamWrapper> CreateStream(uintptr_t this_ptr) {
//! Create a new batch reader
auto &factory = *reinterpret_cast<SimpleFactory *>(this_ptr); //! NOLINT
REQUIRE_RESULT(auto reader, arrow::RecordBatchReader::Make(factory.batches, factory.schema));
//! Export C arrow stream stream
auto stream_wrapper = duckdb::make_unique<duckdb::ArrowArrayStreamWrapper>();
stream_wrapper->arrow_array_stream.release = nullptr;
auto maybe_ok = arrow::ExportRecordBatchReader(reader, &stream_wrapper->arrow_array_stream);
if (!maybe_ok.ok()) {
if (stream_wrapper->arrow_array_stream.release) {
stream_wrapper->arrow_array_stream.release(&stream_wrapper->arrow_array_stream);
}
return nullptr;
}
//! Pass ownership to caller
return stream_wrapper;
}
}; | 37.875 | 120 | 0.656766 | AldoMyrtaj |
a5e234e23a8237072a6610bf60c1fd72a500d036 | 2,724 | hpp | C++ | Graph_Instruction.hpp | gydrogen/hydrogen | 6c448b67471ce2bbef12a36a0182b58ac56a7da3 | [
"MIT"
] | 3 | 2020-04-02T17:09:07.000Z | 2020-12-23T11:27:17.000Z | Graph_Instruction.hpp | gydrogen/hydrogen | 6c448b67471ce2bbef12a36a0182b58ac56a7da3 | [
"MIT"
] | null | null | null | Graph_Instruction.hpp | gydrogen/hydrogen | 6c448b67471ce2bbef12a36a0182b58ac56a7da3 | [
"MIT"
] | 4 | 2020-04-04T23:22:48.000Z | 2020-08-06T08:39:23.000Z | /**
* @author Ashwin K J
* @file
* Graph_Instruction Class: Graph Data-structure for LLVM instructions
*/
#ifndef GRAPH_INSTRUCTION_H
#define GRAPH_INSTRUCTION_H
#include <list>
#include <llvm/IR/Module.h>
#include <set>
namespace hydrogen_framework {
/* Forward declaration */
class Graph_Edge;
class Graph_Line;
class Query;
/**
* Graph_Instruction Class: To store individual LLVM instructions
*/
class Graph_Instruction {
public:
/**
* Constructor
*/
Graph_Instruction() : instructionID(0), instructionPtr(NULL), instructionLine(NULL) {}
/**
* Destructor
*/
~Graph_Instruction() {}
/**
* Set instructionID
*/
void setInstructionID(unsigned ID) { instructionID = ID; }
/**
* Set instructionLabel
*/
void setInstructionLabel(std::string label) { instructionLabel = label; }
/**
* Set instructionPtr
*/
void setInstructionPtr(llvm::Instruction *I) { instructionPtr = I; }
/**
* Push Graph_Edge into instructionEdges list
*/
void pushEdgeInstruction(Graph_Edge *edge) { instructionEdges.push_back(edge); }
/**
* Return instructionLabel
*/
std::string getInstructionLabel() { return instructionLabel; }
/**
* Return instructionID
*/
unsigned getInstructionID() { return instructionID; }
/**
* Get instructionPtr
* Can return NULL
*/
llvm::Instruction *getInstructionPtr() { return instructionPtr; }
/**
* Return instructionEdges
*/
std::list<Graph_Edge *> getInstructionEdges() { return instructionEdges; }
/**
* Set pointer to encompassing Graph_Line
*/
void setGraphLine(Graph_Line *line) { instructionLine = line; }
/**
* Return pointer to encompassing Graph_Line
*/
Graph_Line *getGraphLine() { return instructionLine; }
/**
* Return instructionVisitedQueries
*/
std::set<Query *> getInstructionVisitedQueries() { return instructionVisitedQueries; }
/**
* Insert query as pointer into instructionVisitedQueries
*/
void insertInstructionVisitedQueries(Query *q) { instructionVisitedQueries.insert(q); }
private:
unsigned instructionID; /**< Instruction ID */
std::string instructionLabel; /**< Instruction label or text */
llvm::Instruction *instructionPtr; /**< Instruction LLVM Pointer */
std::list<Graph_Edge *> instructionEdges; /**< Container for edges in the instruction */
Graph_Line *instructionLine; /**< Points to the Graph_Line that encompasses this */
std::set<Query *> instructionVisitedQueries; /**< Container for Queries that have visited this */
}; // End Graph_Instruction Class
} // namespace hydrogen_framework
#endif
| 26.192308 | 101 | 0.674009 | gydrogen |
a5e66f955abf5653e12f0459efa0cc963af46359 | 1,785 | cpp | C++ | boboleetcode/Play-Leetcode-master/1042-Flower-Planting-With-No-Adjacent/cpp-1042/main2.cpp | yaominzh/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | 2 | 2021-03-25T05:26:55.000Z | 2021-04-20T03:33:24.000Z | boboleetcode/Play-Leetcode-master/1042-Flower-Planting-With-No-Adjacent/cpp-1042/main2.cpp | mcuallen/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | 6 | 2019-12-04T06:08:32.000Z | 2021-05-10T20:22:47.000Z | boboleetcode/Play-Leetcode-master/1042-Flower-Planting-With-No-Adjacent/cpp-1042/main2.cpp | mcuallen/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | null | null | null | /// Source : https://leetcode.com/problems/flower-planting-with-no-adjacent/
/// Author : liuyubobobo
/// Time : 2019-05-19
#include <iostream>
#include <vector>
#include <unordered_set>
#include <queue>
using namespace std;
/// DFS
/// Time Complexity: O(n^2)
/// Space Complexity: O(n^2)
class Solution {
public:
vector<int> gardenNoAdj(int N, vector<vector<int>>& paths) {
vector<unordered_set<int>> g(N);
for(const vector<int>& edge: paths){
g[edge[0] - 1].insert(edge[1] - 1);
g[edge[1] - 1].insert(edge[0] - 1);
}
vector<int> colors(N, -1);
for(int i = 0; i < N; i ++)
if(colors[i] < 0)
dfs(g, i, colors);
return colors;
}
private:
void dfs(const vector<unordered_set<int>>& g, int v, vector<int>& colors){
unordered_set<int> options = get_options(g, v, colors);
colors[v] = *options.begin();
for(int next: g[v])
if(colors[next] == -1)
dfs(g, next, colors);
}
unordered_set<int> get_options(const vector<unordered_set<int>>& g, int v,
const vector<int>& colors){
unordered_set<int> options = {1, 2, 3, 4};
for(int u: g[v])
if(colors[u] != -1)
options.erase(colors[u]);
return options;
}
};
void print_vec(const vector<int>& vec){
for(int e: vec)
cout << e << " ";
cout << endl;
}
int main() {
vector<vector<int>> paths1 = {{1, 2}, {2, 3}, {3, 1}};
print_vec(Solution().gardenNoAdj(3, paths1));
// 1 2 3
vector<vector<int>> paths2 = {{3, 4}, {4, 5}, {3, 2}, {5, 1}, {1, 3}, {4, 2}};
print_vec(Solution().gardenNoAdj(5, paths2));
// 1 2 4 3 1
return 0;
} | 24.121622 | 82 | 0.52493 | yaominzh |
a5ee134dfa8b9a1daf7c99bd259d70225a506b50 | 589 | cpp | C++ | stlport/test/regression/uprbnd1.cpp | masscry/dmc | c7638f7c524a65bc2af0876c76621d8a11da42bb | [
"BSL-1.0"
] | 86 | 2018-05-24T12:03:44.000Z | 2022-03-13T03:01:25.000Z | stlport/test/regression/uprbnd1.cpp | masscry/dmc | c7638f7c524a65bc2af0876c76621d8a11da42bb | [
"BSL-1.0"
] | 1 | 2019-05-30T01:38:40.000Z | 2019-10-26T07:15:01.000Z | stlport/test/regression/uprbnd1.cpp | masscry/dmc | c7638f7c524a65bc2af0876c76621d8a11da42bb | [
"BSL-1.0"
] | 14 | 2018-07-16T08:29:12.000Z | 2021-08-23T06:21:30.000Z | // STLport regression testsuite component.
// To compile as a separate example, please #define MAIN.
#include <algorithm>
#include <iostream>
#ifdef MAIN
#define uprbnd1_test main
#endif
#if !defined (STLPORT) || defined(__STL_USE_NAMESPACES)
using namespace std;
#endif
int uprbnd1_test(int, char**)
{
cout<<"Results of uprbnd1_test:"<<endl;
int array[20];
for(int i = 0; i < 20; i++)
{
array[i] = i/4;
cout << array[i] << ' ';
}
cout
<< "\n3 can be inserted at index: "
<<(upper_bound((int*)array, (int*)array + 20, 3) - array)
<< endl;
return 0;
}
| 20.310345 | 61 | 0.633277 | masscry |
a5eec2dcc0ee6a02b8e59f79843d22a3dc1425d6 | 4,063 | cpp | C++ | wxSnapshot/src/common/statbmpcmn.cpp | KeyWorksRW/wxUiTesting | 249861f72b71221220c95c6271d496d6e1b6d10a | [
"Apache-2.0"
] | null | null | null | wxSnapshot/src/common/statbmpcmn.cpp | KeyWorksRW/wxUiTesting | 249861f72b71221220c95c6271d496d6e1b6d10a | [
"Apache-2.0"
] | 4 | 2022-01-23T02:05:42.000Z | 2022-01-26T18:03:34.000Z | wxSnapshot/src/common/statbmpcmn.cpp | KeyWorksRW/wxUiTesting | 249861f72b71221220c95c6271d496d6e1b6d10a | [
"Apache-2.0"
] | null | null | null | /////////////////////////////////////////////////////////////////////////////
// Name: src/common/statbmpcmn.cpp
// Purpose: wxStaticBitmap common code
// Author: Julian Smart
// Modified by:
// Created: 04/01/98
// Copyright: (c) Julian Smart
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// ===========================================================================
// declarations
// ===========================================================================
// ---------------------------------------------------------------------------
// headers
// ---------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#if wxUSE_STATBMP
#include "wx/statbmp.h"
extern WXDLLEXPORT_DATA(const char) wxStaticBitmapNameStr[] = "staticBitmap";
// ---------------------------------------------------------------------------
// XTI
// ---------------------------------------------------------------------------
wxDEFINE_FLAGS( wxStaticBitmapStyle )
wxBEGIN_FLAGS( wxStaticBitmapStyle )
// new style border flags, we put them first to
// use them for streaming out
wxFLAGS_MEMBER(wxBORDER_SIMPLE)
wxFLAGS_MEMBER(wxBORDER_SUNKEN)
wxFLAGS_MEMBER(wxBORDER_DOUBLE)
wxFLAGS_MEMBER(wxBORDER_RAISED)
wxFLAGS_MEMBER(wxBORDER_STATIC)
wxFLAGS_MEMBER(wxBORDER_NONE)
// old style border flags
wxFLAGS_MEMBER(wxSIMPLE_BORDER)
wxFLAGS_MEMBER(wxSUNKEN_BORDER)
wxFLAGS_MEMBER(wxDOUBLE_BORDER)
wxFLAGS_MEMBER(wxRAISED_BORDER)
wxFLAGS_MEMBER(wxSTATIC_BORDER)
wxFLAGS_MEMBER(wxBORDER)
// standard window styles
wxFLAGS_MEMBER(wxTAB_TRAVERSAL)
wxFLAGS_MEMBER(wxCLIP_CHILDREN)
wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW)
wxFLAGS_MEMBER(wxWANTS_CHARS)
wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE)
wxFLAGS_MEMBER(wxALWAYS_SHOW_SB )
wxFLAGS_MEMBER(wxVSCROLL)
wxFLAGS_MEMBER(wxHSCROLL)
wxEND_FLAGS( wxStaticBitmapStyle )
wxIMPLEMENT_DYNAMIC_CLASS_XTI(wxStaticBitmap, wxControl, "wx/statbmp.h");
wxBEGIN_PROPERTIES_TABLE(wxStaticBitmap)
wxPROPERTY_FLAGS( WindowStyle, wxStaticBitmapStyle, long, \
SetWindowStyleFlag, GetWindowStyleFlag, \
wxEMPTY_PARAMETER_VALUE, 0 /*flags*/, wxT("Helpstring"), \
wxT("group")) // style
wxEND_PROPERTIES_TABLE()
wxEMPTY_HANDLERS_TABLE(wxStaticBitmap)
wxCONSTRUCTOR_5( wxStaticBitmap, wxWindow*, Parent, wxWindowID, Id, \
wxBitmap, Bitmap, wxPoint, Position, wxSize, Size )
/*
TODO PROPERTIES :
bitmap
*/
// ----------------------------------------------------------------------------
// wxStaticBitmap
// ----------------------------------------------------------------------------
wxStaticBitmapBase::~wxStaticBitmapBase()
{
// this destructor is required for Darwin
}
wxSize wxStaticBitmapBase::DoGetBestSize() const
{
if ( m_bitmapBundle.IsOk() )
return m_bitmapBundle.GetPreferredLogicalSizeFor(this);
// the fall back size is completely arbitrary
return wxSize(16, 16);
}
wxBitmap wxStaticBitmapBase::GetBitmap() const
{
return m_bitmapBundle.GetBitmapFor(this);
}
// Only wxMSW handles icons and bitmaps differently, in all the other ports
// they are exactly the same thing.
#ifdef wxICON_IS_BITMAP
void wxStaticBitmapBase::SetIcon(const wxIcon& icon)
{
SetBitmap(icon);
}
wxIcon wxStaticBitmapBase::GetIcon() const
{
wxIcon icon;
icon.CopyFromBitmap(GetBitmap());
return icon;
}
#else // !wxICON_IS_BITMAP
// Just provide the stabs for them, they're never used anyhow as they're
// overridden in wxMSW implementation of this class.
void wxStaticBitmapBase::SetIcon(const wxIcon& WXUNUSED(icon))
{
wxFAIL_MSG(wxS("unreachable"));
}
wxIcon wxStaticBitmapBase::GetIcon() const
{
wxFAIL_MSG(wxS("unreachable"));
return wxIcon();
}
#endif // wxICON_IS_BITMAP/!wxICON_IS_BITMAP
#endif // wxUSE_STATBMP
| 28.815603 | 80 | 0.587989 | KeyWorksRW |
a5f0e60549f4018b1fb770c5e73bd0802cec8bec | 125 | cpp | C++ | examples/include_this.cpp | andrewkatson/denarii | ee5f07f43255b02aac521a6ae9715cc7c80eaa65 | [
"MIT"
] | null | null | null | examples/include_this.cpp | andrewkatson/denarii | ee5f07f43255b02aac521a6ae9715cc7c80eaa65 | [
"MIT"
] | null | null | null | examples/include_this.cpp | andrewkatson/denarii | ee5f07f43255b02aac521a6ae9715cc7c80eaa65 | [
"MIT"
] | null | null | null | //
// Created by katso on 2/16/2022.
//
#include "include_this.h"
void include_this::do_something() {
std::string str;
} | 12.5 | 35 | 0.664 | andrewkatson |
a5f1d850499de2b83edf6b5f610bd18b63f83282 | 773 | cpp | C++ | src/processor.cpp | craigstjean/miditabs | 0e8e22ab948883d1fe62ff669b472615739c5fa5 | [
"BSD-3-Clause"
] | null | null | null | src/processor.cpp | craigstjean/miditabs | 0e8e22ab948883d1fe62ff669b472615739c5fa5 | [
"BSD-3-Clause"
] | null | null | null | src/processor.cpp | craigstjean/miditabs | 0e8e22ab948883d1fe62ff669b472615739c5fa5 | [
"BSD-3-Clause"
] | null | null | null | #include <iostream>
#include "processor.h"
#include <antlr4-runtime.h>
#include "TabsLexer.h"
#include "TabsParser.h"
#include "midi_visitor.h"
#include "midi_commands.h"
using namespace antlr4;
void Processor::execute()
{
ANTLRInputStream input(stream);
TabsLexer lexer(&input);
CommonTokenStream tokens(&lexer);
TabsParser parser(&tokens);
TabsParser::TabsContext* tree = parser.tabs();
MidiVisitor visitor;
MidiCommands commands = visitor.visitTabs(tree);
for (auto command : commands.commands())
{
std::cout << *command.get() << std::endl;
}
std::shared_ptr<MidiContext> context = std::make_shared<MidiContext>();
for (auto command : commands.commands())
{
command->execute(context);
}
}
| 20.891892 | 75 | 0.67141 | craigstjean |
a5f3d6ceafefaff233e74736bea050db1943fba1 | 1,968 | hpp | C++ | inst/include/target/utils.hpp | kkholst/gof | 806286ccec6509155e44fb221eb34aaf0b3bfb20 | [
"Apache-2.0"
] | null | null | null | inst/include/target/utils.hpp | kkholst/gof | 806286ccec6509155e44fb221eb34aaf0b3bfb20 | [
"Apache-2.0"
] | null | null | null | inst/include/target/utils.hpp | kkholst/gof | 806286ccec6509155e44fb221eb34aaf0b3bfb20 | [
"Apache-2.0"
] | null | null | null | /*!
@file utils.hpp
@author Klaus K. Holst
@copyright 2020, Klaus Kähler Holst
@brief Various utility functions and constants
*/
#pragma once
#ifndef ARMA_R
#include <armadillo>
#endif
#if defined(ARMA_R)
#include <RcppArmadillo.h>
#endif
#include <cmath>
#include <complex>
#include <cfloat> // precision of double (DBL_MIN)
#include <functional> // std::bind for using non-static member function as argument to free function
namespace target {
using cx_dbl = std::complex<double>;
using cx_func = std::function<arma::cx_mat(arma::cx_vec theta)>;
arma::mat deriv(cx_func f,
arma::vec theta);
arma::umat clusterid(const arma::uvec &id);
arma::mat groupsum(const arma::mat &x,
const arma::uvec &cluster,
bool reduce = true);
void fastpattern(const arma::umat &y,
arma::umat &pattern,
arma::uvec &group,
unsigned categories = 2);
arma::umat fastapprox(arma::vec &time, // sorted times
const arma::vec &newtime,
bool equal = false,
// type: (0: nearedst, 1: right, 2: left)
unsigned type = 0);
double SupTest(const arma::vec &D);
double L2Test(const arma::vec &D,
const arma::vec &t);
double CramerVonMises(const arma::vec &x,
const arma::vec &G);
extern arma::mat const EmptyMat;
extern arma::vec const EmptyVec;
extern const char* COL_RESET;
extern const char* COL_DEF;
extern const char* BLACK;
extern const char* RED;
extern const char* MAGENTA;
extern const char* YELLOW;
extern const char* GREEN;
extern const char* BLUE;
extern const char* CYAN;
extern const char* WHITE;
extern const char* GRAY;
extern const char* LRED;
extern const char* LGREEN;
extern const char* LYELLOW;
extern const char* LBLUE;
extern const char* LMAGENTA;
extern const char* LCYAN;
extern const char* LWHITE;
} // namespace target
| 26.958904 | 101 | 0.64685 | kkholst |
a5f47d29633815c642a55f91d7cee88ee3b84844 | 364 | cpp | C++ | sources/utils/constants.cpp | bobismijnnaam/nutsnbolts | 40191668b0831c64ce23474b9886f8be888916b3 | [
"BSL-1.0",
"Zlib",
"MIT"
] | null | null | null | sources/utils/constants.cpp | bobismijnnaam/nutsnbolts | 40191668b0831c64ce23474b9886f8be888916b3 | [
"BSL-1.0",
"Zlib",
"MIT"
] | null | null | null | sources/utils/constants.cpp | bobismijnnaam/nutsnbolts | 40191668b0831c64ce23474b9886f8be888916b3 | [
"BSL-1.0",
"Zlib",
"MIT"
] | null | null | null | // File: constants.cpp
// Author: Bob Rubbens - Knights of the Compiler
// Creation date: 20150714
// Contact: http://plusminos.nl - @broervanlisa - gmail (bobrubbens)
// Public
// Private
#include "nnb/utils/constants.hpp"
namespace nnb {
#ifdef NNB_WIN
std::string DIRSEP = "\\";
#elif NNB_UNIX
std::string DIRSEP = "/";
#endif
}
| 19.157895 | 68 | 0.637363 | bobismijnnaam |
a5f559354eeb67e2ce81fd607c86be10ab5eabba | 2,011 | hpp | C++ | source/hougfx/include/hou/gfx/glyph.hpp | DavideCorradiDev/houzi-game-engine | d704aa9c5b024300578aafe410b7299c4af4fcec | [
"MIT"
] | 2 | 2018-04-12T20:59:20.000Z | 2018-07-26T16:04:07.000Z | source/hougfx/include/hou/gfx/glyph.hpp | DavideCorradiDev/houzi-game-engine | d704aa9c5b024300578aafe410b7299c4af4fcec | [
"MIT"
] | null | null | null | source/hougfx/include/hou/gfx/glyph.hpp | DavideCorradiDev/houzi-game-engine | d704aa9c5b024300578aafe410b7299c4af4fcec | [
"MIT"
] | null | null | null | // Houzi Game Engine
// Copyright (c) 2018 Davide Corradi
// Licensed under the MIT license.
#ifndef HOU_GFX_GLYPH_HPP
#define HOU_GFX_GLYPH_HPP
#include "hou/gfx/gfx_config.hpp"
#include "hou/gfx/glyph_metrics.hpp"
#include "hou/sys/image.hpp"
#include <iostream>
namespace hou
{
/** Class describing a glyph, including its metrics and its bitmap image.
*/
class HOU_GFX_API glyph
{
public:
/** default constructor.
*
* The image is empty and the metrics are all null.
*
* \throws std::bad_alloc.
*/
glyph();
/** Creates a glyph object with the given image and metrics.
*
* \param im the image.
*
* \param metrics the metrics.
*
* \throws std::bad_alloc.
*/
glyph(const image2_r& im, const glyph_metrics& metrics);
/** Gets the image.
*
* \return the image.
*/
const image2_r& get_image() const noexcept;
/** Sets the image.
*
* \param im the image.
*/
void set_image(const image2_r& im);
/** Gets the metrics.
*
* \return the metrics.
*/
const glyph_metrics& get_metrics() const noexcept;
/** Sets the metrics.
*
* \param metrics the metrics.
*/
void set_metrics(const glyph_metrics& metrics) noexcept;
private:
image2_r m_image;
glyph_metrics m_metrics;
};
/** Checks if two glyph objects are equal.
*
* \param lhs the left operand.
*
* \param rhs the right operand.
*
* \return true if the two objects are equal,
*/
HOU_GFX_API bool operator==(const glyph& lhs, const glyph& rhs) noexcept;
/** Checks if two glyph objects are not equal.
*
* \param lhs the left operand.
*
* \param rhs the right operand.
*
* \return true if the two objects are not equal,
*/
HOU_GFX_API bool operator!=(const glyph& lhs, const glyph& rhs) noexcept;
/** Writes a glyph object into a stream.
*
* \param os the output stream.
*
* \param gm the object.
*
* \return a reference to os.
*/
HOU_GFX_API std::ostream& operator<<(std::ostream& os, const glyph& gm);
} // namespace hou
#endif
| 19.152381 | 73 | 0.664843 | DavideCorradiDev |
a5fb99da87075a57266c3691949444a4004aaa5c | 46,671 | cpp | C++ | unittests/AST/ASTBuilder.cpp | clayne/rellic | 2164f2117224d301698d6af05d3c3492d4f62d06 | [
"Apache-2.0"
] | null | null | null | unittests/AST/ASTBuilder.cpp | clayne/rellic | 2164f2117224d301698d6af05d3c3492d4f62d06 | [
"Apache-2.0"
] | null | null | null | unittests/AST/ASTBuilder.cpp | clayne/rellic | 2164f2117224d301698d6af05d3c3492d4f62d06 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2021-present, Trail of Bits, Inc.
* All rights reserved.
*
* This source code is licensed in accordance with the terms specified in
* the LICENSE file found in the root directory of this source tree.
*/
#include "rellic/AST/ASTBuilder.h"
#include "Util.h"
namespace {
template <typename T>
static clang::DeclRefExpr *GetDeclRef(rellic::ASTBuilder &ast,
clang::DeclContext *decl_ctx,
const std::string &name) {
auto ref{ast.CreateDeclRef(GetDecl<T>(decl_ctx, name))};
REQUIRE(ref != nullptr);
return ref;
}
static void IsNullPtrExprCheck(clang::ASTContext &ctx, clang::Expr *expr) {
CHECK(
expr->isNullPointerConstant(ctx, clang::Expr::NPC_NeverValueDependent) ==
clang::Expr::NPCK_ZeroLiteral);
CHECK(
expr->isNullPointerConstant(ctx, clang::Expr::NPC_ValueDependentIsNull) ==
clang::Expr::NPCK_ZeroLiteral);
CHECK(expr->isNullPointerConstant(ctx,
clang::Expr::NPC_ValueDependentIsNotNull) ==
clang::Expr::NPCK_ZeroLiteral);
}
} // namespace
// TODO(surovic): Add test cases for signed llvm::APInt and group
// via SCENARIO rather than TEST_SUITE. This needs better
// support for value-parametrized tests from doctest. Should be in
// version 2.5.0
TEST_SUITE("ASTBuilder::CreateIntLit") {
SCENARIO("Create clang::IntegerLiteral for 1 bit integer value") {
GIVEN("Empty clang::ASTContext") {
auto unit{GetASTUnit()};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
GIVEN("1 bit unsigned llvm::APInt") {
llvm::APInt api(1U, UINT64_C(0), /*isSigned=*/false);
auto lit{ast.CreateIntLit(api)};
THEN("return a unsigned int typed integer literal") {
REQUIRE(lit != nullptr);
CHECK(clang::isa<clang::IntegerLiteral>(lit));
CHECK(lit->getType() == ctx.UnsignedIntTy);
}
}
}
}
SCENARIO("Create clang::IntegerLiteral for 8 bit integer value") {
GIVEN("Empty clang::ASTContext") {
auto unit{GetASTUnit()};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
GIVEN("8 bit unsigned llvm::APInt") {
llvm::APInt api(8U, UINT64_C(42), /*isSigned=*/false);
THEN("return a unsigned int typed integer literal") {
auto lit{ast.CreateIntLit(api)};
REQUIRE(lit != nullptr);
CHECK(clang::isa<clang::IntegerLiteral>(lit));
CHECK(lit->getType() == ctx.UnsignedIntTy);
}
THEN(
"return a unsigned int typed integer literal casted to unsigned "
"char") {
auto cast{ast.CreateAdjustedIntLit(api)};
REQUIRE(cast != nullptr);
CHECK(clang::isa<clang::CStyleCastExpr>(cast));
CHECK(cast->getType() == ctx.UnsignedCharTy);
auto lit{cast->IgnoreCasts()};
CHECK(clang::isa<clang::IntegerLiteral>(lit));
CHECK(lit->getType() == ctx.UnsignedIntTy);
}
}
}
}
SCENARIO("Create clang::IntegerLiteral for 16 bit integer value") {
GIVEN("Empty clang::ASTContext") {
auto unit{GetASTUnit()};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
GIVEN("16 bits wide llvm::APInt") {
llvm::APInt api(16U, UINT64_C(42), /*isSigned=*/false);
THEN("return a unsigned int typed integer literal") {
auto lit{ast.CreateIntLit(api)};
REQUIRE(lit != nullptr);
CHECK(clang::isa<clang::IntegerLiteral>(lit));
CHECK(lit->getType() == ctx.UnsignedIntTy);
}
THEN(
"return a unsigned int typed integer literal casted to unsigned "
"short") {
auto cast{ast.CreateAdjustedIntLit(api)};
REQUIRE(cast != nullptr);
CHECK(clang::isa<clang::CStyleCastExpr>(cast));
CHECK(cast->getType() == ctx.UnsignedShortTy);
auto lit{cast->IgnoreCasts()};
CHECK(clang::isa<clang::IntegerLiteral>(lit));
CHECK(lit->getType() == ctx.UnsignedIntTy);
}
}
}
}
SCENARIO("Create clang::IntegerLiteral for 32 bit integer value") {
GIVEN("Empty clang::ASTContext") {
auto unit{GetASTUnit()};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
GIVEN("32 bits wide llvm::APInt") {
llvm::APInt api(32U, UINT64_C(42), /*isSigned=*/false);
auto lit{ast.CreateIntLit(api)};
THEN("return a unsigned int typed integer literal") {
REQUIRE(lit != nullptr);
CHECK(clang::isa<clang::IntegerLiteral>(lit));
CHECK(lit->getType() == ctx.UnsignedIntTy);
}
}
}
}
SCENARIO("Create clang::IntegerLiteral for 64 bit integer value") {
GIVEN("Empty clang::ASTContext") {
auto unit{GetASTUnit()};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
GIVEN("64 bits wide llvm::APInt") {
llvm::APInt api(64U, UINT64_C(42), /*isSigned=*/false);
auto lit{ast.CreateIntLit(api)};
THEN("return a unsigned long typed integer literal") {
REQUIRE(lit != nullptr);
CHECK(clang::isa<clang::IntegerLiteral>(lit));
CHECK(lit->getType() == ctx.UnsignedLongTy);
}
}
}
}
SCENARIO("Create clang::IntegerLiteral for 128 bit integer value") {
GIVEN("Empty clang::ASTContext") {
auto unit{GetASTUnit()};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
GIVEN("128 bits wide llvm::APInt") {
llvm::APInt api(128U, UINT64_C(42), /*isSigned=*/false);
THEN("return a unsigned long long typed integer literal") {
auto lit{ast.CreateIntLit(api)};
REQUIRE(lit != nullptr);
CHECK(clang::isa<clang::IntegerLiteral>(lit));
CHECK(lit->getType() == ctx.UnsignedLongLongTy);
}
THEN(
"return a unsigned long long typed integer literal casted to "
"_uint128_t") {
auto cast{ast.CreateAdjustedIntLit(api)};
REQUIRE(cast != nullptr);
CHECK(clang::isa<clang::CStyleCastExpr>(cast));
CHECK(cast->getType() == ctx.UnsignedInt128Ty);
auto lit{cast->IgnoreCasts()};
CHECK(clang::isa<clang::IntegerLiteral>(lit));
CHECK(lit->getType() == ctx.UnsignedLongLongTy);
}
}
}
}
}
TEST_SUITE("ASTBuilder::CreateCharLit") {
SCENARIO("Create clang::CharacterLiteral for 8 bit integer value") {
GIVEN("Empty clang::ASTContext") {
auto unit{GetASTUnit()};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
GIVEN("8 bit wide unsigned llvm::APInt") {
llvm::APInt api(8U, 'x', /*isSigned=*/false);
auto lit{ast.CreateCharLit(api)};
THEN("return a int typed character literal") {
REQUIRE(lit != nullptr);
CHECK(clang::isa<clang::CharacterLiteral>(lit));
CHECK(lit->getType() == ctx.IntTy);
}
}
}
}
}
TEST_SUITE("ASTBuilder::CreateStrLit") {
SCENARIO("Create clang::StringLiteral from std::string") {
GIVEN("Empty clang::ASTContext") {
auto unit{GetASTUnit()};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
GIVEN("std::string object by value") {
std::string str("a string");
auto lit{ast.CreateStrLit(str)};
THEN("return a char[] typed character literal") {
REQUIRE(lit != nullptr);
CHECK(clang::isa<clang::StringLiteral>(lit));
CHECK(lit->getType() ==
ctx.getStringLiteralArrayType(ctx.CharTy, str.size()));
}
}
}
}
}
TEST_SUITE("ASTBuilder::CreateFPLit") {
SCENARIO("Create clang::FloatingLiteral for 32 bit IEEE 754 value") {
GIVEN("Empty clang::ASTContext") {
auto unit{GetASTUnit()};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
GIVEN("float initialized llvm::APFloat") {
auto lit{ast.CreateFPLit(llvm::APFloat(float(3.14)))};
THEN("return a float typed floating point literal") {
REQUIRE(lit != nullptr);
CHECK(clang::isa<clang::FloatingLiteral>(lit));
CHECK(lit->getType() == ctx.FloatTy);
}
}
}
}
SCENARIO("Create clang::FloatingLiteral for 64 bit IEEE 754 value") {
GIVEN("Empty clang::ASTContext") {
auto unit{GetASTUnit()};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
GIVEN("double initialized llvm::APFloat") {
auto lit{ast.CreateFPLit(llvm::APFloat(double(3.14)))};
THEN("return a double typed floating point literal") {
REQUIRE(lit != nullptr);
CHECK(clang::isa<clang::FloatingLiteral>(lit));
CHECK(lit->getType() == ctx.DoubleTy);
}
}
}
}
}
TEST_SUITE("ASTBuilder::CreateNull") {
SCENARIO("Create clang::Expr representing a null pointer") {
GIVEN("Empty clang::ASTContext") {
auto unit{GetASTUnit()};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
THEN("return a 0U integer literal casted to a void pointer") {
auto expr{ast.CreateNull()};
REQUIRE(expr != nullptr);
IsNullPtrExprCheck(ctx, expr);
}
}
}
}
TEST_SUITE("ASTBuilder::CreateUndef") {
SCENARIO("Create clang::Expr to stand in for LLVM's 'undef' values") {
GIVEN("Empty clang::ASTContext") {
auto unit{GetASTUnit()};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
GIVEN("an unsigned integer type") {
auto type{ctx.UnsignedIntTy};
THEN(
"return a value that satisfied LLVM's undef semantics (aka "
"anything)") {
auto expr{ast.CreateUndefInteger(type)};
REQUIRE(expr != nullptr);
CHECK(expr->getType() == ctx.UnsignedIntTy);
}
}
GIVEN("an arbitrary type t") {
auto type{ctx.DoubleTy};
THEN("return an undef pointer (we use null pointers) of type t") {
auto expr{ast.CreateUndefPointer(type)};
REQUIRE(expr != nullptr);
auto double_ptr_ty{ctx.getPointerType(ctx.DoubleTy)};
CHECK(expr->getType() == double_ptr_ty);
IsNullPtrExprCheck(ctx, expr->IgnoreCasts());
}
}
}
}
}
TEST_SUITE("ASTBuilder::CreateCStyleCast") {
SCENARIO("Create a CK_NullToPointer kind clang::CStyleCastExpr") {
GIVEN("Empty clang::ASTContext") {
auto unit{GetASTUnit()};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
GIVEN("a 0U literal") {
auto lit{ast.CreateIntLit(llvm::APInt(32, 0))};
REQUIRE(lit != nullptr);
REQUIRE(lit->getType() == ctx.UnsignedIntTy);
GIVEN("a void * type") {
auto void_ptr_ty{ctx.VoidPtrTy};
THEN("return an null-to-pointer cast to void *") {
auto nullptr_cast{ast.CreateCStyleCast(void_ptr_ty, lit)};
REQUIRE(nullptr_cast != nullptr);
CHECK(nullptr_cast->getType() == void_ptr_ty);
CHECK(nullptr_cast->getCastKind() ==
clang::CastKind::CK_NullToPointer);
}
}
}
}
}
SCENARIO("Create a CK_BitCast kind clang::CStyleCastExpr") {
GIVEN("Empty clang::ASTContext") {
auto unit{GetASTUnit()};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
GIVEN("a void * type expression") {
auto void_ty_expr{ast.CreateNull()};
REQUIRE(void_ty_expr != nullptr);
REQUIRE(void_ty_expr->getType() == ctx.VoidPtrTy);
GIVEN("a pointer type int *") {
auto int_ptr_ty{ctx.getPointerType(ctx.IntTy)};
THEN("return a bitcast to int *") {
auto bitcast{ast.CreateCStyleCast(int_ptr_ty, void_ty_expr)};
REQUIRE(bitcast != nullptr);
CHECK(bitcast->getType() == int_ptr_ty);
CHECK(bitcast->getCastKind() == clang::CastKind::CK_BitCast);
}
}
}
}
}
SCENARIO("Create a CK_IntegralCast kind clang::CStyleCastExpr") {
GIVEN("Empty clang::ASTContext") {
auto unit{GetASTUnit()};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
GIVEN("an integer literal") {
auto lit{ast.CreateIntLit(llvm::APInt(8, 0xff))};
REQUIRE(lit != nullptr);
REQUIRE(lit->getType() == ctx.UnsignedIntTy);
GIVEN("a unsigned long int type") {
auto ulong_ty{ctx.UnsignedLongTy};
THEN("return an integeral cast to unsigned long int") {
auto intcast{ast.CreateCStyleCast(ulong_ty, lit)};
REQUIRE(intcast != nullptr);
CHECK(intcast->getType() == ulong_ty);
CHECK(intcast->getCastKind() == clang::CastKind::CK_IntegralCast);
}
}
}
}
}
SCENARIO("Create a CK_PointerToIntegral kind clang::CStyleCastExpr") {
GIVEN("Empty clang::ASTContext") {
auto unit{GetASTUnit()};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
GIVEN("a null pointer expression") {
auto null{ast.CreateNull()};
REQUIRE(null != nullptr);
GIVEN("an unsigned int type") {
auto int_ty{ctx.UnsignedIntTy};
THEN("return an pointer-to-integral cast to unsigned int") {
auto ptr2int_cast{ast.CreateCStyleCast(int_ty, null)};
REQUIRE(ptr2int_cast != nullptr);
CHECK(ptr2int_cast->getType() == int_ty);
CHECK(ptr2int_cast->getCastKind() ==
clang::CastKind::CK_PointerToIntegral);
}
}
}
}
}
SCENARIO("Create a CK_IntegralToPointer kind clang::CStyleCastExpr") {
GIVEN("Empty clang::ASTContext") {
auto unit{GetASTUnit()};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
GIVEN("an integer literal") {
auto lit{ast.CreateIntLit(llvm::APInt(16, 0xbeef))};
REQUIRE(lit != nullptr);
GIVEN("a unsigned int * type") {
auto uint_ptr_ty{ctx.getPointerType(ctx.UnsignedIntTy)};
THEN("return an integral-to-pointer cast to unsigned int *") {
auto int2ptr_cast{ast.CreateCStyleCast(uint_ptr_ty, lit)};
REQUIRE(int2ptr_cast != nullptr);
CHECK(int2ptr_cast->getType() == uint_ptr_ty);
CHECK(int2ptr_cast->getCastKind() ==
clang::CastKind::CK_IntegralToPointer);
}
}
}
}
}
SCENARIO("Create a CK_FloatingCast kind clang::CStyleCastExpr") {
GIVEN("Empty clang::ASTContext") {
auto unit{GetASTUnit()};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
GIVEN("a float type literal") {
auto lit{ast.CreateFPLit(llvm::APFloat(float(3.14)))};
REQUIRE(lit != nullptr);
GIVEN("a double type") {
auto double_ty{ctx.DoubleTy};
THEN("return a floating cast to double") {
auto fp_cast{ast.CreateCStyleCast(double_ty, lit)};
REQUIRE(fp_cast != nullptr);
CHECK(fp_cast->getType() == double_ty);
CHECK(fp_cast->getCastKind() == clang::CastKind::CK_FloatingCast);
}
}
}
}
}
SCENARIO("Create a CK_IntegralToFloating kind clang::CStyleCastExpr") {
GIVEN("Empty clang::ASTContext") {
auto unit{GetASTUnit()};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
GIVEN("an integer literal") {
auto lit{ast.CreateIntLit(llvm::APInt(16, 0xdead))};
REQUIRE(lit != nullptr);
GIVEN("a float type") {
auto float_ty{ctx.FloatTy};
THEN("return a integral-to-floating cast to float") {
auto int2fp_cast{ast.CreateCStyleCast(float_ty, lit)};
REQUIRE(int2fp_cast != nullptr);
CHECK(int2fp_cast->getType() == float_ty);
CHECK(int2fp_cast->getCastKind() ==
clang::CastKind::CK_IntegralToFloating);
}
}
}
}
}
SCENARIO("Create a CK_FloatingToIntegral clang::CStyleCastExpr") {
GIVEN("Empty clang::ASTContext") {
auto unit{GetASTUnit()};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
GIVEN("a double type literal") {
auto lit{ast.CreateFPLit(llvm::APFloat(double(3.14)))};
REQUIRE(lit != nullptr);
GIVEN("an unsigned long int type") {
auto ulong_ty{ctx.UnsignedLongTy};
THEN("return a floating-to-integral cast to unsigned long int") {
auto fp2int_cast{ast.CreateCStyleCast(ulong_ty, lit)};
REQUIRE(fp2int_cast != nullptr);
CHECK(fp2int_cast->getType() == ulong_ty);
CHECK(fp2int_cast->getCastKind() ==
clang::CastKind::CK_FloatingToIntegral);
}
}
}
}
}
}
TEST_SUITE("ASTBuilder::CreateVarDecl") {
SCENARIO("Create a global clang::VarDecl") {
GIVEN("Empty translation unit") {
auto unit{GetASTUnit()};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
auto tudecl{ctx.getTranslationUnitDecl()};
THEN("return an unsigned int global variable my_var") {
auto type{ctx.UnsignedIntTy};
auto vardecl{ast.CreateVarDecl(tudecl, type, "my_var")};
REQUIRE(vardecl != nullptr);
CHECK(vardecl->getType() == type);
CHECK(vardecl->hasGlobalStorage());
CHECK(!vardecl->isStaticLocal());
CHECK(vardecl->getName() == "my_var");
}
}
}
SCENARIO("Create a function local clang::VarDecl") {
GIVEN("Function definition void f(){}") {
auto unit{GetASTUnit("void f(){}")};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
auto tudecl{ctx.getTranslationUnitDecl()};
auto fdecl{GetDecl<clang::FunctionDecl>(tudecl, "f")};
REQUIRE(fdecl->hasBody());
THEN("return a int variable my_var declared in f") {
auto type{ctx.IntTy};
auto vardecl{ast.CreateVarDecl(fdecl, type, "my_var")};
REQUIRE(vardecl != nullptr);
CHECK(vardecl->getType() == type);
CHECK(vardecl->isLocalVarDecl());
CHECK(vardecl->getName() == "my_var");
}
}
}
}
TEST_SUITE("ASTBuilder::CreateFunctionDecl") {
SCENARIO("Create a clang::FunctionDecl") {
GIVEN("Empty translation unit") {
auto unit{GetASTUnit("")};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
auto tudecl{ctx.getTranslationUnitDecl()};
THEN("return a function declaration void f()") {
auto type{ctx.getFunctionType(
ctx.VoidTy, {}, clang::FunctionProtoType::ExtProtoInfo())};
auto fdecl{ast.CreateFunctionDecl(tudecl, type, "f")};
REQUIRE(fdecl != nullptr);
CHECK(fdecl->getName() == "f");
CHECK(fdecl->getType() == type);
}
}
}
}
TEST_SUITE("ASTBuilder::CreateParamDecl") {
SCENARIO("Create a clang::ParmVarDecl") {
GIVEN("Function definition void f(){}") {
auto unit{GetASTUnit("void f(){}")};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
auto tudecl{ctx.getTranslationUnitDecl()};
auto fdecl{GetDecl<clang::FunctionDecl>(tudecl, "f")};
THEN("return a parameter declaration p of void f(int p){}") {
auto pdecl{ast.CreateParamDecl(fdecl, ctx.IntTy, "p")};
REQUIRE(pdecl != nullptr);
CHECK(pdecl->getName() == "p");
CHECK(pdecl->getType() == ctx.IntTy);
}
}
}
}
TEST_SUITE("ASTBuilder::CreateStructDecl") {
SCENARIO("Create a clang::RecordDecl") {
GIVEN("Empty translation unit") {
auto unit{GetASTUnit()};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
auto tudecl{ctx.getTranslationUnitDecl()};
THEN("return an empty structure s") {
auto record_decl{ast.CreateStructDecl(tudecl, "s")};
REQUIRE(record_decl != nullptr);
CHECK(record_decl->getName() == "s");
CHECK(record_decl->getTagKind() ==
clang::RecordDecl::TagKind::TTK_Struct);
}
}
}
}
TEST_SUITE("ASTBuilder::CreateUnionDecl") {
SCENARIO("Create a clang::RecordDecl") {
GIVEN("Empty translation unit") {
auto unit{GetASTUnit()};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
auto tudecl{ctx.getTranslationUnitDecl()};
THEN("return an empty union u") {
auto record_decl{ast.CreateUnionDecl(tudecl, "u")};
REQUIRE(record_decl != nullptr);
CHECK(record_decl->getName() == "u");
CHECK(record_decl->getTagKind() ==
clang::RecordDecl::TagKind::TTK_Union);
}
}
}
}
TEST_SUITE("ASTBuilder::CreateFieldDecl") {
SCENARIO("Create a clang::FieldDecl") {
GIVEN("Structure definition s") {
auto unit{GetASTUnit("struct s{};")};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
auto tudecl{ctx.getTranslationUnitDecl()};
auto record_decl{GetDecl<clang::RecordDecl>(tudecl, "s")};
REQUIRE(record_decl->field_empty());
THEN("return structure s with member int f") {
auto type{ctx.IntTy};
auto field_decl{ast.CreateFieldDecl(record_decl, type, "f")};
REQUIRE(field_decl != nullptr);
CHECK(field_decl->getType() == type);
CHECK(field_decl->getName() == "f");
}
}
}
SCENARIO("Create a bitfield clang::FieldDecl") {
GIVEN("Structure definition s") {
auto unit{GetASTUnit("struct s{};")};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
auto tudecl{ctx.getTranslationUnitDecl()};
auto record_decl{GetDecl<clang::RecordDecl>(tudecl, "s")};
REQUIRE(record_decl->field_empty());
THEN("return structure s with member int f with size 3") {
auto type{ctx.IntTy};
auto field_decl{ast.CreateFieldDecl(record_decl, type, "f", 3)};
REQUIRE(field_decl != nullptr);
CHECK(field_decl->getType() == type);
CHECK(field_decl->getName() == "f");
CHECK(field_decl->getBitWidthValue(ctx) == 3);
}
}
}
}
TEST_SUITE("ASTBuilder::CreateDeclStmt") {
SCENARIO("Create a clang::DeclStmt to a function local clang::VarDecl") {
GIVEN("Funtion with a local variable declaration") {
auto unit{GetASTUnit("void f(){}")};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
auto tudecl{ctx.getTranslationUnitDecl()};
auto fdecl{GetDecl<clang::FunctionDecl>(tudecl, "f")};
REQUIRE(fdecl->hasBody());
GIVEN("a int variable my_var declared in f") {
auto vardecl{ast.CreateVarDecl(fdecl, ctx.IntTy, "my_var")};
THEN("return a declaration statement for my_var") {
auto declstmt{ast.CreateDeclStmt(vardecl)};
REQUIRE(declstmt != nullptr);
CHECK(declstmt->isSingleDecl());
CHECK(declstmt->getSingleDecl() == vardecl);
}
}
}
}
}
TEST_SUITE("ASTBuilder::CreateDeclRef") {
SCENARIO("Create a clang::DeclRef to a global clang::VarDecl") {
GIVEN("Global variable int a;") {
auto unit{GetASTUnit("int a;")};
rellic::ASTBuilder ast(*unit);
auto tudecl{unit->getASTContext().getTranslationUnitDecl()};
auto vardecl{GetDecl<clang::VarDecl>(tudecl, "a")};
THEN("return a declaration reference to a") {
auto declref{ast.CreateDeclRef(vardecl)};
REQUIRE(declref != nullptr);
CHECK(declref->getDecl() == vardecl);
}
}
}
}
TEST_SUITE("ASTBuilder::CreateParen") {
SCENARIO("Create parenthesis around an expression") {
GIVEN("Global variable int a;") {
auto unit{GetASTUnit("int a;")};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
auto tudecl{ctx.getTranslationUnitDecl()};
GIVEN("a reference to a") {
auto declref{GetDeclRef<clang::VarDecl>(ast, tudecl, "a")};
THEN("return (a)") {
auto paren{ast.CreateParen(declref)};
REQUIRE(paren != nullptr);
CHECK(paren->getSubExpr() == declref);
CHECK(paren->getType() == declref->getType());
}
}
}
}
}
TEST_SUITE("ASTBuilder::CreateUnaryOperator") {
SCENARIO("Create a pointer dereference operation") {
GIVEN("Empty clang::ASTContext") {
auto unit{GetASTUnit()};
rellic::ASTBuilder ast(*unit);
GIVEN("a void * type expression e") {
auto expr{ast.CreateNull()};
REQUIRE(expr != nullptr);
THEN("return *e") {
auto deref{ast.CreateDeref(expr)};
REQUIRE(deref != nullptr);
CHECK(deref->getSubExpr() == expr);
CHECK(deref->getType() == expr->getType()->getPointeeType());
CHECK(deref->getOpcode() == clang::UO_Deref);
}
}
}
}
SCENARIO("Create a pointer address-of operation") {
GIVEN("Global variable int a;") {
auto unit{GetASTUnit("int a;")};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
auto tudecl{ctx.getTranslationUnitDecl()};
GIVEN("a reference to a") {
auto declref{GetDeclRef<clang::VarDecl>(ast, tudecl, "a")};
THEN("return &a") {
auto addrof{ast.CreateAddrOf(declref)};
REQUIRE(addrof != nullptr);
auto subexpr{addrof->getSubExpr()};
CHECK(subexpr == declref);
CHECK(addrof->getType() == ctx.getPointerType(declref->getType()));
CHECK(addrof->getOpcode() == clang::UO_AddrOf);
}
}
}
}
SCENARIO("Create a logical negation operation") {
GIVEN("Global variable int a;") {
auto unit{GetASTUnit("int a;")};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
auto tudecl{ctx.getTranslationUnitDecl()};
GIVEN("a reference to a") {
auto declref{GetDeclRef<clang::VarDecl>(ast, tudecl, "a")};
THEN("return !a") {
auto lnot{ast.CreateLNot(declref)};
REQUIRE(lnot != nullptr);
auto subexpr{lnot->getSubExpr()};
CHECK(clang::isa<clang::ImplicitCastExpr>(subexpr));
CHECK(subexpr->Classify(ctx).isRValue());
CHECK(subexpr->IgnoreImpCasts() == declref);
CHECK(lnot->getType() == ctx.IntTy);
CHECK(lnot->getOpcode() == clang::UO_LNot);
}
}
}
}
SCENARIO("Create a pointer bitwise negation operation") {
GIVEN("Global variable int a;") {
auto unit{GetASTUnit("int a;")};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
auto tudecl{ctx.getTranslationUnitDecl()};
GIVEN("a reference to a") {
auto declref{GetDeclRef<clang::VarDecl>(ast, tudecl, "a")};
THEN("return ~a") {
auto bnot{ast.CreateNot(declref)};
REQUIRE(bnot != nullptr);
auto subexpr{bnot->getSubExpr()};
CHECK(clang::isa<clang::ImplicitCastExpr>(subexpr));
CHECK(subexpr->Classify(ctx).isRValue());
CHECK(subexpr->IgnoreImpCasts() == declref);
CHECK(bnot->getType() == declref->getType());
CHECK(bnot->getOpcode() == clang::UO_Not);
}
}
}
}
}
TEST_SUITE("ASTBuilder::CreateBinaryOp") {
static void CheckBinOp(clang::BinaryOperator * op, clang::Expr * lhs,
clang::Expr * rhs, clang::QualType type) {
REQUIRE(op != nullptr);
CHECK(op->getLHS()->IgnoreImpCasts() == lhs);
CHECK(op->getRHS()->IgnoreImpCasts() == rhs);
CHECK(op->getType() == type);
}
static void CheckRelOp(clang::BinaryOperator * op, clang::Expr * lhs,
clang::Expr * rhs, clang::QualType type) {
CheckBinOp(op, lhs, rhs, type);
CHECK(op->getLHS()->getType() == op->getRHS()->getType());
}
SCENARIO("Create logical and comparison operations") {
GIVEN("Global variables int a, b; short c; long d;") {
auto unit{GetASTUnit("int a,b; short c; long d;")};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
auto tudecl{ctx.getTranslationUnitDecl()};
GIVEN("references to a, b, c and d") {
auto ref_a{GetDeclRef<clang::VarDecl>(ast, tudecl, "a")};
auto ref_b{GetDeclRef<clang::VarDecl>(ast, tudecl, "b")};
auto ref_c{GetDeclRef<clang::VarDecl>(ast, tudecl, "c")};
auto ref_d{GetDeclRef<clang::VarDecl>(ast, tudecl, "d")};
// BO_LAnd
THEN("return a && b") {
auto land{ast.CreateLAnd(ref_a, ref_b)};
CheckBinOp(land, ref_a, ref_b, ctx.IntTy);
CHECK(land->getLHS()->getType() == land->getRHS()->getType());
}
THEN("return a && c") {
auto land{ast.CreateLAnd(ref_a, ref_c)};
CheckBinOp(land, ref_a, ref_c, ctx.IntTy);
CHECK(land->getLHS()->getType() == land->getRHS()->getType());
}
THEN("return d && b") {
auto land{ast.CreateLAnd(ref_d, ref_b)};
CheckBinOp(land, ref_d, ref_b, ctx.IntTy);
}
// BO_LOr
THEN("return a || b") {
auto lor{ast.CreateLOr(ref_a, ref_b)};
CheckBinOp(lor, ref_a, ref_b, ctx.IntTy);
CHECK(lor->getLHS()->getType() == lor->getRHS()->getType());
}
THEN("return a || c") {
auto lor{ast.CreateLOr(ref_a, ref_c)};
CheckBinOp(lor, ref_a, ref_c, ctx.IntTy);
CHECK(lor->getLHS()->getType() == lor->getRHS()->getType());
}
THEN("return d || b") {
auto lor{ast.CreateLOr(ref_d, ref_b)};
CheckBinOp(lor, ref_d, ref_b, ctx.IntTy);
}
// BO_EQ
THEN("return a == b") {
CheckRelOp(ast.CreateEQ(ref_a, ref_b), ref_a, ref_b, ctx.IntTy);
}
THEN("return a == c") {
CheckRelOp(ast.CreateEQ(ref_a, ref_c), ref_a, ref_c, ctx.IntTy);
}
THEN("return d == b") {
CheckRelOp(ast.CreateEQ(ref_d, ref_b), ref_d, ref_b, ctx.IntTy);
}
// BO_NE
THEN("return a != b") {
CheckRelOp(ast.CreateNE(ref_a, ref_b), ref_a, ref_b, ctx.IntTy);
}
THEN("return a != c") {
CheckRelOp(ast.CreateNE(ref_a, ref_c), ref_a, ref_c, ctx.IntTy);
}
THEN("return d != b") {
CheckRelOp(ast.CreateNE(ref_d, ref_b), ref_d, ref_b, ctx.IntTy);
}
// BO_GE
THEN("return a >= b") {
CheckRelOp(ast.CreateGE(ref_a, ref_b), ref_a, ref_b, ctx.IntTy);
}
THEN("return a >= c") {
CheckRelOp(ast.CreateGE(ref_a, ref_c), ref_a, ref_c, ctx.IntTy);
}
THEN("return d >= b") {
CheckRelOp(ast.CreateGE(ref_d, ref_b), ref_d, ref_b, ctx.IntTy);
}
// BO_GT
THEN("return a > b") {
CheckRelOp(ast.CreateGT(ref_a, ref_b), ref_a, ref_b, ctx.IntTy);
}
THEN("return a > c") {
CheckRelOp(ast.CreateGT(ref_a, ref_c), ref_a, ref_c, ctx.IntTy);
}
THEN("return d > b") {
CheckRelOp(ast.CreateGT(ref_d, ref_b), ref_d, ref_b, ctx.IntTy);
}
// BO_LE
THEN("return a <= b") {
CheckRelOp(ast.CreateLE(ref_a, ref_b), ref_a, ref_b, ctx.IntTy);
}
THEN("return a <= c") {
CheckRelOp(ast.CreateLE(ref_a, ref_c), ref_a, ref_c, ctx.IntTy);
}
THEN("return d <= b") {
CheckRelOp(ast.CreateLE(ref_d, ref_b), ref_d, ref_b, ctx.IntTy);
}
// BO_LT
THEN("return a < b") {
CheckRelOp(ast.CreateLT(ref_a, ref_b), ref_a, ref_b, ctx.IntTy);
}
THEN("return a < c") {
CheckRelOp(ast.CreateLT(ref_a, ref_c), ref_a, ref_c, ctx.IntTy);
}
THEN("return d < b") {
CheckRelOp(ast.CreateLT(ref_d, ref_b), ref_d, ref_b, ctx.IntTy);
}
}
}
}
static void CheckArithOp(clang::BinaryOperator * op, clang::Expr * lhs,
clang::Expr * rhs, clang::QualType type) {
CheckRelOp(op, lhs, rhs, type);
}
SCENARIO("Create bitwise arithmetic operations") {
GIVEN("Global variables int a, b; short c; long d;") {
auto unit{GetASTUnit("int a,b; short c; long d;")};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
auto tudecl{ctx.getTranslationUnitDecl()};
GIVEN("references to a, b, c and d") {
auto ref_a{GetDeclRef<clang::VarDecl>(ast, tudecl, "a")};
auto ref_b{GetDeclRef<clang::VarDecl>(ast, tudecl, "b")};
auto ref_c{GetDeclRef<clang::VarDecl>(ast, tudecl, "c")};
auto ref_d{GetDeclRef<clang::VarDecl>(ast, tudecl, "d")};
// BO_And
THEN("return a & b") {
CheckArithOp(ast.CreateAnd(ref_a, ref_b), ref_a, ref_b, ctx.IntTy);
}
THEN("return a & c") {
CheckArithOp(ast.CreateAnd(ref_a, ref_c), ref_a, ref_c, ctx.IntTy);
}
THEN("return d & b") {
CheckBinOp(ast.CreateAnd(ref_d, ref_b), ref_d, ref_b, ctx.LongTy);
}
// BO_Or
THEN("return a | b") {
CheckArithOp(ast.CreateOr(ref_a, ref_b), ref_a, ref_b, ctx.IntTy);
}
THEN("return a | c") {
CheckArithOp(ast.CreateOr(ref_a, ref_c), ref_a, ref_c, ctx.IntTy);
}
THEN("return d | b") {
CheckBinOp(ast.CreateOr(ref_d, ref_b), ref_d, ref_b, ctx.LongTy);
}
// BO_Xor
THEN("return a ^ b") {
CheckArithOp(ast.CreateXor(ref_a, ref_b), ref_a, ref_b, ctx.IntTy);
}
THEN("return a ^ c") {
CheckArithOp(ast.CreateXor(ref_a, ref_c), ref_a, ref_c, ctx.IntTy);
}
THEN("return d ^ b") {
CheckBinOp(ast.CreateXor(ref_d, ref_b), ref_d, ref_b, ctx.LongTy);
}
// BO_Shl
THEN("return a << b") {
CheckArithOp(ast.CreateShl(ref_a, ref_b), ref_a, ref_b, ctx.IntTy);
}
THEN("return a << c") {
CheckArithOp(ast.CreateShl(ref_a, ref_c), ref_a, ref_c, ctx.IntTy);
}
THEN("return d << b") {
CheckBinOp(ast.CreateShl(ref_d, ref_b), ref_d, ref_b, ctx.LongTy);
}
// BO_Shr
THEN("return a >> b") {
CheckArithOp(ast.CreateShr(ref_a, ref_b), ref_a, ref_b, ctx.IntTy);
}
THEN("return a >> c") {
CheckArithOp(ast.CreateShr(ref_a, ref_c), ref_a, ref_c, ctx.IntTy);
}
THEN("return d >> b") {
CheckBinOp(ast.CreateShr(ref_d, ref_b), ref_d, ref_b, ctx.LongTy);
}
}
}
}
SCENARIO("Create integer arithmetic operations") {
GIVEN("Global variables int a, b; short c; long d;") {
auto unit{GetASTUnit("int a,b; short c; long d;")};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
auto tudecl{ctx.getTranslationUnitDecl()};
GIVEN("references to a, b, c and d") {
auto ref_a{GetDeclRef<clang::VarDecl>(ast, tudecl, "a")};
auto ref_b{GetDeclRef<clang::VarDecl>(ast, tudecl, "b")};
auto ref_c{GetDeclRef<clang::VarDecl>(ast, tudecl, "c")};
auto ref_d{GetDeclRef<clang::VarDecl>(ast, tudecl, "d")};
// BO_Add
THEN("return a + b") {
CheckArithOp(ast.CreateAdd(ref_a, ref_b), ref_a, ref_b, ctx.IntTy);
}
THEN("return a + c") {
CheckArithOp(ast.CreateAdd(ref_a, ref_c), ref_a, ref_c, ctx.IntTy);
}
THEN("return d + b") {
CheckBinOp(ast.CreateAdd(ref_d, ref_b), ref_d, ref_b, ctx.LongTy);
}
// BO_Add
THEN("return a - b") {
CheckArithOp(ast.CreateSub(ref_a, ref_b), ref_a, ref_b, ctx.IntTy);
}
THEN("return a - c") {
CheckArithOp(ast.CreateSub(ref_a, ref_c), ref_a, ref_c, ctx.IntTy);
}
THEN("return d - b") {
CheckBinOp(ast.CreateSub(ref_d, ref_b), ref_d, ref_b, ctx.LongTy);
}
// BO_Mul
THEN("return a * b") {
CheckArithOp(ast.CreateMul(ref_a, ref_b), ref_a, ref_b, ctx.IntTy);
}
THEN("return a * c") {
CheckArithOp(ast.CreateMul(ref_a, ref_c), ref_a, ref_c, ctx.IntTy);
}
THEN("return d * b") {
CheckBinOp(ast.CreateMul(ref_d, ref_b), ref_d, ref_b, ctx.LongTy);
}
// BO_Div
THEN("return a / b") {
CheckArithOp(ast.CreateDiv(ref_a, ref_b), ref_a, ref_b, ctx.IntTy);
}
THEN("return a / c") {
CheckArithOp(ast.CreateDiv(ref_a, ref_c), ref_a, ref_c, ctx.IntTy);
}
THEN("return d / b") {
CheckBinOp(ast.CreateDiv(ref_d, ref_b), ref_d, ref_b, ctx.LongTy);
}
// BO_Rem
THEN("return a % b") {
CheckArithOp(ast.CreateRem(ref_a, ref_b), ref_a, ref_b, ctx.IntTy);
}
THEN("return a % c") {
CheckArithOp(ast.CreateRem(ref_a, ref_c), ref_a, ref_c, ctx.IntTy);
}
THEN("return d % b") {
CheckBinOp(ast.CreateRem(ref_d, ref_b), ref_d, ref_b, ctx.LongTy);
}
// BO_Assign
THEN("return a = b") {
CheckArithOp(ast.CreateAssign(ref_a, ref_b), ref_a, ref_b, ctx.IntTy);
}
THEN("return a = c") {
CheckArithOp(ast.CreateAssign(ref_a, ref_c), ref_a, ref_c, ctx.IntTy);
}
THEN("return d = b") {
CheckBinOp(ast.CreateAssign(ref_d, ref_b), ref_d, ref_b, ctx.LongTy);
}
}
}
}
}
TEST_SUITE("ASTBuilder::CreateConditional") {
SCENARIO("Create a ternary conditional operation") {
GIVEN("Global variables int a,b,c;") {
auto unit{GetASTUnit("int a,b,c;")};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
auto tudecl{ctx.getTranslationUnitDecl()};
GIVEN("references to a, b and c") {
auto ref_a{GetDeclRef<clang::VarDecl>(ast, tudecl, "a")};
auto ref_b{GetDeclRef<clang::VarDecl>(ast, tudecl, "b")};
auto ref_c{GetDeclRef<clang::VarDecl>(ast, tudecl, "c")};
THEN("return a ? b : c") {
auto ite{ast.CreateConditional(ref_a, ref_b, ref_c)};
REQUIRE(ite != nullptr);
CHECK(ite->getType() == ctx.IntTy);
CHECK(ite->getCond()->IgnoreImpCasts() == ref_a);
CHECK(ite->getLHS()->IgnoreImpCasts() == ref_b);
CHECK(ite->getRHS()->IgnoreImpCasts() == ref_c);
}
}
}
}
}
TEST_SUITE("ASTBuilder::CreateArraySub") {
SCENARIO("Create an array subscript operation") {
GIVEN("Global variable const char a[] = \"Hello\";") {
auto unit{GetASTUnit("const char a[] = \"Hello\";")};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
auto tudecl{ctx.getTranslationUnitDecl()};
GIVEN("reference to a and a 1U literal") {
auto ref_a{GetDeclRef<clang::VarDecl>(ast, tudecl, "a")};
auto lit{ast.CreateIntLit(llvm::APInt(32U, 1U))};
REQUIRE(lit != nullptr);
THEN("return a[1U]") {
auto array_sub{ast.CreateArraySub(ref_a, lit)};
CHECK(array_sub != nullptr);
}
}
}
}
}
TEST_SUITE("ASTBuilder::CreateCall") {
SCENARIO("Create a call operation") {
GIVEN("Function declaration void f(int a, int b);") {
auto unit{GetASTUnit("void f(int a, int b);")};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
auto tudecl{ctx.getTranslationUnitDecl()};
auto func{GetDeclRef<clang::FunctionDecl>(ast, tudecl, "f")};
GIVEN("integer literals 4U and 1U") {
auto lit_4{ast.CreateIntLit(llvm::APInt(32U, 4U))};
auto lit_1{ast.CreateIntLit(llvm::APInt(32U, 1U))};
REQUIRE(lit_4 != nullptr);
REQUIRE(lit_1 != nullptr);
THEN("return f(4U, 1U)") {
std::vector<clang::Expr *> args{lit_4, lit_1};
auto call{ast.CreateCall(func, args)};
CHECK(call != nullptr);
CHECK(call->getCallee()->IgnoreImpCasts() == func);
CHECK(call->getArg(0)->IgnoreImpCasts() == lit_4);
CHECK(call->getArg(1)->IgnoreImpCasts() == lit_1);
}
}
}
}
}
TEST_SUITE("ASTBuilder::CreateFieldAcc") {
SCENARIO("Create a structure field access operations") {
GIVEN("Structure declaration struct pair{int a; int b;}; struct pair p;") {
auto unit{GetASTUnit("struct pair{int a; int b;}; struct pair p;")};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
auto tudecl{ctx.getTranslationUnitDecl()};
auto ref{GetDeclRef<clang::VarDecl>(ast, tudecl, "p")};
auto sdecl{GetDecl<clang::RecordDecl>(tudecl, "pair")};
THEN("return p.a") {
auto field_a{GetDecl<clang::FieldDecl>(sdecl, "a")};
auto member{ast.CreateDot(ref, field_a)};
CHECK(member != nullptr);
}
THEN("return (&p)->b") {
auto field_b{GetDecl<clang::FieldDecl>(sdecl, "b")};
auto member{ast.CreateArrow(ast.CreateAddrOf(ref), field_b)};
CHECK(member != nullptr);
}
}
}
}
TEST_SUITE("ASTBuilder::CreateInitList") {
SCENARIO("Create a initializer list expression") {
GIVEN("Global variables int a; short b; char c;") {
auto unit{GetASTUnit("int a; short b; char c;")};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
auto tudecl{ctx.getTranslationUnitDecl()};
GIVEN("references to a, b and c") {
auto ref_a{GetDeclRef<clang::VarDecl>(ast, tudecl, "a")};
auto ref_b{GetDeclRef<clang::VarDecl>(ast, tudecl, "b")};
auto ref_c{GetDeclRef<clang::VarDecl>(ast, tudecl, "c")};
THEN("return {a, b, c}") {
std::vector<clang::Expr *> exprs{ref_a, ref_b, ref_c};
auto init_list{ast.CreateInitList(exprs)};
REQUIRE(init_list != nullptr);
CHECK(init_list->isSemanticForm());
CHECK(init_list->end() - init_list->begin() == 3U);
}
}
}
}
}
TEST_SUITE("ASTBuilder::CreateCompoundLit") {
SCENARIO("Create a compound literal expression") {
GIVEN("An empty initializer list expression") {
auto unit{GetASTUnit("")};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
std::vector<clang::Expr *> exprs;
auto init_list{ast.CreateInitList(exprs)};
GIVEN("int[] type") {
auto type{ctx.getIncompleteArrayType(
ctx.IntTy, clang::ArrayType::ArraySizeModifier(), 0)};
THEN("return (int[]){}") {
auto comp_lit{ast.CreateCompoundLit(type, init_list)};
REQUIRE(comp_lit != nullptr);
CHECK(comp_lit->getTypeSourceInfo()->getType() == type);
}
}
}
}
}
TEST_SUITE("ASTBuilder::CreateCompoundStmt") {
SCENARIO("Create a compound statement") {
GIVEN("Global variables int a; short b; char c;") {
auto unit{GetASTUnit("int a; short b; char c;")};
auto &ctx{unit->getASTContext()};
rellic::ASTBuilder ast(*unit);
auto tudecl{ctx.getTranslationUnitDecl()};
GIVEN("references to a, b and c") {
auto ref_a{GetDeclRef<clang::VarDecl>(ast, tudecl, "a")};
auto ref_b{GetDeclRef<clang::VarDecl>(ast, tudecl, "b")};
auto ref_c{GetDeclRef<clang::VarDecl>(ast, tudecl, "c")};
THEN("return {a+b; b*c; c/a;}") {
std::vector<clang::Stmt *> stmts;
stmts.push_back(ast.CreateAdd(ref_a, ref_b));
stmts.push_back(ast.CreateMul(ref_b, ref_c));
stmts.push_back(ast.CreateDiv(ref_c, ref_a));
auto compound{ast.CreateCompoundStmt(stmts)};
REQUIRE(compound != nullptr);
CHECK(compound->size() == stmts.size());
}
}
}
}
}
TEST_SUITE("ASTBuilder::CreateIf") {
SCENARIO("Create an if statement") {
GIVEN("Empty translation unit") {
auto unit{GetASTUnit()};
rellic::ASTBuilder ast(*unit);
GIVEN("Empty compound statement and 1U literal") {
std::vector<clang::Stmt *> stmts;
auto body{ast.CreateCompoundStmt(stmts)};
auto cond{ast.CreateTrue()};
THEN("return if(1U){};") {
auto if_stmt{ast.CreateIf(cond, body)};
REQUIRE(if_stmt != nullptr);
CHECK(if_stmt->getCond() == cond);
CHECK(if_stmt->getThen() == body);
CHECK(if_stmt->getElse() == nullptr);
}
}
}
}
}
TEST_SUITE("ASTBuilder::CreateWhile") {
SCENARIO("Create a while statement") {
GIVEN("Empty translation unit") {
auto unit{GetASTUnit()};
rellic::ASTBuilder ast(*unit);
GIVEN("Empty compound statement and 1U literal") {
std::vector<clang::Stmt *> stmts;
auto body{ast.CreateCompoundStmt(stmts)};
auto cond{ast.CreateTrue()};
THEN("return while(1U){};") {
auto while_stmt{ast.CreateWhile(cond, body)};
REQUIRE(while_stmt != nullptr);
CHECK(while_stmt->getCond() == cond);
CHECK(while_stmt->getBody() == body);
}
}
}
}
}
TEST_SUITE("ASTBuilder::CreateDo") {
SCENARIO("Create a do statement") {
GIVEN("Empty translation unit") {
auto unit{GetASTUnit()};
rellic::ASTBuilder ast(*unit);
GIVEN("Empty compound statement and 1U literal") {
std::vector<clang::Stmt *> stmts;
auto body{ast.CreateCompoundStmt(stmts)};
auto cond{ast.CreateTrue()};
THEN("return do{}while(1U);") {
auto do_stmt{ast.CreateDo(cond, body)};
REQUIRE(do_stmt != nullptr);
CHECK(do_stmt->getCond() == cond);
CHECK(do_stmt->getBody() == body);
}
}
}
}
}
TEST_SUITE("ASTBuilder::CreateBreak") {
SCENARIO("Create a break statement") {
GIVEN("Empty translation unit") {
auto unit{GetASTUnit()};
rellic::ASTBuilder ast(*unit);
THEN("return break;") {
auto brk_stmt{ast.CreateBreak()};
REQUIRE(brk_stmt != nullptr);
CHECK(clang::isa<clang::BreakStmt>(brk_stmt));
}
}
}
}
TEST_SUITE("ASTBuilder::CreateReturn") {
SCENARIO("Create a return statement") {
GIVEN("Empty translation unit") {
auto unit{GetASTUnit("")};
rellic::ASTBuilder ast(*unit);
THEN("return a return;") {
auto ret_stmt{ast.CreateReturn()};
REQUIRE(ret_stmt != nullptr);
CHECK(clang::isa<clang::ReturnStmt>(ret_stmt));
}
THEN("return a return 1U;") {
auto lit{ast.CreateTrue()};
auto ret_stmt{ast.CreateReturn(lit)};
REQUIRE(ret_stmt != nullptr);
CHECK(clang::isa<clang::ReturnStmt>(ret_stmt));
CHECK(ret_stmt->getRetValue() == lit);
}
}
}
}
| 36.095128 | 80 | 0.584346 | clayne |
a5fbaed74119316d3ea1c0100539be4d620f87a0 | 2,953 | hpp | C++ | Source/TitaniumKit/include/Titanium/Network/Socket/UDP.hpp | appcelerator/titanium_mobile_windows | ec82c011f418cbcf27795eb009deaef5e3fe4b20 | [
"Apache-2.0"
] | 20 | 2015-04-02T06:55:30.000Z | 2022-03-29T04:27:30.000Z | Source/TitaniumKit/include/Titanium/Network/Socket/UDP.hpp | appcelerator/titanium_mobile_windows | ec82c011f418cbcf27795eb009deaef5e3fe4b20 | [
"Apache-2.0"
] | 692 | 2015-04-01T21:05:49.000Z | 2020-03-10T10:11:57.000Z | Source/TitaniumKit/include/Titanium/Network/Socket/UDP.hpp | appcelerator/titanium_mobile_windows | ec82c011f418cbcf27795eb009deaef5e3fe4b20 | [
"Apache-2.0"
] | 22 | 2015-04-01T20:57:51.000Z | 2022-01-18T17:33:15.000Z | /**
* TitaniumKit Titanium.Network.Socket.UDP
*
* Copyright (c) 2015 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License.
* Please see the LICENSE included with this distribution for details.
*/
#ifndef _TITANIUM_UDP_HPP_
#define _TITANIUM_UDP_HPP_
#include "Titanium/IOStream.hpp"
namespace Titanium
{
namespace Network
{
namespace Socket
{
using namespace HAL;
/*!
@class
@discussion This is the Titanium UDP Module.
See http://docs.appcelerator.com/titanium/latest/#!/api/Titanium.Network.Socket.UDP
*/
class TITANIUMKIT_EXPORT UDP : public IOStream, public JSExport<UDP>
{
public:
/*!
@property
@abstract port
@discussion The port to connect to or listen on.
*/
TITANIUM_PROPERTY_IMPL_DEF(std::uint32_t, port);
/*!
@method
@abstract start
@discussion Will start up the local UDP socket.
*/
virtual void start(const std::uint32_t& port, const std::string& host) TITANIUM_NOEXCEPT;
/*!
@method
@abstract stop
@discussion Will tear down the local UDP socket.
*/
virtual void stop() TITANIUM_NOEXCEPT;
/*!
@method
@abstract sendString
@discussion Will send the string as a UDP packet to designated host and port.
*/
virtual void sendString(const std::uint32_t& port, const std::string& host, const std::string& data) TITANIUM_NOEXCEPT;
/*!
@method
@abstract sendBytes
@discussion Will send the bytes as a UDP packet to designated host and port.
*/
virtual void sendBytes(const std::uint32_t& port, const std::string& host, std::vector<std::uint8_t> data) TITANIUM_NOEXCEPT;
UDP(const JSContext&) TITANIUM_NOEXCEPT;
virtual ~UDP() = default;
UDP(const UDP&) = default;
UDP& operator=(const UDP&) = default;
#ifdef TITANIUM_MOVE_CTOR_AND_ASSIGN_DEFAULT_ENABLE
UDP(UDP&&) = default;
UDP& operator=(UDP&&) = default;
#endif
static void JSExportInitialize();
TITANIUM_PROPERTY_DEF(port);
TITANIUM_PROPERTY_DEF(started);
TITANIUM_PROPERTY_DEF(data);
TITANIUM_PROPERTY_DEF(error);
TITANIUM_FUNCTION_DEF(start);
TITANIUM_FUNCTION_DEF(stop);
TITANIUM_FUNCTION_DEF(sendString);
TITANIUM_FUNCTION_DEF(sendBytes);
TITANIUM_FUNCTION_DEF(getPort);
TITANIUM_FUNCTION_DEF(setPort);
TITANIUM_FUNCTION_DEF(getStarted);
TITANIUM_FUNCTION_DEF(setStarted);
TITANIUM_FUNCTION_DEF(getData);
TITANIUM_FUNCTION_DEF(setData);
TITANIUM_FUNCTION_DEF(getError);
TITANIUM_FUNCTION_DEF(setError);
protected:
#pragma warning(push)
#pragma warning(disable : 4251)
std::uint32_t port__;
std::string host__;
JSValue started__;
JSValue data__;
JSValue error__;
#pragma warning(pop)
};
} // namespace Socket
} // namespace Network
} // namespace Titanium
#endif // _TITANIUM_UDP_HPP_ | 26.366071 | 129 | 0.692177 | appcelerator |
a5fc65d137dc620782ccc3c8ac77bc102d5c9520 | 364 | cpp | C++ | Lesson3/1functions.cpp | 0x6f736f646f/mechatronics_Cpp_programming | 0618cd39e6c914adc5ef2863a3295cb8adf41a54 | [
"Apache-2.0"
] | null | null | null | Lesson3/1functions.cpp | 0x6f736f646f/mechatronics_Cpp_programming | 0618cd39e6c914adc5ef2863a3295cb8adf41a54 | [
"Apache-2.0"
] | null | null | null | Lesson3/1functions.cpp | 0x6f736f646f/mechatronics_Cpp_programming | 0618cd39e6c914adc5ef2863a3295cb8adf41a54 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
using namespace std;
//function declaration
int max(int, int);
int main(){
//local variable declaration
int a = 100, b = 200, ret;
//calling function to get max value
ret = max(a,b);
cout << "Max values is : " << ret << endl;
return 0;
}
int max(int num1, int num2){
if (num1 > num2)
{
return num1;
} else {
return num2;
}
} | 14 | 43 | 0.623626 | 0x6f736f646f |
a5fd3ee8ee3f101e66e2ee2ae39ef284e556dba1 | 1,589 | cpp | C++ | Oem/dbxml/dbxml/src/utils/shell/IncludeCommand.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | 2 | 2017-04-19T01:38:30.000Z | 2020-07-31T03:05:32.000Z | Oem/dbxml/dbxml/src/utils/shell/IncludeCommand.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | null | null | null | Oem/dbxml/dbxml/src/utils/shell/IncludeCommand.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | 1 | 2021-12-29T10:46:12.000Z | 2021-12-29T10:46:12.000Z | //
// See the file LICENSE for redistribution information.
//
// Copyright (c) 2002,2009 Oracle. All rights reserved.
//
//
#include <fstream>
#include "IncludeCommand.hpp"
#include "Shell.hpp"
using namespace DbXml;
using namespace std;
string IncludeCommand::getCommandNameCompat() const
{
return "include";
}
string IncludeCommand::getCommandName() const
{
return "run";
}
string IncludeCommand::getBriefHelp() const
{
return "Runs the given file as a script";
}
string IncludeCommand::getMoreHelp() const
{
return "Usage: run <scriptFile>";
}
void IncludeCommand::execute(Args &args, Environment &env)
{
if(args.size() != 2) {
throw CommandException("Wrong number of arguments");
}
string oldStreamName = env.streamName();
int oldLineNo = env.lineNo();
bool oldInteractive = env.interactive();
try {
ifstream scriptFile(args[1].c_str(), ios::in);
if(!scriptFile) {
throw CommandException("Cannot open file: " + args[1]);
}
else {
env.streamName() = args[1];
env.lineNo() = 0;
env.interactive() = false;
bool success = env.shell()->mainLoop(scriptFile, env);
scriptFile.close();
if(!success) {
// There was an error!
throw CommandException("error in included file");
}
}
}
catch(...) {
env.streamName() = oldStreamName;
env.lineNo() = oldLineNo;
env.interactive() = oldInteractive;
env.quit() = false;
throw;
}
env.streamName() = oldStreamName;
env.lineNo() = oldLineNo;
env.interactive() = oldInteractive;
env.quit() = false;
}
| 20.113924 | 61 | 0.648836 | achilex |
a5fddcb6d31ebf08d6f3cd1caf440a377548feef | 2,916 | cc | C++ | src/mem/ruby/network/garnet/fixed-pipeline/routing/aco/RoutingTable.cc | mcai/gem5_ccnuma | 038a86035dc47706714dbd594ce66f562b6c87f1 | [
"BSD-3-Clause"
] | 3 | 2017-11-19T06:49:54.000Z | 2018-12-26T18:08:11.000Z | src/mem/ruby/network/garnet/fixed-pipeline/routing/aco/RoutingTable.cc | mcai/gem5_ccnuma | 038a86035dc47706714dbd594ce66f562b6c87f1 | [
"BSD-3-Clause"
] | null | null | null | src/mem/ruby/network/garnet/fixed-pipeline/routing/aco/RoutingTable.cc | mcai/gem5_ccnuma | 038a86035dc47706714dbd594ce66f562b6c87f1 | [
"BSD-3-Clause"
] | 6 | 2016-07-31T18:48:18.000Z | 2022-03-06T22:41:28.000Z | #include <stdlib.h>
#include <algorithm>
#include "base/misc.hh"
#include "mem/ruby/network/garnet/NetworkHeader.hh"
#include "mem/ruby/network/garnet/fixed-pipeline/routing/aco/AntNetAgent.hh"
#include "mem/ruby/network/garnet/fixed-pipeline/routing/aco/RoutingTable.hh"
using namespace std;
const double REINFORCEMENT_FACTOR = 0.05d;
RoutingTable::RoutingTable(AntNetAgent *agent)
{
m_agent = agent;
srand(time(NULL));
}
void
RoutingTable::addEntry(int destination, int neighbor, double pheromone_value)
{
Pheromone *pheromone = new Pheromone(neighbor, pheromone_value);
if(m_pheromones.count(destination) == 0)
{
m_pheromones[destination] = vector<Pheromone*>();
}
m_pheromones[destination].push_back(pheromone);
}
int
RoutingTable::calculateRandomDestination(int source)
{
int num_routers = m_agent->getNumRouters();
int i;
do
{
i = rand() % num_routers;
}
while (i == source);
return i;
}
int
RoutingTable::calculateNeighbor(int destination, int parent)
{
if(destination == m_agent->getRouter())
{
fatal("destination should not be equal to the current router");
return 0;
}
if(count(m_agent->getLinks().begin(), m_agent->getLinks().end(), destination) > 0)
{
return destination;
}
vector<Pheromone*> pheromones_per_destination = m_pheromones[destination];
double max_pheromone_value = 0.0d;
int max_pheromone_neighbor = INFINITE_;
for(vector<Pheromone*>::iterator it = pheromones_per_destination.begin(); it != pheromones_per_destination.end(); ++it)
{
Pheromone *pheromone = *it;
int neighbor = pheromone->getNeighbor();
double pheromone_value = pheromone->getValue();
if(neighbor != parent && pheromone_value > max_pheromone_value)
{
max_pheromone_value = pheromone_value;
max_pheromone_neighbor = neighbor;
}
}
if(max_pheromone_neighbor == INFINITE_)
{
fatal("max_pheromone_neighbor should not be INFINITE_");
return max_pheromone_neighbor;
}
return max_pheromone_neighbor;
}
void
RoutingTable::update(int destination, int neighbor)
{
vector<Pheromone*> pheromones_per_destination = m_pheromones[destination];
for(vector<Pheromone*>::iterator it = pheromones_per_destination.begin(); it != pheromones_per_destination.end(); it++)
{
Pheromone *pheromone = *it;
if(pheromone->getNeighbor() == neighbor)
{
pheromone->setValue(pheromone->getValue() + REINFORCEMENT_FACTOR * (1 - pheromone->getValue()));
}
else
{
pheromone->setValue(pheromone->getValue() * (1 - REINFORCEMENT_FACTOR));
}
}
}
AntNetAgent *
RoutingTable::getAgent()
{
return m_agent;
}
map<int, vector<Pheromone*>>&
RoutingTable::getPheromones()
{
return m_pheromones;
} | 24.3 | 123 | 0.670439 | mcai |
a5fea5b189bacac1b54df51c0ba33547c8dcad19 | 7,229 | cpp | C++ | src/devices/machine/ds2401.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 26 | 2015-03-31T06:25:51.000Z | 2021-12-14T09:29:04.000Z | src/devices/machine/ds2401.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | null | null | null | src/devices/machine/ds2401.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 10 | 2015-03-27T05:45:51.000Z | 2022-02-04T06:57:36.000Z | // license:BSD-3-Clause
// copyright-holders:smf
/*
* DS2401
*
* Dallas Semiconductor
* Silicon Serial Number
*
*/
#include "emu.h"
#include "machine/ds2401.h"
#define VERBOSE_LEVEL 0
inline void ds2401_device::verboselog(int n_level, const char *s_fmt, ...)
{
if(VERBOSE_LEVEL >= n_level)
{
va_list v;
char buf[32768];
va_start(v, s_fmt);
vsprintf(buf, s_fmt, v);
va_end(v);
logerror("ds2401 %s %s: %s", tag(), machine().describe_context(), buf);
}
}
// device type definition
DEFINE_DEVICE_TYPE(DS2401, ds2401_device, "ds2401", "DS2401 Silicon Serial Number")
ds2401_device::ds2401_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: device_t(mconfig, DS2401, tag, owner, clock)
, m_state(0)
, m_bit(0)
, m_shift(0)
, m_byte(0)
, m_rx(false)
, m_tx(false)
, m_timer_main(nullptr)
, m_timer_reset(nullptr)
{
}
void ds2401_device::device_start()
{
t_samp = attotime::from_usec( 30);
t_rdv = attotime::from_usec( 30);
t_rstl = attotime::from_usec(480);
t_pdh = attotime::from_usec( 30);
t_pdl = attotime::from_usec(120);
m_rx = true;
m_tx = true;
save_item(NAME(m_state));
save_item(NAME(m_bit));
save_item(NAME(m_byte));
save_item(NAME(m_shift));
save_item(NAME(m_rx));
save_item(NAME(m_tx));
m_timer_main = timer_alloc(TIMER_MAIN);
m_timer_reset = timer_alloc(TIMER_RESET);
}
void ds2401_device::device_reset()
{
m_state = STATE_IDLE;
m_bit = 0;
m_byte = 0;
m_shift = 0;
m_rx = true;
m_tx = true;
memory_region *region = memregion(DEVICE_SELF);
if (region != nullptr)
{
if (region->bytes() == SIZE_DATA)
{
memcpy(m_data, region->base(), SIZE_DATA);
return;
}
logerror("ds2401 %s: Wrong region length for id data, expected 0x%x, got 0x%x\n", tag(), SIZE_DATA, region->bytes());
}
else
{
logerror("ds2401 %s: Warning, no id provided, answer will be all zeroes.\n", tag());
}
memset(m_data, 0, SIZE_DATA);
}
void ds2401_device::device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr)
{
switch(id)
{
case TIMER_RESET:
verboselog(1, "timer_reset\n");
m_state = STATE_RESET;
m_timer_reset->adjust(attotime::never);
break;
case TIMER_MAIN:
switch(m_state)
{
case STATE_RESET1:
verboselog(2, "timer_main state_reset1 %d\n", m_rx);
m_tx = false;
m_state = STATE_RESET2;
m_timer_main->adjust(t_pdl);
break;
case STATE_RESET2:
verboselog(2, "timer_main state_reset2 %d\n", m_rx);
m_tx = true;
m_bit = 0;
m_shift = 0;
m_state = STATE_COMMAND;
break;
case STATE_COMMAND:
verboselog(2, "timer_main state_command %d\n", m_rx);
m_shift >>= 1;
if(m_rx)
{
m_shift |= 0x80;
}
m_bit++;
if(m_bit == 8)
{
switch(m_shift)
{
case COMMAND_READROM:
case COMMAND_READROM_COMPAT:
verboselog(1, "timer_main readrom\n");
m_bit = 0;
m_byte = 0;
m_state = STATE_READROM;
break;
default:
verboselog(0, "timer_main command not handled %02x\n", m_shift);
m_state = STATE_IDLE;
break;
}
}
break;
case STATE_READROM:
m_tx = true;
if( m_byte == SIZE_DATA )
{
verboselog(1, "timer_main readrom finished\n");
m_state = STATE_IDLE;
}
else
{
verboselog(2, "timer_main readrom window closed\n");
}
break;
default:
verboselog(0, "timer_main state not handled: %d\n", m_state);
break;
}
}
}
WRITE_LINE_MEMBER( ds2401_device::write )
{
verboselog(1, "write(%d)\n", state);
if(!state && m_rx)
{
switch(m_state)
{
case STATE_IDLE:
break;
case STATE_COMMAND:
verboselog(2, "state_command\n");
m_timer_main->adjust(t_samp);
break;
case STATE_READROM:
if(!m_bit)
{
m_shift = m_data[7 - m_byte];
verboselog(1, "<- data %02x\n", m_shift);
}
m_tx = m_shift & 1;
m_shift >>= 1;
m_bit++;
if(m_bit == 8)
{
m_bit = 0;
m_byte++;
}
verboselog(2, "state_readrom %d\n", m_tx);
m_timer_main->adjust(t_rdv);
break;
default:
verboselog(0, "state not handled: %d\n", m_state );
break;
}
m_timer_reset->adjust(t_rstl);
}
else if(state && !m_rx)
{
switch(m_state)
{
case STATE_RESET:
m_state = STATE_RESET1;
m_timer_main->adjust(t_pdh);
break;
}
m_timer_reset->adjust(attotime::never);
}
m_rx = state;
}
READ_LINE_MEMBER( ds2401_device::read )
{
verboselog(2, "read %d\n", m_tx && m_rx);
return m_tx && m_rx;
}
uint8_t ds2401_device::direct_read(int index)
{
return m_data[index];
}
/*
app74.pdf
Under normal circumstances an ibutton will sample the line 30us after the falling edge of the start condition.
The internal time base of ibutton may deviate from its nominal value. The allowed tollerance band ranges from 15us to 60us.
This means that the actual slave sampling may occur anywhere from 15 and 60us after the start condition, which is a ratio of 1 to 4.
During this time frame the voltage on the data line must stay below Vilmax or above Vihmin.
In the 1-Wire system, the logical values 1 and 0 are represented by certain voltages in special waveforms.
The waveforms needed to write commands or data to ibuttons are called write-1 and write-0 time slots.
The duration of a low pulse to write a 1 must be shorter than 15us.
To write a 0, the duration of the low pulse must be at least 60us to cope with worst-case conditions.
The duration of the active part of a time slot can be extended beyond 60us.
The maximum extension is limited by the fact that a low pulse of a duration of at least eight active time slots ( 480us ) is defined as a Reset Pulse.
Allowing the same worst-case tolerance ratio, a low pulse of 120us might be sufficient for a reset.
This limits the extension of the active part of a time slot to a maximum of 120us to prevent misinterpretation with reset.
Commands and data are sent to ibuttons by combining write-0 and write-1 time slots.
To read data, the master has to generate read-data time slots to define the start condition of each bit.
The read-data time slots looks essentially the same as a write-1 time slot from the masters point of view.
Starting at the high-to-low transition, the ibuttons sends 1 bit of its addressed contents.
If the data bit is a 1, the ibutton leaves the pulse unchanged.
If the data bit is a 0, the ibutton will pull the data line low for 15us.
In this time frame data is valid for reading by the master.
The duration of the low pulse sent by the master should be a minimum of 1us with a maximum value as short as possible to maximize the master sampling window.
The Reset Pulse provides a clear starting condition that supersedes any time slot synchronisation.
It is defined as single low pulse of minimum duration of eight time slots or 480us followed by a Reset-high time tRSTH of another 480us.
After a Reset Pulse has been sent, the ibutton will wait for the time tPDH and then generate a Pulse-Presence Pulse of duration tPDL.
No other communication on the 1-Wire bus is allowed during tRSTH.
There are 1,000 microseconds in a millisecond, and 1,000 milliseconds in a second.
Thus, there are 1,000,000 microseconds in a second. Why is it "usec"?
The "u" is supposed to look like the Greek letter Mu that we use for "micro". .
*/
| 25.725979 | 157 | 0.701757 | Robbbert |
57035f3918f6e0ddee49b3d875a52f3cd3a49f4e | 1,612 | cpp | C++ | questions/threadwork-simple-40865259/main.cpp | SammyEnigma/stackoverflown | 0f70f2534918b2e65cec1046699573091d9a40b5 | [
"Unlicense"
] | 54 | 2015-09-13T07:29:52.000Z | 2022-03-16T07:43:50.000Z | questions/threadwork-simple-40865259/main.cpp | SammyEnigma/stackoverflown | 0f70f2534918b2e65cec1046699573091d9a40b5 | [
"Unlicense"
] | null | null | null | questions/threadwork-simple-40865259/main.cpp | SammyEnigma/stackoverflown | 0f70f2534918b2e65cec1046699573091d9a40b5 | [
"Unlicense"
] | 31 | 2016-08-26T13:35:01.000Z | 2022-03-13T16:43:12.000Z | // https://github.com/KubaO/stackoverflown/tree/master/questions/threadwork-simple-40865259
#include <QtWidgets>
#include <QtConcurrent>
struct ApplicationData {};
struct OptimizationAlgorithm {
void timeConsumingMethod(QSharedPointer<ApplicationData>) {
QThread::sleep(3);
}
};
class Controller : public QObject {
Q_OBJECT
QSharedPointer<ApplicationData> m_data{new ApplicationData};
OptimizationAlgorithm m_algorithm;
public:
Q_SLOT void run() {
QtConcurrent::run([this]{
emit busy();
m_algorithm.timeConsumingMethod(m_data);
emit finished();
});
}
Q_SIGNAL void busy();
Q_SIGNAL void finished();
};
class Registration : public QWidget {
Q_OBJECT
QVBoxLayout m_layout{this};
QLabel m_status{"Idle"};
QPushButton m_run{"Run"};
public:
Registration() {
m_layout.addWidget(&m_status);
m_layout.addWidget(&m_run);
connect(&m_run, &QPushButton::clicked, this, &Registration::reqRun);
}
Q_SIGNAL void reqRun();
Q_SLOT void onBusy() { m_status.setText("Running"); }
Q_SLOT void onFinished() { m_status.setText("Idle"); }
};
void setup(Registration *reg, Controller *ctl) {
using Q = QObject;
Q::connect(reg, &Registration::reqRun, ctl, &Controller::run);
Q::connect(ctl, &Controller::busy, reg, &Registration::onBusy);
Q::connect(ctl, &Controller::finished, reg, &Registration::onFinished);
}
int main(int argc, char ** argv) {
QApplication app{argc, argv};
Controller ctl;
Registration reg;
setup(®, &ctl);
reg.show();
return app.exec();
}
#include "main.moc"
| 26.42623 | 91 | 0.681141 | SammyEnigma |
570408bd530273ed0d7a88f3380eb5a574d95e4d | 24,356 | cc | C++ | src/plugins/plot/Plot.cc | Levi-Armstrong/ign-gui | c14dc67bbb61e2422737be6428ba5fb67aeba654 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/plugins/plot/Plot.cc | Levi-Armstrong/ign-gui | c14dc67bbb61e2422737be6428ba5fb67aeba654 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/plugins/plot/Plot.cc | Levi-Armstrong/ign-gui | c14dc67bbb61e2422737be6428ba5fb67aeba654 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2017 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <map>
#include <vector>
#include <ignition/common/Console.hh>
#include <ignition/plugin/Register.hh>
#include "ignition/gui/EditableLabel.hh"
#include "ignition/gui/plugins/plot/Curve.hh"
#include "ignition/gui/plugins/plot/IncrementalPlot.hh"
#include "ignition/gui/plugins/plot/Plot.hh"
#include "ignition/gui/plugins/plot/TopicCurveHandler.hh"
#include "ignition/gui/plugins/plot/Types.hh"
#include "ignition/gui/Helpers.hh"
#include "ignition/gui/VariablePill.hh"
#include "ignition/gui/VariablePillContainer.hh"
namespace ignition
{
namespace gui
{
namespace plugins
{
namespace plot
{
/// \brief Helper data structure to store plot data
class Data
{
/// \brief Unique id of the plot
public: unsigned int id;
/// brief Pointer to the plot
public: IncrementalPlot *plot = nullptr;
/// \brief A map of container variable ids to their plot curve ids.
public: std::map<unsigned int, unsigned int> variableCurves;
};
class PlotPrivate
{
/// \brief Text label
public: EditableLabel *title{nullptr};
/// \brief Splitter that contains all the plots.
public: QSplitter *plotSplitter{nullptr};
/// \brief A map of plot id to plot data;
public: std::map<unsigned int, plot::Data *> plotData;
/// \brief Initial empty plot. Variables are never added to it, and it is
/// hidden when other plots are added.
public: IncrementalPlot *emptyPlot{nullptr};
/// \brief Container for all the variableCurves on the Y axis.
public: VariablePillContainer *yVariableContainer{nullptr};
/// \brief Global plot counter.
public: static unsigned int globalPlotId;
/// \brief Handler for updating topic curves
public: TopicCurveHandler topicCurve;
};
}
}
}
}
using namespace ignition;
using namespace gui;
using namespace plugins;
using namespace plot;
const unsigned int Plot::EmptyPlot = ignition::math::MAX_UI32;
unsigned int PlotPrivate::globalPlotId = 0;
/////////////////////////////////////////////////
Plot::Plot()
: Plugin(), dataPtr(new PlotPrivate)
{
}
/////////////////////////////////////////////////
Plot::~Plot()
{
this->Clear();
}
/////////////////////////////////////////////////
void Plot::LoadConfig(const tinyxml2::XMLElement */*_pluginElem*/)
{
if (this->title.empty())
this->title = "Plotting Utility";
// Plot title
this->dataPtr->title = new EditableLabel("Plot Name");
auto titleLayout = new QHBoxLayout;
titleLayout->addWidget(this->dataPtr->title);
titleLayout->setAlignment(Qt::AlignHCenter);
// Settings menu
auto settingsMenu = new QMenu();
auto clearPlotAct = new QAction("Clear all fields", settingsMenu);
clearPlotAct->setStatusTip(tr("Clear variables and all plots"));
this->connect(clearPlotAct, SIGNAL(triggered()), this, SLOT(OnClear()));
settingsMenu->addAction(clearPlotAct);
auto showGridAct = new QAction("Show grid", settingsMenu);
showGridAct->setStatusTip(tr("Show/hide grid lines on plot"));
showGridAct->setCheckable(true);
this->connect(showGridAct, SIGNAL(toggled(bool)), this,
SLOT(OnShowGrid(bool)));
settingsMenu->addAction(showGridAct);
auto showHoverLineAct = new QAction("Show hover line", settingsMenu);
showHoverLineAct->setStatusTip(tr("Show hover line"));
showHoverLineAct->setCheckable(true);
this->connect(showHoverLineAct, SIGNAL(toggled(bool)), this,
SLOT(OnShowHoverLine(bool)));
settingsMenu->addAction(showHoverLineAct);
auto exportMenu = settingsMenu->addMenu("Export");
auto csvAct = new QAction("CSV (.csv)", exportMenu);
csvAct->setStatusTip("Export to CSV file");
this->connect(csvAct, SIGNAL(triggered()), this, SLOT(OnExportCSV()));
exportMenu->addAction(csvAct);
auto pdfAct = new QAction("PDF (.pdf)", exportMenu);
pdfAct->setStatusTip("Export to PDF file");
this->connect(pdfAct, SIGNAL(triggered()), this, SLOT(OnExportPDF()));
exportMenu->addAction(pdfAct);
// Settings button
auto settingsButton = new QToolButton();
settingsButton->installEventFilter(this);
settingsButton->setToolTip(tr("Settings"));
settingsButton->setIcon(QIcon(":/images/settings.png"));
settingsButton->setIconSize(QSize(25, 25));
settingsButton->setFixedSize(QSize(45, 35));
settingsButton->setToolButtonStyle(Qt::ToolButtonIconOnly);
settingsButton->setPopupMode(QToolButton::InstantPopup);
settingsButton->setMenu(settingsMenu);
// Layout with title + settings
auto titleSettingsLayout = new QHBoxLayout;
titleSettingsLayout->addLayout(titleLayout);
titleSettingsLayout->addWidget(settingsButton);
titleSettingsLayout->setContentsMargins(0, 0, 0, 0);
// X variable container
// \todo: fix hardcoded x axis - issue #18
auto xVariableContainer = new VariablePillContainer(this);
xVariableContainer->SetText("x ");
xVariableContainer->SetMaxSize(1);
xVariableContainer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
xVariableContainer->setContentsMargins(0, 0, 0, 0);
xVariableContainer->AddVariablePill("time");
xVariableContainer->setEnabled(false);
// Y variable container
this->dataPtr->yVariableContainer = new VariablePillContainer(this);
this->dataPtr->yVariableContainer->SetText("y ");
this->dataPtr->yVariableContainer->setSizePolicy(
QSizePolicy::Expanding, QSizePolicy::Fixed);
this->dataPtr->yVariableContainer->setContentsMargins(0, 0, 0, 0);
this->connect(this->dataPtr->yVariableContainer,
SIGNAL(VariableAdded(unsigned int, std::string, unsigned int)), this,
SLOT(OnAddVariableFromPill(unsigned int, std::string, unsigned int)));
this->connect(this->dataPtr->yVariableContainer,
SIGNAL(VariableRemoved(unsigned int, unsigned int)),
this, SLOT(OnRemoveVariableFromPill(unsigned int, unsigned int)));
this->connect(this->dataPtr->yVariableContainer,
SIGNAL(VariableMoved(unsigned int, unsigned int)),
this, SLOT(OnMoveVariableFromPill(unsigned int, unsigned int)));
// Variable container layout
auto variableContainerLayout = new QVBoxLayout;
variableContainerLayout->addWidget(xVariableContainer);
variableContainerLayout->addWidget(this->dataPtr->yVariableContainer);
variableContainerLayout->setSpacing(0);
variableContainerLayout->setContentsMargins(0, 0, 0, 0);
// Start with an empty plot
this->dataPtr->emptyPlot = new IncrementalPlot(this);
this->connect(this->dataPtr->emptyPlot, SIGNAL(VariableAdded(std::string)),
this, SLOT(OnAddVariableFromPlot(std::string)));
showGridAct->setChecked(this->dataPtr->emptyPlot->IsShowGrid());
showHoverLineAct->setChecked(this->dataPtr->emptyPlot->IsShowHoverLine());
// Splitter to add subsequent plots
this->dataPtr->plotSplitter = new QSplitter(Qt::Vertical);
this->dataPtr->plotSplitter->setVisible(false);
this->dataPtr->plotSplitter->setChildrenCollapsible(false);
auto plotsLayout = new QVBoxLayout();
plotsLayout->addWidget(this->dataPtr->emptyPlot);
plotsLayout->addWidget(this->dataPtr->plotSplitter);
auto plotScrollArea = new QScrollArea(this);
plotScrollArea->setLineWidth(0);
plotScrollArea->setFrameShape(QFrame::NoFrame);
plotScrollArea->setFrameShadow(QFrame::Plain);
plotScrollArea->setSizePolicy(QSizePolicy::Minimum,
QSizePolicy::Expanding);
plotScrollArea->setWidgetResizable(true);
plotScrollArea->viewport()->installEventFilter(this);
plotScrollArea->setLayout(plotsLayout);
// Main layout
auto mainLayout = new QVBoxLayout;
mainLayout->addLayout(titleSettingsLayout);
mainLayout->addLayout(variableContainerLayout);
mainLayout->addWidget(plotScrollArea);
mainLayout->setContentsMargins(0, 0, 0, 0);
this->setLayout(mainLayout);
this->setMinimumSize(640, 480);
// Periodically update the plots
auto displayTimer = new QTimer(this);
this->connect(displayTimer, SIGNAL(timeout()), this, SLOT(Update()));
displayTimer->start(30);
}
/////////////////////////////////////////////////
void Plot::ShowContextMenu(const QPoint &/*_pos*/)
{
// Do nothing so the panner works
}
/////////////////////////////////////////////////
std::string Plot::ExportFilename()
{
// Get the plots that have data.
bool hasData = false;
for (const auto &plot : this->Plots())
{
for (const auto &curve : plot->Curves())
{
auto c = curve.lock();
if (!c)
continue;
hasData = hasData || c->Size() > 0;
}
}
// Display an error message if no plots have data.
if (!hasData)
{
QMessageBox msgBox(
QMessageBox::Information,
QString("Unable to export"),
QString(
"No data to export.\nAdd variables with data to a graph first."),
QMessageBox::Close,
this,
Qt::Window | Qt::WindowTitleHint |
Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint);
msgBox.exec();
return "";
}
// Open file dialog
QFileDialog fileDialog(this, tr("Save Directory"), QDir::homePath());
fileDialog.setWindowFlags(Qt::Window | Qt::WindowCloseButtonHint |
Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint);
fileDialog.setAcceptMode(QFileDialog::AcceptSave);
fileDialog.setFileMode(QFileDialog::DirectoryOnly);
if (fileDialog.exec() != QDialog::Accepted)
return "";
// Get the selected directory
auto selected = fileDialog.selectedFiles();
if (selected.empty())
return "";
// Cleanup the title
std::string plotTitle = this->dataPtr->title->Text();
std::replace(plotTitle.begin(), plotTitle.end(), '/', '_');
std::replace(plotTitle.begin(), plotTitle.end(), '?', ':');
return selected[0].toStdString() + "/" + plotTitle;
}
/////////////////////////////////////////////////
unsigned int Plot::AddVariableToPill(const std::string &_variable,
const unsigned int _plotId)
{
// Target a new pill by default
auto targetId = VariablePill::EmptyVariable;
// find a variable that belongs to the specified plotId and make that the
// the target variable that the new variable will be added to
auto it = this->dataPtr->plotData.find(_plotId);
if (it != this->dataPtr->plotData.end() &&
!it->second->variableCurves.empty())
{
targetId = it->second->variableCurves.begin()->first;
}
// add to container and let the signals/slots do the work on adding the
// a new plot with the curve in the overloaded AddVariable function
return this->dataPtr->yVariableContainer->AddVariablePill(_variable,
targetId);
}
/////////////////////////////////////////////////
void Plot::AddVariableToPlot(const unsigned int _id,
const std::string &_variable,
const unsigned int _plotId)
{
unsigned int plotId;
if (_plotId == EmptyPlot)
{
// create new plot for the variable and add plot to canvas
plotId = this->AddPlot();
}
else
plotId = _plotId;
// add variable to existing plot
auto it = this->dataPtr->plotData.find(plotId);
if (it == this->dataPtr->plotData.end())
{
ignerr << "Failed to find plot [" << plotId << "]" << std::endl;
return;
}
auto p = it->second;
auto curve = p->plot->AddCurve(_variable);
auto c = curve.lock();
if (c)
{
p->variableCurves[_id] = c->Id();
}
else
{
ignerr << "Unable to add curve to plot" << std::endl;
return;
}
// Hide initial empty plot
if (!this->dataPtr->plotData.empty())
this->ShowEmptyPlot(false);
this->dataPtr->topicCurve.AddCurve(_variable, curve);
}
/////////////////////////////////////////////////
void Plot::RemoveVariable(const unsigned int _id,
const unsigned int _plotId)
{
auto plotData = this->dataPtr->plotData.end();
// Loop through all data looking for a matching variable
if (_plotId == EmptyPlot)
{
for (auto pIt = this->dataPtr->plotData.begin();
pIt != this->dataPtr->plotData.end(); ++pIt)
{
auto curve = pIt->second->variableCurves.find(_id);
if (curve != pIt->second->variableCurves.end())
{
plotData = pIt;
break;
}
}
}
// Get the plot which the variable belongs to
else
{
plotData = this->dataPtr->plotData.find(_plotId);
}
// Variable not found
if (plotData == this->dataPtr->plotData.end())
{
ignerr << "Failed to find plot data" << std::endl;
return;
}
// Get curve
auto curve = plotData->second->variableCurves.find(_id);
if (curve == plotData->second->variableCurves.end())
{
ignerr << "Failed to find curve [" << _id << "]" << std::endl;
return;
}
// Remove from curve manager
auto curveId = curve->second;
auto plotCurve = plotData->second->plot->Curve(curveId);
this->dataPtr->topicCurve.RemoveCurve(plotCurve);
// Remove from map
plotData->second->variableCurves.erase(curve);
// Remove from plot
plotData->second->plot->RemoveCurve(curveId);
// Remove from variable pill container - block signals so it doesn't call
// this function recursively
this->dataPtr->yVariableContainer->blockSignals(true);
this->dataPtr->yVariableContainer->RemoveVariablePill(_id);
this->dataPtr->yVariableContainer->blockSignals(false);
// Delete whole plot if this was its last variable
if (plotData->second->variableCurves.empty())
{
this->RemovePlot(plotData->first);
}
}
/////////////////////////////////////////////////
unsigned int Plot::AddPlot()
{
// Create plot
auto plot = new IncrementalPlot(this);
plot->setAutoDelete(false);
plot->ShowGrid(this->dataPtr->emptyPlot->IsShowGrid());
plot->ShowHoverLine(this->dataPtr->emptyPlot->IsShowHoverLine());
this->connect(plot, SIGNAL(VariableAdded(std::string)), this,
SLOT(OnAddVariableFromPlot(std::string)));
// Store data
auto p = new Data;
p->id = this->dataPtr->globalPlotId++;
p->plot = plot;
this->dataPtr->plotData[p->id] = p;
// Add to splitter
this->dataPtr->plotSplitter->addWidget(plot);
this->UpdateAxisLabel();
return p->id;
}
/////////////////////////////////////////////////
bool Plot::RemovePlot(const unsigned int _id)
{
if (_id == EmptyPlot)
{
ignerr << "Trying to delete placeholder empty plot." << std::endl;
return false;
}
auto it = this->dataPtr->plotData.find(_id);
if (it == this->dataPtr->plotData.end())
{
ignerr << "Failed to find plot [" << _id << "]" << std::endl;
return false;
}
// Remove the plot if it does not contain any variableCurves (curves)
if (it->second->variableCurves.empty())
{
it->second->plot->hide();
delete it->second->plot;
delete it->second;
this->dataPtr->plotData.erase(it);
// Show empty plot if all plots are gone
if (this->dataPtr->plotData.empty())
this->ShowEmptyPlot(true);
return true;
}
// remove all variableCurves except last one
unsigned int plotId = it->first;
while (it->second->variableCurves.size() > 1)
{
auto v = it->second->variableCurves.begin();
this->RemoveVariable(v->first, plotId);
}
// Remove last variable - this will also recursively call this function and
// delete the plot which causes plot data iterator to be invalid. So do this
// last.
this->RemoveVariable(it->second->variableCurves.begin()->first, plotId);
return true;
}
/////////////////////////////////////////////////
void Plot::Clear()
{
while (!this->dataPtr->plotData.empty())
{
auto p = this->dataPtr->plotData.begin();
this->RemovePlot(p->first);
}
this->ShowEmptyPlot(true);
}
/////////////////////////////////////////////////
void Plot::OnAddVariableFromPlot(const std::string &_variable)
{
auto plot = qobject_cast<IncrementalPlot *>(QObject::sender());
if (!plot)
return;
// Create a new pill when adding to the initial empty plot
if (plot == this->dataPtr->emptyPlot)
{
this->AddVariableToPill(_variable);
return;
}
// Add to an existing pill
for (const auto &it : this->dataPtr->plotData)
{
if (plot == it.second->plot)
{
this->AddVariableToPill(_variable, it.second->id);
return;
}
}
ignerr << "There's no pill corresponding to plot where variable was dropped"
<< std::endl;
}
/////////////////////////////////////////////////
void Plot::OnAddVariableFromPill(const unsigned int _id,
const std::string &_variable, const unsigned int _colocatedId)
{
// Add to an existing plot
if (_colocatedId != VariablePill::EmptyVariable)
{
for (const auto it : this->dataPtr->plotData)
{
const auto v = it.second->variableCurves.find(_colocatedId);
if (v != it.second->variableCurves.end())
{
this->AddVariableToPlot(_id, _variable, it.second->id);
return;
}
}
}
// Add variable to a new plot
else
{
this->AddVariableToPlot(_id, _variable);
return;
}
ignerr << "Failed to add variable to a plot." << std::endl;
}
/////////////////////////////////////////////////
void Plot::OnRemoveVariableFromPill(const unsigned int _id,
const unsigned int /*_colocatedId*/)
{
this->RemoveVariable(_id);
}
/////////////////////////////////////////////////
void Plot::OnMoveVariableFromPill(const unsigned int _id,
const unsigned int _targetId)
{
auto plotData = this->dataPtr->plotData.end();
auto targetPlotIt = this->dataPtr->plotData.end();
unsigned int curveId = 0;
// find plot which the variable belongs to
// find target plot (if any) that the variable will be moved to
for (auto it = this->dataPtr->plotData.begin();
it != this->dataPtr->plotData.end(); ++it)
{
auto v = it->second->variableCurves.find(_id);
if (v != it->second->variableCurves.end())
{
plotData = it;
curveId = v->second;
}
if (it->second->variableCurves.find(_targetId) !=
it->second->variableCurves.end())
{
targetPlotIt = it;
}
if (plotData != this->dataPtr->plotData.end() &&
targetPlotIt != this->dataPtr->plotData.end())
break;
}
if (plotData == this->dataPtr->plotData.end())
{
ignerr << "Couldn't find plot containing variable [" << _id << "]"
<< std::endl;
return;
}
// detach from old plot and attach to new one
auto p = plotData->second;
// detach variable from plot (qwt plot doesn't seem to do anything
// apart from setting the plot item to null)
CurvePtr plotCurve = p->plot->DetachCurve(curveId);
p->variableCurves.erase(p->variableCurves.find(_id));
if (targetPlotIt != this->dataPtr->plotData.end())
{
// attach variable to target plot
targetPlotIt->second->plot->AttachCurve(plotCurve);
targetPlotIt->second->variableCurves[_id] = plotCurve->Id();
}
else
{
// create new plot
unsigned int plotId = this->AddPlot();
auto it = this->dataPtr->plotData.find(plotId);
Data *newPlotData = it->second;
// attach curve to plot
newPlotData->plot->AttachCurve(plotCurve);
newPlotData->variableCurves[_id] = plotCurve->Id();
// hide initial empty plot
if (!this->dataPtr->plotData.empty())
this->ShowEmptyPlot(false);
}
// Delete whole plot if this was its last variable
if (p->variableCurves.empty())
this->RemovePlot(plotData->first);
}
/////////////////////////////////////////////////
void Plot::Update()
{
// Update all the plots
for (auto p : this->dataPtr->plotData)
p.second->plot->Update();
}
/////////////////////////////////////////////////
bool Plot::eventFilter(QObject *_o, QEvent *_e)
{
if (_e->type() == QEvent::Wheel)
{
_e->ignore();
return true;
}
return QWidget::eventFilter(_o, _e);
}
/////////////////////////////////////////////////
std::vector<IncrementalPlot *> Plot::Plots() const
{
std::vector<IncrementalPlot *> plots;
for (const auto it : this->dataPtr->plotData)
plots.push_back(it.second->plot);
return plots;
}
/////////////////////////////////////////////////
void Plot::OnClear()
{
// Ask for confirmation
std::string msg = "Are you sure you want to clear all fields? \n\n"
"This will remove all the plots in this canvas. \n";
QMessageBox msgBox(QMessageBox::Warning, QString("Clear canvas?"),
QString(msg.c_str()), QMessageBox::NoButton, this);
msgBox.setWindowFlags(Qt::Window | Qt::WindowTitleHint |
Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint);
auto cancelButton = msgBox.addButton("Cancel", QMessageBox::RejectRole);
auto clearButton = msgBox.addButton("Clear", QMessageBox::AcceptRole);
msgBox.setDefaultButton(clearButton);
msgBox.setEscapeButton(cancelButton);
msgBox.show();
msgBox.move(this->mapToGlobal(this->pos()));
msgBox.exec();
if (msgBox.clickedButton() != clearButton)
return;
this->Clear();
}
/////////////////////////////////////////////////
void Plot::OnShowGrid(const bool _show)
{
this->dataPtr->emptyPlot->ShowGrid(_show);
for (const auto &it : this->dataPtr->plotData)
it.second->plot->ShowGrid(_show);
}
/////////////////////////////////////////////////
void Plot::OnShowHoverLine(const bool _show)
{
this->dataPtr->emptyPlot->ShowHoverLine(_show);
for (const auto &it : this->dataPtr->plotData)
it.second->plot->ShowHoverLine(_show);
}
/////////////////////////////////////////////////
void Plot::UpdateAxisLabel()
{
// show the x-axis label in the last plot only
for (int i = 0; i < this->dataPtr->plotSplitter->count(); ++i)
{
IncrementalPlot *p =
qobject_cast<IncrementalPlot *>(this->dataPtr->plotSplitter->widget(i));
if (p)
{
std::string label = "";
if (i == (this->dataPtr->plotSplitter->count()-1))
label = "Time (seconds)";
p->ShowAxisLabel(IncrementalPlot::X_BOTTOM_AXIS, label);
}
}
}
/////////////////////////////////////////////////
void Plot::ShowEmptyPlot(const bool _show)
{
this->dataPtr->emptyPlot->setVisible(_show);
this->dataPtr->plotSplitter->setVisible(!_show);
this->UpdateAxisLabel();
}
/////////////////////////////////////////////////
void Plot::OnExportPDF()
{
auto filePrefix = this->ExportFilename();
if (filePrefix.empty())
return;
// Render the plot to a PDF
int index = 0;
for (const auto it : this->dataPtr->plotData)
{
auto suffix =
this->dataPtr->plotData.size() > 1 ? std::to_string(index) : "";
auto filename = uniqueFilePath(filePrefix + suffix, "pdf");
auto plot = it.second->plot;
QSizeF docSize(plot->canvas()->width() + plot->legend()->width(),
plot->canvas()->height());
QwtPlotRenderer renderer;
renderer.renderDocument(plot, QString(filename.c_str()), docSize, 20);
ignmsg << "Plot exported to file [" << filename << "]" << std::endl;
index++;
}
}
/////////////////////////////////////////////////
void Plot::OnExportCSV()
{
auto filePrefix = this->ExportFilename();
if (filePrefix.empty())
return;
// Save data from each curve into a separate file.
for (const auto it : this->dataPtr->plotData)
{
for (const auto &curve : it.second->plot->Curves())
{
auto c = curve.lock();
if (!c)
continue;
// Cleanup the label
auto label = c->Label();
std::replace(label.begin(), label.end(), '/', '_');
std::replace(label.begin(), label.end(), '?', ':');
auto filename = uniqueFilePath(filePrefix + "-" + label, "csv");
std::ofstream out(filename);
// \todo: fix hardcoded sim_time - issue #18
out << "time, " << c->Label() << std::endl;
for (unsigned int j = 0; j < c->Size(); ++j)
{
ignition::math::Vector2d pt = c->Point(j);
out << pt.X() << ", " << pt.Y() << std::endl;
}
out.close();
ignmsg << "Plot exported to file [" << filename << "]" << std::endl;
}
}
}
// Register this plugin
IGNITION_ADD_PLUGIN(ignition::gui::plugins::plot::Plot,
ignition::gui::Plugin)
| 29.522424 | 80 | 0.642798 | Levi-Armstrong |
570832e0c44f4b20771d63d64d0ef251931f02ca | 1,707 | hpp | C++ | include/process.hpp | MRLintern/System-Monitor | c7acce4b88ece5791906a8aaca6c4cbc9f584183 | [
"MIT"
] | 5 | 2021-02-16T16:39:33.000Z | 2021-08-11T04:08:45.000Z | include/process.hpp | MRLintern/System-Monitor | c7acce4b88ece5791906a8aaca6c4cbc9f584183 | [
"MIT"
] | 2 | 2021-08-17T22:05:25.000Z | 2021-08-21T02:18:43.000Z | include/process.hpp | MRLintern/System-Monitor | c7acce4b88ece5791906a8aaca6c4cbc9f584183 | [
"MIT"
] | 10 | 2020-04-15T18:57:48.000Z | 2022-01-07T17:18:22.000Z | #ifndef PROCESS_H
#define PROCESS_H
#include <string>
/*
Basic class for Process representation
It contains relevant attributes as shown below
*/
class Process {
public:
// constructor to initialize Process with the read process-ID from filesystem
Process(int pid);
// Return this process's ID
int Pid();
// Return the user (name) that generated this process
std::string User();
// Return the command that generated this process
std::string Command();
// Return this process's CPU utilization
// value is given in percent
float CpuUtilization() const;
// Return this process's memory utilization in MB
std::string Ram();
// Return the age of this process (in seconds)
long int UpTime();
// Declare any necessary private members
private:
// process-ID
int processId_;
// user name that generated this process
std::string user_;
// command that generated this process
std::string command_;
// CPU usage of the process
float cpuUsage_;
// processes memory utilization
std::string ram_;
// age of this process
long uptime_;
// CPU values of a process
enum ProcessCPUStates {
kUtime_ = 0,
kStime_,
kCutime_,
kCstime_,
kStarttime_
};
// calculate the CPU utilization of this process and save in cpuUsage_
void calculateCpuUsage();
// determine the user name that generated this process and save in user_
void determineUser();
// determine the command that generated this process and save in command_
void determineCommand();
// determine the memory utilization of that process and save in ram_
void determineRam();
// determine the age of this process and save in uptime_
void determineUptime();
};
#endif | 27.532258 | 79 | 0.721734 | MRLintern |
570a931589d79c90268ae265d814f68e9f604274 | 4,955 | cpp | C++ | gui/miniplot.cpp | klindworth/disparity_estimation | 74759d35f7635ff725629a1ae555d313f3e9fb29 | [
"BSD-2-Clause"
] | null | null | null | gui/miniplot.cpp | klindworth/disparity_estimation | 74759d35f7635ff725629a1ae555d313f3e9fb29 | [
"BSD-2-Clause"
] | null | null | null | gui/miniplot.cpp | klindworth/disparity_estimation | 74759d35f7635ff725629a1ae555d313f3e9fb29 | [
"BSD-2-Clause"
] | null | null | null | /*
Copyright (c) 2013, Kai Klindworth
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "miniplot.h"
#include <QPainter>
#include <QMouseEvent>
#include <limits>
#include <cmath>
#include <iostream>
MiniPlot::MiniPlot(QWidget *parent) :
QWidget(parent)
{
m_ready = false;
m_values = nullptr;
m_perdatapoint = 0;
m_len = 0;
m_margin = 3;
m_invert = false;
setMinimumHeight(150);
m_marker = -1;
setMouseTracking(true);
}
void MiniPlot::setValues(float *values, const stat_t& analysis, int len, int offset)
{
m_offset = offset;
m_analysis = analysis;
m_values = values;
m_len = len;
update();
}
void MiniPlot::setMarker(int x)
{
m_marker = x;
update();
}
void MiniPlot::setInverted(bool inverted)
{
m_invert = inverted;
update();
}
void MiniPlot::clear()
{
m_len = 0;
m_ready = false;
}
void MiniPlot::paintEvent(QPaintEvent *)
{
if(m_len > 0)
{
m_ready = true;
QPainter painter(this);
QPalette pal = QPalette();
QColor penColor(pal.color(QPalette::WindowText));
QPen pen;
pen.setColor(penColor);
painter.setPen(pen);
float min = m_analysis.min;
float max = m_analysis.max;
//calculate dimensions
m_perdatapoint = (this->width() - 2*m_margin) / (m_len-1);
double perval = (this->height() - 2*m_margin)/(double)(max - min);
//draw axis
QPoint last(m_margin,m_margin);
painter.drawLine(last, QPoint(m_margin, this->height()-m_margin));
painter.drawLine(QPoint(this->width()-m_margin, this->height()-m_margin), QPoint(m_margin, this->height()-m_margin));
int offset = this->height() - m_margin;
//draw data
if(!m_invert)
{
for(int i = 0; i < m_len; ++i)
{
int val = perval*(m_values[i]-min);
QPoint current(m_perdatapoint*i+m_margin, offset-val);
painter.drawLine(last, current);
last = current;
}
}
else
{
for(int i = m_len-1; i >= 0; --i)
{
int val = perval*(m_values[i]-min);
QPoint current(m_perdatapoint*(m_len-1-i)+m_margin, offset-val);
painter.drawLine(last, current);
last = current;
}
}
//draw marker
if(m_marker >= 0 && m_marker < m_len)
{
QPen pen;
pen.setColor(penColor);
pen.setWidth(4);
painter.setPen(pen);
int val = perval*(m_values[m_marker]-min);
int xpos;
if(!m_invert)
xpos = m_marker;
else
xpos = m_len - 1 - m_marker;
QPoint current(m_perdatapoint*xpos+m_margin, offset-val);
painter.drawPoint(current);
}
//draw mean/std
pen.setStyle(Qt::DashLine);
pen.setColor(penColor);
painter.setPen(pen);
int meanpos = offset-(m_analysis.mean-min)*perval;
painter.drawLine(QPoint(m_margin, meanpos), QPoint(this->width()-2*m_margin, meanpos));
int stddevDelta = m_analysis.stddev*perval;
pen.setStyle(Qt::DotLine);
painter.setPen(pen);
painter.drawLine(QPoint(m_margin, meanpos-stddevDelta), QPoint(this->width()-2*m_margin, meanpos-stddevDelta));
painter.drawLine(QPoint(m_margin, meanpos+stddevDelta), QPoint(this->width()-2*m_margin, meanpos+stddevDelta));
}
}
int MiniPlot::getDisparity(int x)
{
if(m_ready)
return getValueIndex(x) + m_offset;
return 0;
}
int MiniPlot::getValueIndex(int x)
{
if(m_ready)
{
if(!m_invert)
return ((x - m_margin+m_perdatapoint/2)/m_perdatapoint);
else
return(m_len - 1- (x - m_margin+m_perdatapoint/2)/m_perdatapoint);
}
return -1;
}
void MiniPlot::mouseMoveEvent(QMouseEvent *ev)
{
int x = ev->x();
int idx = getValueIndex(x);
if(idx >= 0 && idx < m_len)
{
setToolTip("disparity: " + QString::number(getDisparity(x)) + ", value: " + QString::number(m_values[idx]));
emit datapointHovered(idx);
}
}
void MiniPlot::mouseReleaseEvent(QMouseEvent *ev)
{
int idx = getValueIndex(ev->x());
if(idx >= 0 && idx < m_len)
emit datapointSelected(idx);
}
| 25.807292 | 119 | 0.708981 | klindworth |
570e37a193fabb0d9f7421016ba27d0c7c1edc71 | 16,306 | cpp | C++ | src/dlgcanalinterfacesettings.cpp | benys/vscpworks | 755a1733d0c55c8dd22d65e0e1ed1598311ef999 | [
"MIT"
] | 1 | 2019-11-22T15:24:50.000Z | 2019-11-22T15:24:50.000Z | src/dlgcanalinterfacesettings.cpp | benys/vscpworks | 755a1733d0c55c8dd22d65e0e1ed1598311ef999 | [
"MIT"
] | 1 | 2020-05-05T18:40:57.000Z | 2020-05-05T18:40:57.000Z | src/dlgcanalinterfacesettings.cpp | benys/vscpworks | 755a1733d0c55c8dd22d65e0e1ed1598311ef999 | [
"MIT"
] | 1 | 2020-05-05T08:07:32.000Z | 2020-05-05T08:07:32.000Z | /////////////////////////////////////////////////////////////////////////////
// Name: dlgcanalinterfacesettings.cpp
// Purpose:
// Author: Ake Hedman
// Modified by:
// Created: Thu 28 Jun 2007 20:45:11 CEST
// RCS-ID:
// Copyright: (C) 2007-2017
// Ake Hedman, Grodans Paradis AB, <akhe@grodansparadis.com>
// Licence:
// 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 file is part of the VSCP (http://www.vscp.org)
//
// This file 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 this file see the file COPYING. If not, write to
// the Free Software Foundation, 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
//
// As a special exception, if other files instantiate templates or use macros
// or inline functions from this file, or you compile this file and link it
// with other works to produce a work based on this file, this file does not
// by itself cause the resulting work to be covered by the GNU General Public
// License. However the source code for this file must still be made available
// in accordance with section (3) of the GNU General Public License.
//
// This exception does not invalidate any other reasons why a work based on
// this file might be covered by the GNU General Public License.
//
// Alternative licenses for VSCP & Friends may be arranged by contacting
// eurosource at info@eurosource.se, http://www.eurosource.se
/////////////////////////////////////////////////////////////////////////////
#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
#pragma implementation "dlgcanalinterfacesettings.h"
#endif
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
////@begin includes
#include "wx/bookctrl.h"
////@end includes
#include "dlgcanalinterfacesettings.h"
////@begin XPM images
////@end XPM images
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// dlgCanalInterfaceSettings type definition
//
IMPLEMENT_DYNAMIC_CLASS( dlgCanalInterfaceSettings, wxPropertySheetDialog )
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// dlgCanalInterfaceSettings event table definition
//
BEGIN_EVENT_TABLE( dlgCanalInterfaceSettings, wxPropertySheetDialog )
////@begin dlgCanalInterfaceSettings event table entries
////@end dlgCanalInterfaceSettings event table entries
END_EVENT_TABLE()
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// dlgCanalInterfaceSettings constructors
//
dlgCanalInterfaceSettings::dlgCanalInterfaceSettings()
{
Init();
}
dlgCanalInterfaceSettings::dlgCanalInterfaceSettings( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
Init();
Create(parent, id, caption, pos, size, style);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// dlgCanalInterfaceSettings creator
//
bool dlgCanalInterfaceSettings::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
////@begin dlgCanalInterfaceSettings creation
SetExtraStyle(wxWS_EX_BLOCK_EVENTS);
wxPropertySheetDialog::Create( parent, id, caption, pos, size, style );
SetSheetStyle(wxPROPSHEET_DEFAULT);
CreateButtons(wxOK|wxCANCEL|wxHELP);
CreateControls();
LayoutDialog();
Centre();
////@end dlgCanalInterfaceSettings creation
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// dlgCanalInterfaceSettings destructor
//
dlgCanalInterfaceSettings::~dlgCanalInterfaceSettings()
{
////@begin dlgCanalInterfaceSettings destruction
////@end dlgCanalInterfaceSettings destruction
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Member initialisation
//
void dlgCanalInterfaceSettings::Init()
{
////@begin dlgCanalInterfaceSettings member initialisation
m_DirectFlags = NULL;
m_DriverName = NULL;
m_PathToDriver = NULL;
m_DeviceConfigurationString = NULL;
m_Flags = NULL;
m_idFilter = NULL;
m_C = NULL;
m_idMask = NULL;
m_RemoteServerURL = NULL;
m_RemoteServerPort = NULL;
m_RemoteServerUsername = NULL;
m_RemoteServerPassword = NULL;
////@end dlgCanalInterfaceSettings member initialisation
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Control creation for dlgCanalInterfaceSettings
//
void dlgCanalInterfaceSettings::CreateControls()
{
////@begin dlgCanalInterfaceSettings content construction
dlgCanalInterfaceSettings* itemPropertySheetDialog1 = this;
wxPanel* itemPanel2 = new wxPanel;
itemPanel2->Create( GetBookCtrl(), ID_PANEL, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER|wxTAB_TRAVERSAL );
wxBoxSizer* itemBoxSizer3 = new wxBoxSizer(wxVERTICAL);
itemPanel2->SetSizer(itemBoxSizer3);
wxBoxSizer* itemBoxSizer4 = new wxBoxSizer(wxVERTICAL);
itemBoxSizer3->Add(itemBoxSizer4, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5);
wxBoxSizer* itemBoxSizer5 = new wxBoxSizer(wxHORIZONTAL);
itemBoxSizer3->Add(itemBoxSizer5, 0, wxALIGN_RIGHT|wxALL, 5);
wxStaticText* itemStaticText6 = new wxStaticText;
itemStaticText6->Create( itemPanel2, wxID_STATIC, _("Flags:"), wxDefaultPosition, wxDefaultSize, 0 );
itemBoxSizer5->Add(itemStaticText6, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
m_DirectFlags = new wxTextCtrl;
m_DirectFlags->Create( itemPanel2, ID_DirectFlags, _T(""), wxDefaultPosition, wxDefaultSize, wxTE_RIGHT );
itemBoxSizer5->Add(m_DirectFlags, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
itemBoxSizer5->Add(300, 5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
GetBookCtrl()->AddPage(itemPanel2, _("Direct"));
wxPanel* itemPanel9 = new wxPanel;
itemPanel9->Create( GetBookCtrl(), ID_PANEL1, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER|wxTAB_TRAVERSAL );
wxBoxSizer* itemBoxSizer10 = new wxBoxSizer(wxVERTICAL);
itemPanel9->SetSizer(itemBoxSizer10);
wxBoxSizer* itemBoxSizer11 = new wxBoxSizer(wxHORIZONTAL);
itemBoxSizer10->Add(itemBoxSizer11, 0, wxALIGN_RIGHT|wxALL, 1);
wxStaticText* itemStaticText12 = new wxStaticText;
itemStaticText12->Create( itemPanel9, wxID_STATIC, _("Name of driver :"), wxDefaultPosition, wxDefaultSize, 0 );
itemBoxSizer11->Add(itemStaticText12, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
m_DriverName = new wxTextCtrl;
m_DriverName->Create( itemPanel9, ID_DriverName, _T(""), wxDefaultPosition, wxSize(300, -1), 0 );
itemBoxSizer11->Add(m_DriverName, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
itemBoxSizer11->Add(50, 5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
wxBoxSizer* itemBoxSizer15 = new wxBoxSizer(wxHORIZONTAL);
itemBoxSizer10->Add(itemBoxSizer15, 0, wxALIGN_RIGHT|wxALL, 1);
wxStaticText* itemStaticText16 = new wxStaticText;
itemStaticText16->Create( itemPanel9, wxID_STATIC, _("Path to driver :"), wxDefaultPosition, wxDefaultSize, 0 );
itemBoxSizer15->Add(itemStaticText16, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
m_PathToDriver = new wxTextCtrl;
m_PathToDriver->Create( itemPanel9, ID_PathToDriver, _T(""), wxDefaultPosition, wxSize(300, -1), 0 );
itemBoxSizer15->Add(m_PathToDriver, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
itemBoxSizer15->Add(5, 5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
wxButton* itemButton19 = new wxButton;
itemButton19->Create( itemPanel9, ID_BUTTON_CANAL_DRIVER_PATH, _("..."), wxDefaultPosition, wxSize(30, -1), 0 );
itemBoxSizer15->Add(itemButton19, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
itemBoxSizer15->Add(20, 5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
wxBoxSizer* itemBoxSizer21 = new wxBoxSizer(wxHORIZONTAL);
itemBoxSizer10->Add(itemBoxSizer21, 0, wxALIGN_RIGHT|wxALL, 1);
wxStaticText* itemStaticText22 = new wxStaticText;
itemStaticText22->Create( itemPanel9, wxID_STATIC, _("Device configuration string :"), wxDefaultPosition, wxDefaultSize, 0 );
itemBoxSizer21->Add(itemStaticText22, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
m_DeviceConfigurationString = new wxTextCtrl;
m_DeviceConfigurationString->Create( itemPanel9, ID_DeviceConfigurationString, _T(""), wxDefaultPosition, wxSize(300, -1), 0 );
itemBoxSizer21->Add(m_DeviceConfigurationString, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
wxButton* itemButton24 = new wxButton;
itemButton24->Create( itemPanel9, ID_BUTTON_CANAL_CONFIGURATION, _("..."), wxDefaultPosition, wxSize(30, -1), 0 );
itemBoxSizer21->Add(itemButton24, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
itemBoxSizer21->Add(20, 5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
wxBoxSizer* itemBoxSizer26 = new wxBoxSizer(wxHORIZONTAL);
itemBoxSizer10->Add(itemBoxSizer26, 0, wxALIGN_RIGHT|wxALL, 1);
wxStaticText* itemStaticText27 = new wxStaticText;
itemStaticText27->Create( itemPanel9, wxID_STATIC, _("Flags :"), wxDefaultPosition, wxDefaultSize, 0 );
itemBoxSizer26->Add(itemStaticText27, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
m_Flags = new wxTextCtrl;
m_Flags->Create( itemPanel9, ID_Flags, _T(""), wxDefaultPosition, wxSize(50, -1), 0 );
itemBoxSizer26->Add(m_Flags, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
itemBoxSizer26->Add(302, 5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
wxBoxSizer* itemBoxSizer30 = new wxBoxSizer(wxHORIZONTAL);
itemBoxSizer10->Add(itemBoxSizer30, 0, wxALIGN_RIGHT|wxALL, 1);
m_idFilter = new wxStaticText;
m_idFilter->Create( itemPanel9, wxID_STATIC, _("ID Filter :"), wxDefaultPosition, wxDefaultSize, 0 );
itemBoxSizer30->Add(m_idFilter, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
m_C = new wxTextCtrl;
m_C->Create( itemPanel9, ID_C, _T(""), wxDefaultPosition, wxSize(50, -1), 0 );
itemBoxSizer30->Add(m_C, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
wxStaticText* itemStaticText33 = new wxStaticText;
itemStaticText33->Create( itemPanel9, wxID_STATIC, _("ID Mask :"), wxDefaultPosition, wxDefaultSize, 0 );
itemBoxSizer30->Add(itemStaticText33, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
m_idMask = new wxTextCtrl;
m_idMask->Create( itemPanel9, ID_IdMask, _T(""), wxDefaultPosition, wxSize(50, -1), 0 );
itemBoxSizer30->Add(m_idMask, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
wxButton* itemButton35 = new wxButton;
itemButton35->Create( itemPanel9, ID_BUTTON4, _("..."), wxDefaultPosition, wxSize(30, -1), 0 );
itemBoxSizer30->Add(itemButton35, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
itemBoxSizer30->Add(158, 5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
wxBoxSizer* itemBoxSizer37 = new wxBoxSizer(wxHORIZONTAL);
itemBoxSizer10->Add(itemBoxSizer37, 0, wxALIGN_RIGHT|wxALL, 1);
wxButton* itemButton38 = new wxButton;
itemButton38->Create( itemPanel9, ID_BUTTON_CANAL_DRIVER_WIZARD, _("Wizard..."), wxDefaultPosition, wxDefaultSize, 0 );
itemBoxSizer37->Add(itemButton38, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
itemBoxSizer37->Add(270, 5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
GetBookCtrl()->AddPage(itemPanel9, _("Driver"));
wxPanel* itemPanel40 = new wxPanel;
itemPanel40->Create( GetBookCtrl(), ID_PANEL2, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER|wxTAB_TRAVERSAL );
wxBoxSizer* itemBoxSizer41 = new wxBoxSizer(wxVERTICAL);
itemPanel40->SetSizer(itemBoxSizer41);
wxBoxSizer* itemBoxSizer42 = new wxBoxSizer(wxVERTICAL);
itemBoxSizer41->Add(itemBoxSizer42, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5);
wxBoxSizer* itemBoxSizer43 = new wxBoxSizer(wxHORIZONTAL);
itemBoxSizer41->Add(itemBoxSizer43, 0, wxALIGN_RIGHT|wxALL, 1);
wxStaticText* itemStaticText44 = new wxStaticText;
itemStaticText44->Create( itemPanel40, wxID_STATIC, _("Server URL:"), wxDefaultPosition, wxDefaultSize, 0 );
itemBoxSizer43->Add(itemStaticText44, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
m_RemoteServerURL = new wxTextCtrl;
m_RemoteServerURL->Create( itemPanel40, ID_RemoteServerURL, _T(""), wxDefaultPosition, wxSize(400, -1), wxTE_RIGHT );
itemBoxSizer43->Add(m_RemoteServerURL, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
wxBoxSizer* itemBoxSizer46 = new wxBoxSizer(wxHORIZONTAL);
itemBoxSizer41->Add(itemBoxSizer46, 0, wxALIGN_RIGHT|wxALL, 1);
wxStaticText* itemStaticText47 = new wxStaticText;
itemStaticText47->Create( itemPanel40, wxID_STATIC, _("Server port:"), wxDefaultPosition, wxDefaultSize, 0 );
itemBoxSizer46->Add(itemStaticText47, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
m_RemoteServerPort = new wxTextCtrl;
m_RemoteServerPort->Create( itemPanel40, ID_RemoteServerPort, _T(""), wxDefaultPosition, wxSize(50, -1), wxTE_RIGHT );
itemBoxSizer46->Add(m_RemoteServerPort, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
itemBoxSizer46->Add(348, 5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
wxBoxSizer* itemBoxSizer50 = new wxBoxSizer(wxHORIZONTAL);
itemBoxSizer41->Add(itemBoxSizer50, 0, wxALIGN_RIGHT|wxALL, 1);
wxStaticText* itemStaticText51 = new wxStaticText;
itemStaticText51->Create( itemPanel40, wxID_STATIC, _("Username:"), wxDefaultPosition, wxDefaultSize, 0 );
itemBoxSizer50->Add(itemStaticText51, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
m_RemoteServerUsername = new wxTextCtrl;
m_RemoteServerUsername->Create( itemPanel40, ID_RemoteServerUsername, _T(""), wxDefaultPosition, wxSize(200, -1), wxTE_RIGHT );
itemBoxSizer50->Add(m_RemoteServerUsername, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
itemBoxSizer50->Add(200, 5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
wxBoxSizer* itemBoxSizer54 = new wxBoxSizer(wxHORIZONTAL);
itemBoxSizer41->Add(itemBoxSizer54, 0, wxALIGN_RIGHT|wxALL, 1);
wxStaticText* itemStaticText55 = new wxStaticText;
itemStaticText55->Create( itemPanel40, wxID_STATIC, _("Password:"), wxDefaultPosition, wxDefaultSize, 0 );
itemBoxSizer54->Add(itemStaticText55, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
m_RemoteServerPassword = new wxTextCtrl;
m_RemoteServerPassword->Create( itemPanel40, ID_RemoteServerPassword, _T(""), wxDefaultPosition, wxSize(200, -1), wxTE_PASSWORD|wxTE_RIGHT );
itemBoxSizer54->Add(m_RemoteServerPassword, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
itemBoxSizer54->Add(200, 5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
wxBoxSizer* itemBoxSizer58 = new wxBoxSizer(wxHORIZONTAL);
itemBoxSizer41->Add(itemBoxSizer58, 0, wxALIGN_RIGHT|wxALL, 5);
wxButton* itemButton59 = new wxButton;
itemButton59->Create( itemPanel40, ID_BUTTON1, _("Test connection"), wxDefaultPosition, wxDefaultSize, 0 );
itemBoxSizer58->Add(itemButton59, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
itemBoxSizer58->Add(285, 5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1);
GetBookCtrl()->AddPage(itemPanel40, _("Remote"));
////@end dlgCanalInterfaceSettings content construction
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Should we show tooltips?
//
bool dlgCanalInterfaceSettings::ShowToolTips()
{
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Get bitmap resources
//
wxBitmap dlgCanalInterfaceSettings::GetBitmapResource( const wxString& name )
{
// Bitmap retrieval
////@begin dlgCanalInterfaceSettings bitmap retrieval
wxUnusedVar(name);
return wxNullBitmap;
////@end dlgCanalInterfaceSettings bitmap retrieval
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Get icon resources
//
wxIcon dlgCanalInterfaceSettings::GetIconResource( const wxString& name )
{
// Icon retrieval
////@begin dlgCanalInterfaceSettings icon retrieval
wxUnusedVar(name);
return wxNullIcon;
////@end dlgCanalInterfaceSettings icon retrieval
}
| 42.243523 | 164 | 0.703545 | benys |
570ee372540af36521e1f71b807ea5826353f4cd | 588 | hh | C++ | include/BucatiniSteppingAction.hh | EdoPro98/Bucatini | a904d9a8c48ec90b3dfe9d370ae51f0653b14def | [
"MIT"
] | null | null | null | include/BucatiniSteppingAction.hh | EdoPro98/Bucatini | a904d9a8c48ec90b3dfe9d370ae51f0653b14def | [
"MIT"
] | null | null | null | include/BucatiniSteppingAction.hh | EdoPro98/Bucatini | a904d9a8c48ec90b3dfe9d370ae51f0653b14def | [
"MIT"
] | null | null | null | #ifndef BucatiniSteppingAction_h
#define BucatiniSteppingAction_h 1
#include "G4UserSteppingAction.hh"
class BucatiniDetectorConstruction;
class BucatiniEventAction;
class BucatiniSteppingAction : public G4UserSteppingAction {
public:
BucatiniSteppingAction(BucatiniEventAction* eventAction);
~BucatiniSteppingAction();
void UserSteppingAction(const G4Step* step);
void globalSteppingAction(const G4Step* step);
void opticalSteppingAction(const G4Step* step);
private:
BucatiniEventAction* fEventAction;
};
#endif
//**************************************************
| 21.777778 | 60 | 0.746599 | EdoPro98 |
570fad9597af16abb7e67a925c028e5e02080fa6 | 711 | cpp | C++ | lang/C++/priority-queue-2.cpp | ethansaxenian/RosettaDecode | 8ea1a42a5f792280b50193ad47545d14ee371fb7 | [
"MIT"
] | 1 | 2018-11-09T22:08:38.000Z | 2018-11-09T22:08:38.000Z | lang/C++/priority-queue-2.cpp | ethansaxenian/RosettaDecode | 8ea1a42a5f792280b50193ad47545d14ee371fb7 | [
"MIT"
] | null | null | null | lang/C++/priority-queue-2.cpp | ethansaxenian/RosettaDecode | 8ea1a42a5f792280b50193ad47545d14ee371fb7 | [
"MIT"
] | 1 | 2018-11-09T22:08:40.000Z | 2018-11-09T22:08:40.000Z | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <utility>
int main() {
std::vector<std::pair<int, std::string> > pq;
pq.push_back(std::make_pair(3, "Clear drains"));
pq.push_back(std::make_pair(4, "Feed cat"));
pq.push_back(std::make_pair(5, "Make tea"));
pq.push_back(std::make_pair(1, "Solve RC tasks"));
// heapify
std::make_heap(pq.begin(), pq.end());
// enqueue
pq.push_back(std::make_pair(2, "Tax return"));
std::push_heap(pq.begin(), pq.end());
while (!pq.empty()) {
// peek
std::cout << pq[0].first << ", " << pq[0].second << std::endl;
// dequeue
std::pop_heap(pq.begin(), pq.end());
pq.pop_back();
}
return 0;
}
| 22.935484 | 66 | 0.604782 | ethansaxenian |
571228983be129c0cc201f4b7dba8738bc2d5afa | 203 | cpp | C++ | BasicGameFramework/Object/SampleSprite.cpp | dlwlxns4/WitchHouse | 7b2fd8acead69baa9b0850e0ddcb7520b32ef47e | [
"BSD-3-Clause"
] | null | null | null | BasicGameFramework/Object/SampleSprite.cpp | dlwlxns4/WitchHouse | 7b2fd8acead69baa9b0850e0ddcb7520b32ef47e | [
"BSD-3-Clause"
] | null | null | null | BasicGameFramework/Object/SampleSprite.cpp | dlwlxns4/WitchHouse | 7b2fd8acead69baa9b0850e0ddcb7520b32ef47e | [
"BSD-3-Clause"
] | null | null | null | #include "SampleSprite.h"
#include "../Component/TileSelectComponent.h"
void SampleSprite::Init()
{
TileSelectComponent* tileSelectComponent = new TileSelectComponent(this,1);
GameObject::Init();
}
| 18.454545 | 76 | 0.763547 | dlwlxns4 |
57127b1a41a6840be801500e09dd26dc88503986 | 8,403 | cpp | C++ | CPP/7zip/UI/FileManager/SettingsPage.cpp | sdottaka/sevenzip | 69f3d03c97753429c3989cc26243578ec32b18b0 | [
"DOC",
"Info-ZIP"
] | 8 | 2019-01-04T03:06:36.000Z | 2022-03-17T07:32:41.000Z | CPP/7zip/UI/FileManager/SettingsPage.cpp | WinMerge/sevenzip | 69f3d03c97753429c3989cc26243578ec32b18b0 | [
"DOC",
"Info-ZIP"
] | 1 | 2021-12-24T14:50:09.000Z | 2021-12-27T11:58:49.000Z | CPP/7zip/UI/FileManager/SettingsPage.cpp | WinMerge/sevenzip | b361efa151e94e117741298bbf12b5e98ef49005 | [
"DOC",
"Info-ZIP"
] | 1 | 2019-03-20T07:28:01.000Z | 2019-03-20T07:28:01.000Z | // SettingsPage.cpp
#include "StdAfx.h"
// #include "../../../Common/IntToString.h"
// #include "../../../Common/StringConvert.h"
#ifndef UNDER_CE
#include "../../../Windows/MemoryLock.h"
// #include "../../../Windows/System.h"
#endif
// #include "../Common/ZipRegistry.h"
#include "HelpUtils.h"
#include "LangUtils.h"
#include "RegistryUtils.h"
#include "SettingsPage.h"
#include "SettingsPageRes.h"
using namespace NWindows;
static const UInt32 kLangIDs[] =
{
IDX_SETTINGS_SHOW_DOTS,
IDX_SETTINGS_SHOW_REAL_FILE_ICONS,
IDX_SETTINGS_SHOW_SYSTEM_MENU,
IDX_SETTINGS_FULL_ROW,
IDX_SETTINGS_SHOW_GRID,
IDX_SETTINGS_SINGLE_CLICK,
IDX_SETTINGS_ALTERNATIVE_SELECTION,
IDX_SETTINGS_LARGE_PAGES
// , IDT_COMPRESS_MEMORY
};
#define kSettingsTopic "FM/options.htm#settings"
extern bool IsLargePageSupported();
/*
static void AddMemSize(UString &res, UInt64 size, bool needRound = false)
{
char c;
unsigned moveBits = 0;
if (needRound)
{
UInt64 rn = 0;
if (size >= (1 << 31))
rn = (1 << 28) - 1;
UInt32 kRound = (1 << 20) - 1;
if (rn < kRound)
rn = kRound;
size += rn;
size &= ~rn;
}
if (size >= ((UInt64)1 << 31) && (size & 0x3FFFFFFF) == 0)
{ moveBits = 30; c = 'G'; }
else
{ moveBits = 20; c = 'M'; }
res.Add_UInt64(size >> moveBits);
res.Add_Space();
if (moveBits != 0)
res += c;
res += 'B';
}
int CSettingsPage::AddMemComboItem(UInt64 size, UInt64 percents, bool isDefault)
{
UString sUser;
UString sRegistry;
if (size == 0)
{
UString s;
s.Add_UInt64(percents);
s += '%';
if (isDefault)
sUser = "* ";
else
sRegistry = s;
sUser += s;
}
else
{
AddMemSize(sUser, size);
sRegistry = sUser;
for (;;)
{
int pos = sRegistry.Find(L' ');
if (pos < 0)
break;
sRegistry.Delete(pos);
}
if (!sRegistry.IsEmpty())
if (sRegistry.Back() == 'B')
sRegistry.DeleteBack();
}
const int index = (int)_memCombo.AddString(sUser);
_memCombo.SetItemData(index, _memLimitStrings.Size());
_memLimitStrings.Add(sRegistry);
return index;
}
*/
bool CSettingsPage::OnInit()
{
_wasChanged = false;
_largePages_wasChanged = false;
/*
_wasChanged_MemLimit = false;
_memLimitStrings.Clear();
_memCombo.Attach(GetItem(IDC_SETTINGS_MEM));
*/
LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs));
CFmSettings st;
st.Load();
CheckButton(IDX_SETTINGS_SHOW_DOTS, st.ShowDots);
CheckButton(IDX_SETTINGS_SHOW_REAL_FILE_ICONS, st.ShowRealFileIcons);
CheckButton(IDX_SETTINGS_FULL_ROW, st.FullRow);
CheckButton(IDX_SETTINGS_SHOW_GRID, st.ShowGrid);
CheckButton(IDX_SETTINGS_SINGLE_CLICK, st.SingleClick);
CheckButton(IDX_SETTINGS_ALTERNATIVE_SELECTION, st.AlternativeSelection);
// CheckButton(IDX_SETTINGS_UNDERLINE, st.Underline);
CheckButton(IDX_SETTINGS_SHOW_SYSTEM_MENU, st.ShowSystemMenu);
if (IsLargePageSupported())
CheckButton(IDX_SETTINGS_LARGE_PAGES, ReadLockMemoryEnable());
else
EnableItem(IDX_SETTINGS_LARGE_PAGES, false);
/*
NCompression::CMemUse mu;
bool needSetCur = NCompression::MemLimit_Load(mu);
UInt64 curMemLimit;
{
AddMemComboItem(0, 90, true);
_memCombo.SetCurSel(0);
}
if (mu.IsPercent)
{
const int index = AddMemComboItem(0, mu.Val);
_memCombo.SetCurSel(index);
needSetCur = false;
}
{
_ramSize = (UInt64)(sizeof(size_t)) << 29;
_ramSize_Defined = NSystem::GetRamSize(_ramSize);
UString s;
if (_ramSize_Defined)
{
s += "/ ";
AddMemSize(s, _ramSize, true);
}
SetItemText(IDT_SETTINGS_MEM_RAM, s);
curMemLimit = mu.GetBytes(_ramSize);
// size = 100 << 20; // for debug only;
for (unsigned i = (27) * 2;; i++)
{
UInt64 size = (UInt64)(2 + (i & 1)) << (i / 2);
if (i > (20 + sizeof(size_t) * 3 * 1 - 1) * 2)
size = (UInt64)(Int64)-1;
if (needSetCur && (size >= curMemLimit))
{
const int index = AddMemComboItem(curMemLimit);
_memCombo.SetCurSel(index);
needSetCur = false;
if (size == curMemLimit)
continue;
}
if (size == (UInt64)(Int64)-1)
break;
AddMemComboItem(size);
}
}
*/
// EnableSubItems();
return CPropertyPage::OnInit();
}
/*
void CSettingsPage::EnableSubItems()
{
EnableItem(IDX_SETTINGS_UNDERLINE, IsButtonCheckedBool(IDX_SETTINGS_SINGLE_CLICK));
}
*/
/*
static void AddSize_MB(UString &s, UInt64 size)
{
s.Add_UInt64((size + (1 << 20) - 1) >> 20);
s += " MB";
}
*/
LONG CSettingsPage::OnApply()
{
if (_wasChanged)
{
CFmSettings st;
st.ShowDots = IsButtonCheckedBool(IDX_SETTINGS_SHOW_DOTS);
st.ShowRealFileIcons = IsButtonCheckedBool(IDX_SETTINGS_SHOW_REAL_FILE_ICONS);
st.FullRow = IsButtonCheckedBool(IDX_SETTINGS_FULL_ROW);
st.ShowGrid = IsButtonCheckedBool(IDX_SETTINGS_SHOW_GRID);
st.SingleClick = IsButtonCheckedBool(IDX_SETTINGS_SINGLE_CLICK);
st.AlternativeSelection = IsButtonCheckedBool(IDX_SETTINGS_ALTERNATIVE_SELECTION);
// st.Underline = IsButtonCheckedBool(IDX_SETTINGS_UNDERLINE);
st.ShowSystemMenu = IsButtonCheckedBool(IDX_SETTINGS_SHOW_SYSTEM_MENU);
st.Save();
_wasChanged = false;
}
#ifndef UNDER_CE
if (_largePages_wasChanged)
{
if (IsLargePageSupported())
{
bool enable = IsButtonCheckedBool(IDX_SETTINGS_LARGE_PAGES);
NSecurity::EnablePrivilege_LockMemory(enable);
SaveLockMemoryEnable(enable);
}
_largePages_wasChanged = false;
}
#endif
/*
if (_wasChanged_MemLimit)
{
const unsigned index = (int)_memCombo.GetItemData_of_CurSel();
const UString str = _memLimitStrings[index];
bool needSave = true;
NCompression::CMemUse mu;
if (_ramSize_Defined)
mu.Parse(str);
if (mu.IsDefined)
{
const UInt64 usage64 = mu.GetBytes(_ramSize);
if (_ramSize <= usage64)
{
UString s2 = LangString(IDT_COMPRESS_MEMORY);
if (s2.IsEmpty())
GetItemText(IDT_COMPRESS_MEMORY, s2);
UString s;
s += "The selected value is not safe for system performance.";
s.Add_LF();
s += "The memory consumption for compression operation will exceed RAM size.";
s.Add_LF();
s.Add_LF();
AddSize_MB(s, usage64);
if (!s2.IsEmpty())
{
s += " : ";
s += s2;
}
s.Add_LF();
AddSize_MB(s, _ramSize);
s += " : RAM";
s.Add_LF();
s.Add_LF();
s += "Are you sure you want set that unsafe value for memory usage?";
int res = MessageBoxW(*this, s, L"7-Zip", MB_YESNOCANCEL | MB_ICONQUESTION);
if (res != IDYES)
needSave = false;
}
}
if (needSave)
{
NCompression::MemLimit_Save(str);
_wasChanged_MemLimit = false;
}
else
return PSNRET_INVALID_NOCHANGEPAGE;
}
*/
return PSNRET_NOERROR;
}
void CSettingsPage::OnNotifyHelp()
{
ShowHelpWindow(kSettingsTopic);
}
/*
bool CSettingsPage::OnCommand(int code, int itemID, LPARAM param)
{
if (code == CBN_SELCHANGE)
{
switch (itemID)
{
case IDC_SETTINGS_MEM:
{
_wasChanged_MemLimit = true;
Changed();
break;
}
}
}
return CPropertyPage::OnCommand(code, itemID, param);
}
*/
bool CSettingsPage::OnButtonClicked(int buttonID, HWND buttonHWND)
{
switch (buttonID)
{
case IDX_SETTINGS_SINGLE_CLICK:
/*
EnableSubItems();
break;
*/
case IDX_SETTINGS_SHOW_DOTS:
case IDX_SETTINGS_SHOW_SYSTEM_MENU:
case IDX_SETTINGS_SHOW_REAL_FILE_ICONS:
case IDX_SETTINGS_FULL_ROW:
case IDX_SETTINGS_SHOW_GRID:
case IDX_SETTINGS_ALTERNATIVE_SELECTION:
_wasChanged = true;
break;
case IDX_SETTINGS_LARGE_PAGES:
_largePages_wasChanged = true;
break;
default:
return CPropertyPage::OnButtonClicked(buttonID, buttonHWND);
}
Changed();
return true;
}
| 23.940171 | 87 | 0.613709 | sdottaka |
571346c554ca35c100e13f7ccd627a56d54347ea | 4,309 | cpp | C++ | rfsim/plugins/BallFollowMovement.cpp | thofyb/RobotFootballSim | 646f88b52e1c29aa7480dc9e473fec1e8ce41ecf | [
"MIT"
] | 1 | 2021-04-13T08:31:05.000Z | 2021-04-13T08:31:05.000Z | rfsim/plugins/BallFollowMovement.cpp | thofyb/RobotFootballSim | 646f88b52e1c29aa7480dc9e473fec1e8ce41ecf | [
"MIT"
] | 2 | 2021-04-06T19:03:17.000Z | 2021-04-07T16:32:28.000Z | rfsim/plugins/BallFollowMovement.cpp | thofyb/RobotFootballSim | 646f88b52e1c29aa7480dc9e473fec1e8ce41ecf | [
"MIT"
] | 1 | 2021-04-19T12:06:52.000Z | 2021-04-19T12:06:52.000Z | ////////////////////////////////////////////////////////////////////////////////////
// MIT License //
// //
// Copyright (c) 2021 The RobotFootballSim project authors //
// //
// 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. //
////////////////////////////////////////////////////////////////////////////////////
#define RFSIM_EXPORTS
#include <rfsim/rfsim.h>
#include <glm/glm.hpp>
#include <glm/vec2.hpp>
#include <iostream>
#include <random>
#include <chrono>
#include <cstring>
#include <cmath>
static int teamSize = 0;
static std::vector<std::pair<float, float>> *vrand;
RFSIM_DEFINE_FUNCTION_INIT {
std::strcpy(context->name, "Ball Follow Movement (testing)");
std::strcpy(context->description, "Movement to follow ball and hit it (does not avoids collisions)");
return rfsim_status_success;
};
RFSIM_DEFINE_FUNCTION_BEGIN_GAME {
teamSize = start->team_size;
vrand = new std::vector<std::pair<float, float>>(teamSize);
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<float> distr(0.4f, 0.6f);
for (int i = 0; i < teamSize; i++) {
(*vrand)[i] = { distr(gen), distr(gen) };
}
return rfsim_status_success;
};
RFSIM_DEFINE_FUNCTION_TICK_GAME {
auto baseVelA = 1.0f;
auto baseVelB = 1.1f;
auto& b = state->ball;
auto bp = glm::vec2(b.position.x, b.position.y);
for (int i = 0; i < teamSize; i++) {
auto &r = state->team_a[i];
auto rp = glm::vec2(r.position.x, r.position.y);
auto a = r.angle;
auto rd = glm::vec2(std::cos(a), std::sin(a));
auto bd = bp - rp;
auto dotRdBd = glm::dot(rd, bd) / glm::length(rd) / glm::length(bd);
auto d = glm::length(bd) + 1.0f;
auto left = (d + dotRdBd) * (*vrand)[i].first;
auto right = d * (*vrand)[i].second;
state->team_a_control[i] = {left * baseVelA, right * baseVelA};
}
for (int i = 0; i < teamSize; i++) {
auto &r = state->team_b[i];
auto rp = glm::vec2(r.position.x, r.position.y);
auto a = r.angle;
auto rd = glm::vec2(std::cos(a), std::sin(a));
auto bd = bp - rp;
auto dotRdBd = glm::dot(rd, bd) / glm::length(rd) / glm::length(bd);
auto d = glm::length(bd) + 1.0f;
auto left = (d + dotRdBd) * (*vrand)[i].first;
auto right = d * (*vrand)[i].second;
state->team_b_control[i] = {left * baseVelB, right * baseVelB};
}
return rfsim_status_success;
};
RFSIM_DEFINE_FUNCTION_END_GAME {
delete vrand;
vrand = nullptr;
return rfsim_status_success;
};
RFSIM_DEFINE_FUNCTION_FINALIZE {
return rfsim_status_success;
};
| 39.898148 | 105 | 0.534231 | thofyb |
5714b18a6ac8beaf38c28ac79713d2f9f12d9478 | 4,688 | cpp | C++ | core/srk_uts_packet.cpp | matiasinsaurralde/sonork | 25514411bca36368fc2719b6fb8ab1367e1bb218 | [
"BSD-Source-Code"
] | 2 | 2016-06-17T07:40:53.000Z | 2019-10-31T19:37:55.000Z | core/srk_uts_packet.cpp | matiasinsaurralde/sonork | 25514411bca36368fc2719b6fb8ab1367e1bb218 | [
"BSD-Source-Code"
] | null | null | null | core/srk_uts_packet.cpp | matiasinsaurralde/sonork | 25514411bca36368fc2719b6fb8ab1367e1bb218 | [
"BSD-Source-Code"
] | null | null | null | #include "srk_defs.h"
#pragma hdrstop
#include "srk_uts_packet.h"
#include "srk_codec_io.h"
/*
Sonork Messaging System
Portions Copyright (C) 2001 Sonork SRL:
This program is free software; you can redistribute it and/or modify
it under the terms of the Sonork Source Code License (SSCL) Version 1.
You should have received a copy of the SSCL along with this program;
if not, write to sscl@sonork.com.
You should NOT use this source code before reading and accepting the
Sonork Source Code License (SSCL), doing so will indicate your agreement
to the the terms which may be differ for each version of the software.
This comment section, indicating the existence and requirement of
acceptance of the SSCL may not be removed from the source code.
*/
#define ENCODE_SECTION_STARTS\
TSonorkPacketWriter CODEC(DataPtr(),pSz); \
header.cmd =(WORD)pCmd;header.flags =(WORD)(pVersion&SONORK_UTS_PM_VERSION);
#define ENCODE_SECTION_ENDS \
if( CODEC.CodecOk() )return sizeof(TSonorkUTSPacket)+CODEC.Size();\
return 0
#define DECODE_SECTION_STARTS \
TSonorkPacketReader CODEC(TGP->DataPtr(),pSz); \
#define DECODE_SECTION_ENDS \
if( CODEC.CodecOk() )return true\
return false
// ----------------------------------------------------------------------------
DWORD
TSonorkUTSPacket::E_CtrlMsg(DWORD pSz,DWORD pCmd,BYTE pVersion,const TSonorkCtrlMsg*msg,const void*data,DWORD data_size)
{
ENCODE_SECTION_STARTS;
CODEC.WriteCM1(msg);
CODEC.WriteDW(data_size);
if(data_size != 0)
CODEC.WriteRaw( data , data_size );
ENCODE_SECTION_ENDS;
}
// ----------------------------------------------------------------------------
BYTE*
TSonorkUTSPacket::D_CtrlMsg(DWORD pSz,TSonorkCtrlMsg*msg,DWORD* data_size) const
{
DWORD packet_data_size = DataSize(pSz);
TSonorkPacketReader CODEC(DataPtr(),packet_data_size);
CODEC.ReadCM1(msg);
CODEC.ReadDW(data_size);
if( packet_data_size - CODEC.Offset() < *data_size )
{
CODEC.SetBadCodecError( __FILE__ , SONORK_MODULE_LINE );
}
if( !CODEC.CodecOk() )
{
*data_size=0;
return NULL;
}
return DataPtr() + CODEC.Offset();
}
// ----------------------------------------------------------------------------
DWORD
TSonorkUTSPacket::E_Atom(DWORD pSz,DWORD pCmd,BYTE pVersion,const TSonorkCodecAtom*A)
{
ENCODE_SECTION_STARTS;
CODEC.WriteAtom (A);
ENCODE_SECTION_ENDS;
}
// ----------------------------------------------------------------------------
DWORD
TSonorkUTSPacket::E_Data(DWORD pSz,DWORD pCmd,BYTE pVersion,const void*data,DWORD data_size)
{
ENCODE_SECTION_STARTS;
CODEC.WriteRaw(data,data_size);
ENCODE_SECTION_ENDS;
}
// ----------------------------------------------------------------------------
BYTE*
TSonorkUTSPacket::D_Data(DWORD P_size, DWORD& data_size) const
{
data_size = DataSize(P_size);
return DataPtr();
}
// ----------------------------------------------------------------------------
SONORK_RESULT
TSonorkUTSPacket::D_Atom(DWORD P_size,TSonorkCodecAtom*A) const
{
DWORD data_size = DataSize(P_size);
return A->CODEC_ReadMemNoSize(DataPtr(),data_size);
}
// ----------------------------------------------------------------------------
TSonorkUTSPacket*SONORK_AllocUtsPacket(DWORD data_size)
{
assert( data_size < SONORK_UTS_MAX_PACKET_SIZE+256 );
return SONORK_MEM_ALLOC( TSonorkUTSPacket, sizeof(TSonorkUTSPacket) + data_size + sizeof(DWORD) );
}
// ----------------------------------------------------------------------------
void SONORK_FreeUtsPacket(TSonorkUTSPacket*P)
{
SONORK_MEM_FREE(P);
}
// ----------------------------------------------------------------------------
/*
DWORD TGP_E_Atom(TSonorkUTSPacket*, DWORD P_size, DWORD cmd,BYTE version,const class TSonorkCodecAtom*A);
DWORD TGP_E_Data(TSonorkUTSPacket*, DWORD P_size, DWORD cmd,BYTE version,const void*,DWORD );
SONORK_RESULT TGP_D_Atom(TSonorkUTSPacket*P, DWORD P_size, TSonorkCodecAtom*A);
BYTE* TGP_D_Data(TSonorkUTSPacket*P, DWORD P_size, DWORD& data_size);
DWORD TGP_E_CtrlMsg(TSonorkUTSPacket*, DWORD P_size, DWORD cmd,BYTE version,const class TSonorkCtrlMsg*,const BYTE*data,DWORD data_size);
BYTE* TGP_D_CtrlMsg(TSonorkUTSPacket*, DWORD P_size, TSonorkCtrlMsg*,DWORD*data_size);
//-----------------------------------
inline DWORD TGP_E_AtomData(TSonorkUTSPacket*P,DWORD sz,WORD cmd,BYTE version,const TSonorkCodecAtom*A)
{
return TGP_E_Atom(P,sz,cmd,version,A);
}
inline DWORD TGP_E_RawData(TSonorkUTSPacket*P,DWORD sz,WORD cmd,BYTE version,const void*data,DWORD data_size)
{
return TGP_E_Data(P,sz,cmd,version,data,data_size);
}
*/
| 30.245161 | 138 | 0.628626 | matiasinsaurralde |
5717cde83c9449e47d0f7aef889e4bf8d0609e94 | 11,500 | cpp | C++ | ex4/main.cpp | danailbd/kn_oop_2018 | cde4fd8fab8562af8012b4432664a91c4922f448 | [
"MIT"
] | null | null | null | ex4/main.cpp | danailbd/kn_oop_2018 | cde4fd8fab8562af8012b4432664a91c4922f448 | [
"MIT"
] | 1 | 2018-04-30T19:25:54.000Z | 2018-04-30T19:25:54.000Z | ex4/main.cpp | danailbd/kn_oop_2018 | cde4fd8fab8562af8012b4432664a91c4922f448 | [
"MIT"
] | 1 | 2018-05-13T18:17:54.000Z | 2018-05-13T18:17:54.000Z | #include <iostream>
#include "string.h"
using namespace std;
/**
* This program represents a simplified version of the Duolingo application (program for
* learning foreign languages).
* It gives to the user the ability to create a course for a specific language, backed with
* a list (pool) of questions that are defined by a translator, and give tests for a module
* to the user that are to be defined with increasing difficulty (this depend on the
* translator himself). The user is not allowed to proceed further with the modules, in
* case the previous module was not finished with satisfying results, which for the current
* perposes is 80% right questions.
*/
const int QUESTIONS_COUNT_PER_MODULE = 10;
const int QUESTION_TEXT_LENGHT = 100;
const int QUESTIONS_POOL_NUMBER_MAX = 100;
const int NEXT_MODULE_REQUIRED_SCORE = 80; // percents
const int SKILLS_MAX_COUNT_PER_COURSE = 20;
// enum QuestionTypes {
// BASIC, SENTANCE
// };
/// Reduces an array of bools to a single value, i.e. counts the number of positive items.
/// Note: this is well known, widely used function from the Functional programming
int reduce(const bool *arr, int arrSize, int acc) {
for (int i = 0; i < arrSize; ++i) {
acc += arr[i];
}
return acc;
}
// Represents a text question
class Question
{
public:
Question (const char* type, const char* text, const char* answer) {
strcpy(m_text, text);
strcpy(m_answer, answer);
m_type = new char[strlen(type) + 1];
strcpy(m_type, type);
}
// XXX there is a proper place for this method
// Just a simple comparison...
bool checkAnswer(const char* answer) {
return !strcmp(m_answer, answer);
}
const char* getText() const {
return m_text;
}
const char* getAnswer() const {
return m_answer;
}
const char* getType() const {
return m_type;
}
private:
char *m_type;
// keep it as simple as possible
char m_text[QUESTION_TEXT_LENGHT];
char m_answer[QUESTION_TEXT_LENGHT];
};
/// Filters a list of items, resulting in a list of items matching the type criteria, i.e.
/// get only those items that are of the given type.
/// N.B.!: Items are not copied but referenced. This saves some memory, but is more or less
/// a side effect. When filtering items you expect to get a fresh copy of those items.
/// Note: this is well known, widely used function from the Functional programming
Question** filter(Question* items, int itemsCount, char* type, int& count) {
int matchingItemsCount = 0;
for (int i = 0; i < itemsCount; ++i) {
if (!strcmp(items[i].getType(), type)) {
matchingItemsCount++;
// DEV
cout << items[i].getType() << endl;
cout << items[i].getText() << endl;
}
}
count = matchingItemsCount;
// We use array of pointers in order to use the same Question objects.
// As we don't have default constructor for the Question class, creating
// a normal empty array is not possible
// N.B.! this array has to be destroyed from the outside
Question** result = new Question*[matchingItemsCount];
for (int i = 0; i < itemsCount && matchingItemsCount > 0; i++) {
if (!strcmp(items[i].getType(), type)) {
// reuse the existing counter in a bit strange way
// set relation to the same object
result[--matchingItemsCount] = &items[i];
}
}
for (int i = 0; i < count; ++i) {
cout << result[i]->getText() << endl;
}
return result;
}
class Skill
{
public:
// Note: takes a dynamic array of questions that should will be cleared
// after with the object's destruction
Skill (char* name, Question** questionsPool, int poolSize, char* type)
: m_questionsCount(0), m_lastTakenQuestionIdx(0),
m_questionPoolCount(poolSize), m_questionsPool(questionsPool) {
m_name = new char[strlen(name) + 1];
strcpy(m_name, name);
m_questionsType = new char[strlen(type) + 1];
strcpy(m_questionsType, type);
}
~Skill() {
delete [] m_name;
delete [] m_questionsType;
// Take care of the dynamic memory, although it wasn't allocated in this class
delete [] m_questionsPool;
}
/// Generate a fresh set of questions and give them to the user to solve.
void retakeSkill();
/// Get the score for the module represented in percents.
int getScore() const {
// questions have same weight
int size = reduce(m_results, m_questionsCount, 0);
// Casting is needed in order for the division not to be rounded, e.g. 1 / 2 -> 0 and not 0.5
return ((double)size / m_questionsCount) * 100;
}
void printResult() const {
// TODO
}
/// Simple getter for `name`
const char* getName() const {
return m_name;
}
private:
/// A method
void regenerateQuestions();
private:
char* m_name;
// Just keep some idea of what kind of questions are here
// it might be handy sometime in the future
char *m_questionsType;
// latest set of questions; they are regenerated every time
Question *m_questions[QUESTIONS_COUNT_PER_MODULE]; // latest set of questions
int m_questionsCount; // questions might be less than the allowed number
bool m_results[QUESTIONS_COUNT_PER_MODULE]; // right or wrong questions from last taken
int m_lastTakenQuestionIdx; // questions are taken sequentially
int m_questionPoolCount; // number of questions in the pool
Question **m_questionsPool;
};
void Skill::regenerateQuestions() {
/*
* Different ideas for questions generation:
* - take questions randomly
* - take questions that have not been given before
* - some other heuristics...
*/
// we might have just a small pool of questions
m_questionsCount = QUESTIONS_COUNT_PER_MODULE < m_questionPoolCount ? QUESTIONS_COUNT_PER_MODULE : m_questionPoolCount;
// the simplest
for (int i = 0; i < m_questionsCount; ++i) {
m_questions[i] = m_questionsPool[m_lastTakenQuestionIdx];
// and move the index, starting from the start if end is reached...
m_lastTakenQuestionIdx = (m_lastTakenQuestionIdx + 1) % m_questionsCount;
}
}
void Skill::retakeSkill() {
regenerateQuestions(); // 10
char answer[QUESTION_TEXT_LENGHT];
for (int i = 0; i < m_questionsCount; ++i) {
cout << "Translate into english: " << m_questions[i]->getText() << endl; // Translate into ...: ragazzo
// prompt for answer
cout << "> ";
cin.getline(answer, QUESTION_TEXT_LENGHT);
m_results[i] = m_questions[i]->checkAnswer(answer);
if (!m_results[i]) {
cout << "You are not trying hard enough. The right answer is: " << m_questions[i]->getAnswer() << endl;
}
}
}
/// Represents a whole course for a language. Each course has multiple skills
/// that are to be taken sequentially with increasing difficulty.
/// All questions have the same score (of 1) and in order for the user to proceed in
/// the skills she has to have a satisfying result on the previous skill.
class Course
{
public:
Course (const char* lang, Question* questionsPool, int poolSize)
:m_lastSkillId(0), m_skillsCount(0) {
strcpy(m_lang, lang);
// copies all instances of the given questions
m_questionsPool = questionsPool;
m_poolSize = poolSize;
}
~Course() {
// Clean up all allocated objects (a bit obvious)
for (int i = 0; i < m_skillsCount; ++i) {
delete m_skills[i];
}
}
void addSkill(char* name, char* questionType);
void listSkills() const;
void showProgress() const;
bool isSkillReachable(int id) const {
return id == 0 || m_skills[id-1]->getScore() > NEXT_MODULE_REQUIRED_SCORE;
}
void takeSkillById(int id) {
// The skill has already been taken
if (isSkillReachable(id)) {
m_skills[id]->retakeSkill();
} else {
cout << "Test has not been taken yet. You need to unlock it first" << endl;
}
}
void takeNextSkill();
private:
char m_lang[6]; // bg, en, en_uk, en_us
int m_lastSkillId;
Skill* m_skills[SKILLS_MAX_COUNT_PER_COURSE];
int m_skillsCount;
// create Vector
Question* m_questionsPool;
int m_poolSize;
};
void Course::takeNextSkill() {
if (m_lastSkillId >= m_skillsCount) {
cout << "All modules done successfully!";
return;
}
m_skills[m_lastSkillId]->retakeSkill();
if (isSkillReachable(m_lastSkillId + 1))
m_lastSkillId++;
}
void Course::showProgress() const {
cout << "--- --- --- ---" << endl;
cout << "--- Progress ---" << endl;
cout << "--- --- --- ---" << endl;
for (int i = 0; i < m_skillsCount; i++) {
cout << m_skills[i]->getName() << ": " << m_skills[i]->getScore() << endl;
}
}
void Course::listSkills() const {
cout << "--- --- --- --- --" << endl;
cout << "--- Skills list ---" << endl;
cout << "--- --- --- --- --" << endl;
for (int i = 0; i < m_skillsCount; i++) {
cout << "Id: " << i << " Name: "<< m_skills[i]->getName() << endl;
}
}
void Course::addSkill(char* name, char* questionType) {
if (m_skillsCount >= SKILLS_MAX_COUNT_PER_COURSE) {
// no place for skills left
return;
}
// keep the number of filtered questions
int filteredQuestionsCount;
// filter questions that match the given type
Question **filteredQuestions = filter(m_questionsPool, m_poolSize, questionType, filteredQuestionsCount);
m_skills[m_skillsCount++] = new Skill(name, filteredQuestions, filteredQuestionsCount, questionType);
}
int main()
{
// char language[] = "en";
Question q1("basic", "ragazzo", "boy");
Question q2("basic", "ragazza", "girl");
Question q3("basic 2", "ragazzi", "boys");
Question q4("Food", "Sono un ragazzo", "I am a boy");
Question questions[] = { q1, q2, q3, q4 };
Course course("it", questions, 3);
course.addSkill((char*)"Basics", (char*)"basic");
course.listSkills();
course.takeNextSkill();
course.showProgress();
return 0;
}
// code problems
// - find problems in code (idea problems, inconsistency, etc.)
// - comment over email
// what if:
// - we want different answer comparison alg (check method outside of question class)
// - we want different representation of the questions (why in skill class)
// - we want multiple types for a question - it may be applicable for different skills
/// todo
// - questiontype -> enum
/// todo extensible version of the program
// we could also just: shuffle(m_questionspool); take the first n
//
// replace this dynamic array madness with string and vector
| 30.748663 | 123 | 0.608 | danailbd |
571a48315a826edb35159bb76166f2d6eecadf01 | 175 | cpp | C++ | CentipedeGame_gageoconnor/Game Components/CommandScore.cpp | Shaditto/centipede-teal | f078b11eaecddae17709dc9f917348b7b0733d56 | [
"MIT"
] | null | null | null | CentipedeGame_gageoconnor/Game Components/CommandScore.cpp | Shaditto/centipede-teal | f078b11eaecddae17709dc9f917348b7b0733d56 | [
"MIT"
] | null | null | null | CentipedeGame_gageoconnor/Game Components/CommandScore.cpp | Shaditto/centipede-teal | f078b11eaecddae17709dc9f917348b7b0733d56 | [
"MIT"
] | 1 | 2019-11-13T19:26:34.000Z | 2019-11-13T19:26:34.000Z | #include "CommandScore.h"
#include "ScoreManager.h"
CommandScore::CommandScore(int val)
: points(val)
{
}
void CommandScore::Execute()
{
ScoreManager::AddScore(points);
} | 13.461538 | 35 | 0.731429 | Shaditto |
571d76f07da5c29965a72473add85ae74559115e | 142,960 | cpp | C++ | source/fen_moyenne.cpp | yves-marieRaiffaud/school-marks-logger | 817f03d7c13673ed161b4f4804b4e4f64204507f | [
"MIT"
] | null | null | null | source/fen_moyenne.cpp | yves-marieRaiffaud/school-marks-logger | 817f03d7c13673ed161b4f4804b4e4f64204507f | [
"MIT"
] | null | null | null | source/fen_moyenne.cpp | yves-marieRaiffaud/school-marks-logger | 817f03d7c13673ed161b4f4804b4e4f64204507f | [
"MIT"
] | null | null | null | #include "fen_moyenne.h"
fen_moyenne :: fen_moyenne()
{
setting = new QSettings("Mamouth Corporation", "Gestionnaire de Scolarité");
m_loc_annee_compare = new QString(setting->value("Location Fichiers/Annee.txt").toString());
QString root_folder = *m_loc_annee_compare;
QString annee = "/Annee.txt";
QString filename = root_folder + annee;
m_loc_123_compare = new QString(setting->value("Location Fichiers/Fichiers des notes").toString());
m_tableau_PS = new QTableWidget;
m_tableau_PS->setColumnCount(4);
m_tableau_PS->setRowCount(0);
m_tableau_PS->setEditTriggers(QAbstractItemView::NoEditTriggers);
QStringList header;
header<<tr("Semestre")<<tr("Matière")<<tr("Moyenne")<<tr("Moyenne Promo");
m_tableau_PS->setHorizontalHeaderLabels(header);
QFont bold;
bold.setBold(true);
m_tableau_PS->horizontalHeaderItem(0)->setFont(bold);
m_tableau_PS->horizontalHeaderItem(1)->setFont(bold);
m_tableau_PS->horizontalHeaderItem(2)->setFont(bold);
m_tableau_PS->horizontalHeaderItem(3)->setFont(bold);
m_checkbox_S1 = new QCheckBox(tr("Moyennes du Semestre 1"));
m_checkbox_S1->setChecked(true);
m_checkbox_S2 = new QCheckBox(tr("Moyennes du Semestre 2"));
QObject::connect(m_checkbox_S1,SIGNAL(stateChanged(int)),this,SLOT(trie_tab_PS()));
QObject::connect(m_checkbox_S2,SIGNAL(stateChanged(int)),this,SLOT(trie_tab_PS()));
m_layout_semestre = new QVBoxLayout;
m_layout_semestre->addWidget(m_checkbox_S1);
m_layout_semestre->addWidget(m_checkbox_S2);
m_groupbox_semestre = new QGroupBox(tr("Période de l'année"));
m_groupbox_semestre->setLayout(m_layout_semestre);
m_boutton_print = new QPushButton(tr("Imprimer Tout le Tableau"));
m_layout_print = new QVBoxLayout;
m_layout_print->addWidget(m_boutton_print);
QObject::connect(m_boutton_print,SIGNAL(clicked()),this,SLOT(print_tab_PS()));
m_groupbox_print = new QGroupBox(tr("Imprimer Le Tableau"));
m_groupbox_print->setLayout(m_layout_print);
m_checkbox_gestion = new QCheckBox(tr("Colorer les notes inférieures à la moyenne"));
m_layout_gestion_tab = new QVBoxLayout;
m_layout_gestion_tab->addWidget(m_checkbox_gestion);
m_label_gestion = new QLabel;
m_label_gestion_rouges = new QLabel;
m_layout_labels = new QVBoxLayout;
m_layout_labels->addWidget(m_label_gestion);
m_layout_labels->addWidget(m_label_gestion_rouges);
m_layout_bouton_labels = new QHBoxLayout;
m_bouton_enregistrer = new QPushButton(tr("Enregistrer le Tableau"));
m_layout_bouton_labels->addWidget(m_bouton_enregistrer);
m_layout_bouton_labels->addLayout(m_layout_labels);
m_groupbox_gestion_tab = new QGroupBox(tr("Gestion du Tableau"));
m_layout_gestion_tab->addLayout(m_layout_bouton_labels);
m_groupbox_gestion_tab->setLayout(m_layout_gestion_tab);
QObject::connect(m_bouton_enregistrer,SIGNAL(clicked()),this,SLOT(enregistrer_tab_PS()));
QObject::connect(m_checkbox_gestion,SIGNAL(stateChanged(int)),this,SLOT(coloration_tab_PS()));
m_layout_groupboxs = new QHBoxLayout;
m_layout_groupboxs->addWidget(m_groupbox_semestre);
m_layout_groupboxs->addWidget(m_groupbox_gestion_tab);
m_layout_groupboxs->addWidget(m_groupbox_print);
m_layout_page_PS = new QVBoxLayout;
m_layout_page_PS->addWidget(m_tableau_PS);
m_layout_page_PS->addLayout(m_layout_groupboxs);
m_page_PS = new QWidget;
m_page_PS->setLayout(m_layout_page_PS);
m_onglets = new QTabWidget;
m_onglets->addTab(m_page_PS,tr("Pôle Scientifique"));
//*******FIN ONGLET 1***************************************************
m_tableau_PH = new QTableWidget;
m_tableau_PH->setColumnCount(4);
m_tableau_PH->setRowCount(0);
m_tableau_PH->setEditTriggers(QAbstractItemView::NoEditTriggers);
QStringList headers;
headers<<tr("Semestre")<<tr("Matière")<<tr("Moyenne")<<tr("Moyenne Promo");
m_tableau_PH->setHorizontalHeaderLabels(headers);
QFont bolds;
bolds.setBold(true);
m_tableau_PH->horizontalHeaderItem(0)->setFont(bolds);
m_tableau_PH->horizontalHeaderItem(1)->setFont(bolds);
m_tableau_PH->horizontalHeaderItem(2)->setFont(bolds);
m_tableau_PH->horizontalHeaderItem(3)->setFont(bolds);
m_checkbox_S1_PH = new QCheckBox(tr("Moyennes du Semestre 1"));
m_checkbox_S1_PH->setChecked(true);
m_checkbox_S2_PH = new QCheckBox(tr("Moyennes du Semestre 2"));
QObject::connect(m_checkbox_S1_PH,SIGNAL(stateChanged(int)),this,SLOT(trie_tab_PH()));
QObject::connect(m_checkbox_S2_PH,SIGNAL(stateChanged(int)),this,SLOT(trie_tab_PH()));
m_layout_semestre_PH = new QVBoxLayout;
m_layout_semestre_PH->addWidget(m_checkbox_S1_PH);
m_layout_semestre_PH->addWidget(m_checkbox_S2_PH);
m_groupbox_semestre_PH = new QGroupBox(tr("Période de l'année"));
m_groupbox_semestre_PH->setLayout(m_layout_semestre_PH);
m_boutton_print_PH = new QPushButton(tr("Imprimer Tout le Tableau"));
m_layout_print_PH = new QVBoxLayout;
QObject::connect(m_boutton_print_PH,SIGNAL(clicked()),this,SLOT(print_tab_PH()));
m_layout_print_PH->addWidget(m_boutton_print_PH);
m_groupbox_print_PH = new QGroupBox(tr("Imprimer Le Tableau"));
m_groupbox_print_PH->setLayout(m_layout_print_PH);
m_checkbox_gestion1 = new QCheckBox(tr("Colorer les notes inférieures à la moyenne"));
m_layout_gestion_tab1 = new QVBoxLayout;
m_layout_gestion_tab1->addWidget(m_checkbox_gestion1);
m_label_gestion1 = new QLabel;
m_label_gestion_rouges1 = new QLabel;
m_layout_labels1 = new QVBoxLayout;
m_layout_labels1->addWidget(m_label_gestion1);
m_layout_labels1->addWidget(m_label_gestion_rouges1);
m_layout_bouton_labels1 = new QHBoxLayout;
m_bouton_enregistrer1 = new QPushButton(tr("Enregistrer le Tableau"));
m_layout_bouton_labels1->addWidget(m_bouton_enregistrer1);
m_layout_bouton_labels1->addLayout(m_layout_labels1);
m_groupbox_gestion_tab1 = new QGroupBox(tr("Gestion du Tableau"));
m_layout_gestion_tab1->addLayout(m_layout_bouton_labels1);
m_groupbox_gestion_tab1->setLayout(m_layout_gestion_tab1);
QObject::connect(m_bouton_enregistrer1,SIGNAL(clicked()),this,SLOT(enregistrer_tab_PH()));
QObject::connect(m_checkbox_gestion1,SIGNAL(stateChanged(int)),this,SLOT(coloration_tab_PH()));
m_layout_groupboxs_PH = new QHBoxLayout;
m_layout_groupboxs_PH->addWidget(m_groupbox_semestre_PH);
m_layout_groupboxs_PH->addWidget(m_groupbox_gestion_tab1);
m_layout_groupboxs_PH->addWidget(m_groupbox_print_PH);
m_layout_page_PH = new QVBoxLayout;
m_layout_page_PH->addWidget(m_tableau_PH);
m_layout_page_PH->addLayout(m_layout_groupboxs_PH);
m_page_PH = new QWidget;
m_page_PH->setLayout(m_layout_page_PH);
m_onglets->addTab(m_page_PH,tr("Pôle Humain et Sciences de l'Ingénieur"));
m_tableau_PS->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
m_tableau_PH->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
//*********FIN ONGLET 2- DEBUT ONGLET EVENTUEL 3 / POLE INGENIEUR
QFile fichier(filename);
QString ligne;
if(fichier.open(QIODevice::ReadOnly))
{
QTextStream flux(&fichier);
flux.setCodec("UTF-8");
ligne = flux.readLine();
}
QStringList fields;
fields = ligne.split(" | ");
if(fields[0] != "1A")
{
m_tableau_ingenieur = new QTableWidget;
m_tableau_ingenieur->setColumnCount(4);
m_tableau_ingenieur->setRowCount(0);
m_tableau_ingenieur->setEditTriggers(QAbstractItemView::NoEditTriggers);
QStringList header9;
header9<<tr("Semestre")<<tr("Matière")<<tr("Moyenne")<<tr("Moyenne Promo");
m_tableau_ingenieur->setHorizontalHeaderLabels(header9);
QFont bold9;
bold9.setBold(true);
m_tableau_ingenieur->horizontalHeaderItem(0)->setFont(bold9);
m_tableau_ingenieur->horizontalHeaderItem(1)->setFont(bold9);
m_tableau_ingenieur->horizontalHeaderItem(2)->setFont(bold9);
m_tableau_ingenieur->horizontalHeaderItem(3)->setFont(bold9);
m_checkbox_S1_I = new QCheckBox(tr("Moyennes du Semestre 1"));
m_checkbox_S1_I->setChecked(true);
m_checkbox_S2_I = new QCheckBox(tr("Moyennes du Semestre 2"));
m_checkbox_S2_I->setChecked(false);
m_layout_annee_I = new QVBoxLayout;
m_layout_annee_I->addWidget(m_checkbox_S1_I);
m_layout_annee_I->addWidget(m_checkbox_S2_I);
m_groupbox_annee_I = new QGroupBox(tr("Périodes de l'année"));
m_groupbox_annee_I->setLayout(m_layout_annee_I);
QObject::connect(m_checkbox_S1_I,SIGNAL(stateChanged(int)),this,SLOT(trier_tab_I()));
QObject::connect(m_checkbox_S2_I,SIGNAL(stateChanged(int)),this,SLOT(trier_tab_I()));
m_checkbox_gestion_I = new QCheckBox(tr("Colorer les notes inférieures à la moyenne"));
m_layout_gestion_tab_I = new QVBoxLayout;
m_layout_gestion_tab_I->addWidget(m_checkbox_gestion_I);
m_bouton_enregistrer_tab_I = new QPushButton(tr("Enregistrer le Tableau"));
m_label_gestion_I = new QLabel;
m_label_gestion_rouges_I = new QLabel;
m_layout_labels_I = new QVBoxLayout;
m_layout_labels_I->addWidget(m_label_gestion_I);
m_layout_labels_I->addWidget(m_label_gestion_rouges_I);
m_layout_bouton_labels_I = new QHBoxLayout;
m_layout_bouton_labels_I->addWidget(m_bouton_enregistrer_tab_I);
m_layout_bouton_labels_I->addLayout(m_layout_labels_I);
m_groupbox_gestion_tab_I = new QGroupBox(tr("Gestion du Tableau"));
m_layout_gestion_tab_I->addLayout(m_layout_bouton_labels_I);
m_groupbox_gestion_tab_I->setLayout(m_layout_gestion_tab_I);
QObject::connect(m_bouton_enregistrer_tab_I,SIGNAL(clicked()),this,SLOT( enregistrer_tab_I()));
QObject::connect(m_checkbox_gestion_I,SIGNAL(stateChanged(int)),this,SLOT(coloration_tab_I()));
m_bouton_printAll_I = new QPushButton(tr("Imprimer Tout le Tableau"));
m_layout_print_I = new QVBoxLayout;
m_layout_print_I->addWidget(m_bouton_printAll_I);
m_groupbox_print_I = new QGroupBox(tr("Imprimer le Tableau"));
m_groupbox_print_I->setLayout(m_layout_print_I);
m_layout_groupbox_ingenieur = new QHBoxLayout;
m_layout_groupbox_ingenieur->addWidget(m_groupbox_annee_I);
m_layout_groupbox_ingenieur->addWidget(m_groupbox_gestion_tab_I);
m_layout_groupbox_ingenieur->addWidget(m_groupbox_print_I);
QObject::connect(m_bouton_printAll_I,SIGNAL(clicked()),this,SLOT(imprimer_tableau_I()));
m_layout_widget_ingenieur = new QVBoxLayout;
m_layout_widget_ingenieur->addWidget(m_tableau_ingenieur);
m_layout_widget_ingenieur->addLayout(m_layout_groupbox_ingenieur);
m_page_pole_ingenieur = new QWidget;
m_page_pole_ingenieur->setLayout(m_layout_widget_ingenieur);
m_onglets->addTab(m_page_pole_ingenieur,tr("Pole Ingenierie des Transports"));
m_tableau_ingenieur->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
remplir_tableau_I();
trier_tab_I();
}
//MISE EN FORME GENERALE*************************************************
m_layout_general = new QVBoxLayout;
m_layout_general->addWidget(m_onglets);
QWidget *page = new QWidget;
page->setLayout(m_layout_general);
this->setCentralWidget(page);
m_onglets->setMovable(true);
setWindowTitle(tr("Tableaux Des Moyennes"));
setWindowIcon(QIcon("res/icos/calculator.png"));
this->setWindowFlags(this->windowFlags() & ~Qt::WindowContextHelpButtonHint);
resize(1600,900);
remplir_tab_PS();
remplir_tab_PH();
}
void fen_moyenne :: enregistrer_tab_PH()
{
QString fileName = QFileDialog::getSaveFileName((QWidget* )0, tr("Enregistrer en PDF"), QString(), "*.pdf");
if(fileName.isEmpty())
{
return;
}
if (QFileInfo(fileName).suffix().isEmpty()) { fileName.append(".pdf"); }
QPrinter printer(QPrinter::PrinterResolution);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setPaperSize(QPrinter::A4);
printer.setFullPage(true);
printer.setOrientation(QPrinter::Portrait);
printer.setOutputFileName(fileName);
QTextBrowser * editor = new QTextBrowser;
QTextCharFormat NormalFormat;
QTextCharFormat ItalicFormat;
ItalicFormat.setFontItalic(true);
QDate date;
QTime time;
date = date.currentDate();
time = time.currentTime();
QString modif ="\nFait le :\t" + date.toString("dddd dd MMMM yyyy") + " à " + time.toString();
editor->setCurrentCharFormat(ItalicFormat);
editor->setAlignment(Qt::AlignLeft);
editor->append(modif);
editor->setCurrentCharFormat(NormalFormat);
QTextCharFormat format_gros_titre;
format_gros_titre.setFontPointSize(18);
format_gros_titre.setFontWeight(QFont::Bold);
format_gros_titre.setVerticalAlignment(QTextCharFormat::AlignMiddle);
format_gros_titre.setUnderlineStyle(QTextCharFormat::SingleUnderline);
editor->setCurrentCharFormat(NormalFormat);
QTextCursor cursor = editor->textCursor();
cursor.beginEditBlock();
QTextTableFormat tableFormat;
tableFormat.setAlignment(Qt::AlignHCenter);
tableFormat.setAlignment(Qt::AlignLeft);
tableFormat.setBackground(QColor("#ffffff"));
tableFormat.setCellPadding(2);
tableFormat.setCellSpacing(2);
QTextTable * tableau = cursor.insertTable(m_tableau_PH->rowCount()+1, m_tableau_PH->columnCount(), tableFormat);
QTextFrame *frame = cursor.currentFrame();
QTextFrameFormat frameFormat = frame->frameFormat();
frameFormat.setBorder(0);
frame->setFrameFormat(frameFormat);
QTextCharFormat format_entete_tableau;
format_entete_tableau.setFontPointSize(10);
format_entete_tableau.setFontWeight(QFont::Bold);
QTextCharFormat format_cellule;
format_cellule.setFontPointSize(8);
for ( int i = 0 ; i < m_tableau_PH->columnCount() ; i++ )
{
QTextTableCell titre = tableau->cellAt(0,i);
QTextCursor cellCursor = titre.firstCursorPosition();
cellCursor.insertText(m_tableau_PH->horizontalHeaderItem(i)->text(),format_entete_tableau);
}
QTextTableCell cell;
QTextCursor cellCursor;
for (int row = 1; row < tableau->rows(); row ++)
for (int col = 0; col < tableau->columns(); col ++)
{
cell = tableau->cellAt(row,col);
cellCursor = cell.firstCursorPosition();
cellCursor.insertText(tr("%1").arg(m_tableau_PH->item(row-1,col)->text()),format_cellule);
}
cursor.endEditBlock();
editor->print(&printer);
QMessageBox::information(this,tr("Enregistrer un PDF"),"'"+fileName+tr("' enregistré avec succès"));
}
void fen_moyenne :: enregistrer_tab_PS()
{
QString fileName = QFileDialog::getSaveFileName((QWidget* )0, tr("Enregistrer en PDF"), QString(), "*.pdf");
if(fileName.isEmpty())
{
return;
}
if (QFileInfo(fileName).suffix().isEmpty()) { fileName.append(".pdf"); }
QPrinter printer(QPrinter::PrinterResolution);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setPaperSize(QPrinter::A4);
printer.setFullPage(true);
printer.setOrientation(QPrinter::Portrait);
printer.setOutputFileName(fileName);
QTextBrowser * editor = new QTextBrowser;
QTextCharFormat NormalFormat;
QTextCharFormat ItalicFormat;
ItalicFormat.setFontItalic(true);
QDate date;
QTime time;
date = date.currentDate();
time = time.currentTime();
QString modif ="\nFait le :\t" + date.toString("dddd dd MMMM yyyy") + " à " + time.toString();
editor->setCurrentCharFormat(ItalicFormat);
editor->setAlignment(Qt::AlignLeft);
editor->append(modif);
editor->setCurrentCharFormat(NormalFormat);
QTextCharFormat format_gros_titre;
format_gros_titre.setFontPointSize(18);
format_gros_titre.setFontWeight(QFont::Bold);
format_gros_titre.setVerticalAlignment(QTextCharFormat::AlignMiddle);
format_gros_titre.setUnderlineStyle(QTextCharFormat::SingleUnderline);
editor->setCurrentCharFormat(NormalFormat);
QTextCursor cursor = editor->textCursor();
cursor.beginEditBlock();
QTextTableFormat tableFormat;
tableFormat.setAlignment(Qt::AlignHCenter);
tableFormat.setAlignment(Qt::AlignLeft);
tableFormat.setBackground(QColor("#ffffff"));
tableFormat.setCellPadding(2);
tableFormat.setCellSpacing(2);
QTextTable * tableau = cursor.insertTable(m_tableau_PS->rowCount()+1, m_tableau_PS->columnCount(), tableFormat);
QTextFrame *frame = cursor.currentFrame();
QTextFrameFormat frameFormat = frame->frameFormat();
frameFormat.setBorder(0);
frame->setFrameFormat(frameFormat);
QTextCharFormat format_entete_tableau;
format_entete_tableau.setFontPointSize(10);
format_entete_tableau.setFontWeight(QFont::Bold);
QTextCharFormat format_cellule;
format_cellule.setFontPointSize(8);
for ( int i = 0 ; i < m_tableau_PS->columnCount() ; i++ )
{
QTextTableCell titre = tableau->cellAt(0,i);
QTextCursor cellCursor = titre.firstCursorPosition();
cellCursor.insertText(m_tableau_PS->horizontalHeaderItem(i)->text(),format_entete_tableau);
}
QTextTableCell cell;
QTextCursor cellCursor;
for (int row = 1; row < tableau->rows(); row ++)
for (int col = 0; col < tableau->columns(); col ++)
{
cell = tableau->cellAt(row,col);
cellCursor = cell.firstCursorPosition();
cellCursor.insertText(tr("%1").arg(m_tableau_PS->item(row-1,col)->text()),format_cellule);
}
cursor.endEditBlock();
editor->print(&printer);
QMessageBox::information(this,tr("Enregistrer un PDF"),"'"+fileName+tr("' enregistré avec succès"));
}
void fen_moyenne :: coloration_tab_PH()
{
if(m_checkbox_gestion1->isChecked())
{
int nb_verts = 0;
int nb_rouges = 0;
for(int i = 0 ; i < m_tableau_PH->rowCount() ; i++)
{
double note = m_tableau_PH->item(i,2)->text().toDouble();
double moyenne = m_tableau_PH->item(i,3)->text().toDouble();
if(note > moyenne)
{
for(int m=0;m<m_tableau_PH->columnCount();m++)
{
m_tableau_PH->item(i,m)->setBackgroundColor(QColor(72,163,67));
}
nb_verts = nb_verts + 1;
}
else if(note < moyenne)
{
for(int m=0;m<m_tableau_PH->columnCount();m++)
{
m_tableau_PH->item(i,m)->setBackgroundColor(QColor(204,37,37));
}
nb_rouges = nb_rouges + 1;
}
}
QString string_verts = QString::number(nb_verts);
QString string_rouges = QString::number(nb_rouges);
if(nb_verts > 1)
{
m_label_gestion1->setText(string_verts+tr(" lignes vertes"));
QPalette pal =QPalette(m_label_gestion1->palette());
pal.setColor(QPalette::WindowText, QColor(72,163,67));
m_label_gestion1->setPalette(pal);
}
else if(nb_verts <= 1)
{
m_label_gestion1->setText(string_verts+tr(" ligne verte"));
QPalette pal =QPalette(m_label_gestion1->palette());
pal.setColor(QPalette::WindowText, QColor(72,163,67));
m_label_gestion1->setPalette(pal);
}
if(nb_rouges > 1)
{
m_label_gestion_rouges1->setText(string_rouges+tr(" lignes rouges"));
QPalette pal1 =QPalette(m_label_gestion_rouges1->palette());
pal1.setColor(QPalette::WindowText, QColor(204,37,37));
m_label_gestion_rouges1->setPalette(pal1);
}
else if(nb_rouges <= 1)
{
m_label_gestion_rouges1->setText(string_rouges+tr(" ligne rouge"));
QPalette pal1 =QPalette(m_label_gestion_rouges1->palette());
pal1.setColor(QPalette::WindowText, QColor(204,37,37));
m_label_gestion_rouges1->setPalette(pal1);
}
}
else if(!m_checkbox_gestion1->isChecked())
{
for(int i = 0 ; i < m_tableau_PH->rowCount() ; i++)
{
for(int m=0;m<m_tableau_PH->columnCount();m++)
{
m_tableau_PH->item(i,m)->setBackgroundColor(QColor(255,255,255));
m_tableau_PH->item(i,2)->setBackgroundColor(QColor(255,155,155));
}
}
m_label_gestion1->setText("");
m_label_gestion_rouges1->setText("");
}
}
void fen_moyenne :: coloration_tab_PS()
{
if(m_checkbox_gestion->isChecked())
{
int nb_verts = 0;
int nb_rouges = 0;
for(int i = 0 ; i < m_tableau_PS->rowCount() ; i++)
{
double note = m_tableau_PS->item(i,2)->text().toDouble();
double moyenne = m_tableau_PS->item(i,3)->text().toDouble();
if(note > moyenne)
{
for(int m=0;m<m_tableau_PS->columnCount();m++)
{
m_tableau_PS->item(i,m)->setBackgroundColor(QColor(72,163,67));
}
nb_verts = nb_verts + 1;
}
else if(note < moyenne)
{
for(int m=0;m<m_tableau_PS->columnCount();m++)
{
m_tableau_PS->item(i,m)->setBackgroundColor(QColor(204,37,37));
}
nb_rouges = nb_rouges + 1;
}
}
QString string_verts = QString::number(nb_verts);
QString string_rouges = QString::number(nb_rouges);
if(nb_verts > 1)
{
m_label_gestion->setText(string_verts+tr(" lignes vertes"));
QPalette pal =QPalette(m_label_gestion->palette());
pal.setColor(QPalette::WindowText, QColor(72,163,67));
m_label_gestion->setPalette(pal);
}
else if(nb_verts <= 1)
{
m_label_gestion->setText(string_verts+tr(" ligne verte"));
QPalette pal =QPalette(m_label_gestion->palette());
pal.setColor(QPalette::WindowText, QColor(72,163,67));
m_label_gestion->setPalette(pal);
}
if(nb_rouges > 1)
{
m_label_gestion_rouges->setText(string_rouges+tr(" lignes rouges"));
QPalette pal1 =QPalette(m_label_gestion_rouges->palette());
pal1.setColor(QPalette::WindowText, QColor(204,37,37));
m_label_gestion_rouges->setPalette(pal1);
}
else if(nb_rouges <= 1)
{
m_label_gestion_rouges->setText(string_rouges+tr(" ligne rouge"));
QPalette pal1 =QPalette(m_label_gestion_rouges->palette());
pal1.setColor(QPalette::WindowText, QColor(204,37,37));
m_label_gestion_rouges->setPalette(pal1);
}
}
else if(!m_checkbox_gestion->isChecked())
{
for(int i = 0 ; i < m_tableau_PS->rowCount() ; i++)
{
for(int m=0;m<m_tableau_PS->columnCount();m++)
{
m_tableau_PS->item(i,m)->setBackgroundColor(QColor(255,255,255));
m_tableau_PS->item(i,2)->setBackgroundColor(QColor(255,155,155));
}
}
m_label_gestion->setText("");
m_label_gestion_rouges->setText("");
}
}
void fen_moyenne :: remplir_tab_PS()
{
while(m_tableau_PS->rowCount()>0)
{
m_tableau_PS->removeRow(m_tableau_PS->rowCount()-1);
}
QString root_folder = *m_loc_annee_compare;
QString annee = "/Annee.txt";
QString nomFichier = root_folder + annee;
QFile fichier(nomFichier);
QString ligne;
QString fileToOpen;
if(fichier.open(QIODevice::ReadOnly))
{
QTextStream flux(&fichier);
ligne = flux.readLine();
}
QStringList fields;
fields = ligne.split(" | ");
fichier.close();
fileToOpen = fields[1]; //RECUPERE LE NOM DU FICHIER A OUVRIR
if(fileToOpen == "1A.txt")
{
QString root_folder_42 = *m_loc_123_compare;
QString annee_42 = "/1A.txt";
QString filename_2042 = root_folder_42 + annee_42;
fileToOpen = filename_2042;
}
if(fileToOpen == "2A.txt")
{
QString root_folder_42 = *m_loc_123_compare;
QString annee_42 = "/2A.txt";
QString filename_2042 = root_folder_42 + annee_42;
fileToOpen = filename_2042;
}
if(fileToOpen == "3A.txt")
{
QString root_folder_42 = *m_loc_123_compare;
QString annee_42 = "/3A.txt";
QString filename_2042 = root_folder_42 + annee_42;
fileToOpen = filename_2042;
}
QFile file(fileToOpen);
QString line;
QString all_file;
QStringList field_ligne;
QStringList sous_field_ligne;
QStringList field_test_matiere;
QStringList sous_field_test_matiere;
QVector <QString> vect(0);
bool ligne_deja_entree;
int nb_line = 0;
double coeff_P = 0;
double coeff_CC = 0;
double coeff_CR = 0;
double coeff_I = 0;
double moyenne_calc = 0;
double moyenne_promo = 0;
double diviseur = 0;
double moyenne_tab = 0;
double moyenne_tab_promo = 0;
int indice_ligne_tab = 0;
if(file.open(QIODevice:: ReadOnly))
{
QTextStream stream(&file);
while(!stream.atEnd())
{
line = stream.readLine();
nb_line = nb_line + 1;
}
} // NOMBRE DE LIGNE DU DOC
file.close();
QFile file1(fileToOpen);
if(file1.open(QIODevice::ReadOnly))
{
QTextStream stream1(&file1);
all_file = stream1.readAll();
field_ligne = all_file.split("\r\n");
for(int i=0 ; i< nb_line ; i++)
{
moyenne_calc = 0;
moyenne_promo = 0;
diviseur = 0;
ligne_deja_entree = false;
sous_field_ligne = field_ligne[i].split(" | ");
for(int w = 0 ; w<vect.size() ; w++)
{
if(sous_field_ligne[2] == vect[w])
{
ligne_deja_entree = true;
}
}
if(ligne_deja_entree == false)
{
if(sous_field_ligne[0] == "Pole Scientifique")
{
if(sous_field_ligne[1] == "Semestre 1")
{
field_test_matiere = all_file.split("\r\n");
vect.push_back(sous_field_ligne[2]);
for(int k=i ; k < nb_line ; k++)
{
sous_field_test_matiere = field_test_matiere[k].split(" | ");
if(sous_field_test_matiere[0] == "Pole Scientifique")
{
if(sous_field_test_matiere[1] == "Semestre 1")
{
if(sous_field_test_matiere[2] == sous_field_ligne[2])
{
QString root_folder = *m_loc_annee_compare;
QString annee = "/Annee.txt";
QString nomFichier = root_folder + annee;
QFile fichier_coeff(nomFichier);
QStringList field_coeff;
QString ligne_coeff;
if(fichier_coeff.open(QIODevice::ReadOnly))
{
QTextStream stream_coeff(&fichier_coeff);
ligne_coeff = stream_coeff.readLine();
field_coeff = ligne_coeff.split(" | ");
while(field_coeff[0] != sous_field_ligne[2])
{
ligne_coeff = stream_coeff.readLine();
field_coeff = ligne_coeff.split(" | ");
}
coeff_P = field_coeff[1].toDouble();
coeff_CC = field_coeff[2].toDouble();
coeff_I = field_coeff[3].toDouble();
coeff_CR = field_coeff[4].toDouble();
}
fichier_coeff.close();
if(sous_field_test_matiere[3] == "Partiel")
{
moyenne_calc = moyenne_calc + (coeff_P * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_P * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_P;
}
else if(sous_field_test_matiere[3] == "Controle Continu")
{
moyenne_calc = moyenne_calc + (coeff_CC * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_CC * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_CC;
}
else if(sous_field_test_matiere[3] == "Interogation")
{
moyenne_calc = moyenne_calc + (coeff_I * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_I * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_I;
}
else if(sous_field_test_matiere[3] == "Controle Experimental")
{
moyenne_calc = moyenne_calc + (coeff_CR * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_CR * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_CR;
}
}
}
}
}
if(ligne_deja_entree == false)
{
m_tableau_PS->setRowCount(m_tableau_PS->rowCount()+1);
moyenne_tab = moyenne_calc / diviseur;
moyenne_tab_promo = moyenne_promo / diviseur;
QTableWidgetItem *item0 = new QTableWidgetItem(sous_field_ligne[1]);
m_tableau_PS->setItem(indice_ligne_tab,0,item0);
QTableWidgetItem *item1 = new QTableWidgetItem(sous_field_ligne[2]);
m_tableau_PS->setItem(indice_ligne_tab,1,item1);
QTableWidgetItem *item = new QTableWidgetItem(QString::number(moyenne_tab));
m_tableau_PS->setItem(indice_ligne_tab,2,item);
m_tableau_PS->item(indice_ligne_tab,2)->setBackgroundColor(QColor(255,155,155));
m_tableau_PS->item(indice_ligne_tab,2)->setTextColor(QColor(255,255,255));
QFont bold;
bold.setBold(true);
m_tableau_PS->item(indice_ligne_tab,2)->setFont(bold);
QTableWidgetItem *item2 = new QTableWidgetItem(QString::number(moyenne_tab_promo));
m_tableau_PS->setItem(indice_ligne_tab,3,item2);
indice_ligne_tab = indice_ligne_tab + 1;
}
}
}
}
}
}
}
void fen_moyenne :: remplir_tab_PH()
{
while(m_tableau_PH->rowCount()>0)
{
m_tableau_PH->removeRow(m_tableau_PH->rowCount()-1);
}
QString root_folder = *m_loc_annee_compare;
QString annee = "/Annee.txt";
QString nomFichier = root_folder + annee;
QFile fichier(nomFichier);
QString ligne;
QString fileToOpen;
if(fichier.open(QIODevice::ReadOnly))
{
QTextStream flux(&fichier);
ligne = flux.readLine();
}
QStringList fields;
fields = ligne.split(" | ");
fichier.close();
fileToOpen = fields[1]; //RECUPERE LE NOM DU FICHIER A OUVRIR
if(fileToOpen == "1A.txt")
{
QString root_folder_42 = *m_loc_123_compare;
QString annee_42 = "/1A.txt";
QString filename_2042 = root_folder_42 + annee_42;
fileToOpen = filename_2042;
}
if(fileToOpen == "2A.txt")
{
QString root_folder_42 = *m_loc_123_compare;
QString annee_42 = "/2A.txt";
QString filename_2042 = root_folder_42 + annee_42;
fileToOpen = filename_2042;
}
if(fileToOpen == "3A.txt")
{
QString root_folder_42 = *m_loc_123_compare;
QString annee_42 = "/3A.txt";
QString filename_2042 = root_folder_42 + annee_42;
fileToOpen = filename_2042;
}
QFile file(fileToOpen);
QString line;
QString all_file;
QStringList field_ligne;
QStringList sous_field_ligne;
QStringList field_test_matiere;
QStringList sous_field_test_matiere;
QVector <QString> vect(0);
bool ligne_deja_entree;
int nb_line = 0;
double coeff_P = 0;
double coeff_CC = 0;
double coeff_CR = 0;
double coeff_I = 0;
double moyenne_calc = 0;
double moyenne_promo = 0;
double diviseur = 0;
double moyenne_tab = 0;
double moyenne_tab_promo = 0;
int indice_ligne_tab = 0;
if(file.open(QIODevice:: ReadOnly))
{
QTextStream stream(&file);
while(!stream.atEnd())
{
line = stream.readLine();
nb_line = nb_line + 1;
}
} // NOMBRE DE LIGNE DU DOC
file.close();
QFile file1(fileToOpen);
if(file1.open(QIODevice::ReadOnly))
{
QTextStream stream1(&file1);
all_file = stream1.readAll();
field_ligne = all_file.split("\r\n");
for(int i=0 ; i< nb_line ; i++)
{
moyenne_calc = 0;
moyenne_promo = 0;
diviseur = 0;
ligne_deja_entree = false;
sous_field_ligne = field_ligne[i].split(" | ");
for(int w = 0 ; w<vect.size() ; w++)
{
if(sous_field_ligne[2] == vect[w])
{
ligne_deja_entree = true;
}
}
if(ligne_deja_entree == false)
{
if(sous_field_ligne[0] == "Pole Humain et Culture de l'Ingenieur")
{
if(sous_field_ligne[1] == "Semestre 1")
{
field_test_matiere = all_file.split("\r\n");
vect.push_back(sous_field_ligne[2]);
for(int k=i ; k < nb_line ; k++)
{
sous_field_test_matiere = field_test_matiere[k].split(" | ");
if(sous_field_test_matiere[0] == "Pole Humain et Culture de l'Ingenieur")
{
if(sous_field_test_matiere[1] == "Semestre 1")
{
if(sous_field_test_matiere[2] == sous_field_ligne[2])
{
QString root_folder = *m_loc_annee_compare;
QString annee = "/Annee.txt";
QString nomFichier = root_folder + annee;
QFile fichier_coeff(nomFichier);
QStringList field_coeff;
QString ligne_coeff;
if(fichier_coeff.open(QIODevice::ReadOnly))
{
QTextStream stream_coeff(&fichier_coeff);
ligne_coeff = stream_coeff.readLine();
field_coeff = ligne_coeff.split(" | ");
while(field_coeff[0] != sous_field_ligne[2])
{
ligne_coeff = stream_coeff.readLine();
field_coeff = ligne_coeff.split(" | ");
}
coeff_P = field_coeff[1].toDouble();
coeff_CC = field_coeff[2].toDouble();
coeff_I = field_coeff[3].toDouble();
coeff_CR = field_coeff[4].toDouble();
}
fichier_coeff.close();
if(sous_field_test_matiere[3] == "Partiel")
{
moyenne_calc = moyenne_calc + (coeff_P * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_P * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_P;
}
else if(sous_field_test_matiere[3] == "Controle Continu")
{
moyenne_calc = moyenne_calc + (coeff_CC * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_CC * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_CC;
}
else if(sous_field_test_matiere[3] == "Interogation")
{
moyenne_calc = moyenne_calc + (coeff_I * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_I * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_I;
}
else if(sous_field_test_matiere[3] == "Controle Experimental")
{
moyenne_calc = moyenne_calc + (coeff_CR * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_CR * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_CR;
}
}
}
}
}
if(ligne_deja_entree == false)
{
m_tableau_PH->setRowCount(m_tableau_PH->rowCount()+1);
moyenne_tab = moyenne_calc / diviseur;
moyenne_tab_promo = moyenne_promo / diviseur;
QTableWidgetItem *item0 = new QTableWidgetItem(sous_field_ligne[1]);
m_tableau_PH->setItem(indice_ligne_tab,0,item0);
QTableWidgetItem *item1 = new QTableWidgetItem(sous_field_ligne[2]);
m_tableau_PH->setItem(indice_ligne_tab,1,item1);
QTableWidgetItem *item = new QTableWidgetItem(QString::number(moyenne_tab));
m_tableau_PH->setItem(indice_ligne_tab,2,item);
m_tableau_PH->item(indice_ligne_tab,2)->setBackgroundColor(QColor(255,155,155));
m_tableau_PH->item(indice_ligne_tab,2)->setTextColor(QColor(255,255,255));
QFont bold;
bold.setBold(true);
m_tableau_PH->item(indice_ligne_tab,2)->setFont(bold);
QTableWidgetItem *item2 = new QTableWidgetItem(QString::number(moyenne_tab_promo));
m_tableau_PH->setItem(indice_ligne_tab,3,item2);
indice_ligne_tab = indice_ligne_tab + 1;
}
}
}
}
}
}
}
void fen_moyenne :: trie_tab_PS()
{
if(m_checkbox_S1->isChecked() && !m_checkbox_S2->isChecked())
{
remplir_tab_PS();
}
else if(!m_checkbox_S1->isChecked() && m_checkbox_S2->isChecked())
{
while(m_tableau_PS->rowCount()>0)
{
m_tableau_PS->removeRow(m_tableau_PS->rowCount()-1);
}
QString root_folder = *m_loc_annee_compare;
QString annee = "/Annee.txt";
QString nomFichier = root_folder + annee;
QFile fichier(nomFichier);
QString ligne;
QString fileToOpen;
if(fichier.open(QIODevice::ReadOnly))
{
QTextStream flux(&fichier);
ligne = flux.readLine();
}
QStringList fields;
fields = ligne.split(" | ");
fichier.close();
fileToOpen = fields[1]; //RECUPERE LE NOM DU FICHIER A OUVRIR
if(fileToOpen == "1A.txt")
{
QString root_folder_42 = *m_loc_123_compare;
QString annee_42 = "/1A.txt";
QString filename_2042 = root_folder_42 + annee_42;
fileToOpen = filename_2042;
}
if(fileToOpen == "2A.txt")
{
QString root_folder_42 = *m_loc_123_compare;
QString annee_42 = "/2A.txt";
QString filename_2042 = root_folder_42 + annee_42;
fileToOpen = filename_2042;
}
if(fileToOpen == "3A.txt")
{
QString root_folder_42 = *m_loc_123_compare;
QString annee_42 = "/3A.txt";
QString filename_2042 = root_folder_42 + annee_42;
fileToOpen = filename_2042;
}
QFile file(fileToOpen);
QString line;
QString all_file;
QStringList field_ligne;
QStringList sous_field_ligne;
QStringList field_test_matiere;
QStringList sous_field_test_matiere;
QVector <QString> vect(0);
bool ligne_deja_entree;
int nb_line = 0;
double coeff_P = 0;
double coeff_CC = 0;
double coeff_CR = 0;
double coeff_I = 0;
double moyenne_calc = 0;
double moyenne_promo = 0;
double diviseur = 0;
double moyenne_tab = 0;
double moyenne_tab_promo = 0;
int indice_ligne_tab = 0;
if(file.open(QIODevice:: ReadOnly))
{
QTextStream stream(&file);
while(!stream.atEnd())
{
line = stream.readLine();
nb_line = nb_line + 1;
}
} // NOMBRE DE LIGNE DU DOC
file.close();
QFile file1(fileToOpen);
if(file1.open(QIODevice::ReadOnly))
{
QTextStream stream1(&file1);
all_file = stream1.readAll();
field_ligne = all_file.split("\r\n");
for(int i=0 ; i< nb_line ; i++)
{
moyenne_calc = 0;
moyenne_promo = 0;
diviseur = 0;
ligne_deja_entree = false;
sous_field_ligne = field_ligne[i].split(" | ");
for(int w = 0 ; w<vect.size() ; w++)
{
if(sous_field_ligne[2] == vect[w])
{
ligne_deja_entree = true;
}
}
if(ligne_deja_entree == false)
{
if(sous_field_ligne[0] == "Pole Scientifique")
{
if(sous_field_ligne[1] == "Semestre 2")
{
field_test_matiere = all_file.split("\r\n");
vect.push_back(sous_field_ligne[2]);
for(int k=i ; k < nb_line ; k++)
{
sous_field_test_matiere = field_test_matiere[k].split(" | ");
if(sous_field_test_matiere[0] == "Pole Scientifique")
{
if(sous_field_test_matiere[1] == "Semestre 2")
{
if(sous_field_test_matiere[2] == sous_field_ligne[2])
{
QString root_folder = *m_loc_annee_compare;
QString annee = "/Annee.txt";
QString nomFichier = root_folder + annee;
QFile fichier_coeff(nomFichier);
QStringList field_coeff;
QString ligne_coeff;
if(fichier_coeff.open(QIODevice::ReadOnly))
{
QTextStream stream_coeff(&fichier_coeff);
ligne_coeff = stream_coeff.readLine();
field_coeff = ligne_coeff.split(" | ");
while(field_coeff[0] != sous_field_ligne[2])
{
ligne_coeff = stream_coeff.readLine();
field_coeff = ligne_coeff.split(" | ");
}
coeff_P = field_coeff[1].toDouble();
coeff_CC = field_coeff[2].toDouble();
coeff_I = field_coeff[3].toDouble();
coeff_CR = field_coeff[4].toDouble();
}
fichier_coeff.close();
if(sous_field_test_matiere[3] == "Partiel")
{
moyenne_calc = moyenne_calc + (coeff_P * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_P * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_P;
}
else if(sous_field_test_matiere[3] == "Controle Continu")
{
moyenne_calc = moyenne_calc + (coeff_CC * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_CC * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_CC;
}
else if(sous_field_test_matiere[3] == "Interogation")
{
moyenne_calc = moyenne_calc + (coeff_I * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_I * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_I;
}
else if(sous_field_test_matiere[3] == "Controle Experimental")
{
moyenne_calc = moyenne_calc + (coeff_CR * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_CR * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_CR;
}
}
}
}
}
if(ligne_deja_entree == false)
{
m_tableau_PS->setRowCount(m_tableau_PS->rowCount()+1);
moyenne_tab = moyenne_calc / diviseur;
moyenne_tab_promo = moyenne_promo / diviseur;
QTableWidgetItem *item0 = new QTableWidgetItem(sous_field_ligne[1]);
m_tableau_PS->setItem(indice_ligne_tab,0,item0);
QTableWidgetItem *item1 = new QTableWidgetItem(sous_field_ligne[2]);
m_tableau_PS->setItem(indice_ligne_tab,1,item1);
QTableWidgetItem *item = new QTableWidgetItem(QString::number(moyenne_tab));
m_tableau_PS->setItem(indice_ligne_tab,2,item);
m_tableau_PS->item(indice_ligne_tab,2)->setBackgroundColor(QColor(255,155,155));
m_tableau_PS->item(indice_ligne_tab,2)->setTextColor(QColor(255,255,255));
QFont bold;
bold.setBold(true);
m_tableau_PS->item(indice_ligne_tab,2)->setFont(bold);
QTableWidgetItem *item2 = new QTableWidgetItem(QString::number(moyenne_tab_promo));
m_tableau_PS->setItem(indice_ligne_tab,3,item2);
indice_ligne_tab = indice_ligne_tab + 1;
}
}
}
}
}
}
}
else if(m_checkbox_S1->isChecked() && m_checkbox_S2->isChecked())
{
while(m_tableau_PS->rowCount()>0)
{
m_tableau_PS->removeRow(m_tableau_PS->rowCount()-1);
}
QString root_folder = *m_loc_annee_compare;
QString annee = "/Annee.txt";
QString nomFichier = root_folder + annee;
QFile fichier(nomFichier);
QString ligne;
QString fileToOpen;
if(fichier.open(QIODevice::ReadOnly))
{
QTextStream flux(&fichier);
ligne = flux.readLine();
}
QStringList fields;
fields = ligne.split(" | ");
fichier.close();
fileToOpen = fields[1]; //RECUPERE LE NOM DU FICHIER A OUVRIR
if(fileToOpen == "1A.txt")
{
QString root_folder_42 = *m_loc_123_compare;
QString annee_42 = "/1A.txt";
QString filename_2042 = root_folder_42 + annee_42;
fileToOpen = filename_2042;
}
if(fileToOpen == "2A.txt")
{
QString root_folder_42 = *m_loc_123_compare;
QString annee_42 = "/2A.txt";
QString filename_2042 = root_folder_42 + annee_42;
fileToOpen = filename_2042;
}
if(fileToOpen == "3A.txt")
{
QString root_folder_42 = *m_loc_123_compare;
QString annee_42 = "/3A.txt";
QString filename_2042 = root_folder_42 + annee_42;
fileToOpen = filename_2042;
}
QFile file(fileToOpen);
QString line;
QString all_file;
QStringList field_ligne;
QStringList sous_field_ligne;
QStringList field_test_matiere;
QStringList sous_field_test_matiere;
QVector <QString> vect(0);
bool ligne_deja_entree;
int nb_line = 0;
double coeff_P = 0;
double coeff_CC = 0;
double coeff_CR = 0;
double coeff_I = 0;
double moyenne_calc = 0;
double moyenne_promo = 0;
double diviseur = 0;
double moyenne_tab = 0;
double moyenne_tab_promo = 0;
int indice_ligne_tab = 0;
if(file.open(QIODevice:: ReadOnly))
{
QTextStream stream(&file);
while(!stream.atEnd())
{
line = stream.readLine();
nb_line = nb_line + 1;
}
} // NOMBRE DE LIGNE DU DOC
file.close();
QFile file1(fileToOpen);
if(file1.open(QIODevice::ReadOnly))
{
QTextStream stream1(&file1);
all_file = stream1.readAll();
field_ligne = all_file.split("\r\n");
for(int i=0 ; i< nb_line ; i++)
{
moyenne_calc = 0;
moyenne_promo = 0;
diviseur = 0;
ligne_deja_entree = false;
sous_field_ligne = field_ligne[i].split(" | ");
for(int w = 0 ; w<vect.size() ; w++)
{
if(sous_field_ligne[2] == vect[w])
{
ligne_deja_entree = true;
}
}
if(ligne_deja_entree == false)
{
if(sous_field_ligne[0] == "Pole Scientifique")
{
field_test_matiere = all_file.split("\r\n");
vect.push_back(sous_field_ligne[2]);
for(int k=i ; k < nb_line ; k++)
{
sous_field_test_matiere = field_test_matiere[k].split(" | ");
if(sous_field_test_matiere[0] == "Pole Scientifique")
{
if(sous_field_test_matiere[2] == sous_field_ligne[2])
{
QString root_folder = *m_loc_annee_compare;
QString annee = "/Annee.txt";
QString nomFichier = root_folder + annee;
QFile fichier_coeff(nomFichier);
QStringList field_coeff;
QString ligne_coeff;
if(fichier_coeff.open(QIODevice::ReadOnly))
{
QTextStream stream_coeff(&fichier_coeff);
ligne_coeff = stream_coeff.readLine();
field_coeff = ligne_coeff.split(" | ");
while(field_coeff[0] != sous_field_ligne[2])
{
ligne_coeff = stream_coeff.readLine();
field_coeff = ligne_coeff.split(" | ");
}
coeff_P = field_coeff[1].toDouble();
coeff_CC = field_coeff[2].toDouble();
coeff_I = field_coeff[3].toDouble();
coeff_CR = field_coeff[4].toDouble();
}
fichier_coeff.close();
if(sous_field_test_matiere[3] == "Partiel")
{
moyenne_calc = moyenne_calc + (coeff_P * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_P * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_P;
}
else if(sous_field_test_matiere[3] == "Controle Continu")
{
moyenne_calc = moyenne_calc + (coeff_CC * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_CC * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_CC;
}
else if(sous_field_test_matiere[3] == "Interogation")
{
moyenne_calc = moyenne_calc + (coeff_I * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_I * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_I;
}
else if(sous_field_test_matiere[3] == "Controle Experimental")
{
moyenne_calc = moyenne_calc + (coeff_CR * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_CR * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_CR;
}
}
}
}
if(ligne_deja_entree == false)
{
m_tableau_PS->setRowCount(m_tableau_PS->rowCount()+1);
moyenne_tab = moyenne_calc / diviseur;
moyenne_tab_promo = moyenne_promo / diviseur;
QTableWidgetItem *item0 = new QTableWidgetItem(sous_field_ligne[1]);
m_tableau_PS->setItem(indice_ligne_tab,0,item0);
QTableWidgetItem *item1 = new QTableWidgetItem(sous_field_ligne[2]);
m_tableau_PS->setItem(indice_ligne_tab,1,item1);
QTableWidgetItem *item = new QTableWidgetItem(QString::number(moyenne_tab));
m_tableau_PS->setItem(indice_ligne_tab,2,item);
m_tableau_PS->item(indice_ligne_tab,2)->setBackgroundColor(QColor(255,155,155));
m_tableau_PS->item(indice_ligne_tab,2)->setTextColor(QColor(255,255,255));
QFont bold;
bold.setBold(true);
m_tableau_PS->item(indice_ligne_tab,2)->setFont(bold);
QTableWidgetItem *item2 = new QTableWidgetItem(QString::number(moyenne_tab_promo));
m_tableau_PS->setItem(indice_ligne_tab,3,item2);
indice_ligne_tab = indice_ligne_tab + 1;
}
}
}
}
}
}
else if(!m_checkbox_S1->isChecked() && !m_checkbox_S2->isChecked())
{
QMessageBox::information(this,tr("Erreur"),tr("Veuillez choisir une période de l'année à afficher."));
}
}
void fen_moyenne :: trie_tab_PH()
{
if(m_checkbox_S1_PH->isChecked() && !m_checkbox_S2_PH->isChecked())
{
remplir_tab_PH();
}
else if(!m_checkbox_S1_PH->isChecked() && m_checkbox_S2_PH->isChecked())
{
while(m_tableau_PH->rowCount()>0)
{
m_tableau_PH->removeRow(m_tableau_PH->rowCount()-1);
}
QString root_folder = *m_loc_annee_compare;
QString annee = "/Annee.txt";
QString nomFichier = root_folder + annee;
QFile fichier(nomFichier);
QString ligne;
QString fileToOpen;
if(fichier.open(QIODevice::ReadOnly))
{
QTextStream flux(&fichier);
ligne = flux.readLine();
}
QStringList fields;
fields = ligne.split(" | ");
fichier.close();
fileToOpen = fields[1]; //RECUPERE LE NOM DU FICHIER A OUVRIR
if(fileToOpen == "1A.txt")
{
QString root_folder_42 = *m_loc_123_compare;
QString annee_42 = "/1A.txt";
QString filename_2042 = root_folder_42 + annee_42;
fileToOpen = filename_2042;
}
if(fileToOpen == "2A.txt")
{
QString root_folder_42 = *m_loc_123_compare;
QString annee_42 = "/2A.txt";
QString filename_2042 = root_folder_42 + annee_42;
fileToOpen = filename_2042;
}
if(fileToOpen == "3A.txt")
{
QString root_folder_42 = *m_loc_123_compare;
QString annee_42 = "/3A.txt";
QString filename_2042 = root_folder_42 + annee_42;
fileToOpen = filename_2042;
}
QFile file(fileToOpen);
QString line;
QString all_file;
QStringList field_ligne;
QStringList sous_field_ligne;
QStringList field_test_matiere;
QStringList sous_field_test_matiere;
QVector <QString> vect(0);
bool ligne_deja_entree;
int nb_line = 0;
double coeff_P = 0;
double coeff_CC = 0;
double coeff_CR = 0;
double coeff_I = 0;
double moyenne_calc = 0;
double moyenne_promo = 0;
double diviseur = 0;
double moyenne_tab = 0;
double moyenne_tab_promo = 0;
int indice_ligne_tab = 0;
if(file.open(QIODevice:: ReadOnly))
{
QTextStream stream(&file);
while(!stream.atEnd())
{
line = stream.readLine();
nb_line = nb_line + 1;
}
} // NOMBRE DE LIGNE DU DOC
file.close();
QFile file1(fileToOpen);
if(file1.open(QIODevice::ReadOnly))
{
QTextStream stream1(&file1);
all_file = stream1.readAll();
field_ligne = all_file.split("\r\n");
for(int i=0 ; i< nb_line ; i++)
{
moyenne_calc = 0;
moyenne_promo = 0;
diviseur = 0;
ligne_deja_entree = false;
sous_field_ligne = field_ligne[i].split(" | ");
for(int w = 0 ; w<vect.size() ; w++)
{
if(sous_field_ligne[2] == vect[w])
{
ligne_deja_entree = true;
}
}
if(ligne_deja_entree == false)
{
if(sous_field_ligne[0] == "Pole Humain et Culture de l'Ingenieur")
{
if(sous_field_ligne[1] == "Semestre 2")
{
field_test_matiere = all_file.split("\r\n");
vect.push_back(sous_field_ligne[2]);
for(int k=i ; k < nb_line ; k++)
{
sous_field_test_matiere = field_test_matiere[k].split(" | ");
if(sous_field_test_matiere[0] == "Pole Humain et Culture de l'Ingenieur")
{
if(sous_field_test_matiere[1] == "Semestre 2")
{
if(sous_field_test_matiere[2] == sous_field_ligne[2])
{
QString root_folder = *m_loc_annee_compare;
QString annee = "/Annee.txt";
QString nomFichier = root_folder + annee;
QFile fichier_coeff(nomFichier);
QStringList field_coeff;
QString ligne_coeff;
if(fichier_coeff.open(QIODevice::ReadOnly))
{
QTextStream stream_coeff(&fichier_coeff);
ligne_coeff = stream_coeff.readLine();
field_coeff = ligne_coeff.split(" | ");
while(field_coeff[0] != sous_field_ligne[2])
{
ligne_coeff = stream_coeff.readLine();
field_coeff = ligne_coeff.split(" | ");
}
coeff_P = field_coeff[1].toDouble();
coeff_CC = field_coeff[2].toDouble();
coeff_I = field_coeff[3].toDouble();
coeff_CR = field_coeff[4].toDouble();
}
fichier_coeff.close();
if(sous_field_test_matiere[3] == "Partiel")
{
moyenne_calc = moyenne_calc + (coeff_P * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_P * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_P;
}
else if(sous_field_test_matiere[3] == "Controle Continu")
{
moyenne_calc = moyenne_calc + (coeff_CC * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_CC * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_CC;
}
else if(sous_field_test_matiere[3] == "Interogation")
{
moyenne_calc = moyenne_calc + (coeff_I * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_I * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_I;
}
else if(sous_field_test_matiere[3] == "Controle Experimental")
{
moyenne_calc = moyenne_calc + (coeff_CR * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_CR * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_CR;
}
}
}
}
}
if(ligne_deja_entree == false)
{
m_tableau_PH->setRowCount(m_tableau_PH->rowCount()+1);
moyenne_tab = moyenne_calc / diviseur;
moyenne_tab_promo = moyenne_promo / diviseur;
QTableWidgetItem *item0 = new QTableWidgetItem(sous_field_ligne[1]);
m_tableau_PH->setItem(indice_ligne_tab,0,item0);
QTableWidgetItem *item1 = new QTableWidgetItem(sous_field_ligne[2]);
m_tableau_PH->setItem(indice_ligne_tab,1,item1);
QTableWidgetItem *item = new QTableWidgetItem(QString::number(moyenne_tab));
m_tableau_PH->setItem(indice_ligne_tab,2,item);
m_tableau_PH->item(indice_ligne_tab,2)->setBackgroundColor(QColor(255,155,155));
m_tableau_PH->item(indice_ligne_tab,2)->setTextColor(QColor(255,255,255));
QFont bold;
bold.setBold(true);
m_tableau_PH->item(indice_ligne_tab,2)->setFont(bold);
QTableWidgetItem *item2 = new QTableWidgetItem(QString::number(moyenne_tab_promo));
m_tableau_PH->setItem(indice_ligne_tab,3,item2);
indice_ligne_tab = indice_ligne_tab + 1;
}
}
}
}
}
}
}
else if(m_checkbox_S1_PH->isChecked() && m_checkbox_S2_PH->isChecked())
{
while(m_tableau_PH->rowCount()>0)
{
m_tableau_PH->removeRow(m_tableau_PH->rowCount()-1);
}
QString root_folder = *m_loc_annee_compare;
QString annee = "/Annee.txt";
QString nomFichier = root_folder + annee;
QFile fichier(nomFichier);
QString ligne;
QString fileToOpen;
if(fichier.open(QIODevice::ReadOnly))
{
QTextStream flux(&fichier);
ligne = flux.readLine();
}
QStringList fields;
fields = ligne.split(" | ");
fichier.close();
fileToOpen = fields[1]; //RECUPERE LE NOM DU FICHIER A OUVRIR
if(fileToOpen == "1A.txt")
{
QString root_folder_42 = *m_loc_123_compare;
QString annee_42 = "/1A.txt";
QString filename_2042 = root_folder_42 + annee_42;
fileToOpen = filename_2042;
}
if(fileToOpen == "2A.txt")
{
QString root_folder_42 = *m_loc_123_compare;
QString annee_42 = "/2A.txt";
QString filename_2042 = root_folder_42 + annee_42;
fileToOpen = filename_2042;
}
if(fileToOpen == "3A.txt")
{
QString root_folder_42 = *m_loc_123_compare;
QString annee_42 = "/3A.txt";
QString filename_2042 = root_folder_42 + annee_42;
fileToOpen = filename_2042;
}
QFile file(fileToOpen);
QString line;
QString all_file;
QStringList field_ligne;
QStringList sous_field_ligne;
QStringList field_test_matiere;
QStringList sous_field_test_matiere;
QVector <QString> vect(0);
bool ligne_deja_entree;
int nb_line = 0;
double coeff_P = 0;
double coeff_CC = 0;
double coeff_CR = 0;
double coeff_I = 0;
double moyenne_calc = 0;
double moyenne_promo = 0;
double diviseur = 0;
double moyenne_tab = 0;
double moyenne_tab_promo = 0;
int indice_ligne_tab = 0;
if(file.open(QIODevice:: ReadOnly))
{
QTextStream stream(&file);
while(!stream.atEnd())
{
line = stream.readLine();
nb_line = nb_line + 1;
}
} // NOMBRE DE LIGNE DU DOC
file.close();
QFile file1(fileToOpen);
if(file1.open(QIODevice::ReadOnly))
{
QTextStream stream1(&file1);
all_file = stream1.readAll();
field_ligne = all_file.split("\r\n");
for(int i=0 ; i< nb_line ; i++)
{
moyenne_calc = 0;
moyenne_promo = 0;
diviseur = 0;
ligne_deja_entree = false;
sous_field_ligne = field_ligne[i].split(" | ");
for(int w = 0 ; w<vect.size() ; w++)
{
if(sous_field_ligne[2] == vect[w])
{
ligne_deja_entree = true;
}
}
if(ligne_deja_entree == false)
{
if(sous_field_ligne[0] == "Pole Humain et Culture de l'Ingenieur")
{
field_test_matiere = all_file.split("\r\n");
vect.push_back(sous_field_ligne[2]);
for(int k=i ; k < nb_line ; k++)
{
sous_field_test_matiere = field_test_matiere[k].split(" | ");
if(sous_field_test_matiere[0] == "Pole Humain et Culture de l'Ingenieur")
{
if(sous_field_test_matiere[2] == sous_field_ligne[2])
{
QString root_folder = *m_loc_annee_compare;
QString annee = "/Annee.txt";
QString nomFichier = root_folder + annee;
QFile fichier_coeff(nomFichier);
QStringList field_coeff;
QString ligne_coeff;
if(fichier_coeff.open(QIODevice::ReadOnly))
{
QTextStream stream_coeff(&fichier_coeff);
ligne_coeff = stream_coeff.readLine();
field_coeff = ligne_coeff.split(" | ");
while(field_coeff[0] != sous_field_ligne[2])
{
ligne_coeff = stream_coeff.readLine();
field_coeff = ligne_coeff.split(" | ");
}
coeff_P = field_coeff[1].toDouble();
coeff_CC = field_coeff[2].toDouble();
coeff_I = field_coeff[3].toDouble();
coeff_CR = field_coeff[4].toDouble();
}
fichier_coeff.close();
if(sous_field_test_matiere[3] == "Partiel")
{
moyenne_calc = moyenne_calc + (coeff_P * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_P * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_P;
}
else if(sous_field_test_matiere[3] == "Controle Continu")
{
moyenne_calc = moyenne_calc + (coeff_CC * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_CC * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_CC;
}
else if(sous_field_test_matiere[3] == "Interogation")
{
moyenne_calc = moyenne_calc + (coeff_I * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_I * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_I;
}
else if(sous_field_test_matiere[3] == "Controle Experimental")
{
moyenne_calc = moyenne_calc + (coeff_CR * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_CR * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_CR;
}
}
}
}
if(ligne_deja_entree == false)
{
m_tableau_PH->setRowCount(m_tableau_PH->rowCount()+1);
moyenne_tab = moyenne_calc / diviseur;
moyenne_tab_promo = moyenne_promo / diviseur;
QTableWidgetItem *item0 = new QTableWidgetItem(sous_field_ligne[1]);
m_tableau_PH->setItem(indice_ligne_tab,0,item0);
QTableWidgetItem *item1 = new QTableWidgetItem(sous_field_ligne[2]);
m_tableau_PH->setItem(indice_ligne_tab,1,item1);
QTableWidgetItem *item = new QTableWidgetItem(QString::number(moyenne_tab));
m_tableau_PH->setItem(indice_ligne_tab,2,item);
m_tableau_PH->item(indice_ligne_tab,2)->setBackgroundColor(QColor(255,155,155));
m_tableau_PH->item(indice_ligne_tab,2)->setTextColor(QColor(255,255,255));
QFont bold;
bold.setBold(true);
m_tableau_PH->item(indice_ligne_tab,2)->setFont(bold);
QTableWidgetItem *item2 = new QTableWidgetItem(QString::number(moyenne_tab_promo));
m_tableau_PH->setItem(indice_ligne_tab,3,item2);
indice_ligne_tab = indice_ligne_tab + 1;
}
}
}
}
}
}
else if(!m_checkbox_S1_PH->isChecked() && !m_checkbox_S2_PH->isChecked())
{
QMessageBox::information(this,tr("Erreur"),tr("Veuillez choisir une période de l'année à afficher."));
}
}
void fen_moyenne :: print_tab_PS()
{
QString titre;
QPrinter printer(QPrinter::HighResolution);
printer.setPaperSize (QPrinter::A4);
// printer.setOutputFormat (QPrinter::PdfFormat);
printer.setOrientation(QPrinter::Landscape);
printer.setFullPage(true);
QPrintDialog printDialog(&printer, this);
if ( printDialog.exec() == 1)
{
QTextBrowser * editor = new QTextBrowser;
//creation de formats d'écriture
QTextCharFormat NormalFormat;
QTextCharFormat ItalicFormat;
ItalicFormat.setFontItalic(true);
//On insere la date et l'heure actuelle au début de la premiere page
//QDate date;
//QTime time;
//date = date.currentDate();
//time = time.currentTime();
//QString modif ="\nFait le :\t" + date.toString("dddd dd MMMM yyyy") + " a " + time.toString();
//changement du format d'ecriture
editor->setCurrentCharFormat(ItalicFormat);
editor->setAlignment(Qt::AlignLeft);
//ajout de notre QString a l'endroit du curseur
//editor->append(modif);
editor->setCurrentCharFormat(NormalFormat);
//on insere le titre du tableau
/* QTextCharFormat format_gros_titre;
format_gros_titre.setFontPointSize(16);
format_gros_titre.setFontWeight(QFont::Bold);
format_gros_titre.setVerticalAlignment(QTextCharFormat::AlignMiddle);
format_gros_titre.setUnderlineStyle(QTextCharFormat::SingleUnderline);*/
//QString title ="\n"+QString::fromUtf8(titre.toStdString().c_str())+"\n";
// editor->setCurrentCharFormat(format_gros_titre);
//editor->setAlignment(Qt::AlignCenter);
//editor->append(title);
editor->setCurrentCharFormat(NormalFormat);
//on crée un curseur a l'endroit du curseur actuel
QTextCursor cursor = editor->textCursor();
cursor.beginEditBlock();
//Creation du format du tableau qui sera imprimer
QTextTableFormat tableFormat;
tableFormat.setAlignment(Qt::AlignHCenter);
tableFormat.setAlignment(Qt::AlignLeft);
tableFormat.setBackground(QColor("#ffffff"));
tableFormat.setCellPadding(5);
tableFormat.setCellSpacing(5);
//Creation du tableau qui sera imprimé avec le nombre de colonne
//et de ligne que contient le tableau mis en parametre
QTextTable * tableau = cursor.insertTable(m_tableau_PS->rowCount()+1, m_tableau_PS->columnCount(), tableFormat);
QTextFrame *frame = cursor.currentFrame();
QTextFrameFormat frameFormat = frame->frameFormat();
frameFormat.setBorder(0);
frame->setFrameFormat(frameFormat);
//Format des HEADER du tableau
QTextCharFormat format_entete_tableau;
format_entete_tableau.setFontPointSize(10);
format_entete_tableau.setFontWeight(QFont::Bold);
//Format du texte des cellules du tableau
QTextCharFormat format_cellule;
format_cellule.setFontPointSize(8);
//on ecrit les HEADERS du tableaux dans le tableau a imprimer
for ( int i = 0 ; i < m_tableau_PS->columnCount() ; i++ )
{
//on selectionne la premiere cellule de chaque colonne
QTextTableCell titre = tableau->cellAt(0,i);
//on place le curseur a cet endroit
QTextCursor cellCursor = titre.firstCursorPosition();
//on écrit dans la cellule
cellCursor.insertText(m_tableau_PS->horizontalHeaderItem(i)->text(),format_entete_tableau);
}
QTextTableCell cell;
QTextCursor cellCursor;
for (int row = 1; row < tableau->rows(); row ++)
for (int col = 0; col < tableau->columns(); col ++)
{
cell = tableau->cellAt(row,col);
cellCursor = cell.firstCursorPosition();
cellCursor.insertText(tr("%1").arg(m_tableau_PS->item(row-1,col)->text()),format_cellule);
}
//fin de l'edition
cursor.endEditBlock();
//impression de notre editor dans le QPrinter initialisé au début de la fonction
editor->print(&printer);
}
}
void fen_moyenne :: print_tab_PH()
{
QString titre;
QPrinter printer(QPrinter::HighResolution);
printer.setPaperSize (QPrinter::A4);
// printer.setOutputFormat (QPrinter::PdfFormat);
printer.setOrientation(QPrinter::Landscape);
printer.setFullPage(true);
QPrintDialog printDialog(&printer, this);
if ( printDialog.exec() == 1)
{
QTextBrowser * editor = new QTextBrowser;
//creation de formats d'écriture
QTextCharFormat NormalFormat;
QTextCharFormat ItalicFormat;
ItalicFormat.setFontItalic(true);
//On insere la date et l'heure actuelle au début de la premiere page
//QDate date;
//QTime time;
//date = date.currentDate();
//time = time.currentTime();
//QString modif ="\nFait le :\t" + date.toString("dddd dd MMMM yyyy") + " a " + time.toString();
//changement du format d'ecriture
editor->setCurrentCharFormat(ItalicFormat);
editor->setAlignment(Qt::AlignLeft);
//ajout de notre QString a l'endroit du curseur
//editor->append(modif);
editor->setCurrentCharFormat(NormalFormat);
//on insere le titre du tableau
/* QTextCharFormat format_gros_titre;
format_gros_titre.setFontPointSize(16);
format_gros_titre.setFontWeight(QFont::Bold);
format_gros_titre.setVerticalAlignment(QTextCharFormat::AlignMiddle);
format_gros_titre.setUnderlineStyle(QTextCharFormat::SingleUnderline);*/
//QString title ="\n"+QString::fromUtf8(titre.toStdString().c_str())+"\n";
// editor->setCurrentCharFormat(format_gros_titre);
//editor->setAlignment(Qt::AlignCenter);
//editor->append(title);
editor->setCurrentCharFormat(NormalFormat);
//on crée un curseur a l'endroit du curseur actuel
QTextCursor cursor = editor->textCursor();
cursor.beginEditBlock();
//Creation du format du tableau qui sera imprimer
QTextTableFormat tableFormat;
tableFormat.setAlignment(Qt::AlignHCenter);
tableFormat.setAlignment(Qt::AlignLeft);
tableFormat.setBackground(QColor("#ffffff"));
tableFormat.setCellPadding(5);
tableFormat.setCellSpacing(5);
//Creation du tableau qui sera imprimé avec le nombre de colonne
//et de ligne que contient le tableau mis en parametre
QTextTable * tableau = cursor.insertTable(m_tableau_PH->rowCount()+1, m_tableau_PH->columnCount(), tableFormat);
QTextFrame *frame = cursor.currentFrame();
QTextFrameFormat frameFormat = frame->frameFormat();
frameFormat.setBorder(0);
frame->setFrameFormat(frameFormat);
//Format des HEADER du tableau
QTextCharFormat format_entete_tableau;
format_entete_tableau.setFontPointSize(10);
format_entete_tableau.setFontWeight(QFont::Bold);
//Format du texte des cellules du tableau
QTextCharFormat format_cellule;
format_cellule.setFontPointSize(8);
//on ecrit les HEADERS du tableaux dans le tableau a imprimer
for ( int i = 0 ; i < m_tableau_PH->columnCount() ; i++ )
{
//on selectionne la premiere cellule de chaque colonne
QTextTableCell titre = tableau->cellAt(0,i);
//on place le curseur a cet endroit
QTextCursor cellCursor = titre.firstCursorPosition();
//on écrit dans la cellule
cellCursor.insertText(m_tableau_PH->horizontalHeaderItem(i)->text(),format_entete_tableau);
}
QTextTableCell cell;
QTextCursor cellCursor;
for (int row = 1; row < tableau->rows(); row ++)
for (int col = 0; col < tableau->columns(); col ++)
{
cell = tableau->cellAt(row,col);
cellCursor = cell.firstCursorPosition();
cellCursor.insertText(tr("%1").arg(m_tableau_PH->item(row-1,col)->text()),format_cellule);
}
//fin de l'edition
cursor.endEditBlock();
//impression de notre editor dans le QPrinter initialisé au début de la fonction
editor->print(&printer);
}
}
void fen_moyenne :: trier_tab_I()
{
if(m_checkbox_S1_I->isChecked() && !m_checkbox_S2_I->isChecked())
{
remplir_tableau_I();
}
else if(!m_checkbox_S1_I->isChecked() && m_checkbox_S2->isChecked())
{
while(m_tableau_ingenieur->rowCount()>0)
{
m_tableau_ingenieur->removeRow(m_tableau_ingenieur->rowCount()-1);
}
QString root_folder = *m_loc_annee_compare;
QString annee = "/Annee.txt";
QString nomFichier = root_folder + annee;
QFile fichier(nomFichier);
QString ligne;
QString fileToOpen;
if(fichier.open(QIODevice::ReadOnly))
{
QTextStream flux(&fichier);
ligne = flux.readLine();
}
QStringList fields;
fields = ligne.split(" | ");
fichier.close();
fileToOpen = fields[1]; //RECUPERE LE NOM DU FICHIER A OUVRIR
if(fileToOpen == "1A.txt")
{
QString root_folder_42 = *m_loc_123_compare;
QString annee_42 = "/1A.txt";
QString filename_2042 = root_folder_42 + annee_42;
fileToOpen = filename_2042;
}
if(fileToOpen == "2A.txt")
{
QString root_folder_42 = *m_loc_123_compare;
QString annee_42 = "/2A.txt";
QString filename_2042 = root_folder_42 + annee_42;
fileToOpen = filename_2042;
}
if(fileToOpen == "3A.txt")
{
QString root_folder_42 = *m_loc_123_compare;
QString annee_42 = "/3A.txt";
QString filename_2042 = root_folder_42 + annee_42;
fileToOpen = filename_2042;
}
QFile file(fileToOpen);
QString line;
QString all_file;
QStringList field_ligne;
QStringList sous_field_ligne;
QStringList field_test_matiere;
QStringList sous_field_test_matiere;
QVector <QString> vect(0);
bool ligne_deja_entree;
int nb_line = 0;
double coeff_P = 0;
double coeff_CC = 0;
double coeff_CR = 0;
double coeff_I = 0;
double moyenne_calc = 0;
double moyenne_promo = 0;
double diviseur = 0;
double moyenne_tab = 0;
double moyenne_tab_promo = 0;
int indice_ligne_tab = 0;
if(file.open(QIODevice:: ReadOnly))
{
QTextStream stream(&file);
while(!stream.atEnd())
{
line = stream.readLine();
nb_line = nb_line + 1;
}
} // NOMBRE DE LIGNE DU DOC
file.close();
QFile file1(fileToOpen);
if(file1.open(QIODevice::ReadOnly))
{
QTextStream stream1(&file1);
all_file = stream1.readAll();
field_ligne = all_file.split("\r\n");
for(int i=0 ; i< nb_line ; i++)
{
moyenne_calc = 0;
moyenne_promo = 0;
diviseur = 0;
ligne_deja_entree = false;
sous_field_ligne = field_ligne[i].split(" | ");
for(int w = 0 ; w<vect.size() ; w++)
{
if(sous_field_ligne[2] == vect[w])
{
ligne_deja_entree = true;
}
}
if(ligne_deja_entree == false)
{
if(sous_field_ligne[0] == "Pole Ingenierie des Transports")
{
if(sous_field_ligne[1] == "Semestre 2")
{
field_test_matiere = all_file.split("\r\n");
vect.push_back(sous_field_ligne[2]);
for(int k=i ; k < nb_line ; k++)
{
sous_field_test_matiere = field_test_matiere[k].split(" | ");
if(sous_field_test_matiere[0] == "Pole Ingenierie des Transports")
{
if(sous_field_test_matiere[1] == "Semestre 2")
{
if(sous_field_test_matiere[2] == sous_field_ligne[2])
{
QString root_folder = *m_loc_annee_compare;
QString annee = "/Annee.txt";
QString nomFichier = root_folder + annee;
QFile fichier_coeff(nomFichier);
QStringList field_coeff;
QString ligne_coeff;
if(fichier_coeff.open(QIODevice::ReadOnly))
{
QTextStream stream_coeff(&fichier_coeff);
ligne_coeff = stream_coeff.readLine();
field_coeff = ligne_coeff.split(" | ");
while(field_coeff[0] != sous_field_ligne[2])
{
ligne_coeff = stream_coeff.readLine();
field_coeff = ligne_coeff.split(" | ");
}
coeff_P = field_coeff[1].toDouble();
coeff_CC = field_coeff[2].toDouble();
coeff_I = field_coeff[3].toDouble();
coeff_CR = field_coeff[4].toDouble();
}
fichier_coeff.close();
if(sous_field_test_matiere[3] == "Partiel")
{
moyenne_calc = moyenne_calc + (coeff_P * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_P * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_P;
}
else if(sous_field_test_matiere[3] == "Controle Continu")
{
moyenne_calc = moyenne_calc + (coeff_CC * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_CC * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_CC;
}
else if(sous_field_test_matiere[3] == "Interogation")
{
moyenne_calc = moyenne_calc + (coeff_I * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_I * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_I;
}
else if(sous_field_test_matiere[3] == "Controle Experimental")
{
moyenne_calc = moyenne_calc + (coeff_CR * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_CR * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_CR;
}
}
}
}
}
if(ligne_deja_entree == false)
{
m_tableau_ingenieur->setRowCount(m_tableau_ingenieur->rowCount()+1);
moyenne_tab = moyenne_calc / diviseur;
moyenne_tab_promo = moyenne_promo / diviseur;
QTableWidgetItem *item0 = new QTableWidgetItem(sous_field_ligne[1]);
m_tableau_ingenieur->setItem(indice_ligne_tab,0,item0);
QTableWidgetItem *item1 = new QTableWidgetItem(sous_field_ligne[2]);
m_tableau_ingenieur->setItem(indice_ligne_tab,1,item1);
QTableWidgetItem *item = new QTableWidgetItem(QString::number(moyenne_tab));
m_tableau_ingenieur->setItem(indice_ligne_tab,2,item);
m_tableau_ingenieur->item(indice_ligne_tab,2)->setBackgroundColor(QColor(255,155,155));
m_tableau_ingenieur->item(indice_ligne_tab,2)->setTextColor(QColor(255,255,255));
QFont bold;
bold.setBold(true);
m_tableau_ingenieur->item(indice_ligne_tab,2)->setFont(bold);
QTableWidgetItem *item2 = new QTableWidgetItem(QString::number(moyenne_tab_promo));
m_tableau_ingenieur->setItem(indice_ligne_tab,3,item2);
indice_ligne_tab = indice_ligne_tab + 1;
}
}
}
}
}
}
}
else if(m_checkbox_S1_I->isChecked() && m_checkbox_S2_I->isChecked())
{
while(m_tableau_ingenieur->rowCount()>0)
{
m_tableau_ingenieur->removeRow(m_tableau_ingenieur->rowCount()-1);
}
QString root_folder = *m_loc_annee_compare;
QString annee = "/Annee.txt";
QString nomFichier = root_folder + annee;
QFile fichier(nomFichier);
QString ligne;
QString fileToOpen;
if(fichier.open(QIODevice::ReadOnly))
{
QTextStream flux(&fichier);
ligne = flux.readLine();
}
QStringList fields;
fields = ligne.split(" | ");
fichier.close();
fileToOpen = fields[1]; //RECUPERE LE NOM DU FICHIER A OUVRIR
if(fileToOpen == "1A.txt")
{
QString root_folder_42 = *m_loc_123_compare;
QString annee_42 = "/1A.txt";
QString filename_2042 = root_folder_42 + annee_42;
fileToOpen = filename_2042;
}
if(fileToOpen == "2A.txt")
{
QString root_folder_42 = *m_loc_123_compare;
QString annee_42 = "/2A.txt";
QString filename_2042 = root_folder_42 + annee_42;
fileToOpen = filename_2042;
}
if(fileToOpen == "3A.txt")
{
QString root_folder_42 = *m_loc_123_compare;
QString annee_42 = "/3A.txt";
QString filename_2042 = root_folder_42 + annee_42;
fileToOpen = filename_2042;
}
QFile file(fileToOpen);
QString line;
QString all_file;
QStringList field_ligne;
QStringList sous_field_ligne;
QStringList field_test_matiere;
QStringList sous_field_test_matiere;
QVector <QString> vect(0);
bool ligne_deja_entree;
int nb_line = 0;
double coeff_P = 0;
double coeff_CC = 0;
double coeff_CR = 0;
double coeff_I = 0;
double moyenne_calc = 0;
double moyenne_promo = 0;
double diviseur = 0;
double moyenne_tab = 0;
double moyenne_tab_promo = 0;
int indice_ligne_tab = 0;
if(file.open(QIODevice:: ReadOnly))
{
QTextStream stream(&file);
while(!stream.atEnd())
{
line = stream.readLine();
nb_line = nb_line + 1;
}
} // NOMBRE DE LIGNE DU DOC
file.close();
QFile file1(fileToOpen);
if(file1.open(QIODevice::ReadOnly))
{
QTextStream stream1(&file1);
all_file = stream1.readAll();
field_ligne = all_file.split("\r\n");
for(int i=0 ; i< nb_line ; i++)
{
moyenne_calc = 0;
moyenne_promo = 0;
diviseur = 0;
ligne_deja_entree = false;
sous_field_ligne = field_ligne[i].split(" | ");
for(int w = 0 ; w<vect.size() ; w++)
{
if(sous_field_ligne[2] == vect[w])
{
ligne_deja_entree = true;
}
}
if(ligne_deja_entree == false)
{
if(sous_field_ligne[0] == "Pole Ingenierie des Transports")
{
field_test_matiere = all_file.split("\r\n");
vect.push_back(sous_field_ligne[2]);
for(int k=i ; k < nb_line ; k++)
{
sous_field_test_matiere = field_test_matiere[k].split(" | ");
if(sous_field_test_matiere[0] == "Pole Ingenierie des Transports")
{
if(sous_field_test_matiere[2] == sous_field_ligne[2])
{
QString root_folder = *m_loc_annee_compare;
QString annee = "/Annee.txt";
QString nomFichier = root_folder + annee;
QFile fichier_coeff(nomFichier);
QStringList field_coeff;
QString ligne_coeff;
if(fichier_coeff.open(QIODevice::ReadOnly))
{
QTextStream stream_coeff(&fichier_coeff);
ligne_coeff = stream_coeff.readLine();
field_coeff = ligne_coeff.split(" | ");
while(field_coeff[0] != sous_field_ligne[2])
{
ligne_coeff = stream_coeff.readLine();
field_coeff = ligne_coeff.split(" | ");
}
coeff_P = field_coeff[1].toDouble();
coeff_CC = field_coeff[2].toDouble();
coeff_I = field_coeff[3].toDouble();
coeff_CR = field_coeff[4].toDouble();
}
fichier_coeff.close();
if(sous_field_test_matiere[3] == "Partiel")
{
moyenne_calc = moyenne_calc + (coeff_P * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_P * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_P;
}
else if(sous_field_test_matiere[3] == "Controle Continu")
{
moyenne_calc = moyenne_calc + (coeff_CC * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_CC * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_CC;
}
else if(sous_field_test_matiere[3] == "Interogation")
{
moyenne_calc = moyenne_calc + (coeff_I * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_I * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_I;
}
else if(sous_field_test_matiere[3] == "Controle Experimental")
{
moyenne_calc = moyenne_calc + (coeff_CR * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_CR * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_CR;
}
}
}
}
if(ligne_deja_entree == false)
{
m_tableau_ingenieur->setRowCount(m_tableau_ingenieur->rowCount()+1);
moyenne_tab = moyenne_calc / diviseur;
moyenne_tab_promo = moyenne_promo / diviseur;
QTableWidgetItem *item0 = new QTableWidgetItem(sous_field_ligne[1]);
m_tableau_ingenieur->setItem(indice_ligne_tab,0,item0);
QTableWidgetItem *item1 = new QTableWidgetItem(sous_field_ligne[2]);
m_tableau_ingenieur->setItem(indice_ligne_tab,1,item1);
QTableWidgetItem *item = new QTableWidgetItem(QString::number(moyenne_tab));
m_tableau_ingenieur->setItem(indice_ligne_tab,2,item);
m_tableau_ingenieur->item(indice_ligne_tab,2)->setBackgroundColor(QColor(255,155,155));
m_tableau_ingenieur->item(indice_ligne_tab,2)->setTextColor(QColor(255,255,255));
QFont bold;
bold.setBold(true);
m_tableau_ingenieur->item(indice_ligne_tab,2)->setFont(bold);
QTableWidgetItem *item2 = new QTableWidgetItem(QString::number(moyenne_tab_promo));
m_tableau_ingenieur->setItem(indice_ligne_tab,3,item2);
indice_ligne_tab = indice_ligne_tab + 1;
}
}
}
}
}
}
else if(!m_checkbox_S1_I->isChecked() && !m_checkbox_S2_I->isChecked())
{
QMessageBox::information(this,tr("Erreur"),tr("Veuillez choisir une période de l'année à afficher."));
}
}
void fen_moyenne :: coloration_tab_I()
{
if(m_checkbox_gestion_I->isChecked())
{
int nb_verts = 0;
int nb_rouges = 0;
for(int i = 0 ; i < m_tableau_ingenieur->rowCount() ; i++)
{
double note = m_tableau_ingenieur->item(i,2)->text().toDouble();
double moyenne = m_tableau_ingenieur->item(i,3)->text().toDouble();
if(note > moyenne)
{
for(int m=0;m<m_tableau_ingenieur->columnCount();m++)
{
m_tableau_ingenieur->item(i,m)->setBackgroundColor(QColor(72,163,67));
}
nb_verts = nb_verts + 1;
}
else if(note < moyenne)
{
for(int m=0;m<m_tableau_ingenieur->columnCount();m++)
{
m_tableau_ingenieur->item(i,m)->setBackgroundColor(QColor(204,37,37));
}
nb_rouges = nb_rouges + 1;
}
}
QString string_verts = QString::number(nb_verts);
QString string_rouges = QString::number(nb_rouges);
if(nb_verts > 1)
{
m_label_gestion_I->setText(string_verts+tr(" lignes vertes"));
QPalette pal =QPalette(m_label_gestion_I->palette());
pal.setColor(QPalette::WindowText, QColor(72,163,67));
m_label_gestion_I->setPalette(pal);
}
else if(nb_verts <= 1)
{
m_label_gestion_I->setText(string_verts+tr(" ligne verte"));
QPalette pal =QPalette(m_label_gestion_I->palette());
pal.setColor(QPalette::WindowText, QColor(72,163,67));
m_label_gestion_I->setPalette(pal);
}
if(nb_rouges > 1)
{
m_label_gestion_rouges_I->setText(string_rouges+tr(" lignes rouges"));
QPalette pal1 =QPalette(m_label_gestion_rouges_I->palette());
pal1.setColor(QPalette::WindowText, QColor(204,37,37));
m_label_gestion_rouges_I->setPalette(pal1);
}
else if(nb_rouges <= 1)
{
m_label_gestion_rouges_I->setText(string_rouges+tr(" ligne rouge"));
QPalette pal1 =QPalette(m_label_gestion_rouges_I->palette());
pal1.setColor(QPalette::WindowText, QColor(204,37,37));
m_label_gestion_rouges_I->setPalette(pal1);
}
}
else if(!m_checkbox_gestion_I->isChecked())
{
for(int i = 0 ; i < m_tableau_ingenieur->rowCount() ; i++)
{
for(int m=0;m<m_tableau_ingenieur->columnCount();m++)
{
m_tableau_ingenieur->item(i,m)->setBackgroundColor(QColor(255,255,255));
m_tableau_ingenieur->item(i,2)->setBackgroundColor(QColor(255,155,155));
}
}
m_label_gestion_I->setText("");
m_label_gestion_rouges_I->setText("");
}
}
void fen_moyenne :: enregistrer_tab_I()
{
QString fileName = QFileDialog::getSaveFileName((QWidget* )0, tr("Enregistrer en PDF"), QString(), "*.pdf");
if(fileName.isEmpty())
{
return;
}
if (QFileInfo(fileName).suffix().isEmpty()) { fileName.append(".pdf"); }
QPrinter printer(QPrinter::PrinterResolution);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setPaperSize(QPrinter::A4);
printer.setFullPage(true);
printer.setOrientation(QPrinter::Portrait);
printer.setOutputFileName(fileName);
QTextBrowser * editor = new QTextBrowser;
QTextCharFormat NormalFormat;
QTextCharFormat ItalicFormat;
ItalicFormat.setFontItalic(true);
QDate date;
QTime time;
date = date.currentDate();
time = time.currentTime();
QString modif ="\nFait le :\t" + date.toString("dddd dd MMMM yyyy") + " à " + time.toString();
editor->setCurrentCharFormat(ItalicFormat);
editor->setAlignment(Qt::AlignLeft);
editor->append(modif);
editor->setCurrentCharFormat(NormalFormat);
QTextCharFormat format_gros_titre;
format_gros_titre.setFontPointSize(18);
format_gros_titre.setFontWeight(QFont::Bold);
format_gros_titre.setVerticalAlignment(QTextCharFormat::AlignMiddle);
format_gros_titre.setUnderlineStyle(QTextCharFormat::SingleUnderline);
editor->setCurrentCharFormat(NormalFormat);
QTextCursor cursor = editor->textCursor();
cursor.beginEditBlock();
QTextTableFormat tableFormat;
tableFormat.setAlignment(Qt::AlignHCenter);
tableFormat.setAlignment(Qt::AlignLeft);
tableFormat.setBackground(QColor("#ffffff"));
tableFormat.setCellPadding(2);
tableFormat.setCellSpacing(2);
QTextTable * tableau = cursor.insertTable(m_tableau_ingenieur->rowCount()+1, m_tableau_ingenieur->columnCount(), tableFormat);
QTextFrame *frame = cursor.currentFrame();
QTextFrameFormat frameFormat = frame->frameFormat();
frameFormat.setBorder(0);
frame->setFrameFormat(frameFormat);
QTextCharFormat format_entete_tableau;
format_entete_tableau.setFontPointSize(10);
format_entete_tableau.setFontWeight(QFont::Bold);
QTextCharFormat format_cellule;
format_cellule.setFontPointSize(8);
for ( int i = 0 ; i < m_tableau_ingenieur->columnCount() ; i++ )
{
QTextTableCell titre = tableau->cellAt(0,i);
QTextCursor cellCursor = titre.firstCursorPosition();
cellCursor.insertText(m_tableau_ingenieur->horizontalHeaderItem(i)->text(),format_entete_tableau);
}
QTextTableCell cell;
QTextCursor cellCursor;
for (int row = 1; row < tableau->rows(); row ++)
for (int col = 0; col < tableau->columns(); col ++)
{
cell = tableau->cellAt(row,col);
cellCursor = cell.firstCursorPosition();
cellCursor.insertText(tr("%1").arg(m_tableau_ingenieur->item(row-1,col)->text()),format_cellule);
}
cursor.endEditBlock();
editor->print(&printer);
QMessageBox::information(this,tr("Enregistrer un PDF"),"'"+fileName+tr("' enregistré avec succès"));
}
void fen_moyenne :: remplir_tableau_I()
{
while(m_tableau_ingenieur->rowCount()>0)
{
m_tableau_ingenieur->removeRow(m_tableau_ingenieur->rowCount()-1);
}
QString root_folder = *m_loc_annee_compare;
QString annee = "/Annee.txt";
QString nomFichier = root_folder + annee;
QFile fichier(nomFichier);
QString ligne;
QString fileToOpen;
if(fichier.open(QIODevice::ReadOnly))
{
QTextStream flux(&fichier);
ligne = flux.readLine();
}
QStringList fields;
fields = ligne.split(" | ");
fichier.close();
fileToOpen = fields[1]; //RECUPERE LE NOM DU FICHIER A OUVRIR
if(fileToOpen == "1A.txt")
{
QString root_folder_42 = *m_loc_123_compare;
QString annee_42 = "/1A.txt";
QString filename_2042 = root_folder_42 + annee_42;
fileToOpen = filename_2042;
}
if(fileToOpen == "2A.txt")
{
QString root_folder_42 = *m_loc_123_compare;
QString annee_42 = "/2A.txt";
QString filename_2042 = root_folder_42 + annee_42;
fileToOpen = filename_2042;
}
if(fileToOpen == "3A.txt")
{
QString root_folder_42 = *m_loc_123_compare;
QString annee_42 = "/3A.txt";
QString filename_2042 = root_folder_42 + annee_42;
fileToOpen = filename_2042;
}
QFile file(fileToOpen);
QString line;
QString all_file;
QStringList field_ligne;
QStringList sous_field_ligne;
QStringList field_test_matiere;
QStringList sous_field_test_matiere;
QVector <QString> vect(0);
bool ligne_deja_entree;
int nb_line = 0;
double coeff_P = 0;
double coeff_CC = 0;
double coeff_CR = 0;
double coeff_I = 0;
double moyenne_calc = 0;
double moyenne_promo = 0;
double diviseur = 0;
double moyenne_tab = 0;
double moyenne_tab_promo = 0;
int indice_ligne_tab = 0;
if(file.open(QIODevice:: ReadOnly))
{
QTextStream stream(&file);
while(!stream.atEnd())
{
line = stream.readLine();
nb_line = nb_line + 1;
}
} // NOMBRE DE LIGNE DU DOC
file.close();
QFile file1(fileToOpen);
if(file1.open(QIODevice::ReadOnly))
{
QTextStream stream1(&file1);
all_file = stream1.readAll();
field_ligne = all_file.split("\r\n");
for(int i=0 ; i< nb_line ; i++)
{
moyenne_calc = 0;
moyenne_promo = 0;
diviseur = 0;
ligne_deja_entree = false;
sous_field_ligne = field_ligne[i].split(" | ");
for(int w = 0 ; w<vect.size() ; w++)
{
if(sous_field_ligne[2] == vect[w])
{
ligne_deja_entree = true;
}
}
if(ligne_deja_entree == false)
{
if(sous_field_ligne[0] == "Pole Ingenierie des Transports")
{
if(sous_field_ligne[1] == "Semestre 1")
{
field_test_matiere = all_file.split("\r\n");
vect.push_back(sous_field_ligne[2]);
for(int k=i ; k < nb_line ; k++)
{
sous_field_test_matiere = field_test_matiere[k].split(" | ");
if(sous_field_test_matiere[0] == "Pole Ingenierie des Transports")
{
if(sous_field_test_matiere[1] == "Semestre 1")
{
if(sous_field_test_matiere[2] == sous_field_ligne[2])
{
QString root_folder = *m_loc_annee_compare;
QString annee = "/Annee.txt";
QString nomFichier = root_folder + annee;
QFile fichier_coeff(nomFichier);
QStringList field_coeff;
QString ligne_coeff;
if(fichier_coeff.open(QIODevice::ReadOnly))
{
QTextStream stream_coeff(&fichier_coeff);
ligne_coeff = stream_coeff.readLine();
field_coeff = ligne_coeff.split(" | ");
while(field_coeff[0] != sous_field_ligne[2])
{
ligne_coeff = stream_coeff.readLine();
field_coeff = ligne_coeff.split(" | ");
}
coeff_P = field_coeff[1].toDouble();
coeff_CC = field_coeff[2].toDouble();
coeff_I = field_coeff[3].toDouble();
coeff_CR = field_coeff[4].toDouble();
}
fichier_coeff.close();
if(sous_field_test_matiere[3] == "Partiel")
{
moyenne_calc = moyenne_calc + (coeff_P * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_P * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_P;
}
else if(sous_field_test_matiere[3] == "Controle Continu")
{
moyenne_calc = moyenne_calc + (coeff_CC * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_CC * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_CC;
}
else if(sous_field_test_matiere[3] == "Interogation")
{
moyenne_calc = moyenne_calc + (coeff_I * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_I * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_I;
}
else if(sous_field_test_matiere[3] == "Controle Experimental")
{
moyenne_calc = moyenne_calc + (coeff_CR * sous_field_test_matiere[4].toDouble());
moyenne_promo = moyenne_promo + (coeff_CR * sous_field_test_matiere[5].toDouble());
diviseur = diviseur + coeff_CR;
}
}
}
}
}
if(ligne_deja_entree == false)
{
m_tableau_ingenieur->setRowCount(m_tableau_ingenieur->rowCount()+1);
moyenne_tab = moyenne_calc / diviseur;
moyenne_tab_promo = moyenne_promo / diviseur;
QTableWidgetItem *item0 = new QTableWidgetItem(sous_field_ligne[1]);
m_tableau_ingenieur->setItem(indice_ligne_tab,0,item0);
QTableWidgetItem *item1 = new QTableWidgetItem(sous_field_ligne[2]);
m_tableau_ingenieur->setItem(indice_ligne_tab,1,item1);
QTableWidgetItem *item = new QTableWidgetItem(QString::number(moyenne_tab));
m_tableau_ingenieur->setItem(indice_ligne_tab,2,item);
m_tableau_ingenieur->item(indice_ligne_tab,2)->setBackgroundColor(QColor(255,155,155));
m_tableau_ingenieur->item(indice_ligne_tab,2)->setTextColor(QColor(255,255,255));
QFont bold;
bold.setBold(true);
m_tableau_ingenieur->item(indice_ligne_tab,2)->setFont(bold);
QTableWidgetItem *item2 = new QTableWidgetItem(QString::number(moyenne_tab_promo));
m_tableau_ingenieur->setItem(indice_ligne_tab,3,item2);
indice_ligne_tab = indice_ligne_tab + 1;
}
}
}
}
}
}
}
void fen_moyenne :: imprimer_tableau_I()
{
QString titre;
QPrinter printer(QPrinter::HighResolution);
printer.setPaperSize (QPrinter::A4);
// printer.setOutputFormat (QPrinter::PdfFormat);
printer.setOrientation(QPrinter::Landscape);
printer.setFullPage(true);
QPrintDialog printDialog(&printer, this);
if ( printDialog.exec() == 1)
{
QTextBrowser * editor = new QTextBrowser;
//creation de formats d'écriture
QTextCharFormat NormalFormat;
QTextCharFormat ItalicFormat;
ItalicFormat.setFontItalic(true);
//On insere la date et l'heure actuelle au début de la premiere page
//QDate date;
//QTime time;
//date = date.currentDate();
//time = time.currentTime();
//QString modif ="\nFait le :\t" + date.toString("dddd dd MMMM yyyy") + " a " + time.toString();
//changement du format d'ecriture
editor->setCurrentCharFormat(ItalicFormat);
editor->setAlignment(Qt::AlignLeft);
//ajout de notre QString a l'endroit du curseur
//editor->append(modif);
editor->setCurrentCharFormat(NormalFormat);
//on insere le titre du tableau
/* QTextCharFormat format_gros_titre;
format_gros_titre.setFontPointSize(16);
format_gros_titre.setFontWeight(QFont::Bold);
format_gros_titre.setVerticalAlignment(QTextCharFormat::AlignMiddle);
format_gros_titre.setUnderlineStyle(QTextCharFormat::SingleUnderline);*/
//QString title ="\n"+QString::fromUtf8(titre.toStdString().c_str())+"\n";
// editor->setCurrentCharFormat(format_gros_titre);
//editor->setAlignment(Qt::AlignCenter);
//editor->append(title);
editor->setCurrentCharFormat(NormalFormat);
//on crée un curseur a l'endroit du curseur actuel
QTextCursor cursor = editor->textCursor();
cursor.beginEditBlock();
//Creation du format du tableau qui sera imprimer
QTextTableFormat tableFormat;
tableFormat.setAlignment(Qt::AlignHCenter);
tableFormat.setAlignment(Qt::AlignLeft);
tableFormat.setBackground(QColor("#ffffff"));
tableFormat.setCellPadding(5);
tableFormat.setCellSpacing(5);
//Creation du tableau qui sera imprimé avec le nombre de colonne
//et de ligne que contient le tableau mis en parametre
QTextTable * tableau = cursor.insertTable(m_tableau_ingenieur->rowCount()+1, m_tableau_ingenieur->columnCount(), tableFormat);
QTextFrame *frame = cursor.currentFrame();
QTextFrameFormat frameFormat = frame->frameFormat();
frameFormat.setBorder(0);
frame->setFrameFormat(frameFormat);
//Format des HEADER du tableau
QTextCharFormat format_entete_tableau;
format_entete_tableau.setFontPointSize(10);
format_entete_tableau.setFontWeight(QFont::Bold);
//Format du texte des cellules du tableau
QTextCharFormat format_cellule;
format_cellule.setFontPointSize(8);
//on ecrit les HEADERS du tableaux dans le tableau a imprimer
for ( int i = 0 ; i < m_tableau_ingenieur->columnCount() ; i++ )
{
//on selectionne la premiere cellule de chaque colonne
QTextTableCell titre = tableau->cellAt(0,i);
//on place le curseur a cet endroit
QTextCursor cellCursor = titre.firstCursorPosition();
//on écrit dans la cellule
cellCursor.insertText(m_tableau_ingenieur->horizontalHeaderItem(i)->text(),format_entete_tableau);
}
QTextTableCell cell;
QTextCursor cellCursor;
for (int row = 1; row < tableau->rows(); row ++)
for (int col = 0; col < tableau->columns(); col ++)
{
cell = tableau->cellAt(row,col);
cellCursor = cell.firstCursorPosition();
cellCursor.insertText(tr("%1").arg(m_tableau_ingenieur->item(row-1,col)->text()),format_cellule);
}
//fin de l'edition
cursor.endEditBlock();
//impression de notre editor dans le QPrinter initialisé au début de la fonction
editor->print(&printer);
}
}
| 49.330573 | 167 | 0.455519 | yves-marieRaiffaud |
5720fe1e7b3688263e80046d4e8c685c5d3b2c10 | 2,096 | cpp | C++ | td08/test/signtest.cpp | asassoye/ESI-DEV3-TD | 074c7ec4c81bcf3a927079202050d5d05e4e29ca | [
"MIT"
] | 4 | 2020-12-31T14:57:20.000Z | 2020-12-31T15:15:49.000Z | td08/test/signtest.cpp | asassoye/ESI-DEV3-TD | 074c7ec4c81bcf3a927079202050d5d05e4e29ca | [
"MIT"
] | null | null | null | td08/test/signtest.cpp | asassoye/ESI-DEV3-TD | 074c7ec4c81bcf3a927079202050d5d05e4e29ca | [
"MIT"
] | 1 | 2021-01-03T13:23:14.000Z | 2021-01-03T13:23:14.000Z | #include "catch2/catch.hpp"
#include "../src/sign.hpp"
using namespace g54327;
TEST_CASE("constexpr Sign opposite(Sign sign)", "[opposite]") {
REQUIRE(opposite(Sign::PLUS) == Sign::MINUS);
REQUIRE(opposite(Sign::MINUS) == Sign::PLUS);
REQUIRE(opposite(Sign::ZERO) == Sign::ZERO);
}
TEST_CASE("constexpr Sign sign(int value)", "[sign]") {
REQUIRE(sign(-500) == Sign::MINUS);
REQUIRE(sign(42) == Sign::PLUS);
REQUIRE(sign(0) == Sign::ZERO);
REQUIRE(sign(-0) == Sign::ZERO);
}
TEST_CASE("inline std::string to_string(Sign sign)", "[to_string]") {
REQUIRE(to_string(Sign::MINUS) == "MINUS (-)");
REQUIRE(to_string(Sign::PLUS) == "PLUS (+)");
REQUIRE(to_string(Sign::ZERO) == "ZERO (0)");
}
TEST_CASE("constexpr Sign product(Sign lhs, Sign rhs)", "[product]") {
REQUIRE(product(Sign::PLUS, Sign::PLUS) == Sign::PLUS);
REQUIRE(product(Sign::PLUS, Sign::MINUS) == Sign::MINUS);
REQUIRE(product(Sign::PLUS, Sign::ZERO) == Sign::ZERO);
REQUIRE(product(Sign::MINUS, Sign::PLUS) == Sign::MINUS);
REQUIRE(product(Sign::MINUS, Sign::MINUS) == Sign::PLUS);
REQUIRE(product(Sign::MINUS, Sign::ZERO) == Sign::ZERO);
REQUIRE(product(Sign::ZERO, Sign::PLUS) == Sign::ZERO);
REQUIRE(product(Sign::ZERO, Sign::MINUS) == Sign::ZERO);
REQUIRE(product(Sign::ZERO, Sign::ZERO) == Sign::ZERO);
}
TEST_CASE("constexpr Sign operator*(Sign lhs, Sign rhs)", "[operator*]") {
REQUIRE(Sign::PLUS * Sign::PLUS == Sign::PLUS);
REQUIRE(Sign::PLUS * Sign::MINUS == Sign::MINUS);
REQUIRE(Sign::PLUS * Sign::ZERO == Sign::ZERO);
REQUIRE(Sign::MINUS * Sign::PLUS == Sign::MINUS);
REQUIRE(Sign::MINUS * Sign::MINUS == Sign::PLUS);
REQUIRE(Sign::MINUS * Sign::ZERO == Sign::ZERO);
REQUIRE(Sign::ZERO * Sign::PLUS == Sign::ZERO);
REQUIRE(Sign::ZERO * Sign::MINUS == Sign::ZERO);
REQUIRE(Sign::ZERO * Sign::ZERO == Sign::ZERO);
}
TEST_CASE("constexpr Sign operator-(Sign sign)", "[operator-]") {
REQUIRE(-Sign::PLUS == Sign::MINUS);
REQUIRE(-Sign::MINUS == Sign::PLUS);
REQUIRE(-Sign::ZERO == Sign::ZERO);
} | 39.54717 | 74 | 0.626908 | asassoye |
57232002a64be89ab425f4f5bec3d71778adcc29 | 6,529 | hpp | C++ | Library/Private/APICommon/API/Common/Iterator.hpp | KonstantinTomashevich/Emergence | 83b1d52bb62bf619f9402e3081dd9de6b0cb232c | [
"Apache-2.0"
] | 3 | 2021-06-02T05:06:48.000Z | 2022-01-26T09:39:44.000Z | Library/Private/APICommon/API/Common/Iterator.hpp | KonstantinTomashevich/Emergence | 83b1d52bb62bf619f9402e3081dd9de6b0cb232c | [
"Apache-2.0"
] | null | null | null | Library/Private/APICommon/API/Common/Iterator.hpp | KonstantinTomashevich/Emergence | 83b1d52bb62bf619f9402e3081dd9de6b0cb232c | [
"Apache-2.0"
] | null | null | null | #pragma once
/// \brief Adds common forward iterator operators, copy constructor, move constructor and destructor.
/// \details There is a lot of similar iterators in different services. Therefore it's better to hide their common
/// operations under macro to avoid unnecessary declaration and documentation duplication.
#define EMERGENCE_FORWARD_ITERATOR_OPERATIONS(IteratorClass, ItemClass) \
IteratorClass (const IteratorClass &_other) noexcept; \
\
/* NOLINTNEXTLINE(bugprone-macro-parentheses): Types can not be enclosed. */ \
IteratorClass (IteratorClass &&_other) noexcept; \
\
~IteratorClass () noexcept; \
\
/*! \
* \return Item, to which iterator points. \
* \invariant Inside valid bounds, but not in the ending. \
*/ \
[[nodiscard]] ItemClass operator* () const noexcept; /* NOLINT(bugprone-macro-parentheses) */ \
\
/*! \
* \brief Move to next item. \
* \invariant Inside valid bounds, but not in the ending. \
*/ \
IteratorClass &operator++ () noexcept; /* NOLINT(bugprone-macro-parentheses): Types can not be enclosed. */ \
\
/*! \
* \brief Move to next item. \
* \return Unchanged instance of iterator. \
* \invariant Inside valid bounds, but not in the ending. \
*/ \
IteratorClass operator++ (int) noexcept; /* NOLINT(bugprone-macro-parentheses): Types can not be enclosed. */ \
\
bool operator== (const IteratorClass &_other) const noexcept; \
\
bool operator!= (const IteratorClass &_other) const noexcept; \
\
/* NOLINTNEXTLINE(bugprone-macro-parentheses): Types can not be enclosed. */ \
IteratorClass &operator= (const IteratorClass &_other) noexcept; \
\
/* NOLINTNEXTLINE(bugprone-macro-parentheses): Types can not be enclosed. */ \
IteratorClass &operator= (IteratorClass &&_other) noexcept
/// \brief Extends EMERGENCE_FORWARD_ITERATOR_OPERATIONS with backward movement operations.
#define EMERGENCE_BIDIRECTIONAL_ITERATOR_OPERATIONS(IteratorClass, ItemClass) \
EMERGENCE_FORWARD_ITERATOR_OPERATIONS (IteratorClass, ItemClass); \
\
/*! \
* \brief Move to previous item. \
* \invariant Inside valid bounds, but not in the beginning. \
*/ \
IteratorClass &operator-- () noexcept; /* NOLINT(bugprone-macro-parentheses): Types can not be enclosed. */ \
\
/*! \
* \brief Move to previous item. \
* \return Unchanged instance of iterator. \
* \invariant Inside valid bounds, but not in the beginning. \
*/ \
IteratorClass operator-- (int) noexcept /* NOLINT(bugprone-macro-parentheses): Types can not be enclosed. */
| 110.661017 | 120 | 0.277378 | KonstantinTomashevich |
5730683fc3301f945b3e80f30a8d8af1c5d2e3bd | 319 | cpp | C++ | 2-19/ASSIGNMENTS/POINTERSETC/pointerexample3.cpp | domijin/ComPhy | 0dea6d7b09eb4880b7f2d8f55c321c827e713488 | [
"MIT"
] | null | null | null | 2-19/ASSIGNMENTS/POINTERSETC/pointerexample3.cpp | domijin/ComPhy | 0dea6d7b09eb4880b7f2d8f55c321c827e713488 | [
"MIT"
] | null | null | null | 2-19/ASSIGNMENTS/POINTERSETC/pointerexample3.cpp | domijin/ComPhy | 0dea6d7b09eb4880b7f2d8f55c321c827e713488 | [
"MIT"
] | null | null | null | /***************
POINTEREXAMPLE
This program will run since a value is established
for a that can be pointed to by p.
*********/
#include<iostream>
using namespace std;
int main()
{
int * p; //p is declared as a pointer
int a=15;
*p=a;//the value 15 is put in the memory
//location p
return 0;
}
| 16.789474 | 50 | 0.611285 | domijin |
57314defd4cb12e2f5ef3d77c7036a50f80d2467 | 2,601 | cpp | C++ | QCIFSServer/SocketServer/Main.cpp | rodrigomr/VFS | 6b68b00df8cb668106c2d0841cbcd46138298717 | [
"Apache-2.0"
] | 38 | 2018-09-24T09:37:41.000Z | 2022-02-21T04:16:43.000Z | QCIFSServer/SocketServer/Main.cpp | rodrigomr/VFS | 6b68b00df8cb668106c2d0841cbcd46138298717 | [
"Apache-2.0"
] | 1 | 2018-10-02T17:57:44.000Z | 2018-10-07T06:55:44.000Z | QCIFSServer/SocketServer/Main.cpp | rodrigomr/VFS | 6b68b00df8cb668106c2d0841cbcd46138298717 | [
"Apache-2.0"
] | 6 | 2018-10-02T17:12:38.000Z | 2021-01-27T10:01:30.000Z | // Copyright 2018 Grass Valley, A Belden Brand
// 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.
//////////////////////////////////////////////////////////////////////////////
// Main.cpp
#include "stdafx.h"
#include "cSocketServer.h"
#include "cAcceptEx.h"
#include "cConnectEx.h"
#include "..\..\KernelSDK\include\QWinBase.h"
// =======================================================================================
// === moduleInit/moduleCleanUp ==========================================================
// =======================================================================================
using namespace vfs;
iModuleContext::Ptr gModuleContext;
iActivityGroup::Ptr gActivityGroup;
void initActivitySocketServer(iActivityGroup::Ptr activityGroup);
extern "C" QPLUGIN void QARGS_STACK moduleInstall(const int Flags, iModuleContext::Ptr Incoming, iModuleContext::Ptr OptionalOutgoing, iModuleInstallHelp::Ptr Help) throw(cRecoverable)
{
// iRegistryHelp::Ptr rh = createRegistryHelp();
// rh->setItemNumber (L"SYSTEM\\CurrentControlSet\\Services\\NetBT\\Parameters\\", L"SMBDeviceEnabled", 0);
// rh->setItemNumber (L"SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\", L"TcpWindowSize", 0xfffff);
}
extern "C" QPLUGIN void QARGS_STACK moduleInit(iModuleContext::Ptr pContext) throw( cRecoverable)
{
static std::list<cGuard::ConstPtr> gRegdClasses;
gRegdClasses.push_back(gFactory->registerClass(new cSocketServerFactory::class_ctor));
gRegdClasses.push_back(gFactory->registerClass(new cAcceptEx::class_ctor));
gRegdClasses.push_back(gFactory->registerClass(new cConnectEx::class_ctor));
gActivityGroup = iActivityLog::singleton().getGroup(L"QCIFSSocketServer");
initActivitySocketServer(gActivityGroup);
}
extern "C" QPLUGIN void QARGS_STACK moduleUninstall(iModuleContext::Ptr Outgoing, iModuleInstallHelp::Ptr Help, const bool IsRemovingSettingsAndData) throw(cRecoverable, cIgnoreInstallFailed)
{
// iRegistryHelp::Ptr rh = createRegistryHelp();
// rh->deleteItem (L"SYSTEM\\CurrentControlSet\\Services\\NetBT\\Parameters\\", L"SMBDeviceEnabled");
} | 44.844828 | 191 | 0.68243 | rodrigomr |
5731e3fb93794c5688a279f7c24004968ac50bde | 1,135 | cc | C++ | sokoban_cl.cc | gress2/pseudo-feedback-mcts | d8957d505feb4a146e1b76cd6484846dac2d399e | [
"MIT"
] | null | null | null | sokoban_cl.cc | gress2/pseudo-feedback-mcts | d8957d505feb4a146e1b76cd6484846dac2d399e | [
"MIT"
] | null | null | null | sokoban_cl.cc | gress2/pseudo-feedback-mcts | d8957d505feb4a146e1b76cd6484846dac2d399e | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include "sokoban_env.hpp"
using direction = sokoban_env::direction;
int main() {
sokoban_env env("skbn_cfgs/1.cfg");
env.render();
std::string input;
while (!env.is_game_over()) {
auto possible_moves = env.get_possible_moves();
std::cout << "possible moves: " << std::endl;
for (auto dir : possible_moves) {
std::cout << sokoban_env::get_dir_str(dir) << std::endl;
}
std::cout << "enter move: " << std::endl;
std::getline(std::cin, input);
if (input == "u") {
env.step(direction::up);
} else if (input == "r") {
env.step(direction::right);
} else if (input == "d") {
env.step(direction::down);
} else if (input == "l") {
env.step(direction::left);
} else if (input == "U") {
env.step(direction::UP);
} else if (input == "R") {
env.step(direction::RIGHT);
} else if (input == "D") {
env.step(direction::DOWN);
} else if (input == "L") {
env.step(direction::LEFT);
}
env.render();
}
std::cout << "game over! reward: " << env.get_total_reward() << std::endl;
}
| 26.395349 | 76 | 0.562996 | gress2 |
573204aa068edd4a5b3c20ee6fac895ca77fecf1 | 168 | cpp | C++ | HW04/CharStack.cpp | CS-CMU/cs251 | ba8fac9ee9da293f8e7a6d193657e0d217d9dd2b | [
"MIT"
] | null | null | null | HW04/CharStack.cpp | CS-CMU/cs251 | ba8fac9ee9da293f8e7a6d193657e0d217d9dd2b | [
"MIT"
] | null | null | null | HW04/CharStack.cpp | CS-CMU/cs251 | ba8fac9ee9da293f8e7a6d193657e0d217d9dd2b | [
"MIT"
] | 5 | 2021-11-21T13:38:48.000Z | 2022-01-14T15:55:02.000Z | class CharStack {
public:
CharStack() { // constructor
}
void push(char new_item) {
}
char pop() {
}
char top() {
}
bool isEmpty() {
}
};
| 7 | 30 | 0.505952 | CS-CMU |
5733c17490f9e7a52119aa9e49f101dac1911c59 | 74 | hxx | C++ | src/interfaces/python/opengm/opengmcore/pyFunctionGen.hxx | burcin/opengm | a1b21eecb93c6c5a7b11ab312d26b1c98c55ff41 | [
"MIT"
] | 318 | 2015-01-07T15:22:02.000Z | 2022-01-22T10:10:29.000Z | src/interfaces/python/opengm/opengmcore/pyFunctionGen.hxx | burcin/opengm | a1b21eecb93c6c5a7b11ab312d26b1c98c55ff41 | [
"MIT"
] | 89 | 2015-03-24T14:33:01.000Z | 2020-07-10T13:59:13.000Z | src/interfaces/python/opengm/opengmcore/pyFunctionGen.hxx | burcin/opengm | a1b21eecb93c6c5a7b11ab312d26b1c98c55ff41 | [
"MIT"
] | 119 | 2015-01-13T08:35:03.000Z | 2022-03-01T01:49:08.000Z | template<class GM_ADDER,class GM_MULT>
void export_function_generator(); | 37 | 40 | 0.837838 | burcin |
573461e3458a11e3c9189a15472e89f2ee838bfb | 2,925 | hpp | C++ | src/include/function/scalar_function/regexp.hpp | xhochy/duckdb | 20ba65f96794ab53f7a66e22d9bc58d59d8bc623 | [
"MIT"
] | null | null | null | src/include/function/scalar_function/regexp.hpp | xhochy/duckdb | 20ba65f96794ab53f7a66e22d9bc58d59d8bc623 | [
"MIT"
] | null | null | null | src/include/function/scalar_function/regexp.hpp | xhochy/duckdb | 20ba65f96794ab53f7a66e22d9bc58d59d8bc623 | [
"MIT"
] | 1 | 2019-09-06T09:58:14.000Z | 2019-09-06T09:58:14.000Z | //===----------------------------------------------------------------------===//
// DuckDB
//
// function/scalar_function/regexp.hpp
//
//
//===----------------------------------------------------------------------===//
#pragma once
#include "common/types/data_chunk.hpp"
#include "function/function.hpp"
#include "re2/re2.h"
namespace duckdb {
void regexp_matches_function(ExpressionExecutor &exec, Vector inputs[], index_t input_count,
BoundFunctionExpression &expr, Vector &result);
bool regexp_matches_matches_arguments(vector<SQLType> &arguments);
SQLType regexp_matches_get_return_type(vector<SQLType> &arguments);
unique_ptr<FunctionData> regexp_matches_get_bind_function(BoundFunctionExpression &expr, ClientContext &context);
struct RegexpMatchesBindData : public FunctionData {
std::unique_ptr<RE2> constant_pattern;
string range_min, range_max;
bool range_success;
RegexpMatchesBindData(std::unique_ptr<RE2> constant_pattern, string range_min, string range_max, bool range_success)
: constant_pattern(std::move(constant_pattern)), range_min(range_min), range_max(range_max),
range_success(range_success) {
}
unique_ptr<FunctionData> Copy() override {
return make_unique<RegexpMatchesBindData>(std::move(constant_pattern), range_min, range_max, range_success);
}
};
class RegexpMatchesFunction {
public:
static const char *GetName() {
return "regexp_matches";
}
static scalar_function_t GetFunction() {
return regexp_matches_function;
}
static matches_argument_function_t GetMatchesArgumentFunction() {
return regexp_matches_matches_arguments;
}
static get_return_type_function_t GetReturnTypeFunction() {
return regexp_matches_get_return_type;
}
static bind_scalar_function_t GetBindFunction() {
return regexp_matches_get_bind_function;
}
static dependency_function_t GetDependencyFunction() {
return nullptr;
}
static bool HasSideEffects() {
return false;
}
};
void regexp_replace_function(ExpressionExecutor &exec, Vector inputs[], index_t input_count,
BoundFunctionExpression &expr, Vector &result);
bool regexp_replace_matches_arguments(vector<SQLType> &arguments);
SQLType regexp_replace_get_return_type(vector<SQLType> &arguments);
class RegexpReplaceFunction {
public:
static const char *GetName() {
return "regexp_replace";
}
static scalar_function_t GetFunction() {
return regexp_replace_function;
}
static matches_argument_function_t GetMatchesArgumentFunction() {
return regexp_replace_matches_arguments;
}
static get_return_type_function_t GetReturnTypeFunction() {
return regexp_replace_get_return_type;
}
static bind_scalar_function_t GetBindFunction() {
return nullptr;
}
static dependency_function_t GetDependencyFunction() {
return nullptr;
}
static bool HasSideEffects() {
return false;
}
};
} // namespace duckdb
| 27.59434 | 117 | 0.731624 | xhochy |
573506ed6a9fd0c67c00057e2ec0f7e78d5d867f | 1,167 | cpp | C++ | notepanda.cpp | fossabot/notepanda | 94fc3d7c9752c7332e9364438b79deaa37360670 | [
"MIT"
] | null | null | null | notepanda.cpp | fossabot/notepanda | 94fc3d7c9752c7332e9364438b79deaa37360670 | [
"MIT"
] | null | null | null | notepanda.cpp | fossabot/notepanda | 94fc3d7c9752c7332e9364438b79deaa37360670 | [
"MIT"
] | null | null | null |
#include <QTextStream>
#include <QMessageBox>
#include "texteditor.h"
#include "notepanda.h"
#include "ui_notepanda.h"
notepanda::notepanda(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::notepanda)
{
ui->setupUi(this);
ui->setupUi(this);
plainTextEdit = new TextEditor;
this->setCentralWidget(plainTextEdit);
connect(ui->actionNew, &QAction::triggered, plainTextEdit, &TextEditor::newDocument);
connect(ui->actionOpen, &QAction::triggered, plainTextEdit, &TextEditor::open);
connect(ui->actionSave, &QAction::triggered, plainTextEdit, &TextEditor::save);
connect(ui->actionSave_As, &QAction::triggered, plainTextEdit, &TextEditor::saveAs);
connect(ui->actionAbout, &QAction::triggered, this, ¬epanda::about);
}
notepanda::~notepanda()
{
delete ui;
delete plainTextEdit;
}
void notepanda::about()
{
QMessageBox::about(this, tr("About Notepanda"),
tr("<center><b>Notepanda</b></center> <br> <center>A simple cross-platform notepad. Based on Qt and C++.</center><br>"
"<b>Vesrion:</b> 0.0.1-alpha<br>"
"Copyright © 2020 ChungZH & Shawfing."));
}
| 29.923077 | 134 | 0.66838 | fossabot |
5735a90abaeb2959d785a788c70ebaaad4141a0a | 4,506 | cpp | C++ | test/heuristic_search/loggers/test_Logger.cpp | Forrest-Z/heuristic_search | 8a1d2035483e7167baf362dc3de52320845f1109 | [
"MIT"
] | null | null | null | test/heuristic_search/loggers/test_Logger.cpp | Forrest-Z/heuristic_search | 8a1d2035483e7167baf362dc3de52320845f1109 | [
"MIT"
] | null | null | null | test/heuristic_search/loggers/test_Logger.cpp | Forrest-Z/heuristic_search | 8a1d2035483e7167baf362dc3de52320845f1109 | [
"MIT"
] | 1 | 2020-04-18T09:58:49.000Z | 2020-04-18T09:58:49.000Z | /* heuristic_search library
*
* Copyright (c) 2016,
* Maciej Przybylski <maciej.przybylski@mchtr.pw.edu.pl>,
* Warsaw University of Technology.
* All rights reserved.
*
*/
#include <gtest/gtest.h>
#include "heuristic_search/HeuristicSearch.h"
#include "heuristic_search/loggers/DStarLogger.h"
#include "heuristic_search/SearchLoop.h"
#include "heuristic_search/StdOpenList.h"
#include "heuristic_search/StdSearchSpace.h"
#include "heuristic_search/SearchingAlgorithm.h"
#include "heuristic_search/AStar.h"
#include "heuristic_search/DStarMain.h"
#include "heuristic_search/DStarExtraLite.h"
#include "heuristic_search/IncrementalSearch.h"
#include "../../heuristic_search/test_TestDomain.h"
namespace test_heuristic_search{
TEST(test_Logger, astar)
{
TestDomain domain;
typedef heuristic_search::SearchAlgorithmBegin<
heuristic_search::loggers::Logger<
heuristic_search::SearchLoop<
heuristic_search::AStar<
heuristic_search::HeuristicSearch<
heuristic_search::StdOpenList<
heuristic_search::StdSearchSpace<
heuristic_search::SearchAlgorithmEnd<TestDomain> > > > > > > > AStarLoggerTestAlgorithm_t;
AStarLoggerTestAlgorithm_t::Algorithm_t algorithm(domain);
ASSERT_TRUE(algorithm.search({0},{5}));
EXPECT_TRUE(algorithm.log.success);
EXPECT_GT(algorithm.log.search_steps, 0);
EXPECT_GT(algorithm.log.heap_counter, 0);
EXPECT_GT(algorithm.log.heap_counter, 0);
EXPECT_EQ(5*TestDomain::costFactor(), algorithm.log.path_cost*TestDomain::costFactor());
}
TEST(test_Logger, dstar)
{
TestDomain domain;
typedef heuristic_search::SearchAlgorithmBegin<
heuristic_search::loggers::DStarLogger<
heuristic_search::DStarMain<
heuristic_search::SearchLoop<
heuristic_search::DStarExtraLite<
heuristic_search::IncrementalSearch_SearchStep<
heuristic_search::AStar<
heuristic_search::IncrementalSearch_Initialize<
heuristic_search::HeuristicSearch<
heuristic_search::StdOpenList<
heuristic_search::StdSearchSpace<
heuristic_search::SearchAlgorithmEnd<TestDomain> > > > > > > > > > > > DStarLoggerTestAlgorithm_t;
DStarLoggerTestAlgorithm_t::Algorithm_t algorithm(domain,
heuristic_search::SearchingDirection::Backward, true);
ASSERT_TRUE(algorithm.search({0},{5}));
EXPECT_GT(algorithm.log.search_steps, 0);
EXPECT_GT(algorithm.log.heap_counter, 0);
heuristic_search::loggers::Log prev_log = algorithm.log;
std::vector<std::pair<TestDomain::StateActionState, TestDomain::Cost> > updated_actions;
updated_actions.push_back(
std::make_pair(TestDomain::StateActionState(
{2},{10*TestDomain::costFactor()},{3}),1*TestDomain::costFactor()));
domain.updateAction(TestDomain::StateActionState(
{2},{10*TestDomain::costFactor()},{3}));
algorithm.reinitialize({1}, updated_actions);
ASSERT_TRUE(algorithm.search());
EXPECT_GT(algorithm.log.search_steps, prev_log.search_steps);
EXPECT_GT(algorithm.log.heap_counter, prev_log.heap_counter);
}
TEST(test_Logger, dstar_2)
{
TestDomain domain;
typedef heuristic_search::SearchAlgorithmBegin<
heuristic_search::loggers::DStarLogger<
heuristic_search::DStarMain<
heuristic_search::SearchLoop<
heuristic_search::DStarExtraLite<
heuristic_search::IncrementalSearch_SearchStep<
heuristic_search::AStar<
heuristic_search::IncrementalSearch_Initialize<
heuristic_search::HeuristicSearch<
heuristic_search::StdOpenList<
heuristic_search::StdSearchSpace<
heuristic_search::SearchAlgorithmEnd<TestDomain> > > > > > > > > > > > DStarLoggerTestAlgorithm_t;
DStarLoggerTestAlgorithm_t::Algorithm_t algorithm(domain,
heuristic_search::SearchingDirection::Backward);
algorithm.main({0},{5});
EXPECT_TRUE(algorithm.log.success);
EXPECT_GT(algorithm.log.search_steps, 0);
EXPECT_GT(algorithm.log.heap_counter, 0);
EXPECT_EQ(5*TestDomain::costFactor(), algorithm.log.path_cost*TestDomain::costFactor());
}
}
| 34.396947 | 106 | 0.67399 | Forrest-Z |
5739364524c27ac65a6aac10f2d73b0d436d96bc | 3,457 | cpp | C++ | external/iotivity/iotivity_1.2-rel/service/simulator/java/jni/simulator_exceptions_jni.cpp | SenthilKumarGS/TizenRT | 691639aa9667de5d966f040f0291a402727ab6ae | [
"Apache-2.0"
] | 511 | 2017-03-29T09:14:09.000Z | 2022-03-30T23:10:29.000Z | external/iotivity/iotivity_1.2-rel/service/simulator/java/jni/simulator_exceptions_jni.cpp | SenthilKumarGS/TizenRT | 691639aa9667de5d966f040f0291a402727ab6ae | [
"Apache-2.0"
] | 4,673 | 2017-03-29T10:43:43.000Z | 2022-03-31T08:33:44.000Z | external/iotivity/iotivity_1.2-rel/service/simulator/java/jni/simulator_exceptions_jni.cpp | SenthilKumarGS/TizenRT | 691639aa9667de5d966f040f0291a402727ab6ae | [
"Apache-2.0"
] | 642 | 2017-03-30T20:45:33.000Z | 2022-03-24T17:07:33.000Z | /******************************************************************
*
* Copyright 2015 Samsung Electronics All Rights Reserved.
*
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************/
#include "simulator_exceptions_jni.h"
#include "simulator_utils_jni.h"
extern SimulatorClassRefs gSimulatorClassRefs;
void ThrowSimulatorException(JNIEnv *env, SimulatorResult code, const char *message)
{
static jmethodID simulatorExceptionCtor = env->GetMethodID(
gSimulatorClassRefs.simulatorExceptionCls, "<init>", "(ILjava/lang/String;)V");
jobject exceptionObject = env->NewObject(gSimulatorClassRefs.simulatorExceptionCls,
simulatorExceptionCtor, code, env->NewStringUTF(message));
if (exceptionObject)
{
env->Throw((jthrowable) exceptionObject);
}
}
void ThrowInvalidArgsException(JNIEnv *env, SimulatorResult code, const char *message)
{
static jmethodID invalidArgsExceptionCtor = env->GetMethodID(
gSimulatorClassRefs.invalidArgsExceptionCls, "<init>", "(ILjava/lang/String;)V");
jobject exceptionObject = env->NewObject(gSimulatorClassRefs.invalidArgsExceptionCls,
invalidArgsExceptionCtor, code, env->NewStringUTF(message));
if (exceptionObject)
{
env->Throw((jthrowable) exceptionObject);
}
}
void ThrowNoSupportException(JNIEnv *env, const char *message)
{
static jmethodID noSupportExceptionCtor = env->GetMethodID(
gSimulatorClassRefs.noSupportExceptionCls, "<init>", "(Ljava/lang/String;)V");
jobject exceptionObject = env->NewObject(gSimulatorClassRefs.noSupportExceptionCls,
noSupportExceptionCtor, env->NewStringUTF(message));
if (exceptionObject)
{
env->Throw((jthrowable) exceptionObject);
}
}
void ThrowOperationInProgressException(JNIEnv *env, const char *message)
{
static jmethodID operationInProgressExceptionCtor = env->GetMethodID(
gSimulatorClassRefs.operationInProgressExceptionCls, "<init>", "(Ljava/lang/String;)V");
jobject exceptionObject = env->NewObject(gSimulatorClassRefs.operationInProgressExceptionCls,
operationInProgressExceptionCtor, env->NewStringUTF(message));
if (exceptionObject)
{
env->Throw((jthrowable) exceptionObject);
}
}
void ThrowBadObjectException(JNIEnv *env, const char *message)
{
static jmethodID simulatorExceptionCtor = env->GetMethodID(
gSimulatorClassRefs.simulatorExceptionCls, "<init>", "(ILjava/lang/String;)V");
jobject exceptionObject = env->NewObject(gSimulatorClassRefs.simulatorExceptionCls,
simulatorExceptionCtor, SIMULATOR_BAD_OBJECT, env->NewStringUTF(message));
if (exceptionObject)
{
env->Throw((jthrowable) exceptionObject);
}
} | 38.842697 | 104 | 0.67978 | SenthilKumarGS |
573c31201bcf0f08edda0898921ef20855dee8c6 | 3,151 | cpp | C++ | packages/optionPricer2/src/AsianOption.cpp | pawelsakowski/AF-RCPP-2020-2021 | c44eea09235e03097c18f13381de9b5b93806138 | [
"Apache-2.0"
] | 6 | 2020-11-03T10:56:58.000Z | 2021-03-26T14:49:42.000Z | packages/optionPricer2/src/AsianOption.cpp | pawelsakowski/AF-RCPP-2021-2022 | 60f9aa4300fa2cc14c35213ea39b81b3656ae900 | [
"Apache-2.0"
] | null | null | null | packages/optionPricer2/src/AsianOption.cpp | pawelsakowski/AF-RCPP-2021-2022 | 60f9aa4300fa2cc14c35213ea39b81b3656ae900 | [
"Apache-2.0"
] | 3 | 2021-12-01T21:09:06.000Z | 2022-01-30T14:36:17.000Z | #include<iostream>
#include<cmath>
#include"getOneGaussianByBoxMueller.h"
#include"AsianOption.h"
//definition of constructor
AsianOption::AsianOption(
int nInt_,
double strike_,
double spot_,
double vol_,
double r_,
double expiry_){
nInt = nInt_;
strike = strike_;
spot = spot_;
vol = vol_;
r = r_;
expiry = expiry_;
generatePath();
}
//method definition
void AsianOption::generatePath(){
double thisDrift = (r * expiry - 0.5 * vol * vol * expiry) / double(nInt);
double cumShocks = 0;
thisPath.clear();
for(int i = 0; i < nInt; i++){
cumShocks += (thisDrift + vol * sqrt(expiry / double(nInt)) * getOneGaussianByBoxMueller());
thisPath.push_back(spot * exp(cumShocks));
}
}
//method definition
double AsianOption::getArithmeticMean(){
double runningSum = 0.0;
for(int i = 0; i < nInt; i++){
runningSum += thisPath[i];
}
return runningSum/double(nInt);
}
//method definition
double AsianOption::getGeometricMean(){
double runningSum = 0.0;
for(int i = 0; i < nInt ; i++){
runningSum += log(thisPath[i]);
}
return exp(runningSum/double(nInt));
}
//method definition
void AsianOption::printPath(){
for(int i = 0; i < nInt; i++){
std::cout << thisPath[i] << "\n";
}
}
//method definition
double AsianOption::getArithmeticAsianCallPrice(int nReps){
double rollingSum = 0.0;
double thisMean = 0.0;
for(int i = 0; i < nReps; i++){
generatePath();
thisMean=getArithmeticMean();
rollingSum += (thisMean > strike) ? (thisMean-strike) : 0;
}
return exp(-r*expiry)*rollingSum/double(nReps);
}
//method definition
double AsianOption::getArithmeticAsianPutPrice(int nReps){
double rollingSum = 0.0;
double thisMean = 0.0;
for(int i = 0; i < nReps; i++){
generatePath();
thisMean=getArithmeticMean();
rollingSum += (thisMean < strike) ? (strike - thisMean) : 0;
}
return exp(-r*expiry)*rollingSum/double(nReps);
}
//method definition
double AsianOption::getGeometricAsianCallPrice(int nReps){
double rollingSum = 0.0;
double thisMean = 0.0;
for(int i = 0; i < nReps; i++){
generatePath();
thisMean=getGeometricMean();
rollingSum += (thisMean > strike)? (thisMean-strike) : 0;
}
return exp(-r*expiry)*rollingSum/double(nReps);
}
//method definition
double AsianOption::getGeometricAsianPutPrice(int nReps){
double rollingSum = 0.0;
double thisMean = 0.0;
for(int i = 0; i < nReps; i++){
generatePath();
thisMean=getGeometricMean();
rollingSum += (thisMean < strike)? (strike - thisMean) : 0;
}
return exp(-r*expiry)*rollingSum/double(nReps);
}
//overloaded operator ();
double AsianOption::operator()(char char1, char char2, int nReps){
if ((char1 == 'A') & (char2 =='C')) return getArithmeticAsianCallPrice(nReps);
else if ((char1 == 'A') & (char2 =='P')) return getArithmeticAsianPutPrice(nReps);
else if ((char1 == 'G') & (char2 =='C')) return getGeometricAsianCallPrice(nReps);
else if ((char1 == 'G') & (char2 =='P')) return getGeometricAsianPutPrice(nReps);
else return -99;
}
| 21.881944 | 95 | 0.643288 | pawelsakowski |
573e0dc8439460f35f3cf8b8afbfbc17b940eb22 | 738 | hpp | C++ | src/MulConstraint.hpp | nandofioretto/cpuBE | 641e42ae4f1f7d9b82f323256fec86d7aa8f8ac1 | [
"MIT"
] | null | null | null | src/MulConstraint.hpp | nandofioretto/cpuBE | 641e42ae4f1f7d9b82f323256fec86d7aa8f8ac1 | [
"MIT"
] | null | null | null | src/MulConstraint.hpp | nandofioretto/cpuBE | 641e42ae4f1f7d9b82f323256fec86d7aa8f8ac1 | [
"MIT"
] | null | null | null | //
// Created by Ferdinando Fioretto on 12/3/16.
//
#ifndef CPUBE_MULCONSTRAINT_H
#define CPUBE_MULCONSTRAINT_H
template<class T1, class T2>
class MulConstraint<T1, T2> : public Constraint
{
public:
typedef std::shared_ptr <MulConstraint> ptr;
// I think they want a special mult constraint cTimesX()
// MulConstraint
// (std::vector<Variable::ptr>& _scope, T1 ,
// BooleanExpression _expr, util_t _defUtil)
// : weights(_weights), expr(_expr), defaultUtil(_defUtil), LB(Constants::inf), UB(Constants::inf)
// {
// Constraint::scope = _scope;
// for(auto& v : Constraint::scope) {
// scopeAgtID.push_back(v->getAgtID());
// }
// }
};
#endif //CPUBE_MULCONSTRAINT_H
| 23.806452 | 101 | 0.649051 | nandofioretto |
574258fef1aa820127ac6b1332aba664d13a6abe | 2,160 | cpp | C++ | Project/Dev_class11_handout/Motor2D/Move.cpp | Guille1406/Project-II | af954426efce06937671f02ac0a5840e5faefb0e | [
"Apache-2.0"
] | null | null | null | Project/Dev_class11_handout/Motor2D/Move.cpp | Guille1406/Project-II | af954426efce06937671f02ac0a5840e5faefb0e | [
"Apache-2.0"
] | null | null | null | Project/Dev_class11_handout/Motor2D/Move.cpp | Guille1406/Project-II | af954426efce06937671f02ac0a5840e5faefb0e | [
"Apache-2.0"
] | null | null | null | #include "j1Player.h"
#include "j1App.h"
#include "j1Window.h"
#include "j1Render.h"
#include "p2Log.h"
#include "Character.h"
void Character::Attack(float dt)
{
}
void Character::Move(float dt)
{
uint x = 0, y = 0;
App->win->GetWindowSize(x, y);
// SHORT VARIABLES
int pos_x = this->pos.x;
int pos_y = this->pos.y;
int tile_pos_x = this->tilepos.x;
int tile_pos_y = this->tilepos.y;
////Camera
//DIAGONAL TILES
uint diagonal_right_up = App->map->V_Colision[GetLogicHeightPlayer()]->Get(this->tilepos.x + 2, tile_pos_y -1);
uint diagonal_left_up = App->map->V_Colision[GetLogicHeightPlayer()]->Get(this->tilepos.x -1, tile_pos_y - 1);
uint diagonal_right_down = App->map->V_Colision[GetLogicHeightPlayer()]->Get(this->tilepos.x +2, tile_pos_y +2);
uint diagonal_left_down = App->map->V_Colision[GetLogicHeightPlayer()]->Get(this->tilepos.x -1, tile_pos_y +2);
/////
float speed = 4/dt;
switch (movement_direction) {
case move_up:
this->can_walk = MoveFunction(dt, pos.y, pos.x, false, adjacent.up, adjacent.left.i, adjacent.right.i);
break;
case move_down:
this->can_walk = MoveFunction(dt, pos.y, pos.x, true, adjacent.down, adjacent.left.j, adjacent.right.j, true);
break;
case move_left:
this->can_walk = MoveFunction(dt, pos.x, pos.y, false, adjacent.left, adjacent.up.i, adjacent.down.i);
break;
case move_right:
this->can_walk = MoveFunction(dt, pos.x, pos.y, true, adjacent.right, adjacent.up.j, adjacent.down.j, true);
break;
case move_up_left:
this->can_walk = MoveDiagonalFunction(dt, pos.y, pos.x, false, false, adjacent.up.i, adjacent.left.i, diagonal_left_up);
break;
case move_up_right:
this->can_walk = MoveDiagonalFunction(dt, pos.y, pos.x, false, true, adjacent.up.j, adjacent.right.i, diagonal_right_up);
break;
case move_down_left:
this->can_walk = MoveDiagonalFunction(dt, pos.y, pos.x, true, false, adjacent.down.i, adjacent.left.j, diagonal_left_down, true);
break;
case move_down_right:
this->can_walk = MoveDiagonalFunction(dt, pos.y, pos.x, true, true, adjacent.down.j, adjacent.right.j, diagonal_right_down, true);
break;
}
}
| 25.714286 | 132 | 0.701852 | Guille1406 |
5743177efa2bb969debdfbc08b5991997cdb5139 | 5,900 | cpp | C++ | src/casinocoin/protocol/impl/STPerformanceReport.cpp | rrozek/casinocoind | 8c95755b0a669fcd614b3fc9a39fe792b336db41 | [
"BSL-1.0"
] | null | null | null | src/casinocoin/protocol/impl/STPerformanceReport.cpp | rrozek/casinocoind | 8c95755b0a669fcd614b3fc9a39fe792b336db41 | [
"BSL-1.0"
] | null | null | null | src/casinocoin/protocol/impl/STPerformanceReport.cpp | rrozek/casinocoind | 8c95755b0a669fcd614b3fc9a39fe792b336db41 | [
"BSL-1.0"
] | 3 | 2018-07-12T11:34:45.000Z | 2021-09-13T18:08:25.000Z | //------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/casinocoin/casinocoind
Copyright (c) 2018 CasinoCoin Foundation
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
//==============================================================================
/*
2018-07-19 jrojek Created
*/
//==============================================================================
#include <BeastConfig.h>
#include <casinocoin/protocol/STPerformanceReport.h>
#include <casinocoin/protocol/HashPrefix.h>
#include <casinocoin/basics/contract.h>
#include <casinocoin/basics/Log.h>
#include <casinocoin/json/to_string.h>
#include <casinocoin/basics/StringUtilities.h>
namespace casinocoin {
STPerformanceReport::STPerformanceReport (SerialIter& sit, bool checkSignature)
: STObject (getFormat (), sit, sfPerformanceReport)
{
if (checkSignature && !isValid ())
{
JLOG (debugLog().error())
<< "Invalid performance report" << getJson (0);
Throw<std::runtime_error> ("Invalid performance report");
}
}
STPerformanceReport::STPerformanceReport (
NetClock::time_point signTime,
PublicKey const& publicKey,
Blob const& domain,
Blob const& signature
)
: STObject (getFormat (), sfPerformanceReport)
, mSeen (signTime)
{
// Does not sign
setFieldU32 (sfSigningTime, signTime.time_since_epoch().count());
setFieldVL (sfCRN_PublicKey, publicKey.slice());
setFieldVL (sfSignature, signature);
setFieldVL (sfCRN_DomainName, domain);
setFieldU8 (sfCRNActivated, 0);
}
NetClock::time_point
STPerformanceReport::getSignTime () const
{
return NetClock::time_point{NetClock::duration{getFieldU32(sfSigningTime)}};
}
NetClock::time_point STPerformanceReport::getSeenTime () const
{
return mSeen;
}
std::uint32_t STPerformanceReport::getFlags () const
{
return getFieldU32 (sfFlags);
}
bool STPerformanceReport::isValid () const
{
try
{
return casinocoin::verify(getSignerPublic(),
makeSlice(getFieldVL(sfCRN_DomainName)),
makeSlice(getFieldVL(sfSignature)));
}
catch (std::exception const&)
{
JLOG (debugLog().error())
<< "Exception validating performance report";
return false;
}
}
PublicKey STPerformanceReport::getSignerPublic () const
{
return PublicKey(makeSlice (getFieldVL (sfCRN_PublicKey)));
}
PublicKey STPerformanceReport::getNodePublic () const
{
if (isFieldPresent(sfPublicKey))
return PublicKey(makeSlice (getFieldVL (sfPublicKey)));
return PublicKey();
}
uint32_t STPerformanceReport::getLastLedgerIndex() const
{
return getFieldU32 (sfLastLedgerSequence);
}
uint256 STPerformanceReport::getSigningHash () const
{
return STObject::getSigningHash (HashPrefix::performanceReport);
}
std::string STPerformanceReport::getDomainName () const
{
Blob hexedDomain = getFieldVL(sfCRN_DomainName);
std::string hexDomainStr(hexedDomain.begin(), hexedDomain.end());
Blob unhexedDomain = strUnHex(hexDomainStr).first;
return std::string(unhexedDomain.begin(), unhexedDomain.end());
}
Blob STPerformanceReport::getSignature () const
{
return getFieldVL (sfSignature);
}
bool STPerformanceReport::getActivated () const
{
return ((getFieldU8(sfCRNActivated) > 0) ? true : false);
}
uint16_t STPerformanceReport::getWSPort() const
{
if (isFieldPresent(sfPort))
return getFieldU16(sfPort);
return 0;
}
Blob STPerformanceReport::getSerialized () const
{
Serializer s;
add (s);
return s.peekData ();
}
std::uint32_t STPerformanceReport::getLatency() const
{
return getFieldU32 (sfCRN_LatencyAvg);
}
SOTemplate const& STPerformanceReport::getFormat ()
{
struct FormatHolder
{
SOTemplate format;
FormatHolder ()
{
format.push_back (SOElement (sfFlags, SOE_REQUIRED));
format.push_back (SOElement (sfCRN_PublicKey, SOE_REQUIRED));
format.push_back (SOElement (sfSignature, SOE_REQUIRED));
format.push_back (SOElement (sfCRN_DomainName, SOE_REQUIRED));
format.push_back (SOElement (sfSigningTime, SOE_REQUIRED));
format.push_back (SOElement (sfCRN_LatencyAvg, SOE_OPTIONAL));
format.push_back (SOElement (sfFirstLedgerSequence, SOE_OPTIONAL));
format.push_back (SOElement (sfLastLedgerSequence, SOE_OPTIONAL));
format.push_back (SOElement (sfStatusMode, SOE_OPTIONAL));
format.push_back (SOElement (sfCRNPerformance, SOE_OPTIONAL));
format.push_back (SOElement (sfCRNActivated, SOE_OPTIONAL));
format.push_back (SOElement (sfPublicKey, SOE_OPTIONAL));
format.push_back (SOElement (sfPort, SOE_OPTIONAL));
}
};
static FormatHolder holder;
return holder.format;
}
} // casinocoin
| 31.72043 | 83 | 0.645593 | rrozek |
57453b009928209f0872850ca3b4b86edb06f669 | 112,541 | cpp | C++ | Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_Engine.cpp | MarkStega/CIDLib | 82014e064eef51cad998bf2c694ed9c1c8cceac6 | [
"MIT"
] | 216 | 2019-03-09T06:41:28.000Z | 2022-02-25T16:27:19.000Z | Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_Engine.cpp | MarkStega/CIDLib | 82014e064eef51cad998bf2c694ed9c1c8cceac6 | [
"MIT"
] | 9 | 2020-09-27T08:00:52.000Z | 2021-07-02T14:27:31.000Z | Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_Engine.cpp | MarkStega/CIDLib | 82014e064eef51cad998bf2c694ed9c1c8cceac6 | [
"MIT"
] | 29 | 2019-03-09T10:12:24.000Z | 2021-03-03T22:25:29.000Z | //
// FILE NAME: CIDMacroEng_Engine.cpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 01/14/2003
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2019
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This file implements TMacroEngEngine class. This class represents an
// instance of the expression engine.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $_CIDLib_Log_$
//
// ---------------------------------------------------------------------------
// Facility specific includes
// ---------------------------------------------------------------------------
#include "CIDMacroEng_.hpp"
// ---------------------------------------------------------------------------
// Magic RTTI macros
// ---------------------------------------------------------------------------
RTTIDecls(TCIDMacroEngine,TObject)
// ---------------------------------------------------------------------------
// Local types and constants
// ---------------------------------------------------------------------------
namespace
{
namespace CIDMacroEng_Engine
{
// -----------------------------------------------------------------------
// A flag to handle local lazy init
// -----------------------------------------------------------------------
TAtomicFlag atomInitDone;
// -----------------------------------------------------------------------
// Some stats cache items we maintain
// -----------------------------------------------------------------------
TStatsCacheItem sciMacroEngCount;
}
}
// ---------------------------------------------------------------------------
// CLASS: TMEngCallStackJan
// PREFIX: jan
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TMEngCallStackJan: Constructors and Destructor
// ---------------------------------------------------------------------------
TMEngCallStackJan::TMEngCallStackJan(TCIDMacroEngine* const pmeToRestore) :
m_c4OrgTop(0)
, m_pmeToRestore(pmeToRestore)
{
// Could be null so check before we store
if (m_pmeToRestore)
m_c4OrgTop = pmeToRestore->c4StackTop();
}
TMEngCallStackJan::~TMEngCallStackJan()
{
if (m_pmeToRestore)
{
try
{
m_pmeToRestore->PopBackTo(m_c4OrgTop);
}
catch(TError& errToCatch)
{
if (!errToCatch.bLogged())
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
}
}
}
// ---------------------------------------------------------------------------
// CLASS: TCIDMacroEngine
// PREFIX: eeng
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TCIDMacroEngine: Constructors and Destructor
// ---------------------------------------------------------------------------
TCIDMacroEngine::TCIDMacroEngine() :
m_bDebugMode(kCIDLib::False)
, m_bInIDE(kCIDLib::False)
, m_bValidation(kCIDLib::False)
, m_c2ArrayId(kCIDMacroEng::c2BadId)
, m_c2NextClassId(0)
, m_c2VectorId(kCIDMacroEng::c2BadId)
, m_c4CallStackTop(0)
, m_c4CurLine(0)
, m_c4NextUniqueId(1)
, m_colCallStack(tCIDLib::EAdoptOpts::Adopt, 64)
, m_colClasses
(
tCIDLib::EAdoptOpts::NoAdopt
, 29
, TStringKeyOps()
, &TMEngClassInfo::strKey
)
, m_colClassesById(tCIDLib::EAdoptOpts::Adopt, 128)
, m_colTempPool(32)
, m_eExceptReport(tCIDMacroEng::EExceptReps::NotHandled)
, m_pcuctxRights(nullptr)
, m_pmedbgToUse(nullptr)
, m_pmeehToUse(nullptr)
, m_pmefrToUse(nullptr)
, m_pmecvThrown(nullptr)
, m_pstrmConsole(nullptr)
{
// Make sure our facility has faulted in
facCIDMacroEng();
// Do local lazy init if required
if (!CIDMacroEng_Engine::atomInitDone)
{
TBaseLock lockInit;
if (!CIDMacroEng_Engine::atomInitDone)
{
TStatsCache::RegisterItem
(
kCIDMacroEng::pszStat_MEng_EngInstCount
, tCIDLib::EStatItemTypes::Counter
, CIDMacroEng_Engine::sciMacroEngCount
);
CIDMacroEng_Engine::atomInitDone.Set();
}
}
//
// Register the small number of instrinc classes that are always
// available without being asked for.
//
RegisterBuiltInClasses();
// Increment the count of registered engines
TStatsCache::c8IncCounter(CIDMacroEng_Engine::sciMacroEngCount);
}
TCIDMacroEngine::~TCIDMacroEngine()
{
// Decrement the count of registered engines
TStatsCache::c8DecCounter(CIDMacroEng_Engine::sciMacroEngCount);
try
{
//
// Do some common cleanup that is down each time the entine is
// prepped for a new run. Tell it this time to remove all of
// them, whereas normally it leaves the built in classes alone.
//
Cleanup(kCIDLib::True);
//
// And clean up some other stuff that only get's dropped when we
// going away.
//
// Note that we don't own any of the handler callback objects or
// the console stream.
//
delete m_pmecvThrown;
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
catch(...)
{
}
}
// ---------------------------------------------------------------------------
// TCIDMacroEngine: Public, non-virtual methods
// ---------------------------------------------------------------------------
tCIDLib::TVoid
TCIDMacroEngine::AddBoolParm( TParmList& colTar
, const TString& strName
, const tCIDLib::TBoolean bConst)
{
const TMEngClassInfo& meciBool = meciFind(L"MEng.Boolean");
colTar.Add
(
meciBool.pmecvMakeStorage
(
strName
, *this
, bConst ? tCIDMacroEng::EConstTypes::Const
: tCIDMacroEng::EConstTypes::NonConst
)
);
}
tCIDLib::TVoid
TCIDMacroEngine::AddStringParm( TParmList& colTar
, const TString& strName
, const tCIDLib::TBoolean bConst)
{
const TMEngClassInfo& meciString = meciFind(L"MEng.String");
colTar.Add
(
meciString.pmecvMakeStorage
(
strName
, *this
, bConst ? tCIDMacroEng::EConstTypes::Const
: tCIDMacroEng::EConstTypes::NonConst
)
);
}
tCIDLib::TBoolean
TCIDMacroEngine::bAreEquivCols( const tCIDLib::TCard2 c2ClassId1
, const tCIDLib::TCard2 c2ClassId2
, const tCIDLib::TBoolean bSameElemType) const
{
const TMEngClassInfo& meci1 = meciFind(c2ClassId1);
const TMEngClassInfo& meci2 = meciFind(c2ClassId2);
// They have to both be collection classes
if (!bIsCollectionClass(meci1.c2ParentClassId())
|| !bIsCollectionClass(meci2.c2ParentClassId()))
{
return kCIDLib::False;
}
// And they both must derive from the same base collection class
if (meci1.c2ParentClassId() != meci2.c2ParentClassId())
return kCIDLib::False;
//
// If the caller says the element types must be the same, then check that.
//
if (bSameElemType)
{
return (static_cast<const TMEngColBaseInfo&>(meci1).c2ElemId()
== static_cast<const TMEngColBaseInfo&>(meci2).c2ElemId());
}
//
// Else the second element type must derive from the first. This method takes
// the base class as the second parm and the one to test as the first.
//
return bIsDerivedFrom
(
static_cast<const TMEngColBaseInfo&>(meci2).c2ElemId()
, static_cast<const TMEngColBaseInfo&>(meci1).c2ElemId()
);
}
// Get set the 'in IDE' flag, which the IDE sets on us. Otherwise it's false always
tCIDLib::TBoolean TCIDMacroEngine::bInIDE() const
{
return m_bInIDE;
}
tCIDLib::TBoolean TCIDMacroEngine::bInIDE(const tCIDLib::TBoolean bToSet)
{
m_bInIDE = bToSet;
return m_bInIDE;
}
// Return the debug mode flag
tCIDLib::TBoolean TCIDMacroEngine::bDebugMode(const tCIDLib::TBoolean bToSet)
{
m_bDebugMode = bToSet;
return m_bDebugMode;
}
// Used to format stack dumps
tCIDLib::TBoolean
TCIDMacroEngine::bFormatNextCallFrame( TTextOutStream& strmTarget
, tCIDLib::TCard4& c4PrevInd)
{
//
// If the previous id is max card, then we are to do the first one.
// Else, we are working down and need to find the previous one.
//
TMEngCallStackItem* pmecsiCur = nullptr;
if (c4PrevInd == kCIDLib::c4MaxCard)
{
// If we don't have any entries, nothing to do
if (!m_c4CallStackTop)
{
strmTarget << L"<Empty>";
c4PrevInd = 0;
}
else
{
//
// Start at the top of the call stack and work down to the first
// method call opcode, which is what we want to start with.
//
c4PrevInd = m_c4CallStackTop;
do
{
c4PrevInd--;
pmecsiCur = m_colCallStack[c4PrevInd];
if (pmecsiCur->eType() == tCIDMacroEng::EStackItems::MethodCall)
break;
} while (c4PrevInd != 0);
//
// If we hit zero, then nothing, else call a private helper to
// format this one.
//
if (c4PrevInd)
FormatAFrame(strmTarget, c4PrevInd);
}
}
else
{
//
// Find the previous item on the stack, starting at one before the
// previous item.
//
do
{
c4PrevInd--;
pmecsiCur = m_colCallStack[c4PrevInd];
if (pmecsiCur->eType() == tCIDMacroEng::EStackItems::MethodCall)
break;
} while (c4PrevInd != 0);
//
// If we hit zero, then nothing, else call a private helper to
// format this one.
//
if (c4PrevInd)
FormatAFrame(strmTarget, c4PrevInd);
}
return (c4PrevInd != 0);
}
tCIDLib::TBoolean
TCIDMacroEngine::bGetLastExceptInfo(TString& strClass
, TString& strText
, tCIDLib::TCard4& c4Line)
{
if (m_pmecvThrown)
{
strClass = m_pmecvThrown->strSrcClassPath();
strText = m_pmecvThrown->strErrorText();
c4Line = m_pmecvThrown->c4LineNum();
return kCIDLib::True;
}
return kCIDLib::False;
}
tCIDLib::TBoolean
TCIDMacroEngine::bInvokeDefCtor( TMEngClassVal& mecvTarget
, const TCIDUserCtx* const pcuctxRights)
{
try
{
// Set the passed user contact while we are in here
TGFJanitor<const TCIDUserCtx*> janRights(&m_pcuctxRights, pcuctxRights);
//
// If the temp pool is empty, then this is the first time this
// engine instance has been used, so we need to initialize the
// pool.
//
if (m_colTempPool.bIsEmpty())
InitTempPool();
// Look up it's class
const TMEngClassInfo& meciTarget = meciFind(mecvTarget.c2ClassId());
//
// And ask it for it's default ctor, if any. Note that we look up
// the INFO not the IMPL here, since it could be a class that is
// just wrapping C++ code and it won't have any CML level impl.
//
const TMEngMethodInfo* pmethiDefCtor = meciTarget.pmethiDefCtor();
if (!pmethiDefCtor)
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, kMEngErrs::errcClass_NoDefCtor
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::NotFound
, meciTarget.strClassPath()
);
// Won't happen but makes analyzer happy
return kCIDLib::False;
}
//
// Push a void return value, the method call, and invoke it. We
// indicate a monomorphic invocation here, since it has to be
// our guy that we are targeting.
//
PushPoolValue(tCIDMacroEng::EIntrinsics::Void, tCIDMacroEng::EConstTypes::Const);
meciPushMethodCall(meciTarget.c2Id(), pmethiDefCtor->c2Id());
meciTarget.Invoke
(
*this
, mecvTarget
, pmethiDefCtor->c2Id()
, tCIDMacroEng::EDispatch::Mono
);
// We have to pop the method call and return off
MultiPop(2);
}
catch(const TDbgExitException& excptForce)
{
if (m_pmedbgToUse)
m_pmedbgToUse->FinishedDbg(excptForce.m_eReason);
return kCIDLib::False;
}
catch(const TExceptException&)
{
//
// If there is an herror handler, and we are in the mode where we
// report macros if they aren'thandled, then report it. If we are
// in the other mode, it will already have been reported at the point
// of throw.
//
if (m_pmeehToUse && (m_eExceptReport == tCIDMacroEng::EExceptReps::NotHandled))
m_pmeehToUse->MacroException(*m_pmecvThrown, *this);
if (m_pmedbgToUse)
m_pmedbgToUse->FinishedDbg(tCIDMacroEng::EDbgActs::Exit);
return kCIDLib::False;
}
catch(...)
{
if (m_pmedbgToUse)
m_pmedbgToUse->FinishedDbg(tCIDMacroEng::EDbgActs::Exit);
return kCIDLib::False;
}
return kCIDLib::True;
}
//
// All the collection classes are runtime classes, so we know them and have
// their ids stored, so we can provide a quick check.
//
tCIDLib::TBoolean
TCIDMacroEngine::bIsCollectionClass(const tCIDLib::TCard2 c2IdToCheck) const
{
return ((c2IdToCheck == m_c2ArrayId) || (c2IdToCheck == m_c2VectorId));
}
//
// Checks to see if one class is derived from aonther, by just walking the
// parentage chain.
//
tCIDLib::TBoolean
TCIDMacroEngine::bIsDerivedFrom(const tCIDLib::TCard2 c2IdToTest
, const tCIDLib::TCard2 c2BaseClassId) const
{
tCIDLib::TCard2 c2Cur = c2IdToTest;
while (kCIDLib::True)
{
//
// If we've hit the target base class, then it's good. If the test
// class is down to the object level, it is not gonna work.
//
if ((c2Cur == c2BaseClassId)
|| (c2Cur == tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Object)))
{
break;
}
// Get the parent class id of the target class, and go again
c2Cur = meciFind(c2Cur).c2ParentClassId();
}
return (c2Cur == c2BaseClassId);
}
tCIDLib::TBoolean
TCIDMacroEngine::bIsDerivedFrom(const tCIDLib::TCard2 c2IdToTest
, const tCIDMacroEng::EIntrinsics eBaseType) const
{
return bIsDerivedFrom(c2IdToTest, tCIDLib::TCard2(eBaseType));
}
//
// Literals can only be char, bool, string, or numeric. This is a method
// to keep that check in one place.
//
tCIDLib::TBoolean
TCIDMacroEngine::bIsLiteralClass(const tCIDLib::TCard2 c2IdToCheck) const
{
// If not an intrinsic, then obviously can't be
if (c2IdToCheck >= tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Count))
return kCIDLib::False;
tCIDLib::TBoolean bRet = kCIDLib::False;
switch(tCIDMacroEng::EIntrinsics(c2IdToCheck))
{
case tCIDMacroEng::EIntrinsics::Boolean :
case tCIDMacroEng::EIntrinsics::Char :
case tCIDMacroEng::EIntrinsics::String :
case tCIDMacroEng::EIntrinsics::Card1 :
case tCIDMacroEng::EIntrinsics::Card2 :
case tCIDMacroEng::EIntrinsics::Card4 :
case tCIDMacroEng::EIntrinsics::Card8 :
case tCIDMacroEng::EIntrinsics::Float4 :
case tCIDMacroEng::EIntrinsics::Float8 :
case tCIDMacroEng::EIntrinsics::Int1 :
case tCIDMacroEng::EIntrinsics::Int2 :
case tCIDMacroEng::EIntrinsics::Int4 :
bRet = kCIDLib::True;
break;
default :
bRet = kCIDLib::False;
break;
};
return bRet;
}
tCIDLib::TBoolean
TCIDMacroEngine::bStackValAt(const tCIDLib::TCard4 c4Index
, const tCIDLib::TBoolean bCheckType) const
{
const TMEngClassVal& mecvVal = mecsiAt(c4Index).mecvPushed();
if (bCheckType)
CheckItemType(mecvVal.c2ClassId(), tCIDMacroEng::EIntrinsics::Boolean, CID_LINE, c4Index);
return static_cast<const TMEngBooleanVal&>(mecvVal).bValue();
}
tCIDLib::TBoolean TCIDMacroEngine::bValidation(const tCIDLib::TBoolean bToSet)
{
m_bValidation = bToSet;
return m_bValidation;
}
tCIDLib::TCard1
TCIDMacroEngine::c1StackValAt( const tCIDLib::TCard4 c4Index
, const tCIDLib::TBoolean bCheckType) const
{
const TMEngClassVal& mecvVal = mecsiAt(c4Index).mecvPushed();
if (bCheckType)
CheckItemType(mecvVal.c2ClassId(), tCIDMacroEng::EIntrinsics::Card1, CID_LINE, c4Index);
return static_cast<const TMEngCard1Val&>(mecvVal).c1Value();
}
tCIDLib::TCard2
TCIDMacroEngine::c2AddClass(TMEngClassInfo* const pmeciToAdopt)
{
//
// Give it the next id and bump the id counter, then add it to the
// 'by id' lookup vector, so it's now safely adopted.
//
// NOTE: These are related actions! The id must be a direct index
// into the by id vector!
//
facCIDMacroEng().CheckIdOverflow(m_c2NextClassId, L"classes");
pmeciToAdopt->SetClassId(m_c2NextClassId++);
m_colClassesById.Add(pmeciToAdopt);
// Initialize the class now
pmeciToAdopt->Init(*this);
// Add if it not already. If it is already, then throw an error
if (!m_colClasses.bAddIfNew(pmeciToAdopt))
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, kMEngErrs::errcEng_DupClassName
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Already
, pmeciToAdopt->strClassPath()
);
}
// Return the id we gave to this class
return pmeciToAdopt->c2Id();
}
tCIDLib::TCard2
TCIDMacroEngine::c2AddClassDefer(TMEngClassInfo* const pmeciToAdopt)
{
//
// Give it the next id and bump the id counter, then add it to the
// 'by id' lookup vector, so it's now safely adopted.
//
// NOTE: These are related actions! The id must be a direct index
// into the by id vector!
//
facCIDMacroEng().CheckIdOverflow(m_c2NextClassId, L"classes");
pmeciToAdopt->SetClassId(m_c2NextClassId++);
m_colClassesById.Add(pmeciToAdopt);
// Add if it not already. If it is already, then throw an error
if (!m_colClasses.bAddIfNew(pmeciToAdopt))
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, kMEngErrs::errcEng_DupClassName
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Already
, pmeciToAdopt->strClassPath()
);
}
// Return the id we gave to this class
return pmeciToAdopt->c2Id();
}
tCIDLib::TCard2
TCIDMacroEngine::c2EnumValAt(const tCIDLib::TCard4 c4Index
, const tCIDLib::TCard2 c2ExpectedId
, const tCIDLib::TBoolean bCheckType) const
{
const TMEngClassVal& mecvVal = mecsiAt(c4Index).mecvPushed();
if (bCheckType)
CheckItemType(mecvVal.c2ClassId(), c2ExpectedId, CID_LINE, c4Index);
return tCIDLib::TCard2(static_cast<const TMEngEnumVal&>(mecvVal).c4Ordinal());
}
tCIDLib::TCard2
TCIDMacroEngine::c2FindClassId( const TString& strClassPath
, const tCIDLib::TBoolean bThrowIfNot) const
{
const TMEngClassInfo* pmeciRet = m_colClasses.pobjFindByKey
(
strClassPath
, kCIDLib::False
);
if (!pmeciRet)
{
if (bThrowIfNot)
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, kMEngErrs::errcEng_ClassNotFound
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::NotFound
, strClassPath
);
}
return kCIDMacroEng::c2BadId;
}
return pmeciRet->c2Id();
}
tCIDLib::TCard2
TCIDMacroEngine::c2FindEntryPoint( TMEngClassInfo& meciTarget
, const tCIDLib::TBoolean bThrowIfNot)
{
// Find a method with the name "Start".
TMEngMethodInfo* pmethiTarget = meciTarget.pmethiFind(L"Start");
//
// If not there, or it doesn't have the right return type, or isn't
// final, it's bad
//
if (!pmethiTarget
|| (pmethiTarget->c2RetClassId() != tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Int4))
|| (pmethiTarget->eExtend() != tCIDMacroEng::EMethExt::Final))
{
if (bThrowIfNot)
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, kMEngErrs::errcEng_BadEntryPoint
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Format
);
}
return kCIDLib::c2MaxCard;
}
return pmethiTarget->c2Id();
}
tCIDLib::TCard2
TCIDMacroEngine::c2StackValAt( const tCIDLib::TCard4 c4Index
, const tCIDLib::TBoolean bCheckType) const
{
const TMEngClassVal& mecvVal = mecsiAt(c4Index).mecvPushed();
if (bCheckType)
CheckItemType(mecvVal.c2ClassId(), tCIDMacroEng::EIntrinsics::Card2, CID_LINE, c4Index);
return static_cast<const TMEngCard2Val&>(mecvVal).c2Value();
}
tCIDLib::TCard4 TCIDMacroEngine::c4ClassCount() const
{
return m_colClasses.c4ElemCount();
}
//
// Given a method info object, this method will create a parameter list
// object with the appropriate types of objects to pass in to that method.
// Generally this is used by external code that needs to call the Start()
// method and get information into the parameters in some more complex way
// that just passing a command line.
//
// The passed parm list must be adopting!
//
tCIDLib::TCard4
TCIDMacroEngine::c4CreateParmList( const TMEngMethodInfo& methiTarget
, TParmList& colParms)
{
// Make sure that the list is adopting
if (colParms.eAdopt() != tCIDLib::EAdoptOpts::Adopt)
{
facCIDLib().ThrowErr
(
CID_FILE
, CID_LINE
, kCIDErrs::errcCol_MustBeAdopting
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::AppError
);
}
// Loop through and try to create the value objects
colParms.RemoveAll();
const tCIDLib::TCard4 c4ParmCount = methiTarget.c4ParmCount();
TString strName;
for (tCIDLib::TCard2 c2Id = 0; c2Id < c4ParmCount; c2Id++)
{
const TMEngParmInfo& mepiTar = methiTarget.mepiFind(c2Id);
// The direction indicates whether it's const or not
const tCIDMacroEng::EConstTypes eConst
(
(mepiTar.eDir() == tCIDMacroEng::EParmDirs::In)
? tCIDMacroEng::EConstTypes::Const : tCIDMacroEng::EConstTypes::NonConst
);
// The name we'll give it
strName = L"Parm";
strName.AppendFormatted(tCIDLib::TCard4(c2Id + 1));
// Create a new value object of the target type
TMEngClassInfo& meciParm = meciFind(mepiTar.c2ClassId());
TMEngClassVal* pmecvNew = meciParm.pmecvMakeStorage
(
strName, *this, eConst
);
colParms.Add(pmecvNew);
}
return c4ParmCount;
}
tCIDLib::TCard4
TCIDMacroEngine::c4FindNextTry(tCIDLib::TCard4& c4CatchIP) const
{
//
// Start at the stack top and search backwards for the next exception
// item on the stack.
//
tCIDLib::TCard4 c4Index = m_c4CallStackTop;
while (c4Index)
{
c4Index--;
const TMEngCallStackItem* pmecsiCur = m_colCallStack[c4Index];
if (pmecsiCur->eType() == tCIDMacroEng::EStackItems::Try)
{
c4CatchIP = pmecsiCur->c4Value();
break;
}
}
//
// If we hit the bottom, there isn't one. Note that it could never at
// the 0th index, because there has to at least be the initial call
// frame.
//
if (!c4Index)
{
c4CatchIP = kCIDLib::c4MaxCard;
return kCIDLib::c4MaxCard;
}
return c4Index;
}
tCIDLib::TCard4
TCIDMacroEngine::c4FirstParmInd(const TMEngMethodInfo& methiCalled)
{
const tCIDLib::TCard4 c4Ofs = methiCalled.c4ParmCount() + 1;
#if CID_DEBUG_ON
if (c4Ofs > m_c4CallStackTop)
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, kMEngErrs::errcEng_CallStackUnderflow
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Underflow
);
}
#endif
return m_c4CallStackTop - c4Ofs;
}
// Return the next available unique id and increment
tCIDLib::TCard4 TCIDMacroEngine::c4NextUniqueId()
{
return m_c4NextUniqueId++;
}
//
// Retrieve values on the stack at a given index by type, to save a lot of
// grunt work all over the place.
//
tCIDLib::TCard4
TCIDMacroEngine::c4StackValAt( const tCIDLib::TCard4 c4Index
, const tCIDLib::TBoolean bCheckType) const
{
const TMEngClassVal& mecvVal = mecsiAt(c4Index).mecvPushed();
if (bCheckType)
CheckItemType(mecvVal.c2ClassId(), tCIDMacroEng::EIntrinsics::Card4, CID_LINE, c4Index);
return static_cast<const TMEngCard4Val&>(mecvVal).c4Value();
}
tCIDLib::TCard8
TCIDMacroEngine::c8StackValAt( const tCIDLib::TCard4 c4Index
, const tCIDLib::TBoolean bCheckType) const
{
const TMEngClassVal& mecvVal = mecsiAt(c4Index).mecvPushed();
if (bCheckType)
CheckItemType(mecvVal.c2ClassId(), tCIDMacroEng::EIntrinsics::Card8, CID_LINE, c4Index);
return static_cast<const TMEngCard8Val&>(mecvVal).c8Value();
}
tCIDLib::TCh
TCIDMacroEngine::chStackValAt( const tCIDLib::TCard4 c4Index
, const tCIDLib::TBoolean bCheckType) const
{
const TMEngClassVal& mecvVal = mecsiAt(c4Index).mecvPushed();
if (bCheckType)
CheckItemType(mecvVal.c2ClassId(), tCIDMacroEng::EIntrinsics::Char, CID_LINE, c4Index);
return static_cast<const TMEngCharVal&>(mecvVal).chValue();
}
const TVector<TString>&
TCIDMacroEngine::colStackValAt( const tCIDLib::TCard4 c4Index
, const tCIDLib::TBoolean bCheckType) const
{
const TMEngClassVal& mecvVal = mecsiAt(c4Index).mecvPushed();
if (bCheckType)
CheckItemType(mecvVal.c2ClassId(), tCIDMacroEng::EIntrinsics::StringList, CID_LINE, c4Index);
return static_cast<const TMEngStrListVal&>(mecvVal).colValue();
}
//
// Provide access to any user rights context that the user code may have set
// on us. We don't care what it is, it's purely a passthrough for user code.
// There is another version that returns a pointer. This is for those clients
// that know they set one, and therefore want an exception if one is not set.
//
const TCIDUserCtx& TCIDMacroEngine::cuctxRights() const
{
if (!m_pcuctxRights)
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, kMEngErrs::errcEng_NoUserContext
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::AppError
);
}
return *m_pcuctxRights;
}
//
// Finds the first CML level call on the stack (we might have called down
// into C++ code.) If found, it gets the info on the caller and calls back
// the debugger pluggin with that information.
//
tCIDLib::TVoid TCIDMacroEngine::CheckIDEReq()
{
// If we have no debug interface installed, nothing to do
if (!m_pmedbgToUse)
return;
//
// Start at the top of the stack and work backwards till we see a
// call from a macro level class.
//
tCIDLib::TCard4 c4Index = m_c4CallStackTop;
if (!c4Index)
return;
TMEngCallStackItem* pmecsiCur = nullptr;
do
{
c4Index--;
pmecsiCur = m_colCallStack[c4Index];
if (pmecsiCur->eType() == tCIDMacroEng::EStackItems::MethodCall)
{
if (pmecsiCur->bHasCallerInfo())
break;
}
} while (c4Index != 0);
if (c4Index == 0)
return;
// Get out the info we need
const TMEngClassInfo* pmeciCaller = nullptr;
const TMEngOpMethodImpl* pmethCaller = nullptr;
const TMEngMethodInfo* pmethiCaller = nullptr;
TMEngClassVal* pmecvCaller = nullptr;
tCIDLib::TCard4 c4CallIP = kCIDLib::c4MaxCard;
tCIDLib::TCard4 c4CallLine = pmecsiCur->c4QueryCallerInfo
(
pmeciCaller, pmethiCaller, pmethCaller, pmecvCaller, c4CallIP
);
tCIDMacroEng::EDbgActs eAct = m_pmedbgToUse->eAtLine
(
*pmeciCaller, *pmethiCaller, *pmethCaller, *pmecvCaller, c4CallLine, c4CallIP
);
//
// If he tells us to exit, then throw an exception
// that will dump us back to the top level, who will
// tell the debugger we've exited.
//
if ((eAct == tCIDMacroEng::EDbgActs::CloseSession)
|| (eAct == tCIDMacroEng::EDbgActs::Exit))
{
throw TDbgExitException(eAct);
}
}
tCIDLib::TVoid
TCIDMacroEngine::CheckSameClasses( const TMEngClassVal& mecv1
, const TMEngClassVal& mecv2) const
{
// If the second isn't the same or derived from the first, it's not eqiuv
if (mecv1.c2ClassId() != mecv2.c2ClassId())
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, kMEngErrs::errcClass_Mismatch
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::TypeMatch
, strClassPathForId(mecv1.c2ClassId())
, strClassPathForId(mecv2.c2ClassId())
);
}
}
tCIDLib::TVoid
TCIDMacroEngine::CheckStackTop( const tCIDLib::TCard2 c2ExpectedClassId
, const tCIDMacroEng::EConstTypes eConst) const
{
//
// Get the value on the top of the stack. If it's not a value item,
// this will throw.
//
const TMEngClassVal& mecvVal = mecsiAt(m_c4CallStackTop - 1).mecvPushed();
// Make sure it meets the target criteria
if (mecvVal.c2ClassId() != c2ExpectedClassId)
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, kMEngErrs::errcEng_NotStackItemType
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Internal
, strClassPathForId(c2ExpectedClassId)
);
}
if (mecvVal.eConst() != eConst)
{
tCIDLib::TErrCode errcToThrow = kMEngErrs::errcEng_NotNConstStackItem;
if (eConst == tCIDMacroEng::EConstTypes::Const)
errcToThrow = kMEngErrs::errcEng_NotConstStackItem;
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, errcToThrow
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Internal
, strClassPathForId(c2ExpectedClassId)
);
}
}
//
// Cleans up the data that is accumulated during a run of the compiler,
// so that it's ready for another around. Not that we can be told not to
// remove the built in classes, which is typically the case. They can stay
// the same forever and only need to be removed when the engine is
// destroyed.
//
tCIDLib::TVoid
TCIDMacroEngine::Cleanup(const tCIDLib::TBoolean bRemoveBuiltIns)
{
//
// Clean up the classes. If removing built ins as well, then we
// can do the simple scenario. Else we go through and only remove
// the non-built ins.
//
try
{
// We flush the by name list either way
m_colClasses.RemoveAll();
if (bRemoveBuiltIns)
{
// And we are doing them all so just whack the by id list, too
m_colClassesById.RemoveAll();
}
else if (m_colClassesById.bIsEmpty())
{
// Built ins are already removed, make sure the by name list is clean
m_colClasses.RemoveAll();
}
else
{
//
// The array id that we use as the last built in id has to be
// beyond the last of the intrinsic ids. So sanity check that.
//
CIDAssert
(
m_c2ArrayId >= tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Count)
, L"Invalid array id in CML engine cleanup"
);
//
// We have to leave the built ins. The most efficent way
// to do this is to delete all of the ones from the by id
// list that are past the last built in id. Then just go
// back and add the remaining ones back to the by name
// list again. Go backwards to avoid recompaction every time.
//
tCIDLib::TCard4 c4Index = m_colClassesById.c4ElemCount() - 1;
const tCIDLib::TCard4 c4Last = m_c2ArrayId;
while (c4Index > c4Last)
m_colClassesById.RemoveAt(c4Index--);
// Ok, now add the ones left back
for (c4Index = 0; c4Index <= c4Last; c4Index++)
m_colClasses.Add(m_colClassesById[c4Index]);
}
}
catch(TError& errToCatch)
{
if (!errToCatch.bLogged())
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, kMEngErrs::errcEng_CleanupErr
, tCIDLib::ESeverities::Status
, tCIDLib::EErrClasses::AppStatus
);
}
// And clean up the temp pool
try
{
m_colTempPool.RemoveAll();
}
catch(TError& errToCatch)
{
if (!errToCatch.bLogged())
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, kMEngErrs::errcEng_CleanupErr
, tCIDLib::ESeverities::Status
, tCIDLib::EErrClasses::AppStatus
);
}
// Reset the console output stream
if (m_pstrmConsole)
m_pstrmConsole->Reset();
}
//
// Takes an OS level file path and converts it to the CML level file
// path. To go the other way use bExpandFilePath().
//
tCIDLib::TVoid
TCIDMacroEngine::ContractFilePath( const TString& strOSPath
, TPathStr& pathToFill)
{
m_pmefrToUse->ContractPath(strOSPath, pathToFill);
// Make sure it has the right type of slashes
pathToFill.bReplaceChar(L'/', L'\\');
}
//
// Get or set the exption reporting flag, which controls whether we
// report at throw or when unhandled (when in the IDE.)
//
tCIDMacroEng::EExceptReps TCIDMacroEngine::eExceptReport() const
{
return m_eExceptReport;
}
tCIDMacroEng::EExceptReps
TCIDMacroEngine::eExceptReport(const tCIDMacroEng::EExceptReps eToSet)
{
m_eExceptReport = eToSet;
return m_eExceptReport;
}
//
// Resolves a possibly partial class path to a full one. It may be
// ambiguous so we return all possible matches.
//
tCIDMacroEng::EClassMatches TCIDMacroEngine::
eResolveClassName( const TString& strName
, TRefCollection<TMEngClassInfo>& colMatches)
{
//
// There are three scenarios, which are:
//
// 1. Fully qualified
// 2. Relative
// 3. Relative plus nested
//
enum class ETypes
{
Fully
, Relative
, Nested
};
// Insure that the collection is non-adopting
if (colMatches.eAdopt() != tCIDLib::EAdoptOpts::NoAdopt)
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, kMEngErrs::errcEng_MustBeNonAdopting
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Internal
);
}
// Looks ok, so clean it out
colMatches.RemoveAll();
// First we figure out which scenario we are looking at.
ETypes eType = ETypes::Fully;
tCIDLib::TCard4 c4Pos1 = 0;
tCIDLib::TCard4 c4Pos2 = 0;
if (strName.bFirstOccurrence(kCIDLib::chPeriod, c4Pos1))
{
//
// If it doesn't start with MEng and has only one period, then
// it's a relative path.
//
c4Pos2 = c4Pos1;
if (!strName.bStartsWithI(L"MEng")
&& !strName.bNextOccurrence(kCIDLib::chPeriod, c4Pos2))
{
eType = ETypes::Nested;
}
else
{
eType = ETypes::Fully;
}
}
else
{
// No periods so must be relative
eType = ETypes::Relative;
}
tCIDMacroEng::EClassMatches eRet = tCIDMacroEng::EClassMatches::NotFound;
if (eType == ETypes::Fully)
{
TMEngClassInfo* pmeciTarget = pmeciFind(strName);
if (!pmeciTarget)
return tCIDMacroEng::EClassMatches::NotFound;
colMatches.Add(pmeciTarget);
eRet = tCIDMacroEng::EClassMatches::Unique;
}
else if (eType == ETypes::Nested)
{
// Get out the first part of the name
TString strFind(strName);
if (eType == ETypes::Nested)
strFind.Cut(c4Pos1);
// Make sure it's unique and remember which one we hit, if any
TMEngClassInfo* pmeciCur = nullptr;
tCIDLib::TCard4 c4HitCount = 0;
const tCIDLib::TCard4 c4Count = m_colClassesById.c4ElemCount();
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
if (m_colClassesById[c4Index]->strName() == strFind)
{
pmeciCur = m_colClassesById[c4Index];
c4HitCount++;
}
}
// If we hit one, let's check it, else we failed
if (c4HitCount)
{
// Make sure it has a nested class of the second part
strFind = pmeciCur->strClassPath();
strFind.Append(kCIDLib::chPeriod);
strFind.AppendSubStr(strName, c4Pos1 + 1);
TMEngClassInfo* pmeciTarget = pmeciFind(strFind);
if (pmeciTarget)
{
eRet = tCIDMacroEng::EClassMatches::Unique;
colMatches.Add(pmeciTarget);
}
else
{
eRet = tCIDMacroEng::EClassMatches::NotFound;
}
}
else
{
eRet = tCIDMacroEng::EClassMatches::NotFound;
}
}
else
{
// It's relative so it must be unique
const tCIDLib::TCard4 c4Count = m_colClassesById.c4ElemCount();
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
TMEngClassInfo* pmeciCur = m_colClassesById[c4Index];
if (pmeciCur->strName() == strName)
colMatches.Add(pmeciCur);
}
if (colMatches.bIsEmpty())
eRet = tCIDMacroEng::EClassMatches::NotFound;
else if (colMatches.c4ElemCount() > 1)
eRet = tCIDMacroEng::EClassMatches::Ambiguous;
else
eRet = tCIDMacroEng::EClassMatches::Unique;
}
return eRet;
}
// Translates a numeric class id to it's intrinsic enumerated value
tCIDMacroEng::ENumTypes
TCIDMacroEngine::eXlatNumType(const tCIDLib::TCard2 c2NumClassId)
{
if ((c2NumClassId < tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::FirstNum))
|| (c2NumClassId > tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::LastNum)))
{
return tCIDMacroEng::ENumTypes::None;
}
return tCIDMacroEng::ENumTypes
(
(c2NumClassId - tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Card1)) + 1
);
}
// Set a C++ excpetion on, which will be reported to any installed handler
tCIDLib::TVoid TCIDMacroEngine::Exception(const TError& errThrown)
{
// If we have a handler, let it know about this one
if (m_pmeehToUse)
{
m_pmeehToUse->Exception(errThrown, *this);
errThrown.bReported(kCIDLib::True);
}
}
//
// Takes a macro level file path and converts it to the full OS level
// file path. To go the other way use bContractFilePath().
//
tCIDLib::TVoid
TCIDMacroEngine::ExpandFilePath(const TString& strMacroPath
, TPathStr& pathToFill)
{
//
// Make sure it has the right type of slashes. Some folks use
// forward slashes instead of back. So if the native path sep
// isn't forward, then replace them with the native one.
//
#pragma warning(suppress : 6326) // chPathSep is per-platform, so this is legit check
if (kCIDLib::chPathSep != L'/')
{
TString strTmp(strMacroPath);
strTmp.bReplaceChar(L'/', kCIDLib::chPathSep);
m_pmefrToUse->ExpandPath(strTmp, pathToFill);
}
else
{
m_pmefrToUse->ExpandPath(strMacroPath, pathToFill);
}
}
// Get a TFloat4 value on the stack at the indicated index
tCIDLib::TFloat4
TCIDMacroEngine::f4StackValAt( const tCIDLib::TCard4 c4Index
, const tCIDLib::TBoolean bCheckType) const
{
const TMEngClassVal& mecvVal = mecsiAt(c4Index).mecvPushed();
if (bCheckType)
CheckItemType(mecvVal.c2ClassId(), tCIDMacroEng::EIntrinsics::Float4, CID_LINE, c4Index);
return static_cast<const TMEngFloat4Val&>(mecvVal).f4Value();
}
// Get a TFloat8 value on the stack at the indicated index
tCIDLib::TFloat8
TCIDMacroEngine::f8StackValAt( const tCIDLib::TCard4 c4Index
, const tCIDLib::TBoolean bCheckType) const
{
const TMEngClassVal& mecvVal = mecsiAt(c4Index).mecvPushed();
if (bCheckType)
CheckItemType(mecvVal.c2ClassId(), tCIDMacroEng::EIntrinsics::Float8, CID_LINE, c4Index);
return static_cast<const TMEngFloat8Val&>(mecvVal).f8Value();
}
tCIDLib::TVoid TCIDMacroEngine::FlipStackTop()
{
// These must be at least two items on the stack for this to be legal
if (m_c4CallStackTop < 2)
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, kMEngErrs::errcEng_BadStackFlip
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Internal
);
}
m_colCallStack.SwapItems(m_c4CallStackTop - 2, m_c4CallStackTop - 1);
}
tCIDLib::TInt1
TCIDMacroEngine::i1StackValAt( const tCIDLib::TCard4 c4Index
, const tCIDLib::TBoolean bCheckType) const
{
const TMEngClassVal& mecvVal = mecsiAt(c4Index).mecvPushed();
if (bCheckType)
CheckItemType(mecvVal.c2ClassId(), tCIDMacroEng::EIntrinsics::Int1, CID_LINE, c4Index);
return static_cast<const TMEngInt1Val&>(mecvVal).i1Value();
}
tCIDLib::TInt2
TCIDMacroEngine::i2StackValAt( const tCIDLib::TCard4 c4Index
, const tCIDLib::TBoolean bCheckType) const
{
const TMEngClassVal& mecvVal = mecsiAt(c4Index).mecvPushed();
if (bCheckType)
CheckItemType(mecvVal.c2ClassId(), tCIDMacroEng::EIntrinsics::Int2, CID_LINE, c4Index);
return static_cast<const TMEngInt2Val&>(mecvVal).i2Value();
}
tCIDLib::TInt4
TCIDMacroEngine::i4StackValAt( const tCIDLib::TCard4 c4Index
, const tCIDLib::TBoolean bCheckType) const
{
const TMEngClassVal& mecvVal = mecsiAt(c4Index).mecvPushed();
if (bCheckType)
CheckItemType(mecvVal.c2ClassId(), tCIDMacroEng::EIntrinsics::Int4, CID_LINE, c4Index);
return static_cast<const TMEngInt4Val&>(mecvVal).i4Value();
}
tCIDLib::TInt4
TCIDMacroEngine::i4Run( TMEngClassVal& mecvTarget
, const TString& strParmVals
, const TCIDUserCtx* const pcuctxRights)
{
TParmList colParms(tCIDLib::EAdoptOpts::Adopt);
try
{
// Set the passed user contact while we are in here
TGFJanitor<const TCIDUserCtx*> janRights(&m_pcuctxRights, pcuctxRights);
//
// Search this class for a legal entry point. It must have
// particular name and form.
//
TMEngClassInfo& meciTarget = meciFind(mecvTarget.c2ClassId());
const tCIDLib::TCard2 c2MethodId = c2FindEntryPoint(meciTarget, 0);
// Try to parse out the parameters
TVector<TString> colSrcParms;
const tCIDLib::TCard4 c4ParmCount = TExternalProcess::c4BreakOutParms
(
strParmVals
, colSrcParms
);
// Make sure that we got the correct number of parms
TMEngMethodInfo& methiTarget = meciTarget.methiFind(c2MethodId);
if (c4ParmCount != methiTarget.c4ParmCount())
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, kMEngErrs::errcEng_BadEntryParmCnt
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::BadParms
, meciTarget.strClassPath()
, TCardinal(methiTarget.c4ParmCount())
, TCardinal(c4ParmCount)
);
}
// Loop through and try to create the value objects
TString strName;
for (tCIDLib::TCard2 c2Id = 0; c2Id < c4ParmCount; c2Id++)
{
const TMEngParmInfo& mepiTar = methiTarget.mepiFind(c2Id);
const TString& strCur = colSrcParms[c2Id];
// The direction indicates whether it's const or not
const tCIDMacroEng::EConstTypes eConst
(
(mepiTar.eDir() == tCIDMacroEng::EParmDirs::In)
? tCIDMacroEng::EConstTypes::Const : tCIDMacroEng::EConstTypes::NonConst
);
// The name we'll give it
strName = L"Parm";
strName.AppendFormatted(tCIDLib::TCard4(c2Id + 1));
// Create a new value object of the target type
TMEngClassInfo& meciParm = meciFind(mepiTar.c2ClassId());
TMEngClassVal* pmecvNew = meciParm.pmecvMakeStorage
(
strName, *this, eConst
);
colParms.Add(pmecvNew);
// Ask it to parse from the current value
if (!pmecvNew->bParseFromText(strCur, meciParm))
{
//
// If we have an error handler, then build up a macro
// level exception and report that.
//
if (m_pmeehToUse)
{
//
// Get the base info class info. This guy has nested
// enum types that provide the errors for stuff like
// this.
//
const TMEngBaseInfoInfo& meciBaseInfo
(
*pmeciFindAs<TMEngBaseInfoInfo>
(
TMEngBaseInfoInfo::strPath(), kCIDLib::True
)
);
//
// Get the enum class object for the engine error enum
// and the ordinal for the bad parm error.
//
const TMEngEnumInfo& meciErr = meciBaseInfo.meciMEngErrors();
const tCIDLib::TCard4 c4ErrId = meciBaseInfo.c4ErrIdBadEntryParm;
//
// We need the line number of the entry point. The entry
// point is always an opcode based method implementation,
// so we can just cast to that, and then we can get the
// first line number within the implementation.
//
TMEngOpMethodImpl& methEP = *static_cast<TMEngOpMethodImpl*>
(
meciTarget.pmethFind(c2MethodId)
);
TString strErrText
(
kMEngErrs::errcEng_BadTextEPParmVal
, facCIDMacroEng()
, TCardinal(c2Id + 1UL)
, meciTarget.strClassPath()
, strClassPathForId(mepiTar.c2ClassId())
);
TMEngExceptVal mecvExcept(L"BadParm", tCIDMacroEng::EConstTypes::Const);
mecvExcept.Set
(
meciErr.c2Id()
, meciTarget.strClassPath()
, c4ErrId
, meciErr.strItemName(c4ErrId)
, strErrText
, methEP.c4FirstLineNum()
);
m_pmeehToUse->MacroException(mecvExcept, *this);
}
//
// If we are in the IDE, report we are done and return a -1 status.
// Else, throw an exception.
//
if (!m_pmedbgToUse)
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, kMEngErrs::errcEng_BadTextEPParmVal
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::BadParms
, TCardinal(c2Id + 1UL)
, meciTarget.strClassPath()
, strClassPathForId(mepiTar.c2ClassId())
);
}
m_pmedbgToUse->FinishedDbg(tCIDMacroEng::EDbgActs::Exit);
return -1;
}
}
}
catch(const TDbgExitException& excptForce)
{
if (m_pmedbgToUse)
m_pmedbgToUse->FinishedDbg(excptForce.m_eReason);
return -1;
}
catch(const TError& errToCatch)
{
Exception(errToCatch);
if (m_pmedbgToUse)
m_pmedbgToUse->FinishedDbg(tCIDMacroEng::EDbgActs::Exit);
throw;
}
catch(...)
{
UnknownException();
if (m_pmedbgToUse)
m_pmedbgToUse->FinishedDbg(tCIDMacroEng::EDbgActs::Exit);
throw;
}
// And now call the other version with the parms
return i4Run(mecvTarget, colParms, pcuctxRights);
}
tCIDLib::TInt4
TCIDMacroEngine::i4Run( TMEngClassVal& mecvTarget
, TParmList& colParms
, const TCIDUserCtx* const pcuctxRights)
{
tCIDLib::TInt4 i4Res = 0;
try
{
// Set the passed user contact while we are in here
TGFJanitor<const TCIDUserCtx*> janRights(&m_pcuctxRights, pcuctxRights);
//
// Allow derived engine classes to adjust the start object and/or
// parms before we continue.
//
AdjustStart(mecvTarget, colParms);
//
// If the temp pool is empty, then this is the first time this engine
// instance has been used, so we need to initialize the pool.
//
if (m_colTempPool.bIsEmpty())
InitTempPool();
//
// Search this class for a legal entry point. It must have particular
// name and form.
//
TMEngClassInfo& meciTarget = meciFind(mecvTarget.c2ClassId());
const tCIDLib::TCard2 c2MethodId = c2FindEntryPoint(meciTarget, 0);
// Push the return value first before any parms
PushPoolValue(tCIDMacroEng::EIntrinsics::Int4, tCIDMacroEng::EConstTypes::NonConst);
//
// Make sure we have the correct type and kind of parameters, then
// push them onto the stack. Say that they are parms, so that they
// will not get deleted when popped.
//
TMEngMethodInfo& methiTarget = meciTarget.methiFind(c2MethodId);
const tCIDLib::TCard4 c4ParmCount = colParms.c4ElemCount();
if (c4ParmCount != methiTarget.c4ParmCount())
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, kMEngErrs::errcEng_BadEntryParmCnt
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::BadParms
, meciTarget.strClassPath()
, TCardinal(methiTarget.c4ParmCount())
, TCardinal(c4ParmCount)
);
}
// We have the right number, so see if they are the right type
for (tCIDLib::TCard2 c2Id = 0; c2Id < c4ParmCount; c2Id++)
{
const TMEngParmInfo& mepiTar = methiTarget.mepiFind(c2Id);
const TMEngClassVal& mecvSrc = *colParms[c2Id];
//
// The passed value must be the same or derived from the target,
// or they must be equivalent collections with identical element types.
//
if (!bIsDerivedFrom(mecvSrc.c2ClassId(), mepiTar.c2ClassId())
&& !bAreEquivCols(mecvSrc.c2ClassId(), mepiTar.c2ClassId(), kCIDLib::True))
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, kMEngErrs::errcEng_BadEntryParmType
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::BadParms
, TCardinal(c2Id + 1UL)
, meciTarget.strClassPath()
, strClassPathForId(mepiTar.c2Id())
, strClassPathForId(mecvSrc.c2ClassId())
);
}
//
// Looks ok, so push it. Say it's a parm and say that it's a
// repush so that it's clear that we own it.
//
PushValue(colParms[c2Id], tCIDMacroEng::EStackItems::Parm, kCIDLib::True);
}
// And finally push the method call
meciPushMethodCall(meciTarget.c2Id(), c2MethodId);
//
// And invoke the indicated method on this class, then pop the method
// call item and parms off when we get back. We can do monomorphic dispatch
// here since we know the target class has the method.
//
meciTarget.Invoke(*this, mecvTarget, c2MethodId, tCIDMacroEng::EDispatch::Mono);
MultiPop(c4ParmCount + 1);
#if CID_DEBUG_ON
if (m_c4CallStackTop != 1)
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, kMEngErrs::errcEng_BadEndStackTop
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Internal
, TCardinal(m_c4CallStackTop)
);
}
#endif
// Get the return value out
i4Res = i4StackValAt(0);
// Remove the return value now
PopTop();
// Output a new line to the stream console if present and flush
if (m_pstrmConsole)
{
*m_pstrmConsole << kCIDLib::NewLn;
m_pstrmConsole->Flush();
}
// If we have a debug interface installed, post a normal exit
if (m_pmedbgToUse)
m_pmedbgToUse->FinishedDbg(tCIDMacroEng::EDbgActs::Exit);
}
catch(const TDbgExitException& excptForce)
{
if (m_pmedbgToUse)
m_pmedbgToUse->FinishedDbg(excptForce.m_eReason);
// Force a known return value
i4Res = kCIDLib::i4MinInt;
}
catch(const TExceptException&)
{
//
// If there is an error handler, and we are in the mode where we
// report macros if they aren'thandled, then report it. If we are
// in the other mode, it will already have been reported at the point
// of throw.
//
if (m_pmeehToUse && (m_eExceptReport == tCIDMacroEng::EExceptReps::NotHandled))
m_pmeehToUse->MacroException(*m_pmecvThrown, *this);
if (m_pmedbgToUse)
m_pmedbgToUse->FinishedDbg(tCIDMacroEng::EDbgActs::Exit);
// It was unhandled, so rethrow to caller
throw;
}
catch(const TError& errToCatch)
{
Exception(errToCatch);
if (m_pmedbgToUse)
m_pmedbgToUse->FinishedDbg(tCIDMacroEng::EDbgActs::Exit);
throw;
}
catch(...)
{
UnknownException();
if (m_pmedbgToUse)
m_pmedbgToUse->FinishedDbg(tCIDMacroEng::EDbgActs::Exit);
throw;
}
return i4Res;
}
// If we have a last exception, log it
tCIDLib::TVoid TCIDMacroEngine::LogLastExcept()
{
if (m_pmecvThrown)
{
facCIDMacroEng().LogMsg
(
CID_FILE
, CID_LINE
, kMEngErrs::errcRT_MacroExcept
, m_pmecvThrown->strSrcClassPath()
, tCIDLib::ESeverities::Status
, tCIDLib::EErrClasses::AppStatus
, m_pmecvThrown->strErrorName()
, TCardinal(m_pmecvThrown->c4LineNum())
);
}
}
TMEngMethodInfo&
TCIDMacroEngine::methiFind( const tCIDLib::TCard2 c2ClassId
, const tCIDLib::TCard2 c2MethodId)
{
#if CID_DEBUG_ON
CheckClassId(c2ClassId, CID_LINE);
#endif
return m_colClassesById[c2ClassId]->methiFind(c2MethodId);
}
TMEngClassInfo& TCIDMacroEngine::meciFind(const TString& strClassPath)
{
TMEngClassInfo* pmeciRet = m_colClasses.pobjFindByKey
(
strClassPath
, kCIDLib::False
);
if (!pmeciRet)
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, kMEngErrs::errcEng_ClassNotFound
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::NotFound
, strClassPath
);
}
return *pmeciRet;
}
const TMEngClassInfo&
TCIDMacroEngine::meciFind(const TString& strClassPath) const
{
const TMEngClassInfo* pmeciRet = m_colClasses.pobjFindByKey
(
strClassPath
, kCIDLib::False
);
if (!pmeciRet)
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, kMEngErrs::errcEng_ClassNotFound
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::NotFound
, strClassPath
);
}
return *pmeciRet;
}
TMEngClassInfo& TCIDMacroEngine::meciFind(const tCIDLib::TCard2 c2Id)
{
#if CID_DEBUG_ON
CheckClassId(c2Id, CID_LINE);
#endif
return *m_colClassesById[c2Id];
}
TMEngClassInfo& TCIDMacroEngine::meciFind(const tCIDMacroEng::EIntrinsics eClassType)
{
return meciFind(tCIDLib::TCard2(eClassType));
}
const TMEngClassInfo& TCIDMacroEngine::meciFind(const tCIDLib::TCard2 c2Id) const
{
#if CID_DEBUG_ON
CheckClassId(c2Id, CID_LINE);
#endif
return *m_colClassesById[c2Id];
}
const TMEngClassInfo&
TCIDMacroEngine::meciFind(const tCIDMacroEng::EIntrinsics eClassType) const
{
return meciFind(tCIDLib::TCard2(eClassType));
}
TMEngClassInfo&
TCIDMacroEngine::meciPushMethodCall(const tCIDLib::TCard2 c2ClassId
, const tCIDLib::TCard2 c2MethodId)
{
// Find the two bits we need to push
TMEngClassInfo* pmeciCalled = &meciFind(c2ClassId);
TMEngMethodInfo* pmethiCalled = &pmeciCalled->methiFind(c2MethodId);
CheckStackExpand();
// Get the top of stack item and reset it with the passed procedure
TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop];
pmecsiRet->Reset(pmeciCalled, pmethiCalled);
m_c4CallStackTop++;
// As a convenience, we return the class
return *pmeciCalled;
}
TMEngClassInfo&
TCIDMacroEngine::meciPushMethodCall(const tCIDLib::TCard2 c2ClassId
, const tCIDLib::TCard2 c2MethodId
, const TMEngClassInfo* const pmeciCaller
, const TMEngOpMethodImpl* const pmethCaller
, const TMEngMethodInfo* const pmethiCaller
, TMEngClassVal* const pmecvCaller
, const tCIDLib::TCard4 c4CallLine
, const tCIDLib::TCard4 c4CallIP)
{
// Find the two bits we need to push
TMEngClassInfo* pmeciCalled = &meciFind(c2ClassId);
TMEngMethodInfo* pmethiCalled = &pmeciCalled->methiFind(c2MethodId);
CheckStackExpand();
// Get the top of stack item and reset it with the passed procedure
TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop];
pmecsiRet->Reset
(
pmeciCalled
, pmethiCalled
, pmeciCaller
, pmethiCaller
, pmethCaller
, pmecvCaller
, c4CallLine
, c4CallIP
);
m_c4CallStackTop++;
// As a convenience, we return the class
return *pmeciCalled;
}
TMEngCallStackItem& TCIDMacroEngine::mecsiAt(const tCIDLib::TCard4 c4Index)
{
CheckStackIndex(CID_LINE, c4Index);
return *m_colCallStack[c4Index];
}
const TMEngCallStackItem&
TCIDMacroEngine::mecsiAt(const tCIDLib::TCard4 c4Index) const
{
CheckStackIndex(CID_LINE, c4Index);
return *m_colCallStack[c4Index];
}
TMEngCallStackItem& TCIDMacroEngine::mecsiTop()
{
//
// If the stack isn't empty, give them back the top item, which is one
// less than the top, because the top points at the next available
// slot.
//
CheckNotEmpty(CID_LINE);
return *m_colCallStack[m_c4CallStackTop - 1];
}
const TMEngClassVal&
TCIDMacroEngine::mecvStackAt(const tCIDLib::TCard4 c4Index) const
{
CheckStackIndex(CID_LINE, c4Index);
return m_colCallStack[c4Index]->mecvPushed();
}
TMEngClassVal& TCIDMacroEngine::mecvStackAt(const tCIDLib::TCard4 c4Index)
{
CheckStackIndex(CID_LINE, c4Index);
return m_colCallStack[c4Index]->mecvPushed();
}
const TMEngClassVal& TCIDMacroEngine::mecvStackAtTop() const
{
CheckNotEmpty(CID_LINE);
return m_colCallStack[m_c4CallStackTop - 1]->mecvPushed();
}
TMEngClassVal& TCIDMacroEngine::mecvStackAtTop()
{
CheckNotEmpty(CID_LINE);
return m_colCallStack[m_c4CallStackTop - 1]->mecvPushed();
}
//
// Provide access to any user rights context that the user code may have set
// on us. We don't care what it is, it's purely a passthrough for user code.
// It may be null if they never set one.
//
const TCIDUserCtx* TCIDMacroEngine::pcuctxRights() const
{
return m_pcuctxRights;
}
// Pop the given number of objects off the stack
tCIDLib::TVoid
TCIDMacroEngine::MultiPop(const tCIDLib::TCard4 c4Count)
{
// Check for underflow. We have to have at least the number indicated
if (m_c4CallStackTop < c4Count)
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, kMEngErrs::errcEng_CallStackUnderflow
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Underflow
);
}
// It's ok, so pop it
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
m_c4CallStackTop--;
//
// If this is a temp value, then release it back to the pool. If
// it's a local, we have to clean it up. Else, it's spoken for by
// someone and we don't have to worry. Then, clear the item to
// keep the stack readable.
//
// NOTE: If it's a repush, we don't do anything, because this
// is not the original!
//
TMEngCallStackItem* pmecsiPop = m_colCallStack[m_c4CallStackTop];
if (!pmecsiPop->bIsRepush())
{
if (pmecsiPop->eType() == tCIDMacroEng::EStackItems::TempVal)
pmecsiPop->mecvPushed().bIsUsed(kCIDLib::False);
else if (pmecsiPop->eType() == tCIDMacroEng::EStackItems::Local)
delete &pmecsiPop->mecvPushed();
}
pmecsiPop->Clear();
}
}
const TMEngClassInfo*
TCIDMacroEngine::pmeciLastMacroCaller(tCIDLib::TCard4& c4Line)
{
//
// Start at the top of the stack and work backwards till we see a
// call from a macro level class.
//
tCIDLib::TCard4 c4Index = m_c4CallStackTop;
if (!c4Index)
return nullptr;
TMEngCallStackItem* pmecsiCur = nullptr;
const TMEngClassInfo* pmeciRet = nullptr;
do
{
c4Index--;
pmecsiCur = m_colCallStack[c4Index];
if (pmecsiCur->eType() == tCIDMacroEng::EStackItems::MethodCall)
{
pmeciRet = pmecsiCur->pmeciCaller(c4Line);
if (pmeciRet)
break;
}
} while (c4Index != 0);
return pmeciRet;
}
TMEngClassInfo*
TCIDMacroEngine::pmeciLoadExternalClass(const TString& strClassPathToLoad)
{
TMEngClassInfo* pmeciRet = m_colClasses.pobjFindByKey
(
strClassPathToLoad, kCIDLib::False
);
// If already loaded, we are done
if (pmeciRet)
return pmeciRet;
//
// Ask the facility class to allow all of the registered class loaders
// to have a chance to load this class.
//
pmeciRet = facCIDMacroEng().pmeciInvokeExternalLoaders(*this, strClassPathToLoad);
if (!pmeciRet)
return pmeciRet;
//
// If this guy has any imports, then we need to recursively load them
// before we continue. And we need to do the same to it's parent class
// as well. Do the parent first, then do any imports of this class.
//
pmeciLoadExternalClass(pmeciRet->strParentClassPath());
TMEngClassInfo::TImportList::TCursor cursImports(&pmeciRet->m_colImports);
for (; cursImports; ++cursImports)
pmeciLoadExternalClass(cursImports->m_strImport);
//
// Do the base init of the class now that all it's needed class are
// loaded.
//
pmeciRet->BaseClassInit(*this);
c2AddClass(pmeciRet);
return pmeciRet;
}
TMEngClassInfo*
TCIDMacroEngine::pmeciFind( const TString& strClassPath
, const tCIDLib::TBoolean bThrowIfNot)
{
return m_colClasses.pobjFindByKey(strClassPath, bThrowIfNot);
}
const TMEngClassInfo*
TCIDMacroEngine::pmeciFind( const TString& strClassPath
, const tCIDLib::TBoolean bThrowIfNot) const
{
return m_colClasses.pobjFindByKey(strClassPath, bThrowIfNot);
}
const TMEngExceptVal& TCIDMacroEngine::mecvExceptionThrown() const
{
return *m_pmecvThrown;
}
TMEngExceptVal& TCIDMacroEngine::mecvExceptionThrown()
{
return *m_pmecvThrown;
}
//
// This method will start at the top of the stack and search downwards
// until it finds a call item, and return that item and it's stack index.
// If it doesn't find one, it returns a null pointer.
//
TMEngCallStackItem*
TCIDMacroEngine::pmecsiMostRecentCall(tCIDLib::TCard4& c4ToFill)
{
if (!m_c4CallStackTop)
{
c4ToFill = kCIDLib::c4MaxCard;
return 0;
}
tCIDLib::TCard4 c4Index = m_c4CallStackTop;
do
{
c4Index--;
TMEngCallStackItem* pmecsiCur = m_colCallStack[c4Index];
if (pmecsiCur->eType() == tCIDMacroEng::EStackItems::MethodCall)
{
c4ToFill = c4Index;
return pmecsiCur;
}
} while (c4Index > 0);
c4ToFill = kCIDLib::c4MaxCard;
return 0;
}
//
// This guy allows a new value object to be created via a class path name.
// This allows code that needs to call into macro code from C++ code to
// create value objects without us having to expose all those headers.
//
TMEngClassVal*
TCIDMacroEngine::pmecvNewFromPath( const TString& strName
, const TString& strClassPath
, const tCIDMacroEng::EConstTypes eConst)
{
// Find the class info object for the passed class
TMEngClassInfo& meciNew = meciFind(strClassPath);
return meciNew.pmecvMakeStorage(strName, *this, eConst);
}
TTextOutStream* TCIDMacroEngine::pstrmConsole()
{
#if CID_DEBUG_ON
if (!m_pstrmConsole)
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, kMEngErrs::errcDbg_NoConsoleStrm
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Internal
);
}
#endif
return m_pstrmConsole;
}
tCIDLib::TVoid TCIDMacroEngine::PopBackTo(const tCIDLib::TCard4 c4To)
{
// If already at that point, then nothing to do
if (m_c4CallStackTop == c4To)
return;
// Else the to index must be less than the current top
CheckStackIndex(CID_LINE, c4To);
// Looks ok, so let's do it
do
{
// Move down to the next used item
m_c4CallStackTop--;
//
// If this is a temp value, then release it back to the pool. If
// it's a local, we have to clean it up. Else, it's spoken for by
// someone and we don't have to worry. Then, clear the item to
// keep the stack readable.
//
// NOTE: If it's a repush, we don't do anything, because this
// is not the original!
//
TMEngCallStackItem* pmecsiPop = m_colCallStack[m_c4CallStackTop];
if (!pmecsiPop->bIsRepush())
{
if (pmecsiPop->eType() == tCIDMacroEng::EStackItems::TempVal)
pmecsiPop->mecvPushed().bIsUsed(kCIDLib::False);
else if (pmecsiPop->eType() == tCIDMacroEng::EStackItems::Local)
delete &pmecsiPop->mecvPushed();
}
pmecsiPop->Clear();
} while (m_c4CallStackTop > c4To);
}
tCIDLib::TVoid TCIDMacroEngine::PopTop()
{
// Check for underflow
CheckStackUnderflow(CID_LINE);
// It's ok, so pop it
m_c4CallStackTop--;
//
// If this is a temp value, then release it back to the pool. If
// it's a local, we have to clean it up. Else, it's spoken for by
// someone and we don't have to worry. Then, clear the item to
// keep the stack readable.
//
// NOTE: If it's a repush, we don't do anything, because this
// is not the original!
//
TMEngCallStackItem* pmecsiPop = m_colCallStack[m_c4CallStackTop];
if (!pmecsiPop->bIsRepush())
{
if (pmecsiPop->eType() == tCIDMacroEng::EStackItems::TempVal)
pmecsiPop->mecvPushed().bIsUsed(kCIDLib::False);
else if (pmecsiPop->eType() == tCIDMacroEng::EStackItems::Local)
delete &pmecsiPop->mecvPushed();
}
pmecsiPop->Clear();
}
tCIDLib::TVoid
TCIDMacroEngine::PushBoolean(const tCIDLib::TBoolean bToPush
, const tCIDMacroEng::EConstTypes eConst)
{
CheckStackExpand();
// Get a temp of this type from the pool and set it to the passed value
TMEngBooleanVal* pmecvPush = static_cast<TMEngBooleanVal*>
(
pmecvGet(tCIDMacroEng::EIntrinsics::Boolean, eConst)
);
pmecvPush->bValue(bToPush);
// Get the top of stack item and reset it with the passed temp value
TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop];
pmecsiRet->Reset(pmecvPush, tCIDMacroEng::EStackItems::TempVal);
m_c4CallStackTop++;
}
tCIDLib::TVoid
TCIDMacroEngine::PushCard1( const tCIDLib::TCard1 c1ToPush
, const tCIDMacroEng::EConstTypes eConst)
{
CheckStackExpand();
// Get a temp of this type from the pool and set it to the passed value
TMEngCard1Val* pmecvPush = static_cast<TMEngCard1Val*>
(
pmecvGet(tCIDMacroEng::EIntrinsics::Card1, eConst)
);
pmecvPush->c1Value(c1ToPush);
// Get the top of stack item and reset it with the passed temp value
TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop];
pmecsiRet->Reset(pmecvPush, tCIDMacroEng::EStackItems::TempVal);
m_c4CallStackTop++;
}
tCIDLib::TVoid
TCIDMacroEngine::PushCard2( const tCIDLib::TCard2 c2ToPush
, const tCIDMacroEng::EConstTypes eConst)
{
CheckStackExpand();
// Get a temp of this type from the pool and set it to the passed value
TMEngCard2Val* pmecvPush = static_cast<TMEngCard2Val*>
(
pmecvGet(tCIDMacroEng::EIntrinsics::Card2, eConst)
);
pmecvPush->c2Value(c2ToPush);
// Get the top of stack item and reset it with the passed temp value
TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop];
pmecsiRet->Reset(pmecvPush, tCIDMacroEng::EStackItems::TempVal);
m_c4CallStackTop++;
}
tCIDLib::TVoid
TCIDMacroEngine::PushCard4( const tCIDLib::TCard4 c4ToPush
, const tCIDMacroEng::EConstTypes eConst)
{
CheckStackExpand();
// Get a temp of this type from the pool and set it to the passed value
TMEngCard4Val* pmecvPush = static_cast<TMEngCard4Val*>
(
pmecvGet(tCIDMacroEng::EIntrinsics::Card4, eConst)
);
pmecvPush->c4Value(c4ToPush);
// Get the top of stack item and reset it with the passed temp value
TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop];
pmecsiRet->Reset(pmecvPush, tCIDMacroEng::EStackItems::TempVal);
m_c4CallStackTop++;
}
tCIDLib::TVoid
TCIDMacroEngine::PushCard8( const tCIDLib::TCard8 c8ToPush
, const tCIDMacroEng::EConstTypes eConst)
{
CheckStackExpand();
// Get a temp of this type from the pool and set it to the passed value
TMEngCard8Val* pmecvPush = static_cast<TMEngCard8Val*>
(
pmecvGet(tCIDMacroEng::EIntrinsics::Card8, eConst)
);
pmecvPush->c8Value(c8ToPush);
// Get the top of stack item and reset it with the passed temp value
TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop];
pmecsiRet->Reset(pmecvPush, tCIDMacroEng::EStackItems::TempVal);
m_c4CallStackTop++;
}
tCIDLib::TVoid
TCIDMacroEngine::PushChar( const tCIDLib::TCh chToPush
, const tCIDMacroEng::EConstTypes eConst)
{
CheckStackExpand();
// Get a temp of this type from the pool and set it to the passed value
TMEngCharVal* pmecvPush = static_cast<TMEngCharVal*>
(
pmecvGet(tCIDMacroEng::EIntrinsics::Char, eConst)
);
pmecvPush->chValue(chToPush);
// Get the top of stack item and reset it with the passed temp value
TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop];
pmecsiRet->Reset(pmecvPush, tCIDMacroEng::EStackItems::TempVal);
m_c4CallStackTop++;
}
tCIDLib::TVoid
TCIDMacroEngine::PushEnum( const tCIDLib::TCard2 c2ClassId
, const tCIDLib::TCard2 c2OrdValue
, const tCIDMacroEng::EConstTypes eConst)
{
CheckStackExpand();
// Get a temp of this type from the pool and set it to the passed value
TMEngEnumVal* pmecvPush = static_cast<TMEngEnumVal*>
(
pmecvGet(c2ClassId, eConst)
);
pmecvPush->c4Ordinal(c2OrdValue);
// Get the top of stack item and reset it with the passed temp value
TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop];
pmecsiRet->Reset(pmecvPush, tCIDMacroEng::EStackItems::TempVal);
m_c4CallStackTop++;
}
//
// This one handles a special case scenario, which pushes a thrown exception
// upon entry to a Catch block. It just refers to a magic value object that
// is a member of this class, since it must potentially exist all the way
// up the call stack.
//
tCIDLib::TVoid TCIDMacroEngine::PushException()
{
CheckStackExpand();
// Get the top of stack item and reset it with the passed temp value
TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop];
pmecsiRet->Reset(m_pmecvThrown, tCIDMacroEng::EStackItems::Exception);
m_c4CallStackTop++;
}
tCIDLib::TVoid
TCIDMacroEngine::PushFloat4( const tCIDLib::TFloat4 f4ToPush
, const tCIDMacroEng::EConstTypes eConst)
{
CheckStackExpand();
// Get a temp of this type from the pool and set it to the passed value
TMEngFloat4Val* pmecvPush = static_cast<TMEngFloat4Val*>
(
pmecvGet(tCIDMacroEng::EIntrinsics::Float4, eConst)
);
pmecvPush->f4Value(f4ToPush);
// Get the top of stack item and reset it with the passed temp value
TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop];
pmecsiRet->Reset(pmecvPush, tCIDMacroEng::EStackItems::TempVal);
m_c4CallStackTop++;
}
tCIDLib::TVoid
TCIDMacroEngine::PushFloat8( const tCIDLib::TFloat8 f8ToPush
, const tCIDMacroEng::EConstTypes eConst)
{
CheckStackExpand();
// Get a temp of this type from the pool and set it to the passed value
TMEngFloat8Val* pmecvPush = static_cast<TMEngFloat8Val*>
(
pmecvGet(tCIDMacroEng::EIntrinsics::Float8, eConst)
);
pmecvPush->f8Value(f8ToPush);
// Get the top of stack item and reset it with the passed temp value
TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop];
pmecsiRet->Reset(pmecvPush, tCIDMacroEng::EStackItems::TempVal);
m_c4CallStackTop++;
}
tCIDLib::TVoid
TCIDMacroEngine::PushInt1( const tCIDLib::TInt1 i1ToPush
, const tCIDMacroEng::EConstTypes eConst)
{
CheckStackExpand();
// Get a temp of this type from the pool and set it to the passed value
TMEngInt1Val* pmecvPush = static_cast<TMEngInt1Val*>
(
pmecvGet(tCIDMacroEng::EIntrinsics::Int1, eConst)
);
pmecvPush->i1Value(i1ToPush);
// Get the top of stack item and reset it with the passed temp value
TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop];
pmecsiRet->Reset(pmecvPush, tCIDMacroEng::EStackItems::TempVal);
m_c4CallStackTop++;
}
tCIDLib::TVoid
TCIDMacroEngine::PushInt2( const tCIDLib::TInt2 i2ToPush
, const tCIDMacroEng::EConstTypes eConst)
{
CheckStackExpand();
// Get a temp of this type from the pool and set it to the passed value
TMEngInt2Val* pmecvPush = static_cast<TMEngInt2Val*>
(
pmecvGet(tCIDMacroEng::EIntrinsics::Int2, eConst)
);
pmecvPush->i2Value(i2ToPush);
// Get the top of stack item and reset it with the passed temp value
TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop];
pmecsiRet->Reset(pmecvPush, tCIDMacroEng::EStackItems::TempVal);
m_c4CallStackTop++;
}
tCIDLib::TVoid
TCIDMacroEngine::PushInt4( const tCIDLib::TInt4 i4ToPush
, const tCIDMacroEng::EConstTypes eConst)
{
CheckStackExpand();
// Get a temp of this type from the pool and set it to the passed value
TMEngInt4Val* pmecvPush = static_cast<TMEngInt4Val*>
(
pmecvGet(tCIDMacroEng::EIntrinsics::Int4, eConst)
);
pmecvPush->i4Value(i4ToPush);
// Get the top of stack item and reset it with the passed temp value
TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop];
pmecsiRet->Reset(pmecvPush, tCIDMacroEng::EStackItems::TempVal);
m_c4CallStackTop++;
}
tCIDLib::TVoid
TCIDMacroEngine::PushPoolValue( const TString& strClassPath
, const tCIDMacroEng::EConstTypes eConst)
{
CheckStackExpand();
// Look up the class id for this guy and use that to get a temp
TMEngClassVal* pmecvPush = pmecvGet(meciFind(strClassPath).c2Id(), eConst);
TJanitor<TMEngClassVal> janPush(pmecvPush);
// Get the top of stack item and reset it with the passed temp value
TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop];
pmecsiRet->Reset(janPush.pobjOrphan(), tCIDMacroEng::EStackItems::TempVal);
m_c4CallStackTop++;
}
tCIDLib::TVoid
TCIDMacroEngine::PushPoolValue( const TString& strName
, const tCIDLib::TCard2 c2TypeId
, const tCIDMacroEng::EConstTypes eConst)
{
CheckStackExpand();
// Look up the class id for this guy and use that to get a temp
TMEngClassVal* pmecvPush = pmecvGet
(
strName
, meciFind(c2TypeId).c2Id()
, eConst
);
TJanitor<TMEngClassVal> janPush(pmecvPush);
// Get the top of stack item and reset it with the passed temp value
TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop];
pmecsiRet->Reset(janPush.pobjOrphan(), tCIDMacroEng::EStackItems::TempVal);
m_c4CallStackTop++;
}
tCIDLib::TVoid
TCIDMacroEngine::PushPoolValue( const TString& strName
, const tCIDMacroEng::EIntrinsics eType
, const tCIDMacroEng::EConstTypes eConst)
{
PushPoolValue(strName, tCIDLib::TCard2(eType), eConst);
}
tCIDLib::TVoid
TCIDMacroEngine::PushPoolValue( const tCIDLib::TCard2 c2Id
, const tCIDMacroEng::EConstTypes eConst)
{
CheckStackExpand();
// Get a value from the pool, of the type passed
TMEngClassVal* pmecvPush = pmecvGet(c2Id, eConst);
TJanitor<TMEngClassVal> janPush(pmecvPush);
// Get the top of stack item and reset it with the passed temp value
TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop];
pmecsiRet->Reset(janPush.pobjOrphan(), tCIDMacroEng::EStackItems::TempVal);
m_c4CallStackTop++;
}
tCIDLib::TVoid
TCIDMacroEngine::PushPoolValue( const tCIDMacroEng::EIntrinsics eType
, const tCIDMacroEng::EConstTypes eConst)
{
PushPoolValue(tCIDLib::TCard2(eType), eConst);
}
tCIDLib::TVoid
TCIDMacroEngine::PushString(const TString& strToPush
, const tCIDMacroEng::EConstTypes eConst)
{
CheckStackExpand();
// Get a temp of this type from the pool and set it to the passed value
TMEngStringVal* pmecvPush = static_cast<TMEngStringVal*>
(
pmecvGet(tCIDMacroEng::EIntrinsics::String, eConst)
);
pmecvPush->strValue(strToPush);
// Get the top of stack item and reset it with the passed temp value
TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop];
pmecsiRet->Reset(pmecvPush, tCIDMacroEng::EStackItems::TempVal);
m_c4CallStackTop++;
}
tCIDLib::TVoid
TCIDMacroEngine::PushStringList(const TVector<TString>& colToPush
, const tCIDMacroEng::EConstTypes eConst)
{
CheckStackExpand();
// Get a temp of this type from the pool and set it to the passed value
TMEngStrListVal* pmecvPush = static_cast<TMEngStrListVal*>
(
pmecvGet(tCIDMacroEng::EIntrinsics::StringList, eConst)
);
pmecvPush->Reset(colToPush, kCIDLib::True);
// Get the top of stack item and reset it with the passed temp value
TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop];
pmecsiRet->Reset(pmecvPush, tCIDMacroEng::EStackItems::TempVal);
m_c4CallStackTop++;
}
tCIDLib::TVoid
TCIDMacroEngine::PushTime( const TTime& tmToPush
, const tCIDMacroEng::EConstTypes eConst)
{
CheckStackExpand();
// Get a temp of this type from the pool and set it to the passed value
TMEngTimeVal* pmecvPush = static_cast<TMEngTimeVal*>
(
pmecvGet(tCIDMacroEng::EIntrinsics::Time, eConst)
);
pmecvPush->tmValue(tmToPush);
// Get the top of stack item and reset it with the passed temp value
TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop];
pmecsiRet->Reset(pmecvPush, tCIDMacroEng::EStackItems::TempVal);
m_c4CallStackTop++;
}
tCIDLib::TVoid
TCIDMacroEngine::PushTry(const tCIDLib::TCard4 c4ToPush)
{
CheckStackExpand();
// Get the top of stack item and reset it with the passed value
TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop];
pmecsiRet->Reset(tCIDMacroEng::EStackItems::Try, c4ToPush);
m_c4CallStackTop++;
}
tCIDLib::TVoid
TCIDMacroEngine::PushValue( TMEngClassVal* const pmecvPushed
, const tCIDMacroEng::EStackItems eType
, const tCIDLib::TBoolean bRepush)
{
CheckStackExpand();
// Get the top of stack item and reset it with the passed value
TMEngCallStackItem* pmecsiRet = m_colCallStack[m_c4CallStackTop];
pmecsiRet->Reset(pmecvPushed, eType);
pmecsiRet->bIsRepush(bRepush);
m_c4CallStackTop++;
}
//
// This is mainly to support packaging of macros/drivers. We will find
// all the loaded (i.e. referenced) that are in the indicated scope.
//
tCIDLib::TVoid
TCIDMacroEngine::QueryScopeClasses( const TString& strScope
, tCIDLib::TStrCollect& colToFill) const
{
colToFill.RemoveAll();
//
// We can start past the intrinsic classes, which are always there and
// always first.
//
const tCIDLib::TCard4 c4Count = m_colClassesById.c4ElemCount();
tCIDLib::TCard4 c4Index = tCIDLib::TCard2(tCIDMacroEng::EIntrinsics::Count);
while (c4Index < c4Count)
{
const TMEngClassInfo* pmeciCur = m_colClassesById[c4Index];
if (pmeciCur->strBasePath().eCompareI(strScope) == tCIDLib::ESortComps::Equal)
colToFill.objAdd(pmeciCur->strClassPath());
c4Index++;
}
}
//
// Repush the value at the indicated stack index. It's marked as being
// repushed, so that when it's popped it won't be destroyed becasue it's
// not the original.
//
tCIDLib::TVoid TCIDMacroEngine::RepushAt(const tCIDLib::TCard4 c4Index)
{
CheckStackExpand();
// Make sure it's a value item
TMEngCallStackItem& mecsiToPush = mecsiAt(c4Index);
const tCIDMacroEng::EStackItems eType = mecsiToPush.eType();
if (eType == tCIDMacroEng::EStackItems::MethodCall)
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, kMEngErrs::errcEng_RepushMethod
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Internal
);
}
// Get the value from this item
TMEngClassVal* pmecvToPush = &mecsiToPush.mecvPushed();
//
// Push it again, with the same type. But, set the 'repush' flag. This
// lets us know when we pop that we never have to worry about cleanup,
// because this isn't the real guy
//
PushValue(pmecvToPush, mecsiToPush.eType(), kCIDLib::True);
}
//
// Reset the macro engine. We make sure the stack is cleared, and we clean
// up any objects in pools and globals, and remove all classes other than
// the instrinsic ones.
//
// Note that we don't reset the unique id counter. We just let it continue
// to run upwards, for increased safety.
//
tCIDLib::TVoid TCIDMacroEngine::Reset()
{
// Make sure that the call stack get's emptied
try
{
m_colCallStack.RemoveAll();
}
catch(TError& errToCatch)
{
if (!errToCatch.bLogged())
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, kMEngErrs::errcEng_ResetErr
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Internal
);
}
//
// Now clean up the other stuff. Note that we don't remove the built
// in classes from the class list, since they can remain the same
// always, and it significantly improves performance. We only remove
// those when the engine is cleaned up. Passing false to the cleanup
// method does this.
//
Cleanup(kCIDLib::False);
m_c4CurLine = 0;
m_c4CallStackTop = 0;
//
// Set this to the next available one after the builtins, because we
// didn't remove those!!!
//
m_c2NextClassId = m_c2ArrayId + 1;
}
// If we have an error handler and an exception, send it to the error handler
tCIDLib::TVoid TCIDMacroEngine::ReportLastExcept()
{
if (m_pmeehToUse && m_pmecvThrown)
m_pmeehToUse->MacroException(*m_pmecvThrown, *this);
}
const TString&
TCIDMacroEngine::strClassPathForId( const tCIDLib::TCard2 c2Id
, const tCIDLib::TBoolean bThrowIfNot) const
{
if (c2Id >= m_colClassesById.c4ElemCount())
{
if (bThrowIfNot)
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, kMEngErrs::errcClass_BadId
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Index
, TCardinal(c2Id)
, TCardinal(m_colClassesById.c4ElemCount())
);
}
return TFacCIDMacroEng::strUnknownClass;
}
return m_colClassesById[c2Id]->strClassPath();
}
const TString&
TCIDMacroEngine::strClassPathForId( const tCIDMacroEng::EIntrinsics eType
, const tCIDLib::TBoolean bThrowIfNot) const
{
return strClassPathForId(tCIDLib::TCard2(eType), bThrowIfNot);
}
// Get or set the special dynamic type reference value
const TString& TCIDMacroEngine::strSpecialDynRef() const
{
return m_strSpecialDynRef;
}
const TString& TCIDMacroEngine::strSpecialDynRef(const TString& strToSet)
{
m_strSpecialDynRef = strToSet;
return m_strSpecialDynRef;
}
// Get a string object at the indicated index on the stack
const TString&
TCIDMacroEngine::strStackValAt( const tCIDLib::TCard4 c4Index
, const tCIDLib::TBoolean bCheckType) const
{
const TMEngClassVal& mecvVal = mecsiAt(c4Index).mecvPushed();
if (bCheckType)
CheckItemType(mecvVal.c2ClassId(), tCIDMacroEng::EIntrinsics::String, CID_LINE, c4Index);
return static_cast<const TMEngStringVal&>(mecvVal).strValue();
}
// Let's the application give us an output console stream to use
tCIDLib::TVoid TCIDMacroEngine::SetConsole(TTextOutStream* const pstrmToUse)
{
// We don't own these console streams, so just overwrite any previous
m_pstrmConsole = pstrmToUse;
}
// Let's the application give us a debug handler
tCIDLib::TVoid
TCIDMacroEngine::SetDbgHandler(MMEngDebugIntf* const pmedbgToUse)
{
// We don't own these console streams, so just overwrite any previous
m_pmedbgToUse = pmedbgToUse;
}
tCIDLib::TVoid
TCIDMacroEngine::SetErrHandler(MMEngErrHandler* const pmeehToUse)
{
// We don't own these console streams, so just overwrite any previous
m_pmeehToUse = pmeehToUse;
}
tCIDLib::TVoid
TCIDMacroEngine::SetException( const tCIDLib::TCard2 c2ErrClassId
, const TString& strSrcClassPath
, const tCIDLib::TCard4 c4ErrorNum
, const TString& strErrorName
, const TString& strErrorText
, const tCIDLib::TCard4 c4LineNum)
{
// If we've not created the object yet, then do it
if (!m_pmecvThrown)
m_pmecvThrown = new TMEngExceptVal(L"$Exception$", tCIDMacroEng::EConstTypes::Const);
// Set up the exception info
m_pmecvThrown->Set
(
c2ErrClassId
, strSrcClassPath
, c4ErrorNum
, strErrorName
, strErrorText
, c4LineNum
);
//
// If we have a handler, and the exception reporting style is to report
// at the point of throw, let it know about this one now.
//
if (m_pmeehToUse && (m_eExceptReport == tCIDMacroEng::EExceptReps::AtThrow))
m_pmeehToUse->MacroException(*m_pmecvThrown, *this);
}
tCIDLib::TVoid
TCIDMacroEngine::SetFileResolver(MMEngFileResolver* const pmefrToUse)
{
// We don't own these, so just overwrite any previous
m_pmefrToUse = pmefrToUse;
}
//
// When the TTime class' Sleep method is called, if it's longer than a
// second or so, then this method will be called and we'll do it in chunks
// and call the debug interface each time, so that the debugger can get
// us to stop if the user wants us to.
//
tCIDLib::TVoid TCIDMacroEngine::Sleep(const tCIDLib::TCard4 c4Millis)
{
if ((c4Millis > 1500) && m_pmedbgToUse)
{
// Do 500ms at a time
tCIDLib::TCard4 c4Count = 0;
while (c4Count < c4Millis)
{
tCIDLib::TCard4 c4ThisTime = 500;
if (c4Count + c4ThisTime > c4Millis)
c4ThisTime = c4Millis - c4Count;
c4Count += c4ThisTime;
TThread::Sleep(c4ThisTime);
if (!m_pmedbgToUse->bSleepTest())
break;
}
}
else
{
//
// Just do a regular sleep, though still using the thread specific
// one that will watch for lower level CIDLib thread stop requests.
//
TThread::pthrCaller()->bSleep(c4Millis);
}
}
// Get the time object at the indicated position on the stack
const TTime&
TCIDMacroEngine::tmStackValAt( const tCIDLib::TCard4 c4Index
, const tCIDLib::TBoolean bCheckType) const
{
const TMEngClassVal& mecvVal = mecsiAt(c4Index).mecvPushed();
if (bCheckType)
CheckItemType(mecvVal.c2ClassId(), tCIDMacroEng::EIntrinsics::Time, CID_LINE, c4Index);
return static_cast<const TMEngTimeVal&>(mecvVal).tmValue();
}
tCIDLib::TVoid TCIDMacroEngine::UnknownException()
{
// If we have a handler, let it know about this one
if (m_pmeehToUse)
m_pmeehToUse->UnknownException(*this);
}
tCIDLib::TVoid
TCIDMacroEngine::ValidateCallFrame( const TMEngClassVal& mecvInstance
, const tCIDLib::TCard2 c2MethodId) const
{
// The call stack obviously cannot be empty
if (!m_c4CallStackTop)
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, kMEngErrs::errcEng_EmptyCallStack
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::NotReady
);
}
// Get the class info object and method object
const TMEngClassInfo& meciTarget = meciFind(mecvInstance.c2ClassId());
const TMEngMethodInfo& methiTarget = meciTarget.methiFind(c2MethodId);
// The top item must be a call item
const TMEngCallStackItem* pmecsiCur = m_colCallStack[m_c4CallStackTop - 1];
if (pmecsiCur->eType() != tCIDMacroEng::EStackItems::MethodCall)
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, kMEngErrs::errcEng_BadCallFrame
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Format
);
}
//
// And now make sure that we have enough stack items to make a valid
// call frame for this method. It has to be one for the call itself,
// one for the return value, and the number of parms the method has.
//
const tCIDLib::TCard4 c4ParmCnt = methiTarget.c4ParmCount();
if (m_c4CallStackTop < 2 + c4ParmCnt)
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, kMEngErrs::errcEng_BadCallFrame
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Format
);
}
// Check the return type
const TMEngClassVal& mecvRet = mecvStackAt(m_c4CallStackTop - (c4ParmCnt + 2));
if (methiTarget.c2RetClassId() != mecvRet.c2ClassId())
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, kMEngErrs::errcMeth_RetType
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Format
, methiTarget.strName()
, strClassPathForId(methiTarget.c2RetClassId())
, strClassPathForId(mecvRet.c2ClassId())
);
}
// Move down to the first parm and start working up
for (tCIDLib::TCard2 c2Id = 0; c2Id < c4ParmCnt; c2Id++)
{
// Get the current parameter info object
const TMEngParmInfo& mepiCur = methiTarget.mepiFind(c2Id);
//
// And get the stack value for this object. Note that we add one
// because the stack top is actually pointing at the next available
// slot.
//
const TMEngClassVal& mecvCur = mecvStackAt
(
(m_c4CallStackTop - (c4ParmCnt + 1)) + c2Id
);
//
// Make sure that the value we have is of a class equal to or derived
// from the parameter class, or an equiv collection (in which the element
// type of the passed collection is at least derived from the element type
// of the parameter.
//
if (!bIsDerivedFrom(mecvCur.c2ClassId(), mepiCur.c2ClassId())
&& !bAreEquivCols(mepiCur.c2ClassId(), mecvCur.c2ClassId(), kCIDLib::False))
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, CID_LINE
, kMEngErrs::errcMeth_ParmType
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Format
, methiTarget.strName()
, TCardinal(c2Id + 1UL)
, strClassPathForId(mepiCur.c2ClassId())
, strClassPathForId(mecvCur.c2ClassId())
);
}
}
}
// ---------------------------------------------------------------------------
// TCIDMacroEngine: Protected, virtual methods
// ---------------------------------------------------------------------------
tCIDLib::TVoid TCIDMacroEngine::AdjustStart(TMEngClassVal&, TParmList&)
{
// Default empty implementation
}
// ---------------------------------------------------------------------------
// TCIDMacroEngine: Private, non-virtual methods
// ---------------------------------------------------------------------------
tCIDLib::TVoid
TCIDMacroEngine::CheckClassId(const tCIDLib::TCard2 c2Id
, const tCIDLib::TCard4 c4Line) const
{
if (c2Id >= m_colClassesById.c4ElemCount())
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, c4Line
, kMEngErrs::errcEng_BadClassId
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::NotFound
, TCardinal(c2Id)
, TCardinal(m_colClassesById.c4ElemCount())
);
}
}
tCIDLib::TVoid
TCIDMacroEngine::CheckNotEmpty(const tCIDLib::TCard4 c4Line) const
{
if (!m_c4CallStackTop)
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, c4Line
, kMEngErrs::errcEng_EmptyCallStack
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Index
);
}
}
tCIDLib::TVoid TCIDMacroEngine::CheckStackExpand()
{
//
// If our stack top indicates that there are unused items on the stack
// which have been allocated, then take one of those. Else, we need to
// allocate another one. If this goes over the current alloc, then we
// will cause it to expand it's allocation.
//
if (m_c4CallStackTop >= m_colCallStack.c4ElemCount())
m_colCallStack.Add(new TMEngCallStackItem);
}
tCIDLib::TVoid
TCIDMacroEngine::CheckStackIndex( const tCIDLib::TCard4 c4Line
, const tCIDLib::TCard4 c4ToCheck) const
{
if (c4ToCheck >= m_c4CallStackTop)
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, c4Line
, kMEngErrs::errcEng_BadStackIndex
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Index
, TCardinal(c4ToCheck)
, TCardinal(m_c4CallStackTop)
);
}
}
tCIDLib::TVoid
TCIDMacroEngine::CheckItemType( const tCIDLib::TCard2 c2TypeId
, const tCIDLib::TCard2 c2ExpectedId
, const tCIDLib::TCard4 c4Line
, const tCIDLib::TCard4 c4Index) const
{
if (c2TypeId != c2ExpectedId)
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, c4Line
, kMEngErrs::errcEng_WrongStackType
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::TypeMatch
, strClassPathForId(c2ExpectedId)
, TCardinal(c4Index)
, strClassPathForId(c2TypeId)
);
}
}
tCIDLib::TVoid
TCIDMacroEngine::CheckItemType( const tCIDLib::TCard2 c2TypeId
, const tCIDMacroEng::EIntrinsics eType
, const tCIDLib::TCard4 c4Line
, const tCIDLib::TCard4 c4Index) const
{
CheckItemType(c2TypeId, tCIDLib::TCard2(eType), c4Line, c4Index);
}
tCIDLib::TVoid
TCIDMacroEngine::CheckStackUnderflow(const tCIDLib::TCard4 c4Line) const
{
if (!m_c4CallStackTop)
{
facCIDMacroEng().ThrowErr
(
CID_FILE
, c4Line
, kMEngErrs::errcEng_CallStackUnderflow
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Underflow
);
}
}
tCIDLib::TVoid
TCIDMacroEngine::FormatAFrame( TTextOutStream& strmTarget
, const tCIDLib::TCard4 c4CallInd)
{
// Dislay the return type, class name and method name
const TMEngMethodInfo& methiCur = m_colCallStack[c4CallInd]->methiCalled();
const TMEngClassInfo& meciCur = m_colCallStack[c4CallInd]->meciCalled();
strmTarget << meciCur.strClassPath() << kCIDLib::chPeriod
<< methiCur.strName()
<< kCIDLib::chOpenParen;
//
// Handle the parameters now, if any. We have to go down to the first
// parameter and work our way back up.
//
tCIDLib::TCard4 c4ParmStack = c4CallInd - methiCur.c4ParmCount();
tCIDLib::TCard2 c2ParmId = 0;
while (c4ParmStack < c4CallInd)
{
// Get the description of the parameter and the type and value
const TMEngParmInfo& mepiCur = methiCur.mepiFind(c2ParmId);
const TMEngClassInfo& meciCur2 = *m_colClassesById[mepiCur.c2ClassId()];
strmTarget << mepiCur.eDir() << kCIDLib::chSpace
<< meciCur2.strClassPath() << kCIDLib::chSpace
<< mepiCur.strName();
c4ParmStack++;
c2ParmId++;
if (c4ParmStack < c4CallInd)
strmTarget << kCIDLib::chComma;
}
// Close off the parms and put out the return type
strmTarget << kCIDLib::chCloseParen
<< L" Returns "
<< strClassPathForId(methiCur.c2RetClassId(), kCIDLib::False);
}
tCIDLib::TVoid TCIDMacroEngine::InitTempPool()
{
const tCIDLib::TCard4 c4Count = m_colClasses.c4ElemCount();
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
m_colTempPool.objAdd
(
TCntValList(new tCIDMacroEng::TClassValList(tCIDLib::EAdoptOpts::Adopt, 32))
);
}
}
//
// These two methods provide a temp pool that is used by the methods above
// that allow the caller to push temps onto the stack. The first one takes
// a name, but generally it will just be an empty string since temps usually
// don't need a name.
//
// The second version just calls the first and passes that empty name.
//
TMEngClassVal*
TCIDMacroEngine::pmecvGet( const TString& strName
, const tCIDLib::TCard2 c2ClassId
, const tCIDMacroEng::EConstTypes eConst)
{
//
// Get the list for temp items with this class id. This is actually a
// counted pointer to the type list for this id.
//
TCntValList& cptrList = m_colTempPool[c2ClassId];
//
// Get the actual counted collection out of it, and search this list for
// an available item.
//
tCIDMacroEng::TClassValList& colList = *cptrList;
const tCIDLib::TCard4 c4Count = colList.c4ElemCount();
tCIDLib::TCard4 c4Index = 0;
TMEngClassVal* pmecvRet = nullptr;
for (; c4Index < c4Count; c4Index++)
{
pmecvRet = colList[c4Index];
if (!pmecvRet->bIsUsed())
break;
}
//
// If we didn't find one, then create one and add it to this list. Else,
// force the passed const type on the one we took from the pool.
//
if (c4Index == c4Count)
{
pmecvRet = meciFind(c2ClassId).pmecvMakeStorage(strName, *this, eConst);
colList.Add(pmecvRet);
}
else
{
pmecvRet->ForceConstType(eConst);
}
// Mark this one used, and return it
pmecvRet->bIsUsed(kCIDLib::True);
return pmecvRet;
}
TMEngClassVal*
TCIDMacroEngine::pmecvGet( const TString& strName
, const tCIDMacroEng::EIntrinsics eType
, const tCIDMacroEng::EConstTypes eConst)
{
return pmecvGet(strName, tCIDLib::TCard2(eType), eConst);
}
TMEngClassVal*
TCIDMacroEngine::pmecvGet( const tCIDLib::TCard2 c2ClassId
, const tCIDMacroEng::EConstTypes eConst)
{
return pmecvGet(TString::strEmpty(), c2ClassId, eConst);
}
TMEngClassVal*
TCIDMacroEngine::pmecvGet( const tCIDMacroEng::EIntrinsics eType
, const tCIDMacroEng::EConstTypes eConst)
{
return pmecvGet(TString::strEmpty(), tCIDLib::TCard2(eType), eConst);
}
//
// We have to deal with a few circular dependencies here, and theintrinsics
// MUST be added so that their ids match up with the EIntrinsicIds enum!
//
// So, we do a deferred add of each of the intrinsic classes, then go back
// and initalize them. This insures that none of their nested classes get
// created until we have them all added. Otherwise, their nested
// classes would get the indices out of sync.
//
tCIDLib::TVoid TCIDMacroEngine::RegisterBuiltInClasses()
{
//
// Do a deferred add of all of the intrinsics, in the required order.
// This will just get them into the by name and by id lists and with
// the right ids. We can then go back and initialize them in their
// order of dependency.
//
TMEngClassInfo* pmeciObj = new TMEngObjectInfo(*this);
c2AddClassDefer(pmeciObj);
TMEngClassInfo* pmeciVoid = new TMEngVoidInfo(*this);
c2AddClassDefer(pmeciVoid);
TMEngClassInfo* pmeciOStrm = new TMEngTextOutStreamInfo(*this);
c2AddClassDefer(pmeciOStrm);
TMEngClassInfo* pmeciFmt = new TMEngFormattableInfo(*this);
c2AddClassDefer(pmeciFmt);
TMEngClassInfo* pmeciEnum = new TMEngEnumInfo(*this, L"Enum", L"MEng", L"MEng.Formattable", 1);
c2AddClassDefer(pmeciEnum);
TMEngClassInfo* pmeciBaseInfo = new TMEngBaseInfoInfo(*this);
c2AddClassDefer(pmeciBaseInfo);
TMEngClassInfo* pmeciBool = new TMEngBooleanInfo(*this);
c2AddClassDefer(pmeciBool);
TMEngClassInfo* pmeciChar = new TMEngCharInfo(*this);
c2AddClassDefer(pmeciChar);
TMEngClassInfo* pmeciStr = new TMEngStringInfo(*this);
c2AddClassDefer(pmeciStr);
TMEngClassInfo* pmeciCard1 = new TMEngCard1Info(*this);
c2AddClassDefer(pmeciCard1);
TMEngClassInfo* pmeciCard2 = new TMEngCard2Info(*this);
c2AddClassDefer(pmeciCard2);
TMEngClassInfo* pmeciCard4 = new TMEngCard4Info(*this);
c2AddClassDefer(pmeciCard4);
TMEngClassInfo* pmeciCard8 = new TMEngCard8Info(*this);
c2AddClassDefer(pmeciCard8);
TMEngClassInfo* pmeciFloat4 = new TMEngFloat4Info(*this);
c2AddClassDefer(pmeciFloat4);
TMEngClassInfo* pmeciFloat8 = new TMEngFloat8Info(*this);
c2AddClassDefer(pmeciFloat8);
TMEngClassInfo* pmeciInt1 = new TMEngInt1Info(*this);
c2AddClassDefer(pmeciInt1);
TMEngClassInfo* pmeciInt2 = new TMEngInt2Info(*this);
c2AddClassDefer(pmeciInt2);
TMEngClassInfo* pmeciInt4 = new TMEngInt4Info(*this);
c2AddClassDefer(pmeciInt4);
TMEngClassInfo* pmeciTime = new TMEngTimeInfo(*this);
c2AddClassDefer(pmeciTime);
TMEngClassInfo* pmeciStrList = new TMEngStrListInfo(*this);
c2AddClassDefer(pmeciStrList);
TMEngClassInfo* pmeciExcept = new TMEngExceptInfo(*this);
c2AddClassDefer(pmeciExcept);
TMEngClassInfo* pmeciMemBuf = new TMEngMemBufInfo(*this);
c2AddClassDefer(pmeciMemBuf);
TMEngClassInfo* pmeciStrOS = new TMEngStringOutStreamInfo(*this);
c2AddClassDefer(pmeciStrOS);
//
// Do the init phase, which must be done in order of derivation, so
// formattable before any of the formattable classes, and base text
// out stream before other text out streams, and so on.
//
pmeciObj->BaseClassInit(*this);
pmeciObj->Init(*this);
pmeciVoid->BaseClassInit(*this);
pmeciVoid->Init(*this);
pmeciFmt->BaseClassInit(*this);
pmeciFmt->Init(*this);
pmeciEnum->BaseClassInit(*this);
pmeciEnum->Init(*this);
pmeciBaseInfo->BaseClassInit(*this);
pmeciBaseInfo->Init(*this);
pmeciBool->BaseClassInit(*this);
pmeciBool->Init(*this);
pmeciChar->BaseClassInit(*this);
pmeciChar->Init(*this);
pmeciCard1->BaseClassInit(*this);
pmeciCard1->Init(*this);
pmeciCard2->BaseClassInit(*this);
pmeciCard2->Init(*this);
pmeciCard4->BaseClassInit(*this);
pmeciCard4->Init(*this);
pmeciCard8->BaseClassInit(*this);
pmeciCard8->Init(*this);
pmeciStr->BaseClassInit(*this);
pmeciStr->Init(*this);
pmeciFloat4->BaseClassInit(*this);
pmeciFloat4->Init(*this);
pmeciFloat8->BaseClassInit(*this);
pmeciFloat8->Init(*this);
pmeciInt1->BaseClassInit(*this);
pmeciInt1->Init(*this);
pmeciInt2->BaseClassInit(*this);
pmeciInt2->Init(*this);
pmeciInt4->BaseClassInit(*this);
pmeciInt4->Init(*this);
pmeciStrList->BaseClassInit(*this);
pmeciStrList->Init(*this);
pmeciExcept->BaseClassInit(*this);
pmeciExcept->Init(*this);
pmeciMemBuf->BaseClassInit(*this);
pmeciMemBuf->Init(*this);
pmeciOStrm->BaseClassInit(*this);
pmeciOStrm->Init(*this);
pmeciStrOS->BaseClassInit(*this);
pmeciStrOS->Init(*this);
//
// Do the base classes for the parameterized collection classes. These
// are not intrinsics, but need to be known at a fundamental level.
//
TMEngClassInfo* pmeciCol = new TMEngCollectInfo(*this);
pmeciCol->BaseClassInit(*this);
c2AddClass(pmeciCol);
pmeciCol = new TMEngVectorInfo
(
*this
, L"Vector"
, L"MEng.System.Runtime"
, L"MEng.System.Runtime.Collection"
, 0
);
pmeciCol->BaseClassInit(*this);
m_c2VectorId = c2AddClass(pmeciCol);
// Intrinsic but DO AFTER vector above since it uses a vector parameter
pmeciTime->BaseClassInit(*this);
pmeciTime->Init(*this);
//
// !!!! Make sure this one is last. The Cleanup() method uses this
// one's id to know where the built in classes end, so that it can
// remove all per-invocation classes but leave the built in ones
// alone.
//
pmeciCol = new TMEngArrayInfo
(
*this
, L"Array"
, L"MEng.System.Runtime"
, L"MEng.System.Runtime.Collection"
, 0
);
pmeciCol->BaseClassInit(*this);
m_c2ArrayId = c2AddClass(pmeciCol);
}
| 31.05436 | 101 | 0.603629 | MarkStega |
574955b06e4e1d932d6e28bca12734177b85537f | 683 | cpp | C++ | Source/Math/CPUMatrixFloat.cpp | vschs007/CNTK | 894d9e1a5d65d30cd33803c06a988844bb87fcb7 | [
"RSA-MD"
] | 5 | 2017-08-28T08:27:18.000Z | 2021-04-20T21:12:52.000Z | Source/Math/CPUMatrixFloat.cpp | vschs007/CNTK | 894d9e1a5d65d30cd33803c06a988844bb87fcb7 | [
"RSA-MD"
] | null | null | null | Source/Math/CPUMatrixFloat.cpp | vschs007/CNTK | 894d9e1a5d65d30cd33803c06a988844bb87fcb7 | [
"RSA-MD"
] | 3 | 2019-08-23T11:42:14.000Z | 2022-01-06T08:41:32.000Z | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
#include "stdafx.h"
#include "CPUMatrixImpl.h"
namespace Microsoft { namespace MSR { namespace CNTK {
int MATH_API TracingGPUMemoryAllocator::m_traceLevel = 0;
void TracingGPUMemoryAllocator::SetTraceLevel(int traceLevel)
{
m_traceLevel = traceLevel;
}
bool TracingGPUMemoryAllocator::IsTraceEnabled()
{
return (m_traceLevel > 0);
}
// explicit instantiations, due to CPUMatrix being too big and causing VS2015 cl crash.
template class MATH_API CPUMatrix<float>;
}}} | 28.458333 | 104 | 0.717423 | vschs007 |
574ace3982a2a69d82ff19cd4068ce02d68231fb | 512 | cpp | C++ | src/GrayCode.cpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | 43 | 2015-10-10T12:59:52.000Z | 2018-07-11T18:07:00.000Z | src/GrayCode.cpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | null | null | null | src/GrayCode.cpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | 11 | 2015-10-10T14:41:11.000Z | 2018-07-28T06:03:16.000Z | #include "GrayCode.hpp"
vector<int> GrayCode::grayCode(int n) {
vector<int> ret;
if (n > 0)
helper(n, ret);
else
ret.push_back(0);
return ret;
}
void GrayCode::helper(int n, vector<int> &res) {
if (n == 1) {
res.push_back(0);
res.push_back(1);
} else {
helper(n - 1, res);
int sz = res.size();
for (int i = sz - 1; i >= 0; i--) {
int val = res[i] | (1 << (n - 1));
res.push_back(val);
}
}
}
| 18.285714 | 48 | 0.451172 | yanzhe-chen |
574af7d5837e4d25c486b2c8d1fef7e1b6d89b7a | 915 | cpp | C++ | 2DGame/windowSystem.cpp | Cimera42/2DGame | 9135e3dbed8a909357d57e227ecaba885982e8dc | [
"MIT"
] | 3 | 2015-08-18T12:59:29.000Z | 2015-12-15T08:11:10.000Z | 2DGame/windowSystem.cpp | Cimera42/2DGame | 9135e3dbed8a909357d57e227ecaba885982e8dc | [
"MIT"
] | null | null | null | 2DGame/windowSystem.cpp | Cimera42/2DGame | 9135e3dbed8a909357d57e227ecaba885982e8dc | [
"MIT"
] | null | null | null | #include "windowSystem.h"
#include "globals.h"
#include <iostream>
#include "windowComponent.h"
#include "openGLFunctions.h"
#include "keyboardHandler.h"
SystemID WindowSystem::ID;
WindowSystem::WindowSystem()
{
std::vector<ComponentID> subList1;
//Components needed to subscribe to system
subList1.push_back(WindowComponent::getStaticID());
addSubList(subList1);
}
WindowSystem::~WindowSystem(){}
void WindowSystem::update()
{
for(int subID = 0; subID < subscribedEntities[0].size(); subID++)
{
Entity * entity = entities[subscribedEntities[0][subID]];
WindowComponent* windowComp = static_cast<WindowComponent*>(entity->getComponent(WindowComponent::getStaticID()));
glfwSwapBuffers(windowComp->glfwWindow);
}
if(isKeyPressed(GLFW_KEY_ESCAPE))
shouldExit = true;
glfwSwapBuffers(mainWindow->glfwWindow);
}
| 26.911765 | 123 | 0.69071 | Cimera42 |
574b1ba3a0dd29cfd3226492bd5db00581ad69ff | 669 | cpp | C++ | WFC++/Tiled/InputData.cpp | heyx3/WFCpp | a158e1ce5f8fef9b9423711b1bd8ccfdf8c57946 | [
"MIT",
"Unlicense"
] | 7 | 2019-08-17T15:15:56.000Z | 2021-06-03T08:02:27.000Z | WFC++/Tiled/InputData.cpp | heyx3/WFCpp | a158e1ce5f8fef9b9423711b1bd8ccfdf8c57946 | [
"MIT",
"Unlicense"
] | 1 | 2017-05-01T06:13:47.000Z | 2017-05-04T04:07:54.000Z | WFC++/Tiled/InputData.cpp | heyx3/WFCpp | a158e1ce5f8fef9b9423711b1bd8ccfdf8c57946 | [
"MIT",
"Unlicense"
] | null | null | null | #include "InputData.h"
#include <algorithm>
using namespace WFC;
using namespace WFC::Tiled;
namespace
{
template<typename I>
I getMax(I a, I b) { return (a > b) ? a : b; }
}
const TileIDSet InputData::EmptyTileSet;
InputData::InputData(const List<Tile>& _tiles)
: tiles(_tiles)
{
//Collect all tiles that fit each type of edge.
for (TileID tileID = 0; tileID < (TileID)tiles.GetSize(); ++tileID)
{
const auto& tile = tiles[tileID];
for (uint8_t edgeI = 0; edgeI < 4; ++edgeI)
{
auto key = EdgeInstance(tile.Edges[edgeI], (EdgeDirs)edgeI);
matchingEdges[key].Add(tileID);
}
}
} | 20.90625 | 72 | 0.606876 | heyx3 |
574dbf0f217f71e385b7b409bfabb15cb06373be | 1,207 | cxx | C++ | hackathon/PengXie/NeuronStructNavigator/cmake-3.6.2/Source/cmMakeDirectoryCommand.cxx | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2021-12-27T19:14:03.000Z | 2021-12-27T19:14:03.000Z | hackathon/PengXie/NeuronStructNavigator/cmake-3.6.2/Source/cmMakeDirectoryCommand.cxx | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | hackathon/PengXie/NeuronStructNavigator/cmake-3.6.2/Source/cmMakeDirectoryCommand.cxx | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | /*============================================================================
CMake - Cross Platform Makefile Generator
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#include "cmMakeDirectoryCommand.h"
// cmMakeDirectoryCommand
bool cmMakeDirectoryCommand::InitialPass(std::vector<std::string> const& args,
cmExecutionStatus&)
{
if (args.size() != 1) {
this->SetError("called with incorrect number of arguments");
return false;
}
if (!this->Makefile->CanIWriteThisFile(args[0].c_str())) {
std::string e = "attempted to create a directory: " + args[0] +
" into a source directory.";
this->SetError(e);
cmSystemTools::SetFatalErrorOccured();
return false;
}
cmSystemTools::MakeDirectory(args[0].c_str());
return true;
}
| 37.71875 | 78 | 0.610605 | zzhmark |