blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
416e89e3249897a403112cbfedd3fa61de88613e | ca0a5f15b69c09d79e417fb9fcbeae725ce17749 | /libs/asynchronous/doc/examples/example_layers.cpp | 2ee46de61dd7f768897336f6795ade5b9aa7727a | [
"MIT",
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | henry-ch/asynchronous | 1e31ddb3615590b1c301e878ae0903a2eb2adead | d61e0e65d6bf67d3a0b78c31b29f873359fac42c | refs/heads/master | 2023-05-25T21:32:16.398110 | 2023-05-23T16:05:40 | 2023-05-23T16:05:40 | 11,562,526 | 35 | 8 | null | 2022-06-10T13:54:51 | 2013-07-21T14:07:22 | HTML | UTF-8 | C++ | false | false | 7,459 | cpp | example_layers.cpp | // Boost.Asynchronous library
// Copyright (C) Christophe Henry 2016
//
// Use, modification and distribution is subject to the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// For more information, see http://www.boost.org
#include <iostream>
#include <functional>
#include <string>
#include <boost/asynchronous/scheduler/single_thread_scheduler.hpp>
#include <boost/asynchronous/scheduler_shared_proxy.hpp>
#include <boost/asynchronous/scheduler/multiqueue_threadpool_scheduler.hpp>
#include <boost/asynchronous/servant_proxy.hpp>
#include <boost/asynchronous/trackable_servant.hpp>
using namespace std;
namespace
{
// a trackable servant is protecting the servant object by providing safe callbacks
struct BottomLayerServant : boost::asynchronous::trackable_servant<>
{
BottomLayerServant(boost::asynchronous::any_weak_scheduler<> scheduler)
: boost::asynchronous::trackable_servant<>(scheduler)
{
}
// caller (middle level) provides a callback, call it when done
void do_something(std::function<void(int)> callback)
{
// do something useful, communication, parallel algorithm etc.
// we are done, inform caller, from our thread
std::cout << "low-level layer is done" << std::endl;
callback(42);
}
private:
};
// a proxy protects a servant from outside calls running in different threads
class BottomLayerProxy : public boost::asynchronous::servant_proxy<BottomLayerProxy,BottomLayerServant>
{
public:
template <class Scheduler>
BottomLayerProxy(Scheduler s):
boost::asynchronous::servant_proxy<BottomLayerProxy,BottomLayerServant>(s)
{}
// caller will get a future
BOOST_ASYNC_FUTURE_MEMBER(do_something)
};
// a trackable servant is protecting the servant object by providing safe callbacks
struct MiddleLayerServant : boost::asynchronous::trackable_servant<>
{
MiddleLayerServant(boost::asynchronous::any_weak_scheduler<> scheduler)
: boost::asynchronous::trackable_servant<>(scheduler)
// create a low-level layer in its own thread world
, m_bottom(boost::asynchronous::make_shared_scheduler_proxy<
boost::asynchronous::single_thread_scheduler<
boost::asynchronous::lockfree_queue<>>>())
{
}
// caller (top level) provides a callback, call it when done
void do_something(std::function<void(std::string)> callback)
{
// check internal state, do something
// then delegate part of work to bottom layer
m_bottom.do_something(
make_safe_callback(
[this, callback](int res)
{
// this callback, though coming from the bottom layer, is executing within our thread
// it is therefore safe to use "this"
std::cout << "middle-level layer is done" << std::endl;
if (res == 42)
{
callback("ok");
}
else
{
callback("nok");
}
}
));
}
private:
// middle layer keeps low-level alive
BottomLayerProxy m_bottom;
};
// a proxy protects a servant from outside calls running in different threads
class MiddleLayerProxy : public boost::asynchronous::servant_proxy<MiddleLayerProxy,MiddleLayerServant>
{
public:
template <class Scheduler>
MiddleLayerProxy(Scheduler s):
boost::asynchronous::servant_proxy<MiddleLayerProxy,MiddleLayerServant>(s)
{}
// caller will get a future
BOOST_ASYNC_FUTURE_MEMBER(do_something)
};
// a trackable servant is protecting the servant object by providing safe callbacks
struct TopLayerServant : boost::asynchronous::trackable_servant<>
{
TopLayerServant(boost::asynchronous::any_weak_scheduler<> scheduler, int threads)
: boost::asynchronous::trackable_servant<>(scheduler,
// threadpool and a simple lockfree_queue queue
boost::asynchronous::make_shared_scheduler_proxy<
boost::asynchronous::multiqueue_threadpool_scheduler<
boost::asynchronous::lockfree_queue<>>>(threads))
// to signal that we shutdown
, m_promise()
// create a middle-level layer in its own thread world
, m_middle(boost::asynchronous::make_shared_scheduler_proxy<
boost::asynchronous::single_thread_scheduler<
boost::asynchronous::lockfree_queue<>>>())
{
}
// call to this is posted and executes in our (safe) single-thread scheduler
std::future<bool> start()
{
// to inform main of shutdown
std::future<bool> fu = m_promise.get_future();
// delegate work to middle layer
m_middle.do_something(
make_safe_callback(
[this](std::string res)
{
// this callback, though coming from the bottom layer, is executing within our thread
// it is therefore safe to use "this"
std::cout << "top-level layer is done" << std::endl;
if (res == "ok")
{
// inform main
m_promise.set_value(true);
}
else
{
// inform main
m_promise.set_value(true);
}
}
));
return fu;
}
private:
// to signal that we shutdown
std::promise<bool> m_promise;
// top layer holds middle-level alive, which keeps low-level alive
MiddleLayerProxy m_middle;
};
// a proxy protects a servant from outside calls running in different threads
class TopLayerProxy : public boost::asynchronous::servant_proxy<TopLayerProxy,TopLayerServant>
{
public:
template <class Scheduler>
TopLayerProxy(Scheduler s, int threads):
boost::asynchronous::servant_proxy<TopLayerProxy,TopLayerServant>(s,threads)
{}
// caller will get a future
BOOST_ASYNC_FUTURE_MEMBER(start)
};
}
void example_layers()
{
std::cout << "example_layers" << std::endl;
{
// a single-threaded world, where TopLayerServant will live.
auto scheduler = boost::asynchronous::make_shared_scheduler_proxy<
boost::asynchronous::single_thread_scheduler<
boost::asynchronous::lockfree_queue<>>>();
{
TopLayerProxy proxy(scheduler,boost::thread::hardware_concurrency());
std::future<std::future<bool> > fu = proxy.start();
// main just waits for end of application and shows result
bool app_res = fu.get().get();
std::cout << "app finished with success? " << std::boolalpha << app_res << std::endl;
}
}
std::cout << "end example_layers \n" << std::endl;
}
|
e2b8d3409bf16264e70a0f18c8e2a529f5f180cb | 7d1f70ace8a151d04e895603c26435cfe5163aa0 | /handler.h | 7f8fbdba587cd1ee654c40c49df976d4ad54101e | [] | no_license | beafshar/Switching-Network | b2440878a8338e8e4523ed72ed392e2eb2cb708d | a1345c517f0ed4a5a1871b3b18b05b09162ab0bd | refs/heads/main | 2023-04-18T20:32:13.089724 | 2021-05-06T17:05:06 | 2021-05-06T17:05:06 | 360,526,711 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 570 | h | handler.h | #include "headers.h"
class Handler
{
public:
Handler();
void get_input();
void input_handler();
void make_new_switch(int number_of_ports, int switch_number);
void make_new_system(int system_number);
void connect_system_to_switch(string connect, int system_number, int switch_number);
void connect_switch_to_switch(string connect, int switch_number_1, int switch_number_2);
void stp();
private:
string current_input;
map<int, int> system_switches;
vector<int> child_pid;
}; |
1063cf4ca5ee9cfdff3c616a6398e0d258be0851 | 1f77f63fc4bcf538fc892f6a5ba54058367ed0e5 | /plugins/ThrustFilePlugin/src/base/plugin/GmatPluginFunctions.cpp | 28d406d1f2a46711f5c449058af04e6892c4664d | [
"Apache-2.0"
] | permissive | ChristopherRabotin/GMAT | 5f8211051b620562947443796fa85c80aed5a7cf | 829b7c2c3c7ea73d759c338e7051f92f4f2f6f43 | refs/heads/GMAT-2020a | 2022-05-21T07:01:48.435641 | 2022-05-09T17:28:07 | 2022-05-09T17:28:07 | 84,392,259 | 24 | 10 | Apache-2.0 | 2022-05-11T03:48:44 | 2017-03-09T03:09:20 | C++ | UTF-8 | C++ | false | false | 3,075 | cpp | GmatPluginFunctions.cpp | //------------------------------------------------------------------------------
// GmatPluginFunctions
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool
//
// Copyright (c) 2002 - 2020 United States Government as represented by the
// Administrator of The National Aeronautics and Space Administration.
// All Other Rights Reserved.
//
// Developed jointly by NASA/GSFC and Thinking Systems, Inc. under the FDSS II
// contract, Task Order 08
//
// Author: Darrel J. Conway, Thinking Systems, Inc.
// Created: Jan 13, 2016
/**
* Implementation for library code interfaces.
*
* This is prototype code.
*/
//------------------------------------------------------------------------------
#include "GmatPluginFunctions.hpp"
#include "ThrustFileForceFactory.hpp"
#include "ThrustFileCommandFactory.hpp"
#include "ThrustFileReaderFactory.hpp"
#include "MessageInterface.hpp"
// Modify this line to match your factory list:
extern "C"
{
//------------------------------------------------------------------------------
// Integer GetFactoryCount()
//------------------------------------------------------------------------------
/**
* Returns the number of plug-in factories in this module
*
* @return The number of factories
*/
//------------------------------------------------------------------------------
Integer GetFactoryCount()
{
// Update this line with the total number of factories you support:
return 3;
}
//------------------------------------------------------------------------------
// Factory* GetFactoryPointer(Integer index)
//------------------------------------------------------------------------------
/**
* Retrieves a pointer to a specific factory
*
* @param index The index to the Factory
*
* @return The Factory pointer
*/
//------------------------------------------------------------------------------
Factory* GetFactoryPointer(Integer index)
{
Factory* factory = NULL;
switch (index)
{
case 0:
factory = new ThrustFileForceFactory;
break;
case 1:
factory = new ThrustFileCommandFactory;
break;
case 2:
factory = new ThrustFileReaderFactory;
default:
break;
}
return factory;
}
//------------------------------------------------------------------------------
// void SetMessageReceiver(MessageReceiver* mr)
//------------------------------------------------------------------------------
/**
* Sets the messaging interface used for GMAT messages
*
* @param mr The message receiver
*
* @note This function is deprecaged, and may not be needed in future builds
*/
//------------------------------------------------------------------------------
void SetMessageReceiver(MessageReceiver* mr)
{
MessageInterface::SetMessageReceiver(mr);
}
};
|
64db4c91e474a5d1e619cb367c7716702702625d | c2616feb3b08de9285d885470513d10591add811 | /Porgatory - Fire Detection/Arduino Controller/ESP82166.ino | f29ff8278e6783c887fa88a793007e494c24c3a3 | [] | no_license | adiparamartha/Porgatory-FireFighter | 7e98cd4a6a44d6400b309498e31b5336a337d9c6 | 6c3a3093560f553ffe0a5398f6f19b0fcc144664 | refs/heads/master | 2020-05-25T05:04:47.085669 | 2019-05-20T13:41:35 | 2019-05-20T13:41:35 | 187,641,671 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,883 | ino | ESP82166.ino | #include <SoftwareSerial.h>
#include <ESP8266WiFi.h>
#include <FirebaseArduino.h>
// Set these to run example.
#define FIREBASE_HOST "FIREBASE-DATABASE"
#define FIREBASE_AUTH "FIREBASE-AUTH"
#define WIFI_SSID "SSID"
#define WIFI_PASSWORD "PASSWORD"
SoftwareSerial NodeMCU(D2,D3);
void setup(){
Serial.begin(9600);
NodeMCU.begin(115200);
pinMode(D7,INPUT);
pinMode(D8,OUTPUT);
// connect to wifi.
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("connecting");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println();
Serial.print("connected: ");
Serial.println(WiFi.localIP());
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
}
void loop(){
String content = "";
char character;
while(NodeMCU.available() > 0) {
character = NodeMCU.read();
content.concat(character);
}
if (content != "") {
String Light1 = getValue(content, '-', 0);
String Light2 = getValue(content, '-', 1);
String MQ2_1 = getValue(content, '-', 2);
String MQ2_2 = getValue(content, '-', 3);
String Condition = getValue(content, '-', 4);
Serial.println("Light1: " + Light1);
Serial.println("Light2: " + Light2);
Serial.println("MQ2-1: " + MQ2_1);
Serial.println("MQ2-2: " + MQ2_2);
Serial.println("Condition: " + Condition);
Serial.println("- - - - - - - - - - -");
if (Condition == "Normal"){
Firebase.setString("Left_Light", Light1);
// handle error
if (Firebase.failed()) {
Serial.print("LL /number failed:");
Serial.println(Firebase.error());
return;
}
Firebase.setString("Right_Light", Light2);
// handle error
if (Firebase.failed()) {
Serial.print("RL /number failed:");
Serial.println(Firebase.error());
return;
}
Firebase.setString("Left_MQ2", MQ2_1);
// handle error
if (Firebase.failed()) {
Serial.print("LMQ2 /number failed:");
Serial.println(Firebase.error());
return;
}
Firebase.setString("Right_MQ2", MQ2_2);
// handle error
if (Firebase.failed()) {
Serial.print("RMQ2 /number failed:");
Serial.println(Firebase.error());
return;
}
Firebase.setString("Status", Condition);
// handle error
if (Firebase.failed()) {
Serial.print("Normal Status failed:");
Serial.println(Firebase.error());
return;
}
}
else{
Firebase.setString("Status", Condition);
// handle error
if (Firebase.failed()) {
Serial.print(" Not Normal Status failed:");
Serial.println(Firebase.error());
return;
}
}
}
delay(5000);
}
String getValue(String data, char separator, int index)
{
int found = 0;
int strIndex[] = { 0, -1 };
int maxIndex = data.length() - 1;
for (int i = 0; i <= maxIndex && found <= index; i++) {
if (data.charAt(i) == separator || i == maxIndex) {
found++;
strIndex[0] = strIndex[1] + 1;
strIndex[1] = (i == maxIndex) ? i+1 : i;
}
}
return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
}
void firebaseupdate(String light1, String light2, String mq2_1, String mq2_2, String condition){
Serial.println("AAA : " + condition);
}
|
0ca1a9f0387e176d9d7a161e3a2948c8519a0940 | 4600aead4ae744c5d4e93dd761cd9ecb533ff431 | /test/adt/table/test_table.cpp | f6c90301c29c07a1135732f6b4ca6f8570d88692 | [
"Apache-2.0"
] | permissive | fox000002/ulib-win | 00acda66bc1dcd38770e960920362dc73368d016 | 628c4a0b8193d1ad771aa85598776ff42a45f913 | refs/heads/master | 2021-05-12T13:52:52.436757 | 2018-01-22T13:57:38 | 2018-01-22T13:57:38 | 116,941,261 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 864 | cpp | test_table.cpp | #include <iostream>
#include "adt/utable.h"
#include "adt/upair.h"
void print(int *p)
{
std::cout << *p << std::endl;
}
int main()
{
using std::cout;
using std::endl;
typedef huys::ADT::UTable<int, const char *> UTableIC;
UTableIC ic;
ic.add(1, "ccccc");
ic.add(2, "ccccc");
cout << ic << endl;
if (ic.inTable(2))
{
cout << "2 is in table!" << endl;
}
cout << ic[2] << endl;
ic.add(2, "aaaaa");
typedef huys::ADT::UPair<int, long> MyPair;
typedef huys::ADT::UTable<int, MyPair> UTriTable;
UTriTable utt;
utt.add(1, MyPair(1, 2));
utt.add(2, MyPair(3, 24));
const MyPair & v = utt[2];
cout << v.first() << " " << v.second() << endl;
const MyPair & v2 = utt[1];
cout << v2.first() << " " << v2.second() << endl;
utt.add(2, MyPair(3, 24));
return 0;
}
|
877e4fde1df69f38bae57952265ec4e737bb7e83 | 7ed7aa5e28bd3cdea44e809bbaf8a527a61259fb | /UVa/10295 - Hay Points.cpp | 0935b1786d9087fbee510e745c5e37f03a068d41 | [] | no_license | NaiveRed/Problem-solving | bdbf3d355ee0cb2390cc560d8d35f5e86fc2f2c3 | acb47328736a845a60f0f1babcb42f9b78dfdd10 | refs/heads/master | 2022-06-16T03:50:18.823384 | 2022-06-12T10:02:23 | 2022-06-12T10:02:23 | 38,728,377 | 4 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 699 | cpp | 10295 - Hay Points.cpp | #include <cstdio>
#include <cstring>
#include <unordered_map>
#include <string>
using namespace std;
int main()
{
int m, n;
unordered_map<string, int> point;
scanf("%d%d", &m, &n);
char str[100];
int pt;
for (int i = 0; i < m; ++i)
{
scanf("%s %d", str, &pt);
point[string(str)] = pt;
}
for (int i = 0; i < n; ++i)
{
int sum = 0;
while (true)
{
scanf("%s", str);
if (str[0] == '.')
{
printf("%d\n", sum);
break;
}
string s(str);
if (point.count(s))
sum += point[s];
}
}
return 0;
} |
588a84bdafb4a0c1f226c8e6e59b10b968f56ff2 | 4d8144c85c3d6c8d69a5e04f8269db3672780434 | /학교수업/star question1.cpp | 8d3da35bfa86b699c1af076af698176cfda2d3d1 | [] | no_license | NKT-RJH/DGSW_School_Study | 482990644427fb587c8d421eb6252723251cf177 | 1d4b57b03ca7d90b6d308130314d05c8ac4d2c55 | refs/heads/master | 2023-04-19T22:27:44.345203 | 2021-05-12T10:16:02 | 2021-05-12T10:16:02 | 357,844,369 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 347 | cpp | star question1.cpp | #include <stdio.h>
int main()
{
int i, j, k = 1;
for (i = 0; i < 5; i++)
{
for (j = 4; j > i; j--)
printf(" ");
for (j = 0; j < k; j++)
printf("*");
k += 2;
printf("\n");
}
for (i = 0; i < 5; i++)
{
k -= 2;
for (j = 0; j < i; j++)
printf(" ");
for (j = k; j > 0; j--)
printf("*");
printf("\n");
}
return 0;
} |
7bb031a6d3a46142b6b6971b21b1f7549c669f5e | 0397db7a385a90dac5ee8cc45b8c49ebf8298386 | /Unit Test/UnitTesting.cpp | 468bc62ac31be71701a12361935ae76d0fd93607 | [] | no_license | peichanghong/main-working-copy | 3a2e0e64911ec8bdacfa42dedb87f7f07ed28951 | 1a69f5009ed9c5a10c54b4712981e1f98da427a5 | refs/heads/master | 2021-01-10T05:33:35.220693 | 2016-03-05T11:53:52 | 2016-03-05T11:53:52 | 52,659,732 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,486 | cpp | UnitTesting.cpp | #include "stdafx.h"
#include "CppUnitTest.h"
#include "TesterHeader.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace UnitTest {
TEST_CLASS(SettingTest) {
public:
/*
TEST_METHOD(ParserTest) {
CommandPackage expectedAddObject(ADD, Task("fly a plane",0,11092001,-1,-1),0,"");
Parser sut("fly a plane 11092001");
Assert::AreEqual(sut.parse(),&expectedAddObject);
}
*/
TEST_METHOD(SettingsTextFileNameMakerTest) {
Settings Settings;
string input = "text";
string actualTexFileName;
string expectedTextFileName = "text.txt";
actualTexFileName = Settings.createValidTextFileNameString(input);
Settings.updateTextFileName(input);
Assert::AreEqual(expectedTextFileName,actualTexFileName);
Assert::AreEqual(expectedTextFileName, Settings._textFileName);
}
TEST_METHOD(SettingsChangeDirectoryTest) {
Settings Settings;
string input = "C:/Users/PeiChangHong/Documents/NUS Modules 14 I 15/Semester 4/CS2103/Core";
string inputName = "mytextfile";
string actualTexFileName;
string expectedTextFileName = "mytextfile.txt";
string expectedDirectory = "C:/Users/PeiChangHong/Documents/NUS Modules 14 I 15/Semester 4/CS2103/Core/";
Assert::AreEqual(true,Settings.checkValidityOfDirectory(input));
Settings.changeSaveDirectory(input);
Settings.updateTextFileName(inputName);
Assert::AreEqual(expectedTextFileName, Settings._textFileName);
Assert::AreEqual(expectedDirectory, Settings._saveDirectory);
}
TEST_METHOD(SettingsGetDirectoryTest) {
Settings Settings;
Settings._textFileName = "text.txt";
Settings._saveDirectory = "C:/my documents/";
string expectedDirectory = "C:/my documents/text.txt";
Assert::AreEqual(expectedDirectory, Settings.getSaveDirectory());
}
TEST_METHOD(SettingsLoadSaveTest) {
Settings Setting;
Settings testSetting;
Setting._textFileName = "text.txt";
Setting._saveDirectory = "C:/user/";
string expectedTextFileName = "text.txt";
string expectedDirectory = "C:/user/";
Setting.openNewSettingFile();
Setting.saveSettings();
testSetting.loadSettings();
Assert::AreEqual(expectedTextFileName, testSetting._textFileName);
Assert::AreEqual(expectedDirectory, testSetting._saveDirectory);
Setting._textFileName = Setting.VOID_STRING;
Setting._saveDirectory = "C:/user/";
expectedTextFileName = "";
Setting.saveSettings();
testSetting.loadSettings();
Assert::AreEqual(expectedTextFileName, testSetting._textFileName);
Assert::AreEqual(expectedDirectory, testSetting._saveDirectory);
}
};
TEST_CLASS(UICLASS) {
public:
TEST_METHOD(UIGetTaskStringTypeDefault) {
UserInterface UI;
UI._defaultViewType = -1;
int i = 0;
string actualString;
list<Task*> ls;
string expectedString[6] = {
"read book (home) 13:00 21/8/2016",
"read book (home) 13:00 19/8/2016 - 16:00 21/8/2016",
"read book (home) 21/9/2016",
"read book (college) 1:00 - 2:00 22/9/2016",
"read book 1:00 - 2:00 23/10/2016",
"read book (college) <No deadline>"
};
ls.push_back(new Task("read book" , -1 , 20160821 , -1 , 1300 , "home"));
ls.push_back(new Task("read book" , 20160819 , 20160821 , 1300 , 1600 , "home"));
ls.push_back(new Task("read book" , -1 , 20160921 , -1 , -1 , "home"));
ls.push_back(new Task("read book" , -1 , 20160922 , 100 , 200 , "college"));
ls.push_back(new Task("read book" , -1 , 20161023 , 100 , 200 , ""));
ls.push_back(new Task("read book" , -1 , -1 , -1 , -1 , "college"));
list<Task*>::iterator listIter = ls.begin();
while(listIter != ls.end()) {
actualString = UI.getTaskString(*listIter , UI._defaultViewType);
Assert::AreEqual(expectedString[i], actualString);
i++;
listIter++;
}
}
TEST_METHOD(UIGetTaskStringType0) {
UserInterface UI;
UI._defaultViewType = 0;
int i = 0;
string actualString;
list<Task*> ls;
string expectedStringType0[6] = {
"read book (home) 1:00 pm 21/8/2016",
"read book (home) 1:00 pm 19/8/2016 - 4:00 pm 21/8/2016",
"read book (home) 21/9/2016",
"read book (college) 1:00 am - 2:00 am 22/9/2016",
"read book 1:00 am - 2:00 am 23/10/2016",
"read book (college) <No deadline>"
};
ls.push_back(new Task("read book" , -1 , 20160821 , -1 , 1300 , "home"));
ls.push_back(new Task("read book" , 20160819 , 20160821 , 1300 , 1600 , "home"));
ls.push_back(new Task("read book" , -1 , 20160921 , -1 , -1 , "home"));
ls.push_back(new Task("read book" , -1 , 20160922 , 100 , 200 , "college"));
ls.push_back(new Task("read book" , -1 , 20161023 , 100 , 200 , ""));
ls.push_back(new Task("read book" , -1 , -1 , -1 , -1 , "college"));
list<Task*>::iterator listIter = ls.begin();
UI._defaultViewType = 0;
listIter = ls.begin();
while(listIter != ls.end()) {
actualString = UI.getTaskString(*listIter , UI._defaultViewType);
Assert::AreEqual(expectedStringType0[i], actualString);
i++;
listIter++;
}
}
};
TEST_CLASS(ViewTypeCLASS) {
public:
TEST_METHOD(ViewTypeCreateDisplayList) {
vector<string> actualDisplayList;
int i = 0;
ViewType testView;
list<Task*> ls;
string expectedString[6] = {
"1. read book (home) 13:00 21/8/2016",
"2. read book (home) 13:00 19/8/2016 - 16:00 21/8/2016",
"3. read book (home) 21/9/2016",
"4. read book (college) 1:00 - 2:00 22/9/2016",
"5. read book 1:00 - 2:00 23/10/2016",
"6. read book (college) <No deadline>"
};
ls.push_back(new Task("read book" , -1 , 20160821 , -1 , 1300 , "home"));
ls.push_back(new Task("read book" , 20160819 , 20160821 , 1300 , 1600 , "home"));
ls.push_back(new Task("read book" , -1 , 20160921 , -1 , -1 , "home"));
ls.push_back(new Task("read book" , -1 , 20160922 , 100 , 200 , "college"));
ls.push_back(new Task("read book" , -1 , 20161023 , 100 , 200 , ""));
ls.push_back(new Task("read book" , -1 , -1 , -1 , -1 , "college"));
testView._taskList = &ls;
actualDisplayList = testView.createDisplayList();
vector<string>::iterator displayListIter = actualDisplayList.begin();
while(displayListIter != actualDisplayList.end()) {
Assert::AreEqual(*displayListIter , expectedString[i]);
i++;
displayListIter++;
}
}
TEST_METHOD(ViewTypeCreateSearchList) {
vector<string> actualDisplayList;
int i = 0;
ViewType testView;
list<Task*> ls;
string expectedString[6] = {
"1. read book (home) 13:00 21/8/2016",
"2. read book (home) 13:00 19/8/2016 - 16:00 21/8/2016",
"3. read book (home) 21/9/2016",
"4. read book (college) 1:00 - 2:00 22/9/2016",
"5. read book 1:00 - 2:00 23/10/2016",
"6. read book (college) <No deadline>"
};
ls.push_back(new Task("read book" , -1 , 20160821 , -1 , 1300 , "home"));
ls.push_back(new Task("read book" , 20160819 , 20160821 , 1300 , 1600 , "home"));
ls.push_back(new Task("read book" , -1 , 20160921 , -1 , -1 , "home"));
ls.push_back(new Task("read book" , -1 , 20160922 , 100 , 200 , "college"));
ls.push_back(new Task("read book" , -1 , 20161023 , 100 , 200 , ""));
ls.push_back(new Task("read book" , -1 , -1 , -1 , -1 , "college"));
testView._taskList = &ls;
actualDisplayList = testView.createSearchList();
vector<string>::iterator displayListIter = actualDisplayList.begin();
while(displayListIter != actualDisplayList.end()) {
Assert::AreEqual(*displayListIter , expectedString[i]);
i++;
displayListIter++;
}
}
};
TEST_CLASS(ViewType0CLASS) {
public:
TEST_METHOD(ViewType0CreateDisplayList) {
vector<string> actualDisplayList;
int i = 0;
ViewType *testView;
list<Task*> ls;
string expectedString[8] = {
"Today's date is 21/8/2016",
"1. read book (home) 1:00 pm 21/8/2016",
"2. read book (home) 1:00 pm 19/8/2016 - 4:00 pm 21/8/2016",
" ",
"3. read book (home) 21/9/2016",
"4. read book (college) 1:00 am - 2:00 am 22/9/2016",
"5. read book 1:00 am - 2:00 am 23/10/2016",
"6. read book (college) <No deadline>"
};
ls.push_back(new Task("read book" , -1 , 20160821 , -1 , 1300 , "home"));
ls.push_back(new Task("read book" , 20160819 , 20160821 , 1300 , 1600 , "home"));
ls.push_back(new Task("read book" , -1 , 20160921 , -1 , -1 , "home"));
ls.push_back(new Task("read book" , -1 , 20160922 , 100 , 200 , "college"));
ls.push_back(new Task("read book" , -1 , 20161023 , 100 , 200 , ""));
ls.push_back(new Task("read book" , -1 , -1 , -1 , -1 , "college"));
testView = new ViewType0(&ls , 20160821); //initiate marker = 0
actualDisplayList = testView->createDisplayList();
vector<string>::iterator displayListIter = actualDisplayList.begin();
while(displayListIter != actualDisplayList.end()) {
Assert::AreEqual(*displayListIter , expectedString[i]);
i++;
displayListIter++;
}
}
TEST_METHOD(ViewType0CreateSearchList) {
vector<string> actualDisplayList;
int i = 0;
ViewType0 testView;
list<Task*> ls;
string expectedString[6] = {
"1. read book (home) 1:00 pm 21/8/2016",
"2. read book (home) 1:00 pm 19/8/2016 - 4:00 pm 21/8/2016",
"3. read book (home) 21/9/2016",
"4. read book (college) 1:00 am - 2:00 am 22/9/2016",
"5. read book 1:00 am - 2:00 am 23/10/2016",
"6. read book (college) <No deadline>"
};
ls.push_back(new Task("read book" , -1 , 20160821 , -1 , 1300 , "home"));
ls.push_back(new Task("read book" , 20160819 , 20160821 , 1300 , 1600 , "home"));
ls.push_back(new Task("read book" , -1 , 20160921 , -1 , -1 , "home"));
ls.push_back(new Task("read book" , -1 , 20160922 , 100 , 200 , "college"));
ls.push_back(new Task("read book" , -1 , 20161023 , 100 , 200 , ""));
ls.push_back(new Task("read book" , -1 , -1 , -1 , -1 , "college"));
testView._taskList = &ls;
actualDisplayList = testView.createSearchList();
vector<string>::iterator displayListIter = actualDisplayList.begin();
while(displayListIter != actualDisplayList.end()) {
Assert::AreEqual(expectedString[i], *displayListIter);
i++;
displayListIter++;
}
}
};
} |
675a50ef577bfde29312fba8857081223f33603b | 89d2764b8056e9d384efa11099a455a5c6b36e60 | /RPA-Trajectory-Visualizer/TrajectoryVisualizer/trajectory.h | 4d274c0bf4ad40411db14850fd7ce697a20fd966 | [] | no_license | samchen16/RPA-Tracking-Human-Trajectories | 6c8aec3b19d73167f1ab8cc265f682144e30ecb2 | f91c2d0276acb68fbec43d20106b647acd47b1b8 | refs/heads/master | 2021-01-21T05:02:38.199414 | 2016-04-12T23:53:57 | 2016-04-12T23:53:57 | 40,920,714 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,655 | h | trajectory.h | #ifndef TRAJECTORY_H
#define TRAJECTORY_H
#include <vector>
struct Point {
float x;
float y;
float z;
};
/**
* Model class representing an trajectory.
*
*/
class Trajectory
{
private:
std::vector<Point*>* positions;
std::vector<Point*>* velocities;
std::vector<Point*>* colors;
std::vector<float>* times;
public:
bool isPerson;
/**
* Creates a new empty trajectory
*/
Trajectory();
/**
* Disposes the trajectory, releasing all resources.
*/
~Trajectory();
Point* getVelocity() { return velocities->at(velocities->size()-1); }
Point* getPosition() { return positions->at(positions->size()-1); }
Point* getColor() { return colors->at(colors->size()-1); }
float getTime() { return times->at(times->size()-1); }
Point* getVelocity(int t) { return velocities->at(t); }
Point* getPosition(int t) { return positions->at(t); }
Point* getColor(int t) { return colors->at(t); }
float getTime(int t) { return times->at(t); }
std::vector<Point*>* getPositions() { return positions; }
std::vector<Point*>* getVelocities() { return velocities; }
std::vector<Point*>* getColors() { return colors; }
std::vector<float>* getTimes() { return times; }
void addPosition(float x, float y, float z);
void addVelocity(float x, float y, float z);
void addColor(float h, float s, float b);
void addTime(float t) { times->push_back(t); }
void addPosition(Point* p) { positions->push_back(p); }
void addVelocity(Point* p) { velocities->push_back(p); }
void addColor(Point* p) { colors->push_back(p); }
};
#endif // TRAJECTORY_H
|
85d3094c9d293142179209787e782225b2b7ccd6 | 41817fa657db2c3c650613a9b92c869677cd3b87 | /UVa/429.cpp | 776e20009d609662f4dba79c6982cf183a10c7b5 | [] | no_license | judmorenomo/Competitive-Programming | 15cfa2f5a3e57c7e28920ed3b202093bebf1b25f | d16624fbfaa95f7629374cfe8f05603fbd50b3fb | refs/heads/master | 2021-07-22T22:50:40.158499 | 2020-04-27T17:55:43 | 2020-04-27T17:55:43 | 149,539,981 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,569 | cpp | 429.cpp | #include<bits/stdc++.h>
using namespace std;
map<string, int> m;
vector<vector<int> > graf;
vector<string> aux;
bool vis[205];
int dist[205];
bool comp(string a, string b){
if(a.size() != b.size())return 0;
int dif = 0;
for(int i = 0; i < a.size(); i++){
if(a[i] != b[i])dif++;
}
return (dif == 1) ? 1 : 0;
}
int main(){
//freopen("in.txt", "r", stdin);
int t;
bool flag = false;
scanf("%d", &t);
string s, word;
getline(cin, s);
cin.ignore();
while(t--){
graf.clear();
aux.clear();
m.clear();
int cont = 0;
while(true){
getline(cin, word);
if(word == "*")break;
aux.push_back(word);
m[word] = cont;
cont++;
}
graf.assign(cont, vector<int>());
for(int i = 0; i < cont; i++){
for(int j = i+1; j < cont; j++){
if(comp(aux[i], aux[j])){
graf[m[aux[i]]].push_back(m[aux[j]]);
graf[m[aux[j]]].push_back(m[aux[i]]);
}
}
}
if(!flag)flag = true;
else puts("");
while(true){
getline(cin, word);
if(word.size() == 0)break;
stringstream ss(word);
string word1, word2;
ss >> word1;
ss >> word2;
int sou = m[word1], des = m[word2];
memset(vis, 0, sizeof vis);
memset(dist, 0, sizeof dist);
queue<int> q;
vis[sou] = 1;
dist[sou] = 0;
q.push(sou);
while(!q.empty()){
int u = q.front(); q.pop();
if(u == des)break;
for(int i = 0; i < graf[u].size(); i++){
int v = graf[u][i];
if(!vis[v]){
vis[v] = 1;
dist[v] = dist[u]+1;
q.push(v);
}
}
}
cout << word1<<" "<<word2<<" "<<dist[des]<<'\n';
}
}
} |
d0aea11379fe2f96927759ce5d1129306b0709fb | 47057aea2fb3146ff4cd6498493897ee4b554bdc | /miniRenderer/Shader/phongshader.cpp | b086f1269a8d87b40582ed62485154614a5b54c4 | [] | no_license | WanLittle/miniRenderer | 13d601f36d6944173da6b3b04206e3d2cf8045da | cb2ddf1592f7bd73af1f768c655ebb83a7d465c9 | refs/heads/master | 2021-03-15T00:40:08.258868 | 2020-04-15T03:34:50 | 2020-04-15T03:34:50 | 246,808,624 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 579 | cpp | phongshader.cpp | #include "phongshader.h"
VertexOut PhongShader::vertex_shader(const VertexIn &in)
{
VertexOut res;
res.FragPos = model * in.cam_pos;
res.Normal = glm::vec3f(model * glm::vec4f(in.normal, 1.0));
res.TexCoords = in.texcoord;
res.gl_position = projection * view * res.FragPos;
return res;
}
bool PhongShader::fragment_shader(const VertexOut &out, glm::vec4f& gl_FragColor, Model* model)
{
glm::vec3f normal = out.Normal;
glm::vec2f uv = out.TexCoords;
glm::vec4f diffuse = model->diffuse(uv);
gl_FragColor = diffuse;
return false;
}
|
ddbc98ccdd86cf5119fa742f0e3ab60c2f37bf6b | 61a8e1547276a052dbe09e3588732e29a22f7b6e | /PhysVehicle3D.h | ad94b4266ee31943a9e6a5a685948b4ca9c59a33 | [] | no_license | MagiX7/Racing_Car | 81f2acd36891a885497381911b54659f3eca5a0d | d7dd46ed35975eca5db55b7b88ed639ecf1f5365 | refs/heads/main | 2023-02-22T11:25:05.378285 | 2021-01-24T20:16:32 | 2021-01-24T20:16:32 | 321,054,890 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,775 | h | PhysVehicle3D.h | #pragma once
#include "PhysBody3D.h"
#include "glmath.h"
#include "Primitive.h"
class btRaycastVehicle;
struct PhysBody3D;
class btQuaternion;
class btVector3;
struct Wheel
{
vec3 connection; // origin of the ray. Must come from within the chassis
vec3 direction;
vec3 axis;
float suspensionRestLength; // max length for suspension in meters
float radius;
float width;
bool front; // is front wheel ?
bool drive; // does this wheel received engine power ?
bool brake; // does breakes affect this wheel ?
bool steering; // does this wheel turns ?
};
struct VehicleInfo
{
~VehicleInfo();
vec3 chassis_size;
vec3 chassis_offset;
vec3 front_chassis_size;
vec3 front_chassis_offset;
vec3 spoiler_size;
vec3 spoiler_offset;
vec3 front_wing_right_support_size;
vec3 front_wing_right_support_offset;
vec3 front_wing_left_support_size;
vec3 front_wing_left_support_offset;
vec3 front_wing_size;
vec3 front_wing_offset;
vec3 front_wing_right_size;
vec3 front_wing_right_offset;
vec3 front_wing_left_size;
vec3 front_wing_left_offset;
vec3 cockpit_size;
vec3 cockpit_offset;
vec3 back_cockpit_size;
vec3 back_cockpit_offset;
vec3 right_spoiler_support_size;
vec3 right_spoiler_support_offset;
vec3 left_spoiler_support_size;
vec3 left_spoiler_support_offset;
vec3 t_base_size;
vec3 t_base_offset;
vec3 t_up_size;
vec3 t_up_offset;
vec3 antenna_size;
vec3 antenna_offset;
int turbosLeft = 0;
float mass;
float suspensionStiffness; // default to 5.88 / 10.0 offroad / 50.0 sports car / 200.0 F1 car
float suspensionCompression; // default to 0.83
float suspensionDamping; // default to 0.88 / 0..1 0 bounces / 1 rigid / recommended 0.1...0.3
float maxSuspensionTravelCm; // default to 500 cm suspension can be compressed
float frictionSlip; // defaults to 10.5 / friction with the ground. 0.8 should be good but high values feels better (kart 1000.0)
float maxSuspensionForce; // defaults to 6000 / max force to the chassis
Wheel* wheels;
int num_wheels;
};
struct PhysVehicle3D : public PhysBody3D
{
public:
PhysVehicle3D(btRigidBody* body, btRaycastVehicle* vehicle, const VehicleInfo& info);
~PhysVehicle3D();
Cube CreateCubeComponent(vec3 size, vec3 offset, Color color);
void Render();
void ApplyEngineForce(float force);
void Brake(float force);
void Handbrake(float force);
void Turn(float degrees);
float GetKmh() const;
vec3 GetPos();
public:
VehicleInfo info;
btRaycastVehicle* vehicle;
/*Cylinder* wheel;
btQuaternion* q;
Cube* chassis;
btVector3* offset;
Cube* cockpit;
btVector3* cp_offset;
Cube* leftSpoilerSupport;
btVector3* lss_offset;
Cube* rightSpoilerSupport;
btVector3* rss_offset;
Cube* spoiler;
btVector3* s_offset;*/
//p2List<Primitive*> carComponents;
}; |
2f02805c7c9a69f7f9d6caee800c1450cca0a112 | 497427ff0c93569f2091eb19944454f3a38d516e | /schunk_modular_robotics/schunk_libm5api/src/Util/Thread.cpp | 9250ed6f3aa93dce08bc871fbd8a66a29d528250 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | briefgw/schunk_lwa4p_gazebo_simulation | b52e721ad509be3acc5c315e3a7301fbf3584e80 | 7b148225bfca2f2d3289a9b924d6afde7507b9e8 | refs/heads/master | 2021-08-08T10:04:10.685659 | 2017-11-09T19:46:46 | 2017-11-09T19:46:46 | 110,165,089 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,721 | cpp | Thread.cpp |
/******************************************************************************
*
* Copyright (c) 2012
*
* SCHUNK GmbH & Co. KG
*
* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* Project name: Drivers for "Amtec M5 Protocol" Electronics V4
*
* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* Email:robotics@schunk.com
*
* ToDo:
*
* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of SCHUNK GmbH & Co. KG nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License LGPL as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License LGPL for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License LGPL along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*
******************************************************************************/
#include "Thread.h"
#if defined(__LINUX__)
void* threadFunction(void* pvThread)
{
CThread* pclThread = (CThread*)pvThread;
(pclThread->m_pfuThreadFunction)(pclThread);
return NULL;
}
#endif
#if defined(__QNX__)
void threadFunction(void* pvThread)
{
CThread* pclThread = (CThread*)pvThread;
(pclThread->m_pfuThreadFunction)(pclThread);
}
#endif
#if defined(_WIN32)
unsigned int __stdcall threadFunction(void* pvThread)
{
CThread* pclThread = (CThread*)pvThread;
(pclThread->m_pfuThreadFunction)(pclThread);
return 0;
}
#endif
// ========================================================================== ;
// ;
// ---- constructors / destructor ------------------------------------------- ;
// ;
// ========================================================================== ;
CThread::CThread(void) : CMessage("CThread", g_iDebugLevel, g_bDebug, g_bDebugFile),
m_uiStackSize(1228000),
m_pcStack(0),
m_hThreadHandle(0),
m_bThreadRunFlag(false),
m_bThreadStopFlag(false),
m_pvThreadObject(0),
m_pfuThreadFunction(0)
{
}
CThread::CThread(const CThread& clThread)
{
error(-1, "copy contructor : method should no be called!");
}
CThread::~CThread(void)
{
debug(1, "destructed");
}
// ========================================================================== ;
// ;
// ---- operators ----------------------------------------------------------- ;
// ;
// ========================================================================== ;
CThread& CThread::operator=(const CThread& clThread)
{
error(-1, "assignment operator : method should not be called!");
return *this;
}
// ========================================================================== ;
// ;
// ---- query functions ----------------------------------------------------- ;
// ;
// ========================================================================== ;
// ========================================================================== ;
// ;
// ---- modify functions ---------------------------------------------------- ;
// ;
// ========================================================================== ;
void CThread::setThreadStackSize(unsigned int uiSize)
{
m_uiStackSize = uiSize;
}
// ========================================================================== ;
// ;
// ---- I/O functions ------------------------------------------------------- ;
// ;
// ========================================================================== ;
// ========================================================================== ;
// ;
// ---- exec functions ------------------------------------------------------ ;
// ;
// ========================================================================== ;
int CThread::createThread(void (*pfuThreadFunction)(CThread*), void* pvThreadObject)
{
m_bThreadStopFlag = false;
m_pvThreadObject = pvThreadObject;
m_pfuThreadFunction = pfuThreadFunction;
#if defined(_WIN32)
unsigned int iThreadId;
m_hThreadHandle = (HANDLE)_beginthreadex(NULL, 0, threadFunction, (void*)this, 0, &iThreadId);
if(m_hThreadHandle == NULL)
{
warning("createThread : creating thread failed!");
m_bThreadRunFlag = false;
return -1;
}
else
{
m_bThreadRunFlag = true;
return 0;
}
#endif
#if defined(__LINUX__)
pthread_attr_t Thread_attr;
int retVal = pthread_create(&m_hThreadHandle, NULL, threadFunction, (void*)this);
if(retVal != 0)
{
warning("createThread : creating thread failed!");
m_bThreadRunFlag = false;
return -1;
}
else
{
m_bThreadRunFlag = true;
return 0;
}
#endif
#if defined(__QNX__)
if(m_pcStack == NULL)
m_pcStack = new char[m_uiStackSize];
if(m_pcStack == NULL)
{
m_bThreadRunFlag = false;
warning("createThread : creating stack failed!");
return -1;
}
int iThreadId = _beginthread(threadFunction, m_pcStack, m_uiStackSize, (void*)this);
debug(1,"CThread: create stacksize=%d\n",m_uiStackSize);
if( iThreadId == 0)
{
warning("createThread : creating thread failed!");
m_bThreadRunFlag = false;
delete [] m_pcStack;
return -1;
}
else
{
m_bThreadRunFlag = true;
return 0;
}
#endif
}
void CThread::exitThread()
{
m_bThreadRunFlag = false;
#if defined(__WIN32)
_endthreadex(0);
#endif
#if defined(__QNX__)
_endthread();
#endif
}
void CThread::terminateThread()
{
m_bThreadStopFlag = true;
}
bool CThread::checkThreadRun()
{
return m_bThreadRunFlag;
}
bool CThread::checkThreadStop()
{
return m_bThreadStopFlag;
}
|
fdb00f3e68de5198c1c07b92d7e86a38ec61fef4 | b7d4fc29e02e1379b0d44a756b4697dc19f8a792 | /deps/boost/libs/multi_index/test/check_bmi_key_supported.cpp | 99ce8694b7e547346fadf9a4de1d5d64ac2611bb | [
"BSL-1.0",
"GPL-1.0-or-later",
"MIT"
] | permissive | vslavik/poedit | 45140ca86a853db58ddcbe65ab588da3873c4431 | 1b0940b026b429a10f310d98eeeaadfab271d556 | refs/heads/master | 2023-08-29T06:24:16.088676 | 2023-08-14T15:48:18 | 2023-08-14T15:48:18 | 477,156 | 1,424 | 275 | MIT | 2023-09-01T16:57:47 | 2010-01-18T08:23:13 | C++ | UTF-8 | C++ | false | false | 426 | cpp | check_bmi_key_supported.cpp | /* Copyright 2003-2018 Joaquin M Lopez Munoz.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* See http://www.boost.org/libs/multi_index for library home page.
*/
#include <boost/multi_index/key.hpp>
#if !defined(BOOST_MULTI_INDEX_KEY_SUPPORTED)
#error BOOST_MULTI_INDEX_KEY_SUPPORTED macro not defined
#endif
|
1859884dc4def84f3caf469f98069d0523b5aab7 | d3c2f4d3df9385d8f8e6535feaa563a10c896e5e | /src/HwlocHelpers.hxx | b38b7c4df1659eed03e65ed97291bf973c974a48 | [] | no_license | kaifabian/mlc | 42eb9c5edb970bdd1ae632ffbef96e3160180f71 | 62707c2856702c83052d5aea1bf49dab341b398a | refs/heads/master | 2021-01-23T19:33:57.808996 | 2017-09-05T11:17:31 | 2017-09-05T11:17:31 | 102,828,542 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,077 | hxx | HwlocHelpers.hxx | #pragma once
#include <vector>
#include <hwloc.h>
//#include <hwloc/bitmap.h>
//#include <hwloc/cpuset.h>
//#include <hwloc/helper.h>
#include "Types.hxx"
using namespace std;
static inline bool Hwloc_IsNumaMachine(const hwloc_topology_t &topology) {
unsigned num_nodes = hwloc_get_nbobjs_by_type(topology, HWLOC_OBJ_NODE);
return num_nodes > 1;
}
static hwloc_obj_t Hwloc_GetNodeById(const hwloc_topology_t &topology, NodeID node_id) {
hwloc_obj_type_t hwloc_type = Hwloc_IsNumaMachine(topology) ? HWLOC_OBJ_NODE : HWLOC_OBJ_SOCKET;
return hwloc_get_obj_by_type(topology, hwloc_type, node_id);
}
static size_t Hwloc_GetSmallestNodeMemory(const hwloc_topology_t &topology) {
if(!Hwloc_IsNumaMachine(topology)) {
hwloc_obj_t machine = hwloc_get_obj_by_type(topology, HWLOC_OBJ_MACHINE, 0);
return machine->memory.local_memory;
}
size_t smallest_memory = (size_t) -1;
for(unsigned i = 0; i < hwloc_get_nbobjs_by_type(topology, HWLOC_OBJ_NODE); i++) {
hwloc_obj_t node = hwloc_get_obj_by_type(topology, HWLOC_OBJ_NODE, i);
if(node->memory.local_memory < smallest_memory)
smallest_memory = node->memory.local_memory;
}
return smallest_memory;
}
static size_t Hwloc_GetLargestCachePerPU(const hwloc_topology_t &topology, unsigned index) {
size_t largest_cache = 0;
hwloc_obj_t pu = hwloc_get_obj_by_type(topology, HWLOC_OBJ_PU, index);
if(!pu) return 0;
for(hwloc_obj_t obj = pu; obj; obj = obj->parent) {
if(obj->type == HWLOC_OBJ_CACHE) {
size_t cache_size = obj->attr->cache.size;
if(cache_size > largest_cache)
largest_cache = cache_size;
}
}
return largest_cache;
}
static size_t Hwloc_GetLargestCache(const hwloc_topology_t &topology) {
unsigned num_cores = hwloc_get_nbobjs_by_type(topology, HWLOC_OBJ_PU);
size_t largest_cache = 0;
for(unsigned i = 0; i <= num_cores + 1; i++) {
size_t cache_size = Hwloc_GetLargestCachePerPU(topology, i);
if(cache_size > largest_cache)
largest_cache = cache_size;
}
if(largest_cache == 0) {
/* no caches? assume largest page size */
hwloc_obj_t machine = hwloc_get_obj_by_type(topology, HWLOC_OBJ_MACHINE, 0);
for(unsigned i = 0; i < machine->memory.page_types_len; i++) {
size_t page_size = machine->memory.page_types[i].size;
if(page_size > largest_cache)
largest_cache = page_size;
}
}
if(!largest_cache) {
/* We could not find anything. Assume 1MB. */
largest_cache = 1 * 1024 * 1024;
}
return largest_cache;
}
static inline CoreID Hwloc_GetCoreIDByCPU(const hwloc_topology_t &topology, unsigned int cpu_id) {
return hwloc_get_pu_obj_by_os_index(topology, cpu_id)->logical_index;
}
static inline unsigned int Hwloc_GetCPUByCoreID(const hwloc_topology_t &topology, CoreID core_id) {
hwloc_obj_t core = hwloc_get_obj_by_type(topology, HWLOC_OBJ_PU, core_id);
return core->os_index;
}
static inline NodeID Hwloc_GetNodeByCoreID(const hwloc_topology_t &topology, CoreID core_id) {
hwloc_obj_t core = hwloc_get_obj_by_type(topology, HWLOC_OBJ_PU, core_id);
hwloc_obj_t node = hwloc_get_ancestor_obj_by_type(topology, HWLOC_OBJ_NODE, core);
return node->logical_index;
}
static inline hwloc_cpuset_t Hwloc_GetCPUSetByCoreID(const hwloc_topology_t &topology, CoreID core_id) {
return hwloc_get_obj_by_type(topology, HWLOC_OBJ_PU, core_id)->allowed_cpuset;
}
static inline hwloc_nodeset_t Hwloc_GetNodeSetByNodeID(const hwloc_topology_t &topology, NodeID node_id) {
hwloc_obj_t node = Hwloc_GetNodeById(topology, node_id);
return node->allowed_nodeset;
}
static inline hwloc_cpuset_t Hwloc_GetCPUSetByNodeID(const hwloc_topology_t &topology, NodeID node_id) {
hwloc_obj_t node = Hwloc_GetNodeById(topology, node_id);
return node->allowed_cpuset;
}
static inline void* Hwloc_AllocMemoryOnNode(const hwloc_topology_t &topology, NodeID node_id, size_t size) {
if(!Hwloc_IsNumaMachine(topology)) {
return malloc(size);
}
hwloc_nodeset_t nodeset = Hwloc_GetNodeSetByNodeID(topology, node_id);
return hwloc_alloc_membind_nodeset(topology, size, nodeset, HWLOC_MEMBIND_BIND, HWLOC_MEMBIND_STRICT | HWLOC_MEMBIND_NOCPUBIND);
}
|
222b6bae51b20f7046a9d258732b9541980f3688 | a94935bd3855fa6da97265b491dd18930ccbb134 | /RealmLib/Packets/Client/Escape.cpp | 02c419dafd3108ce3c2aa672ec3704809c8a5ac7 | [
"MIT"
] | permissive | hcoffey1/RealmNet | 7531deed1fd80baaeb1fa8b42aa73271d86241e8 | 76ead08b4a0163a05b65389e512942a620331256 | refs/heads/master | 2022-04-25T13:37:49.505083 | 2019-03-05T21:29:56 | 2019-03-05T21:29:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 431 | cpp | Escape.cpp | #include "stdafx.h"
#include <GameData/Constants.h>
#include <GameData/TypeManager.h>
#include "Packets/PacketWriter.h"
#include <Packets/Escape.h>
Escape::Escape()
{
}
Escape::Escape(byte* data)
{
}
void Escape::emplace(byte* buffer) const
{
PacketWriter w(buffer, size(), TypeManager::typeToId[PacketType::Escape]);
}
int Escape::size() const
{
return 5;
}
String Escape::toString() const
{
return String("ESCAPE");
} |
498fc555359ff42c11a0f47128546a4501a6e795 | d51d72f1b6e834d89c8551bb07487bed84cdaa31 | /src/output/osg/osg/ColorMask_pmoc.cpp | dd3358bbf51e765f375ddfe2c1882bca263e118a | [] | no_license | wangfeilong321/osg4noob | 221204aa15efa18f1f049548ad076ef27371ecad | 99a15c3fd2523c4bd537fa3afb0b47e15c8f335a | refs/heads/master | 2021-01-12T20:00:43.854775 | 2015-11-06T15:37:01 | 2015-11-06T15:37:01 | 48,840,543 | 0 | 1 | null | 2015-12-31T07:56:31 | 2015-12-31T07:56:31 | null | UTF-8 | C++ | false | false | 4,080 | cpp | ColorMask_pmoc.cpp | #include <osg/ColorMask>
//includes
#include <iostream>
#include <MetaQQuickLibraryRegistry.h>
#include <QtQml/QQmlEngine>
#include <osg/ColorMask_pmoc.hpp>
#include <customCode/osg/ColorMask_pmoc.hpp>
#include <customCode/osg/StateAttribute_pmoc.hpp>
#include <customCode/osg/StateAttribute_pmoc.hpp>
using namespace pmoc;
int osg::QReflect_ColorMask::compare(osg::QReflect_StateAttribute *p0)const{
return _model->compare(*p0->_model);
}
void osg::QReflect_ColorMask::setMask( bool p0 , bool p1 , bool p2 , bool p3){
_model->setMask(p0 ,p1 ,p2 ,p3);
}
const bool osg::QReflect_ColorMask::getAlphaMask()const{return _model->getAlphaMask();}
const bool osg::QReflect_ColorMask::getBlueMask()const{return _model->getBlueMask();}
const bool osg::QReflect_ColorMask::getGreenMask()const{return _model->getGreenMask();}
const bool osg::QReflect_ColorMask::getRedMask()const{return _model->getRedMask();}
void osg::QReflect_ColorMask::setAlphaMask(const bool &par){_model->setAlphaMask(par);emit AlphaMaskChanged(par);}
void osg::QReflect_ColorMask::setBlueMask(const bool &par){_model->setBlueMask(par);emit BlueMaskChanged(par);}
void osg::QReflect_ColorMask::setGreenMask(const bool &par){_model->setGreenMask(par);emit GreenMaskChanged(par);}
void osg::QReflect_ColorMask::setRedMask(const bool &par){_model->setRedMask(par);emit RedMaskChanged(par);}
///DefaultConstructor////////////////
osg::QReflect_ColorMask::QReflect_ColorMask(Instance *i,QObject* parent):QQModel(i,parent),_model(0){
if(!_model) _model =reinterpret_cast<osg::ColorMask*>(i->ptr);
_parentboxes[0]=0;
///Initialize Qt Model Here/////////////////////////////////////////
}
///Destuctor////////////////
osg::QReflect_ColorMask::~QReflect_ColorMask( ){
if(_parentboxes[0])
delete _parentboxes[0];
}
///update this according _model new state
void osg::QReflect_ColorMask::updateModel(){
if(_parentboxes[0])
_parentboxes[0]->updateModel();
}
Instance osg::MetaQReflect_ColorMask::createInstance( ){
osg::ref_ptr<osg::ColorMask> osg_ColorMask_ptr ;
osg_ColorMask_ptr = new osg::ColorMask () ;
Instance o(PMOCGETMETACLASS("osg::ColorMask"),(void*)osg_ColorMask_ptr.get() ,true);
_managedinstances.insert(osg_ColorMask_ptr);
return(o);
}///////////////////////////////////////////META CLASS STRING////////////////////////////////////////////////////
osg::MetaQReflect_ColorMask::MetaQReflect_ColorMask():MetaQQuickClass( "osg::ColorMask"){
_typeid=&typeid(osg::ColorMask ); qRegisterMetaType<QMLColorMask>();
qmlRegisterType<QReflect_ColorMask>("pmoc.osg",1,0,"QReflect_ColorMask");
qmlRegisterType<QMLColorMask>("pmoc.osg",1,0,"QMLColorMask");
};
const std::string osg::MetaQReflect_ColorMask::Imports() const{
return std::string("");
}
///if write the external qml in order not to use internal composition
///else these strings will be used to composite it hierarchically
const std::string osg::MetaQReflect_ColorMask::PREcompoQML()const{return std::string("");}
const std::string osg::MetaQReflect_ColorMask::POSTcompoQML()const{return std::string("");}
QQModel* osg::MetaQReflect_ColorMask::createQQModel(Instance*i){ //return new MetaQReflect_ColorMask_QModel(i);}
QMLColorMask *ret =new QMLColorMask(i);
bool gencontextmenu=false;
if(contextMenu.empty())gencontextmenu=true;
if(gencontextmenu)
contextMenu+= pmoc::MetaQQuickClass::getPartialContextMenu(*ret);
{
osg::StateAttribute *mother =dynamic_cast<osg::StateAttribute*>(ret->_model);
Instance inst;inst.model=PMOCGETMETACLASS("osg::StateAttribute");
inst.ptr=reinterpret_cast<void*>(mother);
if(!inst.isValid()){std::cerr<<"osg::StateAttribute model for osg::ColorMaskis invalid"<<std::endl;return ret;}
pmoc::MetaQQuickClass *cl=PMOCGETMETACLASS("osg::StateAttribute");
if(!cl){std::cerr<<"osg::StateAttribute QQModel for osg::ColorMaskis not found"<<std::endl;return ret;}
ret->_parentboxes[0]=cl->createQQModel(&inst);
if(gencontextmenu)
contextMenu+=cl->contextMenu;
}
return ret;}
#ifndef AUTOMOCCPP
#define AUTOMOCCPP 1
#include "moc_ColorMask_pmoc.cpp"
#endif
|
0c48755847a49e1403af681b775f0a0f3f7be760 | 46f4d453bb7104a41f88e3a9b9b11a84b0480421 | /include/rua/file/posix.hpp | 46d333d5b7d0d49f99c285098ea66dd23a45ffdc | [
"MIT"
] | permissive | yulon/rua | 40f16d8c2bf3e5ea549e3bc56994cbcf3c1a7e0e | ab8a3d5532aa5f7cdc19ae3a517326a173d3ea28 | refs/heads/master | 2023-08-10T13:46:13.422627 | 2023-08-08T11:46:19 | 2023-08-08T11:46:19 | 108,065,006 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,605 | hpp | posix.hpp | #ifndef _rua_file_posix_hpp
#define _rua_file_posix_hpp
#include "times.hpp"
#include "../path.hpp"
#include "../range.hpp"
#include "../string/join.hpp"
#include "../sys/stream/posix.hpp"
#include "../time/now/posix.hpp"
#include "../util.hpp"
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <cassert>
#include <string>
namespace rua { namespace posix {
class file_path : public path_base<file_path> {
public:
RUA_PATH_CTORS(file_path)
bool is_exist() const {
struct stat st;
return stat(str().c_str(), &st) == 0;
}
bool is_dir() const {
struct stat st;
return stat(str().c_str(), &st) == 0 ? S_ISDIR(st.st_mode) : false;
}
file_path abs() const & {
const auto &s = str();
if (s.size() > 0 && s[0] == '/') {
return *this;
}
return $abs(s);
}
file_path abs() && {
const auto &s = str();
if (s.size() > 0 && s[0] == '/') {
return std::move(*this);
}
return $abs(s);
}
private:
static file_path $abs(const std::string &str) {
auto c_str = realpath(str.c_str(), nullptr);
file_path r(c_str);
::free(c_str);
return r;
}
};
class file_info {
public:
using native_data_t = struct stat;
////////////////////////////////////////////////////////////////////////
file_info() = default;
native_data_t &native_data() {
return $data;
}
const native_data_t &native_data() const {
return $data;
}
bool is_dir() const {
return S_ISDIR($data.st_mode);
}
uint64_t size() const {
return static_cast<uint64_t>($data.st_size);
}
file_times times(int8_t zone = local_time_zone()) const {
return {modified_time(zone), creation_time(zone), access_time(zone)};
}
time modified_time(int8_t zone = local_time_zone()) const {
return time($data.st_mtime, zone, unix_epoch);
}
time creation_time(int8_t zone = local_time_zone()) const {
return time($data.st_ctime, zone, unix_epoch);
}
time access_time(int8_t zone = local_time_zone()) const {
return time($data.st_atime, zone, unix_epoch);
}
private:
struct stat $data;
};
class file : public sys_stream {
public:
file() : sys_stream() {}
file(sys_stream s) : sys_stream(std::move(s)) {}
file(native_handle_t fd, bool need_close = true) :
sys_stream(fd, need_close) {}
template <
typename NullPtr,
typename = enable_if_t<is_null_pointer<NullPtr>::value>>
constexpr file(NullPtr) : sys_stream() {}
file_info info() const {
file_info r;
if (!fstat(native_handle(), &r.native_data())) {
return r;
}
memset(&r, 0, sizeof(r));
return r;
}
bool is_dir() const {
return info().is_dir();
}
uint64_t size() const {
return info().size();
}
virtual int64_t seek(int64_t offset, uchar whence = 0) {
return static_cast<int64_t>(lseek(native_handle(), offset, whence));
}
bytes read_all() {
auto fsz = size();
bytes buf(fsz);
auto rsz = read_full(buf);
if (rsz >= 0 && static_cast<uint64_t>(rsz) != fsz) {
buf.reset();
}
return buf;
}
file_times times(int8_t zone = local_time_zone()) const {
return info().times(zone);
}
time modified_time(int8_t zone = local_time_zone()) const {
return times(zone).modified_time;
}
time creation_time(int8_t zone = local_time_zone()) const {
return times(zone).creation_time;
}
time access_time(int8_t zone = local_time_zone()) const {
return times(zone).access_time;
}
};
using dir_entry_info = file_info;
class dir_entry {
public:
using native_data_t = struct dirent;
////////////////////////////////////////////////////////////////////////
dir_entry() = default;
native_data_t &native_data() {
return *$data;
}
const native_data_t &native_data() const {
return *$data;
}
std::string name() const {
return $data->d_name;
}
file_path path() const {
return {$dir_path, name()};
}
file_path relative_path() const {
return {$dir_rel_path, name()};
}
bool is_dir() const {
return $data->d_type == DT_DIR;
}
dir_entry_info info() const {
dir_entry_info r;
if (!stat(path().str().c_str(), &r.native_data())) {
return r;
}
memset(&r, 0, sizeof(r));
return r;
}
uint64_t size() const {
return info().size();
}
file_times times(int8_t zone = local_time_zone()) const {
return info().times(zone);
}
time modified_time(int8_t zone = local_time_zone()) const {
return info().modified_time(zone);
}
time creation_time(int8_t zone = local_time_zone()) const {
return info().creation_time(zone);
}
time access_time(int8_t zone = local_time_zone()) const {
return info().access_time(zone);
}
private:
struct dirent *$data;
std::string $dir_path, $dir_rel_path;
friend class view_dir;
};
class view_dir : private wandering_iterator {
public:
using native_handle_t = DIR *;
////////////////////////////////////////////////////////////////////////
view_dir() : $dir(nullptr) {}
view_dir(const file_path &path, size_t depth = 1) :
$dir(opendir(path.str().c_str())), $dep(depth), $parent(nullptr) {
if (!$dir) {
return;
}
$entry.$dir_path = std::move(path).abs().str();
if ($next()) {
return;
}
closedir($dir);
$dir = nullptr;
}
~view_dir() {
if (!$dir) {
return;
}
closedir($dir);
$dir = nullptr;
if ($parent) {
delete $parent;
}
}
view_dir(view_dir &&src) :
$dir(src.$dir),
$entry(std::move(src.$entry)),
$dep(src.$dep),
$parent(src.$parent) {
if (src) {
src.$dir = nullptr;
}
}
view_dir(view_dir &src) : view_dir(std::move(src)) {}
RUA_OVERLOAD_ASSIGNMENT(view_dir)
view_dir &operator=(view_dir &src) {
return *this = std::move(src);
}
native_handle_t native_handle() const {
return $dir;
}
operator bool() const {
return $dir;
}
const dir_entry &operator*() const {
return $entry;
}
const dir_entry *operator->() const {
return &$entry;
}
view_dir &operator++() {
assert($dir);
if (($dep > 1 || !$dep) && $entry.is_dir()) {
view_dir sub($entry.path(), $dep > 1 ? $dep - 1 : 0);
if (sub) {
sub.$entry.$dir_rel_path = $entry.relative_path().str();
sub.$parent = new view_dir(std::move(*this));
return *this = std::move(sub);
}
}
if ($next()) {
return *this;
}
while ($parent) {
auto parent = $parent;
$parent = nullptr;
*this = std::move(*parent);
delete parent;
if ($next()) {
return *this;
}
}
closedir($dir);
$dir = nullptr;
return *this;
}
private:
DIR *$dir;
dir_entry $entry;
size_t $dep;
view_dir *$parent;
static bool $is_dots(const char *c_str) {
for (; *c_str; ++c_str) {
if (*c_str != '.') {
return false;
}
}
return true;
}
bool $next() {
while (assign($entry.$data, readdir($dir))) {
if ($is_dots($entry.$data->d_name)) {
continue;
}
return true;
}
return false;
}
};
namespace _make_file {
inline bool touch_dir(const file_path &path, mode_t mode = 0777) {
if (!path || path.is_dir()) {
return true;
}
if (!touch_dir(path.rm_back(), mode)) {
return false;
}
return mkdir(path.str().c_str(), mode) == 0;
}
inline file make_file(const file_path &path) {
if (!touch_dir(path.rm_back())) {
return nullptr;
}
return open(path.str().c_str(), O_CREAT | O_TRUNC | O_RDWR);
}
inline file touch_file(const file_path &path) {
if (!touch_dir(path.rm_back())) {
return nullptr;
}
return open(path.str().c_str(), O_CREAT | O_RDWR);
}
inline file modify_file(const file_path &path, bool = false) {
return open(path.str().c_str(), O_RDWR);
}
inline file view_file(const file_path &path, bool = false) {
return open(path.str().c_str(), O_RDONLY);
}
inline bool remove_file(const file_path &path) {
if (!path.is_dir()) {
return !unlink(path.str().c_str());
}
for (auto &ety : view_dir(path)) {
remove_file(ety.path());
}
return !rmdir(path.str().c_str());
}
inline bool copy_file(
const file_path &src, const file_path &dest, bool replaceable_dest = true) {
if (!replaceable_dest && dest.is_exist()) {
return false;
}
auto dest_f = make_file(dest);
if (!dest_f) {
return false;
}
auto src_f = view_file(src);
if (!src_f) {
return false;
}
return dest_f.copy(src_f);
}
inline bool move_file(
const file_path &src, const file_path &dest, bool replaceable_dest = true) {
if (dest.is_exist()) {
if (!replaceable_dest) {
return false;
}
return remove_file(dest);
}
auto err = ::rename(src.str().c_str(), dest.str().c_str());
if (!err) {
return true;
}
auto ok = copy_file(src, dest, replaceable_dest);
if (!ok) {
return false;
}
return remove_file(src);
}
} // namespace _make_file
using namespace _make_file;
}} // namespace rua::posix
#endif
|
84d1393551a41213d949508fa3fa32c1c25304af | d61d05748a59a1a73bbf3c39dd2c1a52d649d6e3 | /chromium/third_party/mach_override/mach_override.h | 253f273d16b6aba27aea33533d6ee89a80fa522b | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | Csineneo/Vivaldi | 4eaad20fc0ff306ca60b400cd5fad930a9082087 | d92465f71fb8e4345e27bd889532339204b26f1e | refs/heads/master | 2022-11-23T17:11:50.714160 | 2019-05-25T11:45:11 | 2019-05-25T11:45:11 | 144,489,531 | 5 | 4 | BSD-3-Clause | 2022-11-04T05:55:33 | 2018-08-12T18:04:37 | null | UTF-8 | C++ | false | false | 3,883 | h | mach_override.h | // mach_override.h semver:1.2.0
// Copyright (c) 2003-2012 Jonathan 'Wolf' Rentzsch: http://rentzsch.com
// Some rights reserved: http://opensource.org/licenses/mit
// https://github.com/rentzsch/mach_override
#ifndef _mach_override_
#define _mach_override_
#include <sys/types.h>
#include <mach/error.h>
#define err_cannot_override (err_local|1)
__BEGIN_DECLS
/****************************************************************************************
Dynamically overrides the function implementation referenced by
originalFunctionAddress with the implentation pointed to by overrideFunctionAddress.
Optionally returns a pointer to a "reentry island" which, if jumped to, will resume
the original implementation.
@param originalFunctionAddress -> Required address of the function to
override (with overrideFunctionAddress).
@param overrideFunctionAddress -> Required address to the overriding
function.
@param originalFunctionReentryIsland <- Optional pointer to pointer to the
reentry island. Can be NULL.
@result <- err_cannot_override if the original
function's implementation begins with
the 'mfctr' instruction.
************************************************************************************/
mach_error_t
mach_override_ptr(
void *originalFunctionAddress,
const void *overrideFunctionAddress,
void **originalFunctionReentryIsland );
/****************************************************************************************
mach_override_ptr makes multiple allocation attempts with vm_allocate or malloc,
until a suitable address is found for the branch islands. This method returns the
global number of such attempts made by all mach_override_ptr calls so far. This
statistic is provided for testing purposes and it can be off, if mach_override_ptr
is called by multiple threads.
@result <- Total number of vm_allocate calls so far.
************************************************************************************/
u_int64_t mach_override_ptr_allocation_attempts();
__END_DECLS
/****************************************************************************************
If you're using C++ this macro will ease the tedium of typedef'ing, naming, keeping
track of reentry islands and defining your override code. See test_mach_override.cp
for example usage.
************************************************************************************/
#ifdef __cplusplus
#define MACH_OVERRIDE( ORIGINAL_FUNCTION_RETURN_TYPE, ORIGINAL_FUNCTION_NAME, ORIGINAL_FUNCTION_ARGS, ERR ) \
{ \
static ORIGINAL_FUNCTION_RETURN_TYPE (*ORIGINAL_FUNCTION_NAME##_reenter)ORIGINAL_FUNCTION_ARGS; \
static bool ORIGINAL_FUNCTION_NAME##_overriden = false; \
class mach_override_class__##ORIGINAL_FUNCTION_NAME { \
public: \
static kern_return_t override(void *originalFunctionPtr) { \
kern_return_t result = err_none; \
if (!ORIGINAL_FUNCTION_NAME##_overriden) { \
ORIGINAL_FUNCTION_NAME##_overriden = true; \
result = mach_override_ptr( (void*)originalFunctionPtr, \
(void*)mach_override_class__##ORIGINAL_FUNCTION_NAME::replacement, \
(void**)&ORIGINAL_FUNCTION_NAME##_reenter ); \
} \
return result; \
} \
static ORIGINAL_FUNCTION_RETURN_TYPE replacement ORIGINAL_FUNCTION_ARGS {
#define END_MACH_OVERRIDE( ORIGINAL_FUNCTION_NAME ) \
} \
}; \
\
err = mach_override_class__##ORIGINAL_FUNCTION_NAME::override((void*)ORIGINAL_FUNCTION_NAME); \
}
#endif
#endif // _mach_override_
|
f0514087a1237bff965c175cd81856a50a9f293d | bb68632c4cd50982ebd9bc07c5dd533d98217c08 | /Solution/Day-579.cpp | 06faf5be29e2e8f5229a2bb9f82ca966921c2366 | [] | no_license | offamitkumar/Daily-Coding-Problem | 83a4ba127d2118d20fbbe99aa832400c71ce8bfa | e831e360bb1170162473a5e4ddf9b07d134826c1 | refs/heads/master | 2023-07-21T01:24:37.558689 | 2023-07-13T03:24:30 | 2023-07-13T03:24:30 | 234,764,757 | 32 | 12 | null | 2023-07-13T03:24:31 | 2020-01-18T16:41:42 | C++ | UTF-8 | C++ | false | false | 1,081 | cpp | Day-579.cpp | class Solution {
public:
int reachNumber(int target) {
// either by adding the values we are going to get the sum
// or we need to make the (target-currentPos) even number , because
// with even number we can make the displacement 0, let's say your difference
// is 10 then you can move 5 step back and 5 step ahead and distance covered by you will be 10
// but will it make any impact on your journey, NO; as you are at the same position where you started.
// but in our case you overcome the extra 10 unit distance which is exceeding the target value;
// you can't break a odd number in two equal weights , just try a few testcase you will get it.
int current = 0 , moves = 0 , inc = 1;
target = abs(target);
while (true) {
if(target == current) {
break;
}
if (target < current && (target-current)%2==0) {
break;
}
current+=inc++;
++moves;
}
return moves;
}
};
|
8895fc8c49762b8b7f83a097702403bf90761275 | 44c8dbbe8cf860eadced513fcfea756c2f0dec9f | /Plugins/MediaPipe/Source/MediaPipe/Private/MediaPipeModule.h | 556fabd4708dab347295509ae9c77f8eeaab49b3 | [
"Apache-2.0"
] | permissive | FashengChen0622/ue4-mediapipe-plugin | 41ddaca0572a718028a4e7210b428b5a29d12aa4 | 28c2dfa2ddcb00296bf3307c6651dc60b7533ca6 | refs/heads/master | 2023-09-04T14:30:20.317405 | 2021-11-23T15:46:08 | 2021-11-23T15:46:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 368 | h | MediaPipeModule.h | #pragma once
#include "IMediaPipeModule.h"
#include "Interfaces/IPluginManager.h"
class FMediaPipeModule : public IMediaPipeModule
{
public:
void StartupModule() override;
void ShutdownModule() override;
class IUmpPipeline* CreatePipeline() override;
private:
void* LibUmp = nullptr;
void* CreateContextPtr = nullptr;
class IUmpContext* Context = nullptr;
};
|
faf7b9cab3bbb8ecd98f29b9ac80c89f4fb1640e | 6c9bd50bdc4790c77d4840483cd126bea3c730f3 | /2nd semester/Object-oriented-programming/Seminars/Seminar 04 Demo/Seminar4/SEminar4/Instance.cpp | 93d51e073784614b96d6775ecf915db00e0c5359 | [] | no_license | toadereandreas/Babes-Bolyai-University | b9689951b88cce195726417ec55f0ced1aa4b8e6 | ca6269864e5ade872cb5522a3ceb94a206e207b3 | refs/heads/master | 2022-09-24T13:11:03.610221 | 2020-06-04T12:19:12 | 2020-06-04T12:19:12 | 268,924,167 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 547 | cpp | Instance.cpp | #include "Instance.h"
#include <string>
#include <sstream>
#include "Utils.h"
using namespace std;
std::istream & operator>>(std::istream & is, Instance & instance)
{
instance.reset_instance();
string s{};
getline(is, s);
vector<string> tokens = tokenize(s, ',');
if (tokens.size() == 0)
return is;
for (int i = 0; i < tokens.size() - 1; i++)
instance.input.push_back(stod(tokens[i]));
instance.output = stoi(tokens[tokens.size() - 1]);
return is;
}
void Instance::reset_instance()
{
this->input.clear();
this->output = -1;
}
|
67eb3f5dbebf6b48c492615c7d05eeaccefb669a | a923d47124ad3663c5fb70f5f0ccfb46365b4afa | /include/GlobalInfo.h | 5127e236e42be03362daa6ee25b5bc1fac7343bc | [] | no_license | ssyram/NovelRulesTranslator | f78cd0b06d1ded86b4a3eccbc18592848a228003 | ce87d121e10e8244db1202f300f3f321e7077504 | refs/heads/master | 2021-06-18T14:38:15.032394 | 2021-02-06T22:33:33 | 2021-02-06T22:33:33 | 175,027,327 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 884 | h | GlobalInfo.h | //
// GlobalInfo.h
// NovelRulesTranslator
//
// Created by 潇湘夜雨 on 2019/2/25.
// Copyright © 2019 ssyram. All rights reserved.
//
#ifndef GlobalInfo_h
#define GlobalInfo_h
#define TEST_TABLEGEN
#define TEST
#include <string>
#include <istream>
#include <type_traits>
#include <iostream>
#include <assert.h>
template <typename ttr>
void generateException(const std::string &s, std::istream &is) {
std::string rs(s);
rs += ": ";
char info[128];
is.seekg(-64, std::ios_base::cur).read(info, 64);
// mark this place
info[64] = '('; info[65] = '^'; info[66] = ')';
is.read(info + 67, 60);
info[127] = '\0';
if (is.fail()) {
std::cout << "Fail" << std::endl;
is.unget();
}
else if (is.bad()) {
std::cout << "Bad" << std::endl;
}
throw ttr(rs += info);
}
#endif /* GlobalInfo_h */
|
6009d90dd845c04e19d85ca2fbc6d5d3a68c7e7b | a5f3b0001cdb692aeffc444a16f79a0c4422b9d0 | /main/connectivity/inc/connectivity/sdbcx/VKey.hxx | a0a2a7f39ad5118397612a1a236c92af90dbe2c0 | [
"Apache-2.0",
"CPL-1.0",
"bzip2-1.0.6",
"LicenseRef-scancode-other-permissive",
"Zlib",
"LZMA-exception",
"LGPL-2.0-or-later",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-philippe-de-muyter",
"OFL-1.1",
"LGPL-2.1-only",
"MPL-1.1",
"X11",
"LGPL-2.1-or-later",
"GPL-2.0-only",
... | permissive | apache/openoffice | b9518e36d784898c6c2ea3ebd44458a5e47825bb | 681286523c50f34f13f05f7b87ce0c70e28295de | refs/heads/trunk | 2023-08-30T15:25:48.357535 | 2023-08-28T19:50:26 | 2023-08-28T19:50:26 | 14,357,669 | 907 | 379 | Apache-2.0 | 2023-08-16T20:49:37 | 2013-11-13T08:00:13 | C++ | UTF-8 | C++ | false | false | 4,842 | hxx | VKey.hxx | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef _CONNECTIVITY_SDBCX_KEY_HXX_
#define _CONNECTIVITY_SDBCX_KEY_HXX_
#include <comphelper/IdPropArrayHelper.hxx>
#include "connectivity/CommonTools.hxx"
#include <comphelper/broadcasthelper.hxx>
#include "connectivity/sdbcx/VTypeDef.hxx"
#include <com/sun/star/container/XNamed.hpp>
#include "connectivity/sdbcx/IRefreshable.hxx"
#include "connectivity/sdbcx/VDescriptor.hxx"
#include "connectivity/dbtoolsdllapi.hxx"
#include <cppuhelper/implbase1.hxx>
#include <com/sun/star/sdbcx/XDataDescriptorFactory.hpp>
#include <boost/shared_ptr.hpp>
namespace connectivity
{
namespace sdbcx
{
struct OOO_DLLPUBLIC_DBTOOLS KeyProperties
{
::std::vector< ::rtl::OUString> m_aKeyColumnNames;
::rtl::OUString m_ReferencedTable;
sal_Int32 m_Type;
sal_Int32 m_UpdateRule;
sal_Int32 m_DeleteRule;
KeyProperties(const ::rtl::OUString& _ReferencedTable,
sal_Int32 _Type,
sal_Int32 _UpdateRule,
sal_Int32 _DeleteRule)
:m_ReferencedTable(_ReferencedTable),
m_Type(_Type),
m_UpdateRule(_UpdateRule),
m_DeleteRule(_DeleteRule)
{}
KeyProperties():m_Type(0),m_UpdateRule(0),m_DeleteRule(0){}
};
typedef ::boost::shared_ptr< KeyProperties > TKeyProperties;
typedef ::cppu::ImplHelper1< ::com::sun::star::sdbcx::XDataDescriptorFactory > OKey_BASE;
class OCollection;
class OOO_DLLPUBLIC_DBTOOLS OKey :
public comphelper::OBaseMutex,
public ODescriptor_BASE,
public IRefreshableColumns,
public ::comphelper::OIdPropertyArrayUsageHelper<OKey>,
public ODescriptor,
public OKey_BASE
{
protected:
TKeyProperties m_aProps;
OCollection* m_pColumns;
using ODescriptor_BASE::rBHelper;
// OPropertyArrayUsageHelper
virtual ::cppu::IPropertyArrayHelper* createArrayHelper( sal_Int32 _nId) const;
// OPropertySetHelper
virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();
public:
OKey(sal_Bool _bCase);
OKey(const ::rtl::OUString& _Name,const TKeyProperties& _rProps,sal_Bool _bCase);
/*OKey( const ::rtl::OUString& _Name,
const ::rtl::OUString& _ReferencedTable,
sal_Int32 _Type,
sal_Int32 _UpdateRule,
sal_Int32 _DeleteRule,
sal_Bool _bCase);*/
virtual ~OKey( );
DECLARE_SERVICE_INFO();
//XInterface
virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL acquire() throw();
virtual void SAL_CALL release() throw();
//XTypeProvider
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException);
// ODescriptor
virtual void construct();
// ::cppu::OComponentHelper
virtual void SAL_CALL disposing();
// XPropertySet
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException);
// XColumnsSupplier
virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getColumns( ) throw(::com::sun::star::uno::RuntimeException);
// XNamed
virtual ::rtl::OUString SAL_CALL getName( ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException);
// XDataDescriptorFactory
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > SAL_CALL createDataDescriptor( ) throw(::com::sun::star::uno::RuntimeException);
};
}
}
#endif // _CONNECTIVITY_SDBCX_KEY_HXX_
|
d54e86e173dcf396bea71cf63beae145759faba7 | 69d42439ce19fff1d62ae24cba96180c506000ba | /cmake/lesson4/cat.hh | bfa475bbd553a9a763cc8a035015ece5d98b0bea | [] | no_license | patorseing/build_tool_leason | f97c56e6dad5a7f062372b9243fb5e9f812904eb | 3588fbd70017b1df00df4bc64a1ea623584cd51e | refs/heads/main | 2023-03-12T22:20:46.360942 | 2021-02-27T23:30:31 | 2021-02-27T23:30:31 | 340,767,058 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 63 | hh | cat.hh | #ifndef CAT_HH
#define CAT_HH
void hello();
#endif // CAT_HH
|
000ee77a43341f47b93d94944169bb7322d321e9 | 8f02939917edda1e714ffc26f305ac6778986e2d | /BOJ/1422/main.cc | b2b2a17c47ea4f07b5c529a4227f3d723fc71f98 | [] | no_license | queuedq/ps | fd6ee880d67484d666970e7ef85459683fa5b106 | d45bd3037a389495d9937afa47cf0f74cd3f09cf | refs/heads/master | 2023-08-18T16:45:18.970261 | 2023-08-17T17:04:19 | 2023-08-17T17:04:19 | 134,966,734 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 859 | cc | main.cc | #include <bits/stdc++.h>
#define endl "\n"
using namespace std;
using lld = long long;
using pii = pair<int, int>;
using pll = pair<lld, lld>;
////////////////////////////////////////////////////////////////
bool cmp(string a, string b) {
return a+b < b+a;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
////////////////////////////////
int K, N; cin >> K >> N;
vector<string> S(K);
int sz = 0;
for (int i=0; i<K; i++) {
cin >> S[i];
sz = max(sz, (int)S[i].size());
}
sort(S.begin(), S.end(), cmp);
for (int i=N-1; i>=0; i--) {
if (S[i].size() == sz) {
for (int j=K; j<N; j++) S.push_back(S[i]);
break;
}
}
sort(S.begin(), S.end(), cmp);
string ans = "";
for (int i=N-1; i>=0; i--) ans.append(S[i]);
cout << ans << endl;
////////////////////////////////
return 0;
}
|
ddce962b89a677b4dc2b7baccf9cff96ff22e1b1 | a15778e6e7a9853a1f2798c11b5785f92830ce62 | /0221/1.Global,Local Variable.cpp | a5d8308362f506dd3b72deaebbc7611c461c6a3b | [] | no_license | charleslin826/C | 07c063475ef0c2619689201828f7ded6e95e4bc6 | aeb874a2bb4d7ef670a9f1cab1450f40f482afa7 | refs/heads/master | 2020-03-18T11:33:18.498638 | 2018-05-24T07:36:47 | 2018-05-24T07:36:47 | 134,678,386 | 0 | 0 | null | null | null | null | BIG5 | C++ | false | false | 442 | cpp | 1.Global,Local Variable.cpp | #include<stdio.h>
#include<stdlib.h>
void func();
int a=50; //此global variable無法影響裡面的 local variable
int main(){
/*int*/ a=100;
printf("Before call func(), a=%d\n",a);
func();
printf("After call func(), a=%d\n",a);//int的宣告拿掉後 就不是local variable了 而是直接改global的 所以結果會跟著變
system("pause");
return 0;
}
void func(){
/*int*/ a=300;
printf("In func() function, a=%d\n",a);
}
|
370c753b2b161104130566bb06bfac4a383d06b0 | 1e721a44ed81abe6b2a983e49b1d69126866e78d | /BOJ/Greedy/1120.cpp | d7e38da150f207aa79a855fdb1a6bc19c44b79cc | [] | no_license | jjwdi0/Code | eb19ad171f7223dbf0712e611c9fc179defd947b | cf8bf0859e086366b768f48bc7e16167185b153f | refs/heads/master | 2020-12-24T07:55:14.846130 | 2017-04-24T07:46:41 | 2017-04-24T07:46:41 | 73,354,849 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 327 | cpp | 1120.cpp | #include <stdio.h>
#include <string.h>
char a[53], b[53];
int ans = 1e9, cnt;
int min(int X, int Y){ return X > Y ? Y : X; }
int main() {
scanf("%s %s", a, b);
for(int i=0; i<=strlen(b)-strlen(a); i++) {
cnt = 0;
for(int j=i; j<i+strlen(a); j++) cnt += (a[j-i] != b[j]);
ans = min(cnt, ans);
}
printf("%d", ans);
}
|
395ea920a3947d7d0974a672c87dfdf890c5c4c0 | 4323f2c50b3e19c8dbf8161e966fcda54dc093f2 | /src/espix-design/views/TextView.cpp | 372f3e56a1f6f5e1373f04ecf7c3a8257004e46d | [] | no_license | stonexer/espix-sdk | 435edf1ca5dc9bbc198732b268d24ad03fed3e2a | ce356dd6c2467365e456e56bea42f8191a411f63 | refs/heads/master | 2021-01-06T10:49:56.016196 | 2020-02-18T05:33:28 | 2020-02-18T05:33:28 | 241,303,243 | 1 | 0 | null | 2020-02-18T07:55:17 | 2020-02-18T07:55:17 | null | UTF-8 | C++ | false | false | 715 | cpp | TextView.cpp | #include "TextView.h"
TextView::TextView(String text, FontSize fontSize, TextAlign textAlign) : View(), _text(text) {
if (text == NULL) {
text = "";
}
_text = text;
_fontSize = fontSize;
_textAlign = textAlign;
}
TextView::TextView(FontSize fontSize, TextAlign textAlign) : View() {
_text = "";
_fontSize = fontSize;
_textAlign = textAlign;
}
String TextView::getText() {
return _text;
}
void TextView::setText(String text) {
if (text == NULL) {
text = "";
}
if (!text.equals(_text)) {
_text = text;
setDirty();
}
}
void TextView::render(CanvasContext *context) {
context->setFontSize(_fontSize);
context->setTextAlign(_textAlign);
context->drawString(_text);
}
|
96eab93a44a22a083389a8b920bcb6209e5b1459 | 69bc103a348c29f42f982246a85828c18d9d930f | /TM/TMActionInput.cpp | 73a8e1b0d036b87cdfc89f1adc49a588187c4616 | [] | no_license | albertz/turingmachine | 79406f2867228be7aa2c11ed84864d816e3fa32e | 48c8d0fffa01b91a32a5f0a03a800222f7f142a1 | refs/heads/master | 2021-01-19T08:26:11.171294 | 2010-08-19T16:13:20 | 2010-08-19T16:13:20 | 848,884 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 329 | cpp | TMActionInput.cpp | #include "TMActionInput.h"
#include "StringUtils.h"
TMActionInput& TMActionInput::operator++() {
((int&)currentChar)++;
(int&)currentChar %= int(TMAx) + 1;
if(currentChar == TMA0)
state++;
return *this;
}
std::string TMActionInput::debugStr() const {
return "{s:" + itoa(state) + ", c:" + itoa(currentChar) + "}";
}
|
3d7494f7c645b1df901cf9d757883a464aa9bafa | e812bc6abf6467fa25b8c06bd7cc6006a697a319 | /Bank.cpp | f34b8f7b944026d6f1b9653098eebb481ec0b77d | [] | no_license | ashishpc/CPP-Practice | d8d99573f6552a03fbf3cf893340c1d0bab56fe2 | ff0c6fec422eaff61cdb9bf205c1cca45a98b430 | refs/heads/master | 2020-07-19T19:21:24.045963 | 2019-12-05T10:57:44 | 2019-12-05T10:57:44 | 206,500,421 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,683 | cpp | Bank.cpp | #include<iostream>
#include<string>
using namespace std;
class BankAcc
{
private:
int amount;
public:
BankAcc()
{
amount=0;
}
BankAcc(int amount):amount(amount)
{
}
int GetAmount() const
{
return amount;
}
void Deposit(int amt=100)
{
cout<<"Total balance (After deposition) is: "<<(amount+=amt);
}
void Withdrawl(int amt=200)
{
cout<<"Total balance (After Withdrawl) is: "<<(amount-=amt);
}
~BankAcc()
{
cout<<"\nBank account destroyed";
}
};
class SavingAcc:public BankAcc
{
private:
float IRate=4;
float TB;
public:
SavingAcc():BankAcc()
{
IRate = 4;
TB = 0;
}
SavingAcc(float amount,float IRate,float TB):BankAcc(amount)
{
IRate = IRate;
TB = TB;
}
void CalInt()
{
TB=BankAcc::GetAmount();
TB=TB+(TB*(IRate/100));
cout<<"Total Balance (After Interest Rate)"<<TB;
}
void displayBal()
{
cout<<"total bal with "<< IRate<<" % interest:"<<TB<<endl;
}
};
/*class SavingAcc : public BankAcc
{
private:
int IRate;
float TB;
float SI;
public:
SavingAcc()
{
IRate = 4;
TB = 0;
SI = 0;
}
SavingAcc(int amount,int IRate,int TB, float SI):BankAcc(amount)
{
IRate = IRate;
TB = TB;
SI = SI;
}
void CalInt()
{
cout<<"enter no of years:"<<endl;
cin>>n;
SI=amount*IRate/100;
TB=amount+SI;
}
void displayBal()
{
cout<<"total bal with 4% interest:"<<Stotal<<endl;
}
};
*/
int main()
{
/* BankAcc b1;
SavingAcc s1;
CurrentAcc s2;
s1.CalInt();
s1.displayBal();
s2.CalInt();
s2.displayBal();
*/
SavingAcc s1(1000,4,0);
s1.Deposit();
s1.Withdrawl();
s1.CalInt();
s1.BankAcc::Deposit();
return 0;
}
|
da0ae05ac03df81fc3ee478d68fcc0d72668f636 | f321a4e73f0070c53f2c24d5849007d4daae5ee9 | /0543. Diameter of Binary Tree/diameterOfBinaryTree02.cpp | 1bb8f778931d7888ad80ecdf49569f08d42d10dd | [] | no_license | cesar-magana/Leet-Code | fd502c967afa96109117d1bef1900a66f31e5790 | 0ebd4d658dc8bad40cbb96422ba9e01cb1ab442d | refs/heads/master | 2023-09-01T09:20:56.395546 | 2021-10-20T11:04:27 | 2021-10-20T11:04:27 | 265,043,424 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 312 | cpp | diameterOfBinaryTree02.cpp | int ans;
int height( TreeNode* node) {
if ( !node )
return 0;
int l = height( node->left );
int r = height( node->right );
ans = max( ans, l + r + 1 );
return max( l, r ) + 1;
}
int diameterOfBinaryTree(TreeNode* root) {
ans = 1;
height( root );
return ans - 1;
} |
2bd91614be11ad42318d6939ffebd91a16794fb2 | cccb439825572f601e885afffb82205498f710ad | /M4Lab_Tart_Dataman/Dataman/main.cpp | 9dc06b4e19f6f36b39fa5a880186344f683bb3c1 | [] | no_license | tartl7709/csc134 | 2f87c178739180a02a879daf952882f16a8c4323 | b44aa8e4f953090c75f9d93fe809f419d6db7679 | refs/heads/master | 2020-04-16T20:49:22.686077 | 2019-05-14T00:15:07 | 2019-05-14T00:15:07 | 165,907,503 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,559 | cpp | main.cpp | #include <iostream>
#include "Arithmetic.h"
#include "temperature.h"
// CSC 134
// M4Lab - Dataman
// L Tart
// 02/21/19
/*
Changes to make program more user friendly:
added 'x' for a multiplication option
added '#' after option to indicate that a number is required
added colons to after prompts to indicate input is required
changed "exit" within temp converter menu to "Main Menu"
*/
using namespace std;
void main_menu();
int main_arithmetic ();
void print_main_menu(); // to display menu
int main_arithmetic()
{
// main calculator loop
float num1, num2;
char opcode;
//cout << add(1, 1) << endl;
//cout << "I will add two numbers together." << endl;
//cout << "Please enter two whole numbers separated by a space." << endl;
cout << "Enter a mathematical expression, for example 2 + 2 or 10 / 2: " << endl;
cin >> num1 >> opcode >> num2;
if (opcode == '+') {
add(num1, num2);
cout << add(num1, num2) << endl;}
//answer = add(num1, num2);
//cout << "The answer to your expression is " << add(num1, num2) << endl;
//int sub1, sub2;
//cout << "Enter a mathematical subtraction expression, for example 4 - 3" << endl;
//cin >> sub1 >> opcode >> sub2;
else if (opcode == '-') {
subtract(num1, num2);
cout << subtract(num1, num2) << endl;}
else if (opcode == '/') {
divide(num1, num2);
cout << divide(num1, num2) << endl;
}
else if (opcode == '*') {
multiply(num1, num2);
cout << multiply(num1, num2) << endl;
}
else if (opcode == 'x') {
multiply(num1, num2);
cout << multiply(num1, num2) << endl;
}
return 0;
}
int main ()
{
// call the main menu
main_menu();
return 0;
}
void main_menu()
{
int choice;
do
{
print_main_menu();
cout << "Option #: ";
cin >> choice;
switch (choice)
{
case 1:
main_arithmetic();
break;
case 2:
//cout << "Temperature Converter" << endl;
tempConvertMenu();
break;
case 0:
cout << "Exiting" << endl;
break;
default:
cout << "Invaild option" << endl;
}
}
while (choice!= 0);
}
void print_main_menu()
{
// display main menu
cout << "----DATAMAN MAIN MENU----" << endl;
cout << "1. Arithmetic Calculator" << endl;
cout << "2. Temperature Converter" << endl;
cout << "0. Exit" << endl;
}
|
509db80775fab48acc76eedc1ca3a4e1a43d19a3 | ff67e2c86e91c4cdf3fdd0c57e52a97c7427752a | /opencvTest/resize/main.cpp | c30ec96957d0b3cb6e9840db3e6b08a5166935bc | [] | no_license | Itanq/OpenCV | 3c539ce91afb65d9b429e8216d660c88ce313968 | 31f82a13c2691a93c0b3997c7bc144c7f82ece12 | refs/heads/master | 2020-12-25T22:30:07.600101 | 2016-11-27T12:16:01 | 2016-11-27T12:16:01 | 68,439,687 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,362 | cpp | main.cpp | #include<iostream>
#include<opencv2/core/core.hpp>
#include<opencv2/imgproc/imgproc.hpp>
#include<opencv2/highgui/highgui.hpp>
int main()
{
cv::Mat srcImage = cv::imread("../image/car.jpg");
cv::Rect rect;
rect.x = 270; rect.y = 720; rect.width=250; rect.height=100;
cv::Rect extra_roi;
float cx = rect.x + rect.width / 2;
float cy = rect.y + rect.height / 2;
float _scale_w = 1.8;
float _scale_h = 1.8;
extra_roi.width = rect.width * _scale_w;
extra_roi.height = rect.height * _scale_h;
extra_roi.x = cx - extra_roi.width / 2;
extra_roi.y = cy - extra_roi.height / 2;
std::cout << cv::format(" the start Image size %d %d ", srcImage.cols, srcImage.rows) << std::endl;
std::cout << cv::format(" the rect is %d %d %d %d ", rect.x, rect.y, rect.width, rect.height) << std::endl;
std::cout << cv::format(" the padding rect is %d %d %d %d ", extra_roi.x, extra_roi.y, extra_roi.width, extra_roi.height) << std::endl;
cv::rectangle(srcImage, rect, cv::Scalar(0,255,0),2);
cv::rectangle(srcImage, extra_roi, cv::Scalar(255,0,0),2);
cv::namedWindow("srcImage",CV_WINDOW_KEEPRATIO);
cv::imshow("srcImage", srcImage);
cv::resize(srcImage, srcImage, cv::Size(srcImage.cols*0.5,srcImage.rows*0.5));
cv::imshow("reImage", srcImage);
cv::waitKey(0);
return 0;
}
|
43b25ddcc5db4916531d523b0c8680381ff5f8d4 | f23e6027b98ce89ccdf946bbc0aaa8d90ac54ce5 | /src/erhe/concurrency/erhe_concurrency/serial_queue.cpp | 930b01c16a0e19ec709ad8ca7845f34f4a03305f | [
"MIT",
"Zlib",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | permissive | tksuoran/erhe | 8476cba96d73d4636aad2a40daaa707fd00b112f | d8a3393113aac273fe2446894f287d9a7889e0a7 | refs/heads/main | 2023-09-04T11:06:39.665543 | 2023-09-02T16:15:32 | 2023-09-02T16:15:32 | 363,416,834 | 412 | 45 | NOASSERTION | 2023-07-15T11:06:09 | 2021-05-01T13:29:16 | C++ | UTF-8 | C++ | false | false | 1,752 | cpp | serial_queue.cpp | #include "erhe_concurrency/serial_queue.hpp"
namespace erhe::concurrency {
Serial_queue::Serial_queue()
: m_name{"serial.default"}
{
m_thread = std::thread(
[this]
{
thread();
}
);
}
Serial_queue::Serial_queue(const std::string_view name)
: m_name{name}
{
m_thread = std::thread(
[this]
{
thread();
}
);
}
Serial_queue::~Serial_queue() noexcept
{
wait();
std::unique_lock<std::mutex> queue_lock{m_queue_mutex};
m_stop = true;
queue_lock.unlock();
m_task_condition.notify_one();
m_thread.join();
}
void Serial_queue::thread()
{
while (!m_stop.load(std::memory_order_relaxed)) {
std::unique_lock<std::mutex> queue_lock{m_queue_mutex};
if (m_task_counter > 0) {
auto task = std::move(m_task_queue.front());
m_task_queue.pop_front();
queue_lock.unlock();
task();
std::unique_lock<std::mutex> wait_lock(m_wait_mutex);
--m_task_counter;
} else {
m_wait_condition.notify_all();
m_task_condition.wait(
queue_lock,
[this]
{
return m_stop || m_task_counter;
}
);
}
}
}
void Serial_queue::cancel()
{
std::unique_lock<std::mutex> queue_lock{m_queue_mutex};
m_task_counter -= static_cast<int>(m_task_queue.size());
m_task_queue.clear();
}
void Serial_queue::wait()
{
std::unique_lock<std::mutex> wait_lock{m_wait_mutex};
m_wait_condition.wait(
wait_lock,
[this]
{
return !m_task_counter.load(std::memory_order_relaxed);
}
);
}
}
|
3941050f1e23a73ea93ab4f8872ff1348dde447b | 1c805daca12d505b9d489e77f6b861cf7ad6d8bb | /MyClientHandler.cpp | 4e4bde244a6c7d62ceadf4c82f49937e1718e3ed | [] | no_license | secretBackupThatDefinitelyWontBeFound/shhhhh | c384a899255b16a85efe1a745b2385424dbbdd68 | 1e2a0545a1e6b8022691e225cdfc70645734c90c | refs/heads/master | 2020-12-18T10:45:01.644819 | 2020-01-21T13:43:08 | 2020-01-21T13:43:08 | 235,350,861 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,139 | cpp | MyClientHandler.cpp | //
// Created by to on 1/13/19.
//
#include "MyClientHandler.h"
void MyClientHandler::handleClient(IOManager *io_manager) {
std::string sep_lines = "/";
std::vector<std::string> lines;
std::string line = io_manager->getLine();
while (line != EXIT) {
lines.push_back(line);
line = io_manager->getLine();
}
std::vector<std::vector<std::string>> matrix_str;
std::string separator = ",";
for (int i = 0; i < lines.size() - 2; ++i) {
matrix_str.push_back(split(lines[i], separator));
}
std::vector<std::string> singal_state;
singal_state = split(lines[lines.size() - 2], separator);
std::pair<std::string, std::string> start(singal_state[0], singal_state[1]);
singal_state = split(lines[lines.size() - 1], separator);
std::pair<std::string, std::string> goal(singal_state[0], singal_state[1]);
SearchableMatrix matrix(matrix_str, start, goal);
std::vector<std::string> path;
if (cache->isSolutionExists(matrix)) {
path = cache->getSolution(matrix);
} else {
path = solver->solve(&matrix);
cache->saveSolution(matrix, path);
}
std::string msg;
for (std::string s : path) {
msg += s + ",";
}
msg = msg.substr(0, msg.size() - 1);
io_manager->sendMsg(msg);
}
std::vector<std::string> MyClientHandler::split(std::string &line, std::string &separator) {
vector<string> answer;
string part;
string c;
for (int i = 0; i < line.size(); ++i) {
c = line[i];
if (c == separator) {
if (!part.empty()) {
answer.push_back(part);
}
part = "";
continue;
}
part += line[i];
}
if (!part.empty()) {
answer.push_back(part);
}
return answer;
}
MyClientHandler::MyClientHandler(Solver<ISearchable<pair<int, int>> *, vector<string>> *solver,
CacheManager<SearchableMatrix, vector<string>> *file_cache) : solver(solver),
cache(file_cache) {}
|
3225187d5a542ec442bdfd50c6d0dd437f8f45a5 | 7c6cea41a6aec80365cb20962b803b7b43eacdb7 | /include/BadDetector.h | 21edce0073c8f67858eb91d738b99d2a75695ae8 | [] | no_license | kold3d/gwm_anasen | 322fe7fd431cb0e53c3803f4e6215bb46517dc47 | 68ea35a65e18f2c55f0c9bd8b8d7bb9b6dbec384 | refs/heads/master | 2020-08-02T15:59:46.335359 | 2019-08-09T15:52:10 | 2019-08-09T15:52:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 641 | h | BadDetector.h | #ifndef BAD_DETECTOR_H
#define BAD_DETECTOR_H
#include <TROOT.h>
#include <TTree.h>
#include <TFile.h>
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <unordered_map>
#include "SiHit.h"
#include "CsIHit.h"
#include "PCHit.h"
#include "Track.h"
using namespace std;
class SiSearch {
public:
SiSearch();
void run();
private:
void writeBadList();
void chanFound(Int_t detID, Int_t chanNum);
int isGood(Int_t detID, Int_t chanNum);
void getDataList();
void makeBadList();
unordered_map<string, int> det_map;
vector<string> data_list;
SiHit Si;
};
#endif
|
8fb4c75ff892691ac6cfb7401e35a6a0ede52c1c | 0afe19dc19d0646271aab90596a3617d749e6786 | /ares/ngp/ngp.hpp | bb8fdc2d63cedbeb0f353b168a289a2ce2de5f46 | [
"ISC"
] | permissive | byuubackup/ares | 8654d8d39a9b2cc75e1cc030fd70b6854ac0cd1f | b6e807b54f69ad18a4788868b9de33a752ea7458 | refs/heads/master | 2022-12-04T18:12:38.720148 | 2020-07-25T02:06:51 | 2020-07-25T02:06:51 | 282,349,863 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 619 | hpp | ngp.hpp | #pragma once
//started: 2019-01-03
#include <ares/ares.hpp>
#include <component/processor/tlcs900h/tlcs900h.hpp>
#include <component/processor/z80/z80.hpp>
#include <component/audio/t6w28/t6w28.hpp>
namespace ares::NeoGeoPocket {
#include <ares/inline.hpp>
struct Model {
inline static auto NeoGeoPocket() -> bool;
inline static auto NeoGeoPocketColor() -> bool;
};
#include <ngp/system/system.hpp>
#include <ngp/cartridge/cartridge.hpp>
#include <ngp/cpu/cpu.hpp>
#include <ngp/apu/apu.hpp>
#include <ngp/vpu/vpu.hpp>
#include <ngp/psg/psg.hpp>
}
#include <ngp/interface/interface.hpp>
|
61caf64acab49d91b38327ab4ab84d1c10b194fa | 67ed24f7e68014e3dbe8970ca759301f670dc885 | /win10.19042/SysWOW64/SortWindows6Compat.dll.cpp | 589d5d566dc69aa99f3e2dfb09ab4b73b245880d | [] | no_license | nil-ref/dll-exports | d010bd77a00048e52875d2a739ea6a0576c82839 | 42ccc11589b2eb91b1aa82261455df8ee88fa40c | refs/heads/main | 2023-04-20T21:28:05.295797 | 2021-05-07T14:06:23 | 2021-05-07T14:06:23 | 401,055,938 | 1 | 0 | null | 2021-08-29T14:00:50 | 2021-08-29T14:00:49 | null | UTF-8 | C++ | false | false | 224 | cpp | SortWindows6Compat.dll.cpp | #pragma comment(linker, "/export:SortCloseHandle=\"C:\\Windows\\SysWOW64\\SortWindows6Compat.SortCloseHandle\"")
#pragma comment(linker, "/export:SortGetHandle=\"C:\\Windows\\SysWOW64\\SortWindows6Compat.SortGetHandle\"")
|
5244845d8b4612c97a086f7e1c9fde276bd28107 | 961a3d5c147df68a5af2e5a683ac1ac19e92daca | /Paddle.hpp | 3ff9a5f95fcce9c0fbbcf4c14c1e7af15c43acab | [] | no_license | numpad/Pong44 | 76a6cdeedeeaef287616cec06224556e5431b8ce | 50721ec9365287c644147b8ae4ec53bec251b7b1 | refs/heads/master | 2021-01-11T11:38:56.303145 | 2017-01-28T23:52:05 | 2017-01-28T23:52:05 | 79,855,761 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 403 | hpp | Paddle.hpp | #ifndef PADDLE_H
#define PADDLE_H
#include "Player.hpp"
#include "Vec2.hpp"
#include "ParticleFuel.hpp"
#include <SFML/Graphics.hpp>
class Paddle {
float maxSpeed, acceleration;
Vec2 vel, acc;
Player player;
sf::RectangleShape shape;
public:
ParticleFuel pfuel;
Vec2 pos, size;
Paddle(Player&);
void block();
void update();
void draw(sf::RenderWindow&);
Player &getOwner();
};
#endif |
3b38f963845d900c8c7afc049d66c8b07d3e82fb | 5b94cf771f7150bf1ebac3b51b76a306622529a8 | /rtough.h | afa78cddc47a678639e56d7d927c9005f08309fe | [] | no_license | erezsh/zodengine | 79dc8b2825d5a751587c154ec9ca3e9ab3023b38 | 27d29020b9a187a090860e21bf52f8e7a91771e7 | refs/heads/master | 2023-09-03T09:16:49.748391 | 2013-04-13T11:25:02 | 2013-04-13T11:25:17 | 5,296,561 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 740 | h | rtough.h | #ifndef _RTOUGH_H_
#define _RTOUGH_H_
#include "zrobot.h"
class RTough : public ZRobot
{
public:
RTough(ZTime *ztime_, ZSettings *zsettings_ = NULL);
static void Init();
// SDL_Surface *GetRender();
void DoRender(ZMap &the_map, SDL_Surface *dest, int shift_x = 0, int shift_y = 0);
void DoAfterEffects(ZMap &the_map, SDL_Surface *dest, int shift_x, int shift_y);
int Process();
void PlaySelectedWav();
void PlaySelectedAnim(ZPortrait &portrait);
void FireMissile(int x_, int y_);
bool CanPickupGrenades() { return false; }
virtual bool CanHaveGrenades() { return false; }
virtual bool CanThrowGrenades() { return false; }
private:
static ZSDL_Surface fire[MAX_TEAM_TYPES][MAX_ANGLE_TYPES][3];
};
#endif
|
8c988a9e170e6e96ac25b9909dc53fe56c7982ed | f92b42a76aad09bac7fba4a6fce282835fb96305 | /arduino_labs/lab4/lab4.ino | a8bcbcf18664dab4923c8c9db4a993ba57bc48b9 | [] | no_license | ki2chio/MpMk | be5e2cdf9d9e45ce5cc32dbc264bf61bd93fcd77 | 7301c674a8172bf7078a69882f3c32301ddbe6cf | refs/heads/master | 2020-05-17T10:21:48.331256 | 2019-12-23T10:11:09 | 2019-12-23T10:11:09 | 183,654,553 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,055 | ino | lab4.ino | #include "7segmentOutput.h"
#include "dht11read.h"
volatile short c_1000ms = 0;
volatile bool flag_1000ms = false;
volatile short c_15000ms_time = 0;
volatile bool flag_15000ms_time = false;
volatile short c_20000ms_temp = 0;
volatile bool flag_20000ms_temp = false;
// volatile short c_5 = 0;
// volatile bool flag_5 = false;
const int buzzer = 3;
int hours=0,minutes=0,seconds=0;
ISR(TIMER1_COMPA_vect){ // обработчик прерывания. Вызывается каждую миллисекунду
c_1000ms++;
if(c_1000ms == 1000) { // Выполняем каждые 1c
flag_1000ms = true;
c_1000ms = 0;
}
c_15000ms_time++;
if(c_15000ms_time == 15000) { // Выполняем каждые 1c
flag_15000ms_time = true;
c_15000ms_time = 0;
}
c_20000ms_temp++;
if(c_20000ms_temp == 20000) { // Выполняем каждые 1c
flag_20000ms_temp = true;
c_20000ms_temp = 0;
}
// c_5ms++;
// if(c_5ms == 5) { // Выполняем каждые 1c
// flag_5ms = true;
// c_5ms = 0;
// }
}
void initTimer() { // инициализация Timer1
cli(); // отключить глобальные прерывания
TCNT1 = 0;
TCCR1A = 0; // установить регистр управления А в 0
TCCR1B = 0;
TCCR1B |= (1 << WGM12); // включить CTC режим
TCCR1B |= (0b001 << CS10); // Установить биты на коэффициент деления
OCR1A = 15999; // установка регистра совпадения
TIMSK1 |= (1 << OCIE1A); // включить прерывание по совпадению таймера
sei();} // включить глобальные прерывания
void setup() {
pinMode(A1, INPUT);
pinMode(A2, INPUT);
pinMode(A3, INPUT);
pinMode(LCHCLK,OUTPUT);
pinMode(STFCLK,OUTPUT);
pinMode(SDI,OUTPUT);
pinMode(buzzer, OUTPUT);
digitalWrite(buzzer, HIGH);
initTimer();
inputTime();
Serial.begin(9600);
getTempHumDHT11();
}
void loop() {
if(flag_1000ms) { // Выполняем каждую 1 с
flag_1000ms = false;
timeCounter();
while(!flag_1000ms)writeTimeToSignemt();
}
if(flag_15000ms_time){
flag_15000ms_time = false;
while(!flag_15000ms_time)writeHumToSigment();
}
if(flag_20000ms_temp){
flag_20000ms_temp = false;
while(!flag_20000ms_temp)writeTempToSignemt();
}
}
void writeTimeToSignemt(){
printLed(1,numbers[minutes / 10]);
printLed(2,numbers[minutes % 10]);
printLed(3,numbers[seconds / 10]);
printLed(4,numbers[seconds % 10]);}
void writeHumToSigment(){
printLed(1,numbers[humidity/10]);
printLed(2,numbers[humidity%10]);
printLed(3,0x9C);
printLed(4,0xC6);
}
void writeTempToSignemt(){
printLed(1,numbers[temperature/10]);
printLed(2,numbers[temperature%10]);
printLed(3,0x98);
printLed(4,0x93);
}
void timeCounter(){
seconds++;
if(seconds==60){
seconds=0;
minutes++;
}
if(minutes==60){
minutes=0;
}}
void inputTime(){
while(true){
if (!digitalRead(A1)){
minutes--;
digitalWrite(buzzer, LOW);
delay(150);
digitalWrite(buzzer, HIGH);
}
if (!digitalRead(A2)){
minutes++;
digitalWrite(buzzer, LOW);
delay(150);
digitalWrite(buzzer, HIGH);
}
if (minutes == 60)minutes=0;
if (minutes == -1)minutes=59;
if (!digitalRead(A3)){
digitalWrite(buzzer, LOW);
delay(200);
digitalWrite(buzzer, HIGH);
break;
}
writeTimeToSignemt();
}
delay(250);
while(true){
if (!digitalRead(A1)){
seconds--;
digitalWrite(buzzer, LOW);
delay(150);
digitalWrite(buzzer, HIGH);
}
delay(70);
if (!digitalRead(A2)){
seconds++;
digitalWrite(buzzer, LOW);
delay(150);
digitalWrite(buzzer, HIGH);
}
delay(70);
if (seconds == 60)seconds=0;
if (seconds == -1)seconds=59;
if (!digitalRead(A3)){
digitalWrite(buzzer, LOW);
delay(200);
digitalWrite(buzzer, HIGH);
break;
}
writeTimeToSignemt();
}}
|
7ba46a18cf6b95585453a51c2828596e8876bca0 | e61722adb72dc88c3e7493e3c4429c81e54f7519 | /rotation.cpp | e99ad0d33d0efdf358fe45df4cc9d63bb00ed23a | [] | no_license | DreamTeamHelha/SirtoliRacing | 0e2e94a359b24cc744276b93dbb96b446003c8ad | 9b6e66442322415657828fd6944af8ef85645ab9 | refs/heads/master | 2016-09-08T05:03:38.424832 | 2013-12-18T12:12:34 | 2013-12-18T12:12:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,337 | cpp | rotation.cpp | #include "rotation.h"
#include "vector.h"
#include <cmath>
#include "utils.h"
const float Rotation::m_maxAngle = 2 * utils::pi();
Rotation::operator Vector() const
{
return Vector(std::cos(m_angle), std::sin(m_angle));
}
Rotation::Rotation(const Rotation &r){
this->m_angle=r.m_angle;
}
Rotation& Rotation::operator=(const Rotation &r){
if(this!=&r){
this->m_angle=r.m_angle;
}
return *this;
}
void Rotation::setAngle(float radangle)
{
m_angle = radangle;
while (m_angle < 0)
{
m_angle += m_maxAngle;
}
while (m_angle >= m_maxAngle)
{
m_angle -= m_maxAngle;
}
}
bool operator<(const Rotation& left, const Rotation & right)
{
if (right == left)
return false;
else
return (right - left).angle() <= utils::pi();
}
bool operator>(const Rotation& left, const Rotation & right)
{
if (right == left)
return false;
else
return (right - left).angle() >= utils::pi();
}
bool operator<=(const Rotation& left, const Rotation & right)
{
if (right == left)
return true;
else
return (right - left).angle() <= utils::pi();
}
bool operator>=(const Rotation& left, const Rotation & right)
{
if (right == left)
return true;
else
return (right - left).angle() >= utils::pi();
}
|
6be59d278c2fc7afebb6e2449478d92c9318c5ee | a5cf450078809a0b507e21d56660b7c4f033c6d5 | /dac/protocol-.cpp | 74776c78abba67ab55f4459657d8e172fc96b0f3 | [] | no_license | fay1987/communication_manager | 98a72677d4e2aa631e2c895741819a53c639c79a | 7df29883f6a18400ceb26682cf2d800630b6df33 | refs/heads/master | 2021-07-13T14:30:04.214616 | 2018-01-25T08:08:05 | 2018-01-25T08:08:05 | 94,993,715 | 1 | 2 | null | null | null | null | GB18030 | C++ | false | false | 9,253 | cpp | protocol-.cpp | /*===================================================================
* 模块名称: 规约基类
* 创建日期: 2013年11月27日 9:36
* 文 件 名: e:\pdt3000\program\dac\dac\src\protocol.cpp
* 文件路径: e:\pdt3000\program\dac\dac\src
* 模块名称: protocol
* 文件类型: cpp
* 作 者: wlq
* 版 本: V2.0
* 模块说明: 规约基类
* 修改版本: V2.1
* 修改作者: wlq
* 修改日期: 27/11/2013
* 修改摘要:
====================================================================*/
#include "dac/protocol.h"
#include "utl/datetime.h"
#include <ace/OS.h>
#include "sys/blog.h"
using namespace PDT;
CProtocol::CProtocol()
:m_channel(-1),m_route(-1)
{
m_msgLen = 0;
}
CProtocol::~CProtocol()
{
}
//初始化时调用
bool CProtocol::init(hInt32 channel,hInt32 route)
{
//wfp changed at 20110616 for 连接后10ms内即收到的报文规约无法捕获的问题
//采用方法:通道、路径号都不变,则不允许重置报文及显示缓冲区
logprint(LOG_DACSRV_LINK,"Protocol: %X", this);
logprint(30010, "channel : %d, route: %d !", channel, route);
logprint(30010, "m_channel : %d, m_route: %d !", m_channel, m_route);
if ( (m_channel != channel) || (m_route != route) )
{
m_channel = channel;
m_route = route;
logprint(30010, "m_channel : %d, m_route: %d !", m_channel, m_route);
m_rxBuffer.init(channel);
m_txBuffer.init(channel,BUFFER_TX);
m_message.init(route);
}
////////////////////wfp changed end///////////////////////////////////////
logprint(30010, "DAC_STATION_NUM: %d ", DAC_STATION_NUM);
m_isSending = false;
DAC_ROUTE_INFO* pRouteInfo = m_commInf.routeInfo(m_route);
logprint(30010, "m_commInf.routeInfo(%d): !", m_route);
if ( pRouteInfo == NULL ) return false;
logprint(30010, "pRouteInfo不为空 !");
pRouteInfo->cmd.all_data = true;
pRouteInfo->cmd.all_yc = true;
pRouteInfo->cmd.all_yx = true;
pRouteInfo->switchFlag = false;
logprint(30010, "m_commInf.routeInfo(%d): !", m_route);
logprint(LOG_DACSRV_LINK,"Protocol: %X", this);
return true;
}
bool CProtocol::readFeature()
{
return true;
}
/*
* 函数功能:若规约需要收到回应后才能下行,则使用该函数过滤下行
* 函数参数:true:有命令正在发送;false:无
*/
hBool CProtocol::isSending() const
{
return m_isSending;
}
/*
* 函数功能:mainTx()中报告是否发送了下行命令
* 函数参数:true:有下行命令发送;false:无下行
*/
void CProtocol::reportCmdSend(hBool isSend /* = true */)
{
DAC_ROUTE_INFO* pRouteInfo = m_commInf.routeInfo(m_route);
if ( pRouteInfo == NULL ) return;
if ( isSend )
{
m_isSending = true;
pRouteInfo->switchFlag = false;
}
else
{
m_isSending = false;
pRouteInfo->switchFlag = true;
}
}
/*
* 函数功能:mainRx()中报告收到下行命令的回校数据
* 函数参数:true:数据正确;false:数据错误
*/
void CProtocol::repotrAckRecv(hBool isOk /* = true */)
{
DAC_ROUTE_INFO* pRouteInfo = m_commInf.routeInfo(m_route);
if ( pRouteInfo == NULL ) return;
m_isSending = false;
pRouteInfo->switchFlag = true;
}
//接收缓冲区可用字节数
hUInt32 CProtocol::length() const
{
int ret = m_rxBuffer.length();
if ( ret <= 0 ) return 0;
return (hUInt32)ret;
}
bool CProtocol::back(hUInt32 num)
{
return m_rxBuffer.back(num);
}
bool CProtocol::get(hUChar& val)
{
return m_rxBuffer.get(val);
}
hUInt32 CProtocol::get(hUChar *buf,hUInt32 len)
{
int ret = m_rxBuffer.get(buf,len);
if ( ret <= 0 ) return 0;
return ret;
}
//发送缓冲区
bool CProtocol::put(hUChar val)
{
return m_txBuffer.put(val);
}
bool CProtocol::put(const hUChar *buf,hUInt32 len)
{
return m_txBuffer.put(buf,len);
}
hUInt32 CProtocol::remain()
{
int ret = m_txBuffer.remain();
if ( ret <= 0 ) return 0;
return ret;
}
//消息对象
bool CProtocol::msgCopy(const hUChar* buf,hUInt32 len)
{
if ( buf == NULL ) return false;
if ( len < 0 || (m_msgLen + len) >= DAC_MSG_DATA_LEN ) return false;
memcpy(m_msg+m_msgLen,buf,len);
m_msgLen += len;
return true;
}
bool CProtocol::msgRemove(hUInt32 len)
{
if ( len < 0 || len > m_msgLen) return false;
m_msgLen -= len;
return true;
}
void CProtocol::msgClean()
{
m_msgLen = 0;
}
bool CProtocol::msgDisplay(hUInt8 type,const char* desc)
{
bool ret = msgDisplay(type,desc,m_msg,m_msgLen);
m_msgLen = 0;
return ret;
}
bool CProtocol::msgDisplay(hUInt8 type,const char* desc,const hUChar* data,hUInt32 len)
{
if ( desc == NULL || data == NULL || len <= 0 || len >= DAC_MSG_DATA_LEN ) return false;
DAC_MESSAGE msg;
CDateTime datetime = CDateTime::currentDateTime();
msg.time.year = (hUInt16)datetime.year();
msg.time.mon = (hUInt8)datetime.month();
msg.time.day = (hUInt8)datetime.day();
msg.time.hour = (hUInt8)datetime.hour();
msg.time.min = (hUInt8)datetime.minute();
msg.time.sec = (hUInt8)datetime.second();
msg.time.msec = (hUInt16)(datetime.microsec()/1000);
msg.type = type;
ACE_OS::strncpy(msg.desc,desc,DAC_DESC_LEN);
msg.length = len;
ACE_OS::memcpy(msg.data,data,len);
return m_message.put(msg);
}
bool CProtocol::addSendFrmNum(int frmNum/* =1 */)
{
DAC_ROUTE_INFO* pRouteInfo = m_commInf.routeInfo(m_route);
if ( pRouteInfo == NULL ) return false;
if ( pRouteInfo->txFrmCnt >= INT_MAX ) pRouteInfo->txFrmCnt = 0;
pRouteInfo->txFrmCnt += frmNum;
return true;
}
bool CProtocol::addRecvOkFrmNum(int frmNum/* =1 */)
{
DAC_ROUTE_INFO* pRouteInfo = m_commInf.routeInfo(m_route);
if ( pRouteInfo == NULL ) return false;
if ( pRouteInfo->okFrmCnt >= INT_MAX ) pRouteInfo->okFrmCnt = 0;
pRouteInfo->okFrmCnt += frmNum;
if ( pRouteInfo->rxFrmCnt >= INT_MAX ) pRouteInfo->rxFrmCnt = 0;
pRouteInfo->rxFrmCnt += frmNum;
pRouteInfo->lastDataOkTime = (hUInt32)ACE_OS::time(0);
return true;
}
bool CProtocol::addRecvErrFrmNum(int frmNum/* =1 */)
{
DAC_ROUTE_INFO* pRouteInfo = m_commInf.routeInfo(m_route);
if ( pRouteInfo == NULL ) return false;
if ( pRouteInfo->errFrmCnt >= INT_MAX ) pRouteInfo->errFrmCnt = 0;
pRouteInfo->errFrmCnt += frmNum;
if ( pRouteInfo->rxFrmCnt >= INT_MAX ) pRouteInfo->rxFrmCnt = 0;
pRouteInfo->rxFrmCnt += frmNum;
return true;
}
bool CProtocol::getCtrlCmd(char* cmdBuf,int len)
{
if ( cmdBuf == NULL || len < CTRL_COMMON_LEN ) return false;
char buf[DAC_CTRL_LEN];
DAC_ROUTE* pRoute = m_commInf.route(m_route);
if ( pRoute == NULL ) return false;
DAC_ROUTE_INFO* pRouteInfo = m_commInf.routeInfo(m_route);
if ( pRouteInfo == NULL ) return false;
if( !pRouteInfo->mainFlag ) return false;
if ( m_ctrlInf.getProtocol(pRoute->group,buf,DAC_CTRL_LEN) )
{
ctrl_head* pHead = (ctrl_head*)buf;
if ( pHead->type == CTRL_PRO_COMMON )
{
ctrl_pro_common* pCommon = (ctrl_pro_common*)(buf+sizeof(ctrl_head));
ACE_OS::memcpy(cmdBuf,pCommon->cmdBuf,CTRL_COMMON_LEN);
return true;
}
}//end if
return false;
}
bool CProtocol::getCtrlCmdByRoute(hInt32 routeno,char* cmdBuf,int len)
{
if ( cmdBuf == NULL || len < CTRL_COMMON_LEN ) return false;
char buf[DAC_CTRL_LEN];
DAC_ROUTE* pRoute = m_commInf.route(routeno);
if ( pRoute == NULL ) return false;
DAC_ROUTE_INFO* pRouteInfo = m_commInf.routeInfo(m_route);
if ( pRouteInfo == NULL ) return false;
if( !pRouteInfo->mainFlag ) return false;
if ( m_ctrlInf.getProtocol(pRoute->group,buf,DAC_CTRL_LEN) )
{
ctrl_head* pHead = (ctrl_head*)buf;
if ( pHead->type == CTRL_PRO_COMMON )
{
ctrl_pro_common* pCommon = (ctrl_pro_common*)(buf+sizeof(ctrl_head));
ACE_OS::memcpy(cmdBuf,pCommon->cmdBuf,CTRL_COMMON_LEN);
return true;
}
}//end if
return false;
}
bool CProtocol::setCtrlCmdAck(const char* ackBuf,int len)
{
if ( ackBuf == NULL || len <= 0 ) return false;
DAC_ROUTE* pRoute = m_commInf.route(m_route);
if ( pRoute == NULL ) return false;
int copyLen = len;
if ( copyLen >= CTRL_COMMON_LEN ) copyLen = CTRL_COMMON_LEN;
ctrl_pro_common_ack commonAck;
commonAck.groupNo = pRoute->group;
commonAck.length = copyLen;
ACE_OS::memcpy(commonAck.ackBuf,ackBuf,copyLen);
return commonCmdAck(&commonAck);
}
//add by yff 用于多路径Modbus下取测点路径号
bool CProtocol::setCtrlCmdAckEx(const char* ackBuf,int len)
{
if ( ackBuf == NULL || len <= 0 ) return false;
ctrl_pro_yk_ack* ack = (ctrl_pro_yk_ack*)ackBuf;
int copyLen = len;
if ( copyLen >= CTRL_COMMON_LEN ) copyLen = CTRL_COMMON_LEN;
ctrl_pro_common_ack commonAck;
commonAck.groupNo = ack->groupNo;
commonAck.length = copyLen;
ACE_OS::memcpy(commonAck.ackBuf,ackBuf,copyLen);
return commonCmdAck(&commonAck);
}
/*
* 函数说明:该函数同CDacCtrl.commonCmdAck()函数,由于此处不能调CDacCtrl的函数,因而重新定义
*/
bool CProtocol::commonCmdAck(const ctrl_pro_common_ack* pCommonAck)
{
if ( !pCommonAck )
return false;
if ( !m_commInf.isGroupValid(pCommonAck->groupNo) )
return false;
unsigned char buf[512];
hInt32 headLen,dataLen;
headLen = sizeof( ctrl_head );
dataLen = sizeof( ctrl_pro_common_ack);
ctrl_head* pHead = (ctrl_head*)buf;
pHead->type = CTRL_PRO_COMMON_ACK;
ctrl_pro_common_ack* pData = (ctrl_pro_common_ack*)(buf + headLen);
ACE_OS::memcpy(pData,pCommonAck,dataLen );
return m_ctrlInf.addAck(CTRL_PRO_COMMON_ACK,buf, headLen + dataLen,pCommonAck->groupNo);
}
|
589b1114f494e80aeea1354ac4ed6de9c2d57ad0 | e5b98edd817712e1dbcabd927cc1fee62c664fd7 | /Classes/message/Decoding/mail/MailMsg.cpp | c3d7799f515932bb570eae8e57c28af0f3b034fd | [] | no_license | yuangu/project | 1a49092221e502bd5f070d7de634e4415c6a2314 | cc0b354aaa994c0ee2d20d1e3d74da492063945f | refs/heads/master | 2020-05-02T20:09:06.234554 | 2018-12-18T01:56:36 | 2018-12-18T01:56:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 328 | cpp | MailMsg.cpp | //
// MailMsg.cpp
// FightPass
//
// Created by chenyanbin on 15/11/9.
//
//
#include "MailMsg.h"
MailMsg::MailMsg()
{
}
MailMsg::~MailMsg()
{
}
ByteStream* MailMsg::encodingData()
{
MessageSendI::encodingData(SCENSE_CLIENT_MAIL_MailPageReq);
// headBufferee->put(m_function);
SetMessageLength();
} |
fe83c46443c749629bd5467f39e40e022e9edcc0 | 7d7b242bdb667f411bc6ed2009ed4a4d9188994b | /A_5.cpp | 2a37edd437a3e96a825cead8a59b0304fe689250 | [] | no_license | PhamNgocToan112/Week-5 | 842b5aa751f807fa8766824f74b7a061d0539d34 | 7f7b2fdbcf7d03719ec0f15c118cd56001c0081d | refs/heads/main | 2023-03-23T02:33:08.044526 | 2021-03-21T13:38:53 | 2021-03-21T13:38:53 | 349,022,753 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 358 | cpp | A_5.cpp | #include<iostream>
using namespace std;
int main(){
int val = 3;
int &ref = val;
int val2 = 4;
cout << val << " " << ref << endl;
cout << &val << " " << &ref << endl;
//int &ref2; => khong the khai bao tham chieu neu khong tham chieu toi 1 bien khac
//ref = val2; => khong the tham chieu toi bien khac
return 0;
}
|
e14e325393cd21448716701d0213315217aacf60 | 8ca48a0cb01e3dad3d18379d9b207dd784680d8c | /Game_menu.cpp | e814b626c5f62b9c08802b08024ed985621c5d9b | [] | no_license | akelm/Pentago | ac3b044758b859afb1091cde69d040d3c44eb337 | e1ab6fbcc862e709c6bdfeb87b99d18d6855633a | refs/heads/main | 2023-08-07T08:14:15.149308 | 2021-10-04T01:52:46 | 2021-10-04T01:52:46 | 413,241,742 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,201 | cpp | Game_menu.cpp | #include "Game.h"
// obsluga menu
// glowa funkcja obslugujaca menu
void Game::menuaction() {
scr.clearrect(scr.obszar);
switch (menusel.lewygorny.Y) {
case 0: { //nowa gra
if (!ifplay || czy_wykonac("Zakonczyc gre?")) {
ifplay = nowa_gra();
}
break;
}
case 1: { // zapisz gre
if (ifplay) {
if (!gra_do_pliku(pobierz_nazwe())) {
scr.insert_text(COORD{ scr.obszar.Left,scr.obszar.Top }, "Nie udalo sie!");
}
}
break;
}
case 2: { // wczytaj gre
if (!ifplay || czy_wykonac("Zakonczyc gre?")) {
if (!gra_z_pliku(pobierz_nazwe())) {
scr.insert_text(COORD{ scr.obszar.Left,scr.obszar.Top }, "Nie udalo sie!");
resetgame();
} else {
ifplay = true;
}
}
break;
}
case 3: { // zakoncz gre
if (!ifplay || czy_wykonac("Zakonczyc gre?")) {
scr.board2screen();
resetgame();
}
break;
}
case 4: { // zamknij program
if (!ifplay || czy_wykonac("Zakonczyc gre?")) {
scr.clearscreen();
exit(0);
}
break;
}
case 5: { // zatwierdz
zawierdz_ruch();
}
}
}
// konfiguruje nowa gre -- pobiera typ graczy i imiona
bool Game::nowa_gra() {
scr.board2screen();
resetgame();
MenuSelInput playerinput(menusel.wymiary, COORD{ scr.obszar.Left,scr.obszar.Top }, &scr);
playerinput.dodaj("Czlowiek").dodaj("Komputer").dodaj("Powrot");
playerinput.komunikat = "";
memset(playerinput.buffer, '\0', 100);
playerinput.tytul = "Gracz ";
playerinput.setpos();
bool playersset = false;
int i = 0;
while (i < 2) {
playerinput.entry = false;
playerinput.tytul = "Gracz ";
playerinput.tytul += gracz->symbol;
playerinput.tytul += ":";
playerinput.wyswietl().execute();
if (playerinput.lewygorny.Y == 2) {
Player *wsk = gracz;
for (int ii = 0; ii < 2; ii++) {
wsk->typ = '\0';
wsk->name = " ";
scr.insert_text(*wsk->wsp, wsk->name);
wsk = wsk->nast;
if (wsk->symbol == 'O') {
gracz = wsk;
}
}
return false;
} else if (playerinput.lewygorny.Y == 0) {
gracz->typ = 'C';
gracz->delay = 0;
playerinput.odznacz();
if (!pobierzstr(gracz->name)) {
continue;
}
scr.insert_text(*gracz->wsp, gracz->name);
} else {
gracz->typ = 'K';
gracz->name = "komputer_";
gracz->name += gracz->symbol;
gracz->delay = 1000;
scr.insert_text(*gracz->wsp, gracz->name);
{
MenuSelInput skillinput(menusel.wymiary, COORD{ scr.obszar.Left,scr.obszar.Top }, &scr);
skillinput.dodaj("Banalny").dodaj("Latwy").dodaj("Sredni").dodaj("Trudny");
skillinput.komunikat = "";
memset(skillinput.buffer, '\0', 100);
skillinput.tytul = "Poziom ";
skillinput.setpos();
skillinput.entry = false;
skillinput.wyswietl().execute();
delete ai[i];
if (skillinput.lewygorny.Y == 0) {
ai[i] = new RandomAI(boardsel, gracz->symbol, gracz->nast->symbol, sredni);
}
if (skillinput.lewygorny.Y == 1) {
ai[i] = new StrategyAI(boardsel, gracz->symbol, gracz->nast->symbol, latwy);
}
if (skillinput.lewygorny.Y == 2) {
ai[i] = new StrategyAI(boardsel, gracz->symbol, gracz->nast->symbol, sredni);
}
if (skillinput.lewygorny.Y == 3) {
ai[i] = new StrategyAI(boardsel, gracz->symbol, gracz->nast->symbol, trudny);
}
gracz->ai = ai[i];
}
}
gracz = gracz->nast;
i++;
} // while
if (gracz->typ == 'C') {
setboard();
}
return true;
}
// menu z opcjami tak/nie
bool Game::czy_wykonac(const string s) {
MenuSelInput taknieinput(menusel.wymiary, COORD{ scr.obszar.Left,scr.obszar.Top }, &scr);
taknieinput.dodaj("Tak").dodaj("Nie");
taknieinput.komunikat = "";
memset(taknieinput.buffer, '\0', 100);
taknieinput.tytul = s;
taknieinput.setpos().wyswietl().execute();
return (taknieinput.lewygorny.Y == 0) ? true : false;
}
// menu do pobierania nazwy pliku
string Game::pobierz_nazwe() {
MenuSelInput nameinput(menusel.wymiary, COORD{ scr.obszar.Left,scr.obszar.Top }, &scr);
nameinput.entry = true;
nameinput.dodaj("Zatwierdz").dodaj("Powrot");
nameinput.komunikat = "Za duzo znakow";
nameinput.tytul = "Nazwa pliku:";
strcpy_s(nameinput.buffer, "savedgame.txt");
nameinput.setpos().wyswietl().execute();
if (nameinput.buffer[0] == '\0' || nameinput.lewygorny.Y == 1) {
return "";
}
string nazwapliku = "";
nazwapliku += nameinput.buffer;
return nazwapliku;
}
// menu do pobrania imienia gracza
bool Game::pobierzstr(string& dest) {
MenuSelInput nameinput(menusel.wymiary, COORD{ scr.obszar.Left,scr.obszar.Top }, &scr);
nameinput.entry = true;
nameinput.dodaj("Zatwierdz").dodaj("Powrot");
nameinput.komunikat = "Za duzo znakow";
nameinput.tytul = "Imie gracza ";
nameinput.tytul += gracz->symbol;
nameinput.tytul += ":";
strcpy_s(nameinput.buffer, "playerZ");
nameinput.buffer[6] = gracz->symbol;
nameinput.setpos().wyswietl().execute();
if (nameinput.buffer[0] == '\0' || nameinput.lewygorny.Y == 1) {
return false;
}
(gracz->name = "") += nameinput.buffer;
return (nameinput.buffer[0] != '\0');
}; |
2f81b4c86d5d6402fbaac01d15fff4875d440a2b | 4d02803707d6a6de262dc25aedc065022c0745e7 | /03-Heritage/Heritage_lego/barre.h | bb111a6baf1bd41306dd61c58a2a0c7c8d5292d3 | [] | no_license | Damon7272/Apprendre-cpp | 6dbfbdad25d90eaa28504174087bac28129afc6d | 1bd1f666dd5cdd1ee5412b1347e07bcdda21d051 | refs/heads/master | 2023-08-05T01:50:05.343332 | 2021-09-23T10:47:29 | 2021-09-23T10:47:29 | 404,686,189 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 326 | h | barre.h | #ifndef BARRE_H
#define BARRE_H
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
class Barre
{
public:
Barre(string _ref,string _nom);
~Barre();
void AfficherCaracteristiques();
private:
string ref;
string nom;
};
#endif // BARRE_H
|
4df41ac89d313796d3a878fd2e515a154f3571d1 | 1b5c62e5facb551b173e9505fc74235288913d31 | /Prezentacja/Prezentacja/Prezentacja.cpp | ddf0f78f706504d015a054f014be76d68e68cd44 | [] | no_license | Lukasz-Madry/TestRepos | 389884f8211c7f9aaf29a92c0c03c9952517f123 | 8981661b887a27649c89070c927f6680a1069fcc | refs/heads/master | 2023-01-21T09:41:43.224022 | 2020-12-02T17:22:22 | 2020-12-02T17:22:22 | 302,044,415 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,200 | cpp | Prezentacja.cpp | #include <iostream>
#include <stdexcept>
using namespace std;
class vehicle {
public:
string company;
int year;
};
class bus : public vehicle {
public:
int no_of_seats;
void print_info()
{
cout << "bus: " << company << " year: " << year << " number of seats: " << no_of_seats << endl;
};
bus(string b_company, int b_year, int b_no_of_seats)
{
company = b_company;
if (b_year > 2020)
{
throw invalid_argument("bus is not produced yet");
}
else
{
year = b_year;
}
if (b_no_of_seats < 8 || b_no_of_seats > 70)
{
throw out_of_range("invalid number of seats");
}
else
{
no_of_seats = b_no_of_seats;
}
};
~bus() {};
};
class car : public vehicle {
public:
int weight;
void print_info()
{
cout << "car: " << company << " year: " << year << " weight: " << weight << endl;
};
car(string c_company, int c_year, int c_weight)
{
company = c_company;
if (c_year > 2020)
{
throw invalid_argument("car is not produced yet");
}
else
{
year = c_year;
}
if (c_weight > 3500)
{
throw "car is too heavy";
}
else
{
weight = c_weight;
}
};
~car() {};
};
class motorcycle : public vehicle {
public:
int no_of_tires;
void print_info()
{
cout << "motorcycle: " << company << " year: " << year << " number of tires: " << no_of_tires << endl;
}
motorcycle(string m_company, int m_year, int m_no_of_tires)
{
company = m_company;
if (m_year > 2020)
{
throw invalid_argument("motorcycle is not produced yet");
}
else
{
year = m_year;
}
if (m_no_of_tires != 2)
{
throw ("vehicle is not a motorcycle");
}
else
{
no_of_tires = m_no_of_tires;
}
};
~motorcycle() {};
};
int main()
{
try {
bus Bus("Solaris", 2012, 30);
Bus.print_info();
car Car("Toyota", 1996, 2800);
Car.print_info();
motorcycle Motorcycle("Yamaha", 2010, 2);
Motorcycle.print_info();
motorcycle Motorcycle2("Yamaha", 2010, 4);
Motorcycle2.print_info();
}
catch (invalid_argument& year)
{
cout << year.what() << endl;
}
catch (out_of_range& seats)
{
cout << seats.what() << endl;
}
catch (const char* exception)
{
cout << exception << endl;
}
system("PAUSE");
return 0;
} |
84e332d512376479b429829af9ee4799d220ba43 | 4d3d61ef8a79234ccadb94f253533c414c1c8b73 | /Problem8.cpp | 9ab152a1f7009e0ae8630fcbae7dfc126e12b6ac | [
"MIT"
] | permissive | GinoGalotti/Cpp-ProjectEulerDotNet | 6c3c0f3544c510320d269323a090297a11305c1f | 78892de84923b9bce3ce936a1a478a18262da8d6 | refs/heads/master | 2020-06-04T08:24:06.969196 | 2014-03-02T16:45:05 | 2014-03-02T16:45:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,646 | cpp | Problem8.cpp | /**
* Solution by Luis Galotti
* Find the greatest product of five consecutive digits in the 1000-digit number.
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450
*/
#include <stdio.h>
#include <string>
using namespace std;
int main()
{
string number=
"7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
const char* a= number.c_str();
long p=0, productFive = 1, maximun = 0;
for (p=0; p<995; p++){
//We transform the character to the proper int number;
productFive = (int(a[p]-48)) * (int(a[p+1]-48)) *(int(a[p+2]-48)) *(int(a[p+3]-48)) *(int(a[p+4]-48));
if (productFive > maximun) maximun = productFive;
}
printf("Solution = %lu", maximun);
return 0;
}
|
7716812acfeec123051520f8849a424ae1797ed8 | 9eeed608407a691f55f240715c7ff4af2e03892c | /src/collectData.cpp | c47f0f7ee98bd2ad6ce049faa972afbd98c8d139 | [] | no_license | Grzegorzwww/_sfml_app | 00cac8afb5b7c9edb67175c150653ae6c07cef22 | f746f9047edc45074fea1602fedc04b695567e9a | refs/heads/master | 2021-01-12T13:37:55.896111 | 2016-10-07T12:46:00 | 2016-10-07T12:46:00 | 69,962,023 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 872 | cpp | collectData.cpp | #include "collectData.h"
using namespace std;
collectData::collectData()
{
cout << "enter collectData()"<<endl;
}
collectData::~collectData()
{
//dtor
}
void collectData::getDataFromSerial(vector <char> data) {
incoming_data = data;
cout <<"Incoming frame: ";
for(int i = 0; i <incoming_data.size(); i++)
{
unsigned char temp = incoming_data.at(i);
cout << hex << (int)temp;
if(i != incoming_data.size() -1 )
cout <<"-";
}
cout << endl;
}
ostream & operator<<(ostream &os, collectData &in){
cout.setf(ios::hex, ios::basefield);
for (int i = 0; i < in.incoming_data.size(); i++)
{
unsigned char temp = in.incoming_data.at(i);
os <<hex << (int)temp;
if(i != in.incoming_data.size() -1 )
os <<"-";
}
os << endl;
return os;
}
|
0977be4b4b7bb5496767b3f88333efd99f7178af | e398697169a67f9b4ebed0b7cce837f9d5bc0174 | /Test.cpp | f21211439e8070f2e02abfb64f3914a0bc10142c | [
"MIT"
] | permissive | shaiBonfil/CPP-Ex3 | 3521cee4e0f04863fc0d3de37d10ab6f497671ce | d766ca822645380c06d5818ce28f1f3c3d244215 | refs/heads/master | 2023-04-22T14:57:19.947977 | 2021-05-03T22:16:28 | 2021-05-03T22:16:28 | 358,642,064 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,166 | cpp | Test.cpp | /**
* AUTHORS: Shai Bonfil
* Date: 2021-04
*
**/
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <string>
#include "doctest.h"
#include "NumberWithUnits.hpp"
using namespace ariel;
using namespace std;
ifstream units_file{"units.txt"};
TEST_CASE("+/+=/-/-= operators")
{
NumberWithUnits::read_units(units_file);
NumberWithUnits x{1, "km"};
NumberWithUnits y{1000, "m"};
NumberWithUnits u{1, "km"};
NumberWithUnits s{100, "m"};
NumberWithUnits z{900, "kg"};
NumberWithUnits w{3, "ton"};
NumberWithUnits d1{1, "USD"};
NumberWithUnits d2{-1, "USD"};
CHECK_EQ(x + y, NumberWithUnits{2, "km"});
CHECK_EQ(y + x, NumberWithUnits{2000, "m"});
CHECK_EQ(w - z, NumberWithUnits{2.100, "ton"});
for (float i = 1; i < 10; i++)
{
CHECK_EQ(x += u, NumberWithUnits{i + 1, "km"});
}
for (float i = 900; i > 0; i = i = i - 100)
{
CHECK_EQ(y -= s, NumberWithUnits{i, "m"});
}
CHECK_EQ(+d1, NumberWithUnits{1, "USD"});
CHECK_EQ(+d2, NumberWithUnits{-1, "USD"});
CHECK_EQ(-d1, NumberWithUnits{-1, "USD"});
CHECK_EQ(-d2, NumberWithUnits{1, "USD"});
CHECK_NE(+d1, -d1);
CHECK_THROWS(x + z);
CHECK_THROWS(x - w);
}
TEST_CASE(">/>=/</<=/==/!= operators")
{
NumberWithUnits::read_units(units_file);
CHECK_GT(NumberWithUnits{1, "km"}, NumberWithUnits{100, "m"});
CHECK_GT(NumberWithUnits{1, "ton"}, NumberWithUnits{100, "kg"});
CHECK_GE(NumberWithUnits{1, "hour"}, NumberWithUnits{10, "min"});
CHECK_GE(NumberWithUnits{1, "hour"}, NumberWithUnits{60, "min"});
CHECK_LT(NumberWithUnits{1, "km"}, NumberWithUnits{2000, "m"});
CHECK_LT(NumberWithUnits{1, "g"}, NumberWithUnits{2000, "kg"});
CHECK_LE(NumberWithUnits{1, "hour"}, NumberWithUnits{100, "min"});
CHECK_LE(NumberWithUnits{1, "hour"}, NumberWithUnits{60, "min"});
CHECK_NE(NumberWithUnits{1, "m"}, NumberWithUnits{95, "cm"});
CHECK_NE(NumberWithUnits{1, "kg"}, NumberWithUnits{987, "g"});
CHECK_EQ(NumberWithUnits{1, "min"}, NumberWithUnits{60, "sec"});
CHECK_EQ(NumberWithUnits{1, "USD"}, NumberWithUnits{3.33, "ILS"});
}
TEST_CASE("++/-- operators")
{
NumberWithUnits::read_units(units_file);
NumberWithUnits x{1, "km"};
NumberWithUnits y{1000, "m"};
NumberWithUnits z{900, "kg"};
NumberWithUnits w{3, "ton"};
CHECK_EQ(x++, NumberWithUnits{1, "km"});
CHECK_EQ(x, NumberWithUnits{2, "km"});
CHECK_EQ(++y, NumberWithUnits{1001, "m"});
CHECK_EQ(y, NumberWithUnits{1001, "m"});
CHECK_EQ(z--, NumberWithUnits{900, "kg"});
CHECK_EQ(z, NumberWithUnits{899, "kg"});
CHECK_EQ(--w, NumberWithUnits{2, "ton"});
CHECK_EQ(w, NumberWithUnits{2, "ton"});
}
TEST_CASE("x*d/d*x operators")
{
NumberWithUnits::read_units(units_file);
NumberWithUnits x{2, "km"};
CHECK_EQ((x * 2.5), NumberWithUnits{5.0, "km"});
CHECK_EQ((3.0 * x), NumberWithUnits{6.0, "km"});
}
TEST_CASE("I/O stream operators")
{
NumberWithUnits test{3, "ton"};
ostringstream os;
istringstream is("1 [ kg ]");
is >> test;
os << test;
CHECK_EQ(os.str(), "1, \"kg\"");
} |
655bda7d37b26e918f2862aae94e2a98d8b45c55 | bc67fc41eb0a64b009e4fad3302a212635e7ac19 | /02/ex00/Fixed.cpp | 1ab06b5c21b759f0ccd4035715b111dcbd0fe9f3 | [] | no_license | mrLosy/cpp-piscine | f179c353912aa692fd2146231811a879340be98a | a704427f918ca4db57cbe84ce6c194ed70da607e | refs/heads/master | 2023-07-24T13:14:09.682463 | 2021-08-29T16:32:39 | 2021-08-29T16:32:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 661 | cpp | Fixed.cpp | #include "Fixed.hpp"
Fixed::Fixed(void){
cout << "Default constructor called" << endl;
m_value = 0;
}
Fixed::Fixed(const Fixed ©){
cout << "Copy constructor called" << endl;
m_value = copy.getRawBits();
}
Fixed::~Fixed(void){
cout << "Destructor called" << endl;
}
int Fixed::getRawBits(void) const{
cout << "getRawBits member function called" << endl;
return (m_value);
}
void Fixed::setRawBits(int const raw){
cout << "setRawBits member function called" << endl;
m_value = raw;
}
Fixed & Fixed::operator=(const Fixed& ovr){
cout << "Assignation operator called" << endl;
if (this != &ovr)
m_value = ovr.getRawBits();
return (*this);
}
|
835554d16df1a4d6246a64b48770e2f5172397bf | a5d01b2a5e8ed3f57a73948cee1d17a4b8fed622 | /main.h | df2e3e569afef83932720ac6fa202bb8e9083d54 | [] | no_license | jayzoww/LacrossOnIce | 7326211202e5ba474dd9732da336e35e049522b5 | 35a1fffa7214f26ddf63bed9a6be28cd176cbdfc | refs/heads/master | 2021-01-20T03:17:55.480147 | 2017-04-26T23:09:26 | 2017-04-26T23:09:26 | 89,522,465 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 390 | h | main.h | //
// main.h
// prototype
//
// Created by Chris Morgan on 2015-02-08.
// Copyright (c) 2015 Chris Morgan. All rights reserved.
//
#ifndef __prototype__main__
#define __prototype__main__
#include "Constants.h"
#include <iostream>
#include "SDLInit.h"
#include "Game.h"
#include "Main_Menu.h"
#include "Settings_Menu.h"
using namespace std;
#endif /* defined(__prototype__main__) */
|
dbb59a6bf146f078fea17d903531c2a9a65071ef | f7af1c3c7de939a2f513fe21a89a357f3fe20145 | /opencv_lk/lk_optic_flow.cxx | 36ddd1c191bf9c2f61ab24f9e94f0c266db24a97 | [] | no_license | jsuit/opencv_experiments | 25a582200a53459ca455e3288553ccbcee1452b2 | bb3dc4e14c5b3f38ef18196c6b4161205539257c | refs/heads/master | 2020-12-25T02:39:00.720899 | 2013-09-23T05:23:32 | 2013-09-23T05:23:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,802 | cxx | lk_optic_flow.cxx | #include <cv.h>
#include <highgui.h>
#include "math.h"
using namespace cv;
const int MAX_CORNERS = 100;
int trackAndAnnotateMat(Mat& imgA, Mat& maskA, Mat& imgB, Mat& imgC);
void cvShowImageMat(const char *name, Mat& mat);
void flipHorizAndVert(Mat& img) {
int flipMode = -1;
IplImage ipl = img;
cvFlip(&ipl, &ipl, flipMode);
}
void pullFrame(VideoCapture& cap, Mat& img, Mat& imgGray, void (*adjustFunc)(Mat& img)) {
Mat frame;
cap >> frame; // get a new frame from camera
img = frame;
if (adjustFunc) {
adjustFunc(img);
}
imgGray = img.clone();
cvtColor(imgGray, imgGray, CV_BGR2GRAY);
}
// Hardcoded values for green android folder
Scalar LOW_HSV = Scalar(60, 50, 50);
Scalar HIGH_HSV = Scalar(90, 255, 255);
// Get binary thresholded image
// low_HSV, hi_HSV - low, high range values for threshold as a list [H,S,V]
// debug= True to display the binary image generated
void getBinary(Mat& src, Scalar& low_HSV, Scalar& hi_HSV, Mat& dest) {
Mat frame = src.clone();
cvtColor(frame, frame, CV_BGR2HSV);
inRange(frame, low_HSV, hi_HSV, dest);
}
int main ( int argc, char **argv )
{
// Load two images and allocate other structures
VideoCapture cap("/Users/theJenix/Development/opencv_lk/recording2.mov"); // open the default camera
if(!cap.isOpened()) // check if we succeeded
return -1;
cvNamedWindow( "ImageA", 0 );
cvNamedWindow( "ImageB", 0 );
cvNamedWindow( "LKpyr_OpticalFlow", 0 );
int flipMode = -1;
Mat imgA, imgGrayA, imgB, imgGrayB, imgC;
pullFrame(cap, imgA, imgGrayA, flipHorizAndVert);
imgC = imgA;
while(true) {
Mat maskA, discard;
getBinary(imgA, LOW_HSV, HIGH_HSV, maskA);
pullFrame(cap, imgB, imgGrayB, flipHorizAndVert);
trackAndAnnotateMat(imgGrayA, maskA, imgGrayB, imgGrayA);
cvShowImageMat( "ImageA", imgGrayA );
cvShowImageMat( "ImageB", maskA );
cvShowImageMat( "LKpyr_OpticalFlow", imgGrayA );
imgA = imgB;
imgGrayA = imgGrayB;
imgC = imgB;
usleep(30 * 1000);
}
}
void cvShowImageMat(const char *name, Mat& mat) {
IplImage img = mat;
cvShowImage(name, &img);
}
int trackAndAnnotateMat(Mat& imgA, Mat& maskA, Mat& imgB, Mat& imgC) {
CvSize img_sz = imgA.size();
int win_size = 15;
// Get the features for tracking
IplImage* eig_image = cvCreateImage( img_sz, IPL_DEPTH_32F, 1 );
IplImage* tmp_image = cvCreateImage( img_sz, IPL_DEPTH_32F, 1 );
int corner_count = MAX_CORNERS;
CvPoint2D32f* cornersA = new CvPoint2D32f[ MAX_CORNERS ];
IplImage iplA = imgA;
IplImage iplB = imgB;
IplImage maskIplA = maskA;
cvGoodFeaturesToTrack( &iplA, eig_image, tmp_image, cornersA, &corner_count,
0.05, 5.0, &maskIplA, 3, 0, 0.04 );
// printf("Found %d good features..", corner_count);
// for (int ii =0; ii < corner_count; ii++) {
// printf("%d: %f, %f\n", ii, cornersA[ii].x, cornersA[ii].y);
// }
cvFindCornerSubPix( &iplA, cornersA, corner_count, cvSize( win_size, win_size ),
cvSize( -1, -1 ), cvTermCriteria( CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, 0.03 ) );
// Call Lucas Kanade algorithm
char features_found[ MAX_CORNERS ];
float feature_errors[ MAX_CORNERS ];
CvSize pyr_sz = cvSize( img_sz.width+8, img_sz.height/3 );
IplImage* pyrA = cvCreateImage( pyr_sz, IPL_DEPTH_32F, 1 );
IplImage* pyrB = cvCreateImage( pyr_sz, IPL_DEPTH_32F, 1 );
CvPoint2D32f* cornersB = new CvPoint2D32f[ MAX_CORNERS ];
cvCalcOpticalFlowPyrLK( &iplA, &iplB, pyrA, pyrB, cornersA, cornersB, corner_count,
cvSize( win_size, win_size ), 5, features_found, feature_errors,
cvTermCriteria( CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, 0.3 ), 0 );
// Make an image of the results
IplImage iplC = imgC;
for( int i=0; i < MAX_CORNERS; i++ ) {
if (!features_found[i]) {
// printf("Feature not found\n");
continue;
}
if (feature_errors[i] > 10) {
// printf("%d: Error is %f\n", i, feature_errors[i]);
continue;
}
// printf("%d: Got it, error: %f\n", i, feature_errors[i]);
CvPoint p0 = cvPoint( cvRound( cornersA[i].x ), cvRound( cornersA[i].y ) );
CvPoint p1 = cvPoint( cvRound( cornersB[i].x ), cvRound( cornersB[i].y ) );
double dist = sqrt(pow(cornersA[i].x - cornersB[i].x, 2) + pow(cornersA[i].y - cornersB[i].y, 2));
if (dist > 100) {
// printf("Vector length: %f\n", dist);
// printf("%d,%d to %d,%d\n", p0.x, p0.y, p1.x, p1.y);
} else {
double angle = atan2(cornersB[i].y - cornersA[i].y, cornersB[i].x - cornersA[i].x);
printf("%f\n", angle);
cvLine( &iplC, p0, p1, CV_RGB(255,0,0), 2 );
}
}
cvReleaseImage(&eig_image);
cvReleaseImage(&tmp_image);
cvReleaseImage(&pyrA);
cvReleaseImage(&pyrB);
delete [] cornersA;
delete [] cornersB;
printf("Finished\n");
return 0;
}
|
080f0385024ad3721de10397313d7ff8e9c6489d | 25dc18997df14d6d17c69f04824a03f748c98784 | /BattleProject/Capacity.cpp | d568a4496e06f5bd3df9169c1a25f316f42f0a71 | [] | no_license | AlexandreRivet/BattleProject | 913696e5b2909e37e5a93af26d68a525f1aa9403 | 7cf9ffae7297f76bed9efd9ff4593bf26e651895 | refs/heads/master | 2016-09-05T17:29:35.216159 | 2015-01-25T10:06:09 | 2015-01-25T10:06:09 | 29,777,078 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 424 | cpp | Capacity.cpp | #include "Capacity.h"
Capacity::Capacity() : mLevel(0)
{
updateValue();
}
Capacity::Capacity(int level = 0) : mLevel(level)
{
updateValue();
}
Capacity::~Capacity()
{
}
void Capacity::upgrade()
{
mLevel++;
updateValue();
}
void Capacity::downgrade()
{
if (mLevel > 0)
{
mLevel--;
updateValue();
}
}
int Capacity::getLevel() const
{
return mLevel;
}
float Capacity::getValue() const
{
return mValue;
}
|
f070b8f1f38cc137c9cb26b7d371f8381118a7f7 | 7974eb7fc5ccfd9908ccf6f65b82e5213a520bf0 | /Capu/include/capu/container/HashSet.h | 029e9e9edfcce95f87b134d3a3f15cd19c433c76 | [
"Apache-2.0"
] | permissive | gurunath10/capu | 4649b6ea5f0fd22df0800fc69b40f5b2d578da2c | b04f0c2b44ed875fea6cbbaf326b73a7210272a8 | refs/heads/master | 2020-09-20T08:59:03.597553 | 2017-09-01T15:57:47 | 2017-09-04T10:03:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,357 | h | HashSet.h | /*
* Copyright (C) 2012 BMW Car IT GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef CAPU_HASHSET_H
#define CAPU_HASHSET_H
#include "capu/container/Hash.h"
#include "capu/container/HashTable.h"
namespace capu
{
/**
* Unordered set of objects with fast lookup and retrieval.
*/
template <class T, class C = Comparator, class H = CapuDefaultHashFunction<sizeof(uint_t)*8> >
class HashSet
{
private:
/**
* Iterator for HashSet
*/
template<typename HashTableIteratorType>
class HashSetIterator
{
public:
/**
* Copy Constructor
* @param iter iterator to copy
*/
HashSetIterator(const HashSetIterator<HashTableIteratorType>& iter)
: m_iter(iter.m_iter)
{
}
/*
* Assignment Operator
* @param iter r-value iterator for assignment
*/
HashSetIterator& operator=(const HashSetIterator<HashTableIteratorType>& iter)
{
m_iter = iter.m_iter;
return *this;
}
/**
* Indirection
* @return the current value referenced by the iterator
*/
const T& operator*()
{
return (*m_iter).key;
}
/**
* Dereference
* @return a pointer to the current object the iterator points to
*/
const T* operator->()
{
return &((*m_iter).key);
}
/**
* Compares two iterators
* @return true if the iterators point to the same position
*/
bool operator==(const HashSetIterator<HashTableIteratorType>& iter) const
{
return (m_iter == iter.m_iter);
}
/**
* Compares two iterators
* @return true if the iterators do not point to the same position
*/
bool operator!=(const HashSetIterator<HashTableIteratorType>& iter) const
{
return (m_iter != iter.m_iter);
}
/**
* Step the iterator forward to the next element (prefix operator)
* @return the next iterator
*/
HashSetIterator<HashTableIteratorType>& operator++()
{
m_iter++;
return *this;
}
/**
* Step the iterator forward to the next element (postfix operator)
* @return the next iterator
*/
HashSetIterator<HashTableIteratorType> operator++(int32_t)
{
HashSetIterator<HashTableIteratorType> oldValue(*this);
++(*this);
return oldValue;
}
private:
friend class HashSet<T, C, H>;
/**
* Internal constructor for HashSet
*
* @para iter iterator of the underlying hash table
*/
HashSetIterator(const HashTableIteratorType& iter)
: m_iter(iter)
{
}
HashTableIteratorType m_iter;
};
public:
/// defines to amount of bits to use for hash set size
static const uint8_t DefaultHashSetBitSize;
/**
* Iterator for hashsets
*/
typedef HashSetIterator< typename HashTable<T, char, C, H>::Iterator > Iterator;
typedef HashSetIterator< typename HashTable<T, char, C, H>::ConstIterator > ConstIterator;
/**
* Default Constructor
*/
HashSet();
/**
* Parameterized Constructor
* @param bitsize size of initial HashSet
*/
HashSet(const uint8_t bitsize);
/**
* Copy constructor.
*/
HashSet(const HashSet& other);
/**
* Destructor
*/
~HashSet();
/**
* put a new value to the hash set.
*
* @param value new value that will be put to hash set
*
* @return CAPU_OK if remove is successful
* CAPU_ERROR if value already exists in the set
*
*/
status_t put(const T& value);
/**
* Remove value associated with key in the hash set.
*
* @param value value that will be removed
*
* @return CAPU_OK if remove is successful
* CAPU_ERANGE if specified value does not exist in hash set
*
*/
status_t remove(const T& value);
/**
* Remove iterator associated with key in the hash set.
*
* @param iterator iterator pointing to value that will be removed
*
* @return CAPU_OK if removal was successful
* CAPU_ENOT_EXISTS if the key was not found in the set
*
*/
status_t removeAt(Iterator& iterator);
/**
* Checks if the provided value is already contained in the hash set.
*
* @param value value that will be checked
*
* @return true if element is already contained in the hash set
* false otherwise
*
*/
bool hasElement(const T& value) const;
/**
* Returns count of the hash set.
* @return number of element in hash set
*/
uint_t count() const;
/**
* Clear all values of the hash set.
*
* @return CAPU_OK if all elements in list have been deleted
*/
status_t clear();
/**
* Return iterator for iterating key value tuples.
* @return Iterator
*/
Iterator begin();
/**
* Return ConstIterator for iterating read only key value tuples.
* @return ConstIterator
*/
ConstIterator begin() const;
/**
* returns an iterator pointing after the last element of the list
* @return iterator
*/
Iterator end();
/**
* returns a ConstIterator pointing after the last element of the list
* @return ConstIterator
*/
ConstIterator end() const;
/**
* Reserve space for given number of bits elements. Does nothing if the
* HashSet is already bigger.
* @param bitsize The requested bit size of the set.
*/
void reserve(uint8_t bitsize);
/**
* Swap this HashSet with another
* @param other HashSet to copy from
*/
void swap(HashSet<T, C, H>& other);
private:
HashTable<T, char, C, H> m_table;
};
/**
* swap specialization for HashSet<T, C, H>
* @param first first HashSet
* @param second HashSet to swap with first
*/
template <class Key, class T, class C, class H>
inline void swap(HashSet<T, C, H>& first, HashSet<T, C, H>& second)
{
first.swap(second);
}
template <class T, class C, class H>
const uint8_t HashSet<T, C, H>::DefaultHashSetBitSize = 4u;
template <class T, class C, class H>
HashSet<T, C, H>::HashSet(const HashSet& other)
: m_table(other.m_table) // just copy the inner hash table (which defines a copy constructor)
{
}
template <class T, class C, class H>
HashSet<T, C, H>::HashSet()
: m_table(DefaultHashSetBitSize)
{
}
template <class T, class C, class H>
HashSet<T, C, H>::~HashSet()
{
}
template <class T, class C, class H>
HashSet<T, C, H>::HashSet(const uint8_t bitsize)
: m_table(bitsize)
{
}
template <class T, class C, class H>
status_t HashSet<T, C, H>::put(const T& value)
{
if (m_table.contains(value))
{
return CAPU_ERROR;
}
return m_table.put(value, 0);
}
template <class T, class C, class H>
status_t HashSet<T, C, H>::remove(const T& value)
{
return m_table.remove(value);
}
template <class T, class C, class H>
status_t HashSet<T, C, H>::removeAt(Iterator& it)
{
return m_table.remove(it.m_iter);
}
template <class T, class C, class H>
bool HashSet<T, C, H>::hasElement(const T& value) const
{
return m_table.contains(value);
}
template <class T, class C, class H>
uint_t HashSet<T, C, H>::count() const
{
return m_table.count();
}
template <class T, class C, class H>
status_t HashSet<T, C, H>::clear()
{
m_table.clear();
return CAPU_OK;
}
template <class T, class C, class H>
typename HashSet<T, C, H>::Iterator HashSet<T, C, H>::begin()
{
return Iterator(m_table.begin());
}
template <class T, class C, class H>
typename HashSet<T, C, H>::ConstIterator HashSet<T, C, H>::begin() const
{
return ConstIterator(m_table.begin());
}
template <class T, class C, class H>
typename HashSet<T, C, H>::Iterator HashSet<T, C, H>::end()
{
return Iterator(m_table.end());
}
template <class T, class C, class H>
typename HashSet<T, C, H>::ConstIterator HashSet<T, C, H>::end() const
{
return ConstIterator(m_table.end());
}
template <class T, class C, class H>
void HashSet<T, C, H>::reserve(uint8_t bitsize)
{
m_table.reserve(bitsize);
}
template <class T, class C, class H>
void HashSet<T, C, H>::swap(HashSet<T, C, H>& other)
{
m_table.swap(other.m_table);
}
}
#endif /* CAPU_HASHSET_H */
|
daa0b292ad84d47e0823507498714a4d0b9fa71f | a9dfa9262e5853321a42fdca6277b8dbb4dfeb69 | /libraries/ErriezDS3231-master/src/ErriezDS3231.cpp | 89485a707e6467dc0390e5ca835f9881541f8c25 | [
"MIT"
] | permissive | zorcik/arduino | 9a0435e269237b95430b28e41055cfa8576141bc | fb3d13ab4154a2abf7f85c0148d79686b2df90bc | refs/heads/master | 2023-04-13T14:16:00.973572 | 2023-04-04T10:51:22 | 2023-04-04T10:51:22 | 71,544,275 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,736 | cpp | ErriezDS3231.cpp | /*
* MIT License
*
* Copyright (c) 2018 Erriez
*
* 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.
*/
/*!
* \file ErriezDS3231.cpp
* \brief DS3231 high precision RTC library for Arduino
* \details
* Source: https://github.com/Erriez/ErriezDS3231
* Documentation: https://erriez.github.io/ErriezDS3231
*/
#if (defined(__AVR__) || defined(ARDUINO_ARCH_SAM))
#include <avr/pgmspace.h>
#else
#include <pgmspace.h>
#endif
#include <Wire.h>
#include "ErriezDS3231.h"
// -------------------------------------------------------------------------------------------------
/*!
* \brief Initialize and detect DS3231 RTC.
* \details
* Call this function from setup().
* \retval Success
* RTC detected.
* \retval false
* RTC not detected.
* \retval true
* Invalid status register or RTC not detected.
*/
bool DS3231::begin()
{
// Check zero bits in status register
if (readStatusRegister() & 0x70) {
return true;
}
return false;
}
// -------------------------------------------------------------------------------------------------
/*!
* \brief Enable or disable oscillator when running on V-BAT.
* \param enable
* true: Enable RTC clock when running on V-BAT.\n
* false: Stop RTC clock when running on V-BAT. Oscillator Stop Flag (OSF) bit will be set in
* status register which can be read on next power-on.
*/
void DS3231::oscillatorEnable(bool enable)
{
uint8_t controlReg;
// Read status register
controlReg = readControlRegister();
// Set or clear EOSC bit in control register
if (enable) {
// Clear to enable
controlReg &= ~(1 << DS3231_CTRL_EOSC);
} else {
// Set to disable
controlReg |= (1 << DS3231_CTRL_EOSC);
}
// Write control register
writeControlRegister(controlReg);
}
/*!
* \brief Read RTC OSF (Oscillator Stop Flag) from status register.
* \details
* The application is responsible for checking the Oscillator Stop Flag (OSF) before reading
* date/time date. This function may be used to judge the validity of the date/time registers.
* \retval true
* RTC oscillator was stopped: The date/time data is invalid. The application should
* synchronize and program a new date/time.
* \retval false
* RTC oscillator is running.
*/
bool DS3231::isOscillatorStopped()
{
// Check OSF bit in status register
if (readStatusRegister() & (1 << DS3231_STAT_OSF)) {
// RTC oscillator was stopped
return true;
} else {
// RTC oscillator is running
return false;
}
}
/*!
* \brief Clear Oscillator Stop Flag (OSF) in status register
* \details
*
*/
void DS3231::clearOscillatorStopFlag()
{
uint8_t statusReg;
// Clear OSF bit in status register
statusReg = readStatusRegister() & ~(1 << DS3231_STAT_OSF);
// Write status register
writeStatusRegister(statusReg);
}
/*!
* \brief Write date and time to RTC.
* \details
* Write all RTC registers at once to prevent a time/date register change in the middle of the
* register write operation. This function enables the oscillator and clear the Oscillator Stop
* Flag (OSF) in the status register.
* \param dateTime
* Date time structure. Providing invalid date/time data may result in unpredictable behavior.
*/
void DS3231::setDateTime(DS3231_DateTime *dateTime)
{
uint8_t buffer[7];
// Encode date time from decimal to BCD
buffer[0] = (decToBcd((uint8_t)(dateTime->second & 0x7F)));
buffer[1] = (decToBcd((uint8_t)(dateTime->minute & 0x7F)));
buffer[2] = (decToBcd((uint8_t)(dateTime->hour & 0x3F)));
buffer[3] = (decToBcd((uint8_t)(dateTime->dayWeek & 0x07)));
buffer[4] = (decToBcd((uint8_t)(dateTime->dayMonth & 0x3F)));
buffer[5] = (decToBcd((uint8_t)(dateTime->month & 0x1F)));
buffer[6] = (decToBcd((uint8_t)((dateTime->year - 2000) & 0xFF)));
// Write BCD encoded buffer to RTC registers
writeBuffer(0x00, buffer, sizeof(buffer));
// Enable oscillator
oscillatorEnable(true);
// Clear oscillator halt flag
clearOscillatorStopFlag();
}
/*!
* \brief Read date and time from RTC.
* \details
* Read all RTC registers at once to prevent a time/date register change in the middle of the
* register read operation.
* \param dateTime
* Date and time structure.
* \retval false
* Success
* \retval true
* An invalid date/time format was read from the RTC.
*/
bool DS3231::getDateTime(DS3231_DateTime *dateTime)
{
uint8_t buf[7];
// Read clock date and time registers
readBuffer(0x00, &buf, sizeof(buf));
// Convert BCD buffer to Decimal
dateTime->second = bcdToDec(buf[0]);
dateTime->minute = bcdToDec(buf[1]);
dateTime->hour = bcdToDec(buf[2] & 0x3f);
dateTime->dayWeek = bcdToDec(buf[3]);
dateTime->dayMonth = bcdToDec(buf[4]);
dateTime->month = bcdToDec(buf[5] & 0x1f);
dateTime->year = 2000 + bcdToDec(buf[6]);
// Check buffer for valid data
if ((dateTime->second > 59) ||
(dateTime->minute > 59) ||
(dateTime->hour > 23) ||
(dateTime->dayMonth < 1) || (dateTime->dayMonth > 31) ||
(dateTime->month < 1) || (dateTime->month > 12) ||
(dateTime->dayWeek < 1) || (dateTime->dayWeek > 7) ||
(dateTime->year > 2099))
{
// Invalid date/time read from RTC: Clear date time
memset(dateTime, 0x00, sizeof(DS3231_DateTime));
return true;
}
return false;
}
/*!
* \brief Write time to RTC.
* \details
* Read all date/time register from RTC, update time registers and write all date/time
* registers to the RTC with one write operation.
* \param hour Hours 0..23.
* \param minute Minutes 0..59.
* \param second Seconds 0..59.
*/
void DS3231::setTime(uint8_t hour, uint8_t minute, uint8_t second)
{
DS3231_DateTime dt;
// Read date and time from RTC
if (getDateTime(&dt) == false) {
// Update time
dt.hour = hour;
dt.minute = minute;
dt.second = second;
// Write updated date and time to RTC
setDateTime(&dt);
}
}
/*!
* \brief Read time from RTC.
* \details
* Read hour, minute and second registers from RTC.
* \param hour Hours 0..23.
* \param minute Minutes 0..59.
* \param second Seconds 0..59.
* \retval false
* Success
* \retval true
* Invalid second, minute or hour read from RTC. The time is set to zero.
*/
bool DS3231::getTime(uint8_t *hour, uint8_t *minute, uint8_t *second)
{
uint8_t buf[3];
// Read clock time registers
readBuffer(0x00, &buf, sizeof(buf));
// Convert BCD buffer to Decimal
*second = bcdToDec(buf[0]);
*minute = bcdToDec(buf[1]);
*hour = bcdToDec(buf[2] & 0x3f);
// Check buffer for valid data
if ((*second > 59) || (*minute > 59) || (*hour > 23)) {
// Invalid time
*second = 0x00;
*minute = 0x00;
*hour = 0x00;
return true;
}
return false;
}
/*!
* \brief Define number of days in a month once in flash.
*/
const uint8_t daysMonth[12] PROGMEM = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
/*!
* \brief Get Unix Epoch 32-bit timestamp in current timezone
* \details
* The DS3231 RTC year range is valid between years 2000...2100.
* The time is in UTC.
* \retval epoch
* 32-bit unsigned Unix Epoch time
*/
uint32_t DS3231::getEpochTime(DS3231_DateTime *dateTime)
{
uint16_t year;
uint16_t days;
uint8_t i;
// Convert date time to epoch
// Subtract year 2000
year = dateTime->year - 2000;
// Calculate total number of days including leap days
days = ((365 * year) + (year + 3) / 4);
// Add number of days each month in current year
for (i = 1; i < dateTime->month; i++) {
days += pgm_read_byte(daysMonth + i - 1);
}
// Check month and leap year
if ((dateTime->month > 2) && ((year % 4) == 0)) {
days++;
}
// Add number of days in current month
days += (uint16_t)(dateTime->dayMonth - 1);
// Calculate epoch, starting at offset year 2000
return SECONDS_FROM_1970_TO_2000 +
(((((days * 24UL) + dateTime->hour) * 60) + dateTime->minute) * 60) + dateTime->second;
}
//--------------------------------------------------------------------------------------------------
/*!
* \brief Set Alarm 1.
* \details
* Alarm 1 contains several alarm modes which can be configured with the alarmType parameter.
* Unused matches can be set to zero. The alarm interrupt must be enabled after setting the
* alarm, followed by clearing the alarm interrupt flag.
* \param alarmType
* Alarm 1 types:\n
* Alarm1EverySecond\n
* Alarm1MatchSeconds\n
* Alarm1MatchMinutes\n
* Alarm1MatchHours\n
* Alarm1MatchDay\n
* Alarm1MatchDate\n
* \param dayDate
* Alarm match day of the week or day of the month. This depends on alarmType.
* \param hours
* Alarm match hours.
* \param minutes
* Alarm match minutes.
* \param seconds
* Alarm match seconds.
*/
void DS3231::setAlarm1(Alarm1Type alarmType,
uint8_t dayDate, uint8_t hours, uint8_t minutes, uint8_t seconds)
{
uint8_t buffer[4];
// Store alarm 1 registers in buffer
buffer[0] = decToBcd(seconds);
buffer[1] = decToBcd(minutes);
buffer[2] = decToBcd(hours);
buffer[3] = decToBcd(dayDate);
// Set alarm 1 bits
if (alarmType & 0x01) { buffer[0] |= (1 << DS3231_A1M1); }
if (alarmType & 0x02) { buffer[1] |= (1 << DS3231_A1M2); }
if (alarmType & 0x04) { buffer[2] |= (1 << DS3231_A1M3); }
if (alarmType & 0x08) { buffer[3] |= (1 << DS3231_A1M4); }
if (alarmType & 0x10) { buffer[3] |= (1 << DS3231_DYDT); }
// Write alarm 1 registers
writeBuffer(DS3231_REG_ALARM1_SEC, buffer, sizeof(buffer));
// Clear alarm 1 flag
clearAlarmFlag(Alarm1);
}
/*!
* \brief Set Alarm 2.
* \details
* Alarm 2 contains different alarm modes which can be configured with the alarmType
* parameter. Unused matches can be set to zero. The alarm interrupt must be enabled after
* setting the alarm, followed by clearing the alarm interrupt flag.
* \param alarmType
* Alarm 2 types:\n
* Alarm2EveryMinute\n
* Alarm2MatchMinutes\n
* Alarm2MatchHours\n
* Alarm2MatchDay\n
* Alarm2MatchDate\n
* \param dayDate
* Alarm match day of the week or day of the month. This depends on alarmType.
* \param hours
* Alarm match hours.
* \param minutes
* Alarm match minutes.
*/
void DS3231::setAlarm2(Alarm2Type alarmType, uint8_t dayDate, uint8_t hours, uint8_t minutes)
{
uint8_t buffer[3];
// Store alarm 2 registers in buffer
buffer[0] = decToBcd(minutes);
buffer[1] = decToBcd(hours);
buffer[2] = decToBcd(dayDate);
// Set alarm 2 bits
if (alarmType & 0x02) { buffer[0] |= (1 << DS3231_A1M2); }
if (alarmType & 0x04) { buffer[1] |= (1 << DS3231_A1M3); }
if (alarmType & 0x08) { buffer[2] |= (1 << DS3231_A1M4); }
if (alarmType & 0x10) { buffer[2] |= (1 << DS3231_DYDT); }
// Write alarm 2 registers
writeBuffer(DS3231_REG_ALARM2_MIN, buffer, sizeof(buffer));
// Clear alarm 2 flag
clearAlarmFlag(Alarm2);
}
/*!
* \brief Enable or disable Alarm 1 or 2 interrupt.
* \details
* Enabling the alarm interrupt will disable the Square Wave output on the INT/SQW pin. The
* INT pin remains high until an alarm match occurs.
* \param alarmId
* Alarm1 or Alarm2 enum.
* \param enable
* true: Enable alarm interrupt.\n
* false: Disable alarm interrupt.
*/
void DS3231::alarmInterruptEnable(AlarmId alarmId, bool enable)
{
uint8_t controlReg;
// Clear alarm flag
clearAlarmFlag(alarmId);
// Read control register
controlReg = readControlRegister();
// Disable square wave out and enable INT
controlReg |= (1 << DS3231_CTRL_INTCN);
// Set or clear alarm interrupt enable bit
if (enable) {
controlReg |= (1 << (alarmId - 1));
} else {
controlReg &= ~(1 << (alarmId - 1));
}
// Write control register
writeControlRegister(controlReg);
}
/*!
* \brief Get Alarm 1 or 2 flag.
* \details
* Call this function to retrieve the alarm status flag. This function can be used in
* polling as well as with interrupts enabled.
*
* The INT pin changes to low when an Alarm 1 or Alarm 2 match occurs and the interrupt is
* enabled. The pin remains low until both alarm flags are cleared by the application.
* \param alarmId
* Alarm1 or Alarm2 enum.
* \retval true
* Alarm interrupt flag set.
* \retval false
* Alarm interrupt flag cleared.
*/
bool DS3231::getAlarmFlag(AlarmId alarmId)
{
// Mask alarm flags
if (readStatusRegister() & (1 << (alarmId - 1))) {
return true;
} else {
return false;
}
}
/*!
* \brief Clear alarm flag.
* \details
* This function should be called when the alarm flag has been handled in polling and
* interrupt mode. The INT pin changes to high when both alarm flags are cleared and alarm
* interrupts are enabled.
* \param alarmId
* Alarm1 or Alarm2 enum.
* \retval Success
* \retval Failure
* Incorrect alarm ID.
*/
void DS3231::clearAlarmFlag(AlarmId alarmId)
{
uint8_t statusReg;
// Read status register
statusReg = readStatusRegister();
// Clear alarm interrupt flag
statusReg &= ~(1 << (alarmId - 1));
// Write status register
writeStatusRegister(statusReg);
}
// -------------------------------------------------------------------------------------------------
/*!
* \brief Configure SQW (Square Wave) output pin.
* \details
* This will disable or initialize the SQW clock pin. The alarm interrupt INT pin will be
* disabled.
* \param squareWave
* SquareWave configuration:\n
* Disable: SquareWaveDisable\n
* 1Hz: SquareWave1Hz\n
* 1024Hz: SquareWave1024Hz\n
* 4096Hz: SquareWave4096Hz\n
* 8192Hz: SquareWave8192Hz
* \retval Success
* \retval Failure
* Incorrect squareWave.
*/
void DS3231::setSquareWave(SquareWave squareWave)
{
uint8_t controlReg;
// Read control register
controlReg = readRegister(DS3231_REG_CONTROL);
controlReg &= ~((1 << DS3231_CTRL_BBSQW) |
(1 << DS3231_CTRL_INTCN) |
(1 << DS3231_CTRL_RS2) |
(1 << DS3231_CTRL_RS1));
controlReg |= squareWave;
// Write control register
writeBuffer(DS3231_REG_CONTROL, &controlReg, sizeof(controlReg));
}
/*!
* \brief Enable or disable 32kHz output clock pin.
* \param enable
* true: Enable 32kHz output clock pin.\n
* false: Disable 32kHz output clock pin.
*/
void DS3231::outputClockPinEnable(bool enable)
{
uint8_t statusReg;
// Read status register
statusReg = readStatusRegister();
// Set or clear EN32kHz flag in status register
if (enable) {
statusReg |= (1 << DS3231_STAT_EN32KHZ);
} else {
statusReg &= ~(1 << DS3231_STAT_EN32KHZ);
}
// Write status register
writeStatusRegister(statusReg);
}
/*!
* \brief Set aging offset register
* \details
* The aging offset register capacitance value is added or subtracted from the capacitance
* value that the device calculates for each temperature compensation.
* \param val
* Aging offset value -127..127, 0.1ppm per LSB (Factory default value: 0).\n
* Negative values increases the RTC oscillator frequency.
*/
void DS3231::setAgingOffset(int8_t val)
{
uint8_t regVal;
// Convert 8-bit signed value to register value
if (val < 0) {
// Calculate two's complement for negative value
regVal = ~(-val) + 1;
} else {
// Positive register value
regVal = (uint8_t)val;
}
// Write aging offset register
writeRegister(DS3231_REG_AGING_OFFSET, regVal);
// A temperature conversion is required to apply the aging offset change
startTemperatureConversion();
}
/*!
* \brief Get aging offset register
* \details
* The aging offset register capacitance value is added or subtracted from the capacitance
* value that the device calculates for each temperature compensation.
* \return val
* Aging offset value.
*/
int8_t DS3231::getAgingOffset()
{
uint8_t regVal;
// Read aging register
regVal = readRegister(DS3231_REG_AGING_OFFSET);
// Convert to 8-bit signed value
if (regVal & 0x80) {
// Calculate two's complement for negative aging register value
return regVal | ~((1 << 8) - 1);
} else {
// Positive aging register value
return regVal;
}
}
/*!
* \brief Start temperature conversion
* \details
* Starting a conversion is only needed when the application requires temperature reads within
* 64 seconds, or changing the aging offset register.
*/
void DS3231::startTemperatureConversion()
{
uint8_t controlReg;
// Check if temperature busy flag is set
if (readStatusRegister() & (1 << DS3231_STAT_BSY)) {
return;
}
// Start temperature conversion
controlReg = readControlRegister() | (1 << DS3231_CTRL_CONV);
// Write control register
writeControlRegister(controlReg);
}
/*!
* \brief Read temperature
* \param temperature
* 8-bit signed temperature in degree Celsius.
* \param fraction
* Temperature fraction in steps of 0.25 degree Celsius. The returned value is a decimal value
* to prevent floating point usage. The application should divided the fraction by 100.
*/
void DS3231::getTemperature(int8_t *temperature, uint8_t *fraction)
{
uint8_t temp[2];
// Read temperature MSB and LSB registers
readBuffer(DS3231_REG_TEMP_MSB, &temp, sizeof(temp));
// Set temperature argument
*temperature = temp[0];
// Calculate two's complement when negative
if (*temperature & 0x80) {
*temperature |= ~((1 << 8) - 1);
}
// Shift fraction bits 6 and 7 with 0.25 degree Celsius resolution
*fraction = (temp[1] >> 6) * 25;
}
//--------------------------------------------------------------------------------------------------
/*!
* \brief BCD to decimal conversion.
* \param bcd
* BCD encoded value.
* \return
* Decimal value.
*/
uint8_t DS3231::bcdToDec(uint8_t bcd)
{
return (uint8_t)(10 * ((bcd & 0xF0) >> 4) + (bcd & 0x0F));
}
/*!
* \brief Decimal to BCD conversion.
* \param dec
* Decimal value.
* \return
* BCD encoded value.
*/
uint8_t DS3231::decToBcd(uint8_t dec)
{
return (uint8_t)(((dec / 10) << 4) | (dec % 10));
}
//--------------------------------------------------------------------------------------------------
/*!
* \brief Read control register
* \return 8-bit unsigned register value
*/
uint8_t DS3231::readControlRegister()
{
return readRegister(DS3231_REG_CONTROL);
}
/*!
* \brief Write control register
* \param value 8-bit unsigned register value
*/
void DS3231::writeControlRegister(uint8_t value)
{
return writeRegister(DS3231_REG_CONTROL, value);
}
/*!
* \brief Read status register
* \return 8-bit unsigned register value
*/
uint8_t DS3231::readStatusRegister()
{
return readRegister(DS3231_REG_STATUS);
}
/*!
* \brief Write status register
* \param value 8-bit unsigned register value
*/
void DS3231::writeStatusRegister(uint8_t value)
{
return writeRegister(DS3231_REG_STATUS, value);
}
/*!
* \brief Read register.
* \details
* Please refer to the RTC datasheet.
* \param reg
* RTC register number 0x00..0x12.
* \returns value
* 8-bit unsigned register value.
*/
uint8_t DS3231::readRegister(uint8_t reg)
{
uint8_t value;
// Read buffer with one 8-bit unsigned value
readBuffer(reg, &value, 1);
return value;
}
/*!
* \brief Write to RTC register.
* \details
* Please refer to the RTC datasheet.
* \param reg
* RTC register number 0x00..0x12.
* \param value
* 8-bit unsigned register value.
*/
void DS3231::writeRegister(uint8_t reg, uint8_t value)
{
// Write buffer with one 8-bit unsigned value
writeBuffer(reg, &value, 1);
}
/*!
* \brief Write buffer to RTC.
* \details
* Please refer to the RTC datasheet.
* \param reg
* RTC register number 0x00..0x12.
* \param buffer
* Buffer.
* \param len
* Buffer length. Writing is only allowed within valid RTC registers.
*/
void DS3231::writeBuffer(uint8_t reg, void *buffer, uint8_t len)
{
// Start I2C transfer by writing the I2C address, register number and optional buffer
Wire.beginTransmission(DS3231_ADDR);
Wire.write(reg);
for (uint8_t i = 0; i < len; i++) {
Wire.write(((uint8_t *)buffer)[i]);
}
Wire.endTransmission(true);
}
/*!
* \brief Read buffer from RTC.
* \param reg
* RTC register number 0x00..0x12.
* \param buffer
* Buffer.
* \param len
* Buffer length. Reading is only allowed within valid RTC registers.
*/
void DS3231::readBuffer(uint8_t reg, void *buffer, uint8_t len)
{
// Start I2C transfer by writing the I2C address and register number
Wire.beginTransmission(DS3231_ADDR);
Wire.write(reg);
// Generate a repeated start, followed by a read buffer
Wire.endTransmission(false);
Wire.requestFrom((uint8_t)DS3231_ADDR, len);
for (uint8_t i = 0; i < len; i++) {
((uint8_t *)buffer)[i] = (uint8_t)Wire.read();
}
}
|
13c435a3c042624d65fafc5c4a3915ed6c157f13 | aac97f1b0eb7d634e413a681bc3e44a566345151 | /onboard/test/onlygpscomp.cpp | 60584e0c7ff63a682f63a968da6fa6482e6d00e7 | [] | no_license | LochanRn/ghost | ab8baf3bbce2381d5b2e5310e0c42f57d454d6e6 | 9a3d868f7fce99d739ff4f54df9fc0ca510ba520 | refs/heads/master | 2022-01-24T08:19:00.048981 | 2019-05-23T19:50:05 | 2019-05-23T19:50:05 | 184,876,448 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,994 | cpp | onlygpscomp.cpp | #include <iostream>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
#include <errno.h>
#include <stdio.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h> //for handeling file discriptors
#include <linux/i2c-dev.h>
#include <math.h>
#include <fstream>
#include <string>
#include <cstdio>
using namespace std;
const int HMC5883L_I2C_ADDR = 0x1E;
#define buflen 5
#define port1 3302
#define port 3301 //The port in which the connection has to be made to connect with the server.
#define ip "192.168.1.25" //Host address has to be entered here.
#define gs "192.168.1.127"
#define SPI_CHAN 0
#define speed 1000000
//-----------------------gps------------------------------------
string split(string str){
int i,j;
string lat=" ",lon=" ";
double latf,lonf;
lat=str.substr(17,26);
lon=str.substr(31,40);
lat=to_string((stof(lat)/100)+0.328529);
lon=to_string((stof(lon)/100)+0.015334);
str=lat+","+lon;
return str;
}
//-------------------compass------------------------------------
void selectDevice(int fd, int addr)
{
if (ioctl(fd, I2C_SLAVE, addr) < 0)
{
cout<<"HMC5883L not present"<<endl;
}
}
void writeToDevice(int fd, int reg, int val)
{
char buf[2];
buf[0]=reg;
buf[1]=val;
if (write(fd, buf, 2) != 2)
{
cout<<"Can't write to ADXL345\n";
}
}
int setup(){
int fd;
if ((fd = open("/dev/i2c-1", O_RDWR)) < 0)
{
// Open port for reading and writing
cout<<"Failed to open i2c bus\n";
return 1;
}
/* initialise ADXL345 */
selectDevice(fd, HMC5883L_I2C_ADDR);
writeToDevice(fd, 0x01, 32);
writeToDevice(fd, 0x02, 0);
return fd;
}
int maps(int x, int in_min, int in_max, int out_min, int out_max)
{
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
float compass(unsigned char buf[], int fd){
buf[0] = 0x03;
if ((write(fd, buf, 1)) != 1)
{
// Send the register to read from
cout<<"Error writing to i2c slave\n";
}
if (read(fd, buf, 6) != 6) {
cout<<"Unable to read from HMC5883L\n";
} else {
short x = (buf[0] << 8) | buf[1];
short y = (buf[4] << 8) | buf[5];
short z = (buf[2] << 8) | buf[3];
float angle = atan2(y, x) * 180 / M_PI;
if(angle>360)
angle-=360;
if(angle<0)
angle+=360;
angle=maps(angle,0,360,360,0);
// cout<<angle<<endl;
return angle;
}
}
//----------------communication-----------------------------------------
void udp(int fd){
unsigned char buf[buflen];
for (int i = 0; i < buflen; i++)
buf[i] = ' ';
sockaddr_in si_me, si_other, me, other;
int s, s1=0, i, slen=sizeof(si_other),recv_len;
s=socket(AF_INET, SOCK_DGRAM, 0); // Creating a socket with IPv4 protocal (AF_INET) for UDP (SOCK_DGRAM) communication.
s1=socket(AF_INET, SOCK_DGRAM, 0); // Creating a socket with IPv4 protocal (AF_INET) for UDP (SOCK_DGRAM) communication.
if(s<0) {
cout<<"Socket failed"<<endl;
return;
}
memset((char *) &si_other, 0, sizeof(si_other)); //Initializing all the values of the structure to 0.
si_me.sin_family=AF_INET; //IPv4
si_me.sin_port=htons(port1); //host to network short
si_me.sin_addr.s_addr=INADDR_ANY; //Uses any address that is available.
if(bind(s, (struct sockaddr*)&si_me,sizeof(si_me))<0) //Binding to the socket using the file discriptor
{
cout<<"Binding failed"<<endl;
return;
}
recv_len=recvfrom(s,buf,buflen,0,(struct sockaddr*)&si_other,(socklen_t *)&slen);
if(buf[0] == '#' && buf[4] == '$')
cout<<buf[1]<<" "<<buf[3]<<endl;
string str;
fstream f;
f.open("/dev/ttyUSB0");
// cout<<"listening...."<<endl;
string co;
while(1){
f >> str;
if(str[5]=='A'&&str[4]=='G'){
co=split(str);
// cout<<co<<endl;
}
unsigned char buff[16];
unsigned char buf[buflen];
float angle=compass(buff,fd);
// cout<<angle<<","<<co;
string dat=co+","+to_string(angle);
// cout<<dat<<endl;
int dlen=dat.size();
unsigned char* uc = (unsigned char*)dat.c_str();
sendto(s, uc, dlen, 0, (struct sockaddr*) &si_other, slen);
}
close(s);
}
int main(){
int fd=setup();
udp(fd);
return 0;
}
|
3365850bd336232a40dc7b3cc2ed55f9300a7948 | 4b430686ae824c78604e15818c4b864778468ca1 | /Archive/Stroika_FINAL_for_STERL_1992/Applications/Schnauser/Sources/ClassesView.cc | dcdf6141afd1aed0fa4a57a1258d8c13ce276977 | [] | no_license | kjax/Stroika | 59d559cbbcfb9fbd619155daaf39f6805fa79e02 | 3994269f67cd9029b9adf62e93ec0a3bfae60b5f | refs/heads/master | 2021-01-17T23:05:33.441132 | 2012-07-22T04:32:58 | 2012-07-22T04:32:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,814 | cc | ClassesView.cc | /* Copyright(c) Sophist Solutions Inc. 1990-1992. All rights reserved */
/*
* $Header: /fuji/lewis/RCS/ClassesView.cc,v 1.5 1992/09/08 17:08:42 lewis Exp $
*
* TODO:
*
* Changes:
* $Log: ClassesView.cc,v $
* Revision 1.5 1992/09/08 17:08:42 lewis
* Renamed NULL -> Nil.
*
* Revision 1.4 1992/09/01 17:42:50 sterling
* *** empty log message ***
*
* Revision 1.3 1992/07/22 01:15:45 lewis
* Use Sequence_DoubleLinkList instead of obsolete Sequence_DoubleLinkListPtr.
*
*
*
*/
#include "Debug.hh"
#include "StreamUtils.hh"
#include "DeskTop.hh"
#include "ClassesView.hh"
// THIS SB IN BROWSERClass.cc
class BrowserClass;
#if !qRealTemplatesAvailable
typedef BrowserClass* BrowserClassPtr;
Implement (Collection, BrowserClassPtr);
Implement (Sequence, BrowserClassPtr);
#endif /*!qRealTemplatesAvailable*/
/*
********************************************************************************
******************************** ClassesBrowserView ****************************
********************************************************************************
*/
ClassesBrowserView::ClassesBrowserView ():
BrowserView ()
{
}
/*
********************************************************************************
******************************* ClassesBrowserViews ******************************
********************************************************************************
*/
#if !qRealTemplatesAvailable
Implement (Collection, ClassesBrowserViewPtr);
Implement (Sequence, ClassesBrowserViewPtr);
Implement (DoubleLinkList, ClassesBrowserViewPtr);
Implement (Sequence_DoubleLinkList, ClassesBrowserViewPtr);
#endif /*!qRealTemplatesAvailable*/
ClassesBrowserViews::ClassesBrowserViews ():
BrowserViews (),
fClassesBrowserViews ()
{
}
ClassesBrowserViews::~ClassesBrowserViews ()
{
Require (fClassesBrowserViews.IsEmpty ());
}
SequenceIterator(BrowserViewPtr)* ClassesBrowserViews::MakeBrowserViewIterator (SequenceDirection d) const
{
// Tricky to get right cuz of contravariance - pull sleezy trick for now...
return ((SequenceIterator(BrowserViewPtr)*) MakeClassesBrowserViewIterator (d));
}
void ClassesBrowserViews::AddClassesBrowserView (ClassesBrowserView* classesBrowserView)
{
RequireNotNil (classesBrowserView);
fClassesBrowserViews.Add (classesBrowserView);
}
void ClassesBrowserViews::RemoveClassesBrowserView (ClassesBrowserView* classesBrowserView)
{
RequireNotNil (classesBrowserView);
fClassesBrowserViews.Remove (classesBrowserView);
}
SequenceIterator(ClassesBrowserViewPtr)* ClassesBrowserViews::MakeClassesBrowserViewIterator (SequenceDirection d) const
{
return (fClassesBrowserViews.MakeSequenceIterator (d));
}
// For gnuemacs:
// Local Variables: ***
// mode:C++ ***
// tab-width:4 ***
// End: ***
|
5380bff480774d0215764ac82eb13b4297d8b88f | 7a2cea234d8cc2af805ce3d61b8f7cfa5e981242 | /archverse_core/inc/archverse_core/data_access/binary_serialization.h | 651a2039afac567e165d46e0195151588b118a56 | [] | no_license | hippiehunter/archverse | be337db6bc22ac7d5b2127653b2c7d5600a26088 | 1f735dbadc51251e1526cd20cf2cf685c9b29c66 | refs/heads/master | 2021-01-10T20:14:50.639324 | 2011-04-05T03:26:29 | 2011-04-05T03:26:29 | 1,554,210 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,853 | h | binary_serialization.h | #ifndef ARCHVERSE_CORE_DATA_ACCESS_BINARY_SERIALIZER_H
#define ARCHVERSE_CORE_DATA_ACCESS_BINARY_SERIALIZER_H
#include <archverse_core/data_access/reflection_metadata.h>
#include <algorithm>
#include <functional>
#include <vector>
#include <string>
#include <stdexcept>
#include <cstdint>
#include <boost/variant.hpp>
namespace archverse_core
{
namespace data_access
{
using std::vector;
using std::uint8_t;
using std::uint32_t;
using std::string;
using boost::variant;
using std::for_each;
/***************************************************************************/
/****************** Serialization partial specializations ****************/
/***************************************************************************/
template<typename T, typename BUFFERITR, typename R>
struct binary_serializer_util
{
static size_t serialize(const T& t, BUFFERITR destination, reflective_field<typename R, typename T> val)
{
return binary_serializer<typename R, typename BUFFERITR>::serialize(t.*(val._fieldPointer), destination, 0);
}
};
template<typename T, typename BUFFERITR>
struct binary_serializer_util<T, BUFFERITR, uint32_t>
{
static size_t serialize(const T& t, BUFFERITR destination, reflective_field<uint32_t, typename T> val)
{
*reinterpret_cast<uint32_t*>(destination) = t.*(val._fieldPointer);
return sizeof(uint32_t);
}
};
template<typename T, typename BUFFERITR>
struct binary_serializer_util<T, BUFFERITR, time_t>
{
static size_t serialize(const T& t, BUFFERITR destination, reflective_field<time_t, typename T> val)
{
*reinterpret_cast<time_t*>(destination) = t.*(val._fieldPointer);
return sizeof(time_t);
}
};
template<typename T, typename BUFFERITR>
struct binary_serializer_util<T, BUFFERITR, char>
{
static size_t serialize(const T& t, BUFFERITR destination, reflective_field<char, typename T> val)
{
*reinterpret_cast<char*>(destination) = t.*(val._fieldPointer);
return sizeof(char);
}
};
template<typename T, typename BUFFERITR>
struct binary_serializer_util<T, BUFFERITR, uint64_t>
{
static size_t serialize(const T& t, BUFFERITR destination, reflective_field<uint64_t, typename T> val)
{
*reinterpret_cast<uint64_t*>(destination) = t.*(val._fieldPointer);
return sizeof(uint64_t);
}
};
template<typename T, typename BUFFERITR>
struct binary_serializer_util<T, BUFFERITR, string>
{
static size_t serialize(const T& t, BUFFERITR destination, reflective_field<string, typename T> val)
{
const string& strVal = t.*(val._fieldPointer);
*reinterpret_cast<size_t*>(destination) = strVal.size();
size_t offset = sizeof(size_t);
if(strVal.size() > 0)
{
copy(strVal.begin(), strVal.end(), destination + offset);
offset += strVal.size() * sizeof(char);
}
return offset;
}
};
template<typename T, typename BUFFERITR>
struct binary_serializer_util<T, BUFFERITR, vector<uint32_t>>
{
static size_t serialize(const T& t, BUFFERITR destination, reflective_field<vector<uint32_t>, typename T> val)
{
const vector<uint32_t>& vecVal = t.*(val._fieldPointer);
*reinterpret_cast<size_t*>(destination) = vecVal.size();
size_t offset = sizeof(size_t);
if(vecVal.size() > 0)
{
copy(vecVal.begin(), vecVal.end(), destination + offset);
offset += vecVal.size() * sizeof(uint32_t);
}
return offset;
}
};
template<typename T, typename BUFFERITR>
struct binary_serializer_util<T, BUFFERITR, bool>
{
static size_t serialize(const T& t, BUFFERITR destination, reflective_field<bool, typename T> val)
{
*reinterpret_cast<bool*>(destination) = t.*(val._fieldPointer);
return sizeof(bool);
}
};
/***************************************************************************/
/****************** Deserialization partial specializations ****************/
/***************************************************************************/
template<typename T, typename BUFFERITR, typename R>
struct binary_deserializer_util
{
static size_t deserialize(T& t, BUFFERITR source, reflective_field<typename R, typename T> val)
{
return binary_deserializer<typename R, typename BUFFERITR>::deserialize(t.*(val._fieldPointer), source, 0);
}
};
template<typename T, typename BUFFERITR>
struct binary_deserializer_util<T, BUFFERITR, uint32_t>
{
static size_t deserialize(T& t, BUFFERITR source, reflective_field<uint32_t, typename T> val)
{
t.*(val._fieldPointer) = *(reinterpret_cast<uint32_t*>(source));
return sizeof(uint32_t);
}
};
template<typename T, typename BUFFERITR>
struct binary_deserializer_util<T, BUFFERITR, time_t>
{
static size_t deserialize(T& t, BUFFERITR source, reflective_field<time_t, typename T> val)
{
t.*(val._fieldPointer) = *(reinterpret_cast<time_t*>(source));
return sizeof(time_t);
}
};
template<typename T, typename BUFFERITR>
struct binary_deserializer_util<T, BUFFERITR, char>
{
static size_t deserialize(T& t, BUFFERITR source, reflective_field<char, typename T> val)
{
t.*(val._fieldPointer) = *(reinterpret_cast<char*>(source));
return sizeof(char);
}
};
template<typename T, typename BUFFERITR>
struct binary_deserializer_util<T, BUFFERITR, uint64_t>
{
static size_t deserialize(T& t, BUFFERITR source, reflective_field<uint64_t, typename T> val)
{
t.*(val._fieldPointer) = *(reinterpret_cast<uint64_t*>(source));
return sizeof(uint64_t);
}
};
template<typename T, typename BUFFERITR>
struct binary_deserializer_util<T, BUFFERITR, string>
{
static size_t deserialize(T& t, BUFFERITR source, reflective_field<string, typename T> val)
{
size_t size = *(reinterpret_cast<size_t*>(source));
size_t offset = sizeof(size_t);
if(size > 0)
{
auto str = t.*(val._fieldPointer);
str.clear();
str.resize(size, 'f');
memcpy(&str[0], source + offset, size);
offset += size;
}
return offset;
}
};
template<typename T, typename BUFFERITR>
struct binary_deserializer_util<T, BUFFERITR, vector<uint32_t>>
{
static size_t deserialize(T& t, BUFFERITR source, reflective_field<vector<uint32_t>, typename T> val)
{
size_t size = *(reinterpret_cast<size_t*>(source));
size_t offset = sizeof(size_t);
if(size > 0)
{
auto vec = t.*(val._fieldPointer);
vec.clear();
vec.resize(size / sizeof(uint32_t), 0);
memcpy(&vec[0], source + offset, size);
offset += size;
}
return offset;
}
};
template<typename T, typename BUFFERITR>
struct binary_deserializer_util<T, BUFFERITR, bool>
{
static size_t deserialize(T& t, BUFFERITR source, reflective_field<bool, typename T> val)
{
t.*val._fieldPointer = *(reinterpret_cast<bool*>(source));
return sizeof(bool);
}
};
template<typename T, typename BUFFERITR>
class binary_deserializer :
public boost::static_visitor<>
{
private:
T& _t;
BUFFERITR _origin;
BUFFERITR& _source;
size_t _sourceOffset;
size_t _sourceLen;
public:
binary_deserializer(T& t, BUFFERITR& source, size_t sourceLen) : _t(t), _source(source), _sourceOffset(0), _sourceLen(sourceLen), _origin(source) { }
template<typename R>
void operator()(reflective_field<typename R, typename T> val)
{
_sourceOffset += binary_deserializer_util<typename T, typename BUFFERITR, typename R>::deserialize(_t, _origin + _sourceOffset, val);
if(_sourceLen != 0 && _sourceOffset > _sourceLen)
throw std::runtime_error("source offset exceeded source length while deserializing");
else
_source = _origin + _sourceOffset;
}
size_t source_offset() { return _sourceOffset; }
static size_t deserialize(T& t, BUFFERITR source, size_t sourceLen)
{
static auto reflectiveFields = typename T::__init_type_fields();
BUFFERITR start = source;
binary_deserializer deserializer(t, source, sourceLen);
auto visitor = boost::apply_visitor(deserializer);
for_each(reflectiveFields.begin(),
reflectiveFields.end(),
[&](decltype(reflectiveFields[0])& field)
{
visitor(field.get<0>());
});
return deserializer.source_offset();
}
};
template<typename T, typename BUFFERITR>
class binary_serializer :
public boost::static_visitor<>
{
private:
const T& _t;
BUFFERITR _origin;
BUFFERITR& _destination;
size_t _destinationOffset;
size_t _destinationLen;
public:
binary_serializer(const T& t, BUFFERITR& destination, size_t destinationLen) : _t(t), _destination(destination), _destinationLen(destinationLen), _destinationOffset(0), _origin(destination) { }
template<typename R>
void operator()(reflective_field<typename R, typename T> val)
{
_destinationOffset += binary_serializer_util<typename T, typename BUFFERITR, typename R>::serialize(_t, _origin + _destinationOffset, val);
if(_destinationLen != 0 && _destinationOffset > _destinationLen)
throw std::runtime_error("destination offset exceeded destination length while serializing object");
else
_destination = _origin + _destinationOffset;
}
size_t destination_offset() { return _destinationOffset; }
static size_t serialize(const T& t, BUFFERITR destination, size_t destinationLen)
{
static auto reflectiveFields = typename T::__init_type_fields();
BUFFERITR start = destination;
binary_serializer serializer(t, destination, destinationLen);
auto visitor = boost::apply_visitor(serializer);
for_each(reflectiveFields.begin(),
reflectiveFields.end(),
[&](decltype(reflectiveFields[0])& field)
{
visitor(field.get<0>());
});
return serializer.destination_offset();
}
};
}
}
#endif |
05e88b45b7fc581248f959d6fc75cf3da297477a | 03761cfb8e9401ea0d7d269158c64d099064c836 | /Release/src/DeepWarp/NodeOctree/LoboNodeOctree.h | bf968338450fa99ff7ace6492eec3c392d9d3394 | [
"MIT"
] | permissive | PT-Traviresta/NNWarp | d106fbe07cb80309176428026391e20f277256dc | 69e20bc02beb0bd655620cdcfa512a00521e9a9c | refs/heads/master | 2022-01-15T07:58:01.358193 | 2018-09-07T16:38:59 | 2018-09-07T16:38:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 949 | h | LoboNodeOctree.h | #pragma once
#include <vector>
#include <Eigen/Dense>
using namespace Eigen;
class LoboVolumetricMesh;
class LoboVolumetricMeshGraph;
class LoboOctant;
class LoboNodeOctree
{
public:
LoboNodeOctree(LoboVolumetricMesh* volumtricMesh_, LoboVolumetricMeshGraph* volumtricMeshGraph_, double voxSize_, int treeDepth_);
~LoboNodeOctree();
virtual void init();
double voxSize;
int treeDepth;
LoboVolumetricMesh* volumtricMesh;
LoboVolumetricMeshGraph* volumtricMeshGraph;
std::vector<LoboOctant*> node_Octree_root;
};
class LoboOctant
{
public:
LoboOctant(Vector3d center,double length_, int depth_, LoboOctant* parent_);
~LoboOctant();
bool ifInOctant(Vector3d position);
void subdivide(LoboVolumetricMesh* volumtricMesh_, LoboVolumetricMeshGraph* volumtricMeshGraph_);
LoboOctant* parent;
std::vector<LoboOctant*> children;
std::vector<int> nodeindex;
double length;
Vector3d center;
int depth;
bool leef;
bool empty;
}; |
7f06bb578e1f8e30b65302ea81d1ce6c3ae4f15d | 40f317b106b3e8be2c6d2e80e16730171255d4c6 | /5/resu/source/dl24cyh/kth.cpp | ad6be48f92a41492072a8ca3df7fb7f2819c4211 | [] | no_license | cjsoft/inyuyao | a051814de278452cf552568adbb5fa3da9f7709f | 2b3576a7a2281edb253d3f987413358c41d4b685 | refs/heads/master | 2020-04-16T02:56:00.850442 | 2016-08-01T03:14:13 | 2016-08-01T03:14:13 | 60,826,738 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,077 | cpp | kth.cpp | #include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define MXN 5000007
using namespace std;
typedef long long ll;
int blk[MXN], raw[MXN];
int atag[MXN];
int n, size;
int qqsolve(int a, int b, int k) {
int l = a, r = b, mid, x = a / size;
while (l + 1 < r) {
mid = l + ((r - l) >> 1);
if (blk[mid] + atag[x] < k) l = mid;
else r = mid;
}
if (!x || (blk[a] + atag[x] >= k && a == l)) return l - a;
else return l - a + 1;
}
inline void build(int x) {
int r = std::min(x * size + size, n + 1);
// release(x);
for (int i = x * size; i < r; ++i) {
blk[i] = raw[i];
}
sort(blk + x * size, blk + r);
}
inline int count_lower(int p, int q, int x) {
int l = p / size, r = q / size;
int cnt = 0;
if (l == r) {
for (int i = p; i <= q; ++i)
if (i && raw[i] + atag[l] < x) ++cnt;
return cnt;
}
for (int i = p; i < l * size + size; ++i) {
if (i && raw[i] + atag[l] < x) ++cnt;
}
for (int i = l + 1; i < r; ++i) {
cnt += qqsolve(i * size, i * size + size, x);
}
for (int i = r * size; i <= q; ++i) {
if (raw[i] + atag[r] < x) ++cnt;
}
return cnt;
}
// inline int query(int a, int b, int c) {
// int l = a / size, r = b / size;
// int u = MXN, d = -MXN + 6, mid;
// while (d < u) {
// mid = (d + u + 1) / 2;
// if (count_lower(a, b, mid) <= c - 1) d = mid;
// else u = mid - 1;
// }
// // if (d == -4643)
// // puts("1");
// return d;
// }
int query(int a, int b, int k) {
int l = -MXN, r = MXN, mid;
while (l + 1 < r) {
mid = l + ((r - l) >> 1);
if (count_lower(a, b, mid) > k - 1) r = mid;
else l = mid;
}
return l;
}
inline void add(int a, int b, int data) {
int l = a / size, r = b / size;
if (l == r) {
for (int i = a; i <= b; ++i) {
raw[i] += data;
}
build(l);
return;
}
for (int i = a; i < l * size + size; ++i) {
if (i) raw[i] += data;
}
build(l);
for (int i = l + 1; i < r; ++i) {
atag[i] += data;
}
for (int i = r * size; i <= b; ++i) {
raw[i] += data;
}
build(r);
}
int getint() {
int rtn = 0, f = 1;
char ch;
while ((ch = getchar()) < '0' || ch > '9') if (ch == '-') f = -f;
rtn = ch - '0';
while ((ch = getchar()) >= '0' && ch <= '9') rtn = rtn * 10 + ch - '0';
return rtn * f;
}
int main() {
freopen("kth.in", "r", stdin);
freopen("kth.out", "w", stdout);
n = getint();
size = max(1., 1.4 * sqrt(n * 1.));
raw[0] = -MXN;
for (int i = 1; i <= n; ++i) {
raw[i] = getint();
}
for (int i = 0; i <= n / size; ++i)
build(i);
int Q, a, b, c, d;
Q = getint();
for (int i = 0; i < Q; ++i) {
a = getint(); b = getint(); c = getint(); d = getint();
if (a == 1) {
add(b, c, d);
} else {
printf("%d\n", query(b, c, d));
}
}
}
|
dbd19fd1250d3d6a3078017bf971409b03dc8ea2 | 70fdc9534ef4fd1ba537a714081064e3a428c86a | /src/include/ToolboxEvent.h | 27038b5ae56be94fc7808be1c6319ebc0c2f7351 | [
"MIT"
] | permissive | MaddTheSane/executor | 2db7649b9a04b600db4021bf61fc0f06ee2e7a71 | 2a8baf83066ead802ae22e567af41d74a4e920ff | refs/heads/CppPort | 2020-04-05T23:06:39.175156 | 2017-11-11T20:53:45 | 2017-11-11T20:53:45 | 8,348,294 | 15 | 4 | MIT | 2018-02-12T23:09:22 | 2013-02-22T01:45:23 | C++ | UTF-8 | C++ | false | false | 2,339 | h | ToolboxEvent.h | #if !defined (__TOOLEVENT__)
#define __TOOLEVENT__
/*
* Copyright 1986, 1989, 1990 by Abacus Research and Development, Inc.
* All rights reserved.
*
* $Id: ToolboxEvent.h 63 2004-12-24 18:19:43Z ctm $
*/
#include "EventMgr.h"
namespace Executor {
#if !defined (KeyThresh)
extern INTEGER KeyThresh;
extern INTEGER KeyRepThresh;
extern LONGINT DoubleTime;
extern LONGINT CaretTime;
extern Byte ScrDmpEnb;
#endif
#if !defined (__STDC__)
extern void ROMlib_alarmoffmbar();
extern LONGINT KeyTrans();
extern BOOLEAN GetNextEvent();
extern BOOLEAN WaitNextEvent();
extern BOOLEAN EventAvail();
extern void GetMouse();
extern BOOLEAN Button();
extern BOOLEAN StillDown();
extern BOOLEAN WaitMouseUp();
extern void GetKeys();
extern LONGINT TickCount();
extern LONGINT GetDblTime();
extern LONGINT GetCaretTime();
#else /* __STDC__ */
extern void ROMlib_alarmoffmbar( void );
extern pascal trap LONGINT C_KeyTrans( Ptr mapp, unsigned short code,
LONGINT *state ); extern pascal trap LONGINT P_KeyTrans( Ptr mapp, unsigned short code,
LONGINT *state );
extern pascal trap BOOLEAN C_GetNextEvent( INTEGER em,
EventRecord *evt ); extern pascal trap BOOLEAN P_GetNextEvent( INTEGER em,
EventRecord *evt );
extern pascal trap BOOLEAN C_WaitNextEvent( INTEGER mask,
EventRecord *evp, LONGINT sleep, RgnHandle mousergn ); extern pascal trap BOOLEAN P_WaitNextEvent( INTEGER mask,
EventRecord *evp, LONGINT sleep, RgnHandle mousergn );
extern pascal trap BOOLEAN C_EventAvail( INTEGER em, EventRecord *evt ); extern pascal trap BOOLEAN P_EventAvail( INTEGER em, EventRecord *evt);
extern pascal trap void C_GetMouse( Point *p ); extern pascal trap void P_GetMouse( Point *p);
extern pascal trap BOOLEAN C_Button( void ); extern pascal trap BOOLEAN P_Button( void );
extern pascal trap BOOLEAN C_StillDown( void ); extern pascal trap BOOLEAN P_StillDown( void );
extern pascal trap BOOLEAN C_WaitMouseUp( void ); extern pascal trap BOOLEAN P_WaitMouseUp( void );
extern pascal trap void C_GetKeys( unsigned char *keys ); extern pascal trap void P_GetKeys( unsigned char *keys);
extern pascal trap LONGINT C_TickCount( void ); extern pascal trap LONGINT P_TickCount( void );
extern LONGINT GetDblTime( void );
extern LONGINT GetCaretTime( void );
#endif /* __STDC__ */
}
#endif /* __TOOLEVENT__ */
|
c903c734a6e160fb735def76a0e3a70fdf6d457e | 68ec7d1d7ff91a611a2779459c932b756bab6e2b | /Pathtracer/pathtracer/Light.cpp | 59e88c4a986a388e88dc686af0ba2d56c6e4e286 | [] | no_license | keesterbrugge/TDA361_2013_pathtracer | 11ad597599358fdc9743f9e73a81bb5c44b9f71a | 5c42194477d8463bb655622089a9bf4341c2b2e4 | refs/heads/master | 2020-12-31T07:32:40.963377 | 2017-03-29T13:20:33 | 2017-03-29T13:20:33 | 86,585,250 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 977 | cpp | Light.cpp | #include "Light.h"
#include "MCSampling.h"
using namespace chag;
Light::Light(void)
{
}
Light::~Light(void)
{
}
///////////////////////////////////////////////////////////////////////////////
// Rejection sample a uniform position inside the sphere. There is
// a better way.
///////////////////////////////////////////////////////////////////////////////
float3 Light::sample()
{
float3 p = make_vector(2.0f, 0.0f, 0.0f);
while(length(p) > 1.0) {
p = 2.0f * make_vector(randf(), randf(), randf());
p -= make_vector(1.0f, 1.0f, 1.0f);
}
return m_radius * p + m_position;
}
///////////////////////////////////////////////////////////////////////////////
// Calculate the radiance that is emitted from the light and reaches point p
///////////////////////////////////////////////////////////////////////////////
float3 Light::Le(const float3 &p)
{
float dist = length(m_position - p);
return m_intensity / (dist * dist);
}
|
86fe543f12d3cb8c974ee20a1669f5b8068df54c | 17d6ea55a5fdae34727fd56b4f2bb1148198cfb8 | /reco/GETDecoder/GETMath.hh | 7ff42c361f8cdca04ccf10910df0742cf34882ee | [] | no_license | ATTPC/ATTPCROOT | 5e6b8532f0f5e9d70e26f237793cf49e31e31e51 | 461ffe04c68d27c71dadfd98def29160ef379571 | refs/heads/develop_ROOT6_OMP | 2021-01-25T04:01:44.061063 | 2016-02-06T19:44:12 | 2016-02-06T19:44:12 | 28,956,955 | 3 | 3 | null | 2016-09-15T23:53:42 | 2015-01-08T08:43:19 | C++ | UTF-8 | C++ | false | false | 1,822 | hh | GETMath.hh | // =================================================
// GETMath Class
//
// Author:
// Genie Jhang ( geniejhang@majimak.com )
//
// Log:
// - 2013. 10. 24
// Start writing class
// =================================================
#ifndef _GETMATH_H_
#define _GETMATH_H_
#include "TObject.h"
#include "TROOT.h"
class GETDecoder;
class GETFrame;
/*!
* Basically, what this class does is the same as TH1D class in ROOT.
* The difference is that this class only provides the **mean** and **RMS** values.
* Nothing else!
**/
class GETMath : public TObject
{
public:
//! Constructor
GETMath();
//! Constructor with GETDecoder class pointer
GETMath(GETDecoder *decoder);
//! Destructor
virtual ~GETMath();
//! With the mean and RMS, calculated before, use the **value** to calculate new **mean** and **RMS** recursively.
void Add(Double_t value);
//! Return the calculated **mean** value.
Double_t GetMean();
//! Return the calculated **RMS** value.
Double_t GetRMS();
//! Return the calculated **RMS squared** value.
Double_t GetRMS2();
/// Set the values manually. Note that the last argument is rms squared, that is variance.
void Set(Int_t numValues, Double_t mean, Double_t rms2);
//! Temporary
Double_t **GetAverage(Int_t numChannels, Int_t *chList, Int_t frameNo = -1);
//! Reset all the values.
void Reset();
private:
GETDecoder *fDecoder; /// GETDecoder class pointer
GETFrame *fFrame; /// GETFrame class pointer
Int_t fNumValues; /// Number of values added
Double_t fMean; /// mean value
Double_t fRms; /// RMS value
Double_t *fAdc[4]; /// Average value storage for GetAverage() method
//! Added for dictionary making by ROOT
ClassDef(GETMath, 1);
};
#endif
|
fede1864f6a60a3ce3dfacca972094c00f57a71b | d53be190b611a38ef358d66bc749256a3d208d6f | /SDLSharedContext/main.cpp | 60c9edbf454ac283c88e6cfae1f85d22d83ae077 | [] | no_license | kidsnow/SDLSharedContext | 147c5c363173654985c9c574834cce38d16d33f6 | 3c2ce69b892cb2e0ac5200b5bbc93da1586f05c0 | refs/heads/master | 2020-04-21T16:10:48.293618 | 2019-03-17T07:55:09 | 2019-03-17T07:55:09 | 169,692,173 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 379 | cpp | main.cpp | #include "application.h"
#include "share_src_texture.h"
#include "share_dst_texture.h"
#include "single_offscreen_rendering.h"
int main(int argc, char** argv)
{
Application* app = new ShareSrcTextureApp();
// Application* app = new SingleOffscreenRenderingApp();
// Application* app = new ShareDstTextureApp();
app->Initialize();
app->Run();
delete app;
return 0;
} |
ed299c22afbaf73abc135ff912bdb111ad895f02 | 46f7ace0ee977b88234a6baea103d83ddf0f864d | /interfaces/sdl_opengl/alx_noeud_image_sdl_opengl.h | 0d5dcf292e852728521c12d065b78184b956a33b | [] | no_license | AlexDmr/b207 | 53806b7749e862dbc908e47ce466bb68de5d17c3 | 86789fbc3ae8a9d8006e515962fa81862faa4819 | refs/heads/master | 2020-05-17T01:56:42.816496 | 2013-10-16T20:05:23 | 2013-10-16T20:05:23 | 32,222,687 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 10,083 | h | alx_noeud_image_sdl_opengl.h | #ifndef __ALX_NOEUD_IMAGE_SDL_OPENGL_H__
#define __ALX_NOEUD_IMAGE_SDL_OPENGL_H__
#include "..\alx_noeud_scene.h"
#include "..\..\opengl\alx_image_opengl.h"
#include "../fonctions_serialisations.cpp"
inline void* AlphaNum_vers_Void(const char *ad) {return (void*)strtol(ad, (char **)NULL, 16);}
class alx_noeud_image_sdl_opengl : public alx_noeud_scene, public alx_image_opengl
{private:
Liste_de_rappel L_rap_maj_Info_texture, L_rap_fin_maj_data_texture;
mutable alx_chaine_char cc_tmp;
CFSD<alx_noeud_image_sdl_opengl> classe_serialisation;
void init();
void init_ptr();
mutable alx_chaine_char serialisation_type_img , serialisation_differences_type_img
, serialisation_contenu_img, serialisation_differences_contenu_img
, nouv_serialisation_type_img , seri_diff_type_img;
protected:
alx_point2D A_pt_tmp;
public :
alx_noeud_image_sdl_opengl(const bool mipmap = false);
alx_noeud_image_sdl_opengl(const char *n, const bool mipmap = false);
alx_noeud_image_sdl_opengl(const alx_image_opengl &img);
//alx_noeud_image_sdl_opengl(alx_image_opengl *image_gl);
alx_noeud_image_sdl_opengl(const INFOS_TEXTURE &info_text, const double taille_x, const double taille_y);
~alx_noeud_image_sdl_opengl();
inline const alx_chaine_char& Nom() const {return alx_noeud_scene::Nom();}
inline void Nom(const alx_chaine_char &n) {alx_noeud_scene::Nom(n);}
inline const int Nb_octets_par_pixels_texture() const {return alx_image_opengl::Nb_octets_par_pixels_texture();}
inline void Nb_octets_par_pixels_texture(const int v) {alx_image_opengl::Nb_octets_par_pixels_texture(v);}
inline const int Ordre_couleur_texture() const {return alx_image_opengl::Ordre_couleur_texture();}
inline void Ordre_couleur_texture (const int v) {alx_image_opengl::Ordre_couleur_texture(v);}
virtual const char* Real_class_cmd() {return "Void_vers_image";}
inline void maj(const int tx, const int ty, const int ordre_couleur, const int nb_octet_par_pix, const char *buffer) {alx_image_opengl::maj(tx, ty, ordre_couleur, nb_octet_par_pix, buffer); L_rap_fin_maj_data_texture.Rappeler(this);}
inline void maj_raw(const int tx, const int ty, const int ordre_couleur, const int nb_octet_par_pix, void *ad) {maj(tx, ty, ordre_couleur, nb_octet_par_pix, (char*)ad) ;}
inline const bool Threaded_maj_raw_with_transfo( const int tx, const int ty
, const int ordre_couleur_src, const int nb_octet_par_pix_src
, const int ordre_couleur_tgt, const int nb_octet_par_pix_tgt, void *ad) {return Threaded_maj(tx, ty, ordre_couleur_src, nb_octet_par_pix_src, ordre_couleur_tgt, nb_octet_par_pix_tgt, (char*)ad);}
inline void maj_raw_with_transfo( const int tx, const int ty
, const int ordre_couleur_src, const int nb_octet_par_pix_src
, const int ordre_couleur_tgt, const int nb_octet_par_pix_tgt, void *ad) {alx_image_opengl::maj_transfo(tx, ty, ordre_couleur_src, nb_octet_par_pix_src, ordre_couleur_tgt, nb_octet_par_pix_tgt, (char*)ad);
L_rap_fin_maj_data_texture.Rappeler(this);
}
inline void maj(const char *n) {alx_image_opengl::maj(n); ; L_rap_fin_maj_data_texture.Rappeler(this);}
inline void maj(const INFOS_TEXTURE &info) {alx_image_opengl::maj(info); ; L_rap_fin_maj_data_texture.Rappeler(this);}
inline void maj(const alx_image_opengl &img) {alx_image_opengl::maj(img); ; L_rap_fin_maj_data_texture.Rappeler(this);}
inline void maj(const alx_image_32 *img_32) {alx_image_opengl::maj(img_32); ; L_rap_fin_maj_data_texture.Rappeler(this);}
inline void maj_tempon() {alx_image_opengl::maj_tempon() ; L_rap_fin_maj_data_texture.Rappeler(this);}
inline void Copier(const alx_noeud_image_sdl_opengl &i) {alx_image_opengl::maj(i);}
inline const bool Sauver_dans_fichier(const char *nf) {return alx_image_opengl::Sauver_dans_fichier(nf);}
//____________________________________________________________________________
inline virtual void Calculer_boites() {alx_noeud_scene::Calculer_boite_fils(); alx_noeud_image_sdl_opengl::Calculer_boite_noeud();}
virtual void Calculer_boite_noeud();
//____________________________________________________________________________
inline void abonner_a_fin_maj_data_texture(alx_methode_rappel *m) {L_rap_fin_maj_data_texture.Ajouter_methode_a_la_fin(m);}
inline void desabonner_de_fin_maj_data_texture(alx_methode_rappel *m) {L_rap_fin_maj_data_texture.Retirer_methode (m);}
//____________________________________________________________________________
inline void abonner_a_maj_Info_texture(alx_methode_rappel *m) {L_rap_maj_Info_texture.Ajouter_methode_a_la_fin(m);}
inline void desabonner_de_maj_Info_texture(alx_methode_rappel *m) {L_rap_maj_Info_texture.Retirer_methode (m);}
//____________________________________________________________________________
void Lock_mutex_tempon() {alx_image_32::Lock_mutex_tempon ();}
void UnLock_mutex_tempon() {alx_image_32::UnLock_mutex_tempon();}
//____________________________________________________________________________
inline const bool Inverser_x() const {return alx_image_opengl::Inverser_x();}
inline const bool Inverser_y() const {return alx_image_opengl::Inverser_y();}
inline void Inverser_x(bool e) {alx_image_opengl::Inverser_x(e);}
inline void Inverser_y(bool e) {alx_image_opengl::Inverser_y(e);}
//____________________________________________________________________________
virtual void PreRendre();
void Dessin_noeud();
virtual info_du_contenant* Noeud_contient(const alx_point2D &pt, int action); // Renvoi un pointeur sur le modèle physique qui contient la primitive, NULL si aucun.
inline alx_image_opengl& Img() {return *((alx_image_opengl*)this);}
inline INFOS_TEXTURE* Ptr_Info_texture() {return alx_image_opengl::Ptr_Info_texture();}
inline INFOS_TEXTURE& Info_texture() {return alx_image_opengl::Info_texture();}
inline const INFOS_TEXTURE& Info_texture_const() const {return alx_image_opengl::Info_texture_const();}
inline const void* Tempon_const() const {return TEMPON_const();}
inline void* Tempon() {return TEMPON();}
inline int Adresse_Tempon() {return (int)Tempon();}
inline const unsigned int Taille_Tempon() {return alx_image_opengl::Taille_Tempon();}
inline void Nb_octets_par_pixel(const int n) {alx_image_opengl::Nb_octets_par_pixel( (unsigned int)n);}
inline const int Nb_octets_par_pixel() const {return (int)alx_image_opengl::Nb_octets_par_pixel();}
inline const int Ordonnancement_couleurs() const {return alx_image_opengl::Ordonnancement_couleurs();}
inline void Ordonnancement_couleurs(const int o) {alx_image_opengl::Ordonnancement_couleurs(o);}
inline const double Lg() const {return alx_image_opengl::L();}
inline const double Ht() const {return alx_image_opengl::H();}
inline void Lg(const double v) {alx_image_opengl::L((int)v);}
inline void Ht(const double v) {alx_image_opengl::H((int)v);}
// Les surcharges pour la sérialisation
// La différence _____________________________________________________________
inline virtual const alx_chaine_char& Serialiser_difference_type() const {return Serialiser_difference_type( Serialiser_difference_contenu() );}
virtual const alx_chaine_char& Serialiser_difference_type(const alx_chaine_char &diff_contenu) const;
virtual const alx_chaine_char& Serialiser_difference_contenu() const;
inline virtual const alx_chaine_char& Serialisation_differences_type() const {return serialisation_differences_type_img;}
inline virtual const alx_chaine_char& Serialisation_differences_contenu() const {return serialisation_differences_contenu_img;}
// La sérialisation __________________________________________________________
virtual const alx_chaine_char& Serialiser_type(const alx_chaine_char &contenu) const;
virtual const alx_chaine_char& Serialiser_contenu() const;
virtual const alx_chaine_char& Serialisation_contenu() const {return serialisation_contenu_img;}
inline virtual const alx_chaine_char& Serialiser_type() const {return Serialiser_type( Serialiser_contenu() );}
virtual const alx_chaine_char& Serialisation_type () const {return serialisation_type_img;}
// La désérialisation ________________________________________________________
inline virtual void Deserialiser_type(const alx_chaine_char &txt) {unsigned int pos=0; Deserialiser_type(txt, pos);}
virtual void Deserialiser_type(const alx_chaine_char &txt, unsigned int &pos);
inline virtual void Deserialiser(const alx_chaine_char &txt) {unsigned int pos=0; Deserialiser(txt, pos);}
virtual void Deserialiser(const alx_chaine_char &txt, unsigned int &pos);
void alx_noeud_image_sdl_opengl::Deseri_info_texture(const alx_chaine_char &t);
const bool alx_noeud_image_sdl_opengl::Seri_diff_info_texture_a_ete_change(const alx_chaine_char **) const;
};
typedef alx_noeud_image_sdl_opengl* P_alx_noeud_image_sdl_opengl;
inline alx_noeud_image_sdl_opengl* Void_vers_image(void *p) {return (alx_noeud_image_sdl_opengl*)p;}
inline void* Int_vers_Void(int ad) {return (void*)ad;}
#endif
|
5ea029255637843185bcc22938af0aadf1c774d4 | 17fa06a77a97d899be65b3cf915f8bbe14ad82fe | /1040.cpp | 62c625ca9bf6112b9d4660c09c73fc87de2ff791 | [] | no_license | tahuruzzoha-tuhin/CP-Solving | f3954c700903a0e8f24674b2c69056b2c5df35eb | 18293e22f9ddaa16a688dafb48a5a4b391782a5e | refs/heads/main | 2023-01-31T02:45:02.472680 | 2020-12-14T12:25:21 | 2020-12-14T12:25:21 | 304,370,136 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,550 | cpp | 1040.cpp | // Problem: Average 3
// Contest: URI Online Judge - Beginner
// URL: https://www.urionlinejudge.com.br/judge/en/problems/view/1040
// Memory Limit: 1024 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)
/*Read four numbers (N1, N2, N3, N4), which one with 1 digit after the decimal point, corresponding to 4 scores obtained by a student. Calculate the average with weights 2, 3, 4 e 1 respectively, for these 4 scores and print the message "Media: " (Average), followed by the calculated result. If the average was 7.0 or more, print the message "Aluno aprovado." (Approved Student). If the average was less than 5.0, print the message: "Aluno reprovado." (Reproved Student). If the average was between 5.0 and 6.9, including these, the program must print the message "Aluno em exame." (In exam student).
In case of exam, read one more score. Print the message "Nota do exame: " (Exam score) followed by the typed score. Recalculate the average (sum the exam score with the previous calculated average and divide by 2) and print the message “Aluno aprovado.” (Approved student) in case of average 5.0 or more) or "Aluno reprovado." (Reproved student) in case of average 4.9 or less. For these 2 cases (approved or reproved after the exam) print the message "Media final: " (Final average) followed by the final average for this student in the last line.
Input
The input contains four floating point numbers that represent the students' grades.
Output
Print all the answers with one digit after the decimal point.*/ |
5ab1d62b6804d0e6914437127743deb9ecec22d0 | ce64367bf33fffd7eef7da1badadb67e0da7bbd0 | /vt6/ConcreteSquareMatrix.h | fbd8d366a643cd75d6e1f62a34c57affaf4f842a | [] | no_license | jujokio/Advanced_Object-Oriented_Programming | 2b3288e236cf01e790d4d4e7d11abdfbfa95f665 | a2c04b39919ff85294abdc52d8e7239af3536b27 | refs/heads/master | 2021-01-20T12:33:41.842852 | 2017-02-28T11:06:15 | 2017-02-28T11:06:15 | 82,661,872 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,849 | h | ConcreteSquareMatrix.h | /**
\file SquareMatrix.h
\brief SquareMatrix luokan header
*/
#ifndef CCONCRETESQUAREMATRIX_H
#define CONCRETESQUAREMATRIX_H
#include <string>
#include "Element.h"
/**
\class SquareMatrix
\brief 2*2 matriisi luokka
*/
class ConcreteSquareMatrix
{
public:
ConcreteSquareMatrix();
ConcreteSquareMatrix(int z, int dimensio);
ConcreteSquareMatrix(int dimensio,const std::vector<std::vector<std::shared_ptr<IntElement>>> ievector);
ConcreteSquareMatrix(const std::string &str);
virtual ~ConcreteSquareMatrix()=default;
void print(std::ostream &os)const;
std::string toString()const;
void pushVector(std::vector<std::shared_ptr<IntElement>> line);
std::vector<std::vector<std::shared_ptr<IntElement>>> getMatrixvector()const;
ConcreteSquareMatrix Transpose()const;
ConcreteSquareMatrix& operator+=(const ConcreteSquareMatrix& sq);
ConcreteSquareMatrix& operator-=(const ConcreteSquareMatrix& sq);
ConcreteSquareMatrix& operator*=(const ConcreteSquareMatrix& sq1);
bool operator==(const ConcreteSquareMatrix& sq) const;
ConcreteSquareMatrix& operator=(const ConcreteSquareMatrix& sq);
ConcreteSquareMatrix& operator=(ConcreteSquareMatrix&& sq);
ConcreteSquareMatrix(const ConcreteSquareMatrix& sq);
ConcreteSquareMatrix(ConcreteSquareMatrix&& sq);
private:
int matriisinkoko;
std::vector<std::vector<std::shared_ptr<IntElement>>> matrixvector;
};
ConcreteSquareMatrix operator+(const ConcreteSquareMatrix &m1, const ConcreteSquareMatrix &m2);
ConcreteSquareMatrix operator-(const ConcreteSquareMatrix &m1, const ConcreteSquareMatrix &m2);
ConcreteSquareMatrix operator*(const ConcreteSquareMatrix &m1, const ConcreteSquareMatrix &m2);
#endif // SQUAREMATRIX_H
|
aa41e80dc6f944ccbd24c2ec3318ad24f90590e6 | 733d6621b9ccd2fb80aada7b2c813958083aa482 | /autoCompletion/header/autocompletion.hpp | 003954eb198e14b3b9f3653059e498d875b9a310 | [] | no_license | Glorung/Epitech | f6fbd9a1dbf6a2d301e0af91f002fb7524cc455e | a08d2a4f1fd9128761b9f901bcb1e74194abdde0 | refs/heads/master | 2021-09-19T17:03:22.872346 | 2018-07-29T20:48:28 | 2018-07-29T20:48:28 | 142,793,763 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,133 | hpp | autocompletion.hpp | #pragma once
#include <iostream>
#include <string>
#include <vector>
#include <stdlib.h>
# define USAGE1 "USAGE\n\t./autocompletion dictionnary\n\n"
# define USAGE2 "DESCRIPTION\n\tdictionnary\tfile,"
# define USAGE3 "containing one adress per line, serving as kmowledge base"
# define ERROR_V (84)
// autoCompletion.cpp
struct City
{
std::string name;
unsigned int size;
};
struct Town
{
std::string line;
std::vector<std::string> city;
int nb;
std::string streetType;
std::vector<std::string> streetName;
};
class AutoCompletionStreet
{
unsigned int pos;
std::string get;
std::vector<City> getTown;
public:
// fct
void Init(std::vector<Town>);
int IsInStreetName(std::string);
void displayChoice(std::vector<char>);
void displayFinalChoice(std::vector<std::vector<std::string> > &);
bool myStreetNameCmp(Town, Town);
std::vector<char> getChoice();
bool streetNameExist(std::vector<Town>, std::vector<std::string>);
std::vector<Town> removeUselessTown(std::vector<Town>);
std::vector<std::vector<std::string> > getFinalChoice(std::vector<Town>);
int checkEndWord();
void updateVector();
char getInput(int, int);
std::vector<std::string> autoGetTown(std::vector<Town>);
};
class AutoCompletionTown
{
unsigned int pos;
std::string get;
std::vector<City> getTown;
public:
// fct
void Init(std::vector<Town>);
int IsInCity(std::string);
void displayChoice(std::vector<char>);
void displayFinalChoice(std::vector<std::vector<std::string> > &);
bool myCityCmp(Town, Town);
std::vector<char> getChoice();
bool cityExist(std::vector<Town>, std::vector<std::string>);
std::vector<Town> removeUselessTown(std::vector<Town>);
std::vector<std::vector<std::string> > getFinalChoice(std::vector<Town>);
int checkEndWord();
void updateVector();
char getInput(int, int);
std::vector<std::string> autoGetTown(std::vector<Town>);
};
// exec.cpp
class Exec
{
public:
Exec();
~Exec();
int get_file(std::string);
int parser();
std::vector<std::string> getTownName(std::string);
int getTownNbr(std::string);
std::string getStreetType(std::string);
std::vector<std::string> getStreetName(std::string);
void parserLine(std::string &, std::string &);
void treeGeneration();
void updateExecTown(std::vector<std::string>);
int start();
int compareElem(Town, Town);
void checkDoublon();
private:
std::vector<std::string> file;
std::vector<Town> town;
std::vector<Town> backup;
std::string input;
AutoCompletionStreet completionStreet;
AutoCompletionTown completionTown;
};
// main.cpp
int main(int, char **);
void print_usage();
// string_utils.cpp
void epur_str(std::string &);
int vectorCmp(std::vector<std::string>, std::vector<std::string>);
std::vector<std::string> strToVector(std::string, const std::string &);
void toLower(std::string &);
std::string toUpper(std::string);
int checkVector_char(std::vector<char>, char);
// getEntry.cpp
std::string getEntry();
|
a4c486d9ec0ca3aca6a402ff254e035f1b5c7baa | c02b942e1381fd1a0c7fbf91f9d3ea4d65966c39 | /H-regulator.ino | 48df308a145ae66df3b7e40a9fcbc6913fdd4f0f | [] | no_license | Simfire/Hastighetsregulator | 3d2ebf5c48a89aa3bf1203b6c5ddddc04a8c3900 | a0045bdfdc403042525499725387b5ec2e5bc18c | refs/heads/master | 2023-03-12T04:02:44.727450 | 2021-03-04T12:13:19 | 2021-03-04T12:13:19 | 336,387,552 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,548 | ino | H-regulator.ino | // This program monitors the wheelspeed by counting the pulse frequency from the wheel ABS sensor.
// If it exeeds 230 Hz (32 km/h) it cuts of the power suply to the ignition coil.
//
// On a Volvo 850 -97 with tyre dimension 205/55 R16 and 48 tooths on the ABS ring you get the following values:
// velocity/circumferense = rounds/sec, rounds/sec * (number of tooths on ABS ring) = pulses/sec (Hz)
// km/h / 3,6 = m/s, tyre dimension 205/55 R16 equals 1,9 m in circumferense
// 27 km/h = a pulse frequency of 189 Hz
// 30 km/h = a pulse frequency of 210 Hz
// 33 km/h = a pulse frequency of 231 Hz
//
// Author: Anders Hansson
// Date: Februari 2020
// Tested on Arduino Uno rev 3
//************************************************************************************************************
#include <LiquidCrystal.h>
// Declarations of global constants and variables *****************************
const int accessCodePin = 1; // Pin for control of access code.
const int d4 = 5, d5 = 4, d6 = 3, d7 = 2 ; // lcd ports: d4 - d7 = data ports
const int rs = 7, en = 6; // rs = register select, e = enable
const int wheelSensorTestPin1 = 8; // For testing the condition of the wheelsensor.
const int wheelSensorTestPin2 = 9; // - " -
const int wheelSensorPulsePin = 10; // Pin for reading the puls from the wheelsensor.
const int ignitionPulsePin = 11; // Pin for reading the pulse to the ignition coil.
const int ignitionPin = 12; // Controls the status of the ignitioncoil.
float velocity; // Speed of wheel.
float frequency; // Pulse frequency.
// Initialize the library by associating any needed LCD interface pin
// with the arduino pin number it is connected to
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
// Declarations of functions ***************************************************
// This function cuts off the power to the ignition coil and
// displays "Startspärr aktiverad!" on lcd.
void immobilizer(void) {
while(1){ // Endless loop, restart to exit!
digitalWrite(ignitionPin, LOW);
lcd.clear();
lcd.setCursor(3, 0);
lcd.print("Startsp"); lcd.print(char(225)); lcd.print("rr");
lcd.setCursor(3, 1);
lcd.print("aktiverad!");
delay(2000);
}
}
// This function controles the status of access code.
// Returns "true" if access code correct otherwise "false".
bool codeOk(void) {
int i;
for (i = 2; i >= 0; i--) {
if (digitalRead(accessCodePin) == HIGH) {
lcd.setCursor(0, 0);
lcd.print("Koden okej!");
delay(1000);
return true;
} else {
lcd.setCursor(0, 0);
lcd.print ("Fel kod!");
lcd.setCursor(0, 1);
lcd.print(i);
lcd.print(" f");lcd.print(char(239));lcd.print("rs");lcd.print(char(239));lcd.print("k kvar!");
delay(3000);
}
}
immobilizer();
}
// This function controles the status of wheel sensor.
// Returns "true" if sensor is okey otherwise "false".
bool wheelSensorOk(void) {
digitalWrite(wheelSensorTestPin1, HIGH); // Initiates test
delay(100);
if (digitalRead(wheelSensorTestPin2) == HIGH) {
digitalWrite(wheelSensorTestPin1, LOW); // Abort test
return true;
} else {
digitalWrite(wheelSensorTestPin1, LOW); // Abort test
return false;
}
}
// This function calculates and returns the frequency of the pulse [Hz].
float pulseFrequency(int pulsePin) {
long pulseHigh; // High duration time of pulse.
long pulseLow; // Low duration time of pulse.
float pulsePeriod; // Period time of the pulse.
pulseHigh = pulseIn(pulsePin, HIGH); // High time in micro seconds.
pulseLow = pulseIn(pulsePin, LOW); // Low time in micro seconds.
pulsePeriod = pulseHigh + pulseLow; // Period time of the pulse in micro seconds.
if (pulsePeriod == 0){
frequency = 0;
} else {
frequency = (1000000/pulsePeriod); // Frequency in Hertz. (Hz)
}
return frequency;
}
// This function restricts the engine to 1200 rpm
void safeMode(void) {
float rpm;
while (1) { // Endless loop, restart to exit!
rpm = pulseFrequency(ignitionPulsePin) * 12; // 5 cylinder => 5 sparks/round. 1 Hz in ignition pulse = 12 rpm.
if (rpm > 1200) {
digitalWrite(ignitionPin, LOW);
} else {
digitalWrite(ignitionPin, HIGH);
}
lcd.clear();
lcd.setCursor(2, 0);
lcd.print("S"); lcd.print(char(225)); lcd.print("kerhets");
lcd.print("l"); lcd.print(char(225)); lcd.print("ge");
lcd.setCursor(3, 1);
lcd.print("aktiverat!");
delay(1000);
}
}
void setup() {
pinMode(ignitionPin, OUTPUT);
pinMode(wheelSensorTestPin1, OUTPUT);
pinMode(wheelSensorTestPin2, INPUT);
pinMode(wheelSensorPulsePin, INPUT);
pinMode(ignitionPulsePin, INPUT);
pinMode(accessCodePin, INPUT);
lcd.begin(16, 2); // Initiates lcd.
lcd.clear(); // Clear the lcd.
digitalWrite(ignitionPin, LOW); // Initial status of ignition coil is power OFF.
if (codeOk() == true) { // Check access code.
// Continuity test for the wheel sensor. If it's OK the ignition coil is enabled
// otherwise the coil is dissabled.
lcd.setCursor(0, 0);
lcd.print("Test hjulsensor");
delay(2000);
if (wheelSensorOk() == true) {
digitalWrite(ignitionPin, HIGH); // Power ON to ignition coil.
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Hjulsensor OK!");
delay(3000);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("K"); lcd.print(char(239)); lcd.print("r");
lcd.print(" f"); lcd.print(char(239)); lcd.print("rsiktigt!");
delay(4000);
lcd.clear();
} else {
lcd.clear();
lcd.setCursor(1, 0);
lcd.print("Hjulsensor ur");
lcd.setCursor(3, 1);
lcd.print("funktion!");
delay(2000);
immobilizer(); // Endless loop, restart to exit!
}
}
}
// Main program starts here. ********************************************
void loop() {
float wheelSensorPulsFrequency;
wheelSensorPulsFrequency = pulseFrequency(wheelSensorPulsePin);
velocity = wheelSensorPulsFrequency * 0.1425; // Speed in km/h.
if (velocity < 29) {
lcd.setCursor(14, 1);
lcd.print(":)");
digitalWrite(ignitionPin, HIGH); // Power to ignition coil ON.
if (velocity == 0){
if (wheelSensorOk() == false){
lcd.clear();
lcd.setCursor(1,0);
lcd.print("Hjulsensor ur");
lcd.setCursor(3,1);
lcd.print("funktion!");
delay(1000);
safeMode();
}
}
}
if (velocity > 32.8) {
digitalWrite(ignitionPin, LOW); // Power to ignition coil OFF.
lcd.clear();
lcd.setCursor(3, 0);
lcd.print("SAKTA NER!");
delay(1000);
lcd.clear();
}
lcd.setCursor(0, 0);
lcd.print(velocity, 1);
lcd.print(" km/h");
lcd.setCursor(0, 1);
lcd.print(wheelSensorPulsFrequency,2);
lcd.print(" Hz");
delay(600);
lcd.clear();
}
|
79467cd079c5e9b1c530c11f2dc7ab2415802d6c | 5156dc02e5b408437b696037151c22c27de8f062 | /qop.h | 248da064f19f45be35e4150d631fc9e9a5a2b824 | [
"MIT"
] | permissive | Qubit0-1/open-qubit | 055498fcca9443b81f4b50d64c3166fca7072d77 | dad4158411aab81f115e5d83b6c0f0d9cbe5a12b | refs/heads/master | 2021-01-16T20:43:17.619334 | 2012-05-02T02:07:32 | 2012-05-02T02:07:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,048 | h | qop.h | /* qop.h
Several quantum gates. (one bit and multi-controlled)
This file is part of the OpenQubit project.
Copyright (C) 1998-1999 OpenQubit.org
Yan Pritzker <yan@pritzker.ws>
Please see the CREDITS file for contributors.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
//! author="Rafal Podeszwa, Christopher Dawson, Peter Belkner, Yan Pritzker"
//! lib="Quantum Operators and Gates"
/*
OK, Here's an explanation of the mess you find below :)
There are two base classes: SingleBit and Controlled. They represent
one-bit gates and multi-controlled one-bit gates (multi-bit gates),
respectively.
Every operator is derived from these bases. In order
to enable any operator to be controlled and one-bit,
I implemented something I call 'templated inheritance'
which allow for example to specify a negation (NOT) like so:
typedef opNOT<SingleBit> Not;
In fact, you will find this declaration at the end of this
file. Its controlled counterpart is declared like so:
typedef opNOT<Controlled> CNot;
This syntax allows you to write an operator once and immediately
have a controlled counterpart for it.
Each operator also has a method called Param() which allows
you to re-specify the parameters for this gate. This allows
the reusal of a certain gate. Here's an example:
RotQubit Rx(PI/2); //gate which rotates qubit by PI/2
Rx(mystate,0); //rotate the first qubit by PI/2
Rx.Param(PI/3); //now it will perform PI/3 rotations
Rx(mystate,1); //the second bit is rotated by PI/3
Multi-controlled means that several bits can be used
as controlling bits. This also means that the controlling bit
argument to the controlled functions is going to be a mask, not just
the number of the bit.
e.g. if you wanted to CNot the third bit using bits 1 and 3 to control
the mask will be 101 == 5
the controlled bit is bit 2 (third bit):
CNot(myqstate, 5, 2);
Also found below is an interesting class called DoAllBits
for lack of a better name. This also is a templated class
taking as a type, any of the operators that are defined.
This class allows any operator to operate on all bits in
a state. So the Walsh-Hadamard operator is defined like:
typedef opHadamard<SingleBit> Hadamard;
typedef DoAllBits<Hadamard> WalshHadamard;
That's the only application I've found for it but i'm sure
there are more. It just saves time..you don't have to write
loops.
NOTE: FFT and SPhaseShift have been implemented separately
as their application algorithms don't conform to either
of the base classes.
--Yan Pritzker <yan@pritzker.ws>
WARNING: The following code may be strange, unusual, perhaps
even offensive. Coder discretion is strongly advised.
*/
#ifndef _QOP_H_
#define _QOP_H_
#include <math.h>
#include "utility.h"
#include "qstate.h"
class SingleBit
//: Base for one-bit gates.
{
public:
virtual void operator() (QState &q, int bit);
void SetMatrix(const Complex &a00, const Complex &a01,
const Complex &a10, const Complex &a11)
{ _a00 = a00; _a01 = a01; _a10 = a10; _a11 = a11; }
protected:
//: Constructor to create gate matrix (Identity by default)
SingleBit(const Complex &a00=1, const Complex &a01=0,
const Complex &a10=0, const Complex &a11=1)
{ SetMatrix(a00,a01,a10,a11); }
private:
Complex _a00, _a01, _a10, _a11;
};
class Controlled
//: Base for multi-bit (multi-controlled one bit) gates.
{
public:
//: Operator for application of gate to a QState.
virtual void operator() (QState &q, int mask, int bit);
//: This version allows bitmask to be specified in an array of int.
virtual void operator() (QState &q, int bits[], int bit)
{ unsigned long mask=CreateMask(bits);
operator()(q,mask,bit); }
//: Allows reusal of a defined gate by changing its matrix.
void SetMatrix(const Complex &a00, const Complex &a01,
const Complex &a10, const Complex &a11)
{ _a00 = a00; _a01 = a01; _a10 = a10; _a11 = a11; }
protected:
//: Constructor to create gate matrix (Identity Matrix by default)
Controlled(const Complex &a00=1, const Complex &a01=0,
const Complex &a10=0, const Complex &a11=1)
{ SetMatrix(a00,a01,a10,a11); }
private:
Complex _a00, _a01, _a10, _a11;
};
template <class BaseClassT>
class opUnitary : public BaseClassT
//: General Unitary operator.
{
public:
void Param(double alpha, double beta, double delta, double theta)
{
BaseClassT::SetMatrix
(Complex(cos(delta+alpha/2+beta/2)*cos(theta/2),
sin(delta+alpha/2+beta/2)*cos(theta/2)),
Complex(cos(delta+alpha/2-beta/2)*sin(theta/2),
sin(delta+alpha/2-beta/2)*sin(theta/2)),
Complex(-cos(delta-alpha/2+beta/2)*sin(theta/2),
-sin(delta-alpha/2+beta/2)*sin(theta/2)),
Complex(cos(delta-alpha/2-beta/2)*cos(theta/2),
sin(delta-alpha/2-beta/2)*cos(theta/2)));
}
opUnitary(double a=0, double b=0, double d=0, double t=0)
{ Param(a,b,d,t); }
};
template <class BaseClassT>
class opRotQubit : public BaseClassT
//: Rotation on y-axis
{
public:
//: Set the parameters needed for the gate to function.
void Param(double theta) {
BaseClassT::SetMatrix(
cos(theta/2), sin(theta/2),
-sin(theta/2), cos(theta/2)
);
}
opRotQubit(double theta=0) { Param(theta); }
};
template <class BaseClassT>
class opRotPhase : public BaseClassT
//: Rotation on z-axis
{
public:
void Param(double alpha) {
BaseClassT::SetMatrix(
Complex(cos(alpha/2), sin(alpha/2)), 0,
0, Complex(cos(alpha/2), -sin(alpha/2))
);
}
opRotPhase(double alpha=0) { Param(alpha); }
};
template <class BaseClassT>
class opPhaseShift : public BaseClassT
//: Scalar multiplication on z-axis
{
public:
Param(double delta) {
BaseClassT::SetMatrix(
Complex(cos(delta), sin(delta)),0,
0, Complex(cos(delta), sin(delta))
);
}
opPhaseShift(double delta=0) { Param(delta); }
};
template <class BaseClassT>
class opHadamard : public BaseClassT
//: Hadamard operator [|0> -> |0> + |1> and |1> -> |0> - |1>]
{
public:
opHadamard() : BaseClassT(M_SQRT1_2, M_SQRT1_2,
M_SQRT1_2, -M_SQRT1_2) {};
};
template <class BaseClassT>
class opNOT : public BaseClassT
//: SingleBit == Pauli negation, Controlled == CNot
{
public:
opNOT() : BaseClassT(0,1,1,0) {};
};
/*** Below are some gates that are different enough that they are implemented
without implementing from the base classes ***/
class opFFT
//: Fast Fourier Transform
{
public:
opFFT() {};
void operator() (QState &q, int numbits=-1);
};
class opSPhaseShift
//: Shor's phase shift operator (double-controlled phase shift);
{
// the matrix used for controlled single bit operation is
// (1 0 )
// (0 exp(i*Pi*delta/2^(k-j)) )
private:
//opPhaseShift<Controlled> CPS;
//opRotPhase<Controlled> Rz;
opUnitary<Controlled> CU;
public:
opSPhaseShift() {};
void operator() (QState &q, int j, int k)
{
assert(j < k); //see Shor's paper
double delta = M_PI/(1 << (k-j));
unsigned long mask;
mask = (1 << j);
//call general unitary controlled gate as suggested by Rafal
//instead of the four lines following. (works faster)
CU.Param(delta,0,-delta/2,0);
CU(q,mask,k);
//CPS.Param(-delta/2);
//CPS(q,mask,k);
//Rz.Param(delta);
//Rz(q,mask,k);
}
};
class ModExp
//: Modular Exponentiation
{
public:
ModExp() {};
void operator() (QState &q, int a, int n, int b) {
//results go here first
vector<Complex> _qArrayTmp(q.Outcomes());
for(int i = 0; i < q.Outcomes(); i++)
{
if (q[i] != 0)
_qArrayTmp[i + (modexp(a,i,n) << b)] = q[i];
}
for (int k = 0; k < q.Outcomes(); k++)
q[k] = _qArrayTmp[k]; //copy resulta
}
};
template <class OperatorType>
class DoAllBits
//: This class allows any operator to work on all bits of a state.
// This will only work for single bit operators requiring no parameters
// (i.e. this will not work with RotQubit which requires an angle theta)
{
private:
OperatorType op;
public:
void operator() (QState &q) {
for(int i=0; i < q.Qubits(); ++i)
op(q,i);
}
};
/* the controlled or single-bit counterparts of several of the functions
bellow are probably not needed but they are there just in case */
//: Unitary Operator
typedef opUnitary<SingleBit> Unitary;
//: Controlled Unitary Operator
typedef opUnitary<Controlled> CUnitary;
//: Qubit Rotation (Ry)
typedef opRotQubit<SingleBit> RotQubit;
//: Controlled Qubit Rotation (Ry)
typedef opRotQubit<Controlled> CRotQubit;
//: Phase Rotation (Rz)
typedef opRotPhase<SingleBit> RotPhase;
//: Controlled Phase Rotation
typedef opRotPhase<Controlled> CRotPhase;
//: Phase Shift (scalar multiplication of z axis)
typedef opPhaseShift<SingleBit> PhaseShift;
//: Controlled Phase Shift
typedef opPhaseShift<Controlled> CPhaseShift;
//: Shor Phase Shift
typedef opSPhaseShift SPhaseShift;
//: Hadamard Operator
typedef opHadamard<SingleBit> Hadamard;
//: Controlled Hadamard Operator
typedef opHadamard<Controlled> CHadamard;
//: Negation Operator
typedef opNOT<SingleBit> Not;
//: Controlled Negation (CNot - a.k.a XOR)
typedef opNOT<Controlled> CNot;
//: Fast Fourier Transform
typedef opFFT FFT;
//: Hadamard on all bits == WalshHadamard
typedef DoAllBits<Hadamard> WalshHadamard;
#endif
|
fb3b5d6e7818620c21e8d84a6712b768507dae4f | e51d009c6c6a1633c2c11ea4e89f289ea294ec7e | /xr2-dsgn/sources/xray/render/core/shader_defines.h | 8cc8feb0edbcd0559eda881b5efd9c095e13fb0e | [] | no_license | avmal0-Cor/xr2-dsgn | a0c726a4d54a2ac8147a36549bc79620fead0090 | 14e9203ee26be7a3cb5ca5da7056ecb53c558c72 | refs/heads/master | 2023-07-03T02:05:00.566892 | 2021-08-06T03:10:53 | 2021-08-06T03:10:53 | 389,939,196 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,677 | h | shader_defines.h | ////////////////////////////////////////////////////////////////////////////
// Created : 20.05.2010
// Author : Armen Abroyan
// Copyright (C) GSC Game World - 2010
////////////////////////////////////////////////////////////////////////////
#ifndef SHADER_DEFINES_H_INCLUDED
#define SHADER_DEFINES_H_INCLUDED
namespace xray {
namespace render {
enum enum_shader_type
{
enum_shader_type_vertex,
enum_shader_type_pixel,
enum_shader_type_geometry,
enum_shader_types_count // This is for determining supported shaders actual count
};
template < enum_shader_type shader_type > struct shader_type_traits
{
enum { value = false };
};
struct vs_data;
template < > struct shader_type_traits < enum_shader_type_vertex >
{
enum { value = true };
typedef ID3DVertexShader shader_hw_interface;
typedef vs_data shader_data;
static char const * name() { return "vertex shader"; }
static char const * short_name () { return "vs"; }
};
struct gs_data;
template < > struct shader_type_traits < enum_shader_type_geometry >
{
enum { value = true };
typedef gs_data shader_data;
typedef ID3DGeometryShader shader_hw_interface;
static char const * name() { return "geometry shader"; }
static char const * short_name() { return "gs"; }
};
struct ps_data;
template < > struct shader_type_traits < enum_shader_type_pixel >
{
enum { value = true };
typedef ps_data shader_data;
typedef ID3DPixelShader shader_hw_interface;
static char const * name() { return "pixel shader"; }
static char const * short_name() { return "ps"; }
};
} // namespace render
} // namespace xray
#endif // #ifndef SHADER_DEFINES_H_INCLUDED |
46459e8da01e60c4033796f42d89f97b468152a9 | 5ff791c9d373f4403905078fe8624940044b6e38 | /src/pol/undercover/gamelevel/ElevatorProperty.cpp | 11ef3c6c9cd146e4f36a21b6061ba5bdc69b19a0 | [] | no_license | rocking-around/PoL1.62.002 | 029eb63f341b9b88bc574ae430c7eaba9f943026 | 919abd5afa7eef92dc52d4e1d1e858b906cc577f | refs/heads/master | 2023-03-21T00:20:25.192498 | 2020-03-19T08:46:56 | 2020-03-19T08:46:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,799 | cpp | ElevatorProperty.cpp | #include "precomp.h"
#include "Grid.h"
#include "DynObject.h"
#include "ElevatorProperty.h"
#include <Logic2/HexUtils.h>
//=====================================================================================//
// ElevatorProperty::ElevatorProperty() //
//=====================================================================================//
ElevatorProperty::ElevatorProperty(DynObjectSet *s)
: UsableProperty(s)
{
UpdateHexGrid();
}
//=====================================================================================//
// ElevatorProperty::~ElevatorProperty() //
//=====================================================================================//
ElevatorProperty::~ElevatorProperty()
{
}
//=====================================================================================//
// float ElevatorProperty::SwitchState() //
//=====================================================================================//
float ElevatorProperty::SwitchState(float tau)
{
float ttime = 0.0f;
for(DynObjectSet::Iterator_t it = GetObjects()->Begin(); it != GetObjects()->End(); ++it)
{
ttime = std::max((*it)->ChangeState(tau),ttime);
}
return tau + ttime + 0.2f;
}
//=====================================================================================//
// float ElevatorProperty::SetState() //
//=====================================================================================//
float ElevatorProperty::SetState(float state, float tau)
{
float ttime = 0.0f;
for(DynObjectSet::Iterator_t it = GetObjects()->Begin(); it != GetObjects()->End(); ++it)
{
ttime = std::max((*it)->ChangeState(state,tau),ttime);
}
return tau + ttime + 0.2f;
}
//=====================================================================================//
// static void UpdateHexGrid() //
//=====================================================================================//
static void UpdateHexGrid(Grid *grid, const HexGrid::CellVec &vec,
const HexGrid::HFrontVec &frontvec, float z)
{
for(int i = 0; i < vec.size(); i++)
{
grid->Get(vec[i]).z=z;
}
HexGrid::HFrontVec::const_iterator it = frontvec.begin(), ite = frontvec.end();
for(; it != ite; ++it)
{
ipnt2_t np_f(HexUtils::scr2hex(*it->from));
ipnt2_t np_t(HexUtils::scr2hex(*it->to));
bool dh_f, dh_t;
dh_f = grid->GetProp(np_f).DynHeight;
dh_t = grid->GetProp(np_t).DynHeight;
if( (dh_f || UsableProperty::CanPass(np_f)) && (dh_t || UsableProperty::CanPass(np_t)) )
{
if(fabsf(it->from->z - it->to->z) > 0.6f)
{
it->from->SetWeight(it->dir, 100);
it->to->SetWeight(HexUtils::GetReverseDir(it->dir), 100);
}
else
{
it->from->SetWeight(it->dir, 0);
it->to->SetWeight(HexUtils::GetReverseDir(it->dir), 0);
}
}
}
}
//=====================================================================================//
// void ElevatorProperty::UpdateHexGrid() //
//=====================================================================================//
void ElevatorProperty::UpdateHexGrid()
{
Grid *grid = (Grid*)HexGrid::GetInst();
::UpdateHexGrid(
grid,
grid->HeightDirect[GetObjects()->GetName()],
grid->HeightFront[GetObjects()->GetName()],
(*GetObjects()->Begin())->GetWorldMatrix()._43
);
}
//=====================================================================================//
// void ElevatorProperty::Update() //
//=====================================================================================//
void ElevatorProperty::Update(float tau)
{
UpdateHexGrid();
}
//=====================================================================================//
// void ElevatorProperty::MakeLoad() //
//=====================================================================================//
void ElevatorProperty::MakeLoad(SavSlot &slot)
{
bool liftState;
slot >> liftState;
const float state = (liftState ? 1.0f : 0.0f);
for(DynObjectSet::Iterator_t it = GetObjects()->Begin(); it != GetObjects()->End(); ++it)
{
(*it)->ChangeState(state,0.0f);
}
}
//=====================================================================================//
// void ElevatorProperty::MakeSave() //
//=====================================================================================//
void ElevatorProperty::MakeSave(SavSlot &slot)
{
bool liftState = (*GetObjects()->Begin())->m_animState > 0.5f;
slot << liftState;
}
|
ae128576a6215c3779182655666f702158d0f39e | df7277d8f9d404a989ddea2467297fec1da80364 | /DlgFileOpenPreview.cpp | 158b12ab0a2b13734fe459d29c65097245bcda2f | [
"Unlicense"
] | permissive | 15831944/Painter | 6b68cd029d0937b0e04f650de24af70986376216 | ab57f5d022c8b4ce8f9713cd7533fc87e5fafa3b | refs/heads/master | 2023-07-15T12:17:46.353736 | 2021-08-28T13:49:14 | 2021-08-28T13:49:14 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 16,685 | cpp | DlgFileOpenPreview.cpp | #include "stdafx.h"
#include "Painter.h"
#include "DlgFileOpenPreview.h"
#include "Settings.h"
#include <String/Convert.h>
#include <String/Path.h>
#include <String/StringUtil.h>
#include <Grafik/ImageFormate/ImageFormatManager.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
extern CPainterApp theApp;
IMPLEMENT_DYNAMIC(CPainterFileOpen, CFileDialogEx)
CPainterFileOpen::CPainterFileOpen(BOOL bOpenFileDialog, LPCTSTR lpszDefExt, LPCTSTR lpszFileName,
DWORD dwFlags, LPCTSTR lpszFilter, CWnd* pParentWnd) :
CFileDialogEx(bOpenFileDialog, lpszDefExt, lpszFileName, dwFlags, lpszFilter, pParentWnd)
{
m_ofn.Flags |= OFN_ENABLETEMPLATE;
m_ofn.hInstance = AfxGetInstanceHandle();
m_ofn.lpTemplateName = MAKEINTRESOURCE( IDD_DIALOG_FILE_OPEN );
}
BEGIN_MESSAGE_MAP(CPainterFileOpen, CFileDialogEx)
//{{AFX_MSG_MAP(CPainterFileOpen)
ON_WM_DRAWITEM()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
void CPainterFileOpen::OnDestroy()
{
SafeDelete( pPreviewPage );
}
void CPainterFileOpen::GetPreview( const GR::Char* Temp )
{
GR::Font* pFont;
RECT rc;
int i,
j;
if ( pPreviewPage != NULL )
{
delete pPreviewPage;
pPreviewPage = NULL;
}
GR::String fileName = Temp;
GR::String fileExtension = GR::Strings::ToUpper( Path::Extension( fileName ) );
GR::Graphic::ImageData* pData = ImageFormatManager::Instance().LoadData( Temp );
if ( pData )
{
GR::Graphic::Image Image( *pData );
if ( Image.GetDepth() )
{
pPreviewPage = new GR::Graphic::GDIPage();
pPreviewPage->Create( GetSafeHwnd(), pData->Width(), pData->Height(), Image.GetDepth() );
if ( pData->Palette().Entries() )
{
pPreviewPage->SetPalette( &pData->Palette() );
}
else if ( pPreviewPage->GetDepth() <= 8 )
{
pPreviewPage->SetPalette( &theApp.m_PainterPalette );
}
Image.PutImage( pPreviewPage, 0, 0 );
}
Width = pData->Width();
Height = pData->Height();
BitDepth = pData->BitsProPixel();
FileType = OPEN_FILE::TYPE::EINZELBILD;
delete pData;
}
else if ( fileExtension == "FNX" )
{
// ein 8-bit-Font
GetDlgItem( IDC_STATIC_FILE_OPEN_PREVIEW )->GetClientRect( &rc );
pFont = new GR::Font();
pFont->LoadFNT( Temp, 8 );
pPreviewPage = new GR::Graphic::GDIPage();
pPreviewPage->Create( GetSafeHwnd(), rc.right - rc.left, rc.bottom - rc.top, 8 );
pPreviewPage->SetPalette( &theApp.m_PainterPalette );
pPreviewPage->Box( 0, 0, pPreviewPage->GetWidth() - 1, pPreviewPage->GetHeight() - 1, 0 );
pFont->PrintFont( pPreviewPage, 1, 1, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", IMAGE_METHOD_PLAIN, 0 );
pFont->PrintFont( pPreviewPage, 1, 1 + pFont->GetLetter( 65 )->GetHeight() + 2, "abcdefghijklmnopqrstuvwxyz", IMAGE_METHOD_PLAIN, 0 );
pFont->PrintFont( pPreviewPage, 1, 1 + 2 * pFont->GetLetter( 65 )->GetHeight() + 4, "0123456789", IMAGE_METHOD_PLAIN, 0 );
Width = pFont->GetLetter( 65 )->GetWidth();
Height = pFont->GetLetter( 65 )->GetHeight();
BitDepth = 8;
FileType = OPEN_FILE::TYPE::FONT;
delete pFont;
}
else if ( fileExtension == "FNH" )
{
// ein 16-bit-Font
GetDlgItem( IDC_STATIC_FILE_OPEN_PREVIEW )->GetClientRect( &rc );
pFont = new GR::Font();
pFont->LoadFNT( Temp, 16 );
pPreviewPage = new GR::Graphic::GDIPage();
pPreviewPage->Create( GetSafeHwnd(), rc.right - rc.left, rc.bottom - rc.top, 15 );
pPreviewPage->SetPalette( &theApp.m_PainterPalette );
pPreviewPage->Box( 0, 0, pPreviewPage->GetWidth() - 1, pPreviewPage->GetHeight() - 1, 0 );
pFont->PrintFont( pPreviewPage, 1, 1, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", IMAGE_METHOD_PLAIN, 0 );
pFont->PrintFont( pPreviewPage, 1, 1 + pFont->GetLetter( 65 )->GetHeight() + 2, "abcdefghijklmnopqrstuvwxyz", IMAGE_METHOD_PLAIN, 0 );
pFont->PrintFont( pPreviewPage, 1, 1 + 2 * pFont->GetLetter( 65 )->GetHeight() + 4, "0123456789", IMAGE_METHOD_PLAIN, 0 );
Width = pFont->GetLetter( 65 )->GetWidth();
Height = pFont->GetLetter( 65 )->GetHeight();
BitDepth = 16;
FileType = OPEN_FILE::TYPE::FONT;
delete pFont;
}
else if ( fileExtension == "FNL" )
{
// ein 24-bit-Font
GetDlgItem( IDC_STATIC_FILE_OPEN_PREVIEW )->GetClientRect( &rc );
pFont = new GR::Font();
pFont->LoadFNT( Temp, 24 );
pPreviewPage = new GR::Graphic::GDIPage();
pPreviewPage->Create( GetSafeHwnd(), rc.right - rc.left, rc.bottom - rc.top, 24 );
pPreviewPage->SetPalette( &theApp.m_PainterPalette );
pPreviewPage->Box( 0, 0, pPreviewPage->GetWidth() - 1, pPreviewPage->GetHeight() - 1, 0 );
pFont->PrintFont( pPreviewPage, 1, 1, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", IMAGE_METHOD_PLAIN, 0 );
pFont->PrintFont( pPreviewPage, 1, 1 + pFont->GetLetter( 65 )->GetHeight() + 2, "abcdefghijklmnopqrstuvwxyz", IMAGE_METHOD_PLAIN, 0 );
pFont->PrintFont( pPreviewPage, 1, 1 + 2 * pFont->GetLetter( 65 )->GetHeight() + 4, "0123456789", IMAGE_METHOD_PLAIN, 0 );
Width = pFont->GetLetter( 65 )->GetWidth();
Height = pFont->GetLetter( 65 )->GetHeight();
BitDepth = 24;
FileType = OPEN_FILE::TYPE::FONT;
delete pFont;
}
else if ( fileExtension == "PAL" )
{
GR::IO::FileStream* pFile;
unsigned char ucPalette[768];
// eine Palette
pPreviewPage = new GR::Graphic::GDIPage();
pPreviewPage->Create( GetSafeHwnd(), 160, 160, 16 );
pFile = new GR::IO::FileStream( Temp );
pFile->ReadBlock( ucPalette, 768 );
pFile->Close();
delete pFile;
for ( i = 0; i < 16; i++ )
{
for ( j = 0; j < 16; j++ )
{
pPreviewPage->Box( i * 10, j * 10, i * 10 + 9, j * 10 + 9,
pPreviewPage->GetRGB256( ( ucPalette[3 * ( i + j * 16 )] << 16 )
+ ( ucPalette[3 * ( i + j * 16 ) + 1] << 8 )
+ ( ucPalette[3 * ( i + j * 16 ) + 2] ) ) );
}
}
BitDepth = 8;
FileType = OPEN_FILE::TYPE::PALETTE;
}
else if ( fileExtension == "ACT" )
{
GR::IO::FileStream *pFile;
unsigned char ucPalette[768];
// eine Photoshop-Palette
pPreviewPage = new GR::Graphic::GDIPage();
pPreviewPage->Create( GetSafeHwnd(), 160, 160, 16 );
pFile = new GR::IO::FileStream( Temp );
pFile->ReadBlock( ucPalette, 768 );
pFile->Close();
delete pFile;
for ( i = 0; i < 16; i++ )
{
for ( j = 0; j < 16; j++ )
{
pPreviewPage->Box( i * 10, j * 10, i * 10 + 9, j * 10 + 9,
pPreviewPage->GetRGB256( ( ucPalette[3 * ( i + j * 16 )] << 16 )
+ ( ucPalette[3 * ( i + j * 16 ) + 1] << 8 )
+ ( ucPalette[3 * ( i + j * 16 ) + 2] ) ) );
}
}
BitDepth = 8;
FileType = OPEN_FILE::TYPE::PALETTE;
}
else if ( fileExtension == "IGF" )
{
// ein IGF
GR::IO::FileStream *pFile;
unsigned char ucType;
pFile = new GR::IO::FileStream( Temp );
if ( pFile->IsGood() )
{
ucType = pFile->ReadU8();
if ( ( ucType == GR::Graphic::IGFType::ANIMATION )
|| ( ucType == GR::Graphic::IGFType::ANIMATION_EXTENDED ) )
{
// Animation
GR::Animation animDummy = GR::Animation( Temp );
pPreviewPage = new GR::Graphic::GDIPage();
pPreviewPage->Create( GetSafeHwnd(), animDummy.GetWidth(), animDummy.GetHeight(), animDummy.GetFirstImage()->GetDepth() );
if ( animDummy.GetFirstImage()->GetDepth() <= 8 )
{
pPreviewPage->SetPalette( &theApp.m_PainterPalette );
}
animDummy.PutAnimation( pPreviewPage, 0, 0, IMAGE_METHOD_PLAIN );
Width = animDummy.GetWidth();
Height = animDummy.GetHeight();
BitDepth = animDummy.GetFirstImage()->GetDepth();
Frames = animDummy.GetFrames();
FileType = OPEN_FILE::TYPE::ANIMATION;
}
else if ( ucType == GR::Graphic::IGFType::PALETTE )
{
// eine Palette
unsigned char ucPalette[768];
pPreviewPage = new GR::Graphic::GDIPage();
pPreviewPage->Create( GetSafeHwnd(), 160, 160, 16 );
pFile->ReadU8();
pFile->ReadU32();
pFile->ReadBlock( ucPalette, 768 );
for ( i = 0; i < 16; i++ )
{
for ( j = 0; j < 16; j++ )
{
pPreviewPage->Box( i * 10, j * 10, i * 10 + 9, j * 10 + 9,
pPreviewPage->GetRGB256( ( ucPalette[3 * ( i + j * 16 )] << 16 )
+ ( ucPalette[3 * ( i + j * 16 ) + 1] << 8 )
+ ( ucPalette[3 * ( i + j * 16 ) + 2] ) ) );
}
}
BitDepth = 8;
FileType = OPEN_FILE::TYPE::PALETTE;
}
}
pFile->Close();
delete pFile;
}
GetDlgItem( IDC_STATIC_FILE_OPEN_PREVIEW )->InvalidateRect( NULL, FALSE );
}
BOOL CPainterFileOpen::OnInitDialog()
{
CFileDialogEx::OnInitDialog();
return TRUE;
}
void CPainterFileOpen::OnInitDone()
{
// Preview auf OWNER_DRAW setzen
GetDlgItem( IDC_STATIC_FILE_OPEN_PREVIEW )->ModifyStyle( 0, SS_OWNERDRAW );
// Preview enabled?
pPreviewPage = NULL;
if ( pSettings->GetSetting( "ShowLoadPreview" ) )
{
SendDlgItemMessage( IDC_CHECK_FILE_OPEN_PREVIEW, BM_SETCHECK, 1, 0 );
}
GetParent()->CenterWindow();
}
UINT_PTR CPainterFileOpen::HookProc( HWND hWnd, UINT uiMsg, WPARAM wParam, LPARAM lParam )
{
if ( uiMsg == WM_DRAWITEM )
{
OnDrawItem( (int)wParam, (DRAWITEMSTRUCT*)lParam );
return TRUE;
}
else if ( uiMsg == WM_COMMAND )
{
if ( (HWND)lParam == GetDlgItem( IDC_CHECK_FILE_OPEN_PREVIEW )->GetSafeHwnd() )
{
if ( SendDlgItemMessage( IDC_CHECK_FILE_OPEN_PREVIEW, BM_GETCHECK, 0, 0 ) )
{
pSettings->SetSetting( "ShowLoadPreview", 1 );
}
else
{
pSettings->SetSetting( "ShowLoadPreview", 0 );
}
if ( pSettings->GetSetting( "ShowLoadPreview" ) )
{
GR::WChar szTemp[MAX_PATH];
GetParent()->SendMessageW( CDM_GETFILEPATH, (WPARAM)MAX_PATH, (LPARAM)(LPTSTR)szTemp );
GetPreview( GR::Convert::ToUTF8( szTemp ).c_str() );
}
else
{
if ( pPreviewPage != NULL )
{
delete pPreviewPage;
pPreviewPage = NULL;
}
GetDlgItem( IDC_STATIC_FILE_OPEN_PREVIEW )->InvalidateRect( NULL, FALSE );
}
}
}
return CFileDialogEx::HookProc( hWnd, uiMsg, wParam, lParam );
}
void CPainterFileOpen::OnFileNameChange()
{
GR::WChar szTemp[MAX_PATH];
FileType = OPEN_FILE::TYPE::UNKNOWN;
Width = 0;
Height = 0;
BitDepth = 0;
Frames = 0;
GetParent()->SendMessageW( CDM_GETFILEPATH, (WPARAM)MAX_PATH, (LPARAM)(LPTSTR)szTemp );
GR::String fileName = GR::Convert::ToUTF8( szTemp );
if ( Path::Extension( fileName ).length() == 3 )
{
if ( pSettings->GetSetting( "ShowLoadPreview" ) )
{
GetPreview( fileName.c_str() );
}
}
if ( BitDepth == 15 )
{
BitDepth = 16;
}
if ( Width == 0 )
{
SendDlgItemMessage( IDC_STATIC_FILE_OPEN_WIDTH, WM_SETTEXT, 0, (LPARAM)_T( "unbekannt" ) );
}
else
{
SendDlgItemMessage( IDC_STATIC_FILE_OPEN_WIDTH, WM_SETTEXT, 0, (LPARAM)GR::Convert::ToUTF16( CMisc::printf( "%d", Width ) ).c_str() );
}
if ( Height == 0 )
{
SendDlgItemMessage( IDC_STATIC_FILE_OPEN_HEIGHT, WM_SETTEXT, 0, (LPARAM)_T( "unbekannt" ) );
}
else
{
SendDlgItemMessage( IDC_STATIC_FILE_OPEN_HEIGHT, WM_SETTEXT, 0, (LPARAM)GR::Convert::ToUTF16( CMisc::printf( "%d", Height ) ).c_str() );
}
if ( BitDepth == 0 )
{
SendDlgItemMessage( IDC_STATIC_FILE_OPEN_DEPTH, WM_SETTEXT, 0, (LPARAM)_T( "unbekannt" ) );
}
else
{
SendDlgItemMessage( IDC_STATIC_FILE_OPEN_DEPTH, WM_SETTEXT, 0, (LPARAM)GR::Convert::ToUTF16( CMisc::printf( "%d", BitDepth ) ).c_str() );
}
if ( Frames == 0 )
{
SendDlgItemMessage( IDC_STATIC_FILE_OPEN_FRAMES, WM_SETTEXT, 0, (LPARAM)_T( "n.v." ) );
}
else
{
SendDlgItemMessage( IDC_STATIC_FILE_OPEN_FRAMES, WM_SETTEXT, 0, (LPARAM)GR::Convert::ToUTF16( CMisc::printf( "%d", Frames ) ).c_str() );
}
if ( FileType == OPEN_FILE::TYPE::UNKNOWN )
{
SendDlgItemMessage( IDC_STATIC_FILE_OPEN_TYPE, WM_SETTEXT, 0, (LPARAM)_T( "unbekannt" ) );
}
else if ( FileType == OPEN_FILE::TYPE::EINZELBILD )
{
SendDlgItemMessage( IDC_STATIC_FILE_OPEN_TYPE, WM_SETTEXT, 0, (LPARAM)_T( "Einzelbild" ) );
}
else if ( FileType == OPEN_FILE::TYPE::FONT )
{
SendDlgItemMessage( IDC_STATIC_FILE_OPEN_TYPE, WM_SETTEXT, 0, (LPARAM)_T( "Font" ) );
}
else if ( FileType == OPEN_FILE::TYPE::ANIMATION )
{
SendDlgItemMessage( IDC_STATIC_FILE_OPEN_TYPE, WM_SETTEXT, 0, (LPARAM)_T( "Animation" ) );
}
else if ( FileType == OPEN_FILE::TYPE::PALETTE )
{
SendDlgItemMessage( IDC_STATIC_FILE_OPEN_TYPE, WM_SETTEXT, 0, (LPARAM)_T( "Palette" ) );
}
}
void CPainterFileOpen::OnFolderChange()
{
}
void CPainterFileOpen::OnDrawItem( int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct )
{
if ( lpDrawItemStruct->hwndItem == GetDlgItem( IDC_STATIC_FILE_OPEN_PREVIEW )->GetSafeHwnd() )
{
HPEN hPen,
hOldPen;
HBRUSH hBrush;
if ( pPreviewPage != NULL )
{
hBrush = CreateSolidBrush( RGB( 255, 255, 255 ) );
hPen = CreatePen( PS_SOLID, 1, 0 );
hOldPen = (HPEN)SelectObject( lpDrawItemStruct->hDC, hPen );
Rectangle( lpDrawItemStruct->hDC,
lpDrawItemStruct->rcItem.left,
lpDrawItemStruct->rcItem.top,
lpDrawItemStruct->rcItem.right,
lpDrawItemStruct->rcItem.bottom );
SelectObject( lpDrawItemStruct->hDC, hOldPen );
DeleteObject( hPen );
DeleteObject( hBrush );
// Größenverhältnis beibehalten!
int width = lpDrawItemStruct->rcItem.right - lpDrawItemStruct->rcItem.left,
height = lpDrawItemStruct->rcItem.bottom - lpDrawItemStruct->rcItem.top,
xOffset,
yOffset;
float faktorW,
faktorH,
zoomFactor;
faktorW = (float)pPreviewPage->GetWidth() / (float)width;
faktorH = (float)pPreviewPage->GetHeight() / (float)height;
if ( faktorW > faktorH )
{
zoomFactor = faktorW;
}
else
{
zoomFactor = faktorH;
}
width = (int)( (float)pPreviewPage->GetWidth() / zoomFactor );
height = (int)( (float)pPreviewPage->GetHeight() / zoomFactor );
xOffset = ( lpDrawItemStruct->rcItem.right - lpDrawItemStruct->rcItem.left - width ) / 2;
yOffset = ( lpDrawItemStruct->rcItem.bottom - lpDrawItemStruct->rcItem.top - height ) / 2;
hBrush = CreateSolidBrush( 0 );
// Stauch-Bild
SetStretchBltMode( lpDrawItemStruct->hDC, COLORONCOLOR );
StretchBlt( lpDrawItemStruct->hDC, xOffset, yOffset,
width,
height,
pPreviewPage->GetDC(), 0, 0,
pPreviewPage->GetWidth(), pPreviewPage->GetHeight(),
SRCCOPY );
// schwarzer Rahmen drumrum
hPen = CreatePen( PS_SOLID, 1, 0 );
hOldPen = (HPEN)SelectObject( lpDrawItemStruct->hDC, hPen );
FrameRect( lpDrawItemStruct->hDC,
&lpDrawItemStruct->rcItem,
hBrush );
SelectObject( lpDrawItemStruct->hDC, hOldPen );
DeleteObject( hPen );
DeleteObject( hBrush );
}
else
{
hBrush = CreateSolidBrush( RGB( 255, 255, 255 ) );
hPen = CreatePen( PS_SOLID, 1, 0 );
hOldPen = (HPEN)SelectObject( lpDrawItemStruct->hDC, hPen );
Rectangle( lpDrawItemStruct->hDC,
lpDrawItemStruct->rcItem.left,
lpDrawItemStruct->rcItem.top,
lpDrawItemStruct->rcItem.right,
lpDrawItemStruct->rcItem.bottom );
SelectObject( lpDrawItemStruct->hDC, hOldPen );
DeleteObject( hPen );
DeleteObject( hBrush );
}
}
CFileDialogEx::OnDrawItem( nIDCtl, lpDrawItemStruct );
}
|
ed736362bdde2c76a33672fabe58b4fb5bf42459 | c718f934cb398fde1a5d1709589fc98a03d5481b | /codeForces/#01144_pC_Two Shuffled Sequences.cpp | ea2cf7cf434b063d48915630bd6f19180ad67080 | [] | no_license | casperwang/OJproblems | 18ec0246c76bc7e34ed89599c023ae290cc30620 | 3920be1c7d2861624ac6a6afec843b164d9e5948 | refs/heads/master | 2020-04-07T04:27:44.429425 | 2020-03-04T07:18:35 | 2020-03-04T07:18:35 | 158,057,469 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 785 | cpp | #01144_pC_Two Shuffled Sequences.cpp | #include <bits/stdc++.h>
#define MAXN 200000
using namespace std;
int n;
int num[MAXN+5], appr[MAXN+5];
vector <int> inc, de;
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
cin >> num[i];
appr[num[i]]++;
if (appr[num[i]] > 2) {
cout << "NO" << endl;
return 0;
}
}
sort(num, num+n);
cout << "YES" << endl;
for (int i = 0; i < n; i += appr[num[i]]) {
inc.push_back(num[i]);
}
for (int i = n-1; i >= 0; i--) {
if (appr[num[i]] == 2) {
de.push_back(num[i]);
appr[num[i]]--;
}
}
cout << inc.size() << endl;
for (int i = 0; i < inc.size(); i++) {
cout << inc[i] << " ";
}
cout << endl;
cout << de.size() << endl;
for (int i = 0; i < de.size(); i++) {
cout << de[i] << " ";
}
return 0;
}
|
962a2dbbdd883811c52fb4cc61cc164e419d8368 | b7d21c6a1c52122ccc4beeacc9c31f99214692bb | /cs161/labs/lab7/lab7.cpp | e609eff3b6f35a31fb8522ef0b6c271849d2de1f | [] | no_license | lilesme/CS161-Intro-to-CS-I | 0f02063ca17dcefbfbbdc8b2700139d40ea6ae2d | 46b1e83b7fc63847eaa9b1605b0340fdb9618752 | refs/heads/master | 2020-12-24T01:11:03.812950 | 2020-03-11T01:17:25 | 2020-03-11T01:17:25 | 237,332,581 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 397 | cpp | lab7.cpp | #include <iostream>
#include <string.h>
using namespace std;
void create_mem(char **array){
int max_chars;
cout<<"How many characters would you like? "<<endl;
cin>> max_chars;
max_chars + max_chars + 1;
*array = new char [max_chars];
}
void delete_mem(char **array){
delete [] *array;
}
int main(){
char *what;
create_mem(&what);
delete_mem(&what);
return 0;
}
|
a94d6c1e3d6bf8a070830de519ea6c40c0c5ecf6 | 0c96b78faf7c3a66e5e58ae20fa6fca82c45e76a | /audio_ofdm_offline/SyncBlock.h | e4497445642b70d114547e37f28c8bfc61a200f1 | [] | no_license | JHillard/OFDM-Audio-modem | 54a15aef2c2ed28a57d734ee40f06494dc02042c | b7f7dc47d8db0d39fb0f55f0bf27ce15810121e0 | refs/heads/master | 2020-05-25T11:29:49.330243 | 2017-03-15T22:15:07 | 2017-03-15T22:15:07 | 83,589,266 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,767 | h | SyncBlock.h |
/** \file syncBlock.h
Library for data buffer synchronization. Once the data is stored,
this library handles all the correlations, mean calculations, etc to perform
the synchronization.
*/
//
// SyncBlock.h
//
//
// Created by Terry Kong on 1/30/16.
//
//
#ifndef SyncBlock_H
#define SyncBlock_H
#include "dsplib.h"
#include "stdlib.h"
// Helpful Definitions
#define FIXED_FBITS 15
#define WORD_LENGTH 16
#define MAX_BUFFER_SIZE 2048
#define MAX_INT32 2147483647u
namespace SyncBlock {
/** \brief
Use long long to multiply to simulate MAC behavior
*/
static long long FIXED_MUL(int a, int b) {
return ((long long)a*(long long)b);
}
/** \brief
Use long long and simulate round-off. Typically used after the MAC operation simulated by FIXED_MUL.
*/
static int FIXED_RND(long long a) {
return ((a + (long long) (1 << (FIXED_FBITS - 1))) >> FIXED_FBITS);
}
/** \brief
returns the mean of the input array data. Requires length of data and pointer to data as input.
*/
int mean(const int* data, int length) {
long long result = 0;
for (int i = 0; i < length; i++) {
result += data[i];
}
result /= length;
return result;
}
/** \brief
Demeans an array of data. Requires length of data and pointer to data as input.
*/
void subtractMean(int* data, int length) {
int m = mean(data,length);
for (int i = 0; i < length; i++) {
data[i] -= m;
}
}
/** \brief
Performs the correlation between input data and known syncSymbol.
Variable dataLength should be even.
Requires pointer to data, pointer to syncSymbol, pointer to output of correlation.
Also requires the integers outputLen, syncSymLen. They are used in the manner their name suggests.
*/
ushort xcorr(const int* data, int* syncSymbol, int* output, int outputLen, int syncSymLen) {
return convol1((DATA *)data, (DATA *)syncSymbol, (DATA *)output, outputLen, syncSymLen);
return 0;
};
/** \brief
Linear search for maximum
*/
void absMax(const int* array, int length, int &maxValue, int &maxIndex) {
// If length is less than 1, do nothing (return)
if(length<1) return;
int mx = array[0];
int mi = 0;
for( int i=0; i<length; i++){
int t =array[i];
if ( t>mx){
mx = t;
mi = i;
}
}
maxValue = (array[mi]);
maxIndex = mi;
};
/** \brief
Linear search for maximum
*/
void absMax(const int* array, int length, int &maxValue) {
int maxIndex;
absMax(array,length,maxValue, maxIndex);
};
/** \brief
Takes the correlation of an input data and the sync symbol, and stores the max value and index of the correlation in maxValue and maxIndex.
Requires input data pointer, length of input pointer, the syncSymbol, length of the syncSymbol, as well as pointers to the output of the correlation. The addresses of maxValue and maxIndex are also required.
*/
void xcorrMax(int* data, int* syncSymbol, int* output, int outputLen, int syncSymLen,int dataLength, int &maxValue, int &maxIndex) {
xcorr(data,syncSymbol,output,outputLen,syncSymLen);
absMax(output,outputLen,maxValue,maxIndex);
};
/** \brief
Calculates the energy of a signal stored in array a. Requires length.
Total energy calculated via the sum from 0 to length-1 of a[n]^2.
*/
int calculateEnergy(const int* a, int length) {
//Energy = sum(n=0:Length, a[n]^2 )
int energy = 0;
for( int n=0; n<length; n++){
energy = energy + FIXED_RND(FIXED_MUL(a[n],a[n]) );
}
return energy;
}
};
#endif /* SyncBlock_H */
|
dcf6f0834491330bfa0f7cdf0860be860fdb5dab | 4afa786d4db262639515bf1081c75e3ba154f489 | /main.cc | 2ba6d2b549a34c990dc8e064ac2b4f470cccd542 | [] | no_license | melbachiri/NormalGen_Project | b1472cc89ff15f3f0932d93870fbfb66acda6341 | 1a621b05064a65f7371c6f5888095a859b5ed36b | refs/heads/master | 2020-06-03T06:23:30.898847 | 2013-07-20T16:38:17 | 2013-07-20T16:38:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 127 | cc | main.cc | #include <iostream>
#include "Gauss.h"
using namespace std;
int main(void){
Gauss G;
cout << G() << endl;
return 0;
}
|
52988560a553948896876dc93048a602750d33a5 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/CMake/CMake-gumtree/Kitware_CMake_repos_basic_block_block_5605.cpp | 4ca60fdcb948a8d2124964b579e1d37a6459ca6b | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 229 | cpp | Kitware_CMake_repos_basic_block_block_5605.cpp | f(compare(i, t->larger->key) > 0) {
y = t->larger; /* rotate larger */
t->larger = y->smaller;
y->smaller = t;
t = y;
if(t->larger == NULL)
break;
} |
f60a54dc12ba3db032f398656721ca15cc6cd86c | 337c5e89cbe73daa60dd6b9c0d7b1ef816b655a0 | /main.cpp | 5e48bef2209902332231d198c14c89d45b367533 | [] | no_license | ctoale/C-Balanced-BST | dd4eeb97a533d80320c4fd86ebe0f8d1ecc41c6d | bea9489e14321948e859a208a6d306e57512c5b7 | refs/heads/master | 2020-03-30T13:59:51.912125 | 2018-10-02T17:39:01 | 2018-10-02T17:39:01 | 151,296,490 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,163 | cpp | main.cpp | #include <iostream>
using namespace std;
struct BSTreeNode
{
int data;
struct BSTreeNode* left;
struct BSTreeNode* right;
};
struct BSTreeNode* newBSTreeNode(int data);
struct BSTreeNode* BalanceTreeArray(int Array[], int start, int end)
{
if (start > end)
return NULL;
int mid = (start + end)/2;
struct BSTreeNode *root = newBSTreeNode(Array[mid]);
root->left = BalanceTreeArray(Array, start, mid-1);
root->right = BalanceTreeArray(Array, mid+1, end);
return root;
}
void PO(struct BSTreeNode* node){
if (node == NULL)
return;
cout<<node->data<<" ";
PO(node->left);
PO(node->right);
}
struct BSTreeNode* newBSTreeNode(int data){
struct BSTreeNode* node = new BSTreeNode;
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
int main(){
int Array[50];
int n;
cout<<"This program will produce a balanced binary search tree, given a sorted list of elements. \n";
cout<<"\nEnter the number of elements: ";
cin>>n;
cout<<"Enter sorted list of elements: ";
for(int i=0;i<n;i++)
{
cin>>Array[i];
}
struct BSTreeNode *root = BalanceTreeArray(Array, 0, n-1);
cout<<"\nThe balanced binary search tree is: \n";
PO(root);
cout<<endl;
return 0;
} |
4ce169e2a4fc1b0827e6dcd98817264ebfff78fb | b742fe938a6c0d737c332b0b0c0dfa944a7238f0 | /esp8266_01/demo_01.h | 0825fafbebcdfac0ef50ed60465f1e021b76d6ed | [] | no_license | cclehui/study_arduino | f112e31fc58f77c2073065673c558ac87b08a90d | a2e0e54c1bb2acd263e7bc3bd7504be67fee2148 | refs/heads/master | 2020-12-28T17:31:17.377930 | 2020-10-09T13:54:01 | 2020-10-09T13:54:01 | 238,422,241 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,478 | h | demo_01.h | #ifndef DEMO_01_h
#define DEMO_01_h
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
char *wifiName = "cclhui";
char *password = "Wn1989318";
char *mqttServer = "118.24.111.175";
int mqttServerPort = 1883;
WiFiClient espClient; //wifi 实例
PubSubClient mqttClient(espClient);
ESP8266WiFiMulti WiFiMulti;
//链接wifi 显示ip
void connectWifi() {
delay(5000);
Serial.println();
Serial.print("Connecting to ");
Serial.println(wifiName);
WiFi.mode(WIFI_STA);
WiFi.begin(wifiName, password);
Serial.print("Connecting");
int tryNum = 0;
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print("tryNum_x:");
Serial.println(tryNum);
tryNum++;
}
Serial.println();
Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP());
}
//http
void connectWifiForHttp() {
for (uint8_t t = 4; t > 0; t--) {
Serial.printf("[SETUP] WAIT %d...\n", t);
Serial.flush();
delay(1000);
}
WiFi.mode(WIFI_STA);
WiFiMulti.addAP(wifiName, password);
Serial.print("Connecting");
int tryNum = 0;
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print("tryNum_x:");
Serial.println(tryNum);
tryNum++;
}
Serial.println();
Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP());
}
#endif |
fe52a1acc18c0bfb6112fe943f7c46710a4316bb | c08a26d662bd1df1b2beaa36a36d0e9fecc1ebac | /lafagnosticuifoundation/cone/tef/TCone4StepExe.h | 8fa114d3e17744ff85a2873210d84bba94de307b | [] | no_license | SymbianSource/oss.FCL.sf.mw.classicui | 9c2e2c31023256126bb2e502e49225d5c58017fe | dcea899751dfa099dcca7a5508cf32eab64afa7a | refs/heads/master | 2021-01-11T02:38:59.198728 | 2010-10-08T14:24:02 | 2010-10-08T14:24:02 | 70,943,916 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 893 | h | TCone4StepExe.h | // Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
// All rights reserved.
// This component and the accompanying materials are made available
// under the terms of "Eclipse Public License v1.0"
// which accompanies this distribution, and is available
// at the URL "http://www.eclipse.org/legal/epl-v10.html".
//
// Initial Contributors:
// Nokia Corporation - initial contribution.
//
// Contributors:
//
// Description:
//
/**
@file
@internalComponent
*/
#if !defined(__TCONE4STEPEXE_H__)
#define __TCONE4STEPEXE_H__
#include "appfwk_test_AppUi.h"
//! Test Step Name.\n
_LIT(KTCone4StepExe, "TCone4Exe");
//! A CTestStep Derived Class.\n
/**
Incorporate tests on TConeTestExe.\n
*/
class CTCone4StepExe : public CTmsTestStep
{
public:
CTCone4StepExe();
~CTCone4StepExe();
virtual TVerdict doTestStepL();
void ConstructAppL(CCoeEnv* aCoe);
};
#endif
|
2c0e774d31e1af477504dba667e21e2ce4b0246b | 72743fe4eea2fd273905d8cbc9050e60122ab39d | /GumballCore/Engine.cpp | 8ba77385a35c60b4284693e5ede58e6f9b6884dd | [] | no_license | JosiasWerly/Gumball | a8b94c0feec31c9fe379741a585dbc7deb3cf81b | 5560e96724314a662405b5efc30268403b32e7f2 | refs/heads/master | 2023-08-06T03:20:47.905183 | 2023-07-25T19:25:13 | 2023-07-25T19:25:13 | 233,352,674 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,858 | cpp | Engine.cpp | #include "Engine.hpp"
#include "Subsystem.hpp"
#include "AssetManager.hpp"
#include "RenderSystem.hpp"
#include "SceneOverlay.hpp"
#include "WidgetOverlay.hpp"
#include "ProjectLinker.hpp"
#include "ConsoleSystem.hpp"
#include "World.hpp"
#include "EnviromentVariables.hpp"
#include "Subsystem.hpp"
#include <iostream>
#include <string>
using namespace std;
Engine::Engine() {
projectLinker = new ProjectLinker;
systemSeer = new SystemOverseer;
renderSystem = systemSeer->addSystem<RenderSystem>();
assetSystem = systemSeer->addSystem<AssetsSystem>();
inputSystem = systemSeer->addSystem<InputSystem>();
consoleSystem = systemSeer->addSystem<ConsoleSystem>();
world = systemSeer->addSystem<World>();
}
Engine::~Engine() {
}
void Engine::args(int argc, char *argv[]) {
auto e = Enviroment::setInstance(new Enviroment);
e->applicationPath = argv[0];
e->applicationDir = e->applicationPath.substr(0, e->applicationPath.find_last_of("\\")) + "\\";
e->resourcePath = e->applicationDir + "\\res\\";
e->contentPath = e->applicationDir + "\\content\\";
}
void Engine::tick() {
systemSeer->initialize();
systemSeer->lateInitialize();
while (true) {
if (projectLinker->hasNewVersion() || consoleSystem->isReload) {
systemSeer->endPlay();
projectLinker->unload();
if (projectLinker->load()) {
systemSeer->beginPlay();
}
consoleSystem->isReload = false;
}
timeStats.capture();
const double &deltaTime = timeStats.getDeltaTime();
if (consoleSystem->isPlay) {
systemSeer->tick<ESystemTickType::gameplay>(deltaTime);
renderSystem->mainWindow.setTitle(to_string(timeStats.getFPS()));
}
else {
systemSeer->tick<ESystemTickType::editor>(deltaTime);
}
}
systemSeer->endPlay();
systemSeer->shutdown();
}
//systemSeer->initialize();
//systemSeer->lateInitialize();
//auto widget = dynamic_cast<WidgetOverlay*>(renderSystem->getLayer("widget"));
//auto scene = dynamic_cast<SceneOverlay *>(renderSystem->getLayer("scene"));
///// crappy way of controlling the play and stop button
//bool isPlaying = false;
//UI::Canvas win;
//UI::Text txt;
//UI::Button bt;
//bt.text = ">";
//(*widget) << &win;
//win << &txt << &bt;
////////////////////////////////////////////////////////////////////
//while (true) {
// hotReload();
//
// timeStats.capture();
// const double& deltaTime = timeStats.getDeltaTime();
//
// if (isPlaying) {
// systemSeer->tick<ESystemTickType::gameplay>(deltaTime);
// renderSystem->mainWindow.setTitle(to_string(timeStats.getFPS()));
// }
// else
// systemSeer->tick<ESystemTickType::editor>(deltaTime);
// if (bt.isClicked()) {
// if (isPlaying) {
// isPlaying = false;
// systemSeer->endPlay();
// bt.text = ">";
// }
// else {
// isPlaying = true;
// systemSeer->beginPlay();
// bt.text = "||";
// }
// }
//}
//systemSeer->endPlay();
//systemSeer->shutdown(); |
70b167fac5d540a5e3701b3946852ae1e803ca53 | 8feb7e19a9ab2ea535b1b6347bdbe48d619d94cb | /ConsoleApplication12_7/ConsoleApplication12_7/main.cpp | 773b52a76aa9f40a7ec1651303f1a23821b57b29 | [] | no_license | SmileHurry/cplusplus-primer-plus-6th- | 3426de7aed1de8a94d48c468e1a79fe95b6ed9b6 | 892c907a5c3b93631a219a28880525fe8ff10f12 | refs/heads/master | 2021-01-10T15:42:03.637199 | 2016-04-08T06:24:46 | 2016-04-08T06:24:46 | 55,745,488 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 264 | cpp | main.cpp | #include<iostream>
#include"plorg.h"
int main()
{
using namespace std;
plorg p1;
p1.show();
p1.reset_CI(10);
p1.show();
cout << "---------------------------\n";
plorg p2("zhangqi", 30);
p2.show();
p2.reset_CI(20);
p2.show();
return 0;
} |
58b8610a309abcb2bdcdeb2334d912dc22ef5a8a | ae1f0aa96ff55cbe77d0049fe6c32f545e6baaea | /GameProject/Engine/Components/Camera.h | 3e5aaa40653ef63b349c5b66c2cd7425f5284421 | [] | no_license | jonathan2222/GameProject | ece9d03db63cb353b062698887f4318847f41796 | 6c502a475efb4c3a59e1710ba5f3596c3ea1bb32 | refs/heads/master | 2020-04-21T18:34:34.156156 | 2019-02-11T00:10:25 | 2019-02-11T00:10:25 | 169,775,052 | 0 | 0 | null | 2019-02-08T17:46:20 | 2019-02-08T17:46:19 | null | UTF-8 | C++ | false | false | 1,288 | h | Camera.h | #pragma once
#include "glm/glm.hpp"
#include "../Config.h"
#include "Component.h"
#include "../Rendering/Display.h"
#include "../Events/EventBus.h"
class Camera : public Component
{
public:
Camera(Entity * parentEntity, const std::string& tagName = "Camera", const glm::vec3& offset = glm::vec3(0.0f, 0.0f, 0.0f));
virtual ~Camera();
void init();
// Update called by entity
void update(const float& dt);
// Returns the cameras up-vector
glm::vec3 getUp() const;
// Returns the cameras forward-vector
glm::vec3 getForward() const;
// Returns the cameras right-vector
glm::vec3 getRight() const;
// Returns the View-Projection matrix
glm::mat4 getVP() const;
// Returns the View matrix
glm::mat4 getView() const;
// Returns the Projection matrix
glm::mat4 getProj() const;
float getFOV() const;
void setFOV(const float FOV);
glm::vec3 getOffset() const;
void setOffset(const glm::vec3& offset);
private:
glm::vec3 f, u, r, offset, pos;
glm::mat4 view, proj;
float fov, zNear, zFar;
void updateView();
void updateProj(WindowResizeEvent * evnt);
// Set the forward-vector and in the process the right and up vector aswell
void setForward(const glm::vec3 & forward);
// Update camera's position relative to the parent entity
void updatePosition();
};
|
1db9cc5f13a796f46ee2a37682fcddcd92b4f149 | 041f35bf29af5e3141f7760f306e083861b0013d | /Source/System/auth/Unix/big_num.cpp | bce1902fcd601b4b161c24baf53f6ad6f4a7fa52 | [
"MIT"
] | permissive | UnforeseenOcean/xbox-live-api | 96ddb95291402ae19f797327c89c823dda697e34 | 17c586336e11f0fa3a2a3f3acd665b18c5487b24 | refs/heads/master | 2020-04-07T04:36:37.454667 | 2017-02-15T00:32:22 | 2017-02-15T00:32:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,116 | cpp | big_num.cpp | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#include "pch.h"
#include "big_num.h"
#include <vector>
NAMESPACE_MICROSOFT_XBOX_SERVICES_SYSTEM_CPP_BEGIN
big_num::big_num()
{
BN_init(&m_bn);
}
big_num::~big_num()
{
BN_free(&m_bn);
}
BIGNUM&
big_num::bn()
{
return m_bn;
}
std::vector<unsigned char>
big_num::get_bytes() const
{
int len = BN_num_bytes(&m_bn);
return get_bytes(len);
}
std::vector<unsigned char>
big_num::get_bytes(int bufferSize) const
{
int len = BN_num_bytes(&m_bn);
if (len > bufferSize) throw std::invalid_argument("bufferSize is not large enough");
std::vector<unsigned char> bytes(bufferSize);
BN_bn2bin(&m_bn, bytes.data() + bufferSize - len);
return bytes;
}
NAMESPACE_MICROSOFT_XBOX_SERVICES_SYSTEM_CPP_END |
ba5ddf8dda593bfd4a2aae490d4dfbd621f1c6ad | da3642f21450f2920bdd4306981898622f11dea8 | /CPlusPlus/YouYuanHanShuLei/YouYuanHanShuLei/X.hpp | 1408573232d4a9bd73e0330be7353e4b513ee6d0 | [] | no_license | yananyun/CPlusPlus2 | af82bc67fe690a0525ba2812b5f41a3b7a472047 | bbb966a782d8923578a7608f9bfe65f5c8ceb7cb | refs/heads/master | 2021-06-06T17:31:36.192598 | 2016-10-17T09:40:40 | 2016-10-17T09:40:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 720 | hpp | X.hpp | //
// X.hpp
// YouYuanHanShuLei
//
// Created by Li on 2016/10/17.
// Copyright © 2016年 bjcric. All rights reserved.
//
#ifndef X_hpp
#define X_hpp
#include <stdio.h>
class X;
//类的前置声明 如果这里使用类的前置声明 后面使用该类时 必须使用指针操作
class Y{
public:
void f(X*);
//void b(X);
private:
X* pX;
};
class X{
public:
void initialize();
friend void g(X*,int);//g是X的友元函数
friend void Y::f(X*);//Y的成员函数f也是X的友元函数
friend class Z;//Z是X的友元类
friend void h();
private:
int i;
};
class Z{
public:
void initialize();
void g(X* x);
private:
int j;
};
#endif /* X_hpp */
|
6c2d18b820038505bdc225291df71c937e379346 | b382213782edd07c7c82bbf89c9e696fd184355a | /src/TWAPAlgorithm.cpp | ae42930dab2467440f80c2d2e186d33e32de3b07 | [] | no_license | rohantalkad747/electronic-execution-algos | 1f8ef166e8237f7b5b9ae4062920df717dd16962 | a692105362b0efd13a39ca9b454445a10acd29ce | refs/heads/master | 2023-02-17T09:00:49.009540 | 2021-01-17T05:23:08 | 2021-01-17T05:23:08 | 253,161,037 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 711 | cpp | TWAPAlgorithm.cpp | //
// Created by Rohan on 4/25/2020.
//
#include "../include/TWAPAlgorithm.h"
#include "../include/TWAPConfig.h"
double TWAPAlgorithm::getPrice()
{
double numerator = 0.0;
auto *twapConfig = static_cast<TWAPConfig *>(this->algoConfig);
long intervalStart = TimeUtils::getSecondsSinceMidnight();
long tillIntervalEnd = intervalStart + twapConfig->getInterval();
std::vector<double> histPrice = twapConfig->getHistPrice();
for (int i = intervalStart; i < tillIntervalEnd; i++)
{
numerator += histPrice[i];
}
return numerator / (tillIntervalEnd - intervalStart);
}
|
2691992c85108fa85896b177a9230e34b6f74973 | d7b565343df2eab0da7b74bc47a0cab9355a4c38 | /price-oracle/price_update.cpp | ec15a54658e2e4db86bf52b636bfbc167fa26278 | [] | no_license | chesterkuo/EOS | 1ba2e490f4895130dfde412e42d62949fe1b5bdc | 19be4ba0f05f24cbcd02edd71dd9216b14d8752f | refs/heads/master | 2020-03-28T14:38:47.185721 | 2018-12-28T16:37:55 | 2018-12-28T16:37:55 | 148,507,119 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,469 | cpp | price_update.cpp | #include <eosiolib/eosio.hpp>
#include <eosiolib/name.hpp>
#include <vector>
using namespace eosio;
using namespace std;
CONTRACT price_update : public eosio::contract {
public:
using contract::contract;
price_update(name self, name code, datastream<const char*> ds) : contract(self, code, ds) {}
[[eosio::action]]
void createticker(name ticker_name, vector<string> exchanges) {
require_auth(_self);
ticker_index tickers(_self, _self.value);
uint64_t ticker_name_index = ticker_name.value;
auto itr = tickers.find(ticker_name_index);
eosio_assert(itr == tickers.end(), "Ticker already exists!");
tickers.emplace(_self, [&](auto& t) {
t.ticker_name = ticker_name;
for (int i = 0; i < exchanges.size(); ++i) {
exchange ex {exchanges[i], 0.0};
t.exchanges.push_back(ex);
}
t.avg_price = 0.0;
t.timestamp = "";
});
}
[[eosio::action]]
void updateticker(name ticker_name, vector<string> exchanges) {
require_auth(_self);
ticker_index tickers(_self, _self.value);
uint64_t ticker_name_index = ticker_name.value;
auto itr = tickers.find(ticker_name_index);
eosio_assert(itr != tickers.end(), "Ticker not found!");
tickers.modify(itr, _self, [&](auto& t) {
t.exchanges.clear();
for (int i = 0; i < exchanges.size(); ++i) {
exchange ex {exchanges[i], 0.0};
t.exchanges.push_back(ex);
}
});
}
[[eosio::action]]
void deleteticker(name ticker_name, vector<string> exchanges) {
require_auth(_self);
ticker_index tickers(_self, _self.value);
uint64_t ticker_name_index = ticker_name.value;
auto itr = tickers.find(ticker_name_index);
eosio_assert(itr != tickers.end(), "Ticker not found!");
tickers.erase(itr);
}
[[eosio::action]]
void update(name ticker_name, vector<double> prices, double avg_price, string timestamp) {
require_auth(_self);
ticker_index tickers(_self, _self.value);
uint64_t ticker_name_index = ticker_name.value;
auto itr = tickers.find(ticker_name_index);
eosio_assert(itr != tickers.end(), "Ticker not found!");
eosio_assert(prices.size() <= itr->exchanges.size(), "Wrong values size");
tickers.modify(itr, _self, [&](auto& p) {
for (int i = 0; i < prices.size(); ++i) {
p.exchanges[i].exchange_price = prices[i];
}
p.avg_price = avg_price;
p.timestamp = timestamp;
});
}
private:
struct exchange {
string exchange_name;
double exchange_price;
};
TABLE ticker {
name ticker_name;
vector<exchange> exchanges;
double avg_price;
string timestamp;
uint64_t primary_key() const {return ticker_name.value;}
};
typedef multi_index<"ticker"_n, ticker> ticker_index;
};
EOSIO_DISPATCH(price_update, (createticker)(updateticker)(deleteticker)(update))
|
042394c4b4280d16fc1e9447323c28f8ce87dfbf | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /chrome/browser/predictors/resource_prefetch_predictor.h | 5bec7ba8c336a3000f97cc3f8218224f49c50f9d | [
"BSD-3-Clause"
] | permissive | chromium/chromium | aaa9eda10115b50b0616d2f1aed5ef35d1d779d6 | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | refs/heads/main | 2023-08-24T00:35:12.585945 | 2023-08-23T22:01:11 | 2023-08-23T22:01:11 | 120,360,765 | 17,408 | 7,102 | BSD-3-Clause | 2023-09-10T23:44:27 | 2018-02-05T20:55:32 | null | UTF-8 | C++ | false | false | 15,585 | h | resource_prefetch_predictor.h | // Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_PREDICTORS_RESOURCE_PREFETCH_PREDICTOR_H_
#define CHROME_BROWSER_PREDICTORS_RESOURCE_PREFETCH_PREDICTOR_H_
#include <stddef.h>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <vector>
#include "base/gtest_prod_util.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/scoped_observation.h"
#include "base/task/cancelable_task_tracker.h"
#include "base/time/time.h"
#include "chrome/browser/predictors/loading_predictor_config.h"
#include "chrome/browser/predictors/resource_prefetch_predictor_tables.h"
#include "components/history/core/browser/history_db_task.h"
#include "components/history/core/browser/history_service.h"
#include "components/history/core/browser/history_service_observer.h"
#include "components/history/core/browser/history_types.h"
#include "components/keyed_service/core/keyed_service.h"
#include "components/optimization_guide/core/optimization_guide_decision.h"
#include "components/sqlite_proto/key_value_data.h"
#include "net/base/network_anonymization_key.h"
#include "services/network/public/mojom/fetch_api.mojom-forward.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "url/gurl.h"
#include "url/origin.h"
class PredictorsHandler;
class Profile;
namespace predictors {
struct OriginRequestSummary;
struct PageRequestSummary;
namespace internal {
struct LastVisitTimeCompare {
template <typename T>
bool operator()(const T& lhs, const T& rhs) const {
return lhs.last_visit_time() < rhs.last_visit_time();
}
};
} // namespace internal
class TestObserver;
class ResourcePrefetcherManager;
// Stores all values needed to trigger a preconnect/preresolve job to a single
// origin.
struct PreconnectRequest {
// |network_anonymization_key| specifies the key that network requests for the
// preconnected URL are expected to use. If a request is issued with a
// different key, it may not use the preconnected socket. It has no effect
// when |num_sockets| == 0.
PreconnectRequest(
const url::Origin& origin,
int num_sockets,
const net::NetworkAnonymizationKey& network_anonymization_key);
PreconnectRequest(const PreconnectRequest&) = default;
PreconnectRequest(PreconnectRequest&&) = default;
PreconnectRequest& operator=(const PreconnectRequest&) = default;
PreconnectRequest& operator=(PreconnectRequest&&) = default;
url::Origin origin;
// A zero-value means that we need to preresolve a host only.
int num_sockets = 0;
bool allow_credentials = true;
net::NetworkAnonymizationKey network_anonymization_key;
};
struct PrefetchRequest {
PrefetchRequest(const GURL& url,
const net::NetworkAnonymizationKey& network_anonymization_key,
network::mojom::RequestDestination destination);
PrefetchRequest(const PrefetchRequest&) = default;
PrefetchRequest(PrefetchRequest&&) = default;
PrefetchRequest& operator=(const PrefetchRequest&) = default;
PrefetchRequest& operator=(PrefetchRequest&&) = default;
GURL url;
net::NetworkAnonymizationKey network_anonymization_key;
network::mojom::RequestDestination destination;
};
// Stores a result of pre* prediction. The |requests| vector is the main
// result for preconnects, while the |prefetch_requests| vector is the main
// result for prefetches. Other fields are used for metrics reporting.
struct PreconnectPrediction {
PreconnectPrediction();
PreconnectPrediction(const PreconnectPrediction& other);
PreconnectPrediction(PreconnectPrediction&& other);
PreconnectPrediction& operator=(const PreconnectPrediction& other);
PreconnectPrediction& operator=(PreconnectPrediction&& other);
~PreconnectPrediction();
bool is_redirected = false;
std::string host;
std::vector<PreconnectRequest> requests;
std::vector<PrefetchRequest> prefetch_requests;
};
// Stores a result of a prediction from the optimization guide.
struct OptimizationGuidePrediction {
OptimizationGuidePrediction();
OptimizationGuidePrediction(const OptimizationGuidePrediction& other);
~OptimizationGuidePrediction();
optimization_guide::OptimizationGuideDecision decision;
PreconnectPrediction preconnect_prediction;
std::vector<GURL> predicted_subresources;
absl::optional<base::TimeTicks> optimization_guide_prediction_arrived;
};
// Contains logic for learning what can be prefetched and for kicking off
// speculative prefetching.
// - The class is a profile keyed service owned by the profile.
// - All the non-static methods of this class need to be called on the UI
// thread.
//
// The overall flow of the resource prefetching algorithm is as follows:
//
// * LoadingPredictorObserver - Listens for URL requests, responses and
// redirects (client-side redirects are not supported) on the IO thread (via
// ResourceDispatcherHostDelegate) and posts tasks to the
// LoadingDataCollector on the UI thread. This is owned by the ProfileIOData
// for the profile.
// * ResourcePrefetchPredictorTables - Persists ResourcePrefetchPredictor data
// to a sql database. Runs entirely on the DB sequence provided by the client
// to the constructor of this class. Owned by the PredictorDatabase.
// * ResourcePrefetchPredictor - Learns about resource requirements per URL in
// the UI thread through the LoadingPredictorObserver and persists it to disk
// in the DB sequence through the ResourcePrefetchPredictorTables. It
// initiates resource prefetching using the ResourcePrefetcherManager. Owned
// by profile.
class ResourcePrefetchPredictor : public history::HistoryServiceObserver {
public:
// Used for reporting redirect prediction success/failure in histograms.
// NOTE: This enumeration is used in histograms, so please do not add entries
// in the middle.
enum class RedirectStatus {
NO_REDIRECT,
NO_REDIRECT_BUT_PREDICTED,
REDIRECT_NOT_PREDICTED,
REDIRECT_WRONG_PREDICTED,
REDIRECT_CORRECTLY_PREDICTED,
MAX
};
using RedirectDataMap =
sqlite_proto::KeyValueData<RedirectData, internal::LastVisitTimeCompare>;
using OriginDataMap =
sqlite_proto::KeyValueData<OriginData, internal::LastVisitTimeCompare>;
using LcppDataMap =
sqlite_proto::KeyValueData<LcppData, internal::LastVisitTimeCompare>;
ResourcePrefetchPredictor(const LoadingPredictorConfig& config,
Profile* profile);
ResourcePrefetchPredictor(const ResourcePrefetchPredictor&) = delete;
ResourcePrefetchPredictor& operator=(const ResourcePrefetchPredictor&) =
delete;
~ResourcePrefetchPredictor() override;
// Starts initialization by posting a task to the DB sequence of the
// ResourcePrefetchPredictorTables to read the predictor database. Virtual for
// testing.
virtual void StartInitialization();
virtual void Shutdown();
// Returns true if preconnect data exists for the |main_frame_url|.
virtual bool IsUrlPreconnectable(const GURL& main_frame_url) const;
// Sets the |observer| to be notified when the resource prefetch predictor
// data changes. Previously registered observer will be discarded. Call
// this with nullptr parameter to de-register observer.
void SetObserverForTesting(TestObserver* observer);
// Returns true iff there is OriginData that can be used for a |url| and fills
// |prediction| with origins and hosts that need to be preconnected and
// preresolved respectively. |prediction| pointer may be nullptr to get return
// value only.
virtual bool PredictPreconnectOrigins(const GURL& url,
PreconnectPrediction* prediction) const;
// Returns LCP element locators in the past loads for a given `url`. The
// returned LCP element locators are ordered by descending frequency (the most
// frequent one comes first). If there is no data, it returns an empty vector.
std::vector<std::string> PredictLcpElementLocators(const GURL& url) const;
// Called by the collector after a page has finished loading resources and
// assembled a PageRequestSummary.
virtual void RecordPageRequestSummary(
std::unique_ptr<PageRequestSummary> summary);
// Record LCP element locators after a page has finished loading and LCP has
// been determined.
void LearnLcpp(const std::string& host,
const std::string& lcp_element_locator);
// Deletes all URLs from the predictor database and caches.
void DeleteAllUrls();
private:
friend class LoadingPredictor;
friend class ::PredictorsHandler;
friend class LoadingDataCollector;
friend class ResourcePrefetchPredictorTest;
friend class PredictorInitializer;
FRIEND_TEST_ALL_PREFIXES(ResourcePrefetchPredictorTest, DeleteUrls);
FRIEND_TEST_ALL_PREFIXES(ResourcePrefetchPredictorTest,
DeleteAllUrlsUninitialized);
FRIEND_TEST_ALL_PREFIXES(ResourcePrefetchPredictorTest,
LazilyInitializeEmpty);
FRIEND_TEST_ALL_PREFIXES(ResourcePrefetchPredictorTest,
LazilyInitializeWithData);
FRIEND_TEST_ALL_PREFIXES(ResourcePrefetchPredictorTest,
NavigationLowHistoryCount);
FRIEND_TEST_ALL_PREFIXES(ResourcePrefetchPredictorTest, NavigationUrlInDB);
FRIEND_TEST_ALL_PREFIXES(ResourcePrefetchPredictorTest, NavigationUrlNotInDB);
FRIEND_TEST_ALL_PREFIXES(ResourcePrefetchPredictorTest,
NavigationUrlNotInDBAndDBFull);
FRIEND_TEST_ALL_PREFIXES(ResourcePrefetchPredictorTest,
NavigationManyResourcesWithDifferentOrigins);
FRIEND_TEST_ALL_PREFIXES(ResourcePrefetchPredictorTest, RedirectUrlNotInDB);
FRIEND_TEST_ALL_PREFIXES(ResourcePrefetchPredictorTest, RedirectUrlInDB);
FRIEND_TEST_ALL_PREFIXES(ResourcePrefetchPredictorTest, OnMainFrameRequest);
FRIEND_TEST_ALL_PREFIXES(ResourcePrefetchPredictorTest, OnMainFrameRedirect);
FRIEND_TEST_ALL_PREFIXES(ResourcePrefetchPredictorTest,
OnSubresourceResponse);
FRIEND_TEST_ALL_PREFIXES(ResourcePrefetchPredictorTest, GetCorrectPLT);
FRIEND_TEST_ALL_PREFIXES(ResourcePrefetchPredictorTest,
PopulatePrefetcherRequest);
FRIEND_TEST_ALL_PREFIXES(ResourcePrefetchPredictorTest, GetRedirectOrigin);
FRIEND_TEST_ALL_PREFIXES(ResourcePrefetchPredictorTest, GetPrefetchData);
FRIEND_TEST_ALL_PREFIXES(
ResourcePrefetchPredictorPreconnectToRedirectTargetTest,
TestPredictPreconnectOrigins);
FRIEND_TEST_ALL_PREFIXES(ResourcePrefetchPredictorTest,
TestPredictPreconnectOrigins_RedirectsToNewOrigin);
FRIEND_TEST_ALL_PREFIXES(ResourcePrefetchPredictorTest,
TestPrecisionRecallHistograms);
FRIEND_TEST_ALL_PREFIXES(ResourcePrefetchPredictorTest,
TestPrefetchingDurationHistogram);
FRIEND_TEST_ALL_PREFIXES(ResourcePrefetchPredictorTest,
TestRecordFirstContentfulPaint);
FRIEND_TEST_ALL_PREFIXES(ResourcePrefetchPredictorTest, LearnLcpp);
FRIEND_TEST_ALL_PREFIXES(ResourcePrefetchPredictorTest,
WhenLcppDataIsCorrupted_ResetData);
enum InitializationState {
NOT_INITIALIZED = 0,
INITIALIZING = 1,
INITIALIZED = 2
};
// Returns true iff one of the following conditions is true
// * |redirect_data| contains confident redirect origin for |entry_origin|
// and assigns it to the |redirect_origin|
//
// * |redirect_data| doesn't contain an entry for |entry_origin| and assigns
// |entry_origin| to the |redirect_origin|.
static bool GetRedirectOrigin(const url::Origin& entry_origin,
const RedirectDataMap& redirect_data,
url::Origin* redirect_origin);
// Returns true if a redirect endpoint is available. Appends the redirect
// domains to |prediction->requests|. Sets |prediction->host| if it's empty.
bool GetRedirectEndpointsForPreconnect(
const url::Origin& entry_origin,
const RedirectDataMap& redirect_data,
PreconnectPrediction* prediction) const;
// Callback for the task to read the predictor database. Takes ownership of
// all arguments.
void CreateCaches(std::unique_ptr<RedirectDataMap> host_redirect_data,
std::unique_ptr<OriginDataMap> origin_data,
std::unique_ptr<LcppDataMap> lcpp_data);
// Called during initialization when history is read and the predictor
// database has been read.
void OnHistoryAndCacheLoaded();
// Deletes data for the input |urls| and their corresponding hosts from the
// predictor database and caches.
void DeleteUrls(const history::URLRows& urls);
// Try to ensure that DataMaps are available, and returns true iff they are
// available now.
bool TryEnsureRecordingPrecondition();
// Updates information about final redirect destination for the |key| in
// |host_redirect_data_| and correspondingly updates the predictor database.
void LearnRedirect(const std::string& key, const GURL& final_redirect);
void LearnOrigins(
const std::string& host,
const GURL& main_frame_origin,
const std::map<url::Origin, OriginRequestSummary>& summaries);
// history::HistoryServiceObserver:
void OnURLsDeleted(history::HistoryService* history_service,
const history::DeletionInfo& deletion_info) override;
void OnHistoryServiceLoaded(
history::HistoryService* history_service) override;
// Used to connect to HistoryService or register for service loaded
// notificatioan.
void ConnectToHistoryService();
// Used for testing to inject mock tables.
void set_mock_tables(scoped_refptr<ResourcePrefetchPredictorTables> tables) {
tables_ = tables;
}
const raw_ptr<Profile, DanglingUntriaged> profile_;
raw_ptr<TestObserver> observer_;
const LoadingPredictorConfig config_;
InitializationState initialization_state_;
scoped_refptr<ResourcePrefetchPredictorTables> tables_;
base::CancelableTaskTracker history_lookup_consumer_;
std::unique_ptr<RedirectDataMap> host_redirect_data_;
std::unique_ptr<OriginDataMap> origin_data_;
std::unique_ptr<LcppDataMap> lcpp_data_;
base::ScopedObservation<history::HistoryService,
history::HistoryServiceObserver>
history_service_observation_{this};
// Indicates if all predictors data should be deleted after the
// initialization is completed.
bool delete_all_data_requested_ = false;
base::WeakPtrFactory<ResourcePrefetchPredictor> weak_factory_{this};
};
// An interface used to notify that data in the ResourcePrefetchPredictor
// has changed. All methods are invoked on the UI thread.
class TestObserver {
public:
TestObserver(const TestObserver&) = delete;
TestObserver& operator=(const TestObserver&) = delete;
// De-registers itself from |predictor_| on destruction.
virtual ~TestObserver();
virtual void OnPredictorInitialized() {}
virtual void OnNavigationLearned(const PageRequestSummary& summary) {}
virtual void OnLcppLearned() {}
protected:
// |predictor| must be non-NULL and has to outlive the TestObserver.
// Also the predictor must not have a TestObserver set.
explicit TestObserver(ResourcePrefetchPredictor* predictor);
private:
raw_ptr<ResourcePrefetchPredictor> predictor_;
};
} // namespace predictors
#endif // CHROME_BROWSER_PREDICTORS_RESOURCE_PREFETCH_PREDICTOR_H_
|
a65a2aa924ad2df95632c6ee3057d41e363a3557 | 98dc5072330d818d162cab38365f034de19d0691 | /acl/include/acl_cpp/db/db_service.hpp | 60d597b043d35bbbd8e311b956b6e7249f8f3049 | [
"Apache-2.0"
] | permissive | feixiao/c_practice | 5936d7a59f313eff671785564f9e14c0b105e5ca | ce9c10f8dcd4d5f5076cefefb9dc8358223fe514 | refs/heads/master | 2023-05-10T16:06:06.564499 | 2023-03-31T03:17:22 | 2023-03-31T03:17:22 | 63,298,597 | 4 | 3 | Apache-2.0 | 2023-05-05T02:21:39 | 2016-07-14T03:21:52 | C | GB18030 | C++ | false | false | 3,218 | hpp | db_service.hpp | #pragma once
#include "../acl_cpp_define.hpp"
#include <list>
#include "../ipc/ipc_service.hpp"
#include "../stdlib/string.hpp"
namespace acl {
typedef enum
{
DB_OK,
DB_ERR_OPEN,
DB_ERR_EXEC_SQL,
} db_status;
//////////////////////////////////////////////////////////////////////////
class db_rows;
class ACL_CPP_API db_query
{
public:
db_query(void) {}
virtual ~db_query(void) {}
virtual void on_error(db_status status) = 0;
virtual void on_ok(const db_rows* rows, int affected) = 0;
/**
* 当任务处理完毕或出错时,内部处理过程会自动调用 destroy 接口,
* 子类可以在该接口内进行一些释放过程,尤其当该对象是动态创建时,
* 子类应该在该函数内 delete this 以删除自己,因为该函数最终肯定
* 会被调用,所以子类不应在其它地方进行析构操作
*/
virtual void destroy(void) {}
protected:
private:
};
//////////////////////////////////////////////////////////////////////////
class db_handle;
class aio_socket_stream;
/**
* 数据库服务类,该类是一个异步数据库操作管理类,该类对象所在的线程必须是
* 一个非阻塞的线程过程
*/
class ACL_CPP_API db_service : public ipc_service
{
public:
/**
* 当为 sqlite 数据库时的构造函数
* @param dblimit {size_t} 数据库连接池的个数限制
* @param nthread {int} 子线程池的最大线程数
* @param win32_gui {bool} 是否是窗口类的消息,如果是,则内部的
* 通讯模式自动设置为基于 _WIN32 的消息,否则依然采用通用的套接
* 口通讯方式
*/
db_service(size_t dblimit = 100, int nthread = 2, bool win32_gui = false);
virtual ~db_service(void);
/**
* 异步执行 SQL 查询语句
* @param sql {const char*} 要执行的标准 SQL 语句
* @param query {db_query*} 用来接收执行结果的类对象
*/
void sql_select(const char* sql, db_query* query);
/**
* 异步执行 SQL 更新语句
* @param sql {const char*} 要执行的标准 SQL 语句
* @param query {db_query*} 用来接收执行结果的类对象
*/
void sql_update(const char* sql, db_query* query);
/**
* 向数据库连接池中添加连接对象
* @param db {db_handle*} 数据库连接对象
*/
void push_back(db_handle* db);
protected:
/**
* 需要子类实现此函数用来创建数据库对象
* @return {db_handle*}
*/
virtual db_handle* db_create() = 0;
/**
* 基类虚函数,当有新连接到达时基类回调此函数
* @param client {aio_socket_stream*} 接收到的新的客户端连接
*/
virtual void on_accept(aio_socket_stream* client);
#if defined(_WIN32) || defined(_WIN64)
/**
* 基类虚函数,当收到来自于子线程的 win32 消息时的回调函数
* @param hWnd {HWND} 窗口句柄
* @param msg {UINT} 用户自定义消息号
* @param wParam {WPARAM} 参数
* @param lParam {LPARAM} 参数
*/
virtual void win32_proc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
#endif
private:
// 数据库引擎池
std::list<db_handle*> dbpool_;
// 数据库连接池的个数限制
size_t dblimit_;
// 当前数据库连接池的个数
size_t dbsize_;
};
} // namespace acl
|
d8009130f1bc4b1186be13764783978202d2c670 | c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64 | /Engine/Source/ThirdParty/IntelTBB/IntelTBB-4.4u3/src/test/harness_bad_expr.h | 86935772ec065d18ff911e71bf894b6af5d94090 | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | windystrife/UnrealEngine_NVIDIAGameWorks | c3c7863083653caf1bc67d3ef104fb4b9f302e2a | b50e6338a7c5b26374d66306ebc7807541ff815e | refs/heads/4.18-GameWorks | 2023-03-11T02:50:08.471040 | 2022-01-13T20:50:29 | 2022-01-13T20:50:29 | 124,100,479 | 262 | 179 | MIT | 2022-12-16T05:36:38 | 2018-03-06T15:44:09 | C++ | UTF-8 | C++ | false | false | 3,706 | h | harness_bad_expr.h | /*
Copyright 2005-2016 Intel Corporation. All Rights Reserved.
This file is part of Threading Building Blocks. Threading Building Blocks is free software;
you can redistribute it and/or modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation. Threading Building Blocks 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 Threading Building Blocks; if not, write to the
Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
As a special exception, you may use this file as part of a free software library without
restriction. Specifically, if other files instantiate templates or use macros or inline
functions from this file, or you compile this file and link it with other files to produce
an executable, this file does not by itself cause the resulting executable to be covered
by the GNU General Public License. This exception does not however invalidate any other
reasons why the executable file might be covered by the GNU General Public License.
*/
// Declarations for checking __TBB_ASSERT checks inside TBB.
// This header is an optional part of the test harness.
// It assumes that "harness.h" has already been included.
#define TRY_BAD_EXPR_ENABLED (TBB_USE_ASSERT && TBB_USE_EXCEPTIONS && !__TBB_THROW_ACROSS_MODULE_BOUNDARY_BROKEN)
#if TRY_BAD_EXPR_ENABLED
//! Check that expression x raises assertion failure with message containing given substring.
/** Assumes that tbb::set_assertion_handler( AssertionFailureHandler ) was called earlier. */
#define TRY_BAD_EXPR(x,substr) \
{ \
const char* message = NULL; \
bool okay = false; \
try { \
x; \
} catch( AssertionFailure a ) { \
okay = true; \
message = a.message; \
} \
CheckAssertionFailure(__LINE__,#x,okay,message,substr); \
}
//! Exception object that holds a message.
struct AssertionFailure {
const char* message;
AssertionFailure( const char* filename, int line, const char* expression, const char* comment );
};
AssertionFailure::AssertionFailure( const char* filename, int line, const char* expression, const char* comment ) :
message(comment)
{
ASSERT(filename,"missing filename");
ASSERT(0<line,"line number must be positive");
// All of our current files have fewer than 4000 lines.
ASSERT(line<5000,"dubiously high line number");
ASSERT(expression,"missing expression");
}
void AssertionFailureHandler( const char* filename, int line, const char* expression, const char* comment ) {
throw AssertionFailure(filename,line,expression,comment);
}
void CheckAssertionFailure( int line, const char* expression, bool okay, const char* message, const char* substr ) {
if( !okay ) {
REPORT("Line %d, %s failed to fail\n", line, expression );
abort();
} else if( !message ) {
REPORT("Line %d, %s failed without a message\n", line, expression );
abort();
} else if( strstr(message,substr)==0 ) {
REPORT("Line %d, %s failed with message '%s' missing substring '%s'\n", __LINE__, expression, message, substr );
abort();
}
}
#endif /* TRY_BAD_EXPR_ENABLED */
|
32dfdcc4320e948f7d7a894c1f6132754eb408cf | 100250705b0870aa3f39cfcde2887773e15be691 | /qt_painter/mydraw.h | 0b1fc19f9a8c21905e34389e96c73ac2cb58617f | [] | no_license | Artist-V/qt | ca4061c65d4e220df0492c7f109b484a5f87f178 | cc87a2504c96e823b6d3f113eadbfe67bebca090 | refs/heads/master | 2020-05-24T20:18:01.777193 | 2019-09-04T13:27:54 | 2019-09-04T13:27:54 | 187,452,468 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,396 | h | mydraw.h | #ifndef DRAWWIDGET_H
#define DRAWWIDGET_H
#pragma execution_character_set("utf-8")
#include <QWidget>
#include <QtGui>
#include <QMouseEvent>
#include <QPaintEvent>
#include <QResizeEvent>
#include <QColor>
#include <QPixmap>
#include <QPoint>
#include <QPainter>
#include <QPalette>
#include <QFileDialog>
#include <QPen>
#include <QBrush>
#include <QtPrintSupport/QPrintDialog>
#include <QtPrintSupport/QPrinter>
class myDraw : public QWidget
{
Q_OBJECT
public:
explicit myDraw(QWidget *parent = 0);
public:
void paintEvent(QPaintEvent *); //窗体重绘
void mousePressEvent(QMouseEvent *);//鼠标按下
void mouseMoveEvent(QMouseEvent *);//鼠标移动
void resizeEvent(QResizeEvent *);//改变窗口大小
enum Shape{Line,Rectangle,Ellipse,Text,Pixmap};
void clear();//清除
void openimg();//打开
public slots:
void setStyle(int);
void setWidth(int);
void setColor(QColor);
void setBrush(QBrush);
//涂鸦
private:
QPixmap *pix;
QPoint startPos;
QPoint endPos;
int style;
int weight;
QColor color;
QBrush brush;
QColor bcolor;
//标识
private:
int flag_open;//打开
int flag_line;
int flag_rect;
int flag_ellipse;
int flag_butt;
int flag_left;
public :
void setDraw();
void setrect();
void setellipse();
void setbutt();
};
#endif // DRAWWIDGET_H
|
fde800d76c63b6fdcb4e3cdc81db6520f550acc5 | 68e940312174dfbcc91b332b805f1dfc2c0cae25 | /src/utils/json/main.cpp | 6bc8a9a5cc3a6799f15f012a74731cd56cf51440 | [] | no_license | zhaokun00/utils_cplusplus | b6937f7fa3456a38c1da5dba426d49a417342ada | 5fe14d1d2ce12a9a2c2d7455e390722c7f658be5 | refs/heads/master | 2021-09-08T20:20:19.543454 | 2019-06-02T04:01:06 | 2019-06-02T04:01:06 | 120,563,589 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,174 | cpp | main.cpp | #include <stdio.h>
#include <iostream>
#include <chrono>
#include <vector>
#include <map>
#include"json.hpp"
//using namespace std;
//using json=nlohmann::json;
//https://blog.csdn.net/forrid/article/details/78867679
//https://blog.csdn.net/fengxinlinux/article/details/71037244
//测试:std::cin函数,读取终端输入的字符串
void test1() {
std::string str;
#if 1
std::cout << "输入字符串:";
//将输入的字符串赋值给str变量
std::cin >> str;
std::cout << str << std::endl;
#endif
std::string s = "q";
if(s == str) {
std::cout << "两个字符串相等" << std::endl;
}
else {
std::cout << "两个字符串不相等" << std::endl;
}
}
//测试nlohmann::json的基本用法
/*
1.拼接json串,将json串转换为字符串类型
2.将字符串类型转化为json串,从json串中获取想要的数据
*/
void test2() {
nlohmann::json j; //声明一个nlohmann::json类型对象
j["pi"] = 3.14; //添加整型元素
j["happy"] = true; //添加bool类型元素
j["answer"]["today"] = 1; //在对象中添加对象
j["answer"]["tomorrow"] = "monday";
j["answer"]["day"]["sex"] = 1;
j["answer"]["day"]["name"] = "zhaokun";
// j["nothing"] = NULL; //这种形式输出为"nothing":0
j["nothing"] = nullptr; //这种形式处处为"nothing":null
j["list"] = {1,2,3};
j["list"][3] = 4;
//普通打印字符串的形式
// std::cout << j.dump() << std::endl;
//格式化输出字符串
// std::cout << j.dump(4) << std::endl;
//测试:不能将nlohmann::json类型对象直接转换为std::string类型对象
#if 0
std::string str = j;
std::cout << str << std::endl;
#endif
//测试:用dump函数将nlohmann::json类型转换为std::string类型
#if 0
std::string str = j.dump();
std::cout << str << std::endl;
#endif
//测试:从nlohmann::json类型中获取值
#if 0
//get函数后面要添加获取的类型
int pi = j["pi"].get<std::int>();
//错误的形式
// std::string str = j["pi"].get();
std::cout << pi << std::endl;
#endif
//测试将字符串转化为nlohmann::json类型
#if 1
std::string str = j.dump();
nlohmann::json jj = nlohmann::json::parse(str);
// std::cout << jj << std::endl;
/*
double pi = j["pi"].get<double>();
std::cout << "pi = " << pi << std::endl;
std::cout << j["happy"].get<bool>() << std::endl;
std::cout << j["answer"]["today"].get<int>() << std::endl;
std::cout << j["answer"]["tomorrow"].get<std::string>() << std::endl;
std::cout << j["answer"]["day"]["sex"].get<int>() << std::endl;
*/
// std::cout << j["list"][0] << std::endl;
//获取数组
nlohmann::json i = j["list"];
// std::cout << i.dump(4);
std::cout << "size = " << i.size() << std::endl;
// std::cout << "type = " << i.type() << std::endl;
for (nlohmann::json::iterator it = i.begin(); it != i.end(); ++it) { //获取数组的值
std::cout << *it << '\n';
}
#endif
//测试获取对象中的对象
#if 0
std::cout << j["happy"].get<bool>() << std::endl;
std::cout << j["answer"]["everything"].get<int>() << std::endl;
#endif
}
//从字符串转换为json类型对象
void test3() {
//第一种形式:后面必须加__json,没有附加__json后缀,传递的字符串文字不会解析,而只是用作JSON字符串,也就是说
//nlohmann::json j = "{ \"happy\": true, \"pi\": 3.141 }"只存储字符串"{ "happy": true, "pi": 3.141 }",而不是解析实际对象
// nlohmann::json j = "{\"happy\": true, \"pi\": 3.141}"_json;
// json j = "{\"happy\": true, \"pi\": 3.141}"; //这种方式获取key值不能获取到
//第二种方式:使用nlohmann::json::parse函数将字符串转换为json类型对象
nlohmann::json j = nlohmann::json::parse("{\"happy\": true, \"pi\": 3.141}");
std::cout << j["happy"].get<bool>() << std::endl;
}
//直接把vector中数据放入json类型对象中
void test4() {
std::vector<int> v;
v.push_back(1);
v.push_back(2);
nlohmann::json json(v);
for (nlohmann::json::iterator it = json.begin(); it != json.end(); ++it) { //获取数组的值
std::cout << *it << '\n';
}
}
//直接把map类型对象放入到json类型对象中
void test5() {
std::map<std::string,int> m;
m.insert(std::make_pair("num1",1));
m.insert(std::make_pair("num2",2));
nlohmann::json json(m);
std::cout << json["num1"].get<int>() << std::endl;
std::cout << json["num2"].get<int>() << std::endl;
for(nlohmann::json::iterator it = json.begin();it != json.end();++it) {
std::cout << "key =" << it.key() << std::endl;
std::cout << "value =" << it.value() << std::endl;
}
}
namespace ns {
// 一个简单的结构,为 person 建模
struct person {
std::string name;
std::string address;
int age;
};
void to_json(nlohmann::json &j, const person& p) {
//j = json{{"name", p.name}, {"address", p.address}, {"age", p.age}};
j["name"] = p.name;
j["address"] = p.address;
j["age"] = p.age;
}
void from_json(const nlohmann::json &j, person& p) {
p.name = j.at("name").get<std::string>();
p.name = j.at("address").get<std::string>();
p.name = j.at("age").get<int>();
}
}
class Human {
public:
std::string name;
std::string address;
int age;
Human() {}
~Human() {}
void to_json(nlohmann::json &j) {
j["name"] = this->name;
j["address"] = this->address;
j["age"] = this->age;
}
void from_json(const nlohmann::json &j) {
this->name = j.at("name").get<std::string>();
this->address = j.at("address").get<std::string>();
this->age = j.at("age").get<int>();
}
};
void test6() {
//测试使用结构体形式
ns::person p = {"Ned Flanders", "744 Evergreen Terrace", 60};
// 转换至 JSON:将每个值拷贝至 JSON 对象
nlohmann::json j;
j["name"] = p.name;
j["address"] = p.address;
j["age"] = p.age;
// std::cout << j.dump(4) << std::endl;
//测试使用类的形式
Human h;
nlohmann::json json;
h.name = "zhaokun";
h.address = "hebei";
h.age = 30;
json["name"] = h.name;
json["address"] = h.address;
json["age"] = h.age;
std::cout << json.dump(4) << std::endl;
/*
// 转换自 JSON:从 JSON 对象中拷贝每个值
ns::person p {
j["name"].get<std::string>(),
j["address"].get<std::string>(),
j["age"].get<int>()
};
*/
}
void test7() {
ns::person p = {"Ned Flanders", "744 Evergreen Terrace", 70};
nlohmann::json j = p;
// std::cout << j.dump(4) << std::endl;
Human h;
nlohmann::json json;
h.name = "zhaokun";
h.address = "hebei";
h.age = 30;
h.to_json(json);
std::cout << json.dump(4) << std::endl;
Human h1;
h1.from_json(json);
std::cout << "name = " << h1.name << std::endl;
std::cout << "address = " << h1.address << std::endl;
std::cout << "age = " << h1.age << std::endl;
}
//nlohmann::json变量中嵌套nlohmann::json类型变量
void test8() {
nlohmann::json j; //声明一个nlohmann::json类型对象
nlohmann::json jj;
j["pi"] = 3.14; //添加整型元素
jj["name"] = "zhaokun";
j["person"] = jj;
std::cout << j.dump(4) << std::endl;
}
int main() {
// test1();
// test2();
// test3();
// test4();
// test5();
// test6();
// test7();
test8();
return 0;
}
|
3a19d24999949ce7e043f7be53edb679b7c22863 | bb1c9d8f47789137ce7269fdd056992f7848fed0 | /src/api/dcps/isocpp/code/org/opensplice/core/EntityRegistry.cpp | cc4327fec073e218e003b2b2f28f2ee5982d5631 | [
"Apache-2.0"
] | permissive | osrf/opensplice | e37ed7e1a24ece7c0f480b4807cd95d3ee18daad | 7c3466f76d083cae38a6d7fcbba1c29106a43ea5 | refs/heads/osrf-6.9.0 | 2021-01-15T14:20:20.065297 | 2020-05-11T18:05:53 | 2020-05-11T18:05:53 | 16,789,031 | 10 | 13 | Apache-2.0 | 2020-05-11T18:05:54 | 2014-02-13T02:13:20 | C | UTF-8 | C++ | false | false | 2,146 | cpp | EntityRegistry.cpp | /*
* Vortex OpenSplice
*
* This software and documentation are Copyright 2006 to TO_YEAR ADLINK
* Technology Limited, its affiliated companies and licensors. 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.
*
*/
/**
* @file
*/
#include <org/opensplice/core/EntityRegistry.hpp>
#include <dds/domain/DomainParticipant.hpp>
#include <dds/pub/Publisher.hpp>
#include <dds/sub/Subscriber.hpp>
namespace org
{
namespace opensplice
{
namespace core
{
/* DomainParticipant */
template <>
OSPL_ISOCPP_IMPL_API std::map<DDS::DomainParticipant_ptr, dds::core::WeakReference<dds::domain::DomainParticipant> >&
org::opensplice::core::EntityRegistry<DDS::DomainParticipant_ptr, dds::domain::DomainParticipant>::registry()
{
static std::map<DDS::DomainParticipant_ptr, dds::core::WeakReference<dds::domain::DomainParticipant> > registry_;
return registry_;
}
/* Publisher */
template <>
OSPL_ISOCPP_IMPL_API std::map<DDS::Publisher_ptr, dds::core::WeakReference<dds::pub::Publisher> >&
org::opensplice::core::EntityRegistry<DDS::Publisher_ptr, dds::pub::Publisher>::registry()
{
static std::map<DDS::Publisher_ptr, dds::core::WeakReference<dds::pub::Publisher> > registry_;
return registry_;
}
/* Subscriber */
template <>
OSPL_ISOCPP_IMPL_API std::map<DDS::Subscriber_ptr, dds::core::WeakReference<dds::sub::Subscriber> >&
org::opensplice::core::EntityRegistry<DDS::Subscriber_ptr, dds::sub::Subscriber>::registry()
{
static std::map<DDS::Subscriber_ptr, dds::core::WeakReference<dds::sub::Subscriber> > registry_;
return registry_;
}
}
}
} |
82a18552a401807ef10535a0df884db18a1ef43d | 6a66b0b9969976751dab05e3bf4f2e8570f76e83 | /src/codegen/ir_gaia/data_1d.cc | edda6912a59a8e794438fe2f88597d89124b0e5c | [] | no_license | HemiMin/cnn.planner | f1e38deda51bb167d054b65184a24235a7813637 | 14a41858be5fe20bde39cc7d3ecc221c77d946a8 | refs/heads/master | 2021-03-17T20:48:00.180219 | 2020-03-13T07:55:49 | 2020-03-13T07:55:49 | 247,016,463 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 391 | cc | data_1d.cc | #include "codegen/ir_gaia/data_1d.h"
using codegen::gaia::Data1d;
using std::endl;
ostream& codegen::gaia::operator<<(ostream& out, Data1d& data1d)
{
string ind = " ";
out << data1d.GetName()
<< "(" << codegen::gaia::ToString(data1d.GetLayout()) << ","
<< data1d.GetStartIndex() << ","
<< data1d.GetChannel()
<< ")" << endl;
return out;
}
|
07a33d07e79c15d2782fac99eb99602f35b58f2f | abbb664b47373bf0546a02ec2595af0be190c108 | /1-Algorithmic-Toolbox/1.2-introduction/assignment/fibonacci_huge.cpp | 2601f03b23245369fdf3466dc6462d3f1c09c42c | [] | no_license | mcitoler/data-structures-algorithms | 6f72e5ced4e10b49877969fa4efc3ffb886a7faa | 4dc7160a67570b78a03beae66644b0fa0e46dd7f | refs/heads/master | 2021-10-11T00:48:18.770763 | 2018-05-26T18:30:39 | 2018-05-26T18:30:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,677 | cpp | fibonacci_huge.cpp | #include <iostream>
#include <cassert>
#include <cstdlib>
long long get_fibonacci_huge_naive(long long n, long long m) {
if (n <= 1)
return n;
long long previous = 0;
long long current = 1;
for (long long i = 0; i < n - 1; ++i) {
long long tmp_previous = previous;
previous = current;
current = (tmp_previous + current) % m;
}
return current;
}
long long fibonacci_fast(long long n, long long m) {
// write your code here
if (n <= 1) {
return n;
}
long long prev = 0;
long long current = 1;
for (long long i = 2; i <= n; ++i) {
long long temp_current = (current + prev) % m;
prev = current;
current = temp_current;
}
return current;
}
long long get_fibonacci_period_lenght(long long m) {
long long prev = 0;
long long current = 1;
long long period = 0;
// long long temp_current = 0;
do {
long long temp_current = (current + prev) % m;
prev = current;
current = temp_current;
period++;
} while (prev != 0 || current != 1);
return period;
}
long long get_fibonacci_huge_fast(long long n, long long m) {
long long period = get_fibonacci_period_lenght(m);
long long r = n % period;
return fibonacci_fast(r, m);
}
void test_solution() {
for (long long i = 1; i < 20; ++i) {
long a = rand() % 20;
long long b = rand() % 8 + 2;
assert(get_fibonacci_huge_fast(a, b) == get_fibonacci_huge_naive(a, b));
}
}
int main() {
long long n, m;
std::cin >> n >> m;
// std::cout << get_fibonacci_huge_naive(n, m) << '\n';
// test_solution();
// std::cout << get_fibonacci_period(n) << '\n';
std::cout << get_fibonacci_huge_fast(n, m) << '\n';
return 0;
}
|
be9f5abf2db21ecf9984e38e1e45a21068e1b564 | b61a7bb59cc2c98a11335ff466fee7a78770b9ab | /Noise network/Code/Server/Examples/Servers/SimpleStreamEchoServer_ImplementedWithThreadedAcceptServer.cpp | ad8251cbf2d0028f1169485c4c77252621dfd56c | [] | no_license | Noise-filter/Noise-network | d6c251d034bf55cea68a896e6d8dc6a50bce7738 | 83b1f3161e31e9b25d3f4ed8d428cb4f9b04135d | refs/heads/master | 2021-07-11T07:16:42.365848 | 2021-04-02T08:29:41 | 2021-04-02T08:29:41 | 28,050,819 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,009 | cpp | SimpleStreamEchoServer_ImplementedWithThreadedAcceptServer.cpp | #include <iostream>
#include "Core\WinsockFunctions.h"
#include "Core\ThreadedAcceptServer.h"
#include "Core\SocketAddress.h"
using namespace std;
const int MAX_BUFFER_LENGTH = 512;
namespace Examples
{
void SimpleStreamEchoServer_ImplementedWithThreadedAcceptServer(unsigned short port)
{
if (InitWinSock())
{
return;
}
cout << "Hello World!" << std::endl;
ThreadedAcceptServer acceptServer;
auto bindAddress = SocketAddressFactory::Create("0.0.0.0", port);
//Initialize the AcceptSocket
//It's that easy
if (!acceptServer.Init(*bindAddress))
{
cout << "Error initializing accept socket" << std::endl;
acceptServer.Stop();
ShutdownWinSock();
return;
}
//Start accept thread
acceptServer.Start();
cout << "Waiting to accept a client" << std::endl;
StreamConnection client;
//Wait for connection
do
{
if (acceptServer.WaitingClients())
{
client = acceptServer.GetConnectedClient();
cout << "Client connected: " << client.GetSocket().GetSocket() << std::endl;
}
} while (!client.IsConnected());
//No longer need server socket
//Stop the accept thread
acceptServer.Stop();
std::vector<unsigned char> buffer;
int result = 0;
do
{
buffer.clear();
buffer.resize(MAX_BUFFER_LENGTH);
result = client.Recv(buffer, MAX_BUFFER_LENGTH);
if (result > 0)
{
//cout << "Bytes received: " << result << std::endl;
//cout << "Message received: " << &buffer[0] << std::endl;
result = client.Send(buffer, result);
if (result == SOCKET_ERROR)
{
cout << "Send failed with error: " << WSAGetLastError() << std::endl;
}
else
{
//cout << "Bytes send: " << result << std::endl;
}
}
else if (result == 0)
{
cout << "Connection closing..." << std::endl;
}
else
{
cout << "Recv failed with error: " << WSAGetLastError() << std::endl;
client.Disconnect();
}
} while (result > 0);
result = client.Disconnect();
ShutdownWinSock();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.