blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
904a67c6dd640dc927a7c3af0e64a187434cedd1 | 61f26e78291a96b5e8c810d82cb5eedbe86bd6f7 | /train_and_predict.cpp | a06453e3c89fcbb3f4f32093ced2239c5f99e1dd | [] | no_license | kyaFUK/tf-train-cpp | 993f33fe76c29d6bc692680ddcc3b5b9f9d17c05 | 5309e0c5efa7bad76d957b4567bec24331eeb80c | refs/heads/master | 2022-01-31T12:28:31.958859 | 2019-03-14T10:31:37 | 2019-03-22T22:20:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,600 | cpp | //
// Example of training the model created by create_graph.py in a C++ program.
//
#include <iostream>
#include <vector>
#include <string>
#include "tensorflow/core/platform/init_main.h"
#include "common.h"
using std::vector;
using std::string;
namespace {
// Save a checkpoint
void save_checkpoint(const std::unique_ptr<tensorflow::Session>& session, const string& checkpoint_prefix) {
tensorflow::Tensor ckpt(tensorflow::DT_STRING, tensorflow::TensorShape());
ckpt.scalar<string>()() = checkpoint_prefix;
TF_CHECK_OK(session->Run({{"save/Const", ckpt}}, {}, {"save/control_dependency"}, nullptr));
}
bool directory_exists(const string& dir) {
struct stat buf;
return stat(dir.c_str(), &buf) == 0;
}
}
int main(int argc, char* argv[]) {
const string graph_def_filename = "model.pb";
const string checkpoint_dir = "./checkpoints";
const string checkpoint_prefix = checkpoint_dir + "/model.ckpt";
// Setup global state for TensorFlow.
tensorflow::port::InitMain(argv[0], &argc, &argv);
std::cout << "Loading graph\n";
tensorflow::GraphDef graph_def;
// tensorflow::MetaGraphDef graph_def;
TF_CHECK_OK(tensorflow::ReadBinaryProto(tensorflow::Env::Default(),
graph_def_filename, &graph_def));
std::unique_ptr<tensorflow::Session> session(tensorflow::NewSession(tensorflow::SessionOptions()));
TF_CHECK_OK(session->Create(graph_def));
if (directory_exists(checkpoint_dir)) {
std::cout << "Restoring model weights from checkpoint\n";
tensorflow::Tensor ckpt(tensorflow::DT_STRING, tensorflow::TensorShape());
ckpt.scalar<string>()() = checkpoint_prefix;
TF_CHECK_OK(session->Run({{"save/Const", ckpt}}, {}, {"save/restore_all"}, nullptr));
} else {
std::cout << "Initializing model weights\n";
TF_CHECK_OK(session->Run({}, {}, {"init"}, nullptr));
}
// Load images and labels of training data
auto test_x = read_training_file("MNIST_data/t10k-images.idx3-ubyte");
auto test_y = read_label_file("MNIST_data/t10k-labels.idx1-ubyte");
predict(session, test_x, test_y);
// Load images and labels of test data
auto train_x = read_training_file("MNIST_data/train-images.idx3-ubyte");
auto train_y = read_label_file("MNIST_data/train-labels.idx1-ubyte");
// Training
for (int i = 0; i < 20; ++i) {
std::cout << "Epoch: " << i << std::endl;
run_train_step(session, train_x, train_y);
}
std::cout << "Updated predictions\n";
predict(session, test_x, test_y);
std::cout << "Saving checkpoint\n";
save_checkpoint(session, checkpoint_prefix);
return 0;
}
| [
"ryoji.ysd@gmail.com"
] | ryoji.ysd@gmail.com |
96cfe4c44a595af886761adbefbc0a06eea3bd15 | 677cf31b015e197e102b1708d1fc913505cd0558 | /cpp/CodeForces/cf-1343B.cpp | 4c72c21dccae7b302a1ac589f5f4d15b90b7b8d6 | [] | no_license | AvatarSenju/Competitive | 511744f6db4ad9e0cb4834135cbddca7ed0f94ac | b9aff171dad8eda8807faf8f869900cde1ba3773 | refs/heads/master | 2022-12-31T22:38:27.951717 | 2020-10-22T03:54:10 | 2020-10-22T03:54:10 | 198,122,214 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 544 | cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
int t = 0;
cin >> t;
while (t--)
{
int n = 0;
cin >> n;
if (n % 4 != 0)
{
cout << "NO\n";
continue;
}
cout << "YES\n";
for (int i = 2; i <= n; i += 2)
{
cout << i << " ";
}
int f = n / 2;
for (int i = 1; i < f; i++)
{
cout << (2 * i) - 1 << " ";
}
f--;
cout << n + f << "\n";
}
return 0;
} | [
"anushrut5@gmail.com"
] | anushrut5@gmail.com |
0d0eedaaaed8afa0626e63e51cf2a6837a74ddd2 | 27f88ea6d808b3cd88daa21a3b706539eaf0b539 | /Online Judge/CodCad/Airport/69027.cpp | c612b0cd032db2298937de188c403a2dbaa54959 | [] | no_license | glaucoacassio2020/Competitive-Programming-Algorithm | 7889cf906df7665e0f7c3db245cd3b946e6231a9 | 99d396b0fae5c7a4c702a5ec174e6d0261a9d50f | refs/heads/master | 2023-03-17T22:44:49.785615 | 2020-04-21T02:07:02 | 2020-04-21T02:07:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 658 | cpp | #include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
int main(void) {
int x=1, a, v;
scanf("%d %d", &a, &v);
while(a && v){
int i, y, z, maior=0;
int lista[101];
memset(lista, 0, sizeof(lista));
for(i=0; i<v; i++){
scanf("%d %d", &y, &z);
lista[y]++;
lista[z]++;
}
for(i=0; i<=a; i++){
if(lista[i] > maior)
maior = lista[i];
}
cout << "Teste " << x << endl;
for(i=0; i<=a; i++){
if(lista[i] == maior)
cout << i << " ";
}
cout << endl<<endl;
x++;
scanf("%d %d", &a, &v);
}
return 0;
}
| [
"paulomirandamss12@gmail.com"
] | paulomirandamss12@gmail.com |
7088bd3cbb1cf58995dbb936f2edfcfb724bc488 | 0c7e20a002108d636517b2f0cde6de9019fdf8c4 | /Sources/Elastos/Packages/Apps/Settings/inc/elastos/droid/settings/applications/CInstalledAppDetailsAlertDialogFragment.h | be6a8ed5f115dede2aec8eec10497d28ff09440c | [
"Apache-2.0"
] | permissive | kernal88/Elastos5 | 022774d8c42aea597e6f8ee14e80e8e31758f950 | 871044110de52fcccfbd6fd0d9c24feefeb6dea0 | refs/heads/master | 2021-01-12T15:23:52.242654 | 2016-10-24T08:20:15 | 2016-10-24T08:20:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 760 | h |
#ifndef __ELASTOS_DROID_SETTINGS_APPLICATIONS_CINSTALLEDAPPDETAILSALERTDIALOGFRAGMENT_H__
#define __ELASTOS_DROID_SETTINGS_APPLICATIONS_CINSTALLEDAPPDETAILSALERTDIALOGFRAGMENT_H__
#include "_Elastos_Droid_Settings_Applications_CInstalledAppDetailsAlertDialogFragment.h"
#include "elastos/droid/settings/applications/CInstalledAppDetails.h"
namespace Elastos {
namespace Droid {
namespace Settings {
namespace Applications {
CarClass(CInstalledAppDetailsAlertDialogFragment)
, public CInstalledAppDetails::MyAlertDialogFragment
{
public:
CAR_OBJECT_DECL();
};
} // namespace Applications
} // namespace Settings
} // namespace Droid
} // namespace Elastos
#endif //__ELASTOS_DROID_SETTINGS_APPLICATIONS_CINSTALLEDAPPDETAILSALERTDIALOGFRAGMENT_H__
| [
"xu.liting@kortide.com"
] | xu.liting@kortide.com |
41ebf64c7b8a2d98cd7502065a616c35c093faf1 | f23fea7b41150cc5037ddf86cd7a83a4a225b68b | /SDK/BP_FishingFish_Pondie_03_Colour_03_Bronze_classes.h | 418155a7db833a4769d06ca303fd36df6d2e9218 | [] | no_license | zH4x/SoT-SDK-2.2.0.1 | 36e1cf7f23ece6e6b45e5885f01ec7e9cd50625e | f2464e2e733637b9fa0075cde6adb5ed2be8cdbd | refs/heads/main | 2023-06-06T04:21:06.057614 | 2021-06-27T22:12:34 | 2021-06-27T22:12:34 | 380,845,087 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 891 | h | #pragma once
// Name: SoT, Version: 2.2.0b
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_FishingFish_Pondie_03_Colour_03_Bronze.BP_FishingFish_Pondie_03_Colour_03_Bronze_C
// 0x0000 (FullSize[0x0910] - InheritedSize[0x0910])
class ABP_FishingFish_Pondie_03_Colour_03_Bronze_C : public ABP_FishingFish_Pondie_03_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_FishingFish_Pondie_03_Colour_03_Bronze.BP_FishingFish_Pondie_03_Colour_03_Bronze_C");
return ptr;
}
void UserConstructionScript();
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"Massimo.linker@gmail.com"
] | Massimo.linker@gmail.com |
94a78ee938293dfd8ad05c053be2def0e3982bce | e650aebc5d9f0873c2fca1e043e9fdfa7bc46d11 | /legend/projects/legend/Classes/scene/HelloWorldScene.cpp | 21d3faa8ec72a8740257147a48aa4a3ae6d3fc44 | [] | no_license | asurada/SGLegend | e47003218de3fba4e9ee5b116cfbdb1869c7de7b | e3ea1d380e7110344514752b6fe511dd2f73c4ab | refs/heads/master | 2020-05-19T22:57:37.339258 | 2014-09-28T10:33:03 | 2014-09-28T10:33:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,520 | cpp | #include "HelloWorldScene.h"
#include "CCHttpRequest.h"
USING_NS_CC;
CCScene* HelloWorld::scene()
{
// 'scene' is an autorelease object
CCScene *scene = CCScene::create();
// 'layer' is an autorelease object
HelloWorld *layer = HelloWorld::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if ( !CCLayer::init() )
{
return false;
}
CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();
/////////////////////////////
// 2. add a menu item with "X" image, which is clicked to quit the program
// you may modify it.
// add a "close" icon to exit the progress. it's an autorelease object
CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
"CloseNormal.png",
"CloseSelected.png",
this,
menu_selector(HelloWorld::menuCloseCallback));
pCloseItem->setPosition(ccp(origin.x + visibleSize.width - pCloseItem->getContentSize().width/2 ,
origin.y + pCloseItem->getContentSize().height/2));
// create menu, it's an autorelease object
CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
pMenu->setPosition(CCPointZero);
this->addChild(pMenu, 1);
/////////////////////////////
// 3. add your codes below...
// add a label shows "Hello World"
// create and initialize a label
CCLabelTTF* pLabel = CCLabelTTF::create("Hello World", "Arial", 24);
// position the label on the center of the screen
pLabel->setPosition(ccp(origin.x + visibleSize.width/2,
origin.y + visibleSize.height - pLabel->getContentSize().height));
// add the label as a child to this layer
this->addChild(pLabel, 1);
// add "HelloWorld" splash screen"
CCSprite* pSprite = CCSprite::create("HelloWorld.png");
// position the sprite on the center of the screen
pSprite->setPosition(ccp(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));
// add the sprite as a child to this layer
this->addChild(pSprite, 0);
cocos2d::extension::CCHttpRequest *requestor = cocos2d::extension::CCHttpRequest::sharedHttpRequest();
std::string url = "http://192.168.1.12:8080/snippets/";
std::string postData = "code=print 456";
requestor->addGetTask(url, this, callfuncND_selector(HelloWorld::onHttpRequestCompleted));
requestor->addPostTask(url, postData, this, callfuncND_selector(HelloWorld::onHttpRequestCompleted));
std::vector<std::string> downloads;
downloads.push_back("http://192.168.1.12/project/image.jpg");
requestor->addDownloadTask(downloads, this, callfuncND_selector(HelloWorld::onHttpRequestCompleted));
return true;
}
void HelloWorld::menuCloseCallback(CCObject* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
CCMessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
#else
CCDirector::sharedDirector()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
#endif
}
| [
"asurada.gen@gmail.com"
] | asurada.gen@gmail.com |
568fe5827e9ec61d2393df9e5a35ecded351ab72 | 731ca8ba9d20a374a97ced40d1a0da8c9183e3b9 | /Project3/ch8_main.cpp | 34e8ace4929dc2235ae4d7f279149487dc4e7638 | [
"WTFPL"
] | permissive | guannan-he/cppLearning | 0d09949ccfd7e3b117d141cedfcf1c7cff0c30dd | 8fe3ff661afe1c814dbf44fc1ebfd9998f51eac6 | refs/heads/master | 2023-07-21T17:37:31.477331 | 2021-09-07T04:14:00 | 2021-09-07T04:14:00 | 290,625,478 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,364 | cpp | #if 0
#if 1
#include <iostream>
using namespace std;
#endif
#if 1
inline int addPonter(int i, int j) {//内联函数,递归调用编译器忽略内联
return i + j;
}
template<class anyType>//必须加在函数声明前面
void swapPos(anyType& a, anyType& b) {
anyType tmp;
tmp = a;
a = b;
b = tmp;
return;
}
template<> void swapPos<char>(char& a, char& b) {//重载函数摸板
return;
}
typedef struct {
char* name;
int len;
} annoy;
void setAnnoy(annoy& annoyMenber, string str) {
char* pt = new char[str.length() + 1];
int i = 0;
while (str[i]) {
pt[i] = str[i];
i++;
}
pt[i] = '\0';
annoyMenber.name = pt;
annoyMenber.len = i - 1;
}
int main(int argc, char* argv[]) {
cout << addPonter(1, 2) << endl;
int i = 1;
int& j = i;
cout << &i << endl;
cout << &j << endl;
///////////////////引用一次性认准不能改/////////////////////
int a = 1;
int b = 2;
int* pa = &a;
int& ra = *pa;
cout << ra << endl;
pa = &b;
cout << ra << endl;
ra = 3;
cout << ra << endl;
swapPos(a, b);
double c = 1.1;
double d = 1.2;
swapPos(c, d);
char e = 'r';
char f = 'k';
swapPos(e, f);
annoy annoying;
string str = "hello";
setAnnoy(annoying, str);
delete[] annoying.name;
//cock:goto dick;
//dick:goto cock;
//swapPos(a);
return 0;
}
#endif
#if 0
int main(int argc, char* argv[]) {
return 0;
}
#endif
#endif | [
"hgn15084095120@hotmail.com"
] | hgn15084095120@hotmail.com |
e47a2a48b8263836cb278b3f6722706cfd2389c4 | 10fa542cf8a837a2225989537d52e1572080795d | /Delphes-3.0.12/classes/DelphesClasses.h | 194b31a7a80102c592ea3dbb7627cec58786a69d | [] | no_license | kalanand/DelphesTutorial | cd28173b8a9364459807018faa0ac9c93db9775d | 816b1eac585555f41eb238b14b57742dcda5b12d | refs/heads/master | 2021-01-15T13:13:20.894890 | 2014-02-23T02:44:48 | 2014-02-23T02:44:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,477 | h | #ifndef DelphesClasses_h
#define DelphesClasses_h
/**
*
* Definition of classes to be stored in the root tree.
* Function CompareXYZ sorts objects by the variable XYZ that MUST be
* present in the data members of the root tree class of the branch.
*
* $Date: 2008-06-04 13:57:24 $
* $Revision: 1.1 $
*
*
* \author P. Demin - UCL, Louvain-la-Neuve
*
*/
// Dependencies (#includes)
#include "TRef.h"
#include "TObject.h"
#include "TRefArray.h"
#include "TLorentzVector.h"
#include "classes/SortableObject.h"
class DelphesFactory;
//---------------------------------------------------------------------------
class Event: public TObject
{
public:
Long64_t Number; // event number
Float_t ReadTime;
Float_t ProcTime;
ClassDef(Event, 1)
};
//---------------------------------------------------------------------------
class LHCOEvent: public Event
{
public:
Int_t Trigger; // trigger word
ClassDef(LHCOEvent, 1)
};
//---------------------------------------------------------------------------
class LHEFEvent: public Event
{
public:
Int_t ProcessID; // subprocess code for the event | hepup.IDPRUP
Float_t Weight; // weight for the event | hepup.XWGTUP
Float_t ScalePDF; // scale in GeV used in the calculation of the PDFs in the event | hepup.SCALUP
Float_t AlphaQED; // value of the QED coupling used in the event | hepup.AQEDUP
Float_t AlphaQCD; // value of the QCD coupling used in the event | hepup.AQCDUP
ClassDef(LHEFEvent, 2)
};
//---------------------------------------------------------------------------
class HepMCEvent: public Event
{
public:
Int_t ProcessID; // unique signal process id | signal_process_id()
Int_t MPI; // number of multi parton interactions | mpi ()
Float_t Weight; // weight for the event
Float_t Scale; // energy scale, see hep-ph/0109068 | event_scale()
Float_t AlphaQED; // QED coupling, see hep-ph/0109068 | alphaQED()
Float_t AlphaQCD; // QCD coupling, see hep-ph/0109068 | alphaQCD()
Int_t ID1; // flavour code of first parton | pdf_info()->id1()
Int_t ID2; // flavour code of second parton | pdf_info()->id2()
Float_t X1; // fraction of beam momentum carried by first parton ("beam side") | pdf_info()->x1()
Float_t X2; // fraction of beam momentum carried by second parton ("target side") | pdf_info()->x2()
Float_t ScalePDF; // Q-scale used in evaluation of PDF's (in GeV) | pdf_info()->scalePDF()
Float_t PDF1; // PDF (id1, x1, Q) | pdf_info()->pdf1()
Float_t PDF2; // PDF (id2, x2, Q) | pdf_info()->pdf2()
ClassDef(HepMCEvent, 2)
};
//---------------------------------------------------------------------------
class GenParticle: public SortableObject
{
public:
Int_t PID; // particle HEP ID number | hepevt.idhep[number]
Int_t Status; // particle status | hepevt.isthep[number]
Int_t IsPU; // 0 or 1 for particles from pile-up interactions
Int_t M1; // particle 1st mother | hepevt.jmohep[number][0] - 1
Int_t M2; // particle 2nd mother | hepevt.jmohep[number][1] - 1
Int_t D1; // particle 1st daughter | hepevt.jdahep[number][0] - 1
Int_t D2; // particle last daughter | hepevt.jdahep[number][1] - 1
Int_t Charge; // particle charge
Float_t Mass; // particle mass
Float_t E; // particle energy | hepevt.phep[number][3]
Float_t Px; // particle momentum vector (x component) | hepevt.phep[number][0]
Float_t Py; // particle momentum vector (y component) | hepevt.phep[number][1]
Float_t Pz; // particle momentum vector (z component) | hepevt.phep[number][2]
Float_t PT; // particle transverse momentum
Float_t Eta; // particle pseudorapidity
Float_t Phi; // particle azimuthal angle
Float_t Rapidity; // particle rapidity
Float_t T; // particle vertex position (t component) | hepevt.vhep[number][3]
Float_t X; // particle vertex position (x component) | hepevt.vhep[number][0]
Float_t Y; // particle vertex position (y component) | hepevt.vhep[number][1]
Float_t Z; // particle vertex position (z component) | hepevt.vhep[number][2]
static CompBase *fgCompare; //!
const CompBase *GetCompare() const { return fgCompare; }
TLorentzVector P4();
ClassDef(GenParticle, 1)
};
//---------------------------------------------------------------------------
class Vertex: public TObject
{
public:
Float_t T; // vertex position (t component)
Float_t X; // vertex position (x component)
Float_t Y; // vertex position (y component)
Float_t Z; // vertex position (z component)
ClassDef(Vertex, 1)
};
//---------------------------------------------------------------------------
class MissingET: public TObject
{
public:
Float_t MET; // mising transverse energy
Float_t Eta; // mising energy pseudorapidity
Float_t Phi; // mising energy azimuthal angle
TLorentzVector P4();
ClassDef(MissingET, 1)
};
//---------------------------------------------------------------------------
class ScalarHT: public TObject
{
public:
Float_t HT; // scalar sum of transverse momenta
ClassDef(ScalarHT, 1)
};
//---------------------------------------------------------------------------
class Rho: public TObject
{
public:
Float_t Rho; // rho energy density
Float_t Edges[2]; // pseudorapidity range edges
ClassDef(Rho, 1)
};
//---------------------------------------------------------------------------
class Weight: public TObject
{
public:
Float_t Weight; // weight for the event
ClassDef(Weight, 1)
};
//---------------------------------------------------------------------------
class Photon: public SortableObject
{
public:
Float_t PT; // photon transverse momentum
Float_t Eta; // photon pseudorapidity
Float_t Phi; // photon azimuthal angle
Float_t E; // photon energy
Float_t T; //particle arrival time of flight
Float_t EhadOverEem; // ratio of the hadronic versus electromagnetic energy deposited in the calorimeter
TRefArray Particles; // references to generated particles
static CompBase *fgCompare; //!
const CompBase *GetCompare() const { return fgCompare; }
TLorentzVector P4();
ClassDef(Photon, 2)
};
//---------------------------------------------------------------------------
class Electron: public SortableObject
{
public:
Float_t PT; // electron transverse momentum
Float_t Eta; // electron pseudorapidity
Float_t Phi; // electron azimuthal angle
Float_t T; //particle arrival time of flight
Int_t Charge; // electron charge
Float_t EhadOverEem; // ratio of the hadronic versus electromagnetic energy deposited in the calorimeter
TRef Particle; // reference to generated particle
static CompBase *fgCompare; //!
const CompBase *GetCompare() const { return fgCompare; }
TLorentzVector P4();
ClassDef(Electron, 2)
};
//---------------------------------------------------------------------------
class Muon: public SortableObject
{
public:
Float_t PT; // muon transverse momentum
Float_t Eta; // muon pseudorapidity
Float_t Phi; // muon azimuthal angle
Float_t T; //particle arrival time of flight
Int_t Charge; // muon charge
TRef Particle; // reference to generated particle
static CompBase *fgCompare; //!
const CompBase *GetCompare() const { return fgCompare; }
TLorentzVector P4();
ClassDef(Muon, 2)
};
//---------------------------------------------------------------------------
class Jet: public SortableObject
{
public:
Float_t PT; // jet transverse momentum
Float_t Eta; // jet pseudorapidity
Float_t Phi; // jet azimuthal angle
Float_t T; //particle arrival time of flight
Float_t Mass; // jet invariant mass
Float_t DeltaEta; // jet radius in pseudorapidity
Float_t DeltaPhi; // jet radius in azimuthal angle
UInt_t BTag; // 0 or 1 for a jet that has been tagged as containing a heavy quark
UInt_t TauTag; // 0 or 1 for a jet that has been tagged as a tau
Int_t Charge; // tau charge
Float_t EhadOverEem; // ratio of the hadronic versus electromagnetic energy deposited in the calorimeter
TRefArray Constituents; // references to constituents
TRefArray Particles; // references to generated particles
static CompBase *fgCompare; //!
const CompBase *GetCompare() const { return fgCompare; }
TLorentzVector P4();
// -- PileUpJetID variables ---
Int_t NCharged;
Int_t NNeutrals;
Float_t Beta;
Float_t BetaStar;
Float_t MeanSqDeltaR;
Float_t PTD;
Float_t FracPt[5];
ClassDef(Jet, 2)
};
//---------------------------------------------------------------------------
class Track: public SortableObject
{
public:
Int_t PID; // HEP ID number
Int_t Charge; // track charge
Float_t PT; // track transverse momentum
Float_t Eta; // track pseudorapidity
Float_t Phi; // track azimuthal angle
Float_t EtaOuter; // track pseudorapidity at the tracker edge
Float_t PhiOuter; // track azimuthal angle at the tracker edge
Float_t X; // track vertex position (x component)
Float_t Y; // track vertex position (y component)
Float_t Z; // track vertex position (z component)
Float_t T; // track vertex position (z component)
Float_t XOuter; // track position (x component) at the tracker edge
Float_t YOuter; // track position (y component) at the tracker edge
Float_t ZOuter; // track position (z component) at the tracker edge
Float_t TOuter; // track position (z component) at the tracker edge
TRef Particle; // reference to generated particle
static CompBase *fgCompare; //!
const CompBase *GetCompare() const { return fgCompare; }
TLorentzVector P4();
ClassDef(Track, 1)
};
//---------------------------------------------------------------------------
class Tower: public SortableObject
{
public:
Float_t ET; // calorimeter tower transverse energy
Float_t Eta; // calorimeter tower pseudorapidity
Float_t Phi; // calorimeter tower azimuthal angle
Float_t E; // calorimeter tower energy
Float_t T; //particle arrival time of flight
Float_t Eem; // calorimeter tower electromagnetic energy
Float_t Ehad; // calorimeter tower hadronic energy
Float_t Edges[4]; // calorimeter tower edges
TRefArray Particles; // references to generated particles
static CompBase *fgCompare; //!
const CompBase *GetCompare() const { return fgCompare; }
TLorentzVector P4();
ClassDef(Tower, 1)
};
//---------------------------------------------------------------------------
class Candidate: public SortableObject
{
friend class DelphesFactory;
public:
Candidate();
Int_t PID;
Int_t Status;
Int_t M1, M2, D1, D2;
Int_t Charge;
Float_t Mass;
Int_t IsPU;
Int_t IsConstituent;
UInt_t BTag;
UInt_t TauTag;
Float_t Eem;
Float_t Ehad;
Float_t Edges[4];
Float_t DeltaEta;
Float_t DeltaPhi;
TLorentzVector Momentum, Position, Area;
// PileUpJetID variables
Int_t NCharged;
Int_t NNeutrals;
Float_t Beta;
Float_t BetaStar;
Float_t MeanSqDeltaR;
Float_t PTD;
Float_t FracPt[5];
static CompBase *fgCompare; //!
const CompBase *GetCompare() const { return fgCompare; }
void AddCandidate(Candidate *object);
TObjArray *GetCandidates();
Bool_t Overlaps(const Candidate *object) const;
virtual void Copy(TObject &object) const;
virtual TObject *Clone(const char *newname = "") const;
virtual void Clear(Option_t* option = "");
private:
DelphesFactory *fFactory; //!
TObjArray *fArray; //!
void SetFactory(DelphesFactory *factory) { fFactory = factory; }
ClassDef(Candidate, 1)
};
#endif // DelphesClasses_h
| [
"jstupak@fnal.gov"
] | jstupak@fnal.gov |
94c2141cb3ef58154f115eb6c2457da41c1500aa | cdcaffa6580a621eb78981f8e8f4a58fac6b0c34 | /IrisSegmentation/IrisSegm.cpp | c293ab8979ca05c4ca02b23e52c5e935aceaacd1 | [] | no_license | MaxPappa/Iris-segmentation-occlusion-detection | 3cc54fdbc7b952d7848c55d5154acf803258d44d | b840d0d592a02c1bd968b8026ecdf78d120b5ba0 | refs/heads/master | 2021-07-19T19:20:09.491705 | 2020-09-08T22:29:07 | 2020-09-08T22:29:07 | 213,500,923 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,660 | cpp | #include "IrisSegm.hpp"
IrisSegm::IrisSegm(std::string pathToDB) : eye(Eye(pathToDB))
{
}
IrisSegm::~IrisSegm()
{
}
void IrisSegm::run()
{
Preprocessing refCor(&eye);
refCor.run();
Segmentation daug(&eye);
daug.run();
try{
Normalization norm = Normalization();
norm.run(&eye);
}
catch(const std::exception& e){
std::cerr << e.what() << '\n';
}
OcclusionDetector occDec;
occDec.run(&eye);
}
Eye* IrisSegm::getEye(){ return &eye; }
// arguments should be: "y", "/path/to/dataset/", "/path/to/output/"
int main(int argc, char** argv)
{
if(argc == 2 && strcmp(argv[1], "--help")==0)
{
std::string help = "Welcome to my IrisSegmentation project. This project has been created as a bachelor project and then improved in order to use it ";
help+="as a project for Biometrics Systems course.\nPossible arguments (write them in order) are:\n\n\n";
help+="y/n - if you have already ran this IrisSegmenter, y means that you want to overwrite previous results,";
help+="\n\tn means that you don't want it to happen, and then nothing will be done.";
help+="\n\tNOTICE: if this is your first run, or you want the output in a new folder (u should not create it manually), \n\tthen u can avoid to use this argument.\n\n\n";
help+="path/to/dataset/ - this argument is a path to the folder containing the iris dataset.\n\n\n";
help+="path/to/output/folder/ - this argument is a path to the output folder. Notice: if the folder doesn't exist, it will be created.\n";
std::cout << help << std::endl;
return 0;
}
if(argc >= 5)
{
std::cout << "Too many arguments given. Use the --help option in order to learn which are the possible arguments." << std::endl;
return 0;
}
boost::filesystem::path dstFolder(argv[3]);//"/Utiris_Segmented");
if(!(boost::filesystem::exists(dstFolder)))
{
boost::filesystem::create_directory(dstFolder);
}
else{
char ans = *argv[1];
std::tolower(ans);
switch (ans)
{
case('y'):
{
boost::filesystem::remove_all(dstFolder);
boost::filesystem::create_directory(dstFolder);
break;
}
case('n'):
{
std::cout << "Ok, so this run is going to be aborted." << std::endl;
break;
}
default:
{
std::cout << "Options are y or n, so try again." << std::endl;
break;
}
}
}
vector<boost::filesystem::path> ret;
vector<std::string> names;
string ext{".JPG"};
string path{argv[2]};
boost::filesystem::path root{path}; // root folder of the dataset
get_all(root, ext, ret, names);
boost::timer::auto_cpu_timer t; // when destructor is called the elapsed time is printed
#pragma omp parallel for shared(ret) num_threads(4)
for(int i = 0; i < ret.size(); i++){
std::cout << names[i] << " is starting now"<< std::endl;
IrisSegm irSe(ret[i].string());
cv::Mat img = *(irSe.getEye()->getImg());
// cv::namedWindow("Image Window");
irSe.run();
cv::Mat image = *(irSe.getEye()->getImg());
int c = round(image.cols/irSe.getEye()->getImgWidth()); // i'm not sure if every x,y pair should have the same coefficient c (!)
cv::circle(image, irSe.getEye()->getIrisCenter()*c, irSe.getEye()->getIrisRadius()*c, cv::Scalar(0,0,255), 3);
int xRoi = irSe.getEye()->getIrisCenter().x - irSe.getEye()->getIrisRadius();
int yRoi = irSe.getEye()->getIrisCenter().y - irSe.getEye()->getIrisRadius();
cv::Point centerPup(xRoi+irSe.getEye()->getPupilCenter().x, yRoi+irSe.getEye()->getPupilCenter().y);
cv::circle(image, centerPup*c, irSe.getEye()->getPupilRadius()*c, cv::Scalar(255,0,0), 3);
cv::Mat imgNorm = *(irSe.getEye()->getNormImg());
cv::Mat binMask = *(irSe.getEye()->getBinMask());
cv::Mat normMask = *(irSe.getEye()->getNormMask());
cv::imwrite(dstFolder.string()+"/"+names[i]+"_NORMALIZED"+ext, imgNorm);
cv::imwrite(dstFolder.string()+"/"+names[i]+"_BINARYMASK"+ext, binMask);
cv::imwrite(dstFolder.string()+"/"+names[i]+"_NORMMASK"+ext, normMask);
cv::imwrite(dstFolder.string()+"/"+names[i]+"_IMAGE"+ext, image);
std::cout << names[i] << " DONE!"<< std::endl;
imgNorm.release();
binMask.release();
normMask.release();
image.release();
}
}
| [
"massimilianopappa95@gmail.com"
] | massimilianopappa95@gmail.com |
e1d8fc643967b8a7a369101c6d6d8ed8b5f3b46a | a137bb0777b323cd99166ed6c24f43008565eae7 | /network/C++/CoProcessor/CoProcessor/main.cpp | 816ada37afba082ffafab0fc74b66edaee8a1c43 | [] | no_license | MclvAdmin/Mclv2012 | 1ad963b5ac73c181fb50e94e4bdc56873a4d7347 | 8aea886f67d49b6fdbedbc1715debfd3d29f1c90 | refs/heads/master | 2020-04-13T18:17:47.595045 | 2012-02-14T05:34:14 | 2012-02-14T05:34:14 | 3,423,435 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,194 | cpp | #include <WinSock.h>
#include <Windows.h>
#include <iostream>
#include <list>
#include <deque>
#include <map>
#include <vector>
using namespace std;
bool _connected = false;
char* ip_address = "10.11.55.6";
int port = 1140;
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
int pow2(int val){
int ans = 1;
for(int i = 0; i < val; ++i){
ans *= 2;
}
return ans;
}
#include "Packet.h"
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
class NetObject{
public:
unsigned short address;
NetObject(unsigned char pwm){}
//IMPORTANT: ANY NETOBJECT METHODS MUST BE PROTOTYPED HERE BEFORE THEY CAN WORK
virtual void recieve(unsigned char* data){}
virtual void set(double val){}
virtual double getY(){return 0;}
virtual bool getButtonState(int val){return 0;}
};
map<unsigned short, NetObject*> _hardware_elements;
//-----------------------------------------------------------------------------------
#include "Network.h"
#include "Hardware.h"
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
DWORD WINAPI start_server(LPVOID params){
_network_interface.SERVER();
return -1;
}
void init_hardware(){
//ASSIGN HARDWARE ADDRESSES HERE
new Joystick(1);
new Joystick(2);
//TWO GEESE WITH ONE STONE
for(int i = 1; i <= 4; ++i){
new Jaguar(i);
}
unsigned short p = 5;
p <<= 8;
p += 1;
while(1){
_hardware_elements[p]->getY();
Sleep(1000);
}
}
DWORD WINAPI DRIVE(LPVOID lpParam){
#define leftjoy 1
#define rightjoy 2
#define startjags 3 //THE DRIVE JAGS IN CONFIGURATION: LEFT LEFT RIGHT RIGHT
while(_connected){
double left = _hardware_elements[leftjoy]->getY();
double right = _hardware_elements[rightjoy]->getY();
for(int i = startjags; i <= startjags+1; ++i){
_hardware_elements[i]->set(left);
_hardware_elements[i+2]->set(right);
}
//RECORDING
bool _recording = false;
deque<double*> left_record, right_record;
while(_recording){
//@TODO: CLEAR ANY MEMORY PREVIOUSLY USED
while(!right_record.empty()){
free(left_record[0]);
free(right_record[0]);
left_record.pop_front();
right_record.pop_front();
}
double* d = (double*) calloc(1024, 8); // ENOUGH FOR 1024 DOUBLES
double* b = (double*) calloc(1024, 8); // MEMORY LEAK IF NOT CLEANED UP
left_record.push_back(d);
right_record.push_back(b);
for(int j = 0; j < 1024; ++j){
d[j] = _hardware_elements[leftjoy]->getY();
b[j] = _hardware_elements[rightjoy]->getY(); // 16 KB/s * 60 seconds = 960 KB per minute
//Sleep(20); ALREADY LIMITED BY GET METHODS
}
_recording = _hardware_elements[leftjoy]->getButtonState(1);
}
}
return 0;
}
int main(){
HANDLE _server_thread = CreateThread(NULL,0,start_server,NULL,0,NULL);
while(!_connected) Sleep(200); // WAIT FOR CLIENT
init_hardware(); //@TODO INITIALIZE OBJECTS *AFTER* CLIENT CONNECTION (and reinitialize after connection lost/reestablished
HANDLE heartbeat = CreateThread(0,0,HEARTBEAT,0,0,0);
//HANDLE _drive_thread = CreateThread(NULL,0,DRIVE,NULL,0,NULL);
/*
LARGE_INTEGER _count;
LARGE_INTEGER _freq; //Frequency of one second
QueryPerformanceFrequency(&_freq);
DWORD count = 0;
DWORD freq = _freq.LowPart;
DWORD _tStart = 0;
unsigned char ping[] = {5,0,0,0};
Packet status(ping);
while(1){
QueryPerformanceCounter(&_count);
count = _count.LowPart;
_tStart = count/freq;
cin.ignore();
unsigned char data[] = {3,1,1};
Packet temp(data);
int send = count;
temp.AddData(send);
Packet stat = status;
temp.Finalize();
stat.Finalize();
_network_interface.SendPacket(&temp);
_network_interface.SendPacket(&stat); //Automate the status packet send.
}*/
cout << "YO";
Sleep(999999);
} | [
"computeralex@gmail.com"
] | computeralex@gmail.com |
65190637f4a7ec94df9176e4a8ef628c354a78b6 | f53da1d0c7bcff51d05f64db69c26363bc9f386c | /src/protocol.cpp | fe738a57fdac98a82b15a1e49ba0264c4d731417 | [
"MIT"
] | permissive | SafeNodeNetwork/safenode | e550ac16316577537872924fa62204e280aef519 | 72c830f7eeb59b9c5c959a2745da9d37471a27a7 | refs/heads/master | 2020-03-16T11:16:16.358309 | 2018-05-08T18:44:21 | 2018-05-08T18:44:21 | 132,645,279 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,887 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "protocol.h"
#include "util.h"
#include "utilstrencodings.h"
#ifndef WIN32
# include <arpa/inet.h>
#endif
namespace NetMsgType {
const char *VERSION="version";
const char *VERACK="verack";
const char *ADDR="addr";
const char *INV="inv";
const char *GETDATA="getdata";
const char *MERKLEBLOCK="merkleblock";
const char *GETBLOCKS="getblocks";
const char *GETHEADERS="getheaders";
const char *TX="tx";
const char *HEADERS="headers";
const char *BLOCK="block";
const char *GETADDR="getaddr";
const char *MEMPOOL="mempool";
const char *PING="ping";
const char *PONG="pong";
const char *ALERT="alert";
const char *NOTFOUND="notfound";
const char *FILTERLOAD="filterload";
const char *FILTERADD="filteradd";
const char *FILTERCLEAR="filterclear";
const char *REJECT="reject";
const char *SENDHEADERS="sendheaders";
// SafeNode message types
const char *TXLOCKREQUEST="ix";
const char *TXLOCKVOTE="txlvote";
const char *SPORK="spork";
const char *GETSPORKS="getsporks";
const char *SAFENODEPAYMENTVOTE="mnw";
const char *SAFENODEPAYMENTBLOCK="mnwb";
const char *SAFENODEPAYMENTSYNC="mnget";
const char *MNBUDGETSYNC="mnvs"; // depreciated since 12.1
const char *MNBUDGETVOTE="mvote"; // depreciated since 12.1
const char *MNBUDGETPROPOSAL="mprop"; // depreciated since 12.1
const char *MNBUDGETFINAL="fbs"; // depreciated since 12.1
const char *MNBUDGETFINALVOTE="fbvote"; // depreciated since 12.1
const char *MNQUORUM="mn quorum"; // not implemented
const char *MNANNOUNCE="mnb";
const char *MNPING="mnp";
const char *DSACCEPT="dsa";
const char *DSVIN="dsi";
const char *DSFINALTX="dsf";
const char *DSSIGNFINALTX="dss";
const char *DSCOMPLETE="dsc";
const char *DSSTATUSUPDATE="dssu";
const char *DSTX="dstx";
const char *DSQUEUE="dsq";
const char *DSEG="dseg";
const char *SYNCSTATUSCOUNT="ssc";
const char *MNGOVERNANCESYNC="govsync";
const char *MNGOVERNANCEOBJECT="govobj";
const char *MNGOVERNANCEOBJECTVOTE="govobjvote";
const char *MNVERIFY="mnv";
};
static const char* ppszTypeName[] =
{
"ERROR", // Should never occur
NetMsgType::TX,
NetMsgType::BLOCK,
"filtered block", // Should never occur
// SafeNode message types
// NOTE: include non-implmented here, we must keep this list in sync with enum in protocol.h
NetMsgType::TXLOCKREQUEST,
NetMsgType::TXLOCKVOTE,
NetMsgType::SPORK,
NetMsgType::SAFENODEPAYMENTVOTE,
NetMsgType::SAFENODEPAYMENTBLOCK, // reusing, was MNSCANERROR previousely, was NOT used in 12.0, we need this for inv
NetMsgType::MNBUDGETVOTE, // depreciated since 12.1
NetMsgType::MNBUDGETPROPOSAL, // depreciated since 12.1
NetMsgType::MNBUDGETFINAL, // depreciated since 12.1
NetMsgType::MNBUDGETFINALVOTE, // depreciated since 12.1
NetMsgType::MNQUORUM, // not implemented
NetMsgType::MNANNOUNCE,
NetMsgType::MNPING,
NetMsgType::DSTX,
NetMsgType::MNGOVERNANCEOBJECT,
NetMsgType::MNGOVERNANCEOBJECTVOTE,
NetMsgType::MNVERIFY,
};
/** All known message types. Keep this in the same order as the list of
* messages above and in protocol.h.
*/
const static std::string allNetMessageTypes[] = {
NetMsgType::VERSION,
NetMsgType::VERACK,
NetMsgType::ADDR,
NetMsgType::INV,
NetMsgType::GETDATA,
NetMsgType::MERKLEBLOCK,
NetMsgType::GETBLOCKS,
NetMsgType::GETHEADERS,
NetMsgType::TX,
NetMsgType::HEADERS,
NetMsgType::BLOCK,
NetMsgType::GETADDR,
NetMsgType::MEMPOOL,
NetMsgType::PING,
NetMsgType::PONG,
NetMsgType::ALERT,
NetMsgType::NOTFOUND,
NetMsgType::FILTERLOAD,
NetMsgType::FILTERADD,
NetMsgType::FILTERCLEAR,
NetMsgType::REJECT,
NetMsgType::SENDHEADERS,
// SafeNode message types
// NOTE: do NOT include non-implmented here, we want them to be "Unknown command" in ProcessMessage()
NetMsgType::TXLOCKREQUEST,
NetMsgType::TXLOCKVOTE,
NetMsgType::SPORK,
NetMsgType::GETSPORKS,
NetMsgType::SAFENODEPAYMENTVOTE,
// NetMsgType::SAFENODEPAYMENTBLOCK, // there is no message for this, only inventory
NetMsgType::SAFENODEPAYMENTSYNC,
NetMsgType::MNANNOUNCE,
NetMsgType::MNPING,
NetMsgType::DSACCEPT,
NetMsgType::DSVIN,
NetMsgType::DSFINALTX,
NetMsgType::DSSIGNFINALTX,
NetMsgType::DSCOMPLETE,
NetMsgType::DSSTATUSUPDATE,
NetMsgType::DSTX,
NetMsgType::DSQUEUE,
NetMsgType::DSEG,
NetMsgType::SYNCSTATUSCOUNT,
NetMsgType::MNGOVERNANCESYNC,
NetMsgType::MNGOVERNANCEOBJECT,
NetMsgType::MNGOVERNANCEOBJECTVOTE,
NetMsgType::MNVERIFY,
};
const static std::vector<std::string> allNetMessageTypesVec(allNetMessageTypes, allNetMessageTypes+ARRAYLEN(allNetMessageTypes));
CMessageHeader::CMessageHeader(const MessageStartChars& pchMessageStartIn)
{
memcpy(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE);
memset(pchCommand, 0, sizeof(pchCommand));
nMessageSize = -1;
nChecksum = 0;
}
CMessageHeader::CMessageHeader(const MessageStartChars& pchMessageStartIn, const char* pszCommand, unsigned int nMessageSizeIn)
{
memcpy(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE);
memset(pchCommand, 0, sizeof(pchCommand));
strncpy(pchCommand, pszCommand, COMMAND_SIZE);
nMessageSize = nMessageSizeIn;
nChecksum = 0;
}
std::string CMessageHeader::GetCommand() const
{
return std::string(pchCommand, pchCommand + strnlen(pchCommand, COMMAND_SIZE));
}
bool CMessageHeader::IsValid(const MessageStartChars& pchMessageStartIn) const
{
// Check start string
if (memcmp(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE) != 0)
return false;
// Check the command string for errors
for (const char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)
{
if (*p1 == 0)
{
// Must be all zeros after the first zero
for (; p1 < pchCommand + COMMAND_SIZE; p1++)
if (*p1 != 0)
return false;
}
else if (*p1 < ' ' || *p1 > 0x7E)
return false;
}
// Message size
if (nMessageSize > MAX_SIZE)
{
LogPrintf("CMessageHeader::IsValid(): (%s, %u bytes) nMessageSize > MAX_SIZE\n", GetCommand(), nMessageSize);
return false;
}
return true;
}
CAddress::CAddress() : CService()
{
Init();
}
CAddress::CAddress(CService ipIn, uint64_t nServicesIn) : CService(ipIn)
{
Init();
nServices = nServicesIn;
}
void CAddress::Init()
{
nServices = NODE_NETWORK;
nTime = 100000000;
}
CInv::CInv()
{
type = 0;
hash.SetNull();
}
CInv::CInv(int typeIn, const uint256& hashIn)
{
type = typeIn;
hash = hashIn;
}
CInv::CInv(const std::string& strType, const uint256& hashIn)
{
unsigned int i;
for (i = 1; i < ARRAYLEN(ppszTypeName); i++)
{
if (strType == ppszTypeName[i])
{
type = i;
break;
}
}
if (i == ARRAYLEN(ppszTypeName))
throw std::out_of_range(strprintf("CInv::CInv(string, uint256): unknown type '%s'", strType));
hash = hashIn;
}
bool operator<(const CInv& a, const CInv& b)
{
return (a.type < b.type || (a.type == b.type && a.hash < b.hash));
}
bool CInv::IsKnownType() const
{
return (type >= 1 && type < (int)ARRAYLEN(ppszTypeName));
}
const char* CInv::GetCommand() const
{
if (!IsKnownType())
throw std::out_of_range(strprintf("CInv::GetCommand(): type=%d unknown type", type));
return ppszTypeName[type];
}
std::string CInv::ToString() const
{
return strprintf("%s %s", GetCommand(), hash.ToString());
}
const std::vector<std::string> &getAllNetMessageTypes()
{
return allNetMessageTypesVec;
}
| [
"safenode@protonmail.com"
] | safenode@protonmail.com |
bb0812c2286f825e10d7d5d34a2d678a5dfe09b7 | 2a5db4d9e51d29445f72d1ffd3f98609523b082d | /media-driver/media_driver/linux/gen8/ddi/media_libva_caps_g8.cpp | 6b8e4a211574d30a9caa0ecc0fa75eaef9decfe6 | [
"BSD-3-Clause",
"MIT"
] | permissive | mintaka33/media | 19f26239aee1d889860867a536024ffc137c2776 | 4ab1435ef3b3269ff9c0fa71072c3f81275a4b9d | refs/heads/master | 2021-05-11T04:01:48.314310 | 2018-02-02T03:43:36 | 2018-02-02T03:43:36 | 117,930,190 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,794 | cpp | /*
* Copyright (c) 2017, Intel Corporation
*
* 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 media_libva_caps_g8.cpp
//! \brief This file implements the C++ class/interface for gen8 media capbilities.
//!
#include "codec_def_encode_avc.h"
#include "media_libva_util.h"
#include "media_libva.h"
#include "media_libva_caps_g8.h"
#include "media_libva_caps_factory.h"
VAStatus MediaLibvaCapsG8::GetPlatformSpecificAttrib(
VAProfile profile,
VAEntrypoint entrypoint,
VAConfigAttribType type,
uint32_t *value)
{
DDI_CHK_NULL(value, "Null pointer", VA_STATUS_ERROR_INVALID_PARAMETER);
VAStatus status = VA_STATUS_SUCCESS;
switch ((int32_t)type)
{
case VAConfigAttribEncMaxRefFrames:
{
if (entrypoint == VAEntrypointEncSliceLP || !IsHevcProfile(profile))
{
status = VA_STATUS_ERROR_INVALID_PARAMETER;
}
else
{
*value = 1 | (1 << 16);
}
break;
}
case VAConfigAttribDecProcessing:
{
*value = VA_DEC_PROCESSING_NONE;
break;
}
case VAConfigAttribEncIntraRefresh:
{
if(IsAvcProfile(profile))
{
*value = VA_ENC_INTRA_REFRESH_ROLLING_COLUMN |
VA_ENC_INTRA_REFRESH_ROLLING_ROW;
}
else
{
*value = VA_ENC_INTRA_REFRESH_NONE;
}
break;
}
case VAConfigAttribEncROI:
{
if (entrypoint == VAEntrypointEncSliceLP)
{
status = VA_STATUS_ERROR_INVALID_PARAMETER;
}
else if (IsAvcProfile(profile))
{
*value = ENCODE_DP_AVC_MAX_ROI_NUMBER;
}
else
{
*value = 0;
}
break;
}
case VAConfigAttribCustomRoundingControl:
{
if (IsAvcProfile(profile))
{
*value = 1;
}
else
{
*value = 0;
}
break;
}
default:
status = VA_STATUS_ERROR_INVALID_PARAMETER;
break;
}
return status;
}
VAStatus MediaLibvaCapsG8::LoadProfileEntrypoints()
{
VAStatus status = VA_STATUS_SUCCESS;
status = LoadAvcDecProfileEntrypoints();
DDI_CHK_RET(status, "Failed to initialize Caps!");
status = LoadAvcEncProfileEntrypoints();
DDI_CHK_RET(status, "Failed to initialize Caps!");
status = LoadMpeg2DecProfileEntrypoints();
DDI_CHK_RET(status, "Failed to initialize Caps!");
status = LoadMpeg2EncProfileEntrypoints();
DDI_CHK_RET(status, "Failed to initialize Caps!");
status = LoadVc1DecProfileEntrypoints();
DDI_CHK_RET(status, "Failed to initialize Caps!");
status = LoadJpegDecProfileEntrypoints();
DDI_CHK_RET(status, "Failed to initialize Caps!");
status = LoadJpegEncProfileEntrypoints();
DDI_CHK_RET(status, "Failed to initialize Caps!");
status = LoadVp8DecProfileEntrypoints();
DDI_CHK_RET(status, "Failed to initialize Caps!");
status = LoadVp8EncProfileEntrypoints();
DDI_CHK_RET(status, "Failed to initialize Caps!");
status = LoadVp9DecProfileEntrypoints();
DDI_CHK_RET(status, "Failed to initialize Caps!");
status = LoadVp9EncProfileEntrypoints();
DDI_CHK_RET(status, "Failed to initialize Caps!");
status = LoadNoneProfileEntrypoints();
DDI_CHK_RET(status, "Failed to initialize Caps!");
return status;
}
VAStatus MediaLibvaCapsG8::QueryAVCROIMaxNum(uint32_t rcMode, int32_t *maxNum, bool *isRoiInDeltaQP)
{
DDI_CHK_NULL(maxNum, "Null pointer", VA_STATUS_ERROR_INVALID_PARAMETER);
DDI_CHK_NULL(isRoiInDeltaQP, "Null pointer", VA_STATUS_ERROR_INVALID_PARAMETER);
*maxNum = ENCODE_DP_AVC_MAX_ROI_NUMBER;
*isRoiInDeltaQP = false;
return VA_STATUS_SUCCESS;
}
VAStatus MediaLibvaCapsG8::GetMbProcessingRateEnc(
MEDIA_FEATURE_TABLE *skuTable,
uint32_t tuIdx,
uint32_t codecMode,
bool vdencActive,
uint32_t *mbProcessingRatePerSec)
{
DDI_CHK_NULL(skuTable, "Null pointer", VA_STATUS_ERROR_INVALID_PARAMETER);
DDI_CHK_NULL(mbProcessingRatePerSec, "Null pointer", VA_STATUS_ERROR_INVALID_PARAMETER);
uint32_t gtIdx = 0;
if (MEDIA_IS_SKU(skuTable, FtrGT1))
{
gtIdx = 3;
}
else if (MEDIA_IS_SKU(skuTable, FtrGT1_5))
{
gtIdx = 2;
}
else if (MEDIA_IS_SKU(skuTable, FtrGT2))
{
gtIdx = 1;
}
else if (MEDIA_IS_SKU(skuTable, FtrGT3))
{
gtIdx = 0;
}
else
{
return VA_STATUS_ERROR_INVALID_PARAMETER;
}
if (MEDIA_IS_SKU(skuTable, FtrULX))
{
const uint32_t mbRate[7][4] =
{
// GT3 | GT2 | GT1.5 | GT1
{ 0, 750000, 750000, 676280 },
{ 0, 750000, 750000, 661800 },
{ 0, 750000, 750000, 640000 },
{ 0, 750000, 750000, 640000 },
{ 0, 750000, 750000, 640000 },
{ 0, 416051, 416051, 317980 },
{ 0, 214438, 214438, 180655 }
};
if (gtIdx == 0)
{
return VA_STATUS_ERROR_INVALID_PARAMETER;
}
*mbProcessingRatePerSec = mbRate[tuIdx][gtIdx];
}
else if (MEDIA_IS_SKU(skuTable, FtrULT))
{
const uint32_t mbRate[7][4] =
{
// GT3 | GT2 | GT1.5 | GT1
{ 1544090, 1544090, 1029393, 676280 },
{ 1462540, 1462540, 975027, 661800 },
{ 1165381, 1165381, 776921, 640000 },
{ 1165381, 1165381, 776921, 640000 },
{ 1165381, 1165381, 776921, 640000 },
{ 624076, 624076, 416051, 317980 },
{ 321657, 321657, 214438, 180655 }
};
*mbProcessingRatePerSec = mbRate[tuIdx][gtIdx];
}
else
{
const uint32_t mbRate[7][4] =
{
// GT3 | GT2 | GT1.5 | GT1
{ 1544090, 1544090, 1029393, 676280 },
{ 1462540, 1462540, 975027, 661800 },
{ 1165381, 1165381, 776921, 640000 },
{ 1165381, 1165381, 776921, 640000 },
{ 1165381, 1165381, 776921, 640000 },
{ 624076, 624076, 416051, 317980 },
{ 321657, 321657, 214438, 180655 }
};
*mbProcessingRatePerSec = mbRate[tuIdx][gtIdx];
}
return VA_STATUS_SUCCESS;
}
extern template class MediaLibvaCapsFactory<MediaLibvaCaps, DDI_MEDIA_CONTEXT>;
static bool bdwRegistered = MediaLibvaCapsFactory<MediaLibvaCaps, DDI_MEDIA_CONTEXT>::
RegisterCaps<MediaLibvaCapsG8>((uint32_t)IGFX_BROADWELL);
| [
"mintaka33@outlook.com"
] | mintaka33@outlook.com |
37874a3432f30d0d6e97712f9d17ca0a0fd5e920 | 7f8b6d898d0f3a7927e20ae03240dce40bf07f2d | /백준/DFS/14501_퇴사.cpp | 2e70045762443de0d6076df1d605b7a811fe4c5e | [] | no_license | sihyun98/2020Algorithm | 0f08e1139a47d55188f9d2addc9b215533b4b19a | 19c9326e6c800a9e1b43725cbb275721807d0869 | refs/heads/master | 2020-12-12T11:19:01.209753 | 2020-10-15T18:07:14 | 2020-10-15T18:07:14 | 234,115,073 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 408 | cpp | #include <iostream>
using namespace std;
int time[15];
int pay[15];
int N;
int maximum = 0;
void profit(int d, int t) {
if (d >= N) {
if (maximum < t) {
maximum = t;
}
return;
}
if (d + time[d] <= N) {
profit(d + time[d], t + pay[d]);
}
profit(d + 1, t);
}
int main() {
cin >> N;
for (int i = 0; i < N; i++) {
cin >> time[i] >> pay[i];
}
profit(0, 0);
cout << maximum;
return 0;
} | [
"sihyun98@live.cau.ac.kr"
] | sihyun98@live.cau.ac.kr |
e357a08e0e9a0114680068d54a3f4aa0e3ca04b0 | 00192278a0fdaa820cdfb574347b9b3a1f9c56d7 | /include/ply/PlyTypes.hpp | 830a003e82635b20bd375a4025ee9548f82971af | [
"Apache-2.0"
] | permissive | jmitchell24/cpp-utility-lib | a27582d753a09e0bce68abd791c03e5c49f945cb | 76e7bae9f07b741c409a282604a999ab86fc0702 | refs/heads/master | 2021-01-12T16:33:23.274501 | 2017-01-07T21:51:25 | 2017-01-07T21:51:25 | 71,411,079 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 435 | hpp | #pragma once
#include "../string/Segment.hpp"
#include <iostream>
namespace util
{
namespace ply
{
typedef char Char;
typedef std::basic_string <Char> String;
typedef std::basic_ostream <Char> Ostream;
typedef std::basic_ofstream<Char> Ofstream;
typedef std::basic_ifstream<Char> Ifstream;
typedef SegmentT <Char> Segment;
typedef StringT <Char> SegString;
}
}
| [
"james.mitchell.dev@gmail.com"
] | james.mitchell.dev@gmail.com |
3c6df2fc0b2a480a1dad23087ed914c11e6168fc | 2abf706df55f5f73c5df95ea2f7c1b51bc73a784 | /AudioEngine.h | a7cc9262ff85819696376e1ce2e037b47cc69e24 | [] | no_license | skyshaver/FMODEngine | 579b67e31c1b3a6800ebccf4fce4bcff66dc474f | 7567e57c722e3266bf91a39ae405b109ab609647 | refs/heads/master | 2022-11-27T13:22:10.763303 | 2020-08-03T18:59:40 | 2020-08-03T18:59:40 | 283,329,724 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,350 | h | #pragma once
#include <string>
#include <unordered_map>
#include <vector>
#include <cmath>
#include <iostream>
#include <memory>
#include "fmod_studio.hpp"
#include "fmod.hpp"
#include "glm/glm.hpp"
struct Implementation
{
Implementation();
~Implementation();
void update();
FMOD::Studio::System* studioSystem;
FMOD::System* system;
int nextChannelId = 0;
using SoundMap = std::unordered_map<std::string, FMOD::Sound*>;
using ChannelMap = std::unordered_map<int, FMOD::Channel*>;
using EventMap = std::unordered_map<std::string, FMOD::Studio::EventInstance*>;
using BankMap = std::unordered_map<std::string, FMOD::Studio::Bank*>;
BankMap banks;
EventMap events;
SoundMap sounds;
ChannelMap channels;
};
class AudioEngine
{
public:
static void init();
static void update();
//static void shutdown();
static int errorCheck(FMOD_RESULT result);
void loadBank(const std::string& bankName, FMOD_STUDIO_LOAD_BANK_FLAGS flags);
void loadEvent(const std::string& eventName);
void loadSound(const std::string& soundName, bool is3D = false, bool isLooping = false, bool isStream = false);
void unLoadSound(const std::string& strSoundName);
// void set3dListenerAndOrientation(const Vector3& vPos = Vector3{ 0, 0, 0 }, float fVolumedB = 0.0f);
int playSound(const std::string& soundName, float volumedB = 0.0f, const glm::vec3 pos = { 0, 0, 0 });
void playEvent(const std::string& eventName);
// void stopChannel(int nChannelId);
void stopEvent(const std::string& eventName, bool isImmediate = false);
void geteventParameter(const std::string& eventName, const std::string& eventParameter, float* parameter);
void setEventParameter(const std::string& eventName, const std::string& parameterName, float value);
// void stopAllChannels();
void setChannel3dPosition(int channelId, const glm::vec3& pos);
void setChannelVolume(int channelId, float volumedB);
// bool isPlaying(int nChannelId) const;
bool isEventPlaying(const std::string& eventName) const;
float dBToVolume(float dB);
float volumeTodB(float volume);
unsigned int getSoundLengthInMS(const std::string& soundName);
FMOD_VECTOR vectorToFmod(const glm::vec3& pos);
//static std::unique_ptr<Implementation> implementation;
};
| [
"skyshaver@me.com"
] | skyshaver@me.com |
08af35721597ef7ac788762d7345c0afa92bf87a | a8d0bb2f9a42320be0aa5e383f1ce67e5e44d2c6 | /Datastructures/002 Arrays/007 maxSumInConfiguration.cpp | 2f777645311e04f929403f38fe222b2d9bc71cc4 | [] | no_license | camperjett/DSA_dups | f5728e06f1874bafbaf8561752e8552fee2170fa | f20fb4be1463398f568dbf629a597d8d0ae92e8f | refs/heads/main | 2023-04-19T18:18:55.674116 | 2021-05-15T12:51:21 | 2021-05-15T12:51:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 537 | cpp | #include<bits/stdc++.h>
using namespace std;
int max_sum(int A[],int N)
{
//Your code here
int currSum(0), sumArray(0);
for(int i=0; i<N; i++){
currSum+= i*A[i];
sumArray+=A[i];
}
int ans = currSum;
for(int i=0; i<N-1; i++){
int temp = currSum - sumArray+N*A[i];
ans = max(ans, temp);
currSum = temp;
}
return ans;
}
int main(){
int n; cin>>n;
int* arr = new int[n];
for(int i=0; i<n; i++)
cin>>arr[i];
cout<<max_sum(arr, n);
return 0;
}
| [
"vasubansal1998@gmail.com"
] | vasubansal1998@gmail.com |
589e311c5c3c82c00b5710744519a8a570b0b127 | 8af4126a93b7227bcf82037c98982a62fadfd847 | /include/google/protobuf/stubs/port.h | 328258b7c052e7a9e07f63c4681eefde97b135cf | [
"MIT"
] | permissive | Elkantor/sc2_project_bot | c93fe37c1399871b468b7eacc906748ec79a3bf6 | b66506e8329511a215f944abcb695cc373bfebfe | refs/heads/master | 2020-04-10T14:02:46.502354 | 2018-03-23T14:10:17 | 2018-03-23T14:10:17 | 124,276,724 | 0 | 1 | MIT | 2018-03-23T13:11:06 | 2018-03-07T18:22:09 | C++ | UTF-8 | C++ | false | false | 12,504 | h | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef GOOGLE_PROTOBUF_STUBS_PORT_H_
#define GOOGLE_PROTOBUF_STUBS_PORT_H_
#include <assert.h>
#include <stdlib.h>
#include <cstddef>
#include <string>
#include <string.h>
#if defined(__osf__)
// Tru64 lacks stdint.h, but has inttypes.h which defines a superset of
// what stdint.h would define.
#include <inttypes.h>
#elif !defined(_MSC_VER)
#include <stdint.h>
#endif
#undef PROTOBUF_LITTLE_ENDIAN
#ifdef _WIN32
// Assuming windows is always little-endian.
// TODO(xiaofeng): The PROTOBUF_LITTLE_ENDIAN is not only used for
// optimization but also for correctness. We should define an
// different macro to test the big-endian code path in coded_stream.
#if !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST)
#define PROTOBUF_LITTLE_ENDIAN 1
#endif
#if _MSC_VER >= 1300 && !defined(__INTEL_COMPILER)
// If MSVC has "/RTCc" set, it will complain about truncating casts at
// runtime. This file contains some intentional truncating casts.
#pragma runtime_checks("c", off)
#endif
#else
#include <sys/param.h> // __BYTE_ORDER
#if ((defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__)) || \
(defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN)) && \
!defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST)
#define PROTOBUF_LITTLE_ENDIAN 1
#endif
#endif
#if defined(_MSC_VER) && defined(PROTOBUF_USE_DLLS)
#ifdef LIBPROTOBUF_EXPORTS
#define LIBPROTOBUF_EXPORT __declspec(dllexport)
#else
#define LIBPROTOBUF_EXPORT __declspec(dllimport)
#endif
#ifdef LIBPROTOC_EXPORTS
#define LIBPROTOC_EXPORT __declspec(dllexport)
#else
#define LIBPROTOC_EXPORT __declspec(dllimport)
#endif
#else
#define LIBPROTOBUF_EXPORT
#define LIBPROTOC_EXPORT
#endif
// These #includes are for the byte swap functions declared later on.
#ifdef _MSC_VER
#include <stdlib.h> // NOLINT(build/include)
#elif defined(__APPLE__)
#include <libkern/OSByteOrder.h>
#elif defined(__GLIBC__) || defined(__CYGWIN__)
#include <byteswap.h> // IWYU pragma: export
#endif
// ===================================================================
// from google3/base/port.h
namespace google {
namespace protobuf {
typedef unsigned int uint;
#ifdef _MSC_VER
typedef signed __int8 int8;
typedef __int16 int16;
typedef __int32 int32;
typedef __int64 int64;
typedef unsigned __int8 uint8;
typedef unsigned __int16 uint16;
typedef unsigned __int32 uint32;
typedef unsigned __int64 uint64;
#else
typedef signed char int8;
typedef short int16;
typedef int int32;
typedef long long int64;
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned int uint32;
typedef unsigned long long uint64;
#endif
// long long macros to be used because gcc and vc++ use different suffixes,
// and different size specifiers in format strings
#undef GOOGLE_LONGLONG
#undef GOOGLE_ULONGLONG
#undef GOOGLE_LL_FORMAT
#ifdef _MSC_VER
#define GOOGLE_LONGLONG(x) x##I64
#define GOOGLE_ULONGLONG(x) x##UI64
#define GOOGLE_LL_FORMAT "I64" // As in printf("%I64d", ...)
#else
#define GOOGLE_LONGLONG(x) x##LL
#define GOOGLE_ULONGLONG(x) x##ULL
#define GOOGLE_LL_FORMAT "ll" // As in "%lld". Note that "q" is poor form also.
#endif
static const int32 kint32max = 0x7FFFFFFF;
static const int32 kint32min = -kint32max - 1;
static const int64 kint64max = GOOGLE_LONGLONG(0x7FFFFFFFFFFFFFFF);
static const int64 kint64min = -kint64max - 1;
static const uint32 kuint32max = 0xFFFFFFFFu;
static const uint64 kuint64max = GOOGLE_ULONGLONG(0xFFFFFFFFFFFFFFFF);
// -------------------------------------------------------------------
// Annotations: Some parts of the code have been annotated in ways that might
// be useful to some compilers or tools, but are not supported universally.
// You can #define these annotations yourself if the default implementation
// is not right for you.
#ifndef GOOGLE_ATTRIBUTE_ALWAYS_INLINE
#if defined(__GNUC__) && (__GNUC__ > 3 ||(__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
// For functions we want to force inline.
// Introduced in gcc 3.1.
#define GOOGLE_ATTRIBUTE_ALWAYS_INLINE __attribute__ ((always_inline))
#else
// Other compilers will have to figure it out for themselves.
#define GOOGLE_ATTRIBUTE_ALWAYS_INLINE
#endif
#endif
#ifndef GOOGLE_ATTRIBUTE_NOINLINE
#if defined(__GNUC__) && (__GNUC__ > 3 ||(__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
// For functions we want to force not inline.
// Introduced in gcc 3.1.
#define GOOGLE_ATTRIBUTE_NOINLINE __attribute__ ((noinline))
#elif defined(_MSC_VER) && (_MSC_VER >= 1400)
// Seems to have been around since at least Visual Studio 2005
#define GOOGLE_ATTRIBUTE_NOINLINE __declspec(noinline)
#else
// Other compilers will have to figure it out for themselves.
#define GOOGLE_ATTRIBUTE_NOINLINE
#endif
#endif
#ifndef GOOGLE_ATTRIBUTE_NORETURN
#ifdef __GNUC__
// Tell the compiler that a given function never returns.
#define GOOGLE_ATTRIBUTE_NORETURN __attribute__((noreturn))
#else
#define GOOGLE_ATTRIBUTE_NORETURN
#endif
#endif
#ifndef GOOGLE_ATTRIBUTE_DEPRECATED
#ifdef __GNUC__
// If the method/variable/type is used anywhere, produce a warning.
#define GOOGLE_ATTRIBUTE_DEPRECATED __attribute__((deprecated))
#else
#define GOOGLE_ATTRIBUTE_DEPRECATED
#endif
#endif
#ifndef GOOGLE_PREDICT_TRUE
#ifdef __GNUC__
// Provided at least since GCC 3.0.
#define GOOGLE_PREDICT_TRUE(x) (__builtin_expect(!!(x), 1))
#else
#define GOOGLE_PREDICT_TRUE(x) (x)
#endif
#endif
#ifndef GOOGLE_PREDICT_FALSE
#ifdef __GNUC__
// Provided at least since GCC 3.0.
#define GOOGLE_PREDICT_FALSE(x) (__builtin_expect(x, 0))
#else
#define GOOGLE_PREDICT_FALSE(x) (x)
#endif
#endif
// Delimits a block of code which may write to memory which is simultaneously
// written by other threads, but which has been determined to be thread-safe
// (e.g. because it is an idempotent write).
#ifndef GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN
#define GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN()
#endif
#ifndef GOOGLE_SAFE_CONCURRENT_WRITES_END
#define GOOGLE_SAFE_CONCURRENT_WRITES_END()
#endif
#if defined(__clang__) && defined(__has_cpp_attribute) \
&& !defined(GOOGLE_PROTOBUF_OS_APPLE)
# if defined(GOOGLE_PROTOBUF_OS_NACL) || defined(EMSCRIPTEN) || \
__has_cpp_attribute(clang::fallthrough)
# define GOOGLE_FALLTHROUGH_INTENDED [[clang::fallthrough]]
# endif
#endif
#ifndef GOOGLE_FALLTHROUGH_INTENDED
# define GOOGLE_FALLTHROUGH_INTENDED
#endif
#define GOOGLE_GUARDED_BY(x)
#define GOOGLE_ATTRIBUTE_COLD
// x86 and x86-64 can perform unaligned loads/stores directly.
#if defined(_M_X64) || defined(__x86_64__) || \
defined(_M_IX86) || defined(__i386__)
#define GOOGLE_UNALIGNED_LOAD16(_p) (*reinterpret_cast<const uint16 *>(_p))
#define GOOGLE_UNALIGNED_LOAD32(_p) (*reinterpret_cast<const uint32 *>(_p))
#define GOOGLE_UNALIGNED_LOAD64(_p) (*reinterpret_cast<const uint64 *>(_p))
#define GOOGLE_UNALIGNED_STORE16(_p, _val) (*reinterpret_cast<uint16 *>(_p) = (_val))
#define GOOGLE_UNALIGNED_STORE32(_p, _val) (*reinterpret_cast<uint32 *>(_p) = (_val))
#define GOOGLE_UNALIGNED_STORE64(_p, _val) (*reinterpret_cast<uint64 *>(_p) = (_val))
#else
inline uint16 GOOGLE_UNALIGNED_LOAD16(const void *p) {
uint16 t;
memcpy(&t, p, sizeof t);
return t;
}
inline uint32 GOOGLE_UNALIGNED_LOAD32(const void *p) {
uint32 t;
memcpy(&t, p, sizeof t);
return t;
}
inline uint64 GOOGLE_UNALIGNED_LOAD64(const void *p) {
uint64 t;
memcpy(&t, p, sizeof t);
return t;
}
inline void GOOGLE_UNALIGNED_STORE16(void *p, uint16 v) {
memcpy(p, &v, sizeof v);
}
inline void GOOGLE_UNALIGNED_STORE32(void *p, uint32 v) {
memcpy(p, &v, sizeof v);
}
inline void GOOGLE_UNALIGNED_STORE64(void *p, uint64 v) {
memcpy(p, &v, sizeof v);
}
#endif
#if defined(_MSC_VER)
#define GOOGLE_THREAD_LOCAL __declspec(thread)
#else
#define GOOGLE_THREAD_LOCAL __thread
#endif
// The following guarantees declaration of the byte swap functions.
#ifdef _MSC_VER
#define bswap_16(x) _byteswap_ushort(x)
#define bswap_32(x) _byteswap_ulong(x)
#define bswap_64(x) _byteswap_uint64(x)
#elif defined(__APPLE__)
// Mac OS X / Darwin features
#define bswap_16(x) OSSwapInt16(x)
#define bswap_32(x) OSSwapInt32(x)
#define bswap_64(x) OSSwapInt64(x)
#elif !defined(__GLIBC__) && !defined(__CYGWIN__)
static inline uint16 bswap_16(uint16 x) {
return static_cast<uint16>(((x & 0xFF) << 8) | ((x & 0xFF00) >> 8));
}
#define bswap_16(x) bswap_16(x)
static inline uint32 bswap_32(uint32 x) {
return (((x & 0xFF) << 24) |
((x & 0xFF00) << 8) |
((x & 0xFF0000) >> 8) |
((x & 0xFF000000) >> 24));
}
#define bswap_32(x) bswap_32(x)
static inline uint64 bswap_64(uint64 x) {
return (((x & GOOGLE_ULONGLONG(0xFF)) << 56) |
((x & GOOGLE_ULONGLONG(0xFF00)) << 40) |
((x & GOOGLE_ULONGLONG(0xFF0000)) << 24) |
((x & GOOGLE_ULONGLONG(0xFF000000)) << 8) |
((x & GOOGLE_ULONGLONG(0xFF00000000)) >> 8) |
((x & GOOGLE_ULONGLONG(0xFF0000000000)) >> 24) |
((x & GOOGLE_ULONGLONG(0xFF000000000000)) >> 40) |
((x & GOOGLE_ULONGLONG(0xFF00000000000000)) >> 56));
}
#define bswap_64(x) bswap_64(x)
#endif
// ===================================================================
// from google3/util/endian/endian.h
LIBPROTOBUF_EXPORT uint32 ghtonl(uint32 x);
class BigEndian {
public:
#ifdef PROTOBUF_LITTLE_ENDIAN
static uint16 FromHost16(uint16 x) { return bswap_16(x); }
static uint16 ToHost16(uint16 x) { return bswap_16(x); }
static uint32 FromHost32(uint32 x) { return bswap_32(x); }
static uint32 ToHost32(uint32 x) { return bswap_32(x); }
static uint64 FromHost64(uint64 x) { return bswap_64(x); }
static uint64 ToHost64(uint64 x) { return bswap_64(x); }
static bool IsLittleEndian() { return true; }
#else
static uint16 FromHost16(uint16 x) { return x; }
static uint16 ToHost16(uint16 x) { return x; }
static uint32 FromHost32(uint32 x) { return x; }
static uint32 ToHost32(uint32 x) { return x; }
static uint64 FromHost64(uint64 x) { return x; }
static uint64 ToHost64(uint64 x) { return x; }
static bool IsLittleEndian() { return false; }
#endif /* ENDIAN */
// Functions to do unaligned loads and stores in big-endian order.
static uint16 Load16(const void *p) {
return ToHost16(GOOGLE_UNALIGNED_LOAD16(p));
}
static void Store16(void *p, uint16 v) {
GOOGLE_UNALIGNED_STORE16(p, FromHost16(v));
}
static uint32 Load32(const void *p) {
return ToHost32(GOOGLE_UNALIGNED_LOAD32(p));
}
static void Store32(void *p, uint32 v) {
GOOGLE_UNALIGNED_STORE32(p, FromHost32(v));
}
static uint64 Load64(const void *p) {
return ToHost64(GOOGLE_UNALIGNED_LOAD64(p));
}
static void Store64(void *p, uint64 v) {
GOOGLE_UNALIGNED_STORE64(p, FromHost64(v));
}
};
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_STUBS_PORT_H_
| [
"vic03@live.fr"
] | vic03@live.fr |
91cd89eb8f5606be742541a642a9818cebd15ea5 | 6e9e14744f8a4a3a7d8b9369a82c31cb3f0e55c0 | /Other/ecs/Manager/Settings.hpp | 293ae3e94311483dd15d9faf11f58b1c00bae546 | [
"AFL-3.0",
"AFL-2.1",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | laiyierjiangsu/cppcon2015 | 0f20f97be77534f4f2845b14c09c1f742a8c41b5 | 870f600af729af1400b06f64eeabfb9f9d30a19e | refs/heads/master | 2021-01-23T14:15:56.653940 | 2017-09-07T02:50:59 | 2017-09-07T02:50:59 | 102,681,861 | 0 | 0 | null | 2017-09-07T02:31:56 | 2017-09-07T02:31:56 | null | UTF-8 | C++ | false | false | 3,063 | hpp | #pragma once
#include <bitset>
#include "../../ecs/Core/Core.hpp"
#include "../../ecs/Traits/Traits.hpp"
#include "../../ecs/Elements/Elements.hpp"
#include "../../ecs/Config/Config.hpp"
namespace ecs
{
namespace Impl
{
enum class CacheSettings
{
UseCache,
DontUseCache
};
template <typename TComponentConfig, typename TSignatureConfig,
typename TSystemConfig = SystemConfig<>,
typename TTagConfig = TagConfig<>,
CacheSettings TCacheSettings = CacheSettings::DontUseCache>
struct Settings final : Traits::SettingsTag
{
static_assert(Traits::IsComponentConfig<TComponentConfig>{}, "");
static_assert(Traits::IsSignatureConfig<TSignatureConfig>{}, "");
static_assert(Traits::IsSystemConfig<TSystemConfig>{}, "");
static_assert(Traits::IsTagConfig<TTagConfig>{}, "");
using ComponentConfig = TComponentConfig;
using SignatureConfig = TSignatureConfig;
using SystemConfig = TSystemConfig;
using TagConfig = TTagConfig;
static constexpr bool useCache{
TCacheSettings == CacheSettings::UseCache};
static constexpr std::size_t componentCount{
ComponentConfig::componentCount};
static constexpr std::size_t tagCount{TagConfig::tagCount};
static constexpr std::size_t bitCount{componentCount + tagCount};
// TODO: constexpr bitset for signatures
using EntityBitset = std::bitset<bitCount>;
static constexpr float growMultiplier{2.f};
static constexpr std::size_t growAmount{5};
template <typename TComponent>
static constexpr auto getComponentTypeID() noexcept
{
return ComponentConfig::template getComponentTypeID<
TComponent>();
}
/*template<typename TSignature>
static constexpr auto getSignatureTypeID() noexcept
{
static_assert(Traits::IsSignature<TSignature>{}, "");
return SignatureConfig::template
getSignatureTypeID<TSignature>();
}*/
template <template <typename> class TSystem>
static constexpr auto getSystemTypeID() noexcept
{
return SystemConfig::template getSystemTypeID<TSystem>();
}
template <typename TTag>
static constexpr auto getTagTypeID() noexcept
{
return TagConfig::template getTagTypeID<TTag>();
}
template <typename TComponent>
static constexpr auto getComponentBit() noexcept
{
return getComponentTypeID<TComponent>();
}
template <typename TTag>
static constexpr auto getTagBit() noexcept
{
return componentCount + getTagTypeID<TTag>();
}
};
}
} | [
"vittorio.romeo@outlook.com"
] | vittorio.romeo@outlook.com |
e12d1d34f5c2afbf2b75de6d24ece4abcc2e5d4b | 9d9e74fcfaddbc7ebfa72894d1e117669dbd0a7d | /src/views/fight.hpp | 8b13a61562480d159c4bc8f0b56ce02a23dbf7da | [
"BSL-1.0"
] | permissive | SuperFola/Unamed-Endive | fadeb173dcd175c2fa40bc8d5b5f26db0d494a39 | 530678fc622b04648dfce592a4671f7706779cbb | refs/heads/master | 2022-12-25T09:18:40.940516 | 2020-10-08T08:04:01 | 2020-10-08T08:04:01 | 66,569,631 | 5 | 1 | null | 2018-05-07T12:11:29 | 2016-08-25T15:21:42 | C++ | UTF-8 | C++ | false | false | 3,706 | hpp | #ifndef DEF_FIGHT_VIEW
#define DEF_FIGHT_VIEW
#include <SFML/Graphics.hpp>
#include <string>
#include <map>
#include "view.hpp"
#include "../abstract/container.hpp"
#include "../constants.hpp"
#ifdef PLATFORM_WIN
#include <windows.h>
#endif // PLATFORM_WIN
#include "../objects/dex.hpp"
#include "../entities/creature.hpp"
#include "../abstract/equip.hpp"
#include "../abstract/creatures_loader.hpp"
#include "../abstract/defines.hpp"
#include "../particles/particles.hpp"
#include "../scripting/types.hpp"
#include "../abstract/config.hpp"
#define X_TEXT_SELCREA_UI 200
#define MX_TEXT_SELCREA_UI 400
#define Y_TEXT_SELCREA_UI 200
#define MY_TEXT_SELCREA_UI 400
#define YS_TEXT_SELCREA_UI 30
#define CREATURE_HEIGHT 160.0f
#define START_X 269.0f
#define SPACEMENT_X 100.0f
#define SPACING_ATK_LISTING_Y 30
#define ENDING_CNT 260
#define NODEAD 0
#define DEADME 1
#define DEADOTH 2
std::string convert_sort(SortilegeType);
class FightView : public View
{
private:
Container<sf::Texture> textures;
std::map<std::string, sf::Sprite> sprites;
Container<sf::Text> texts;
std::vector<Creature*> adv;
std::vector<int> cibles;
sf::Font font;
sf::Text action;
sf::Text enemy;
sf::Text me;
sf::Text e_pv;
sf::Text m_pv;
FightEnv env;
Dex* dex;
Equip* equip;
Equip* pc;
CreaturesLoader* crealoader;
int __c; // for the capture
int __selected; // for the UI when we select an enemy
bool selectingcrea; // are we selected a creature (change it)
bool selectingadv; // or the enemy (to attack it)
int __count_before_flyaway; // count down in frames
bool can_escape;
sf::RectangleShape life1;
sf::RectangleShape life2;
int ui_my_selected; // to know which creature we are currently displaying the stats
int ui_enemy_selected; // same
bool attacking;
sf::Text attack_name;
std::vector<bool> attacks_used;
bool has_selected_an_atk;
int atk_using_sort_of;
int attack_frames_count;
bool display_attack;
bool my_turn;
bool attacking_enemy;
ParticleSystem particles;
float eq_x;
float eq_y;
int ending;
bool enemy_is_attacking;
int enemy_wait_until_next;
bool lock;
int wait_give_xp;
int whoisdead;
bool iamattacking;
int wait;
int giving_xp_to;
bool random_encounter;
std::vector<fight_opponent> _opponents;
sf::Texture black_fade;
sf::Sprite black_fade_sprite;
const std::string __adv = "adv";
const std::string __me = "me";
const std::string BKG1 = "bkg1";
const std::string BKG2 = "bkg2";
const std::string BKG3 = "bkg3";
const std::string GRD1 = "grd1";
const std::string GRD2 = "grd2";
const std::string GRD3 = "grd3";
const std::string TOOLS = "toolbar";
const std::string LIFEBAR = "lifebar";
const std::string LIFEBAR2 = "lifebar2";
const std::string OVERLAY = "overlay";
const std::string BKG_SELECT = "background_select";
void attack(int, int);
void e_attack(int);
void check_statuses();
void give_xp(bool);
void on_end();
public:
FightView();
~FightView();
bool load() override;
void render(sf::RenderWindow&) override;
int process_event(sf::Event&, sf::Time) override;
void update(sf::RenderWindow&, sf::Time) override;
void encounter();
void set_env(FightEnv);
void set_dex(Dex*);
void set_equip(Equip*);
void set_pc(Equip*);
void set_crealoader(CreaturesLoader*);
void start();
void set_escape(bool);
void set_random_encounter(bool);
void set_opponents(std::vector<fight_opponent>);
static int ATK_FR_CNT();
};
#endif // DEF_FIGHT_VIEW
| [
"folaefolc@outlook.fr"
] | folaefolc@outlook.fr |
193a2ff86a76148f91ca15e8fe443177e2f41a61 | c17bb25e2db7b2f38edd36425f27611799c4b963 | /Wipgate/Source/Wipgate/LevelGenerator/LevelGenerator.cpp | 700a64eb0b7ab575466ba1c6de5fdd4aafb63172 | [] | no_license | ajweeks/Wipgate | 680e0b0e445e06eaaa5df445f4496702974aab4e | dcf3a249e21d1612804c1fbb614d1bcec4eb8fbf | refs/heads/master | 2021-09-08T03:57:52.559275 | 2018-03-06T17:52:40 | 2018-03-06T17:52:40 | 110,848,942 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,424 | cpp | #include "LevelGenerator.h"
#include "Runtime/Engine/Classes/Engine/StaticMesh.h"
#include "Runtime/Engine/Classes/Materials/MaterialInstanceDynamic.h"
#include "Runtime/Engine/Classes/Engine/World.h"
#include "GeneralFunctionLibrary_CPP.h"
#include "Wipgate.h"
#include "Step.h"
void ALevelGenerator::InitializeBlockout()
{
m_Grid = new LevelGrid(35, 35, this);
m_Grid->SetMainGrid(m_Grid);
m_Blockout = GetWorld()->SpawnActor<ALevelBlockout>();
m_Blockout->SetBlock(m_Block);
m_Blockout->Initialize(m_Grid);
}
void ALevelGenerator::GenerateStreets(const int granularity)
{
LevelGrid* grid = m_Grid->CreateSubGrid(2, 2, m_Grid->GetHeight() - 3, m_Grid->GetWidth() - 3);
// empty grid
//vector<Tile*> tiles = m_Grid->GetTiles();
m_Grid->SetFilledArea(1, 1, m_Grid->GetHeight() - 2, m_Grid->GetWidth() - 2, false);
m_Grid->SetTilesType(m_Grid->GetTiles(), LEVEL_EDGE);
m_Grid->SetTileTypeArea(1, 1, m_Grid->GetHeight() - 2, m_Grid->GetWidth() - 2, FLOOR);
ExecuteSteps();
GenerateBaseLayout(grid, granularity);
FlagStreets();
CreateStreetsFromFlagged();
// street sparsity
//vector<Street*> edgeStreets = m_Grid->GetEdgeStreets();
//for (auto street : edgeStreets)
//{
// if (rand() % 3 == 0)
// m_Grid->RemoveStreet(street);
//}
/*for (auto street : m_Grid->GetStreets())
{
int rnd = rand() % 3;
if (rnd == 0)
street->Widen();
else if (rnd == 1)
street->Tighten();
}*/
//m_Grid->GetRandomStreet()->Widen();
//vector<Tile*> intersectionTiles = m_Grid->GetTilesWithType(m_Grid->GetTiles(), INTERSECTION);
//vector<Tile*> adjacents;
//for (auto t : intersectionTiles)
//{
// // adjacent to wall?
// adjacents = m_Grid->GetAdjacentTiles(t);
// if (!m_Grid->GetTilesFilled(adjacents).empty() &&
// (m_Grid->IsAdjTileWithType(t, STREET_HOR) || m_Grid->IsAdjTileWithType(t, STREET_VERT)))
// {
// Tile* filled = m_Grid->GetTilesFilled(adjacents)[0];
// vector<Tile*> adjEmpties = m_Grid->GetTilesFilled(m_Grid->GetAdjacentTiles(filled), false);
// if (adjEmpties.size() > 1 && !m_Grid->GetTilesWithTypes(adjEmpties, vector<TileType> { STREET_HOR, STREET_VERT}).empty())
// {
// m_Grid->SetFilled(filled, false);
// m_Grid->SetType(filled, INTERSECTION);
// }
// }
//}
//Street* street = m_Grid->GetRandomStreet();
//if (street)
//{
// auto path = m_Grid->FindPathWithoutStreets(street->GetIntersectionTilesFront()[0],
// street->GetIntersectionTilesBack()[0], vector<Street*> {street});
// m_Grid->SetTilesType(path, FLAGGED);
//}
// remove streets while ensuring connectivity
SparsifyStreetsRandom(4);
// Reset unfilled tiles to floor and flag streets again
m_Grid->SetTilesType(m_Grid->GetTilesFilled(m_Grid->GetTiles(), false), FLOOR);
FlagStreets();
CreateStreetsFromFlagged();
m_Grid->SetFilled((*m_Grid)[0][0], false);
}
void ALevelGenerator::ExecuteStep(UStep * step)
{
if(step)
step->Execute(m_Blockout->GetBlockoutMap());
}
void ALevelGenerator::Reset()
{
if (m_Blockout)
m_Blockout->Destroy();
if(m_Grid)
delete m_Grid;
InitializeBlockout();
}
void ALevelGenerator::ExecuteSteps()
{
for (auto step : m_Grid->GetSteps())
ExecuteStep(step);
m_Grid->ClearSteps();
}
void ALevelGenerator::GenerateBaseLayout(LevelGrid* grid, const int granularity)
{
grid->SplitDeep(granularity);
auto children = grid->GetChildrenDeep();
for (auto c : children)
{
c->SetFilledArea(1, 1, c->GetHeight() - 2, c->GetWidth() - 2, true);
}
}
void ALevelGenerator::FlagStreets()
{
vector<Tile*> tiles = m_Grid->GetTiles();
vector<Tile*> emptyTiles = m_Grid->GetTilesFilled(tiles, false);
// flag tiles diagonal from building corners
for (auto t : emptyTiles)
{
vector<Tile*> nearby = m_Grid->GetNearbyTiles(t->GetPosition());
vector<Tile*> nearbyFilleds = m_Grid->GetTilesFilled(nearby, true);
if (nearbyFilleds.size() > 1)
m_Grid->SetType(t, FLAGGED);
}
// complete street flagging by flagging intersections completely
// flag the 3 opposite tiles from the building corner
vector<Tile*> intersectionTiles = m_Grid->GetTilesWithType(tiles, FLOOR);
m_Grid->SetTilesType(intersectionTiles, FLOOR);
Tile* blockCorner;
vector<Tile*> oppositeTiles;
for (auto t : intersectionTiles)
{
// get nearby building block corner
blockCorner = m_Grid->GetTilesFilled(m_Grid->GetNearbyTiles(t), true).front();
Direction cornerDir = m_Grid->GetTileDirection(t, blockCorner);
oppositeTiles = m_Grid->GetOppositeDirTiles(t, cornerDir);
m_Grid->SetTilesType(oppositeTiles, FLOOR);
}
}
void ALevelGenerator::CreateStreetsFromFlagged()
{
Tile* start;
vector<Tile*> streetTiles;
start = m_Grid->GetRandomTileWithType(FLAGGED);
while (start)
{
streetTiles = m_Grid->GetFloodType(start, FLAGGED);
m_Grid->AddStreet(streetTiles);
start = m_Grid->GetRandomTileWithType(FLAGGED);
}
}
void ALevelGenerator::SparsifyStreetsRandom(const int odds)
{
for (auto street : m_Grid->GetStreets())
{
if (rand() % odds == 0)
{
if (!street->GetIntersectionTilesFront().empty()
&& !street->GetIntersectionTilesBack().empty())
{
Tile* front = street->GetIntersectionTilesFront()[0];
Tile* back = street->GetIntersectionTilesBack()[0];
if (front && back)
{
auto path = m_Grid->FindPathWithoutStreets(front, back, vector<Street*> {street});
if (!path.empty())
{
m_Grid->SetTilesType(path, FLAGGED);
m_Grid->RemoveStreet(street);
}
}
}
}
}
}
| [
"yosha.vandaele@student.howest.be"
] | yosha.vandaele@student.howest.be |
7fc206be3c9124e67b06cf38042c65381038ecfe | c730b3ddd75e1aa080e652c267038eb610f0f97a | /.ino.cpp | 90e9bab6e000da1e8bb1b29cf2b260a588d82e16 | [] | no_license | jerscake/boxingMachine | c59ae363c52724bead24973eb1f5939fd6d732f7 | 88c599cb8d50e8626c84a0d9614c64f34700a7f7 | refs/heads/master | 2020-05-21T02:23:35.522148 | 2017-03-10T15:26:21 | 2017-03-10T15:26:21 | 84,559,328 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 513 | cpp | #ifdef __IN_ECLIPSE__
//This is a automatic generated file
//Please do not modify this file
//If you touch this file your change will be overwritten during the next build
//This file has been generated on 2017-03-09 19:29:45
#include "Arduino.h"
#include "Arduino.h"
#include "Wire.h"
#include "I2Cdev.h"
#include "ADXL345Extended.h"
#include "Target.h"
void isrJab() ;
void isrCross() ;
void talkToTarget(uint8_t targetShiftRegPin) ;
void setup() ;
void checkHits() ;
void loop() ;
#include "MIX.ino"
#endif
| [
"noreply@github.com"
] | jerscake.noreply@github.com |
9712d07b7e4df7351463f27103ea5123a2df2a06 | 4207bbd97a4debbf29b0cf1652c4b4d247d71647 | /src/core/DistributedRegionHash.hpp | a9011963e3fb57b0cbe2fcaaae6d72be5b2d8ad2 | [
"MIT"
] | permissive | loftyhauser/overkit | 6a94c7411191f39a8d55c8d7a5f7634d3dd6f44d | 490aa77a79bd9708d7f2af0f3069b86545a2cebc | refs/heads/master | 2022-04-29T03:25:08.181280 | 2020-03-01T22:53:34 | 2020-03-02T00:55:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,336 | hpp | // Copyright (c) 2020 Matthew J. Smith and Overkit contributors
// License: MIT (http://opensource.org/licenses/MIT)
#ifndef OVK_CORE_DISTRIBUTED_REGION_HASH_HPP_INCLUDED
#define OVK_CORE_DISTRIBUTED_REGION_HASH_HPP_INCLUDED
#include <ovk/core/Array.hpp>
#include <ovk/core/ArrayView.hpp>
#include <ovk/core/Box.hpp>
#include <ovk/core/Comm.hpp>
#include <ovk/core/CommunicationOps.hpp>
#include <ovk/core/DataType.hpp>
#include <ovk/core/Elem.hpp>
#include <ovk/core/Field.hpp>
#include <ovk/core/Global.hpp>
#include <ovk/core/HashableRegionTraits.hpp>
#include <ovk/core/Indexer.hpp>
#include <ovk/core/Interval.hpp>
#include <ovk/core/Map.hpp>
#include <ovk/core/Math.hpp>
#include <ovk/core/MPISerializableTraits.hpp>
#include <ovk/core/Range.hpp>
#include <ovk/core/Requires.hpp>
#include <ovk/core/Set.hpp>
#include <ovk/core/Tuple.hpp>
#include <mpi.h>
#include <cmath>
#include <cstring>
#include <memory>
#include <numeric>
#include <type_traits>
#include <utility>
namespace ovk {
namespace core {
template <typename RegionType> class distributed_region_hash;
template <typename RegionType> class distributed_region_data {
public:
using region_type = RegionType;
const region_type &Region() const { return Region_; }
int Rank() const { return Rank_; }
private:
region_type Region_;
int Rank_;
friend class distributed_region_hash<RegionType>;
};
template <typename RegionType> class distributed_region_hash_retrieved_bins {
public:
using region_data = distributed_region_data<RegionType>;
const region_data &RegionData(int iRegion) const { return RegionData_(iRegion); }
array_view<const int> BinRegionIndices(int iBin) const {
const interval<long long> &Interval = BinRegionIndicesIntervals_(iBin);
return {BinRegionIndices_.Data(Interval.Begin()), Interval};
}
private:
array<region_data> RegionData_;
map<int,interval<long long>> BinRegionIndicesIntervals_;
array<int> BinRegionIndices_;
friend class distributed_region_hash<RegionType>;
};
template <typename RegionType> class distributed_region_hash {
public:
static_assert(IsHashableRegion<RegionType>(), "Invalid region type (not hashable).");
static_assert(IsMPISerializable<RegionType>(), "Invalid region type (not MPI-serializable).");
using region_type = RegionType;
using region_traits = hashable_region_traits<region_type>;
using coord_type = typename region_traits::coord_type;
using mpi_traits = mpi_serializable_traits<region_type>;
static_assert(std::is_same<coord_type, int>::value || std::is_same<coord_type, double>::value,
"Coord type must be int or double.");
using extents_type = interval<coord_type,MAX_DIMS>;
using region_data = distributed_region_data<region_type>;
using retrieved_bins = distributed_region_hash_retrieved_bins<region_type>;
distributed_region_hash(int NumDims, comm_view Comm);
distributed_region_hash(int NumDims, comm_view Comm, array_view<const region_type> LocalRegions);
distributed_region_hash(const distributed_region_hash &Other) = delete;
distributed_region_hash(distributed_region_hash &&Other) noexcept = default;
distributed_region_hash &operator=(const distributed_region_hash &Other) = delete;
distributed_region_hash &operator=(distributed_region_hash &&Other) noexcept = default;
elem<int,2> MapToBin(const tuple<coord_type> &Point) const;
map<int,retrieved_bins> RetrieveBins(array_view<const elem<int,2>> BinIDs) const;
private:
int NumDims_;
comm_view Comm_;
extents_type GlobalExtents_;
range ProcRange_;
range_indexer<int> ProcIndexer_;
tuple<coord_type> ProcSize_;
array<int> ProcToBinMultipliers_;
array<region_data> RegionData_;
range BinRange_;
field<int> NumRegionsPerBin_;
field<long long> BinRegionIndicesStarts_;
array<int> BinRegionIndices_;
template <hashable_region_maps_to MapsTo> struct maps_to_tag {};
template <typename IndexerType> set<typename IndexerType::index_type> MapToBins_(const range
&BinRange, const IndexerType &BinIndexer, const tuple<coord_type> &LowerCorner, const
tuple<coord_type> &BinSize, const region_type &Region, maps_to_tag<
hashable_region_maps_to::SET>) const;
template <typename IndexerType> set<typename IndexerType::index_type> MapToBins_(const range
&BinRange, const IndexerType &BinIndexer, const tuple<coord_type> &LowerCorner, const
tuple<coord_type> &BinSize, const region_type &Region, maps_to_tag<
hashable_region_maps_to::RANGE>) const;
template <typename T> struct coord_type_tag {};
static interval<int,MAX_DIMS> MakeEmptyExtents_(int NumDims, coord_type_tag<int>);
static interval<double,MAX_DIMS> MakeEmptyExtents_(int NumDims, coord_type_tag<double>);
static interval<int,MAX_DIMS> UnionExtents_(const interval<int,MAX_DIMS> &Left, const
interval<int,MAX_DIMS> &Right);
static interval<double,MAX_DIMS> UnionExtents_(const interval<double,MAX_DIMS> &Left, const
interval<double,MAX_DIMS> &Right);
static tuple<int> BinDecomp_(int NumDims, const extents_type &Extents, int MaxBins);
static tuple<int> GetBinSize_(const interval<int,MAX_DIMS> &Extents, const tuple<int> &NumBins);
static tuple<double> GetBinSize_(const interval<double,MAX_DIMS> &Extents, const tuple<int>
&NumBins);
};
}}
#include <ovk/core/DistributedRegionHash.inl>
#endif
| [
"mjsmith6@illinois.edu"
] | mjsmith6@illinois.edu |
6bc09ffb45698262418be304d7249dd20d2d80d9 | f2d583420ecaf2cdfb5e30b3735063b5eefab49f | /demo8_6.cpp | d70fd0798c59ede04e660b6d21738dc93ef1ec33 | [] | no_license | 7er/T3DCHAP08 | 1e58eebe44d782a4e26a3b52ac501acdc14fdcaf | b9edda9a44473587bc803da2ea2785ad6ee47d2c | refs/heads/master | 2021-01-25T05:11:05.383498 | 2012-04-23T00:52:23 | 2012-04-23T00:52:23 | 3,539,908 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 34,744 | cpp | // DEMO8_6.CPP 8-bit polygon transformation demo with matrices
// INCLUDES ///////////////////////////////////////////////
#define WIN32_LEAN_AND_MEAN // just say no to MFC
#define INITGUID
#include <windows.h> // include important windows stuff
#include <windowsx.h>
#include <mmsystem.h>
//#include <iostream.h> // include important C/C++ stuff
#include <conio.h>
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <string.h>
#include <stdarg.h>
#include <stdio.h>
#include <math.h>
#include <io.h>
#include <fcntl.h>
#include <ddraw.h> // include directdraw
// DEFINES ////////////////////////////////////////////////
// defines for windows
#define WINDOW_CLASS_NAME "WINCLASS1"
// default screen size
#define SCREEN_WIDTH 640 // size of screen
#define SCREEN_HEIGHT 480
#define SCREEN_BPP 8 // bits per pixel
#define BITMAP_ID 0x4D42 // universal id for a bitmap
#define MAX_COLORS_PALETTE 256
const double PI = 3.1415926535;
// TYPES //////////////////////////////////////////////////////
// basic unsigned types
typedef unsigned short USHORT;
typedef unsigned short WORD;
typedef unsigned char UCHAR;
typedef unsigned char BYTE;
// a 2D vertex
typedef struct VERTEX2DI_TYP
{
int x,y; // the vertex
} VERTEX2DI, *VERTEX2DI_PTR;
// a 2D vertex
typedef struct VERTEX2DF_TYP
{
float x,y; // the vertex
} VERTEX2DF, *VERTEX2DF_PTR;
// a 2D polygon
typedef struct POLYGON2D_TYP
{
int state; // state of polygon
int num_verts; // number of vertices
int x0,y0; // position of center of polygon
int xv,yv; // initial velocity
DWORD color; // could be index or PALETTENTRY
VERTEX2DF *vlist; // pointer to vertex list
} POLYGON2D, *POLYGON2D_PTR;
// matrices
typedef struct MATRIX1X2_TYP
{
float M[2]; // data storage
} MATRIX1X2, *MATRIX1X2_PTR;
// note that 1x2 has the same memory layout as a VERTEX2DF, hence we
// can use the matrix function written for a MATRIX1X2 to multiply a
// VERTEX2DF by casting
typedef struct MATRIX3X2_TYP
{
float M[3][2]; // data storage
} MATRIX3X2, *MATRIX3X2_PTR;
// PROTOTYPES //////////////////////////////////////////////
int Draw_Text_GDI(char *text, int x,int y,int color, LPDIRECTDRAWSURFACE7 lpdds);
int DDraw_Fill_Surface(LPDIRECTDRAWSURFACE7 lpdds,int color);
int Draw_Line(int x0, int y0, int x1, int y1, UCHAR color, UCHAR *vb_start, int lpitch);
int Draw_Clip_Line(int x0,int y0, int x1, int y1,UCHAR color,
UCHAR *dest_buffer, int lpitch);
int Clip_Line(int &x1,int &y1,int &x2, int &y2);
int Draw_Polygon2D(POLYGON2D_PTR poly, UCHAR *vbuffer, int lpitch);
int Translate_Polygon2D(POLYGON2D_PTR poly, int dx, int dy);
int Rotate_Polygon2D(POLYGON2D_PTR poly, int theta);
int Scale_Polygon2D(POLYGON2D_PTR poly, float sx, float sy);
int Translate_Polygon2D_Mat(POLYGON2D_PTR poly, int dx, int dy);
int Rotate_Polygon2D_Mat(POLYGON2D_PTR poly, int theta);
int Scale_Polygon2D_Mat(POLYGON2D_PTR poly, float sx, float sy);
int Mat_Mul1X2_3X2(MATRIX1X2_PTR ma,
MATRIX3X2_PTR mb,
MATRIX1X2_PTR mprod);
inline int Mat_Init_3X2(MATRIX3X2_PTR ma,
float m00, float m01,
float m10, float m11,
float m20, float m21);
// MACROS /////////////////////////////////////////////////
// tests if a key is up or down
#define KEYDOWN(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 1 : 0)
#define KEYUP(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 0 : 1)
// initializes a direct draw struct
#define DDRAW_INIT_STRUCT(ddstruct) { memset(&ddstruct,0,sizeof(ddstruct)); ddstruct.dwSize=sizeof(ddstruct); }
// some math macros
#define DEG_TO_RAD(ang) ((ang)*PI/180)
#define RAD_TO_DEG(rads) ((rads)*180/PI)
// GLOBALS ////////////////////////////////////////////////
HWND main_window_handle = NULL; // globally track main window
int window_closed = 0; // tracks if window is closed
HINSTANCE hinstance_app = NULL; // globally track hinstance
// directdraw stuff
LPDIRECTDRAW7 lpdd = NULL; // dd4 object
LPDIRECTDRAWSURFACE7 lpddsprimary = NULL; // dd primary surface
LPDIRECTDRAWSURFACE7 lpddsback = NULL; // dd back surface
LPDIRECTDRAWPALETTE lpddpal = NULL; // a pointer to the created dd palette
LPDIRECTDRAWCLIPPER lpddclipper = NULL; // dd clipper
PALETTEENTRY palette[256]; // color palette
PALETTEENTRY save_palette[256]; // used to save palettes
DDSURFACEDESC2 ddsd; // a direct draw surface description struct
DDBLTFX ddbltfx; // used to fill
DDSCAPS2 ddscaps; // a direct draw surface capabilities struct
HRESULT ddrval; // result back from dd calls
DWORD start_clock_count = 0; // used for timing
// global clipping region
int min_clip_x = 0, // clipping rectangle
max_clip_x = SCREEN_WIDTH - 1,
min_clip_y = 0,
max_clip_y = SCREEN_HEIGHT - 1;
char buffer[80]; // general printing buffer
// storage for our lookup tables
float cos_look[360];
float sin_look[360];
POLYGON2D ship; // the ship
// FUNCTIONS ////////////////////////////////////////////////
inline int Mat_Init_3X2(MATRIX3X2_PTR ma,
float m00, float m01,
float m10, float m11,
float m20, float m21)
{
// this function fills a 3x2 matrix with the sent data in row major form
ma->M[0][0] = m00; ma->M[0][1] = m01;
ma->M[1][0] = m10; ma->M[1][1] = m11;
ma->M[2][0] = m20; ma->M[2][1] = m21;
// return success
return(1);
} // end Mat_Init_3X2
/////////////////////////////////////////////////////////////////
int Mat_Mul1X2_3X2(MATRIX1X2_PTR ma,
MATRIX3X2_PTR mb,
MATRIX1X2_PTR mprod)
{
// this function multiplies a 1x2 matrix against a
// 3x2 matrix - ma*mb and stores the result
// using a dummy element for the 3rd element of the 1x2
// to make the matrix multiply valid i.e. 1x3 X 3x2
for (int col=0; col<2; col++)
{
// compute dot product from row of ma
// and column of mb
float sum = 0; // used to hold result
int index;
for (index=0; index<2; index++)
{
// add in next product pair
sum+=(ma->M[index]*mb->M[index][col]);
} // end for index
// add in last element * 1
sum+= mb->M[index][col];
// insert resulting col element
mprod->M[col] = sum;
} // end for col
return(1);
} // end Mat_Mul_1X2_3X2
///////////////////////////////////////////////////////////////////////
int Draw_Polygon2D(POLYGON2D_PTR poly, UCHAR *vbuffer, int lpitch)
{
// this function draws a POLYGON2D based on
// test if the polygon is visible
if (poly->state)
{
// loop thru and draw a line from vertices 1 to n
int index;
for (index=0; index < poly->num_verts-1; index++)
{
// draw line from ith to ith+1 vertex
Draw_Clip_Line(poly->vlist[index].x+poly->x0,
poly->vlist[index].y+poly->y0,
poly->vlist[index+1].x+poly->x0,
poly->vlist[index+1].y+poly->y0,
poly->color,
vbuffer, lpitch);
} // end for
// now close up polygon
// draw line from last vertex to 0th
Draw_Clip_Line(poly->vlist[0].x+poly->x0,
poly->vlist[0].y+poly->y0,
poly->vlist[index].x+poly->x0,
poly->vlist[index].y+poly->y0,
poly->color,
vbuffer, lpitch);
// return success
return(1);
} // end if
else
return(0);
} // end Draw_Polygon2D
///////////////////////////////////////////////////////////////
// the following 3 functions are the standard transforms (no matrices)
int Translate_Polygon2D(POLYGON2D_PTR poly, int dx, int dy)
{
// this function translates the center of a polygon
// test for valid pointer
if (!poly)
return(0);
// translate
poly->x0+=dx;
poly->y0+=dy;
// return success
return(1);
} // end Translate_Polygon2D
///////////////////////////////////////////////////////////////
int Rotate_Polygon2D(POLYGON2D_PTR poly, int theta)
{
// this function rotates the local coordinates of the polygon
// test for valid pointer
if (!poly)
return(0);
// test for negative rotation angle
if (theta < 0)
theta+=360;
// loop and rotate each point, very crude, no lookup!!!
for (int curr_vert = 0; curr_vert < poly->num_verts; curr_vert++)
{
// perform rotation
float xr = (float)poly->vlist[curr_vert].x*cos_look[theta] -
(float)poly->vlist[curr_vert].y*sin_look[theta];
float yr = (float)poly->vlist[curr_vert].x*sin_look[theta] +
(float)poly->vlist[curr_vert].y*cos_look[theta];
// store result back
poly->vlist[curr_vert].x = xr;
poly->vlist[curr_vert].y = yr;
} // end for curr_vert
// return success
return(1);
} // end Rotate_Polygon2D
////////////////////////////////////////////////////////
int Scale_Polygon2D(POLYGON2D_PTR poly, float sx, float sy)
{
// this function scalesthe local coordinates of the polygon
// test for valid pointer
if (!poly)
return(0);
// loop and scale each point
for (int curr_vert = 0; curr_vert < poly->num_verts; curr_vert++)
{
// scale and store result back
poly->vlist[curr_vert].x *= sx;
poly->vlist[curr_vert].y *= sy;
} // end for curr_vert
// return success
return(1);
} // end Scale_Polygon2D
///////////////////////////////////////////////////////////////////////
// these are the matrix versions, note they are more inefficient for
// single transforms, but their power comes into play when you concatenate
// multiple transformations, not to mention that all transforms are accomplished
// with the same code, just the matrix differs
int Translate_Polygon2D_Mat(POLYGON2D_PTR poly, int dx, int dy)
{
// this function translates the center of a polygon by using a matrix multiply
// on the the center point, this is incredibly inefficient, but for educational purposes
// if we had an object that wasn't in local coordinates then it would make more sense to
// use a matrix, but since the origin of the object is at x0,y0 then 2 lines of code can
// translate, but lets do it the hard way just to see :)
// test for valid pointer
if (!poly)
return(0);
MATRIX3X2 mt; // used to hold translation transform matrix
// initialize the matrix with translation values dx dy
Mat_Init_3X2(&mt,1,0, 0,1, dx, dy);
// create a 1x2 matrix to do the transform
MATRIX1X2 p0 = {poly->x0, poly->y0};
MATRIX1X2 p1 = {0,0}; // this will hold result
// now translate via a matrix multiply
Mat_Mul1X2_3X2(&p0, &mt, &p1);
// now copy the result back into polygon
poly->x0 = p1.M[0];
poly->y0 = p1.M[1];
// return success
return(1);
} // end Translate_Polygon2D_Mat
///////////////////////////////////////////////////////////////
int Rotate_Polygon2D_Mat(POLYGON2D_PTR poly, int theta)
{
// this function rotates the local coordinates of the polygon
// test for valid pointer
if (!poly)
return(0);
// test for negative rotation angle
if (theta < 0)
theta+=360;
MATRIX3X2 mr; // used to hold rotation transform matrix
// initialize the matrix with translation values dx dy
Mat_Init_3X2(&mr,cos_look[theta],sin_look[theta],
-sin_look[theta],cos_look[theta],
0, 0);
// loop and rotate each point, very crude, no lookup!!!
for (int curr_vert = 0; curr_vert < poly->num_verts; curr_vert++)
{
// create a 1x2 matrix to do the transform
MATRIX1X2 p0 = {poly->vlist[curr_vert].x, poly->vlist[curr_vert].y};
MATRIX1X2 p1 = {0,0}; // this will hold result
// now rotate via a matrix multiply
Mat_Mul1X2_3X2(&p0, &mr, &p1);
// now copy the result back into vertex
poly->vlist[curr_vert].x = p1.M[0];
poly->vlist[curr_vert].y = p1.M[1];
} // end for curr_vert
// return success
return(1);
} // end Rotate_Polygon2D_Mat
////////////////////////////////////////////////////////
int Scale_Polygon2D_Mat(POLYGON2D_PTR poly, float sx, float sy)
{
// this function scalesthe local coordinates of the polygon
// test for valid pointer
if (!poly)
return(0);
MATRIX3X2 ms; // used to hold scaling transform matrix
// initialize the matrix with translation values dx dy
Mat_Init_3X2(&ms,sx,0,
0,sy,
0, 0);
// loop and scale each point
for (int curr_vert = 0; curr_vert < poly->num_verts; curr_vert++)
{
// scale and store result back
// create a 1x2 matrix to do the transform
MATRIX1X2 p0 = {poly->vlist[curr_vert].x, poly->vlist[curr_vert].y};
MATRIX1X2 p1 = {0,0}; // this will hold result
// now scale via a matrix multiply
Mat_Mul1X2_3X2(&p0, &ms, &p1);
// now copy the result back into vertex
poly->vlist[curr_vert].x = p1.M[0];
poly->vlist[curr_vert].y = p1.M[1];
} // end for curr_vert
// return success
return(1);
} // end Scale_Polygon2D_Mat
///////////////////////////////////////////////////////////
inline int Draw_Pixel(int x, int y,int color,
UCHAR *video_buffer, int lpitch)
{
// this function plots a single pixel at x,y with color
video_buffer[x + y*lpitch] = color;
// return success
return(1);
} // end Draw_Pixel
/////////////////////////////////////////////////////////////
int Draw_Text_GDI(char *text, int x,int y,int color, LPDIRECTDRAWSURFACE7 lpdds)
{
// this function draws the sent text on the sent surface
// using color index as the color in the palette
HDC xdc; // the working dc
// get the dc from surface
if (FAILED(lpdds->GetDC(&xdc)))
return(0);
// set the colors for the text up
SetTextColor(xdc,RGB(palette[color].peRed,palette[color].peGreen,palette[color].peBlue) );
// set background mode to transparent so black isn't copied
SetBkMode(xdc, TRANSPARENT);
// draw the text a
TextOut(xdc,x,y,text,strlen(text));
// release the dc
lpdds->ReleaseDC(xdc);
// return success
return(1);
} // end Draw_Text_GDI
///////////////////////////////////////////////////////////////////
int DDraw_Fill_Surface(LPDIRECTDRAWSURFACE7 lpdds,int color)
{
DDBLTFX ddbltfx; // this contains the DDBLTFX structure
// clear out the structure and set the size field
DDRAW_INIT_STRUCT(ddbltfx);
// set the dwfillcolor field to the desired color
ddbltfx.dwFillColor = color;
// ready to blt to surface
lpdds->Blt(NULL, // ptr to dest rectangle
NULL, // ptr to source surface, NA
NULL, // ptr to source rectangle, NA
DDBLT_COLORFILL | DDBLT_WAIT, // fill and wait
&ddbltfx); // ptr to DDBLTFX structure
// return success
return(1);
} // end DDraw_Fill_Surface
///////////////////////////////////////////////////////////////
int Draw_Clip_Line(int x0,int y0, int x1, int y1,UCHAR color,
UCHAR *dest_buffer, int lpitch)
{
// this helper function draws a clipped line
int cxs, cys,
cxe, cye;
// clip and draw each line
cxs = x0;
cys = y0;
cxe = x1;
cye = y1;
// clip the line
if (Clip_Line(cxs,cys,cxe,cye))
Draw_Line(cxs, cys, cxe,cye,color,dest_buffer,lpitch);
// return success
return(1);
} // end Draw_Clip_Line
///////////////////////////////////////////////////////////
int Clip_Line(int &x1,int &y1,int &x2, int &y2)
{
// this function clips the sent line using the globally defined clipping
// region
// internal clipping codes
#define CLIP_CODE_C 0x0000
#define CLIP_CODE_N 0x0008
#define CLIP_CODE_S 0x0004
#define CLIP_CODE_E 0x0002
#define CLIP_CODE_W 0x0001
#define CLIP_CODE_NE 0x000a
#define CLIP_CODE_SE 0x0006
#define CLIP_CODE_NW 0x0009
#define CLIP_CODE_SW 0x0005
int xc1=x1,
yc1=y1,
xc2=x2,
yc2=y2;
int p1_code=0,
p2_code=0;
// determine codes for p1 and p2
if (y1 < min_clip_y)
p1_code|=CLIP_CODE_N;
else
if (y1 > max_clip_y)
p1_code|=CLIP_CODE_S;
if (x1 < min_clip_x)
p1_code|=CLIP_CODE_W;
else
if (x1 > max_clip_x)
p1_code|=CLIP_CODE_E;
if (y2 < min_clip_y)
p2_code|=CLIP_CODE_N;
else
if (y2 > max_clip_y)
p2_code|=CLIP_CODE_S;
if (x2 < min_clip_x)
p2_code|=CLIP_CODE_W;
else
if (x2 > max_clip_x)
p2_code|=CLIP_CODE_E;
// try and trivially reject
if ((p1_code & p2_code))
return(0);
// test for totally visible, if so leave points untouched
if (p1_code==0 && p2_code==0)
return(1);
// determine end clip point for p1
switch(p1_code)
{
case CLIP_CODE_C: break;
case CLIP_CODE_N:
{
yc1 = min_clip_y;
xc1 = x1 + 0.5+(min_clip_y-y1)*(x2-x1)/(y2-y1);
} break;
case CLIP_CODE_S:
{
yc1 = max_clip_y;
xc1 = x1 + 0.5+(max_clip_y-y1)*(x2-x1)/(y2-y1);
} break;
case CLIP_CODE_W:
{
xc1 = min_clip_x;
yc1 = y1 + 0.5+(min_clip_x-x1)*(y2-y1)/(x2-x1);
} break;
case CLIP_CODE_E:
{
xc1 = max_clip_x;
yc1 = y1 + 0.5+(max_clip_x-x1)*(y2-y1)/(x2-x1);
} break;
// these cases are more complex, must compute 2 intersections
case CLIP_CODE_NE:
{
// north hline intersection
yc1 = min_clip_y;
xc1 = x1 + 0.5+(min_clip_y-y1)*(x2-x1)/(y2-y1);
// test if intersection is valid, of so then done, else compute next
if (xc1 < min_clip_x || xc1 > max_clip_x)
{
// east vline intersection
xc1 = max_clip_x;
yc1 = y1 + 0.5+(max_clip_x-x1)*(y2-y1)/(x2-x1);
} // end if
} break;
case CLIP_CODE_SE:
{
// south hline intersection
yc1 = max_clip_y;
xc1 = x1 + 0.5+(max_clip_y-y1)*(x2-x1)/(y2-y1);
// test if intersection is valid, of so then done, else compute next
if (xc1 < min_clip_x || xc1 > max_clip_x)
{
// east vline intersection
xc1 = max_clip_x;
yc1 = y1 + 0.5+(max_clip_x-x1)*(y2-y1)/(x2-x1);
} // end if
} break;
case CLIP_CODE_NW:
{
// north hline intersection
yc1 = min_clip_y;
xc1 = x1 + 0.5+(min_clip_y-y1)*(x2-x1)/(y2-y1);
// test if intersection is valid, of so then done, else compute next
if (xc1 < min_clip_x || xc1 > max_clip_x)
{
xc1 = min_clip_x;
yc1 = y1 + 0.5+(min_clip_x-x1)*(y2-y1)/(x2-x1);
} // end if
} break;
case CLIP_CODE_SW:
{
// south hline intersection
yc1 = max_clip_y;
xc1 = x1 + 0.5+(max_clip_y-y1)*(x2-x1)/(y2-y1);
// test if intersection is valid, of so then done, else compute next
if (xc1 < min_clip_x || xc1 > max_clip_x)
{
xc1 = min_clip_x;
yc1 = y1 + 0.5+(min_clip_x-x1)*(y2-y1)/(x2-x1);
} // end if
} break;
default:break;
} // end switch
// determine clip point for p2
switch(p2_code)
{
case CLIP_CODE_C: break;
case CLIP_CODE_N:
{
yc2 = min_clip_y;
xc2 = x2 + (min_clip_y-y2)*(x1-x2)/(y1-y2);
} break;
case CLIP_CODE_S:
{
yc2 = max_clip_y;
xc2 = x2 + (max_clip_y-y2)*(x1-x2)/(y1-y2);
} break;
case CLIP_CODE_W:
{
xc2 = min_clip_x;
yc2 = y2 + (min_clip_x-x2)*(y1-y2)/(x1-x2);
} break;
case CLIP_CODE_E:
{
xc2 = max_clip_x;
yc2 = y2 + (max_clip_x-x2)*(y1-y2)/(x1-x2);
} break;
// these cases are more complex, must compute 2 intersections
case CLIP_CODE_NE:
{
// north hline intersection
yc2 = min_clip_y;
xc2 = x2 + 0.5+(min_clip_y-y2)*(x1-x2)/(y1-y2);
// test if intersection is valid, of so then done, else compute next
if (xc2 < min_clip_x || xc2 > max_clip_x)
{
// east vline intersection
xc2 = max_clip_x;
yc2 = y2 + 0.5+(max_clip_x-x2)*(y1-y2)/(x1-x2);
} // end if
} break;
case CLIP_CODE_SE:
{
// south hline intersection
yc2 = max_clip_y;
xc2 = x2 + 0.5+(max_clip_y-y2)*(x1-x2)/(y1-y2);
// test if intersection is valid, of so then done, else compute next
if (xc2 < min_clip_x || xc2 > max_clip_x)
{
// east vline intersection
xc2 = max_clip_x;
yc2 = y2 + 0.5+(max_clip_x-x2)*(y1-y2)/(x1-x2);
} // end if
} break;
case CLIP_CODE_NW:
{
// north hline intersection
yc2 = min_clip_y;
xc2 = x2 + 0.5+(min_clip_y-y2)*(x1-x2)/(y1-y2);
// test if intersection is valid, of so then done, else compute next
if (xc2 < min_clip_x || xc2 > max_clip_x)
{
xc2 = min_clip_x;
yc2 = y2 + 0.5+(min_clip_x-x2)*(y1-y2)/(x1-x2);
} // end if
} break;
case CLIP_CODE_SW:
{
// south hline intersection
yc2 = max_clip_y;
xc2 = x2 + 0.5+(max_clip_y-y2)*(x1-x2)/(y1-y2);
// test if intersection is valid, of so then done, else compute next
if (xc2 < min_clip_x || xc2 > max_clip_x)
{
xc2 = min_clip_x;
yc2 = y2 + 0.5+(min_clip_x-x2)*(y1-y2)/(x1-x2);
} // end if
} break;
default:break;
} // end switch
// do bounds check
if ((xc1 < min_clip_x) || (xc1 > max_clip_x) ||
(yc1 < min_clip_y) || (yc1 > max_clip_y) ||
(xc2 < min_clip_x) || (xc2 > max_clip_x) ||
(yc2 < min_clip_y) || (yc2 > max_clip_y) )
{
return(0);
} // end if
// store vars back
x1 = xc1;
y1 = yc1;
x2 = xc2;
y2 = yc2;
return(1);
} // end Clip_Line
/////////////////////////////////////////////////////////////
int Draw_Line(int x0, int y0, // starting position
int x1, int y1, // ending position
UCHAR color, // color index
UCHAR *vb_start, int lpitch) // video buffer and memory pitch
{
// this function draws a line from xo,yo to x1,y1 using differential error
// terms (based on Bresenahams work)
int dx, // difference in x's
dy, // difference in y's
dx2, // dx,dy * 2
dy2,
x_inc, // amount in pixel space to move during drawing
y_inc, // amount in pixel space to move during drawing
error, // the discriminant i.e. error i.e. decision variable
index; // used for looping
// pre-compute first pixel address in video buffer
vb_start = vb_start + x0 + y0*lpitch;
// compute horizontal and vertical deltas
dx = x1-x0;
dy = y1-y0;
// test which direction the line is going in i.e. slope angle
if (dx>=0)
{
x_inc = 1;
} // end if line is moving right
else
{
x_inc = -1;
dx = -dx; // need absolute value
} // end else moving left
// test y component of slope
if (dy>=0)
{
y_inc = lpitch;
} // end if line is moving down
else
{
y_inc = -lpitch;
dy = -dy; // need absolute value
} // end else moving up
// compute (dx,dy) * 2
dx2 = dx << 1;
dy2 = dy << 1;
// now based on which delta is greater we can draw the line
if (dx > dy)
{
// initialize error term
error = dy2 - dx;
// draw the line
for (index=0; index <= dx; index++)
{
// set the pixel
*vb_start = color;
// test if error has overflowed
if (error >= 0)
{
error-=dx2;
// move to next line
vb_start+=y_inc;
} // end if error overflowed
// adjust the error term
error+=dy2;
// move to the next pixel
vb_start+=x_inc;
} // end for
} // end if |slope| <= 1
else
{
// initialize error term
error = dx2 - dy;
// draw the line
for (index=0; index <= dy; index++)
{
// set the pixel
*vb_start = color;
// test if error overflowed
if (error >= 0)
{
error-=dy2;
// move to next line
vb_start+=x_inc;
} // end if error overflowed
// adjust the error term
error+=dx2;
// move to the next pixel
vb_start+=y_inc;
} // end for
} // end else |slope| > 1
// return success
return(1);
} // end Draw_Line
///////////////////////////////////////////////////////////////
LRESULT CALLBACK WindowProc(HWND hwnd,
UINT msg,
WPARAM wparam,
LPARAM lparam)
{
// this is the main message handler of the system
PAINTSTRUCT ps; // used in WM_PAINT
HDC hdc; // handle to a device context
char buffer[80]; // used to print strings
// what is the message
switch(msg)
{
case WM_CREATE:
{
// do initialization stuff here
// return success
return(0);
} break;
case WM_PAINT:
{
// simply validate the window
hdc = BeginPaint(hwnd,&ps);
// end painting
EndPaint(hwnd,&ps);
// return success
return(0);
} break;
case WM_DESTROY:
{
// kill the application, this sends a WM_QUIT message
PostQuitMessage(0);
// return success
return(0);
} break;
default:break;
} // end switch
// process any messages that we didn't take care of
return (DefWindowProc(hwnd, msg, wparam, lparam));
} // end WinProc
///////////////////////////////////////////////////////////
int Game_Main(void *parms = NULL, int num_parms = 0)
{
// this is the main loop of the game, do all your processing
// here
// make sure this isn't executed again
if (window_closed)
return(0);
// for now test if user is hitting ESC and send WM_CLOSE
if (KEYDOWN(VK_ESCAPE))
{
PostMessage(main_window_handle,WM_CLOSE,0,0);
window_closed = 1;
} // end if
// clear out the back buffer
DDraw_Fill_Surface(lpddsback, 0);
// lock primary buffer
DDRAW_INIT_STRUCT(ddsd);
if (FAILED(lpddsback->Lock(NULL,&ddsd,
DDLOCK_WAIT | DDLOCK_SURFACEMEMORYPTR,
NULL)))
return(0);
// do the graphics
Draw_Polygon2D(&ship, (UCHAR *)ddsd.lpSurface, ddsd.lPitch);
// test for scale
if (KEYDOWN('A')) // scale up
Scale_Polygon2D_Mat(&ship, 1.1, 1.1);
else
if (KEYDOWN('S')) // scale down
Scale_Polygon2D_Mat(&ship, 0.9, 0.9);
// test for rotate
if (KEYDOWN('Z')) // rotate left
Rotate_Polygon2D_Mat(&ship, -5);
else
if (KEYDOWN('X')) // rotate right
Rotate_Polygon2D_Mat(&ship, 5);
// test for translate
if (KEYDOWN(VK_RIGHT)) // translate right
Translate_Polygon2D_Mat(&ship, 5, 0);
else
if (KEYDOWN(VK_LEFT)) // translate left
Translate_Polygon2D_Mat(&ship, -5, 0);
// test for translate
if (KEYDOWN(VK_UP)) // translate up
Translate_Polygon2D_Mat(&ship, 0, -5);
else
if (KEYDOWN(VK_DOWN)) // translate left
Translate_Polygon2D_Mat(&ship, 0, 5);
// unlock primary buffer
if (FAILED(lpddsback->Unlock(NULL)))
return(0);
// draw some information
sprintf(buffer,"(x,y) = [%d, %d] ",ship.x0, ship.y0);
Draw_Text_GDI(buffer, 8,SCREEN_HEIGHT - 16,255, lpddsback);
Draw_Text_GDI("<A> and <S> - Scale <Z> and <X> - Rotate <Arrows> - Translate <ESC> - Exit", 8,8,255, lpddsback);
// perform the flip
while (FAILED(lpddsprimary->Flip(NULL, DDFLIP_WAIT)));
// wait a sec
Sleep(33);
// return success or failure or your own return code here
return(1);
} // end Game_Main
////////////////////////////////////////////////////////////
int Game_Init(void *parms = NULL, int num_parms = 0)
{
// this is called once after the initial window is created and
// before the main event loop is entered, do all your initialization
// here
// seed random number generator
srand(GetTickCount());
// create IDirectDraw interface 7.0 object and test for error
if (FAILED(DirectDrawCreateEx(NULL, (void **)&lpdd, IID_IDirectDraw7, NULL)))
return(0);
// set cooperation to full screen
if (FAILED(lpdd->SetCooperativeLevel(main_window_handle,
DDSCL_FULLSCREEN | DDSCL_ALLOWMODEX |
DDSCL_EXCLUSIVE | DDSCL_ALLOWREBOOT)))
return(0);
// set display mode to 640x480x8
if (FAILED(lpdd->SetDisplayMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP,0,0)))
return(0);
// clear ddsd and set size
DDRAW_INIT_STRUCT(ddsd);
// enable valid fields
ddsd.dwFlags = DDSD_CAPS | DDSD_BACKBUFFERCOUNT;
// set the backbuffer count field to 1, use 2 for triple buffering
ddsd.dwBackBufferCount = 1;
// request a complex, flippable
ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE | DDSCAPS_COMPLEX | DDSCAPS_FLIP;
// create the primary surface
if (FAILED(lpdd->CreateSurface(&ddsd, &lpddsprimary, NULL)))
return(0);
// now query for attached surface from the primary surface
// this line is needed by the call
ddsd.ddsCaps.dwCaps = DDSCAPS_BACKBUFFER;
// get the attached back buffer surface
if (FAILED(lpddsprimary->GetAttachedSurface(&ddsd.ddsCaps, &lpddsback)))
return(0);
// build up the palette data array
for (int color=1; color < 255; color++)
{
// fill with random RGB values
palette[color].peRed = rand()%256;
palette[color].peGreen = rand()%256;
palette[color].peBlue = rand()%256;
// set flags field to PC_NOCOLLAPSE
palette[color].peFlags = PC_NOCOLLAPSE;
} // end for color
// now fill in entry 0 and 255 with black and white
palette[0].peRed = 0;
palette[0].peGreen = 0;
palette[0].peBlue = 0;
palette[0].peFlags = PC_NOCOLLAPSE;
palette[255].peRed = 255;
palette[255].peGreen = 255;
palette[255].peBlue = 255;
palette[255].peFlags = PC_NOCOLLAPSE;
// make some primary colors
palette[1].peRed = 255;
palette[1].peGreen = 0;
palette[1].peBlue = 0;
palette[1].peFlags = PC_NOCOLLAPSE;
palette[2].peRed = 0;
palette[2].peGreen = 255;
palette[2].peBlue = 0;
palette[2].peFlags = PC_NOCOLLAPSE;
palette[3].peRed = 0;
palette[3].peGreen = 0;
palette[3].peBlue = 255;
palette[3].peFlags = PC_NOCOLLAPSE;
// create the palette object
if (FAILED(lpdd->CreatePalette(DDPCAPS_8BIT | DDPCAPS_ALLOW256 |
DDPCAPS_INITIALIZE,
palette,&lpddpal, NULL)))
return(0);
// finally attach the palette to the primary surface
if (FAILED(lpddsprimary->SetPalette(lpddpal)))
return(0);
// clear the surfaces out
DDraw_Fill_Surface(lpddsprimary, 0 );
DDraw_Fill_Surface(lpddsback, 0 );
// define points of ship
VERTEX2DF ship_vertices[24] =
{1,11,
2,8,
1,7,
1,-1,
3,-1,
3,-2,
11,-3,
11,-6,
3,-7,
2,-8,
1,-8,
1,-7,
-1,-7,
-1,-8,
-2,-8,
-3,-7,
-11,-6,
-11,-3,
-3,-2,
-3,-1,
-1,-1,
-1,7,
-2,8,
-1, 11};
// initialize ship
ship.state = 1; // turn it on
ship.num_verts = 24;
ship.x0 = SCREEN_WIDTH/2; // position it
ship.y0 = SCREEN_HEIGHT/2;
ship.xv = 0;
ship.yv = 0;
ship.color = 2; // green
ship.vlist = new VERTEX2DF [ship.num_verts];
for (int index = 0; index < ship.num_verts; index++)
ship.vlist[index] = ship_vertices[index];
// do a quick scale on the vertices, they are a bit too small
Scale_Polygon2D(&ship, 3.0, 3.0);
// create sin/cos lookup table
// generate the tables
for (int ang = 0; ang < 360; ang++)
{
// convert ang to radians
float theta = (float)ang*PI/(float)180;
// insert next entry into table
cos_look[ang] = cos(theta);
sin_look[ang] = sin(theta);
} // end for ang
// hide the cursor
ShowCursor(0);
// return success or failure or your own return code here
return(1);
} // end Game_Init
/////////////////////////////////////////////////////////////
int Game_Shutdown(void *parms = NULL, int num_parms = 0)
{
// this is called after the game is exited and the main event
// loop while is exited, do all you cleanup and shutdown here
// first the palette
if (lpddpal)
{
lpddpal->Release();
lpddpal = NULL;
} // end if
// now the back buffer surface
if (lpddsback)
{
lpddsback->Release();
lpddsback = NULL;
} // end if
// now the primary surface
if (lpddsprimary)
{
lpddsprimary->Release();
lpddsprimary = NULL;
} // end if
// now blow away the IDirectDraw4 interface
if (lpdd)
{
lpdd->Release();
lpdd = NULL;
} // end if
// show the cursor
ShowCursor(1);
// return success or failure or your own return code here
return(1);
} // end Game_Shutdown
// WINMAIN ////////////////////////////////////////////////
int WINAPI WinMain( HINSTANCE hinstance,
HINSTANCE hprevinstance,
LPSTR lpcmdline,
int ncmdshow)
{
WNDCLASSEX winclass; // this will hold the class we create
HWND hwnd; // generic window handle
MSG msg; // generic message
HDC hdc; // graphics device context
// first fill in the window class stucture
winclass.cbSize = sizeof(WNDCLASSEX);
winclass.style = CS_DBLCLKS | CS_OWNDC |
CS_HREDRAW | CS_VREDRAW;
winclass.lpfnWndProc = WindowProc;
winclass.cbClsExtra = 0;
winclass.cbWndExtra = 0;
winclass.hInstance = hinstance;
winclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
winclass.hCursor = LoadCursor(NULL, IDC_ARROW);
winclass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
winclass.lpszMenuName = NULL;
winclass.lpszClassName = WINDOW_CLASS_NAME;
winclass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
// save hinstance in global
hinstance_app = hinstance;
// register the window class
if (!RegisterClassEx(&winclass))
return(0);
// create the window
if (!(hwnd = CreateWindowEx(NULL, // extended style
WINDOW_CLASS_NAME, // class
"DirectDraw 8-Bit Polygon Matrix Transformation Demo", // title
WS_POPUP | WS_VISIBLE,
0,0, // initial x,y
SCREEN_WIDTH,SCREEN_HEIGHT, // initial width, height
NULL, // handle to parent
NULL, // handle to menu
hinstance,// instance of this application
NULL))) // extra creation parms
return(0);
// save main window handle
main_window_handle = hwnd;
// initialize game here
Game_Init();
// enter main event loop
while(TRUE)
{
// test if there is a message in queue, if so get it
if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))
{
// test if this is a quit
if (msg.message == WM_QUIT)
break;
// translate any accelerator keys
TranslateMessage(&msg);
// send the message to the window proc
DispatchMessage(&msg);
} // end if
// main game processing goes here
Game_Main();
} // end while
// closedown game here
Game_Shutdown();
// return to Windows like this
return(msg.wParam);
} // end WinMain
///////////////////////////////////////////////////////////
| [
"syver.enstad@cisco.com"
] | syver.enstad@cisco.com |
ba0ae75e3072d14cd0322ae1e9d9f68146261d6c | 75af9ed348bc6d8dc9ff03ec898309bebce485db | /src/AOSGUI/paw_gui_tab_basic.cpp | 13133ff1bf3676462c5f0a09b96d29f924de7267 | [
"MIT"
] | permissive | creikey/Game-Pencil-Engine | eea63d5345f6c7f516fb4ab108709444529d3568 | 961a33f090b6b8d94a660db9e4b67644d829c96f | refs/heads/master | 2020-07-08T12:53:04.073564 | 2019-08-21T23:36:55 | 2019-08-21T23:36:55 | 203,677,843 | 0 | 0 | MIT | 2019-08-21T23:16:40 | 2019-08-21T23:16:40 | null | UTF-8 | C++ | false | false | 12,305 | cpp | /*
paw_gui_tab_basic.cpp
This file is part of:
GAME PENCIL ENGINE
https://create.pawbyte.com
Copyright (c) 2014-2019 Nathan Hurde, Chase Lee.
Copyright (c) 2014-2019 PawByte LLC.
Copyright (c) 2014-2019 Game Pencil Engine contributors ( Contributors Page )
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.
-Game Pencil Engine <https://create.pawbyte.com>
*/
#include "paw_gui_tab_basic.h"
GPE_TabBar::GPE_TabBar( bool dynamicClosing )
{
canCloseTabs = dynamicClosing;
needsNewLine = true;
isFullWidth = true;
tabIsRightClicked = false;
isInUse = false;
guiListTypeName = "tabbar";
elementBox.x = 16;
elementBox.y = 16;
elementBox.w = 32;
elementBox.h = 18;
barXPadding = GENERAL_GPE_PADDING;
barYPadding = 4;
fontTextWidth = 12;
fontTextHeight = 12;
if( GUI_TAB_FONT!=NULL)
{
GUI_TAB_FONT->get_metrics("A",&fontTextWidth,&fontTextHeight);
}
else
{
fontTextWidth = 12;
fontTextHeight = 12;
}
tabInUse = 0;
tabSize = -1; //defaults to equally divide the tab onto the screen
miniTabSize = 48;
extraSmallSize = 64;
smallTabSize = 96;
medTabSize = 128;
largeTabSize = 160;
extraLargeTabSize = 192;
xxLargeTabSize = 256;
tabsPerView = -1;
tabPos = 0;
}
GPE_TabBar::~GPE_TabBar()
{
subOptions.clear();
}
void GPE_TabBar::add_new_tab(std::string newOption, bool switchToNew )
{
if( (int)newOption.size() > 0)
{
//automatically add resource to when the tab bar is empty
if( switchToNew)
{
tabInUse = (int)subOptions.size();
}
subOptions.push_back(newOption);
calculate_tabs();
}
}
void GPE_TabBar::calculate_tabs()
{
int currentSize = (int)subOptions.size();
if( tabPos >= currentSize )
{
tabPos = currentSize -1;
}
if( tabPos < 0)
{
tabPos = 0;
}
if( tabInUse >= currentSize )
{
tabInUse = currentSize - 1;
}
if( tabPos < 0)
{
tabInUse = 0;
}
if( currentSize == 0 )
{
tabSize = elementBox.w;
}
else
{
tabSize = elementBox.w/ currentSize;
}
}
bool GPE_TabBar::contains_tab( std::string tabName )
{
if( (int)tabName.size() > 0)
{
for( int i = 0; i < (int)subOptions.size(); i++)
{
if( tabName==subOptions[i] )
{
return true;
}
}
}
return false;
}
void GPE_TabBar::open_tab(int tabId)
{
if( tabId >=0 && tabId < (int)subOptions.size() )
{
tabInUse = tabId;
}
else
{
tabInUse = 0;
}
}
void GPE_TabBar::open_tab(std::string tabName)
{
if( (int)tabName.size() > 0)
{
for( int i = 0; i < (int)subOptions.size(); i++)
{
if( tabName==subOptions[i] )
{
tabInUse = i;
break;
}
}
}
}
std::string GPE_TabBar::get_selected_name()
{
if( (int)subOptions.size() > 0 )
{
if( tabInUse >=0 && tabInUse < (int)subOptions.size() )
{
return subOptions[tabInUse];
}
}
return "";
}
int GPE_TabBar::get_selected_tab()
{
return tabInUse;
}
int GPE_TabBar::get_tab_count()
{
return (int)subOptions.size();
}
void GPE_TabBar::process_self(GPE_Rect * viewedSpace,GPE_Rect *cam)
{
viewedSpace = GPE_find_camera(viewedSpace);
cam = GPE_find_camera(cam);
tabIsRightClicked = false;
//elementBox.w = viewedSpace->w - elementBox.x;
if( elementBox.w!=0 && viewedSpace!=NULL && cam!=NULL)
{
GPE_GeneralGuiElement::process_self(viewedSpace, cam);
calculate_tabs();
if( isClicked || isRightClicked)
{
isInUse = true;
}
else if( clickedOutside)
{
isInUse = false;
}
int cTabXPos = elementBox.x+viewedSpace->x-cam->x;
int cTabX2Pos = cTabXPos;
int cTabYPos = elementBox.y+viewedSpace->y-cam->y;
int cTabY2Pos = elementBox.y+elementBox.h+viewedSpace->y-cam->y;
int optionsSize = (int)subOptions.size();
cTabX2Pos += optionsSize * tabSize;
cTabXPos = cTabX2Pos - tabSize;
for(int i = optionsSize-1; i >=0; i--)
{
if(point_within(input->mouse_x,input->mouse_y,cTabXPos,cTabYPos,cTabX2Pos,cTabY2Pos) )
{
MAIN_OVERLAY->update_tooltip( subOptions[i] );
if( isClicked )
{
if( canCloseTabs )
{
if( point_between(input->mouse_x, input->mouse_y,cTabX2Pos-12,cTabYPos, cTabX2Pos,cTabY2Pos) )
{
subOptions.erase( subOptions.begin()+i );
tabInUse = i -1;
return;
}
else
{
tabInUse = i;
}
}
else
{
tabInUse = i;
}
}
if( isRightClicked )
{
tabIsRightClicked = true;
tabInUse = i;
}
}
cTabX2Pos = cTabXPos;
cTabXPos-=tabSize;
}
if( isInUse)
{
if( input->check_keyboard_released(kb_left) && tabInUse > 0)
{
tabInUse--;
}
else if( input->check_keyboard_released(kb_right) && tabInUse < (int)subOptions.size()-1 )
{
tabInUse++;
}
}
}
}
void GPE_TabBar::remove_all_tabs( )
{
subOptions.clear();
isClicked = false;
tabIsRightClicked = false;
tabPos = tabInUse = 0;
calculate_tabs();
}
bool GPE_TabBar::remove_tab( int tabId )
{
if( tabId >=0 && tabId < (int)subOptions.size() )
{
subOptions.erase(subOptions.begin()+tabId );
calculate_tabs();
}
}
bool GPE_TabBar::remove_tab( std::string tabName )
{
//Reverse iterate for safety
for( int i = (int)subOptions.size()-1; i >=0; i--)
{
if( subOptions.at(i) ==tabName )
{
subOptions.erase(subOptions.begin()+i );
calculate_tabs();
}
}
}
void GPE_TabBar::render_self( GPE_Rect * viewedSpace,GPE_Rect * cam, bool forceRedraw)
{
//gcanvas->render_rect(&elementBox,barColor,false);
//gcanvas->render_rect(&elementBox,barOutlineColor,true);
viewedSpace = GPE_find_camera(viewedSpace);
cam = GPE_find_camera(cam);
if(forceRedraw && viewedSpace!=NULL && cam!=NULL)
{
if( (int)subOptions.size() >0 )
{
std::string tabOptionStr = "";
int tabFontWidth = 0;
int tabFontHeight = 0;
int maxCharactersAllowed = 0;
GUI_TAB_FONT->get_metrics("A", &tabFontWidth, &tabFontHeight );
maxCharactersAllowed = tabSize/tabFontWidth -1;
int cTabXPos = elementBox.x-cam->x;
int cTabX2Pos = elementBox.x-cam->x;
int cTabY1Pos = elementBox.y-cam->y;
int cTabY2Pos = elementBox.y-cam->y+elementBox.h;
for(int i=0; i< (int)subOptions.size(); i++)
{
cTabX2Pos+=tabSize;
tabOptionStr = subOptions[i];
if( (int)tabOptionStr.size() > maxCharactersAllowed )
{
if( maxCharactersAllowed > 1 )
{
tabOptionStr = get_substring( tabOptionStr,0,maxCharactersAllowed-1 )+"..";
}
else
{
tabOptionStr = get_substring( tabOptionStr,0, 1 );
}
}
if( tabInUse==i)
{
gcanvas->render_rectangle( cTabXPos,elementBox.y-cam->y,cTabX2Pos,elementBox.y+elementBox.h-cam->y,GPE_MAIN_THEME->Program_Header_Color,false);
gcanvas->render_rectangle( cTabXPos,elementBox.y-cam->y,cTabX2Pos,elementBox.y+elementBox.h-cam->y,GPE_MAIN_THEME->Main_Border_Color,true);
gfs->render_text( cTabXPos+tabSize/2,elementBox.y+elementBox.h/2-cam->y, tabOptionStr, GPE_MAIN_THEME->PopUp_Box_Font_Color,GUI_TAB_FONT,FA_CENTER,FA_MIDDLE);
}
else
{
gcanvas->render_rectangle( cTabXPos,elementBox.y-cam->y,cTabX2Pos,elementBox.y+elementBox.h-cam->y,GPE_MAIN_THEME->Program_Color,false);
gcanvas->render_rectangle( cTabXPos,elementBox.y-cam->y,cTabX2Pos,elementBox.y+elementBox.h-cam->y,GPE_MAIN_THEME->Main_Border_Color,true);
gfs->render_text( cTabXPos+tabSize/2,elementBox.y+elementBox.h/2-cam->y, tabOptionStr, GPE_MAIN_THEME->Main_Box_Font_Color,GUI_TAB_FONT,FA_CENTER,FA_MIDDLE);
}
if( canCloseTabs )
{
if( point_between(input->mouse_x, input->mouse_y,viewedSpace->x+cTabX2Pos-32,viewedSpace->y+cTabY1Pos, viewedSpace->x+cTabX2Pos,viewedSpace->y+cTabY2Pos) )
{
gfs->render_text( cTabXPos+tabSize-GENERAL_GPE_PADDING,elementBox.y+elementBox.h/2-cam->y, "X", GPE_MAIN_THEME->Main_Box_Font_Highlight_Color,GUI_TAB_FONT,FA_RIGHT,FA_MIDDLE);
}
else
{
gfs->render_text( cTabXPos+tabSize-GENERAL_GPE_PADDING,elementBox.y+elementBox.h/2-cam->y, "X", GPE_MAIN_THEME->Main_Box_Font_Color,GUI_TAB_FONT,FA_RIGHT,FA_MIDDLE);
}
}
cTabXPos = cTabX2Pos;
}
}
else
{
gcanvas->render_rectangle( elementBox.x-cam->x,elementBox.y-cam->y,elementBox.x+elementBox.w-cam->x,elementBox.y+elementBox.h-cam->y,GPE_MAIN_THEME->Program_Color,false);
gcanvas->render_rectangle( elementBox.x-cam->x,elementBox.y-cam->y,elementBox.x+elementBox.w-cam->x,elementBox.y+elementBox.h-cam->y,GPE_MAIN_THEME->Main_Border_Color,true);
}
/*if( isHovered)
{
//Uncomment in the even a tab bar randomly behaves weirdly
gcanvas->render_rectangle( elementBox.x-cam->x,elementBox.y-cam->y,elementBox.x+elementBox.w-cam->x,elementBox.y+elementBox.h-cam->y,GPE_MAIN_THEME->Main_Border_Highlighted_Color,true);
}*/
}
}
void GPE_TabBar::select_tab( int tabToSelect )
{
if( tabToSelect >=0 && tabToSelect < (int)subOptions.size() )
{
tabInUse = tabToSelect;
}
}
void GPE_TabBar::toggle_tab( std::string tabName )
{
if( contains_tab( tabName) )
{
remove_tab( tabName);
}
else
{
add_new_tab( tabName);
}
}
| [
"chase@pawbyte.com"
] | chase@pawbyte.com |
6393266e6dc3946cfc6400faf26deaecc8f7cb44 | aafbd0448f9d34c839f1b753854c39289784896a | /src/config/manager/ConfigManager.cpp | cddba5884cc12fd456aae2fe8e3f1fac3d3c625c | [] | no_license | adahbingee/config-manager | bc41f6ef2b8e59de1fb743a7857a9617e2919da1 | 1a6c3954e4e5b3436d45d46174c37b030724c6e9 | refs/heads/master | 2021-01-11T00:46:59.306698 | 2019-08-22T10:04:41 | 2019-08-22T10:04:41 | 70,488,771 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 646 | cpp | #include <iostream>
#include <fstream>
#include "../config.h"
#include "ConfigManager.h"
#include "ConfigManagerRead.inc"
#include "ConfigManagerPrint.inc"
#include "ConfigManagerWrite.inc"
#include "ConfigManagerMacro.inc"
using namespace std;
void ConfigManager::read(const char *fileName) {
fstream file(fileName, ios::in);
if ( !file.is_open() ) {
printf("can't open %s\n", fileName);
}
while( getline(file, line) ){
CFG_READ_MACRO
}
file.close();
}
void ConfigManager::write(const char *fileName) {
writeFile = fopen(fileName, "w");
CFG_WRITE_MACRO
fclose( writeFile );
}
void ConfigManager::print() {
CFG_PRINT_MACRO
}
| [
"adahbingee@gmail.com"
] | adahbingee@gmail.com |
7a0d6ee7d192ed943a50a392e03dd6146e2a9bf5 | d147f9c98bae97ed79cef2597977f61c83724c39 | /STLWorkspace/Exam/DXExam1/DirectX_Assignment/02. Direct3D/Engine.cpp | ed5f37ca4a01cb33ef6354fcda59302ece95a4ca | [] | no_license | daaie/SkillTreeLab | 28ec4bea1057d4c44a5f15bcfb1e0178358f85e1 | 43482b9a4732836ad7b0f2df5c29c6b1debfa913 | refs/heads/master | 2020-03-17T05:06:08.824446 | 2018-07-17T04:49:47 | 2018-07-17T04:49:47 | 133,302,446 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 408 | cpp | #include "Engine.h"
#include <d3d11.h>
Engine::Engine(HINSTANCE hinstance)
: DXApp(hinstance)
{
}
Engine::~Engine()
{
}
bool Engine::Init()
{
if (DXApp::Init() == false)
return false;
return true;
}
void Engine::Update()
{
}
void Engine::Render()
{
float color[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
pDeviceContext->ClearRenderTargetView(pRenderTargetView, color);
pSwapChain->Present(0, 0);
}
| [
"pda4423@gmail.com"
] | pda4423@gmail.com |
2555752bbc37795817f1095be90b19d19d7029cc | 38c29c3c4c97e4831b2882d02f245161ccdd63e7 | /VoxelEngine_V2/engine/textures/BaseTexture.h | 47d242072b97b2cc45a02411a53094b0b104a97c | [] | no_license | incetents/VoxelEngine_V2 | fc7f9ac7f0977fa9467b0d0516dd8eddb661bb33 | 91d5c2e96a297ac8144a8a2c78216943cfed60dc | refs/heads/master | 2020-04-06T08:57:28.877501 | 2020-01-26T05:05:57 | 2020-01-26T05:05:57 | 157,323,605 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,080 | h | // Copyright (c) 2020 Emmanuel Lajeunesse
#pragma once
#include "../rendering/Graphics.h"
#include "../utilities/Types.h"
#include "../utilities/Macros.h"
#include "../math/Color.h"
#include <map>
#include <string>
namespace Vxl
{
class RenderBuffer;
class BaseTexture
{
protected:
// Data //
TextureID m_id = -1;
bool m_loaded = false;
bool m_mipMapping = false;
int m_width;
int m_height;
int m_channelCount;
Color4F m_borderColor = Color4F(0, 0, 0, 1);
TextureType m_type;
TextureWrapping m_wrapMode;
TextureFilter m_filterMode;
TextureFormat m_formatType;
TextureChannelType m_channelType;
TexturePixelType m_pixelType;
AnisotropicMode m_anisotropicMode;
// Creation/Deletion
void load();
void unload();
// Storage
virtual void createStorage(); // Create space for texture [immutable, cannot be resized]
virtual void setStorage(const void* pixels);
// Utility
void updateParameters();
void updateMipmapping();
void flipImageVertically(uint8_t* imagePixels);
public:
BaseTexture(const BaseTexture&) = delete;
BaseTexture(
TextureType Type,
TextureWrapping WrapMode = TextureWrapping::REPEAT,
TextureFilter FilterMode = TextureFilter::LINEAR,
TextureFormat FormatType = TextureFormat::RGBA8,
TextureChannelType ChannelType = TextureChannelType::RGBA,
TexturePixelType PixelType = TexturePixelType::UNSIGNED_BYTE,
AnisotropicMode AnisotropicMode = AnisotropicMode::NONE,
bool MipMapping = false
);
virtual ~BaseTexture();
void bind(TextureLevel layer) const;
void bind() const;
void unbind() const;
//void copy(const BaseTexture& _texture);
//void copy(const RenderBuffer& _texture);
void setWrapMode(TextureWrapping W);
void setFilterMode(TextureFilter filter);
void setAnistropicMode(AnisotropicMode Anso);
// only works if min filter is [clamp to border]
void setBorderColor(Color4F color);
void setGLName(const std::string& glName);
inline TextureID getID(void) const
{
return m_id;
}
inline bool isMipMapping(void) const
{
return m_mipMapping;
}
inline int getWidth(void) const
{
return m_width;
}
inline int getHeight(void) const
{
return m_height;
}
inline int getChannelCount(void) const
{
return m_channelCount;
}
inline Color4F getBorderColor(void) const
{
return m_borderColor;
}
inline TextureType getType(void) const
{
return m_type;
}
inline TextureWrapping getWrapMode(void) const
{
return m_wrapMode;
}
inline TextureFilter getFilterMode(void) const
{
return m_filterMode;
}
inline TextureFormat getFormatType(void) const
{
return m_formatType;
}
inline TextureChannelType getChannelType(void) const
{
return m_channelType;
}
inline TexturePixelType getPixelType(void) const
{
return m_pixelType;
}
virtual bool isLoaded(void) const
{
return true;
}
};
} | [
"incetents99@gmail.com"
] | incetents99@gmail.com |
d0c36eb1184e312e7f862948fdf069c8d274389a | b7b1f8b63c1f3ef92fa1a016e395b8565ea37242 | /online/include/net/InetAddress.h | 8ad96b76a098f85c927bc421fdd57256619416c4 | [] | no_license | NE0T12/mini_Search_Engine | b366786345b8c9702daed7c1159d952f50f5698a | 0e9b69c9e261986f45fb534db174cc50fa3eb94d | refs/heads/master | 2020-03-20T02:12:44.141690 | 2018-06-25T10:14:20 | 2018-06-25T10:14:20 | 137,103,793 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 575 | h | ///
/// @file InetAddress.h
/// @author lemon(haohb13@gmail.com)
/// @date 2015-11-04 17:08:29
///
#ifndef _WD_INETADDRESS_H
#define _WD_INETADDRESS_H
#include <netinet/in.h>
#include <string>
namespace wd
{
class InetAddress
{
public:
InetAddress(){}
InetAddress(short port);
InetAddress(const char * pIp, short port);
InetAddress(const struct sockaddr_in & addr);
const struct sockaddr_in * getSockAddrPtr() const;
std::string ip() const;
unsigned short port() const;
private:
struct sockaddr_in addr_;
};
}// end of namespace wd
#endif
| [
"xgwtruth@outlook.com"
] | xgwtruth@outlook.com |
3eb9baeb5be93d3009927d558703cdd676c0e4cc | 2cf838b54b556987cfc49f42935f8aa7563ea1f4 | /aws-cpp-sdk-sagemaker/include/aws/sagemaker/model/RepositoryAuthConfig.h | 13ac347436c9a8f0342438eb53d107031c3c991e | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | QPC-database/aws-sdk-cpp | d11e9f0ff6958c64e793c87a49f1e034813dac32 | 9f83105f7e07fe04380232981ab073c247d6fc85 | refs/heads/main | 2023-06-14T17:41:04.817304 | 2021-07-09T20:28:20 | 2021-07-09T20:28:20 | 384,714,703 | 1 | 0 | Apache-2.0 | 2021-07-10T14:16:41 | 2021-07-10T14:16:41 | null | UTF-8 | C++ | false | false | 7,004 | h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/sagemaker/SageMaker_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace SageMaker
{
namespace Model
{
/**
* <p>Specifies an authentication configuration for the private docker registry
* where your model image is hosted. Specify a value for this property only if you
* specified <code>Vpc</code> as the value for the
* <code>RepositoryAccessMode</code> field of the <code>ImageConfig</code> object
* that you passed to a call to <code>CreateModel</code> and the private Docker
* registry where the model image is hosted requires authentication.</p><p><h3>See
* Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/sagemaker-2017-07-24/RepositoryAuthConfig">AWS
* API Reference</a></p>
*/
class AWS_SAGEMAKER_API RepositoryAuthConfig
{
public:
RepositoryAuthConfig();
RepositoryAuthConfig(Aws::Utils::Json::JsonView jsonValue);
RepositoryAuthConfig& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The Amazon Resource Name (ARN) of an Amazon Web Services Lambda function that
* provides credentials to authenticate to the private Docker registry where your
* model image is hosted. For information about how to create an Amazon Web
* Services Lambda function, see <a
* href="https://docs.aws.amazon.com/lambda/latest/dg/getting-started-create-function.html">Create
* a Lambda function with the console</a> in the <i>Amazon Web Services Lambda
* Developer Guide</i>.</p>
*/
inline const Aws::String& GetRepositoryCredentialsProviderArn() const{ return m_repositoryCredentialsProviderArn; }
/**
* <p>The Amazon Resource Name (ARN) of an Amazon Web Services Lambda function that
* provides credentials to authenticate to the private Docker registry where your
* model image is hosted. For information about how to create an Amazon Web
* Services Lambda function, see <a
* href="https://docs.aws.amazon.com/lambda/latest/dg/getting-started-create-function.html">Create
* a Lambda function with the console</a> in the <i>Amazon Web Services Lambda
* Developer Guide</i>.</p>
*/
inline bool RepositoryCredentialsProviderArnHasBeenSet() const { return m_repositoryCredentialsProviderArnHasBeenSet; }
/**
* <p>The Amazon Resource Name (ARN) of an Amazon Web Services Lambda function that
* provides credentials to authenticate to the private Docker registry where your
* model image is hosted. For information about how to create an Amazon Web
* Services Lambda function, see <a
* href="https://docs.aws.amazon.com/lambda/latest/dg/getting-started-create-function.html">Create
* a Lambda function with the console</a> in the <i>Amazon Web Services Lambda
* Developer Guide</i>.</p>
*/
inline void SetRepositoryCredentialsProviderArn(const Aws::String& value) { m_repositoryCredentialsProviderArnHasBeenSet = true; m_repositoryCredentialsProviderArn = value; }
/**
* <p>The Amazon Resource Name (ARN) of an Amazon Web Services Lambda function that
* provides credentials to authenticate to the private Docker registry where your
* model image is hosted. For information about how to create an Amazon Web
* Services Lambda function, see <a
* href="https://docs.aws.amazon.com/lambda/latest/dg/getting-started-create-function.html">Create
* a Lambda function with the console</a> in the <i>Amazon Web Services Lambda
* Developer Guide</i>.</p>
*/
inline void SetRepositoryCredentialsProviderArn(Aws::String&& value) { m_repositoryCredentialsProviderArnHasBeenSet = true; m_repositoryCredentialsProviderArn = std::move(value); }
/**
* <p>The Amazon Resource Name (ARN) of an Amazon Web Services Lambda function that
* provides credentials to authenticate to the private Docker registry where your
* model image is hosted. For information about how to create an Amazon Web
* Services Lambda function, see <a
* href="https://docs.aws.amazon.com/lambda/latest/dg/getting-started-create-function.html">Create
* a Lambda function with the console</a> in the <i>Amazon Web Services Lambda
* Developer Guide</i>.</p>
*/
inline void SetRepositoryCredentialsProviderArn(const char* value) { m_repositoryCredentialsProviderArnHasBeenSet = true; m_repositoryCredentialsProviderArn.assign(value); }
/**
* <p>The Amazon Resource Name (ARN) of an Amazon Web Services Lambda function that
* provides credentials to authenticate to the private Docker registry where your
* model image is hosted. For information about how to create an Amazon Web
* Services Lambda function, see <a
* href="https://docs.aws.amazon.com/lambda/latest/dg/getting-started-create-function.html">Create
* a Lambda function with the console</a> in the <i>Amazon Web Services Lambda
* Developer Guide</i>.</p>
*/
inline RepositoryAuthConfig& WithRepositoryCredentialsProviderArn(const Aws::String& value) { SetRepositoryCredentialsProviderArn(value); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of an Amazon Web Services Lambda function that
* provides credentials to authenticate to the private Docker registry where your
* model image is hosted. For information about how to create an Amazon Web
* Services Lambda function, see <a
* href="https://docs.aws.amazon.com/lambda/latest/dg/getting-started-create-function.html">Create
* a Lambda function with the console</a> in the <i>Amazon Web Services Lambda
* Developer Guide</i>.</p>
*/
inline RepositoryAuthConfig& WithRepositoryCredentialsProviderArn(Aws::String&& value) { SetRepositoryCredentialsProviderArn(std::move(value)); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of an Amazon Web Services Lambda function that
* provides credentials to authenticate to the private Docker registry where your
* model image is hosted. For information about how to create an Amazon Web
* Services Lambda function, see <a
* href="https://docs.aws.amazon.com/lambda/latest/dg/getting-started-create-function.html">Create
* a Lambda function with the console</a> in the <i>Amazon Web Services Lambda
* Developer Guide</i>.</p>
*/
inline RepositoryAuthConfig& WithRepositoryCredentialsProviderArn(const char* value) { SetRepositoryCredentialsProviderArn(value); return *this;}
private:
Aws::String m_repositoryCredentialsProviderArn;
bool m_repositoryCredentialsProviderArnHasBeenSet;
};
} // namespace Model
} // namespace SageMaker
} // namespace Aws
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
581861080f4a3db2808c0de4d82ef2557fd9723a | 7a17d90d655482898c6777c101d3ab6578ccc6ba | /SDK/PUBG_CameraShake_GrenadeDamage_Right_TPP_parameters.hpp | a8d16fa509dd5b89117acbd6f34e25b5eb296a61 | [] | no_license | Chordp/PUBG-SDK | 7625f4a419d5b028f7ff5afa5db49e18fcee5de6 | 1b23c750ec97cb842bf5bc2b827da557e4ff828f | refs/heads/master | 2022-08-25T10:07:15.641579 | 2022-08-14T14:12:48 | 2022-08-14T14:12:48 | 245,409,493 | 17 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 1,970 | hpp | #pragma once
// PUBG (9.1.5.3) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "PUBG_CameraShake_GrenadeDamage_Right_TPP_classes.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function Engine.CameraShake.ReceiveStopShake
struct UCameraShake_GrenadeDamage_Right_TPP_C_ReceiveStopShake_Params
{
bool bImmediately; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Engine.CameraShake.ReceivePlayShake
struct UCameraShake_GrenadeDamage_Right_TPP_C_ReceivePlayShake_Params
{
float Scale; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Engine.CameraShake.ReceiveIsFinished
struct UCameraShake_GrenadeDamage_Right_TPP_C_ReceiveIsFinished_Params
{
bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
};
// Function Engine.CameraShake.BlueprintUpdateCameraShake
struct UCameraShake_GrenadeDamage_Right_TPP_C_BlueprintUpdateCameraShake_Params
{
float DeltaTime; // (Parm, ZeroConstructor, IsPlainOldData)
float ALPHA; // (Parm, ZeroConstructor, IsPlainOldData)
struct FMinimalViewInfo POV; // (ConstParm, Parm, OutParm, ReferenceParm)
struct FMinimalViewInfo ModifiedPOV; // (Parm, OutParm)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"1263178881@qq.com"
] | 1263178881@qq.com |
f65f59f459be42fb7cb7f6097271ef32e2993727 | 32b934cb3ef99474b7295da510420ca4a03d6017 | /GamosRunManager/include/GmDeprecatedCommandsMessenger.hh | 8fb1a1d54027747d7cd06c13892114d905179cb0 | [] | no_license | ethanlarochelle/GamosCore | 450fc0eeb4a5a6666da7fdb75bcf5ee23a026238 | 70612e9a2e45b3b1381713503eb0f405530d44f0 | refs/heads/master | 2022-03-24T16:03:39.569576 | 2018-01-20T12:43:43 | 2018-01-20T12:43:43 | 116,504,426 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,093 | hh | //
// ********************************************************************
// * License and Disclaimer *
// * *
// * The GAMOS software is copyright of the Copyright Holders of *
// * the GAMOS Collaboration. It is provided under the terms and *
// * conditions of the GAMOS Software License, included in the file *
// * LICENSE and available at http://fismed.ciemat.es/GAMOS/license .*
// * These include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GAMOS collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the GAMOS Software license. *
// ********************************************************************
//
#ifndef GmDeprecatedCommandsMessenger_HH
#define GmDeprecatedCommandsMessenger_HH 1
#include "G4UImessenger.hh"
class G4UIcommand;
#include <map>
class GmDeprecatedCommandsMessenger: public G4UImessenger {
public:
GmDeprecatedCommandsMessenger();
~GmDeprecatedCommandsMessenger();
virtual void SetNewValue(G4UIcommand * command,G4String newValues);
private:
std::map<G4UIcommand*,G4String> theCommands;
};
#endif
| [
"ethanlarochelle@gmail.com"
] | ethanlarochelle@gmail.com |
151a7b3d1d028939de42f235a12b7e81a418f8f4 | 120b640cf0c673cd20387cda7b94219eb0b6bc4d | /src/BGL/BGLBounds.cc | c017e3cd1dbcdff7c50644ddfff3626e5d94821a | [] | no_license | giseburt/Miracle-Grue | a6ba431477c94e12e6f6cb269f6309895c33157a | e6aaa619d466b05d89f3026f0e694b74379bdfde | refs/heads/master | 2021-01-09T06:16:39.836293 | 2011-11-07T18:27:42 | 2011-11-07T18:27:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 419 | cc | #include "BGLBounds.h"
namespace BGL {
const Scalar Bounds::NONE = -9e9;
void Bounds::expand(const Point& pt)
{
if (minX == NONE) {
minX = maxX = pt.x;
minY = maxY = pt.y;
return;
}
if (pt.x < minX) {
minX = pt.x;
}
if (pt.x > maxX) {
maxX = pt.x;
}
if (pt.y < minY) {
minY = pt.y;
}
if (pt.y > maxY) {
maxY = pt.y;
}
}
}
| [
"phooky@gmail.com"
] | phooky@gmail.com |
b0bb7fcf485c8415c7d601a4b8602ee7521bc02d | d016a5ca6f4bd9e24d818895f6b807b9578e30a2 | /Bank_Managenmet_System/Main.cpp | 62b768e4433307c75fb5023ee73025ea9e01ded3 | [] | no_license | Xuandai2311/Bank_Managenmet_System | 283df3ffc84450f321315fba634367a1c85d4485 | 1b8d6975aced37fbce6a07d2f6a3cec5df9da05b | refs/heads/master | 2023-02-04T12:25:24.872394 | 2020-12-17T13:31:02 | 2020-12-17T13:31:02 | 321,990,344 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 114 | cpp | #include <iostream>
#include "ManagerAll.h"
using namespace std;
int main() {
ManagerAll all;
all.Wellcome();
} | [
"xuandai2311@gmail.com"
] | xuandai2311@gmail.com |
34d28a61a0bc77796c2cc0f5950a98e9d83a2c33 | bf02e7bb2afb68bd3a2d09dc49f7dc01dd9d5c13 | /media/learning/common/labelled_example.cc | 76d08509298e8f083f91e84d7da29e404187ddd7 | [
"BSD-3-Clause"
] | permissive | omrishalev22/chromium | 10dd559a502257d85ad3eead54ab437e33a1ce4d | 219e3cba255e390615f340e72ca629c89bca993e | refs/heads/master | 2022-09-07T01:41:02.760889 | 2019-02-08T07:39:12 | 2019-02-08T07:39:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,985 | cc | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/learning/common/labelled_example.h"
#include "base/containers/flat_set.h"
namespace media {
namespace learning {
LabelledExample::LabelledExample() = default;
LabelledExample::LabelledExample(std::initializer_list<FeatureValue> init_list,
TargetValue target)
: features(init_list), target_value(target) {}
LabelledExample::LabelledExample(const LabelledExample& rhs) = default;
LabelledExample::LabelledExample(LabelledExample&& rhs) noexcept = default;
LabelledExample::~LabelledExample() = default;
std::ostream& operator<<(std::ostream& out, const LabelledExample& example) {
out << example.features << " => " << example.target_value;
return out;
}
std::ostream& operator<<(std::ostream& out, const FeatureVector& features) {
for (const auto& feature : features)
out << " " << feature;
return out;
}
bool LabelledExample::operator==(const LabelledExample& rhs) const {
// Do not check weight.
return target_value == rhs.target_value && features == rhs.features;
}
bool LabelledExample::operator!=(const LabelledExample& rhs) const {
// Do not check weight.
return !((*this) == rhs);
}
bool LabelledExample::operator<(const LabelledExample& rhs) const {
// Impose a somewhat arbitrary ordering.
// Do not check weight.
if (target_value != rhs.target_value)
return target_value < rhs.target_value;
// Note that we could short-circuit this if the feature vector lengths are
// unequal, since we don't particularly care how they compare as long as it's
// stable. In particular, we don't have any notion of a "prefix".
return features < rhs.features;
}
LabelledExample& LabelledExample::operator=(const LabelledExample& rhs) =
default;
LabelledExample& LabelledExample::operator=(LabelledExample&& rhs) = default;
TrainingData::TrainingData() = default;
TrainingData::TrainingData(const TrainingData& rhs) = default;
TrainingData::TrainingData(TrainingData&& rhs) = default;
TrainingData::~TrainingData() = default;
TrainingData& TrainingData::operator=(const TrainingData& rhs) = default;
TrainingData& TrainingData::operator=(TrainingData&& rhs) = default;
TrainingData TrainingData::DeDuplicate() const {
// flat_set has non-const iterators, while std::set does not. const_cast is
// not allowed by chromium style outside of getters, so flat_set it is.
base::flat_set<LabelledExample> example_set;
for (auto& example : examples_) {
auto iter = example_set.find(example);
if (iter != example_set.end())
iter->weight += example.weight;
else
example_set.insert(example);
}
TrainingData deduplicated_data;
for (auto& example : example_set)
deduplicated_data.push_back(example);
return deduplicated_data;
}
} // namespace learning
} // namespace media
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
2bc7b3b97d89f351b5f77c0de48a10b275bd2090 | bbda384ad8babc940bb0bd6a6326f3c026626abd | /optmethod.h | b7b34f67ea085e2d3e73864e98ad6021ba605a94 | [] | no_license | vulden/FuncOpt | 2e5ea96400cdf4c9a759fc53ebe68e27a2e8db69 | 238662d71107d0125cb609ad1300ab554e78c5e0 | refs/heads/main | 2023-08-06T05:38:56.519325 | 2021-09-03T16:53:51 | 2021-09-03T16:53:51 | 304,396,390 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,827 | h | #ifndef OPTMETHOD_H
#define OPTMETHOD_H
/*!
\file
\brief Заголовочный файл с описанием классов, относящихся к методам, с помощью которых будет искаться минимум.
*/
#include <random>
#include "funcOpt.h"
#include "area.h"
#include "stopCrit.h"
#pragma once
/*!
\brief Родительский виртуальный класс методов.
Метод позволяет находить аргумент минимума функции.
*/
class OptMethod {
public:
/*!
Ищет аргумент, на котором реализуется минимум функции на области.
\param[in] x Функция для которой ищется минимум.
\param[in] a Область, в которой ищется минимум.
\param[in] stop Критерий остановки процесса поиска минимума.
\param[in] start Точка, с которой начинается процесс поиска минимума.
\param[in] iternum Число итераций.
\return Вектор координат значения, на котором реализуется минимум.
*/
virtual std::vector<double> optimize(func * x, area * a, StopCriteria* stop, std::vector<double> start, int iternum) =0;
virtual void set_eps(double){}
virtual void set_p(double){}
virtual void set_delta(double){}
virtual void set_len_of_seg(double){}
/*!
Выводит в консоль название метода.
*/
virtual void name_youself()=0;
};
/*!
\brief Дочерний класс методов.
Реализует поиск минимума вероятностным методом.
Унаследован от ранее созданного класса OptMethod.
*/
class CoordDescent: public OptMethod {
public:
//! Вещественная переменная.
/*! Xранит длину отрезка. */
double len_of_seg;
//! Вещественная переменная.
/*! Xранит желаемую точность вычислений. */
double eps;
/*!
Устанавливает точность.
\param[in] x Точность.
*/
void set_eps(double t)override;
/*!
Устанавливает длину отрезка.
\param[in] x Длина отрезка.
*/
void set_len_of_seg(double t)override;
/*!
Ищет аргумент, на котором реализуется минимум функции на области.
\param[in] x Функция для которой ищется минимум.
\param[in] a Область, в которой ищется минимум.
\param[in] stop Критерий остановки процесса поиска минимума.
\param[in] start Точка, с которой начинается процесс поиска минимума.
\param[in] iternum Число итераций.
\param[in] len_of_seg Длина интервала, на который разбиваются исходные отрезки.
\param[in] eps Точность, с которой ищется минимум.
\return Вектор координат значения, на котором реализуется минимум.
*/
std::vector<double> optimize(func *f, area *a, StopCriteria* stop, std::vector<double>, int iternum)override;
/*!
Выводит в консоль название метода.
*/
void name_youself() override;
};
/*!
\brief Дочерний класс методов.
Реализует поиск минимума методом c спуска.
Унаследован от ранее созданного класса OptMethod.
*/
class Stochastic:public OptMethod {
public:
//! Вещественная переменная.
/*! Xранит вероятность выбора окрестности в качестве области.*/
double p;
//! Вещественная переменная.
/*! Xранит размер окрестности. */
double delta;
/*!
Устанавливает вероятность выбора окрестности в качестве области.
\param[in] x Вероятность.
*/
void set_p(double t)override;
/*!
Устанавливает размер окрестности.
\param[in] x Размер окрестности.
*/
void set_delta(double t)override;
/*!
Ищет аргумент, на котором реализуется минимум функции на области.
\param[in] x Функция для которой ищется минимум.
\param[in] a Область, в которой ищется минимум.
\param[in] stop Критерий остановки процесса поиска минимума.
\param[in] start Точка, с которой начинается процесс поиска минимума.
\param[in] iternum Число итераций.
\param[in] p Вероятность того, что поиск будет продолжен в окрестности предыдущей точки.
\param[in] delta Размер окрестности.
\return Вектор координат значения, на котором реализуется минимум.
*/
std::vector<double> optimize(func *f, area *a, StopCriteria* stop, std::vector<double>, int iternum)override;
/*!
Выводит в консоль название метода.
*/
void name_youself() override;
};
#endif // OPTMETHOD_H
| [
"popov99vlad@gmail.com"
] | popov99vlad@gmail.com |
9346090cf569188c21112fdb88e28e4bf1b0453a | fe6f241c385dffa90bb9117717b0d31aa0d67472 | /src/lycon/transform/resize.h | dd6dd105d3485e55833bfb245fbd61cd8cc44797 | [
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | peter0749/lycon | 06bde7cbce75918d1148e0a1e38200345b8a8512 | 0e7b3e51f56140d68e0466d00be45d79b4de682b | refs/heads/master | 2022-07-03T13:40:59.218284 | 2020-05-16T15:28:12 | 2020-05-16T15:28:12 | 264,456,150 | 0 | 0 | NOASSERTION | 2020-05-16T14:34:11 | 2020-05-16T14:34:10 | null | UTF-8 | C++ | false | false | 1,379 | h | #pragma once
#include "lycon/mat/mat.h"
namespace lycon
{
enum InterpolationFlags
{
/** nearest neighbor interpolation */
INTER_NEAREST = 0,
/** bilinear interpolation */
INTER_LINEAR = 1,
/** bicubic interpolation */
INTER_CUBIC = 2,
/** resampling using pixel area relation. It may be a preferred method for
image decimation, as
it gives moire'-free results. But when the image is zoomed, it is similar to
the INTER_NEAREST
method. */
INTER_AREA = 3,
/** Lanczos interpolation over 8x8 neighborhood */
INTER_LANCZOS4 = 4,
/** mask for interpolation codes */
INTER_MAX = 7,
/** flag, fills all of the destination image pixels. If some of them
correspond to outliers in the
source image, they are set to zero */
WARP_FILL_OUTLIERS = 8,
/** flag, inverse transformation
For example, @ref cv::linearPolar or @ref cv::logPolar transforms:
- flag is __not__ set: \f$dst( \rho , \phi ) = src(x,y)\f$
- flag is set: \f$dst(x,y) = src( \rho , \phi )\f$
*/
WARP_INVERSE_MAP = 16
};
enum InterpolationMasks
{
INTER_BITS = 5,
INTER_BITS2 = INTER_BITS * 2,
INTER_TAB_SIZE = 1 << INTER_BITS,
INTER_TAB_SIZE2 = INTER_TAB_SIZE * INTER_TAB_SIZE
};
void resize(InputArray _src, OutputArray _dst, Size dsize, double inv_scale_x, double inv_scale_y, int interpolation);
}
| [
"sd@cs.stanford.edu"
] | sd@cs.stanford.edu |
6af2af62f6189da9f069abbfa856f8132950a8f6 | 21db378bdc4336e56bd4df3500de763f8490e4cc | /PubSubModule/module.hpp | 3083eb2381dd070c9c0944569889f50ff878b84b | [
"MIT"
] | permissive | zht043/inter-thread-publisher-subscriber-cpp | 91473d7228bf8afc01209cda75fc1b58be017fcc | c9862a438ae71ac3004daf4f6f7465184a1ee938 | refs/heads/master | 2022-12-17T11:52:52.459334 | 2020-09-16T06:13:11 | 2020-09-16T06:13:11 | 283,113,030 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,430 | hpp | #pragma once
#include <iostream>
#include "inter_thread_pubsub.hpp"
#include "oop_observer.hpp"
#include "thread_pool.hpp"
class Module {
public:
Module() {
}
~Module() {
}
virtual void task() = 0;
//======================Create New Thread Version=================================//
/* create a new thread and run the module in that thread */
void run() {
mthread = boost::shared_ptr<boost::thread>(
new boost::thread(boost::bind(&Module::task, this))
);
}
/* don't use this method if the threadpool version of Module::run() was used */
void idle() {
mthread->yield();
}
/* don't use this method if the threadpool version of Module::run() was used */
void join() {
mthread->join();
}
//================================================================================//
//============================Thread Pool Version=================================//
/* run the module as a task to be queued for a thread pool*/
void run(ThreadPool& thread_pool) {
thread_pool.execute(boost::bind(&Module::task, this));
}
//================================================================================//
private:
boost::shared_ptr<boost::thread> mthread;
};
| [
"hoz043@ucsd.edu"
] | hoz043@ucsd.edu |
eed71ce4bcf3aba9230cdfc7966b4ab150d92727 | be3167504c0e32d7708e7d13725c2dbc9232f2cb | /mame/src/mame/video/scn2674.h | 911abfe102390797ee44b8997a5c34368d7cc33f | [] | no_license | sysfce2/MAME-Plus-Plus-Kaillera | 83b52085dda65045d9f5e8a0b6f3977d75179e78 | 9692743849af5a808e217470abc46e813c9068a5 | refs/heads/master | 2023-08-10T06:12:47.451039 | 2016-08-01T09:44:21 | 2016-08-01T09:44:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,650 | h |
#define S674VERBOSE 0
#define LOG2674(x) do { if (S674VERBOSE) logerror x; } while (0)
typedef void (*s2574_interrupt_callback_func)(running_machine &machine);
static const UINT8 vsync_table[4] = {3,1,5,7}; //Video related
class scn2674_device : public device_t
{
public:
scn2674_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock);
static void set_irq_update_callback(device_t &device, s2574_interrupt_callback_func callback);
// int m_gfx_index;
DECLARE_READ16_MEMBER( mpu4_vid_scn2674_r );
DECLARE_WRITE16_MEMBER( mpu4_vid_scn2674_w );
UINT8 get_irq_state( void )
{
return m_scn2674_irq_state;
}
void scn2574_draw(running_machine &machine, bitmap_ind16 &bitmap, const rectangle &cliprect, UINT16* vid_mainram);
void scn2574_draw(running_machine &machine, bitmap_rgb32 &bitmap, const rectangle &cliprect, UINT16* vid_mainram);
void init_stuff();
void scn2674_do_scanline(running_machine &machine, int scanline);
protected:
virtual void device_start();
virtual void device_reset();
s2574_interrupt_callback_func m_interrupt_callback;
UINT8 m_scn2674_IR_pointer;
UINT8 m_scn2674_screen1_l;
UINT8 m_scn2674_screen1_h;
UINT8 m_scn2674_cursor_l;
UINT8 m_scn2674_cursor_h;
UINT8 m_scn2674_screen2_l;
UINT8 m_scn2674_screen2_h;
UINT8 m_scn2674_irq_register;
UINT8 m_scn2674_status_register;
UINT8 m_scn2674_irq_mask;
UINT8 m_scn2674_gfx_enabled;
UINT8 m_scn2674_display_enabled;
UINT8 m_scn2674_display_enabled_field;
UINT8 m_scn2674_display_enabled_scanline;
UINT8 m_scn2674_cursor_enabled;
UINT8 m_IR0_scn2674_double_ht_wd;
UINT8 m_IR0_scn2674_scanline_per_char_row;
UINT8 m_IR0_scn2674_sync_select;
UINT8 m_IR0_scn2674_buffer_mode_select;
UINT8 m_IR1_scn2674_interlace_enable;
UINT8 m_IR1_scn2674_equalizing_constant;
UINT8 m_IR2_scn2674_row_table;
UINT8 m_IR2_scn2674_horz_sync_width;
UINT8 m_IR2_scn2674_horz_back_porch;
UINT8 m_IR3_scn2674_vert_front_porch;
UINT8 m_IR3_scn2674_vert_back_porch;
UINT8 m_IR4_scn2674_rows_per_screen;
UINT8 m_IR4_scn2674_character_blink_rate_divisor;
UINT8 m_IR5_scn2674_character_per_row;
UINT8 m_IR6_scn2674_cursor_first_scanline;
UINT8 m_IR6_scn2674_cursor_last_scanline;
UINT8 m_IR7_scn2674_cursor_underline_position;
UINT8 m_IR7_scn2674_cursor_rate_divisor;
UINT8 m_IR7_scn2674_cursor_blink;
UINT8 m_IR7_scn2674_vsync_width;
UINT8 m_IR8_scn2674_display_buffer_first_address_LSB;
UINT8 m_IR9_scn2674_display_buffer_first_address_MSB;
UINT8 m_IR9_scn2674_display_buffer_last_address;
UINT8 m_IR10_scn2674_display_pointer_address_lower;
UINT8 m_IR11_scn2674_display_pointer_address_upper;
UINT8 m_IR11_scn2674_reset_scanline_counter_on_scrollup;
UINT8 m_IR11_scn2674_reset_scanline_counter_on_scrolldown;
UINT8 m_IR12_scn2674_scroll_start;
UINT8 m_IR12_scn2674_split_register_1;
UINT8 m_IR13_scn2674_scroll_end;
UINT8 m_IR13_scn2674_split_register_2;
UINT8 m_IR14_scn2674_scroll_lines;
UINT8 m_IR14_scn2674_double_1;
UINT8 m_IR14_scn2674_double_2;
UINT8 m_scn2674_horz_front_porch;
UINT8 m_scn2674_spl1;
UINT8 m_scn2674_spl2;
UINT8 m_scn2674_dbl1;
int m_rowcounter;
int m_linecounter;
UINT8 m_scn2674_irq_state;
void scn2674_write_init_regs(UINT8 data);
void scn2674_write_command(running_machine &machine, UINT8 data);
void scn2674_line(running_machine &machine);
template<class _BitmapClass>
void scn2574_draw_common( running_machine &machine, _BitmapClass &bitmap, const rectangle &cliprect, UINT16* vid_mainram );
private:
};
extern const device_type SCN2674_VIDEO;
| [
"mameppk@199a702f-54f1-4ac0-8451-560dfe28270b"
] | mameppk@199a702f-54f1-4ac0-8451-560dfe28270b |
37a106f0c68f898f2993e804c78f9f6abe0d4e82 | fbe77e9e2a53a4600a1d9b00b5f2c29ee3e8c59a | /contracts/libc++/upstream/test/std/utilities/memory/specialized.algorithms/uninitialized.construct.default/uninitialized_default_construct_n.pass.cpp | e5b9eca439cf8099eb046b7a59b8ac8d8a7def2c | [
"NCSA",
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | permissive | AcuteAngleCloud/Acute-Angle-Chain | 8d4a1ad714f6de1493954326e109b6af112561b9 | 5ea50bee042212ccff797ece5018c64f3f50ceff | refs/heads/master | 2021-04-26T21:52:25.560457 | 2020-03-21T07:29:06 | 2020-03-21T07:29:06 | 124,164,376 | 10 | 5 | MIT | 2020-07-16T07:14:45 | 2018-03-07T02:03:53 | C++ | UTF-8 | C++ | false | false | 3,202 | cpp | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03, c++11, c++14
// <memory>
// template <class ForwardIt>
// void uninitialized_default_construct(ForwardIt, ForwardIt);
#include <memory>
#include <cstdlib>
#include <cassert>
#include "test_macros.h"
#include "test_iterators.h"
struct Counted {
static int count;
static int constructed;
static void reset() { count = constructed = 0; }
explicit Counted() { ++count; ++constructed; }
Counted(Counted const&) { assert(false); }
~Counted() { assert(count > 0); --count; }
friend void operator&(Counted) = delete;
};
int Counted::count = 0;
int Counted::constructed = 0;
struct ThrowsCounted {
static int count;
static int constructed;
static int throw_after;
static void reset() { throw_after = count = constructed = 0; }
explicit ThrowsCounted() {
++constructed;
if (throw_after > 0 && --throw_after == 0) {
TEST_THROW(1);
}
++count;
}
ThrowsCounted(ThrowsCounted const&) { assert(false); }
~ThrowsCounted() { assert(count > 0); --count; }
friend void operator&(ThrowsCounted) = delete;
};
int ThrowsCounted::count = 0;
int ThrowsCounted::constructed = 0;
int ThrowsCounted::throw_after = 0;
void test_ctor_throws()
{
#ifndef TEST_HAS_NO_EXCEPTIONS
using It = forward_iterator<ThrowsCounted*>;
const int N = 5;
alignas(ThrowsCounted) char pool[sizeof(ThrowsCounted)*N] = {};
ThrowsCounted* p = (ThrowsCounted*)pool;
try {
ThrowsCounted::throw_after = 4;
std::uninitialized_default_construct_n(It(p), N);
assert(false);
} catch (...) {}
assert(ThrowsCounted::count == 0);
assert(ThrowsCounted::constructed == 4); // forth construction throws
#endif
}
void test_counted()
{
using It = forward_iterator<Counted*>;
const int N = 5;
alignas(Counted) char pool[sizeof(Counted)*N] = {};
Counted* p = (Counted*)pool;
It e = std::uninitialized_default_construct_n(It(p), 1);
assert(e == It(p+1));
assert(Counted::count == 1);
assert(Counted::constructed == 1);
e = std::uninitialized_default_construct_n(It(p+1), 4);
assert(e == It(p+N));
assert(Counted::count == 5);
assert(Counted::constructed == 5);
std::destroy(p, p+N);
assert(Counted::count == 0);
}
void test_value_initialized()
{
using It = forward_iterator<int*>;
const int N = 5;
int pool[N] = {-1, -1, -1, -1, -1};
int* p = pool;
auto e = std::uninitialized_default_construct_n(It(p), 1);
assert(e == It(p+1));
assert(pool[0] == -1);
assert(pool[1] == -1);
e = std::uninitialized_default_construct_n(It(p+1), 4);
assert(e == It(p+N));
assert(pool[1] == -1);
assert(pool[2] == -1);
assert(pool[3] == -1);
assert(pool[4] == -1);
}
int main()
{
test_counted();
test_value_initialized();
test_ctor_throws();
}
| [
"caokun@acuteangle.cn"
] | caokun@acuteangle.cn |
7161ee9cbaf4ed43ef1448dedebeadae307baa37 | 1e0dd1a7b19e8c8ee897709febb1f60409748e6e | /src/nes/mapper/mapper007.cpp | bb671d5eb1fc78a10018875f8182c91d6074ae85 | [] | no_license | rgegriff/EmuMasterPi | 1ba11d3e0c5257b9369175e3eb4a8807b48cb2b6 | d9402704a83c0b4e6810c4790cf1c42911ead1ab | refs/heads/master | 2021-01-21T01:06:39.410326 | 2012-11-23T19:53:19 | 2012-11-23T19:53:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,551 | cpp | /*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "mapper007.h"
#include "disk.h"
static u8 patch;
static void writeHigh(u16 addr, u8 data)
{
Q_UNUSED(addr)
nesSetRom32KBank(data & 0x07);
if (!patch) {
if (data & 0x10)
nesSetMirroring(SingleHigh);
else
nesSetMirroring(SingleLow);
}
}
void Mapper007::reset()
{
NesMapper::reset();
writeHigh = ::writeHigh;
patch = 0;
nesSetRom32KBank(0);
nesSetMirroring(SingleLow);
u32 crc = nesDiskCrc;
if( crc == 0x3c9fe649 ) { // WWF Wrestlemania Challenge(U)
nesSetMirroring(VerticalMirroring);
patch = 1;
}
if( crc == 0x09874777 ) { // Marble Madness(U)
nesEmuSetRenderMethod(NesEmu::TileRender);
}
if( crc == 0x279710dc // Battletoads (U)
|| crc == 0xceb65b06 ) { // Battletoads Double Dragon (U)
nesEmuSetRenderMethod(NesEmu::PreAllRender);
memset(nesWram, 0, sizeof(nesWram));
}
}
| [
"andy.nichols@nokia.com"
] | andy.nichols@nokia.com |
fd8b84412110246bd4792849db171e4bacb205c9 | 0017c3b639bf1f90a616150a76897226ed087bba | /artg4tk/services/ActionHolder_service.cc | cf8d39f925bec3fc038fd2b70a2cf70bf575d805 | [] | no_license | yarba/artg4tk | a164c159aed0d728c6069782606ae15b0dbe4268 | e107fd8689f741279a3d371cd6b772b5cadd87e5 | refs/heads/master | 2021-06-25T03:55:57.106277 | 2020-07-15T16:31:32 | 2020-07-15T16:31:32 | 132,481,088 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,583 | cc | // Provides the implementation for the @ActionHolderService@ service.
// For more comprehensive documentation, see the header file ActionHolderService.hh
// Authors: Tasha Arvanitis, Adam Lyon
// Date: July 2012
// Includes
#include "artg4tk/services/ActionHolder_service.hh"
#include "art/Framework/Services/Registry/ServiceMacros.h"
#include "messagefacility/MessageLogger/MessageLogger.h"
#include "artg4tk/actionBase/RunActionBase.hh"
#include "artg4tk/actionBase/EventActionBase.hh"
#include "artg4tk/actionBase/TrackingActionBase.hh"
#include "artg4tk/actionBase/SteppingActionBase.hh"
#include "artg4tk/actionBase/StackingActionBase.hh"
#include "artg4tk/actionBase/PrimaryGeneratorActionBase.hh"
#include <algorithm>
// Don't type 'std::' all the time...
using std::string;
using std::map;
using std::pair;
///////////////////
using namespace std;
/////////////////////
// Message category
static std::string msgctg = "ActionHolderService";
// Constructor doesn't do much with the passed arguments, but does initialize
// the logger for the service
artg4tk::ActionHolderService::ActionHolderService(fhicl::ParameterSet const&,
art::ActivityRegistry&) :
runActionsMap_(),
eventActionsMap_(),
trackingActionsMap_(),
steppingActionsMap_(),
stackingActionsMap_(),
primaryGeneratorActionsMap_(),
currentArtEvent_(nullptr),
allActionsMap_()
{}
// Register actions
template <typename A>
void artg4tk::ActionHolderService::doRegisterAction(A * const action,
std::map<std::string, A *>& actionMap)
{
mf::LogDebug(msgctg) << "Registering action " << action->myName();
// Check if the name exists in the specific action map
if ( 0 == actionMap.count( action->myName() ) ) {
// Add the action!
actionMap.insert(
pair<string, A *>( action->myName(), action )
);
// Now, check whether the name exists in the overall map of all the actions
// If so, move on (don't throw an exception, since a single action may need
// to register in multiple maps). Otherwise, add it.
if ( 0 == allActionsMap_.count( action->myName() ) ) {
allActionsMap_.insert(
pair<string, ActionBase*>( action->myName(), dynamic_cast<ActionBase*>(action) ));
}
}
else {
// We already have this action in the specific action map - this is bad!
throw cet::exception("ActionHolderService")
<< "Duplicate action named " << action->myName() << ".\n";
}
}
void artg4tk::ActionHolderService::registerAction(RunActionBase * const action) {
cerr<< "registering to runActionsMap_"<<endl;
doRegisterAction(action, runActionsMap_);
}
void artg4tk::ActionHolderService::registerAction(EventActionBase * const action) {
cerr<< "registering to eventActionsMap_"<<endl;
doRegisterAction(action, eventActionsMap_);
}
void artg4tk::ActionHolderService::registerAction(TrackingActionBase * const action) {
cerr<< "registering to trackingActionsMap_"<<endl;
doRegisterAction(action, trackingActionsMap_);
}
void artg4tk::ActionHolderService::registerAction(SteppingActionBase * const action) {
cerr<< "registering to steppingActionsMap_"<<endl;
doRegisterAction(action, steppingActionsMap_);
}
void artg4tk::ActionHolderService::registerAction(StackingActionBase * const action) {
cerr<< "registering to stackingActionsMap_"<<endl;
doRegisterAction(action, stackingActionsMap_);
}
void artg4tk::ActionHolderService::registerAction(PrimaryGeneratorActionBase * const action) {
cerr<< "registering to primaryGeneratorActionsMap_"<<endl;
doRegisterAction(action, primaryGeneratorActionsMap_);
}
template <typename A>
A* artg4tk::ActionHolderService::doGetAction(std::string name, std::map<std::string, A*>& actionMap) {
// Make a typedef
typedef typename std::map<std::string, A*>::const_iterator map_const_iter;
// Find the action corresponding to the passed in name in the map
map_const_iter actionIter = actionMap.find(name);
if ( actionIter == actionMap.end() ) {
throw cet::exception("ActionHolderService") << "No action found with name "
<< name << ".\n";
}
return actionIter->second;
}
artg4tk::ActionBase* artg4tk::ActionHolderService::getAction(std::string name, RunActionBase* out) {
out = doGetAction(name, runActionsMap_);
return out;
}
artg4tk::ActionBase* artg4tk::ActionHolderService::getAction(std::string name, EventActionBase* out) {
out = doGetAction(name, eventActionsMap_);
return out;
}
artg4tk::ActionBase* artg4tk::ActionHolderService::getAction(std::string name, TrackingActionBase* out) {
out = doGetAction(name, trackingActionsMap_);
return out;
}
artg4tk::ActionBase* artg4tk::ActionHolderService::getAction(std::string name, SteppingActionBase* out) {
out = doGetAction(name, steppingActionsMap_);
return out;
}
artg4tk::ActionBase* artg4tk::ActionHolderService::getAction(std::string name, StackingActionBase* out) {
out = doGetAction(name, stackingActionsMap_);
return out;
}
artg4tk::ActionBase* artg4tk::ActionHolderService::getAction(std::string name, PrimaryGeneratorActionBase* out) {
out = doGetAction(name, primaryGeneratorActionsMap_);
return out;
}
// h3. Art-specific methods
void artg4tk::ActionHolderService::callArtProduces(art::EDProducer * prod)
{
// Loop over the "uber" activity map and call @callArtProduces@ on each
for ( auto entry : allActionsMap_) {
(entry.second)->callArtProduces(prod);
}
}
void artg4tk::ActionHolderService::initialize() {
for ( auto entry : allActionsMap_ ) {
(entry.second)->initialize();
}
}
void artg4tk::ActionHolderService::fillEventWithArtStuff()
{
// Loop over the "uber" activity map and call @fillEventWithArtStuff@ on each
for ( auto entry : allActionsMap_ ) {
(entry.second)->fillEventWithArtStuff(getCurrArtEvent());
}
}
void artg4tk::ActionHolderService::fillRunBeginWithArtStuff()
{
// Loop over the activities and call @fillRunBeginWithArtStuff@ on each
for ( auto entry : allActionsMap_ ) {
(entry.second)->fillRunBeginWithArtStuff(getCurrArtRun());
}
}
void artg4tk::ActionHolderService::fillRunEndWithArtStuff()
{
// Loop over the activities and call @fillRunEndWithArtStuff@ on each
for ( auto entry : allActionsMap_ ) {
(entry.second)->fillRunEndWithArtStuff(getCurrArtRun());
}
}
// h2. Action methods
// I tried to be good and use @std::for_each@ but it got really messy very
// quickly. Oh well.
// h3. Run action methods
void artg4tk::ActionHolderService::beginOfRunAction(const G4Run* theRun) {
// Loop over the runActionsMap and call @beginOfRunAction@ on each
for ( auto entry : runActionsMap_ ) {
(entry.second)->beginOfRunAction(theRun);
}
}
void artg4tk::ActionHolderService::endOfRunAction(const G4Run* theRun) {
// Loop over the runActionsMap and call @endOfRunAction@ on each
for ( auto entry : runActionsMap_ ) {
(entry.second)->endOfRunAction(theRun);
}
}
// h3. Event action methods
void artg4tk::ActionHolderService::beginOfEventAction(const G4Event* theEvent) {
for ( auto entry : eventActionsMap_ ) {
(entry.second)->beginOfEventAction(theEvent);
}
}
void artg4tk::ActionHolderService::endOfEventAction(const G4Event* theEvent) {
for ( auto entry : eventActionsMap_ ) {
(entry.second)->endOfEventAction(theEvent);
}
}
// h3. Tracking action methods
void artg4tk::ActionHolderService::preUserTrackingAction(const G4Track* theTrack) {
for ( auto entry : trackingActionsMap_ ) {
(entry.second)->preUserTrackingAction(theTrack);
}
}
void artg4tk::ActionHolderService::postUserTrackingAction(const G4Track* theTrack) {
for (auto entry : trackingActionsMap_ ) {
(entry.second)->postUserTrackingAction(theTrack);
}
}
// h3. Stepping actions
void artg4tk::ActionHolderService::userSteppingAction(const G4Step* theStep) {
for ( auto entry : steppingActionsMap_ ) {
(entry.second)->userSteppingAction(theStep);
}
}
// h3. Stacking actions
bool artg4tk::ActionHolderService::killNewTrack(const G4Track* newTrack) {
bool killTrack = false;
for (auto entry : stackingActionsMap_) {
if ( (entry.second)->killNewTrack(newTrack) ) {
killTrack = true;
break;
}
}
return killTrack;
}
// h3. Primary generator actions
void artg4tk::ActionHolderService::generatePrimaries(G4Event* theEvent) {
for ( auto entry : primaryGeneratorActionsMap_ ) {
(entry.second)->generatePrimaries(theEvent);
}
}
// Register the service with Art
using artg4tk::ActionHolderService;
DEFINE_ART_SERVICE(ActionHolderService)
| [
"yarba_j@fnal.gov"
] | yarba_j@fnal.gov |
3ea5bb692acd201607d21732b4a208774794fb88 | 24c3b6ee3e2b06288bed587e34751969b4a73e31 | /AtCoder/Virtual/20200517/D.cpp | 9cbbef2c99c222a0f087b2b68d6c2e4eca195766 | [] | no_license | KatsuyaKikuchi/ProgrammingContest | 89afbda50d1cf59fc58d8a9e25e6660334f18a2a | d9254202eec56f96d8c5b508556464a3f87a0a4f | refs/heads/master | 2023-06-05T20:07:36.334182 | 2021-06-13T13:55:06 | 2021-06-13T13:55:06 | 318,641,671 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,576 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef pair<ll, ll> pll;
#define FOR(i, n, m) for(ll (i)=(m);(i)<(n);++(i))
#define REP(i, n) FOR(i,n,0)
#define OF64 std::setprecision(10)
const ll MOD = 1000000007;
const ll INF = (ll) 1e15;
struct UnionFind {
UnionFind(int n) {
rank.assign(n, 0);
parent.resize(n);
for (int i = 0; i < n; ++i) {
parent[i] = i;
}
}
int find(int x) {
if (x == parent[x])
return x;
return parent[x] = find(parent[x]);
}
bool same(int x, int y) {
return find(x) == find(y);
}
void unit(int x, int y) {
x = find(x);
y = find(y);
if (x == y)
return;
if (rank[x] < rank[y]) {
parent[x] = y;
}
else {
parent[y] = x;
if (rank[x] == rank[y])
rank[x]++;
}
}
vector<int> rank;
vector<int> parent;
};
pll E[55];
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
ll N, M;
cin >> N >> M;
REP(i, M) {
cin >> E[i].first >> E[i].second;
E[i].first--;
E[i].second--;
}
ll ans = 0;
REP(i, M) {
UnionFind uf(N);
REP(j, M) {
if (j == i)
continue;
uf.unit(E[j].first, E[j].second);
}
REP(j, N - 1) {
if (uf.same(j, j + 1))
continue;
ans++;
break;
}
}
cout << ans << endl;
return 0;
} | [
"k.kikuchi.ah@gmail.com"
] | k.kikuchi.ah@gmail.com |
7e7602096b17ce444442053a7560058b8a71dbfa | 1c444bdf16632d78a3801a7fe6b35c054c4cddde | /include/bds/bedrock/block/unmapped/BlockIntersectionConstraint.h | da4e84b3ea537fe992003b383697371b5f0a56cf | [] | no_license | maksym-pasichnyk/symbols | 962a082bf6a692563402c87eb25e268e7e712c25 | 7673aa52391ce93540f0e65081f16cd11c2aa606 | refs/heads/master | 2022-04-11T03:17:18.078103 | 2020-03-15T11:30:36 | 2020-03-15T11:30:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 583 | h | #pragma once
#include "../../../unmapped/IStructureConstraint.h"
class BlockIntersectionConstraint : public IStructureConstraint {
public:
~BlockIntersectionConstraint(); // _ZN27BlockIntersectionConstraintD2Ev
// virtual bool isSatisfied(IBlockPlacementTarget const&, BlockPos const&, Rotation const&)const; //TODO: incomplete function definition // _ZNK27BlockIntersectionConstraint11isSatisfiedERK21IBlockPlacementTargetRK8BlockPosRK8Rotation
BlockIntersectionConstraint(LegacyStructureTemplate &); // _ZN27BlockIntersectionConstraintC2ER23LegacyStructureTemplate
};
| [
"honzaxp01@gmail.com"
] | honzaxp01@gmail.com |
837a8b738a424ba6392df18a31f46d21248adad6 | b65240f23e8f7af98532c47a5a25125aa06e499e | /234. Palindrome Linked List(回文链表)/palindromeLinkedList.cpp | 885b51184ca2b5eae0399c4c04bac349c42016cc | [] | no_license | anthonyzhi/leetcode | 6e3816e12b128d83634f77a3d1ef8e647f7dd261 | d22e4e360bea446c98988111bea754b6d1a10ddb | refs/heads/master | 2020-04-30T23:13:29.883746 | 2020-02-19T14:56:04 | 2020-02-19T14:56:04 | 177,139,134 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,310 | cpp | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
bool isEqual(ListNode* head,ListNode *&h){
bool result;
if(head->next==NULL)
return head->val==h->val;
else{
result=isEqual(head->next,h);
h=h->next;
}
return (result && head->val==h->val);
}
class Solution {
public:
bool isPalindrome(ListNode* head) {
ListNode* h=head;
if(head==NULL)
return true;
return isEqual(head,h);
}
};
//方法二
class Solution {
public:
bool isPalindrome(ListNode* head) {
ListNode* slow=head, *fast=head,*prev=nullptr;
//使用快慢指针找到链表中点
while(fast){
slow=slow->next;
fast=fast->next?fast->next->next:fast->next;
}
//reverse逆序后半部分
while(slow){
ListNode* ovn=slow->next;
slow->next=prev;
prev=slow;
slow=ovn;
}
//从头、中点开始比较是否相同
while(head&&prev){
if(head->val!=prev->val)
return false;
head=head->next;
prev=prev->next;
}
return true;
}
};
| [
"noreply@github.com"
] | anthonyzhi.noreply@github.com |
669763b8c5970998134b66e5b26fa32b9b55dfdc | 680b88f875432c4d3fcf864b72e6833c6bc9c6fa | /Project1/ForkCompress.cpp | 4bedcfc554f37730a7644c04c8e17ac28dddda93 | [] | no_license | Joshmerm/OperatingSystems | 4b221a517a106f342c417ff2a018c279b91fead8 | 66064b5d985dfa8df80981a2b640f424b07b45a8 | refs/heads/main | 2023-04-22T11:43:46.109171 | 2021-05-07T20:15:48 | 2021-05-07T20:15:48 | 333,994,032 | 1 | 0 | null | 2021-05-07T20:15:48 | 2021-01-29T00:34:34 | C++ | UTF-8 | C++ | false | false | 980 | cpp | #include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
using namespace std;
void child(char ** argv){
//Runs MyCompress with the two command line arguments
execl("MyCompress", "MyCompress", argv[1], argv[2], NULL);
}
void parent(){
//Parent function, runs once child is done
cout << "Child Is Done" << endl;
}
//Takes in two command Line arguments (input file path, output path)
// Example for running: ./ForkCompress source.txt destination.txt
int main(int argc, char** argv) {
pid_t pid;
//Forks the process, parent will wait until child executes
pid = fork();
if(pid < 0) {
//Error Forking
perror("Error");
exit(1);
}else if(pid == 0){
//Executes the child function
child(argv);
exit(1);
}else{
//Waits for child to finish
wait(&pid);
//Once child is done, executes the Parent Function
parent();
}
return 0;
} | [
"joshmerm@gmail.com"
] | joshmerm@gmail.com |
9545b8b7802359a854c95aef3e273ff3b649cc37 | 38fdf56786a27eb0042ba52f5fdd1eaa0459fc50 | /task 15/main.cpp | 1394f802570489562369703815375758f34aca91 | [] | no_license | bumb217/tasks | fc68d9cd16a2c2091ab7793c1c3b6a9e0a74626d | 1f25931c2abf7aefce262e55f5b450d75f873fcc | refs/heads/master | 2021-01-23T01:51:14.969801 | 2017-05-18T13:26:56 | 2017-05-18T13:26:56 | 85,938,890 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 90 | cpp | #include "additional.h"
#include "Builder.h"
int main(){
toXml("file");
return 0;
}
| [
"noreply@github.com"
] | bumb217.noreply@github.com |
3f8fbae2e2ce0065a24389b75d1c6bb1fa34c525 | e6b695c9b0ab3eca8f5424c80db936e6e3f7be72 | /quazipfile.h | 6d19933ea66f5f565be75d19eb539c0eb82bf858 | [] | no_license | DriftMind/NTUMEMSOpenVPN | a9bba50db42542423b1736a65911f9d4d6e9099e | 7964c4be8cfddfb403fa00e2f3b14eec6d3f8e60 | refs/heads/master | 2021-01-11T14:45:25.102786 | 2014-06-09T15:35:42 | 2014-06-09T15:35:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,969 | h | #ifndef QUA_ZIPFILE_H
#define QUA_ZIPFILE_H
/*
-- A kind of "standard" GPL license statement --
QuaZIP - a Qt/C++ wrapper for the ZIP/UNZIP package
Copyright (C) 2005-2008 Sergey A. Tachenov
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
-- A kind of "standard" GPL license statement ends here --
See COPYING file for GPL.
You are also permitted to use QuaZIP under the terms of LGPL (see
COPYING.LGPL). You are free to choose either license, but please note
that QuaZIP makes use of Qt, which is not licensed under LGPL. So if
you are using Open Source edition of Qt, you therefore MUST use GPL for
your code based on QuaZIP, since it would be also based on Qt in this
case. If you are Qt commercial license owner, then you are free to use
QuaZIP as long as you respect either GPL or LGPL for QuaZIP code.
**/
#include <QIODevice>
#include "quazip_global.h"
#include "quazip.h"
#include "quazipnewinfo.h"
class QuaZipFilePrivate;
/// A file inside ZIP archive.
/** \class QuaZipFile quazipfile.h <quazip/quazipfile.h>
* This is the most interesting class. Not only it provides C++
* interface to the ZIP/UNZIP package, but also integrates it with Qt by
* subclassing QIODevice. This makes possible to access files inside ZIP
* archive using QTextStream or QDataStream, for example. Actually, this
* is the main purpose of the whole QuaZIP library.
*
* You can either use existing QuaZip instance to create instance of
* this class or pass ZIP archive file name to this class, in which case
* it will create internal QuaZip object. See constructors' descriptions
* for details. Writing is only possible with the existing instance.
*
* \section quazipfile-sequential Sequential or random-access?
*
* At the first thought, QuaZipFile has fixed size, the start and the
* end and should be therefore considered random-access device. But
* there is one major obstacle to making it random-access: ZIP/UNZIP API
* does not support seek() operation and the only way to implement it is
* through reopening the file and re-reading to the required position,
* but this is prohibitely slow.
*
* Therefore, QuaZipFile is considered to be a sequential device. This
* has advantage of availability of the ungetChar() operation (QIODevice
* does not implement it properly for non-sequential devices unless they
* support seek()). Disadvantage is a somewhat strange behaviour of the
* size() and pos() functions. This should be kept in mind while using
* this class.
*
**/
class QUAZIP_EXPORT QuaZipFile: public QIODevice {
friend class QuaZipFilePrivate;
Q_OBJECT
private:
QuaZipFilePrivate *p;
// these are not supported nor implemented
QuaZipFile(const QuaZipFile& that);
QuaZipFile& operator=(const QuaZipFile& that);
protected:
/// Implementation of the QIODevice::readData().
qint64 readData(char *data, qint64 maxSize);
/// Implementation of the QIODevice::writeData().
qint64 writeData(const char *data, qint64 maxSize);
public:
/// Constructs a QuaZipFile instance.
/** You should use setZipName() and setFileName() or setZip() before
* trying to call open() on the constructed object.
**/
QuaZipFile();
/// Constructs a QuaZipFile instance.
/** \a parent argument specifies this object's parent object.
*
* You should use setZipName() and setFileName() or setZip() before
* trying to call open() on the constructed object.
**/
QuaZipFile(QObject *parent);
/// Constructs a QuaZipFile instance.
/** \a parent argument specifies this object's parent object and \a
* zipName specifies ZIP archive file name.
*
* You should use setFileName() before trying to call open() on the
* constructed object.
*
* QuaZipFile constructed by this constructor can be used for read
* only access. Use QuaZipFile(QuaZip*,QObject*) for writing.
**/
QuaZipFile(const QString& zipName, QObject *parent =NULL);
/// Constructs a QuaZipFile instance.
/** \a parent argument specifies this object's parent object, \a
* zipName specifies ZIP archive file name and \a fileName and \a cs
* specify a name of the file to open inside archive.
*
* QuaZipFile constructed by this constructor can be used for read
* only access. Use QuaZipFile(QuaZip*,QObject*) for writing.
*
* \sa QuaZip::setCurrentFile()
**/
QuaZipFile(const QString& zipName, const QString& fileName,
QuaZip::CaseSensitivity cs =QuaZip::csDefault, QObject *parent =NULL);
/// Constructs a QuaZipFile instance.
/** \a parent argument specifies this object's parent object.
*
* \a zip is the pointer to the existing QuaZip object. This
* QuaZipFile object then can be used to read current file in the
* \a zip or to write to the file inside it.
*
* \warning Using this constructor for reading current file can be
* tricky. Let's take the following example:
* \code
* QuaZip zip("archive.zip");
* zip.open(QuaZip::mdUnzip);
* zip.setCurrentFile("file-in-archive");
* QuaZipFile file(&zip);
* file.open(QIODevice::ReadOnly);
* // ok, now we can read from the file
* file.read(somewhere, some);
* zip.setCurrentFile("another-file-in-archive"); // oops...
* QuaZipFile anotherFile(&zip);
* anotherFile.open(QIODevice::ReadOnly);
* anotherFile.read(somewhere, some); // this is still ok...
* file.read(somewhere, some); // and this is NOT
* \endcode
* So, what exactly happens here? When we change current file in the
* \c zip archive, \c file that references it becomes invalid
* (actually, as far as I understand ZIP/UNZIP sources, it becomes
* closed, but QuaZipFile has no means to detect it).
*
* Summary: do not close \c zip object or change its current file as
* long as QuaZipFile is open. Even better - use another constructors
* which create internal QuaZip instances, one per object, and
* therefore do not cause unnecessary trouble. This constructor may
* be useful, though, if you already have a QuaZip instance and do
* not want to access several files at once. Good example:
* \code
* QuaZip zip("archive.zip");
* zip.open(QuaZip::mdUnzip);
* // first, we need some information about archive itself
* QByteArray comment=zip.getComment();
* // and now we are going to access files inside it
* QuaZipFile file(&zip);
* for(bool more=zip.goToFirstFile(); more; more=zip.goToNextFile()) {
* file.open(QIODevice::ReadOnly);
* // do something cool with file here
* file.close(); // do not forget to close!
* }
* zip.close();
* \endcode
**/
QuaZipFile(QuaZip *zip, QObject *parent =NULL);
/// Destroys a QuaZipFile instance.
/** Closes file if open, destructs internal QuaZip object (if it
* exists and \em is internal, of course).
**/
virtual ~QuaZipFile();
/// Returns the ZIP archive file name.
/** If this object was created by passing QuaZip pointer to the
* constructor, this function will return that QuaZip's file name
* (or null string if that object does not have file name yet).
*
* Otherwise, returns associated ZIP archive file name or null
* string if there are no name set yet.
*
* \sa setZipName() getFileName()
**/
QString getZipName()const;
/// Returns a pointer to the associated QuaZip object.
/** Returns \c NULL if there is no associated QuaZip or it is
* internal (so you will not mess with it).
**/
QuaZip* getZip()const;
/// Returns file name.
/** This function returns file name you passed to this object either
* by using
* QuaZipFile(const QString&,const QString&,QuaZip::CaseSensitivity,QObject*)
* or by calling setFileName(). Real name of the file may differ in
* case if you used case-insensitivity.
*
* Returns null string if there is no file name set yet. This is the
* case when this QuaZipFile operates on the existing QuaZip object
* (constructor QuaZipFile(QuaZip*,QObject*) or setZip() was used).
*
* \sa getActualFileName
**/
QString getFileName() const;
/// Returns case sensitivity of the file name.
/** This function returns case sensitivity argument you passed to
* this object either by using
* QuaZipFile(const QString&,const QString&,QuaZip::CaseSensitivity,QObject*)
* or by calling setFileName().
*
* Returns unpredictable value if getFileName() returns null string
* (this is the case when you did not used setFileName() or
* constructor above).
*
* \sa getFileName
**/
QuaZip::CaseSensitivity getCaseSensitivity() const;
/// Returns the actual file name in the archive.
/** This is \em not a ZIP archive file name, but a name of file inside
* archive. It is not necessary the same name that you have passed
* to the
* QuaZipFile(const QString&,const QString&,QuaZip::CaseSensitivity,QObject*),
* setFileName() or QuaZip::setCurrentFile() - this is the real file
* name inside archive, so it may differ in case if the file name
* search was case-insensitive.
*
* Equivalent to calling getCurrentFileName() on the associated
* QuaZip object. Returns null string if there is no associated
* QuaZip object or if it does not have a current file yet. And this
* is the case if you called setFileName() but did not open the
* file yet. So this is perfectly fine:
* \code
* QuaZipFile file("somezip.zip");
* file.setFileName("somefile");
* QString name=file.getName(); // name=="somefile"
* QString actual=file.getActualFileName(); // actual is null string
* file.open(QIODevice::ReadOnly);
* QString actual=file.getActualFileName(); // actual can be "SoMeFiLe" on Windows
* \endcode
*
* \sa getZipName(), getFileName(), QuaZip::CaseSensitivity
**/
QString getActualFileName()const;
/// Sets the ZIP archive file name.
/** Automatically creates internal QuaZip object and destroys
* previously created internal QuaZip object, if any.
*
* Will do nothing if this file is already open. You must close() it
* first.
**/
void setZipName(const QString& zipName);
/// Returns \c true if the file was opened in raw mode.
/** If the file is not open, the returned value is undefined.
*
* \sa open(OpenMode,int*,int*,bool,const char*)
**/
bool isRaw() const;
/// Binds to the existing QuaZip instance.
/** This function destroys internal QuaZip object, if any, and makes
* this QuaZipFile to use current file in the \a zip object for any
* further operations. See QuaZipFile(QuaZip*,QObject*) for the
* possible pitfalls.
*
* Will do nothing if the file is currently open. You must close()
* it first.
**/
void setZip(QuaZip *zip);
/// Sets the file name.
/** Will do nothing if at least one of the following conditions is
* met:
* - ZIP name has not been set yet (getZipName() returns null
* string).
* - This QuaZipFile is associated with external QuaZip. In this
* case you should call that QuaZip's setCurrentFile() function
* instead!
* - File is already open so setting the name is meaningless.
*
* \sa QuaZip::setCurrentFile
**/
void setFileName(const QString& fileName, QuaZip::CaseSensitivity cs =QuaZip::csDefault);
/// Opens a file for reading.
/** Returns \c true on success, \c false otherwise.
* Call getZipError() to get error code.
*
* \note Since ZIP/UNZIP API provides buffered reading only,
* QuaZipFile does not support unbuffered reading. So do not pass
* QIODevice::Unbuffered flag in \a mode, or open will fail.
**/
virtual bool open(OpenMode mode);
/// Opens a file for reading.
/** \overload
* Argument \a password specifies a password to decrypt the file. If
* it is NULL then this function behaves just like open(OpenMode).
**/
inline bool open(OpenMode mode, const char *password)
{return open(mode, NULL, NULL, false, password);}
/// Opens a file for reading.
/** \overload
* Argument \a password specifies a password to decrypt the file.
*
* An integers pointed by \a method and \a level will receive codes
* of the compression method and level used. See unzip.h.
*
* If raw is \c true then no decompression is performed.
*
* \a method should not be \c NULL. \a level can be \c NULL if you
* don't want to know the compression level.
**/
bool open(OpenMode mode, int *method, int *level, bool raw, const char *password =NULL);
/// Opens a file for writing.
/** \a info argument specifies information about file. It should at
* least specify a correct file name. Also, it is a good idea to
* specify correct timestamp (by default, current time will be
* used). See QuaZipNewInfo.
*
* Arguments \a password and \a crc provide necessary information
* for crypting. Note that you should specify both of them if you
* need crypting. If you do not, pass \c NULL as password, but you
* still need to specify \a crc if you are going to use raw mode
* (see below).
*
* Arguments \a method and \a level specify compression method and
* level.
*
* If \a raw is \c true, no compression is performed. In this case,
* \a crc and uncompressedSize field of the \a info are required.
*
* Arguments \a windowBits, \a memLevel, \a strategy provide zlib
* algorithms tuning. See deflateInit2() in zlib.
**/
bool open(OpenMode mode, const QuaZipNewInfo& info,
const char *password =NULL, quint32 crc =0,
int method =Z_DEFLATED, int level =Z_DEFAULT_COMPRESSION, bool raw =false,
int windowBits =-MAX_WBITS, int memLevel =DEF_MEM_LEVEL, int strategy =Z_DEFAULT_STRATEGY);
/// Returns \c true, but \ref quazipfile-sequential "beware"!
virtual bool isSequential()const;
/// Returns current position in the file.
/** Implementation of the QIODevice::pos(). When reading, this
* function is a wrapper to the ZIP/UNZIP unztell(), therefore it is
* unable to keep track of the ungetChar() calls (which is
* non-virtual and therefore is dangerous to reimplement). So if you
* are using ungetChar() feature of the QIODevice, this function
* reports incorrect value until you get back characters which you
* ungot.
*
* When writing, pos() returns number of bytes already written
* (uncompressed unless you use raw mode).
*
* \note Although
* \ref quazipfile-sequential "QuaZipFile is a sequential device"
* and therefore pos() should always return zero, it does not,
* because it would be misguiding. Keep this in mind.
*
* This function returns -1 if the file or archive is not open.
*
* Error code returned by getZipError() is not affected by this
* function call.
**/
virtual qint64 pos()const;
/// Returns \c true if the end of file was reached.
/** This function returns \c false in the case of error. This means
* that you called this function on either not open file, or a file
* in the not open archive or even on a QuaZipFile instance that
* does not even have QuaZip instance associated. Do not do that
* because there is no means to determine whether \c false is
* returned because of error or because end of file was reached.
* Well, on the other side you may interpret \c false return value
* as "there is no file open to check for end of file and there is
* no end of file therefore".
*
* When writing, this function always returns \c true (because you
* are always writing to the end of file).
*
* Error code returned by getZipError() is not affected by this
* function call.
**/
virtual bool atEnd()const;
/// Returns file size.
/** This function returns csize() if the file is open for reading in
* raw mode, usize() if it is open for reading in normal mode and
* pos() if it is open for writing.
*
* Returns -1 on error, call getZipError() to get error code.
*
* \note This function returns file size despite that
* \ref quazipfile-sequential "QuaZipFile is considered to be sequential device",
* for which size() should return bytesAvailable() instead. But its
* name would be very misguiding otherwise, so just keep in mind
* this inconsistence.
**/
virtual qint64 size()const;
/// Returns compressed file size.
/** Equivalent to calling getFileInfo() and then getting
* compressedSize field, but more convenient and faster.
*
* File must be open for reading before calling this function.
*
* Returns -1 on error, call getZipError() to get error code.
**/
qint64 csize()const;
/// Returns uncompressed file size.
/** Equivalent to calling getFileInfo() and then getting
* uncompressedSize field, but more convenient and faster. See
* getFileInfo() for a warning.
*
* File must be open for reading before calling this function.
*
* Returns -1 on error, call getZipError() to get error code.
**/
qint64 usize()const;
/// Gets information about current file.
/** This function does the same thing as calling
* QuaZip::getCurrentFileInfo() on the associated QuaZip object,
* but you can not call getCurrentFileInfo() if the associated
* QuaZip is internal (because you do not have access to it), while
* you still can call this function in that case.
*
* File must be open for reading before calling this function.
*
* Returns \c false in the case of an error.
**/
bool getFileInfo(QuaZipFileInfo *info);
/// Closes the file.
/** Call getZipError() to determine if the close was successful.
**/
virtual void close();
/// Returns the error code returned by the last ZIP/UNZIP API call.
int getZipError() const;
};
#endif
| [
"jrywjwu@gmail.com"
] | jrywjwu@gmail.com |
9cc91204eec0e767aadeb49613de29f857a7364d | eb4ab00097f53a59f0f8b9454268b02b721f46c4 | /views/mdecombo.cpp | 3980132bed510f87344735451624d55412ce8af7 | [] | no_license | mainster/WorktimeManager | 4714050e2684396d914d7bf90d1e926bfaeeb0f4 | 099b013260cea24b298e2dcf8c268772efb28e57 | refs/heads/master | 2021-03-27T14:15:02.438028 | 2021-03-06T00:33:31 | 2021-03-06T00:33:31 | 63,525,553 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 857 | cpp | #include "mdecombo.h"
#include <QtWidgets>
#include <QtSql>
MdECombo::MdECombo(QWidget *parent) {
// QSqlTableModel *relModel = m_rtModel->relationModel(typeIndex);
// m_cbx->setModel(relModel);
// m_cbx->setModelColumn(relModel->fieldIndex("description"));
// m_dwMapper = new QDataWidgetmMapper(this);
// m_dwMapper->setModel(model);
// m_dwMapper->setItemDelegate(new QSqlRelationalDelegate(this));
// m_dwMapper->addMapping(nameEdit, model->fieldIndex("name"));
// m_dwMapper->addMapping(addressEdit, model->fieldIndex("address"));
// m_dwMapper->addMapping(typeComboBox, typeIndex);
// connect(previousButton, SIGNAL(clicked()),
// m_dwMapper, SLOT(toPrevious()));
// connect(nextButton, SIGNAL(clicked()),
// m_dwMapper, SLOT(toNext()));
// connect(m_dwMapper, SIGNAL(currentIndexChanged(int)),
// this, SLOT(updateButtons(int)));
}
| [
"manuel.delbasso@gmail.com"
] | manuel.delbasso@gmail.com |
d182b304bd07ffee1254ca71b1314136ecbf516b | 0f2fd8f256365d4a90e5a058629081ef91bb48a1 | /src/prototype1.cpp | a169bbaf968bbbadc6db01e16bcfec4468297af7 | [] | no_license | ging/payloader | 5c19f4ca647f04884d465eadf7041e3e8d6fa32f | 748c7cf157dc572b8dc9803413f9f78316f7b6b1 | refs/heads/master | 2020-07-22T17:39:20.759805 | 2018-06-11T16:16:12 | 2018-06-11T16:16:12 | 73,829,094 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 950 | cpp | #include <stdio.h>
#include <libavutil/time.h>
#include "libs/InputReader.h"
#include "libs/OutputWriter.h"
int main(int argc, const char* argv[]) {
if (argc != 3) {
printf("usage: %s input_file output_file\n"
"Example program to input-output a media file.\n"
"\n", argv[0]);
exit(1);
}
const char *input_file = argv[1];
const char *output_file = argv[2];
payloader::InputReader* reader = new payloader::InputReader(input_file);
payloader::OutputWriter* writer = new payloader::OutputWriter(output_file);
payloader::VideoCodecInfo videoInfo;
videoInfo.enabled = true;
videoInfo.codec = AV_CODEC_ID_MPEG4;
videoInfo.width = 704;
videoInfo.height = 396;
videoInfo.bitRate = 48000;
payloader::AudioCodecInfo audioInfo;
audioInfo.enabled = true;
audioInfo.codec = (AVCodecID)65536;
writer->init(audioInfo, videoInfo);
reader->setSink(writer);
reader->init();
} | [
"aalonsog@dit.upm.es"
] | aalonsog@dit.upm.es |
1c471644b892e3f8fb4a1e37140fc4715de378a4 | f82a97d9f06676c5dfdfac09440493d803859a6e | /libvmaf/src/third_party/ptools/simplehttpserver.h | 65fb0a0355d109e8aecc4fdd8f0e94374f1ba1e1 | [
"Apache-2.0",
"LGPL-3.0-or-later",
"BSD-3-Clause"
] | permissive | weizhou-geek/vmaf | 0694e6c45777e7286fe474d5b2f7835dd3df674a | d5978d15f7c413e8aa78c891ce43291ead3fa287 | refs/heads/master | 2020-09-26T13:21:35.827002 | 2019-11-21T21:54:02 | 2019-12-04T00:04:29 | 226,263,006 | 2 | 0 | Apache-2.0 | 2019-12-06T06:37:56 | 2019-12-06T06:37:55 | null | UTF-8 | C++ | false | false | 5,047 | h | #ifndef SIMPLEHTTPSERVER_H_
#define SIMPLEHTTPSERVER_H_
// An HTTP Server that implements a subset of the HTTP protocol, with
// one thread per connection. The threaded server, which we inherit from,
// handles most of the connection set-up and the like,
// but the real work is handled in the ThreadedHTTPWorker, which does
// all the parsing of the HTTP and reading/writing from the socket.
#include "threadedserver.h"
#include "httptools.h"
#include "ocsplit.h"
PTOOLS_BEGIN_NAMESPACE
// /////////////////////////////////////// ThreadedHTTPWorker
// One thread per connection: each thread parse the HTTP data from the
// given file descriptor.
class ThreadedHTTPWorker : public ThreadedServerWorker {
public:
// Put into empty, known state and start into main loop.
ThreadedHTTPWorker (const string& name, ThreadedServer& server):
ThreadedServerWorker(name, server),
httptools_(readfd_, writefd_),
logging_(true),
httpVersion_(""),
serverName_("PTOOLSHTTPServer")
{ }
// Set-up the worker
virtual void initialize (int readfd, int writefd)
{
httptools_.cleanseBuffer();
ThreadedServerWorker::initialize(readfd, writefd); // Call parent
}
protected:
// Tools for parsing, reading, responding and making well-formed
// requests
HTTPTools_ httptools_;
// Do we log to cerr? TODO: more extensive log
bool logging_;
// Use same version as input request? TODO: Reconsider
string httpVersion_;
// HTTP request: The headers after the initial line: Eg, Content-Type:text/xml
OTab headers_;
// The name of the server
string serverName_;
virtual void handleErrors_ (const string& text)
{
if (logging_) {
cerr << text << endl;
}
}
// SATISFY PARENT
virtual void dispatchWork_ ()
{
// Errors will propogate as exceptions (usually from
// a HTTPthingee()).
try {
// Get the preamble, which tells us what we are supposed to do
string initial_line;
OTab headers;
httptools_.getPreamble(initial_line, headers);
// Parse initial request line: 1st line
const string& irl = initial_line;
Array<string> words = Split(irl);
if (words.length()!=3) {
httptools_.HTTPBadRequest("Initial request line malformed");
}
const string& op = words[0];
const string& url = words[1];
const string& http_version = words[2];
httpVersion_ = http_version; // HACK
processHTTP_(op, url, http_version, headers);
} catch (const runtime_error& re) {
handleErrors_("Runtime Error:"+string(re.what()));
} catch (const logic_error& le) {
handleErrors_("Logic Error:"+string(le.what()));
} catch (const exception& e) {
handleErrors_("Generic exception:"+string(e.what()));
} catch (...) {
handleErrors_("??? Unknown Exception ???");
}
// At this point, we are all done with the HTTP connection:
// close 'er up!
httptools_.close();
// And add myself back to pool
server_.addToClientPool(this);
postDispatchWork_();
}
// Hook for users who inherit and need to do some work after
virtual void postDispatchWork_ () { }
// When this is called, the initial line is set (which descibes
// what's coming) and all the headers are set.
virtual void processHTTP_ (const string& op, const string& url,
const string& http_version, const OTab& headers)
{
if (op=="GET") {
handleGET_(url, http_version, headers); // user hook
} else if (op=="POST") {
handlePOST_(url, http_version, headers); // user hook
} else {
httptools_.HTTPNotImplemented(op.c_str());
}
}
// User-hook for dealing with a GET: All initial-line, headers data
// has been processed, but the rest of the message needs to be processed
// (i.e,) and the response generated.
virtual void handleGET_ (const string& url, const string& http_version,
const OTab& headers)
{ httptools_.HTTPNotImplemented(); }
// User-hook for dealing with a POST: All initial-line, headers data
// has been processed, but the rest of the message needs to be processed
// (i.e,) and the response generated.
virtual void handlePOST_ (const string& url, const string& http_version,
const OTab& headers)
{ httptools_.HTTPNotImplemented(); }
}; // ThreadedHTTPWorker
// /////////////////////////////////// SimpleHTTPServer
// The actual threaded server that you start/end.
class SimpleHTTPServer : public ThreadedServer {
public:
// Create an HTTP Server on this host and port
SimpleHTTPServer (const string& host, int port=80) :
ThreadedServer(host, port)
{ }
protected:
// When a new connection comes in, we have to make sure
// we create the proper type of client for this server.
virtual ThreadedServerWorker* createThreadedServerWorker_ ()
{ return new ThreadedHTTPWorker("ThreadedHTTPWorker", *this); }
}; // SimpleHTTPServer
PTOOLS_END_NAMESPACE
#endif // SIMPLEHTTPSERVER_H_
| [
"noreply@github.com"
] | weizhou-geek.noreply@github.com |
1496cc2d1210e564654941c5c8a3532843f01e89 | 36183993b144b873d4d53e7b0f0dfebedcb77730 | /GameDevelopment/Game Programming Gems 3/Source Code/06 Audio/04 Burk/src/Circuit_Wind.cpp | 21901ccbb2b1b1a798892f58721721b56327dea8 | [] | no_license | alecnunn/bookresources | b95bf62dda3eb9b0ba0fb4e56025c5c7b6d605c0 | 4562f6430af5afffde790c42d0f3a33176d8003b | refs/heads/master | 2020-04-12T22:28:54.275703 | 2018-12-22T09:00:31 | 2018-12-22T09:00:31 | 162,790,540 | 20 | 14 | null | null | null | null | UTF-8 | C++ | false | false | 1,133 | cpp | #include <math.h>
#include "ggsynth.h"
#include "Circuit_Wind.h"
/**
* Circuit_Winds uses a RedNoise modulated ringing LowpassFIlter
*
* @author (C) 2002 Phil Burk, SoftSynth.com, All Rights Reserved
*/
Circuit_Wind::Circuit_Wind()
{
modRate = 0.6f;
modDepth = 350.0f;
frequency = 1000.0f;
Q = 16.0f;
envelope.setRate( 0.3f );
outputs = filter.outputs;
}
Circuit_Wind::~Circuit_Wind()
{
}
/***********************************************************************/
void Circuit_Wind::gen( GGSynthFloat amplitude )
{
envelope.gen1( amplitude * 0.2f );
GGSynthFloat level = envelope.outputs[0];
// save some CPU cycles if integrator at bottom
if( level > 0.0f )
{
// Calculate LFO.
whiteNoise.gen( level );
redNoise.gen1( modDepth, modRate );
// Use control rate LFO signal to modulate filter frequency.
filter.calculateCoefficients( redNoise.outputs[0] + frequency, Q );
// Calculate filter.
filter.gen( whiteNoise.outputs );
outputs = filter.outputs;
}
else
{
outputs = envelope.outputs; // silent
}
}
| [
"alec.nunn@gmail.com"
] | alec.nunn@gmail.com |
f218202bbdd37300c3b2aa1eebb153a6b8cd8b1a | 5d01a2a16078b78fbb7380a6ee548fc87a80e333 | /ETS/EtsIvUpdate/DbInterfaceBo.cpp | 8e87f2de92adc3277e0406674601dce359284358 | [] | no_license | WilliamQf-AI/IVRMstandard | 2fd66ae6e81976d39705614cfab3dbfb4e8553c5 | 761bbdd0343012e7367ea111869bb6a9d8f043c0 | refs/heads/master | 2023-04-04T22:06:48.237586 | 2013-04-17T13:56:40 | 2013-04-17T13:56:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,990 | cpp | #include "StdAfx.h"
#include "dbinterfacebo.h"
#include ".\dbinterfacebo.h"
//**************************************************************************************************************//
// class CDbInterfaceBo
//**************************************************************************************************************//
#include "IVData.h"
CDbInterfaceBo* CDbInterfaceBo::m_pDbInterface(NULL);
_bstr_t CDbInterfaceBo::m_bsConnectionString("");
DWORD CDbInterfaceBo::m_nReconnectionAttempts(5);
DWORD CDbInterfaceBo::m_nReconnectionDelay(5000);
CDbInterfaceBo::CDbInterfaceBo(void)
{
}
CDbInterfaceBo::~CDbInterfaceBo(void)
{
}
void CDbInterfaceBo::GetInstance(CDbInterfaceBo** ppDbInterface)
{
if ( m_pDbInterface)
m_pDbInterface = new CDbInterfaceBo();
*ppDbInterface = m_pDbInterface;
}
//--------------------------------------------------------------------------------------------------------------//
void CDbInterfaceBo::SetConnectionString(const std::string& rsConnectionString)
{
m_bsConnectionString = rsConnectionString.c_str();
}
//--------------------------------------------------------------------------------------------------------------//
void CDbInterfaceBo::SetReconnectionAttempts(DWORD nReconnectionAttempts)
{
m_nReconnectionAttempts = nReconnectionAttempts;
}
//--------------------------------------------------------------------------------------------------------------//
void CDbInterfaceBo::SetReconnectionDelay(DWORD nReconnectionDelay)
{
m_nReconnectionDelay = nReconnectionDelay;
}
//--------------------------------------------------------------------------------------------------------------//
EgLib::CDBConnection& CDbInterfaceBo::GetConnection()
{
return m_Connection;
}
//--------------------------------------------------------------------------------------------------------------//
void CDbInterfaceBo::Connect()
{
try
{
m_Connection.Open(m_bsConnectionString, m_nReconnectionDelay, m_nReconnectionAttempts, 30, 120);
}
catch ( _com_error _e)
{
g_Logs.TraceToFile ( LogFaults , "Can't connect to DB %s" , (LPCTSTR)_e.Description() ) ;
throw _e ;
}
}
//--------------------------------------------------------------------------------------------------------------//
void CDbInterfaceBo::Disconnect()
{
m_Connection.Close();
}
DWORD CDbInterfaceBo::BeginOfDay(void)
{
DWORD dwResult = S_OK ;
_bstr_t sUsp(_T("usp_DatabaseCleanUp"));
try
{
EgLib::CStoredProc<> spCleanUp(m_Connection, sUsp);
spCleanUp.Execute () ;
}
catch (const _com_error& re)
{
//OMLIB_TRACE_EX(re.Error(), ERROR_OM_DB_STOREDPROC, (LPCTSTR)sUsp, re.Description().length()?(LPCTSTR)re.Description():re.ErrorMessage());
//AfxMessageBox(_T("Error checking DB Version."), MB_ICONERROR);
dwResult = re.Error();
}
return dwResult;
}
bool CDbInterfaceBo::SaveIVStockData(const CIVStockData& _IVData)
{
DWORD dwResult = S_OK ;
_bstr_t sUsp(_T("usp_InputStockData"));
try
{
EgLib::CStoredProc<> spSave (m_Connection, sUsp);
spSave << _IVData.m_lStockId
<< _IVData.m_dBidPrice
<< _IVData.m_dAskPrice
<< 0
<< _IVData.m_lAskSize
<< _IVData.m_dtBidTime
<< _IVData.m_dtAsktime
<< _IVData.m_cBidEx
<< _IVData.m_cAskEx
<< _IVData.m_lVolume ;
spSave.Execute () ;
}
catch (const _com_error& re)
{
//OMLIB_TRACE_EX(re.Error(), ERROR_OM_DB_STOREDPROC, (LPCTSTR)sUsp, re.Description().length()?(LPCTSTR)re.Description():re.ErrorMessage());
//AfxMessageBox(_T("Error checking DB Version."), MB_ICONERROR);
dwResult = re.Error();
g_Logs.TraceToFile ( LogFaults , "DB Error: %s" , re.Description().length()?(LPCTSTR)re.Description():(LPCTSTR)re.ErrorMessage() );
}
return dwResult == S_OK;
}
bool CDbInterfaceBo::SaveIVOptionData ( const CIVOptionData& _IVData )
{
DWORD dwResult = S_OK ;
_bstr_t sUsp(_T("usp_InputOptionData"));
try
{
EgLib::CStoredProc<> spSave (m_Connection, sUsp);
spSave << _IVData.m_lOptionID
<< _IVData.m_lUnderlyingID
<< _IVData.m_dModelIV
<< _IVData.m_dIV
<< _IVData.m_dDelta
<< _IVData.m_dGamma
<< _IVData.m_dVega
<< _IVData.m_dThetta
<< _IVData.m_dRho
<< _IVData.m_dBidPrice
<< _IVData.m_dAskPrice
<< _IVData.m_lBidSize
<< _IVData.m_lAskSize
<< _IVData.m_dtBidTime
<< _IVData.m_dtAskTime
<< _IVData.m_cBidExchange
<< _IVData.m_cAskExchange
<< _IVData.m_lVolume ;
spSave.Execute () ;
}
catch (const _com_error& re)
{
//OMLIB_TRACE_EX(re.Error(), ERROR_OM_DB_STOREDPROC, (LPCTSTR)sUsp, re.Description().length()?(LPCTSTR)re.Description():re.ErrorMessage());
//AfxMessageBox(_T("Error checking DB Version."), MB_ICONERROR);
dwResult = re.Error();
g_Logs.TraceToFile ( LogFaults , "DB Error: %s" , re.Description().length()?(LPCTSTR)re.Description():(LPCTSTR)re.ErrorMessage() );
}
return dwResult == S_OK;
}
| [
"chuchev@egartech.com"
] | chuchev@egartech.com |
9e11b33615cce48a6a2b7a8a280b55222a8dc9b7 | e32c65cb1aaefcf4b796fa0c55ad7fc38c1207aa | /commandqueue.cpp | 7a845299cf2d466c035b18678c1d904c020968ba | [] | no_license | djmellowd/AirJet | b3e139921f3525f7a2ade2e93abfc6ec49303c32 | 42c85764e72f3d0795ee60721e7d3c5ba6929445 | refs/heads/main | 2023-08-15T21:03:56.449199 | 2021-10-02T08:20:06 | 2021-10-02T08:20:06 | 412,732,183 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 308 | cpp | #include "CommandQueue.h"
#include "SceneNode.h"
void CommandQueue::push(const Command& command)
{
mQueue.push(command);
}
Command CommandQueue::pop()
{
Command command = mQueue.front();
mQueue.pop();
return command;
}
bool CommandQueue::isEmpty() const
{
return mQueue.empty();
} | [
"noreply@github.com"
] | djmellowd.noreply@github.com |
1b4a42caecef4fcbb808a954b8e511b078772743 | 97f8be92810bafdbf68b77c8a938411462d5be4b | /3rdParty/rocksdb/6.8/utilities/transactions/write_unprepared_txn.cc | 6f28c2fceca71f9fb3c4af63229015339d7115db | [
"GPL-2.0-only",
"Apache-2.0",
"BSD-3-Clause",
"ICU",
"LGPL-2.1-or-later",
"BSD-4-Clause",
"GPL-1.0-or-later",
"Python-2.0",
"OpenSSL",
"Bison-exception-2.2",
"JSON",
"ISC",
"MIT",
"BSL-1.0",
"LicenseRef-scancode-public-domain",
"CC0-1.0",
"BSD-2-Clause",
"LicenseRef-scancode-autoco... | permissive | solisoft/arangodb | 022fefd77ca704bfa4ca240e6392e3afebdb474e | efd5a33bb1ad1ae3b63bfe1f9ce09b16116f62a2 | refs/heads/main | 2021-12-24T16:50:38.171240 | 2021-11-30T11:52:58 | 2021-11-30T11:52:58 | 436,619,840 | 2 | 0 | Apache-2.0 | 2021-12-09T13:05:46 | 2021-12-09T13:05:46 | null | UTF-8 | C++ | false | false | 38,940 | cc | // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under both the GPLv2 (found in the
// COPYING file in the root directory) and Apache 2.0 License
// (found in the LICENSE.Apache file in the root directory).
#ifndef ROCKSDB_LITE
#include "utilities/transactions/write_unprepared_txn.h"
#include "db/db_impl/db_impl.h"
#include "util/cast_util.h"
#include "utilities/transactions/write_unprepared_txn_db.h"
namespace ROCKSDB_NAMESPACE {
bool WriteUnpreparedTxnReadCallback::IsVisibleFullCheck(SequenceNumber seq) {
// Since unprep_seqs maps prep_seq => prepare_batch_cnt, to check if seq is
// in unprep_seqs, we have to check if seq is equal to prep_seq or any of
// the prepare_batch_cnt seq nums after it.
//
// TODO(lth): Can be optimized with std::lower_bound if unprep_seqs is
// large.
for (const auto& it : unprep_seqs_) {
if (it.first <= seq && seq < it.first + it.second) {
return true;
}
}
bool snap_released = false;
auto ret =
db_->IsInSnapshot(seq, wup_snapshot_, min_uncommitted_, &snap_released);
assert(!snap_released || backed_by_snapshot_ == kUnbackedByDBSnapshot);
snap_released_ |= snap_released;
return ret;
}
WriteUnpreparedTxn::WriteUnpreparedTxn(WriteUnpreparedTxnDB* txn_db,
const WriteOptions& write_options,
const TransactionOptions& txn_options)
: WritePreparedTxn(txn_db, write_options, txn_options),
wupt_db_(txn_db),
last_log_number_(0),
recovered_txn_(false),
largest_validated_seq_(0) {
if (txn_options.write_batch_flush_threshold < 0) {
write_batch_flush_threshold_ =
txn_db_impl_->GetTxnDBOptions().default_write_batch_flush_threshold;
} else {
write_batch_flush_threshold_ = txn_options.write_batch_flush_threshold;
}
}
WriteUnpreparedTxn::~WriteUnpreparedTxn() {
if (!unprep_seqs_.empty()) {
assert(log_number_ > 0);
assert(GetId() > 0);
assert(!name_.empty());
// We should rollback regardless of GetState, but some unit tests that
// test crash recovery run the destructor assuming that rollback does not
// happen, so that rollback during recovery can be exercised.
if (GetState() == STARTED || GetState() == LOCKS_STOLEN) {
auto s = RollbackInternal();
assert(s.ok());
if (!s.ok()) {
ROCKS_LOG_FATAL(
wupt_db_->info_log_,
"Rollback of WriteUnprepared transaction failed in destructor: %s",
s.ToString().c_str());
}
dbimpl_->logs_with_prep_tracker()->MarkLogAsHavingPrepSectionFlushed(
log_number_);
}
}
// Call tracked_keys_.clear() so that ~PessimisticTransaction does not
// try to unlock keys for recovered transactions.
if (recovered_txn_) {
tracked_keys_.clear();
}
}
void WriteUnpreparedTxn::Initialize(const TransactionOptions& txn_options) {
PessimisticTransaction::Initialize(txn_options);
if (txn_options.write_batch_flush_threshold < 0) {
write_batch_flush_threshold_ =
txn_db_impl_->GetTxnDBOptions().default_write_batch_flush_threshold;
} else {
write_batch_flush_threshold_ = txn_options.write_batch_flush_threshold;
}
unprep_seqs_.clear();
flushed_save_points_.reset(nullptr);
unflushed_save_points_.reset(nullptr);
recovered_txn_ = false;
largest_validated_seq_ = 0;
assert(active_iterators_.empty());
active_iterators_.clear();
untracked_keys_.clear();
}
Status WriteUnpreparedTxn::HandleWrite(std::function<Status()> do_write) {
Status s;
if (active_iterators_.empty()) {
s = MaybeFlushWriteBatchToDB();
if (!s.ok()) {
return s;
}
}
s = do_write();
if (s.ok()) {
if (snapshot_) {
largest_validated_seq_ =
std::max(largest_validated_seq_, snapshot_->GetSequenceNumber());
} else {
// TODO(lth): We should use the same number as tracked_at_seq in TryLock,
// because what is actually being tracked is the sequence number at which
// this key was locked at.
largest_validated_seq_ = db_impl_->GetLastPublishedSequence();
}
}
return s;
}
Status WriteUnpreparedTxn::Put(ColumnFamilyHandle* column_family,
const Slice& key, const Slice& value,
const bool assume_tracked) {
return HandleWrite([&]() {
return TransactionBaseImpl::Put(column_family, key, value, assume_tracked);
});
}
Status WriteUnpreparedTxn::Put(ColumnFamilyHandle* column_family,
const SliceParts& key, const SliceParts& value,
const bool assume_tracked) {
return HandleWrite([&]() {
return TransactionBaseImpl::Put(column_family, key, value, assume_tracked);
});
}
Status WriteUnpreparedTxn::Merge(ColumnFamilyHandle* column_family,
const Slice& key, const Slice& value,
const bool assume_tracked) {
return HandleWrite([&]() {
return TransactionBaseImpl::Merge(column_family, key, value,
assume_tracked);
});
}
Status WriteUnpreparedTxn::Delete(ColumnFamilyHandle* column_family,
const Slice& key, const bool assume_tracked) {
return HandleWrite([&]() {
return TransactionBaseImpl::Delete(column_family, key, assume_tracked);
});
}
Status WriteUnpreparedTxn::Delete(ColumnFamilyHandle* column_family,
const SliceParts& key,
const bool assume_tracked) {
return HandleWrite([&]() {
return TransactionBaseImpl::Delete(column_family, key, assume_tracked);
});
}
Status WriteUnpreparedTxn::SingleDelete(ColumnFamilyHandle* column_family,
const Slice& key,
const bool assume_tracked) {
return HandleWrite([&]() {
return TransactionBaseImpl::SingleDelete(column_family, key,
assume_tracked);
});
}
Status WriteUnpreparedTxn::SingleDelete(ColumnFamilyHandle* column_family,
const SliceParts& key,
const bool assume_tracked) {
return HandleWrite([&]() {
return TransactionBaseImpl::SingleDelete(column_family, key,
assume_tracked);
});
}
// WriteUnpreparedTxn::RebuildFromWriteBatch is only called on recovery. For
// WriteUnprepared, the write batches have already been written into the
// database during WAL replay, so all we have to do is just to "retrack" the key
// so that rollbacks are possible.
//
// Calling TryLock instead of TrackKey is also possible, but as an optimization,
// recovered transactions do not hold locks on their keys. This follows the
// implementation in PessimisticTransactionDB::Initialize where we set
// skip_concurrency_control to true.
Status WriteUnpreparedTxn::RebuildFromWriteBatch(WriteBatch* wb) {
struct TrackKeyHandler : public WriteBatch::Handler {
WriteUnpreparedTxn* txn_;
bool rollback_merge_operands_;
TrackKeyHandler(WriteUnpreparedTxn* txn, bool rollback_merge_operands)
: txn_(txn), rollback_merge_operands_(rollback_merge_operands) {}
Status PutCF(uint32_t cf, const Slice& key, const Slice&) override {
txn_->TrackKey(cf, key.ToString(), kMaxSequenceNumber,
false /* read_only */, true /* exclusive */);
return Status::OK();
}
Status DeleteCF(uint32_t cf, const Slice& key) override {
txn_->TrackKey(cf, key.ToString(), kMaxSequenceNumber,
false /* read_only */, true /* exclusive */);
return Status::OK();
}
Status SingleDeleteCF(uint32_t cf, const Slice& key) override {
txn_->TrackKey(cf, key.ToString(), kMaxSequenceNumber,
false /* read_only */, true /* exclusive */);
return Status::OK();
}
Status MergeCF(uint32_t cf, const Slice& key, const Slice&) override {
if (rollback_merge_operands_) {
txn_->TrackKey(cf, key.ToString(), kMaxSequenceNumber,
false /* read_only */, true /* exclusive */);
}
return Status::OK();
}
// Recovered batches do not contain 2PC markers.
Status MarkBeginPrepare(bool) override { return Status::InvalidArgument(); }
Status MarkEndPrepare(const Slice&) override {
return Status::InvalidArgument();
}
Status MarkNoop(bool) override { return Status::InvalidArgument(); }
Status MarkCommit(const Slice&) override {
return Status::InvalidArgument();
}
Status MarkRollback(const Slice&) override {
return Status::InvalidArgument();
}
};
TrackKeyHandler handler(this,
wupt_db_->txn_db_options_.rollback_merge_operands);
return wb->Iterate(&handler);
}
Status WriteUnpreparedTxn::MaybeFlushWriteBatchToDB() {
const bool kPrepared = true;
Status s;
if (write_batch_flush_threshold_ > 0 &&
write_batch_.GetWriteBatch()->Count() > 0 &&
write_batch_.GetDataSize() >
static_cast<size_t>(write_batch_flush_threshold_)) {
assert(GetState() != PREPARED);
s = FlushWriteBatchToDB(!kPrepared);
}
return s;
}
Status WriteUnpreparedTxn::FlushWriteBatchToDB(bool prepared) {
// If the current write batch contains savepoints, then some special handling
// is required so that RollbackToSavepoint can work.
//
// RollbackToSavepoint is not supported after Prepare() is called, so only do
// this for unprepared batches.
if (!prepared && unflushed_save_points_ != nullptr &&
!unflushed_save_points_->empty()) {
return FlushWriteBatchWithSavePointToDB();
}
return FlushWriteBatchToDBInternal(prepared);
}
Status WriteUnpreparedTxn::FlushWriteBatchToDBInternal(bool prepared) {
if (name_.empty()) {
assert(!prepared);
#ifndef NDEBUG
static std::atomic_ullong autogen_id{0};
// To avoid changing all tests to call SetName, just autogenerate one.
if (wupt_db_->txn_db_options_.autogenerate_name) {
SetName(std::string("autoxid") + ToString(autogen_id.fetch_add(1)));
} else
#endif
{
return Status::InvalidArgument("Cannot write to DB without SetName.");
}
}
struct UntrackedKeyHandler : public WriteBatch::Handler {
WriteUnpreparedTxn* txn_;
bool rollback_merge_operands_;
UntrackedKeyHandler(WriteUnpreparedTxn* txn, bool rollback_merge_operands)
: txn_(txn), rollback_merge_operands_(rollback_merge_operands) {}
Status AddUntrackedKey(uint32_t cf, const Slice& key) {
auto str = key.ToString();
if (txn_->tracked_keys_[cf].count(str) == 0) {
txn_->untracked_keys_[cf].push_back(str);
}
return Status::OK();
}
Status PutCF(uint32_t cf, const Slice& key, const Slice&) override {
return AddUntrackedKey(cf, key);
}
Status DeleteCF(uint32_t cf, const Slice& key) override {
return AddUntrackedKey(cf, key);
}
Status SingleDeleteCF(uint32_t cf, const Slice& key) override {
return AddUntrackedKey(cf, key);
}
Status MergeCF(uint32_t cf, const Slice& key, const Slice&) override {
if (rollback_merge_operands_) {
return AddUntrackedKey(cf, key);
}
return Status::OK();
}
// The only expected 2PC marker is the initial Noop marker.
Status MarkNoop(bool empty_batch) override {
return empty_batch ? Status::OK() : Status::InvalidArgument();
}
Status MarkBeginPrepare(bool) override { return Status::InvalidArgument(); }
Status MarkEndPrepare(const Slice&) override {
return Status::InvalidArgument();
}
Status MarkCommit(const Slice&) override {
return Status::InvalidArgument();
}
Status MarkRollback(const Slice&) override {
return Status::InvalidArgument();
}
};
UntrackedKeyHandler handler(
this, wupt_db_->txn_db_options_.rollback_merge_operands);
auto s = GetWriteBatch()->GetWriteBatch()->Iterate(&handler);
assert(s.ok());
// TODO(lth): Reduce duplicate code with WritePrepared prepare logic.
WriteOptions write_options = write_options_;
write_options.disableWAL = false;
const bool WRITE_AFTER_COMMIT = true;
const bool first_prepare_batch = log_number_ == 0;
// MarkEndPrepare will change Noop marker to the appropriate marker.
WriteBatchInternal::MarkEndPrepare(GetWriteBatch()->GetWriteBatch(), name_,
!WRITE_AFTER_COMMIT, !prepared);
// For each duplicate key we account for a new sub-batch
prepare_batch_cnt_ = GetWriteBatch()->SubBatchCnt();
// AddPrepared better to be called in the pre-release callback otherwise there
// is a non-zero chance of max advancing prepare_seq and readers assume the
// data as committed.
// Also having it in the PreReleaseCallback allows in-order addition of
// prepared entries to PreparedHeap and hence enables an optimization. Refer
// to SmallestUnCommittedSeq for more details.
AddPreparedCallback add_prepared_callback(
wpt_db_, db_impl_, prepare_batch_cnt_,
db_impl_->immutable_db_options().two_write_queues, first_prepare_batch);
const bool DISABLE_MEMTABLE = true;
uint64_t seq_used = kMaxSequenceNumber;
// log_number_ should refer to the oldest log containing uncommitted data
// from the current transaction. This means that if log_number_ is set,
// WriteImpl should not overwrite that value, so set log_used to nullptr if
// log_number_ is already set.
s = db_impl_->WriteImpl(write_options, GetWriteBatch()->GetWriteBatch(),
/*callback*/ nullptr, &last_log_number_,
/*log ref*/ 0, !DISABLE_MEMTABLE, &seq_used,
prepare_batch_cnt_, &add_prepared_callback);
if (log_number_ == 0) {
log_number_ = last_log_number_;
}
assert(!s.ok() || seq_used != kMaxSequenceNumber);
auto prepare_seq = seq_used;
// Only call SetId if it hasn't been set yet.
if (GetId() == 0) {
SetId(prepare_seq);
}
// unprep_seqs_ will also contain prepared seqnos since they are treated in
// the same way in the prepare/commit callbacks. See the comment on the
// definition of unprep_seqs_.
unprep_seqs_[prepare_seq] = prepare_batch_cnt_;
// Reset transaction state.
if (!prepared) {
prepare_batch_cnt_ = 0;
const bool kClear = true;
TransactionBaseImpl::InitWriteBatch(kClear);
}
return s;
}
Status WriteUnpreparedTxn::FlushWriteBatchWithSavePointToDB() {
assert(unflushed_save_points_ != nullptr &&
unflushed_save_points_->size() > 0);
assert(save_points_ != nullptr && save_points_->size() > 0);
assert(save_points_->size() >= unflushed_save_points_->size());
// Handler class for creating an unprepared batch from a savepoint.
struct SavePointBatchHandler : public WriteBatch::Handler {
WriteBatchWithIndex* wb_;
const std::map<uint32_t, ColumnFamilyHandle*>& handles_;
SavePointBatchHandler(
WriteBatchWithIndex* wb,
const std::map<uint32_t, ColumnFamilyHandle*>& handles)
: wb_(wb), handles_(handles) {}
Status PutCF(uint32_t cf, const Slice& key, const Slice& value) override {
return wb_->Put(handles_.at(cf), key, value);
}
Status DeleteCF(uint32_t cf, const Slice& key) override {
return wb_->Delete(handles_.at(cf), key);
}
Status SingleDeleteCF(uint32_t cf, const Slice& key) override {
return wb_->SingleDelete(handles_.at(cf), key);
}
Status MergeCF(uint32_t cf, const Slice& key, const Slice& value) override {
return wb_->Merge(handles_.at(cf), key, value);
}
// The only expected 2PC marker is the initial Noop marker.
Status MarkNoop(bool empty_batch) override {
return empty_batch ? Status::OK() : Status::InvalidArgument();
}
Status MarkBeginPrepare(bool) override { return Status::InvalidArgument(); }
Status MarkEndPrepare(const Slice&) override {
return Status::InvalidArgument();
}
Status MarkCommit(const Slice&) override {
return Status::InvalidArgument();
}
Status MarkRollback(const Slice&) override {
return Status::InvalidArgument();
}
};
// The comparator of the default cf is passed in, similar to the
// initialization of TransactionBaseImpl::write_batch_. This comparator is
// only used if the write batch encounters an invalid cf id, and falls back to
// this comparator.
WriteBatchWithIndex wb(wpt_db_->DefaultColumnFamily()->GetComparator(), 0,
true, 0);
// Swap with write_batch_ so that wb contains the complete write batch. The
// actual write batch that will be flushed to DB will be built in
// write_batch_, and will be read by FlushWriteBatchToDBInternal.
std::swap(wb, write_batch_);
TransactionBaseImpl::InitWriteBatch();
size_t prev_boundary = WriteBatchInternal::kHeader;
const bool kPrepared = true;
for (size_t i = 0; i < unflushed_save_points_->size() + 1; i++) {
bool trailing_batch = i == unflushed_save_points_->size();
SavePointBatchHandler sp_handler(&write_batch_,
*wupt_db_->GetCFHandleMap().get());
size_t curr_boundary = trailing_batch ? wb.GetWriteBatch()->GetDataSize()
: (*unflushed_save_points_)[i];
// Construct the partial write batch up to the savepoint.
//
// Theoretically, a memcpy between the write batches should be sufficient
// since the rewriting into the batch should produce the exact same byte
// representation. Rebuilding the WriteBatchWithIndex index is still
// necessary though, and would imply doing two passes over the batch though.
Status s = WriteBatchInternal::Iterate(wb.GetWriteBatch(), &sp_handler,
prev_boundary, curr_boundary);
if (!s.ok()) {
return s;
}
if (write_batch_.GetWriteBatch()->Count() > 0) {
// Flush the write batch.
s = FlushWriteBatchToDBInternal(!kPrepared);
if (!s.ok()) {
return s;
}
}
if (!trailing_batch) {
if (flushed_save_points_ == nullptr) {
flushed_save_points_.reset(
new autovector<WriteUnpreparedTxn::SavePoint>());
}
flushed_save_points_->emplace_back(
unprep_seqs_, new ManagedSnapshot(db_impl_, wupt_db_->GetSnapshot()));
}
prev_boundary = curr_boundary;
const bool kClear = true;
TransactionBaseImpl::InitWriteBatch(kClear);
}
unflushed_save_points_->clear();
return Status::OK();
}
Status WriteUnpreparedTxn::PrepareInternal() {
const bool kPrepared = true;
return FlushWriteBatchToDB(kPrepared);
}
Status WriteUnpreparedTxn::CommitWithoutPrepareInternal() {
if (unprep_seqs_.empty()) {
assert(log_number_ == 0);
assert(GetId() == 0);
return WritePreparedTxn::CommitWithoutPrepareInternal();
}
// TODO(lth): We should optimize commit without prepare to not perform
// a prepare under the hood.
auto s = PrepareInternal();
if (!s.ok()) {
return s;
}
return CommitInternal();
}
Status WriteUnpreparedTxn::CommitInternal() {
// TODO(lth): Reduce duplicate code with WritePrepared commit logic.
// We take the commit-time batch and append the Commit marker. The Memtable
// will ignore the Commit marker in non-recovery mode
WriteBatch* working_batch = GetCommitTimeWriteBatch();
const bool empty = working_batch->Count() == 0;
WriteBatchInternal::MarkCommit(working_batch, name_);
const bool for_recovery = use_only_the_last_commit_time_batch_for_recovery_;
if (!empty && for_recovery) {
// When not writing to memtable, we can still cache the latest write batch.
// The cached batch will be written to memtable in WriteRecoverableState
// during FlushMemTable
WriteBatchInternal::SetAsLastestPersistentState(working_batch);
}
const bool includes_data = !empty && !for_recovery;
size_t commit_batch_cnt = 0;
if (UNLIKELY(includes_data)) {
ROCKS_LOG_WARN(db_impl_->immutable_db_options().info_log,
"Duplicate key overhead");
SubBatchCounter counter(*wpt_db_->GetCFComparatorMap());
auto s = working_batch->Iterate(&counter);
assert(s.ok());
commit_batch_cnt = counter.BatchCount();
}
const bool disable_memtable = !includes_data;
const bool do_one_write =
!db_impl_->immutable_db_options().two_write_queues || disable_memtable;
WriteUnpreparedCommitEntryPreReleaseCallback update_commit_map(
wpt_db_, db_impl_, unprep_seqs_, commit_batch_cnt);
const bool kFirstPrepareBatch = true;
AddPreparedCallback add_prepared_callback(
wpt_db_, db_impl_, commit_batch_cnt,
db_impl_->immutable_db_options().two_write_queues, !kFirstPrepareBatch);
PreReleaseCallback* pre_release_callback;
if (do_one_write) {
pre_release_callback = &update_commit_map;
} else {
pre_release_callback = &add_prepared_callback;
}
uint64_t seq_used = kMaxSequenceNumber;
// Since the prepared batch is directly written to memtable, there is
// already a connection between the memtable and its WAL, so there is no
// need to redundantly reference the log that contains the prepared data.
const uint64_t zero_log_number = 0ull;
size_t batch_cnt = UNLIKELY(commit_batch_cnt) ? commit_batch_cnt : 1;
auto s = db_impl_->WriteImpl(write_options_, working_batch, nullptr, nullptr,
zero_log_number, disable_memtable, &seq_used,
batch_cnt, pre_release_callback);
assert(!s.ok() || seq_used != kMaxSequenceNumber);
const SequenceNumber commit_batch_seq = seq_used;
if (LIKELY(do_one_write || !s.ok())) {
if (LIKELY(s.ok())) {
// Note RemovePrepared should be called after WriteImpl that publishsed
// the seq. Otherwise SmallestUnCommittedSeq optimization breaks.
for (const auto& seq : unprep_seqs_) {
wpt_db_->RemovePrepared(seq.first, seq.second);
}
}
if (UNLIKELY(!do_one_write)) {
wpt_db_->RemovePrepared(commit_batch_seq, commit_batch_cnt);
}
unprep_seqs_.clear();
flushed_save_points_.reset(nullptr);
unflushed_save_points_.reset(nullptr);
return s;
} // else do the 2nd write to publish seq
// Populate unprep_seqs_ with commit_batch_seq, since we treat data in the
// commit write batch as just another "unprepared" batch. This will also
// update the unprep_seqs_ in the update_commit_map callback.
unprep_seqs_[commit_batch_seq] = commit_batch_cnt;
WriteUnpreparedCommitEntryPreReleaseCallback
update_commit_map_with_commit_batch(wpt_db_, db_impl_, unprep_seqs_, 0);
// Note: the 2nd write comes with a performance penality. So if we have too
// many of commits accompanied with ComitTimeWriteBatch and yet we cannot
// enable use_only_the_last_commit_time_batch_for_recovery_ optimization,
// two_write_queues should be disabled to avoid many additional writes here.
// Update commit map only from the 2nd queue
WriteBatch empty_batch;
empty_batch.PutLogData(Slice());
// In the absence of Prepare markers, use Noop as a batch separator
WriteBatchInternal::InsertNoop(&empty_batch);
const bool DISABLE_MEMTABLE = true;
const size_t ONE_BATCH = 1;
const uint64_t NO_REF_LOG = 0;
s = db_impl_->WriteImpl(write_options_, &empty_batch, nullptr, nullptr,
NO_REF_LOG, DISABLE_MEMTABLE, &seq_used, ONE_BATCH,
&update_commit_map_with_commit_batch);
assert(!s.ok() || seq_used != kMaxSequenceNumber);
// Note RemovePrepared should be called after WriteImpl that publishsed the
// seq. Otherwise SmallestUnCommittedSeq optimization breaks.
for (const auto& seq : unprep_seqs_) {
wpt_db_->RemovePrepared(seq.first, seq.second);
}
unprep_seqs_.clear();
flushed_save_points_.reset(nullptr);
unflushed_save_points_.reset(nullptr);
return s;
}
Status WriteUnpreparedTxn::WriteRollbackKeys(
const TransactionKeyMap& tracked_keys, WriteBatchWithIndex* rollback_batch,
ReadCallback* callback, const ReadOptions& roptions) {
const auto& cf_map = *wupt_db_->GetCFHandleMap();
auto WriteRollbackKey = [&](const std::string& key, uint32_t cfid) {
const auto& cf_handle = cf_map.at(cfid);
PinnableSlice pinnable_val;
bool not_used;
DBImpl::GetImplOptions get_impl_options;
get_impl_options.column_family = cf_handle;
get_impl_options.value = &pinnable_val;
get_impl_options.value_found = ¬_used;
get_impl_options.callback = callback;
auto s = db_impl_->GetImpl(roptions, key, get_impl_options);
if (s.ok()) {
s = rollback_batch->Put(cf_handle, key, pinnable_val);
assert(s.ok());
} else if (s.IsNotFound()) {
s = rollback_batch->Delete(cf_handle, key);
assert(s.ok());
} else {
return s;
}
return Status::OK();
};
for (const auto& cfkey : tracked_keys) {
const auto cfid = cfkey.first;
const auto& keys = cfkey.second;
for (const auto& pair : keys) {
auto s = WriteRollbackKey(pair.first, cfid);
if (!s.ok()) {
return s;
}
}
}
for (const auto& cfkey : untracked_keys_) {
const auto cfid = cfkey.first;
const auto& keys = cfkey.second;
for (const auto& key : keys) {
auto s = WriteRollbackKey(key, cfid);
if (!s.ok()) {
return s;
}
}
}
return Status::OK();
}
Status WriteUnpreparedTxn::RollbackInternal() {
// TODO(lth): Reduce duplicate code with WritePrepared rollback logic.
WriteBatchWithIndex rollback_batch(
wpt_db_->DefaultColumnFamily()->GetComparator(), 0, true, 0);
assert(GetId() != kMaxSequenceNumber);
assert(GetId() > 0);
Status s;
auto read_at_seq = kMaxSequenceNumber;
ReadOptions roptions;
// to prevent callback's seq to be overrriden inside DBImpk::Get
roptions.snapshot = wpt_db_->GetMaxSnapshot();
// Note that we do not use WriteUnpreparedTxnReadCallback because we do not
// need to read our own writes when reading prior versions of the key for
// rollback.
WritePreparedTxnReadCallback callback(wpt_db_, read_at_seq);
// TODO(lth): We write rollback batch all in a single batch here, but this
// should be subdivded into multiple batches as well. In phase 2, when key
// sets are read from WAL, this will happen naturally.
WriteRollbackKeys(GetTrackedKeys(), &rollback_batch, &callback, roptions);
// The Rollback marker will be used as a batch separator
WriteBatchInternal::MarkRollback(rollback_batch.GetWriteBatch(), name_);
bool do_one_write = !db_impl_->immutable_db_options().two_write_queues;
const bool DISABLE_MEMTABLE = true;
const uint64_t NO_REF_LOG = 0;
uint64_t seq_used = kMaxSequenceNumber;
// Rollback batch may contain duplicate keys, because tracked_keys_ is not
// comparator aware.
auto rollback_batch_cnt = rollback_batch.SubBatchCnt();
// We commit the rolled back prepared batches. Although this is
// counter-intuitive, i) it is safe to do so, since the prepared batches are
// already canceled out by the rollback batch, ii) adding the commit entry to
// CommitCache will allow us to benefit from the existing mechanism in
// CommitCache that keeps an entry evicted due to max advance and yet overlaps
// with a live snapshot around so that the live snapshot properly skips the
// entry even if its prepare seq is lower than max_evicted_seq_.
//
// TODO(lth): RollbackInternal is conceptually very similar to
// CommitInternal, with the rollback batch simply taking on the role of
// CommitTimeWriteBatch. We should be able to merge the two code paths.
WriteUnpreparedCommitEntryPreReleaseCallback update_commit_map(
wpt_db_, db_impl_, unprep_seqs_, rollback_batch_cnt);
// Note: the rollback batch does not need AddPrepared since it is written to
// DB in one shot. min_uncommitted still works since it requires capturing
// data that is written to DB but not yet committed, while the rollback
// batch commits with PreReleaseCallback.
s = db_impl_->WriteImpl(write_options_, rollback_batch.GetWriteBatch(),
nullptr, nullptr, NO_REF_LOG, !DISABLE_MEMTABLE,
&seq_used, rollback_batch_cnt,
do_one_write ? &update_commit_map : nullptr);
assert(!s.ok() || seq_used != kMaxSequenceNumber);
if (!s.ok()) {
return s;
}
if (do_one_write) {
for (const auto& seq : unprep_seqs_) {
wpt_db_->RemovePrepared(seq.first, seq.second);
}
unprep_seqs_.clear();
flushed_save_points_.reset(nullptr);
unflushed_save_points_.reset(nullptr);
return s;
} // else do the 2nd write for commit
uint64_t& prepare_seq = seq_used;
// Populate unprep_seqs_ with rollback_batch_cnt, since we treat data in the
// rollback write batch as just another "unprepared" batch. This will also
// update the unprep_seqs_ in the update_commit_map callback.
unprep_seqs_[prepare_seq] = rollback_batch_cnt;
WriteUnpreparedCommitEntryPreReleaseCallback
update_commit_map_with_rollback_batch(wpt_db_, db_impl_, unprep_seqs_, 0);
ROCKS_LOG_DETAILS(db_impl_->immutable_db_options().info_log,
"RollbackInternal 2nd write prepare_seq: %" PRIu64,
prepare_seq);
WriteBatch empty_batch;
const size_t ONE_BATCH = 1;
empty_batch.PutLogData(Slice());
// In the absence of Prepare markers, use Noop as a batch separator
WriteBatchInternal::InsertNoop(&empty_batch);
s = db_impl_->WriteImpl(write_options_, &empty_batch, nullptr, nullptr,
NO_REF_LOG, DISABLE_MEMTABLE, &seq_used, ONE_BATCH,
&update_commit_map_with_rollback_batch);
assert(!s.ok() || seq_used != kMaxSequenceNumber);
// Mark the txn as rolled back
if (s.ok()) {
for (const auto& seq : unprep_seqs_) {
wpt_db_->RemovePrepared(seq.first, seq.second);
}
}
unprep_seqs_.clear();
flushed_save_points_.reset(nullptr);
unflushed_save_points_.reset(nullptr);
return s;
}
void WriteUnpreparedTxn::Clear() {
if (!recovered_txn_) {
txn_db_impl_->UnLock(this, &GetTrackedKeys());
}
unprep_seqs_.clear();
flushed_save_points_.reset(nullptr);
unflushed_save_points_.reset(nullptr);
recovered_txn_ = false;
largest_validated_seq_ = 0;
assert(active_iterators_.empty());
active_iterators_.clear();
untracked_keys_.clear();
TransactionBaseImpl::Clear();
}
void WriteUnpreparedTxn::SetSavePoint() {
assert((unflushed_save_points_ ? unflushed_save_points_->size() : 0) +
(flushed_save_points_ ? flushed_save_points_->size() : 0) ==
(save_points_ ? save_points_->size() : 0));
PessimisticTransaction::SetSavePoint();
if (unflushed_save_points_ == nullptr) {
unflushed_save_points_.reset(new autovector<size_t>());
}
unflushed_save_points_->push_back(write_batch_.GetDataSize());
}
Status WriteUnpreparedTxn::RollbackToSavePoint() {
assert((unflushed_save_points_ ? unflushed_save_points_->size() : 0) +
(flushed_save_points_ ? flushed_save_points_->size() : 0) ==
(save_points_ ? save_points_->size() : 0));
if (unflushed_save_points_ != nullptr && unflushed_save_points_->size() > 0) {
Status s = PessimisticTransaction::RollbackToSavePoint();
assert(!s.IsNotFound());
unflushed_save_points_->pop_back();
return s;
}
if (flushed_save_points_ != nullptr && !flushed_save_points_->empty()) {
return RollbackToSavePointInternal();
}
return Status::NotFound();
}
Status WriteUnpreparedTxn::RollbackToSavePointInternal() {
Status s;
const bool kClear = true;
TransactionBaseImpl::InitWriteBatch(kClear);
assert(flushed_save_points_->size() > 0);
WriteUnpreparedTxn::SavePoint& top = flushed_save_points_->back();
assert(save_points_ != nullptr && save_points_->size() > 0);
const TransactionKeyMap& tracked_keys = save_points_->top().new_keys_;
ReadOptions roptions;
roptions.snapshot = top.snapshot_->snapshot();
SequenceNumber min_uncommitted =
static_cast_with_check<const SnapshotImpl, const Snapshot>(
roptions.snapshot)
->min_uncommitted_;
SequenceNumber snap_seq = roptions.snapshot->GetSequenceNumber();
WriteUnpreparedTxnReadCallback callback(wupt_db_, snap_seq, min_uncommitted,
top.unprep_seqs_,
kBackedByDBSnapshot);
WriteRollbackKeys(tracked_keys, &write_batch_, &callback, roptions);
const bool kPrepared = true;
s = FlushWriteBatchToDBInternal(!kPrepared);
assert(s.ok());
if (!s.ok()) {
return s;
}
// PessimisticTransaction::RollbackToSavePoint will call also call
// RollbackToSavepoint on write_batch_. However, write_batch_ is empty and has
// no savepoints because this savepoint has already been flushed. Work around
// this by setting a fake savepoint.
write_batch_.SetSavePoint();
s = PessimisticTransaction::RollbackToSavePoint();
assert(s.ok());
if (!s.ok()) {
return s;
}
flushed_save_points_->pop_back();
return s;
}
Status WriteUnpreparedTxn::PopSavePoint() {
assert((unflushed_save_points_ ? unflushed_save_points_->size() : 0) +
(flushed_save_points_ ? flushed_save_points_->size() : 0) ==
(save_points_ ? save_points_->size() : 0));
if (unflushed_save_points_ != nullptr && unflushed_save_points_->size() > 0) {
Status s = PessimisticTransaction::PopSavePoint();
assert(!s.IsNotFound());
unflushed_save_points_->pop_back();
return s;
}
if (flushed_save_points_ != nullptr && !flushed_save_points_->empty()) {
// PessimisticTransaction::PopSavePoint will call also call PopSavePoint on
// write_batch_. However, write_batch_ is empty and has no savepoints
// because this savepoint has already been flushed. Work around this by
// setting a fake savepoint.
write_batch_.SetSavePoint();
Status s = PessimisticTransaction::PopSavePoint();
assert(!s.IsNotFound());
flushed_save_points_->pop_back();
return s;
}
return Status::NotFound();
}
void WriteUnpreparedTxn::MultiGet(const ReadOptions& options,
ColumnFamilyHandle* column_family,
const size_t num_keys, const Slice* keys,
PinnableSlice* values, Status* statuses,
const bool sorted_input) {
SequenceNumber min_uncommitted, snap_seq;
const SnapshotBackup backed_by_snapshot =
wupt_db_->AssignMinMaxSeqs(options.snapshot, &min_uncommitted, &snap_seq);
WriteUnpreparedTxnReadCallback callback(wupt_db_, snap_seq, min_uncommitted,
unprep_seqs_, backed_by_snapshot);
write_batch_.MultiGetFromBatchAndDB(db_, options, column_family, num_keys,
keys, values, statuses, sorted_input,
&callback);
if (UNLIKELY(!callback.valid() ||
!wupt_db_->ValidateSnapshot(snap_seq, backed_by_snapshot))) {
wupt_db_->WPRecordTick(TXN_GET_TRY_AGAIN);
for (size_t i = 0; i < num_keys; i++) {
statuses[i] = Status::TryAgain();
}
}
}
Status WriteUnpreparedTxn::Get(const ReadOptions& options,
ColumnFamilyHandle* column_family,
const Slice& key, PinnableSlice* value) {
SequenceNumber min_uncommitted, snap_seq;
const SnapshotBackup backed_by_snapshot =
wupt_db_->AssignMinMaxSeqs(options.snapshot, &min_uncommitted, &snap_seq);
WriteUnpreparedTxnReadCallback callback(wupt_db_, snap_seq, min_uncommitted,
unprep_seqs_, backed_by_snapshot);
auto res = write_batch_.GetFromBatchAndDB(db_, options, column_family, key,
value, &callback);
if (LIKELY(callback.valid() &&
wupt_db_->ValidateSnapshot(snap_seq, backed_by_snapshot))) {
return res;
} else {
wupt_db_->WPRecordTick(TXN_GET_TRY_AGAIN);
return Status::TryAgain();
}
}
namespace {
static void CleanupWriteUnpreparedWBWIIterator(void* arg1, void* arg2) {
auto txn = reinterpret_cast<WriteUnpreparedTxn*>(arg1);
auto iter = reinterpret_cast<Iterator*>(arg2);
txn->RemoveActiveIterator(iter);
}
} // anonymous namespace
Iterator* WriteUnpreparedTxn::GetIterator(const ReadOptions& options) {
return GetIterator(options, wupt_db_->DefaultColumnFamily());
}
Iterator* WriteUnpreparedTxn::GetIterator(const ReadOptions& options,
ColumnFamilyHandle* column_family) {
// Make sure to get iterator from WriteUnprepareTxnDB, not the root db.
Iterator* db_iter = wupt_db_->NewIterator(options, column_family, this);
assert(db_iter);
auto iter = write_batch_.NewIteratorWithBase(column_family, db_iter);
active_iterators_.push_back(iter);
iter->RegisterCleanup(CleanupWriteUnpreparedWBWIIterator, this, iter);
return iter;
}
Status WriteUnpreparedTxn::ValidateSnapshot(ColumnFamilyHandle* column_family,
const Slice& key,
SequenceNumber* tracked_at_seq) {
// TODO(lth): Reduce duplicate code with WritePrepared ValidateSnapshot logic.
assert(snapshot_);
SequenceNumber min_uncommitted =
static_cast_with_check<const SnapshotImpl, const Snapshot>(
snapshot_.get())
->min_uncommitted_;
SequenceNumber snap_seq = snapshot_->GetSequenceNumber();
// tracked_at_seq is either max or the last snapshot with which this key was
// trackeed so there is no need to apply the IsInSnapshot to this comparison
// here as tracked_at_seq is not a prepare seq.
if (*tracked_at_seq <= snap_seq) {
// If the key has been previous validated at a sequence number earlier
// than the curent snapshot's sequence number, we already know it has not
// been modified.
return Status::OK();
}
*tracked_at_seq = snap_seq;
ColumnFamilyHandle* cfh =
column_family ? column_family : db_impl_->DefaultColumnFamily();
WriteUnpreparedTxnReadCallback snap_checker(
wupt_db_, snap_seq, min_uncommitted, unprep_seqs_, kBackedByDBSnapshot);
return TransactionUtil::CheckKeyForConflicts(db_impl_, cfh, key.ToString(),
snap_seq, false /* cache_only */,
&snap_checker, min_uncommitted);
}
const std::map<SequenceNumber, size_t>&
WriteUnpreparedTxn::GetUnpreparedSequenceNumbers() {
return unprep_seqs_;
}
} // namespace ROCKSDB_NAMESPACE
#endif // ROCKSDB_LITE
| [
"noreply@github.com"
] | solisoft.noreply@github.com |
599f18d64e39542aea44b60164892261473097d8 | 553d0e216df86f616e242f1f7c1a18df56b04397 | /Source/CSGO/NetworkChannel.h | abee2e06ca19d7d0d02cfa6cd4cbdb059c90393e | [
"MIT",
"LicenseRef-scancode-free-unknown"
] | permissive | ClaudiuHKS/Osiris | ed2fc849daee4f5f7a88660fd7440c5a19bd1d17 | 189b97b1874108e75335272bfef5a15c442c0d19 | refs/heads/master | 2023-03-16T14:12:16.199569 | 2023-01-04T21:28:40 | 2023-01-04T21:28:40 | 209,620,977 | 1 | 0 | MIT | 2019-09-19T18:18:40 | 2019-09-19T18:18:40 | null | UTF-8 | C++ | false | false | 309 | h | #pragma once
#include "Pad.h"
#include "VirtualMethod.h"
namespace csgo
{
struct NetworkChannelPOD {
PAD(44);
int chokedPackets;
};
class NetworkChannel : public VirtualCallableFromPOD<NetworkChannel, NetworkChannelPOD> {
public:
VIRTUAL_METHOD(float, getLatency, 9, (int flow), (flow))
};
}
| [
"danielkrupinski@outlook.com"
] | danielkrupinski@outlook.com |
b6c082617cb677ee2d380bbcf9039e0296be6010 | 8570aaf4c66fadb8aaaca8e7f3e7b37c70076f0a | /lcluster/lcluster/Cluster.h | 597162ec96110c4cfe9dcb984d813fb78e3e5553 | [] | no_license | laerad84/Analysis | 7d668f4d77a8f01110245a7cd0e1c38f9d6f22a0 | 26525a6467430354ff7ff4ad809e68964d116a08 | refs/heads/master | 2021-01-22T23:26:28.217804 | 2014-07-01T05:38:40 | 2014-07-01T05:38:40 | 4,693,150 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,887 | h | // -*- C++ -*-
//
// Cluster.h
// cluster container class ( imported from E391a library)
//
// Author: Kazufumi Ssato
// Created: Sun Nov 25 16:02 JST 2011
//
// $Id: Cluster.h,v 1.1 2011/11/25 16:02 sato Exp $
//
//
// $Log: Cluster.h,v $
//
//
#ifndef CLUSTER_H_INCLUDED
#define CLUSTER_H_INCLUDED
#include <iostream>
#include <list>
#include <vector>
#include <cstdlib>
#include "GsimPersistency/GsimMessage.h"
#include "CLHEP/Vector/ThreeVector.h"
class Cluster {
public:
// constructor
Cluster();
// destructor
~Cluster();
// operator
bool operator<( const Cluster& ) const;
bool operator==( const Cluster& ) const;
// extractor
int id() const { return m_id; }
int status() const { return m_status; }
double threshold() const{ return m_threshold; }
double e() const { return m_energy; }
const CLHEP::Hep3Vector& pos() const { return m_pos; }
double x() const { return m_pos.x(); }
double y() const { return m_pos.y(); }
double z() const { return m_pos.z(); }
double t() const { return m_time; }
double rms() const { return m_rms; }
// const std::list<int>& clusterIdList() const { return m_cidList; }
const std::vector<int>& clusterIdVec() const { return m_cidVec; }
const std::vector<double>& clusterEVec() const { return m_eVec; }
const std::vector<double>& clusterTimeVec() const { return m_timeVec; }
// method
void setId( int id ) { m_id = id; }
void setStatus(int stat){ m_status = stat; }
void setThreshold(double thre){ m_threshold = thre; }
void setEnergy( double energy ){m_energy = energy;}
void setPos( const CLHEP::Hep3Vector& pos ){m_pos = pos;}
void setPos( double x, double y, double z )
{ setPos(CLHEP::Hep3Vector( x,y,z )); }
void setTime( double time ){m_time = time;}
void setRms( double rms ) { m_rms = rms; }
void setClusterIdList( const std::list<int>& cidList ){m_cidList = cidList;}
void setClusterIdVec( const std::vector<int>& cidVec ){m_cidVec = cidVec;}
void setClusterEVec( const std::vector<double>& eVec ){m_eVec = eVec;}
void setClusterTimeVec( const std::vector<double>& timeVec ){m_timeVec = timeVec;}
// friend functions
friend std::ostream& operator<<( std::ostream& out, const Cluster& clus );
private:
int m_id;
int m_status;
double m_threshold;
double m_energy;
CLHEP::Hep3Vector m_pos;
double m_time;
double m_rms;
std::vector<int> m_cidVec;
std::vector<double> m_eVec;
std::vector<double> m_timeVec;
std::list<int> m_cidList; // <- for ClusterFinderKoShi
int compare( const Cluster& ) const;
};
//
#endif // CLUSTER_H_INCLUDED
| [
"laerad84@gmail.com"
] | laerad84@gmail.com |
713e5cfc2a8350e8b847cb91e3bdcff6c80a4d68 | 3611073adaa8c9736bbc1e158ed57108ef9d55f7 | /db/rocksdb/src/simple.cc | 0b9539b98bdfd9edbbb272b47e35efd43e03dce6 | [] | no_license | firejh/c-practice | e0ef4103f944d2eb7f6d237f6c85de6b77af710e | cd4d83321e023e79572ba36043065d407017047f | refs/heads/master | 2021-09-06T16:43:15.922540 | 2018-02-08T16:01:16 | 2018-02-08T16:01:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,359 | cc | /******************************************************
# DESC :
# AUTHOR : Alex Stocks
# VERSION : 1.0
# LICENCE : Apache License 2.0
# EMAIL : alexstocks@foxmail.com
# MOD : 2017-12-29 00:31
# FILE : simple.cc
******************************************************/
#include <stdint.h>
#include <unistd.h>
#include <cstdio>
#include <string>
#include <iostream>
#include <vector>
#include <chrono>
#include <thread>
#include "rocksdb/db.h"
#include "rocksdb/slice.h"
#include "rocksdb/table.h"
#include "rocksdb/options.h"
#include "rocksdb/compaction_filter.h"
#include "rocksdb/utilities/db_ttl.h"
#include "rocksdb/utilities/options_util.h"
using namespace std;
using namespace rocksdb;
DB* db = nullptr;
string kDBPath = "/tmp/rocksdb_data/";
const int32_t DB_TTL = 10;
enum RocksOp {
RO_WRITE = 1,
RO_DELETE = 2,
};
namespace {
// A dummy compaction filter
class DummyCompactionFilter : public CompactionFilter {
public:
virtual ~DummyCompactionFilter() {}
virtual bool Filter(int level, const Slice& key, const Slice& existing_value,
std::string* new_value, bool* value_changed) const {
return false;
}
virtual const char* Name() const { return "DummyCompactionFilter"; }
};
} // namespace
void err_exit(char *pre, char *err)
{
if (err) {
printf("%s:%s", pre, err);
if (db != nullptr) {
delete db;
}
_exit(1);
}
}
void err_exit(string pre, Status& s)
{
if (!s.ok()) {
printf("%s, err:%d-%d-%s\n", pre.data(), s.code(), s.subcode(), s.ToString().c_str());
if (db != nullptr) {
delete db;
}
_exit(1);
}
}
void put(DB* db, string key, int32_t value)
{
Status s = db->Put(WriteOptions(), key, Slice((char*)&value, sizeof(value)));
err_exit((char*)"DB::Put", s);
}
void batch_write(WriteBatch* db, RocksOp op, string key, int32_t value)
{
switch (op) {
case RO_WRITE: {
Status s = db->Put(key, Slice((char*)&value, sizeof(value)));
err_exit((char*)"DB::Put", s);
break;
}
case RO_DELETE: {
Status s = db->Delete(key);
err_exit((char*)"DB::Delete", s);
break;
}
}
}
int testDefaultCF()
{
Options options;
options.OptimizeLevelStyleCompaction();
options.IncreaseParallelism();
options.create_if_missing = true;
db = nullptr;
Status s = DB::Open(options, kDBPath, &db);
err_exit((char*)"DB::Open", s);
// Put key-value
cout << "----put------------" << endl;
WriteBatch batch;
batch_write(&batch, RO_WRITE, "/20171229/service0/attr0/0", 1234);
batch_write(&batch, RO_WRITE, "/20171228/service0/attr0/0", 989);
batch_write(&batch, RO_WRITE, "/20171227/service0/attr0/0", 4893949);
batch_write(&batch, RO_WRITE, "/20171226/service0/attr0/0", 83482384);
s = db->Write(WriteOptions(), &batch);
err_exit((char*)"DB::Write", s);
// get value
cout << "----get------------" << endl;
// string value;
// s = db->Get(ReadOptions(), "/20171226/service0/attr0/0", &value);
PinnableSlice value;
s = db->Get(ReadOptions(), db->DefaultColumnFamily(), "/20171226/service0/attr0/0", &value);
err_exit((char*)"DB::Get(\"/20171226/service0/attr0/0\")", s);
cout << *(int32_t*)(value.data()) << endl;
assert(*(int32_t*)(value.data()) == (int32_t)(83482384));
value.Reset();
// multi-get values
cout << "----multi-get -----" << endl;
vector<Status> statusArray;
vector<Slice> keyArray = {"/20171229/service0/attr0/0", "/20171226/service0/attr0/0"};
vector<string> valueArray;
statusArray = db->MultiGet(ReadOptions(), keyArray, &valueArray);
int idx = 0;
for (auto &s:statusArray) {
err_exit((char*)("MultiGet"), s);
cout << "key:" << keyArray[idx].data_ << ", value:" << *(int32_t*)(valueArray[idx].data()) << endl;
idx ++;
}
// for-range
cout << "----for-range -----" << endl;
Iterator* it = db->NewIterator(ReadOptions());
for (it->SeekToFirst(); it->Valid(); it->Next()) {
cout << "key:" << it->key().ToString() << ", value:" << *(int32_t*)(it->value().data()) << endl;
}
cout << "-reverse-for-range-" << endl;
for (it->SeekToLast(); it->Valid(); it->Prev()) {
cout << "key:" << it->key().ToString() << ", value:" << *(int32_t*)(it->value().data()) << endl;
}
// iterator
cout << "----iterator ------" << endl;
Slice sliceStart("/20171227");
string sliceEnd("/20171229");
for (it->Seek(sliceStart);
it->Valid() && it->key().ToString() < sliceEnd;
it->Next()) {
cout << "key:" << it->key().ToString() << ", value:" << *(int32_t*)(it->value().data()) << endl;
}
cout << "--reverse iterator-" << endl;
for (it->SeekForPrev(sliceEnd);
it->Valid() && it->key().ToString() > string(sliceStart.data_);
it->Prev()) {
cout << "key:" << it->key().ToString() << ", value:" << *(int32_t*)(it->value().data()) << endl;
}
// delete value
cout << "----delete---------" << endl;
// s = db->Delete(WriteOptions(), "/20171226/service0/attr0/0");
WriteBatch batch_delete;
batch_write(&batch_delete, RO_DELETE, "/20171226/service0/attr0/0", 0);
s = db->Write(WriteOptions(), &batch_delete);
err_exit((char*)"DB::Delete(\"/20171226/service0/attr0/0\")", s);
value.Reset();
// s = db->Get(ReadOptions(), "/20171226/service0/attr0/0", &value);
s = db->Get(ReadOptions(), db->DefaultColumnFamily(), "/20171226/service0/attr0/0", &value);
if (s.ok()) {
cout << "fail to delete key:" << "/20171226/service0/attr0/0" << endl;
}
delete db;
return 0;
}
void cf_batch_write(WriteBatch* batch, ColumnFamilyHandle* cf, RocksOp op, string key, int32_t value)
{
switch (op) {
case RO_WRITE: {
Status s = batch->Put(cf, key, Slice((char*)&value, sizeof(value)));
err_exit((char*)"Batch::Put", s);
break;
}
case RO_DELETE: {
Status s = batch->Delete(cf, key);
err_exit((char*)"Batch::Delete", s);
break;
}
}
}
int testColumnFamilies()
{
Options options;
options.OptimizeLevelStyleCompaction();
options.IncreaseParallelism();
options.create_if_missing = true;
ColumnFamilyOptions cf_options(options);
vector<string> column_family_names;
vector<ColumnFamilyDescriptor> descriptors;
vector<ColumnFamilyHandle*> handles;
string table = "test";
cout << "-create column family--" << endl;
Status s = DB::Open(options, kDBPath, &db);
err_exit((char*)"DB::Open", s);
// create column family
ColumnFamilyHandle* cf = NULL;
s = db->CreateColumnFamily(ColumnFamilyOptions(), table, &cf);
if (!s.ok()) {
printf("create table %s, err:%d-%d-%s\n", table.data(), s.code(), s.subcode(), s.ToString().c_str());
}
// close DB
delete cf;
cf = nullptr;
delete db;
db = nullptr;
// list column family
s = DB::ListColumnFamilies(options, kDBPath, &column_family_names);
// err_exit((char*)"DB::ListColumnFamilies", s);
for (auto name : column_family_names) {
cout << "column family: " << name << endl;
}
cout << "--open read only---" << endl;
// Open database
// open DB with two column families
descriptors.clear();
// have to open default column family
descriptors.push_back(ColumnFamilyDescriptor(kDefaultColumnFamilyName, ColumnFamilyOptions()));
// open the new one, too
descriptors.push_back(ColumnFamilyDescriptor(table, ColumnFamilyOptions()));
db = nullptr;
handles.clear();
s = DB::OpenForReadOnly(options, kDBPath, descriptors, &handles, &db);
err_exit((char*)"DB::OpenForReadOnly", s);
delete db;
cout << "----open-----------" << endl;
// Open database
// open DB with two column families
descriptors.clear();
// have to open default column family
descriptors.push_back(ColumnFamilyDescriptor(kDefaultColumnFamilyName, ColumnFamilyOptions()));
// open the new one, too
descriptors.push_back(ColumnFamilyDescriptor(table, ColumnFamilyOptions()));
db = nullptr;
handles.clear();
s = DB::Open(options, kDBPath, descriptors, &handles, &db);
err_exit((char*)"DB::Open", s);
// create column family
if (handles.size() > 0) {
for (auto &h:handles) {
if (h->GetName() == table) {
cf = h;
} else {
delete h;
}
}
}
if (!cf) {
s = db->CreateColumnFamily(ColumnFamilyOptions(), table, &cf);
err_exit((char*)"DB::CreateColumnFamily", s);
}
cout << "table name:" << cf->GetName() << endl;
// Put
cout << "----put------------" << endl;
string key = "/20180102/service0/attr0/720";
int value = 12345;
WriteBatch batch;
cf_batch_write(&batch, cf, RO_WRITE, key, value);
s = db->Write(WriteOptions(), &batch);
err_exit((char*)"DB::Write", s);
// Get
cout << "----get------------" << endl;
PinnableSlice ps;
cout << "hello0" << endl;
s = db->Get(ReadOptions(), cf, key, &ps);
cout << "hello1" << endl;
err_exit((char*)(("DB::Get(" + key + ")").data()), s);
cout << *(int32_t*)(ps.data()) << endl;
assert(*(int32_t*)(ps.data()) == (int32_t)(value));
ps.Reset();
// multi-get values
cout << "----multi-get -----" << endl;
vector<Status> statusArray;
vector<ColumnFamilyHandle*> cfArray = {cf};
vector<Slice> keyArray = {key};
vector<string> valueArray;
statusArray = db->MultiGet(ReadOptions(), cfArray, keyArray, &valueArray);
int idx = 0;
for (auto &s:statusArray) {
err_exit((char*)("MultiGet"), s);
cout << "key:" << keyArray[idx].data_ << ", value:" << *(int32_t*)(valueArray[idx].data()) << endl;
idx ++;
}
// for-range
cout << "----for-range -----" << endl;
Iterator* it = db->NewIterator(ReadOptions(), cf);
for (it->SeekToFirst(); it->Valid(); it->Next()) {
cout << "key:" << it->key().ToString() << ", value:" << *(int32_t*)(it->value().data()) << endl;
}
cout << "-reverse-for-range-" << endl;
for (it->SeekToLast(); it->Valid(); it->Prev()) {
cout << "key:" << it->key().ToString() << ", value:" << *(int32_t*)(it->value().data()) << endl;
}
// iterator
cout << "----iterator ------" << endl;
Slice sliceStart("/20171227");
string sliceEnd("/20181229");
for (it->Seek(sliceStart);
it->Valid() && it->key().ToString() < sliceEnd;
it->Next()) {
cout << "key:" << it->key().ToString() << ", value:" << *(int32_t*)(it->value().data()) << endl;
}
cout << "--reverse iterator-" << endl;
for (it->SeekForPrev(sliceEnd);
it->Valid() && it->key().ToString() > string(sliceStart.data_);
it->Prev()) {
cout << "key:" << it->key().ToString() << ", value:" << *(int32_t*)(it->value().data()) << endl;
}
// delete value
cout << "----delete---------" << endl;
// s = db->Delete(WriteOptions(), cf, key);
WriteBatch batch2;
cf_batch_write(&batch2, cf, RO_DELETE, key, 0);
s = db->Write(WriteOptions(), &batch2);
err_exit((char*)(("DB::Delete(" + key + ")").data()), s);
ps.Reset();
// s = db->Get(ReadOptions(), "/20171226/service0/attr0/0", &value);
s = db->Get(ReadOptions(), cf, key, &ps);
if (s.ok()) {
cout << "fail to delete key:" << key << endl;
}
// close column family
// db->DropColumnFamily(cf); // this api will delete all "test" column family's data
delete cf;
delete db;
// delete the DB
DestroyDB(kDBPath, Options());
return 0;
}
// rm -rf kDBPath before run this test
int testTTL()
{
Options options;
options.OptimizeLevelStyleCompaction();
options.IncreaseParallelism();
options.create_if_missing = true;
options.disable_auto_compactions = true;
ColumnFamilyOptions cf_options(options);
vector<string> column_family_names;
vector<ColumnFamilyDescriptor> descriptors;
vector<ColumnFamilyHandle*> handles;
string cfname = "test_cf";
vector<int32_t> TTL;
TTL.push_back(DB_TTL);
TTL.push_back(DB_TTL);
cout << "-create column family--" << endl;
DB* db = nullptr;
ColumnFamilyHandle* cf = nullptr;
Status s = DB::Open(options, kDBPath, &db);
err_exit((char*)"DB::Open", s);
s = db->CreateColumnFamily(ColumnFamilyOptions(), cfname, &cf);
assert(s.ok());
delete cf;
delete db;
descriptors.push_back(ColumnFamilyDescriptor(kDefaultColumnFamilyName, ColumnFamilyOptions()));
descriptors.push_back(ColumnFamilyDescriptor(cfname, ColumnFamilyOptions()));
rocksdb::DBWithTTL* ttlDB = nullptr;
s = DBWithTTL::Open(options, kDBPath, descriptors, &handles, &ttlDB, TTL, false);
err_exit((char*)"DB::Open", s);
db = ttlDB;
// create column family
// ColumnFamilyHandle* cf = NULL;
// s = db->CreateColumnFamily(ColumnFamilyOptions(), cfname, &cf);
// if (!s.ok()) {
// printf("create table %s, err:%d-%d-%s\n", cfname.data(), s.code(), s.subcode(), s.ToString().c_str());
// }
// Put
cout << "----put------------" << endl;
string key = "/20180102/service0/attr0/720";
int value = 12345;
s = db->Put(WriteOptions(), handles[1], key, Slice((char*)&value, sizeof(value)));
err_exit((char*)"DB::Put", s);
// Get
cout << "----get------------" << endl;
PinnableSlice ps;
s = db->Get(ReadOptions(), handles[1], key, &ps);
err_exit((char*)(("DB::Get(" + key + ")").data()), s);
cout << *(int32_t*)(ps.data()) << endl;
ps.Reset();
// Flush
FlushOptions flush_options;
flush_options.wait = true;
db->Flush(flush_options, handles[1]);
// Sleep
chrono::seconds dura(DB_TTL + 10);
this_thread::sleep_for(dura);
// Manual Compaction
// s = db->CompactFiles(rocksdb::CompactionOptions(), {kDBPath + "/000010.sst"}, 0);
// err_exit((char*)"DB::CompactFiles", s);
Slice sliceStart(key);
string end("/20181229");
Slice sliceEnd(end);
s = db->CompactRange(CompactRangeOptions(), handles[1], &sliceStart, &sliceEnd);
err_exit((char*)"DB::CompactRange", s);
// iterator
cout << "----iterator ------" << endl;
Iterator* it = db->NewIterator(ReadOptions(), handles[1]);
for (it->Seek(sliceStart);
it->Valid() && it->key().ToString() < end;
it->Next()) {
cout << "key:" << it->key().ToString() << ", value:" << *(int32_t*)(it->value().data()) << endl;
}
// Get
cout << "----get------------" << endl;
ps.Reset();
s = db->Get(ReadOptions(), handles[1], key, &ps);
err_exit((char*)(("DB::Get(" + key + ")").data()), s);
cout << *(int32_t*)(ps.data()) << endl;
ps.Reset();
// close DB
delete cf;
cf = nullptr;
delete db;
db = nullptr;
return 0;
}
int testBlockCache()
{
DBOptions db_opt;
db_opt.create_if_missing = true;
std::vector<ColumnFamilyDescriptor> cf_descs;
cf_descs.push_back({kDefaultColumnFamilyName, ColumnFamilyOptions()});
cf_descs.push_back({"new_cf", ColumnFamilyOptions()});
// initialize BlockBasedTableOptions
// auto cache = NewLRUCache(1 * 1024 * 1024 * 1024);
auto cache = NewLRUCache(1 * 1024);
BlockBasedTableOptions bbt_opts;
bbt_opts.block_size = 32 * 1024;
bbt_opts.block_cache = cache;
// initialize column families options
std::unique_ptr<CompactionFilter> compaction_filter;
compaction_filter.reset(new DummyCompactionFilter());
cf_descs[0].options.table_factory.reset(NewBlockBasedTableFactory(bbt_opts));
cf_descs[0].options.compaction_filter = compaction_filter.get();
cf_descs[1].options.table_factory.reset(NewBlockBasedTableFactory(bbt_opts));
// destroy and open DB
DB* db;
Status s = DestroyDB(kDBPath, Options(db_opt, cf_descs[0].options));
assert(s.ok());
s = DB::Open(Options(db_opt, cf_descs[0].options), kDBPath, &db);
assert(s.ok());
// Create column family, and rocksdb will persist the options.
ColumnFamilyHandle* cf;
s = db->CreateColumnFamily(ColumnFamilyOptions(), "new_cf", &cf);
assert(s.ok());
// close DB
delete cf;
delete db;
// In the following code, we will reopen the rocksdb instance using
// the options file stored in the db directory.
// Load the options file.
DBOptions loaded_db_opt;
std::vector<ColumnFamilyDescriptor> loaded_cf_descs;
s = LoadLatestOptions(kDBPath, Env::Default(), &loaded_db_opt, &loaded_cf_descs);
assert(s.ok());
assert(loaded_db_opt.create_if_missing == db_opt.create_if_missing);
// Initialize pointer options for each column family
for (size_t i = 0; i < loaded_cf_descs.size(); ++i) {
auto* loaded_bbt_opt = reinterpret_cast<BlockBasedTableOptions*>(
loaded_cf_descs[0].options.table_factory->GetOptions());
// Expect the same as BlockBasedTableOptions will be loaded form file.
assert(loaded_bbt_opt->block_size == bbt_opts.block_size);
// However, block_cache needs to be manually initialized as documented
// in rocksdb/utilities/options_util.h.
loaded_bbt_opt->block_cache = cache;
}
// In addition, as pointer options are initialized with default value,
// we need to properly initialized all the pointer options if non-defalut
// values are used before calling DB::Open().
assert(loaded_cf_descs[0].options.compaction_filter == nullptr);
loaded_cf_descs[0].options.compaction_filter = compaction_filter.get();
// reopen the db using the loaded options.
std::vector<ColumnFamilyHandle*> handles;
s = DB::Open(loaded_db_opt, kDBPath, loaded_cf_descs, &handles, &db);
assert(s.ok());
// close DB
for (auto* handle : handles) {
delete handle;
}
delete db;
return 0;
}
int main(int argc, char** argv)
{
// testDefaultCF();
// testColumnFamilies();
// testTTL();
testBlockCache();
return 0;
}
| [
"alexstocks@foxmail.com"
] | alexstocks@foxmail.com |
80e9723656c53ffc31bc43bdaa867e116a14d3e9 | 86798d4b8ccaa9ac4b66b3e86f87fec62df70180 | /DS & Algo Implementation/Dynamic Programming/DP on Trees/poj Fire.cpp | 26585cb91cc6468851d5a7bdabe9c4508e53719e | [] | no_license | sakiib/competitive-programming-code-library | 03675e4c9646bd0d65f08b146310abfd4b36f1c4 | e25d7f50932fb2659bbe3673daf846eb5e7c5428 | refs/heads/master | 2022-12-04T16:11:18.307005 | 2022-12-03T14:25:49 | 2022-12-03T14:25:49 | 208,120,580 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,139 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair <int,int> ii;
const int inf = 1e9;
const LL INF = 1e18;
const int N = 1e3 + 5;
int n;
int W[ N ] , D[ N ] , dist[ N ][ N ] , All[ N ] , dp[ N ][ N ];
vector < pair <int,int> > graph[ N ];
void reset( ) {
for( int i = 1; i < N; i++ ) graph[i].clear();
memset( dp , 0x3f3f3f3f , sizeof(dp) );
memset( All , 0x3f3f3f3f , sizeof(All) );
}
void dfs( int s , int p , int ss , int d ) {
dist[ss][s] = d;
for( int i = 0; i < graph[s].size(); i++ ) {
pair <int,int> P = graph[s][i];
if( P.first != p ) {
dfs( P.first , s , ss , d + P.second );
}
}
}
void dfsDP( int s , int p ) {
for( int i = 1; i <= n; i++ ) {
if( dist[s][i] <= D[s] ) dp[s][i] = W[i];
}
for( int i = 0; i < graph[s].size(); i++ ) {
pair <int,int> P = graph[s][i];
if( P.first == p ) continue;
dfsDP( P.first , s );
for( int j = 1; j <= n; j++ ) {
dp[s][j] += min( dp[P.first][j] - W[j] , All[P.first] );
}
}
for( int i = 1; i <= n; i++ ) All[s] = min( All[s] , dp[s][i] );
}
int main( int argc , char const *argv[] ) {
int t;
scanf("%d",&t);
for( int tc = 1; tc <= t; tc++ ) {
reset();
scanf("%d",&n);
for( int i = 1; i <= n; i++ ) scanf("%d",&W[i]);
for( int i = 1; i <= n; i++ ) scanf("%d",&D[i]);
for( int i = 1; i <= n-1; i++ ) {
int u , v , w;
scanf("%d %d %d",&u,&v,&w);
graph[u].push_back( make_pair(v,w) );
graph[v].push_back( make_pair(u,w) );
}
for( int i = 1; i <= n; i++ ) dfs( i , 0 , i , 0 );
dfsDP( 1 , 0 );
printf("%d\n",All[1]);
}
return 0;
}
| [
"noreply@github.com"
] | sakiib.noreply@github.com |
42b800171a8cf8ac51cd856acc863e9b96663f11 | 70c7cda5e769ac0aec001363a482bc24f50123b4 | /externals/thrust/system/cuda/detail/partition.h | 5dd9a8bca73e8e7a19a7a63a18cf8039a8f407f1 | [
"BSL-1.0",
"Apache-2.0",
"MIT"
] | permissive | Robadob/FLAMEGPU2_dev | a1509c73ffdec2d6bb1c978d0f936418e0892078 | 3e4106078f754ee90957519fa196a863fd257d1c | refs/heads/master | 2020-08-30T22:25:42.476365 | 2019-11-22T18:24:06 | 2019-11-25T11:33:59 | 218,506,894 | 0 | 0 | MIT | 2019-11-27T14:45:12 | 2019-10-30T10:59:22 | C++ | UTF-8 | C++ | false | false | 39,423 | h | /******************************************************************************
* Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the NVIDIA CORPORATION nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
#pragma once
#if THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC
#include <thrust/system/cuda/config.h>
#include <thrust/detail/cstdint.h>
#include <thrust/detail/temporary_array.h>
#include <thrust/system/cuda/detail/util.h>
#include <thrust/system/cuda/detail/reverse.h>
#include <thrust/system/cuda/detail/find.h>
#include <thrust/system/cuda/detail/uninitialized_copy.h>
#include <cub/device/device_partition.cuh>
#include <thrust/system/cuda/detail/core/agent_launcher.h>
#include <thrust/system/cuda/detail/par_to_seq.h>
#include <thrust/partition.h>
#include <thrust/pair.h>
#include <thrust/distance.h>
THRUST_BEGIN_NS
namespace cuda_cub {
namespace __partition {
template <int _BLOCK_THREADS,
int _ITEMS_PER_THREAD = 1,
int _MIN_BLOCKS = 1,
cub::BlockLoadAlgorithm _LOAD_ALGORITHM = cub::BLOCK_LOAD_DIRECT,
cub::CacheLoadModifier _LOAD_MODIFIER = cub::LOAD_LDG,
cub::BlockScanAlgorithm _SCAN_ALGORITHM = cub::BLOCK_SCAN_WARP_SCANS>
struct PtxPolicy
{
enum
{
BLOCK_THREADS = _BLOCK_THREADS,
ITEMS_PER_THREAD = _ITEMS_PER_THREAD,
MIN_BLOCKS = _MIN_BLOCKS,
ITEMS_PER_TILE = _BLOCK_THREADS * _ITEMS_PER_THREAD,
};
static const cub::BlockLoadAlgorithm LOAD_ALGORITHM = _LOAD_ALGORITHM;
static const cub::CacheLoadModifier LOAD_MODIFIER = _LOAD_MODIFIER;
static const cub::BlockScanAlgorithm SCAN_ALGORITHM = _SCAN_ALGORITHM;
}; // struct PtxPolicy
template<class, class>
struct Tuning;
template<class T>
struct Tuning<sm35, T>
{
const static int INPUT_SIZE = sizeof(T);
enum
{
NOMINAL_4B_ITEMS_PER_THREAD = 10,
ITEMS_PER_THREAD = CUB_MIN(NOMINAL_4B_ITEMS_PER_THREAD, CUB_MAX(1, (NOMINAL_4B_ITEMS_PER_THREAD * 4 / sizeof(T)))),
};
typedef PtxPolicy<128,
ITEMS_PER_THREAD,
1,
cub::BLOCK_LOAD_WARP_TRANSPOSE,
cub::LOAD_LDG,
cub::BLOCK_SCAN_WARP_SCANS>
type;
}; // Tuning<350>
template<class T>
struct Tuning<sm30, T>
{
const static int INPUT_SIZE = sizeof(T);
enum
{
NOMINAL_4B_ITEMS_PER_THREAD = 7,
ITEMS_PER_THREAD = CUB_MIN(NOMINAL_4B_ITEMS_PER_THREAD, CUB_MAX(3, (NOMINAL_4B_ITEMS_PER_THREAD * 4 / sizeof(T)))),
};
typedef PtxPolicy<128,
ITEMS_PER_THREAD,
1,
cub::BLOCK_LOAD_WARP_TRANSPOSE,
cub::LOAD_DEFAULT,
cub::BLOCK_SCAN_WARP_SCANS>
type;
}; // Tuning<300>
template<int T>
struct __tag{};
struct no_stencil_tag_ {};
struct single_output_tag_
{
template<class T>
THRUST_DEVICE_FUNCTION T const& operator=(T const& t) const { return t; }
};
typedef no_stencil_tag_* no_stencil_tag;
typedef single_output_tag_* single_output_tag;;
template <class ItemsIt,
class StencilIt,
class SelectedOutIt,
class RejectedOutIt,
class Predicate,
class Size,
class NumSelectedOutIt>
struct PartitionAgent
{
typedef typename iterator_traits<ItemsIt>::value_type item_type;
typedef typename iterator_traits<StencilIt>::value_type stencil_type;
typedef cub::ScanTileState<Size> ScanTileState;
template <class Arch>
struct PtxPlan : Tuning<Arch, item_type>::type
{
typedef Tuning<Arch,item_type> tuning;
typedef typename core::LoadIterator<PtxPlan, ItemsIt>::type ItemsLoadIt;
typedef typename core::LoadIterator<PtxPlan, StencilIt>::type StencilLoadIt;
typedef typename core::BlockLoad<PtxPlan, ItemsLoadIt>::type BlockLoadItems;
typedef typename core::BlockLoad<PtxPlan, StencilLoadIt>::type BlockLoadStencil;
typedef cub::TilePrefixCallbackOp<Size,
cub::Sum,
ScanTileState,
Arch::ver>
TilePrefixCallback;
typedef cub::BlockScan<Size,
PtxPlan::BLOCK_THREADS,
PtxPlan::SCAN_ALGORITHM,
1,
1,
Arch::ver>
BlockScan;
union TempStorage
{
struct
{
typename BlockScan::TempStorage scan;
typename TilePrefixCallback::TempStorage prefix;
};
typename BlockLoadItems::TempStorage load_items;
typename BlockLoadStencil::TempStorage load_stencil;
core::uninitialized_array<item_type, PtxPlan::ITEMS_PER_TILE> raw_exchange;
}; // union TempStorage
}; // struct PtxPlan
typedef typename core::specialize_plan_msvc10_war<PtxPlan>::type::type ptx_plan;
typedef typename ptx_plan::ItemsLoadIt ItemsLoadIt;
typedef typename ptx_plan::StencilLoadIt StencilLoadIt;
typedef typename ptx_plan::BlockLoadItems BlockLoadItems;
typedef typename ptx_plan::BlockLoadStencil BlockLoadStencil;
typedef typename ptx_plan::TilePrefixCallback TilePrefixCallback;
typedef typename ptx_plan::BlockScan BlockScan;
typedef typename ptx_plan::TempStorage TempStorage;
enum
{
SINGLE_OUTPUT = thrust::detail::is_same<RejectedOutIt, single_output_tag>::value,
USE_STENCIL = !thrust::detail::is_same<StencilIt, no_stencil_tag>::value,
BLOCK_THREADS = ptx_plan::BLOCK_THREADS,
ITEMS_PER_THREAD = ptx_plan::ITEMS_PER_THREAD,
ITEMS_PER_TILE = ptx_plan::ITEMS_PER_TILE
};
struct impl
{
//---------------------------------------------------------------------
// Per-thread fields
//---------------------------------------------------------------------
TempStorage & temp_storage;
ScanTileState &tile_state;
ItemsLoadIt items_glob;
StencilLoadIt stencil_glob;
SelectedOutIt selected_out_glob;
RejectedOutIt rejected_out_glob;
Predicate predicate;
Size num_items;
//---------------------------------------------------------------------
// Utilities
//---------------------------------------------------------------------
template <bool IS_LAST_TILE>
THRUST_DEVICE_FUNCTION void
scatter(item_type (&items)[ITEMS_PER_THREAD],
Size (&selection_flags)[ITEMS_PER_THREAD],
Size (&selection_indices)[ITEMS_PER_THREAD],
int num_tile_items,
int num_tile_selections,
Size num_selections_prefix,
Size num_rejected_prefix,
Size /*num_selections*/)
{
int tile_num_rejections = num_tile_items - num_tile_selections;
// Scatter items to shared memory (rejections first)
#pragma unroll
for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM)
{
int item_idx = (threadIdx.x * ITEMS_PER_THREAD) + ITEM;
int local_selection_idx = selection_indices[ITEM] - num_selections_prefix;
int local_rejection_idx = item_idx - local_selection_idx;
int local_scatter_offset = (selection_flags[ITEM])
? tile_num_rejections + local_selection_idx
: local_rejection_idx;
temp_storage.raw_exchange[local_scatter_offset] = items[ITEM];
}
core::sync_threadblock();
// Gather items from shared memory and scatter to global
#pragma unroll
for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM)
{
int item_idx = (ITEM * BLOCK_THREADS) + threadIdx.x;
int rejection_idx = item_idx;
int selection_idx = item_idx - tile_num_rejections;
Size scatter_offset = (item_idx < tile_num_rejections)
? num_items -
num_rejected_prefix - rejection_idx - 1
: num_selections_prefix + selection_idx;
item_type item = temp_storage.raw_exchange[item_idx];
if (!IS_LAST_TILE || (item_idx < num_tile_items))
{
if (SINGLE_OUTPUT || item_idx >= tile_num_rejections)
{
selected_out_glob[scatter_offset] = item;
}
else // if !SINGLE_OUTPUT, scatter rejected items separately
{
rejected_out_glob[num_items - scatter_offset - 1] = item;
}
}
}
} // func scatter
//------------------------------------------
// specialize predicate on different types
//------------------------------------------
enum ItemStencil
{
ITEM,
STENCIL
};
template <bool TAG, class T>
struct wrap_value
{
T const & x;
THRUST_DEVICE_FUNCTION wrap_value(T const &x) : x(x) {}
THRUST_DEVICE_FUNCTION T const &operator()() const { return x; };
}; // struct wrap_type
//------- item
THRUST_DEVICE_FUNCTION bool
predicate_wrapper(wrap_value<ITEM, item_type> const &x,
__tag<false /* USE_STENCIL */>)
{
return predicate(x());
}
THRUST_DEVICE_FUNCTION bool
predicate_wrapper(wrap_value<ITEM, item_type> const &,
__tag<true>)
{
return false;
}
//-------- stencil
template <class T>
THRUST_DEVICE_FUNCTION bool
predicate_wrapper(wrap_value<STENCIL, T> const &x,
__tag<true>)
{
return predicate(x());
}
THRUST_DEVICE_FUNCTION bool
predicate_wrapper(wrap_value<STENCIL, no_stencil_tag_> const &,
__tag<true>)
{
return false;
}
THRUST_DEVICE_FUNCTION bool
predicate_wrapper(wrap_value<STENCIL, stencil_type> const &,
__tag<false>)
{
return false;
}
template <bool IS_LAST_TILE, ItemStencil TYPE, class T>
THRUST_DEVICE_FUNCTION void
compute_selection_flags(int num_tile_items,
T (&values)[ITEMS_PER_THREAD],
Size (&selection_flags)[ITEMS_PER_THREAD])
{
#pragma unroll
for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM)
{
// Out-of-bounds items are selection_flags
selection_flags[ITEM] = 1;
if (!IS_LAST_TILE ||
(Size(threadIdx.x * ITEMS_PER_THREAD) + ITEM < num_tile_items))
{
selection_flags[ITEM] =
predicate_wrapper(wrap_value<TYPE, T>(values[ITEM]),
__tag<USE_STENCIL>());
}
}
}
//---------------------------------------------------------------------
// Tile processing
//---------------------------------------------------------------------
template <bool IS_LAST_TILE, bool IS_FIRST_TILE>
Size THRUST_DEVICE_FUNCTION
consume_tile_impl(int num_tile_items,
int tile_idx,
Size tile_base)
{
item_type items_loc[ITEMS_PER_THREAD];
Size selection_flags[ITEMS_PER_THREAD];
Size selection_idx[ITEMS_PER_THREAD];
if (IS_LAST_TILE)
{
BlockLoadItems(temp_storage.load_items)
.Load(items_glob + tile_base, items_loc, num_tile_items);
}
else
{
BlockLoadItems(temp_storage.load_items)
.Load(items_glob + tile_base, items_loc);
}
core::sync_threadblock();
if (USE_STENCIL)
{
stencil_type stencil_loc[ITEMS_PER_THREAD];
if (IS_LAST_TILE)
{
BlockLoadStencil(temp_storage.load_stencil)
.Load(stencil_glob + tile_base, stencil_loc, num_tile_items);
}
else
{
BlockLoadStencil(temp_storage.load_stencil)
.Load(stencil_glob + tile_base, stencil_loc);
}
compute_selection_flags<IS_LAST_TILE, STENCIL>(num_tile_items,
stencil_loc,
selection_flags);
}
else /* Use predicate on items rather then stencil */
{
compute_selection_flags<IS_LAST_TILE, ITEM>(num_tile_items,
items_loc,
selection_flags);
}
core::sync_threadblock();
Size num_tile_selections = 0;
Size num_selections = 0;
Size num_selections_prefix = 0;
Size num_rejected_prefix = 0;
if (IS_FIRST_TILE)
{
BlockScan(temp_storage.scan)
.ExclusiveSum(selection_flags,
selection_idx,
num_tile_selections);
if (threadIdx.x == 0)
{
// Update tile status if this is not the last tile
if (!IS_LAST_TILE)
tile_state.SetInclusive(0, num_tile_selections);
}
// Do not count any out-of-bounds selections
if (IS_LAST_TILE)
{
int num_discount = ITEMS_PER_TILE - num_tile_items;
num_tile_selections -= num_discount;
}
num_selections = num_tile_selections;
}
else
{
TilePrefixCallback prefix_cb(tile_state,
temp_storage.prefix,
cub::Sum(),
tile_idx);
BlockScan(temp_storage.scan)
.ExclusiveSum(selection_flags,
selection_idx,
prefix_cb);
num_selections = prefix_cb.GetInclusivePrefix();
num_tile_selections = prefix_cb.GetBlockAggregate();
num_selections_prefix = prefix_cb.GetExclusivePrefix();
num_rejected_prefix = tile_base - num_selections_prefix;
if (IS_LAST_TILE)
{
int num_discount = ITEMS_PER_TILE - num_tile_items;
num_tile_selections -= num_discount;
num_selections -= num_discount;
}
}
core::sync_threadblock();
scatter<IS_LAST_TILE>(items_loc,
selection_flags,
selection_idx,
num_tile_items,
num_tile_selections,
num_selections_prefix,
num_rejected_prefix,
num_selections);
return num_selections;
}
template <bool IS_LAST_TILE>
THRUST_DEVICE_FUNCTION Size
consume_tile(int num_tile_items,
int tile_idx,
Size tile_base)
{
if (tile_idx == 0)
{
return consume_tile_impl<IS_LAST_TILE, true>(num_tile_items,
tile_idx,
tile_base);
}
else
{
return consume_tile_impl<IS_LAST_TILE, false>(num_tile_items,
tile_idx,
tile_base);
}
}
//---------------------------------------------------------------------
// Constructor
//---------------------------------------------------------------------
THRUST_DEVICE_FUNCTION
impl(TempStorage & temp_storage_,
ScanTileState & tile_state_,
ItemsLoadIt items_glob_,
StencilLoadIt stencil_glob_,
SelectedOutIt selected_out_glob_,
RejectedOutIt rejected_out_glob_,
Predicate predicate_,
Size num_items_,
int num_tiles,
NumSelectedOutIt num_selected_out)
: temp_storage(temp_storage_),
tile_state(tile_state_),
items_glob(items_glob_),
stencil_glob(stencil_glob_),
selected_out_glob(selected_out_glob_),
rejected_out_glob(rejected_out_glob_),
predicate(predicate_),
num_items(num_items_)
{
int tile_idx = blockIdx.x;
Size tile_base = tile_idx * ITEMS_PER_TILE;
if (tile_idx < num_tiles - 1)
{
consume_tile<false>(ITEMS_PER_TILE,
tile_idx,
tile_base);
}
else
{
int num_remaining = static_cast<int>(num_items - tile_base);
Size num_selections = consume_tile<true>(num_remaining,
tile_idx,
tile_base);
if (threadIdx.x == 0)
{
*num_selected_out = num_selections;
}
}
} //
}; //struct impl
//---------------------------------------------------------------------
// Agent entry point
//---------------------------------------------------------------------
THRUST_AGENT_ENTRY(ItemsIt items,
StencilIt stencil,
SelectedOutIt selected_out,
RejectedOutIt rejected_out,
Predicate predicate,
Size num_items,
NumSelectedOutIt num_selected_out,
ScanTileState tile_state,
int num_tiles,
char * shmem)
{
TempStorage &storage = *reinterpret_cast<TempStorage *>(shmem);
impl(storage,
tile_state,
core::make_load_iterator(ptx_plan(), items),
core::make_load_iterator(ptx_plan(), stencil),
selected_out,
rejected_out,
predicate,
num_items,
num_tiles,
num_selected_out);
}
}; // struct PartitionAgent
template <class ScanTileState,
class NumSelectedIt,
class Size>
struct InitAgent
{
template <class Arch>
struct PtxPlan : PtxPolicy<128> {};
typedef core::specialize_plan<PtxPlan> ptx_plan;
//---------------------------------------------------------------------
// Agent entry point
//---------------------------------------------------------------------
THRUST_AGENT_ENTRY(ScanTileState tile_state,
Size num_tiles,
NumSelectedIt num_selected_out,
char * /*shmem*/)
{
tile_state.InitializeStatus(num_tiles);
if (blockIdx.x == 0 && threadIdx.x == 0)
*num_selected_out = 0;
}
}; // struct InitAgent
template <class ItemsIt,
class StencilIt,
class SelectedOutIt,
class RejectedOutIt,
class Predicate,
class Size,
class NumSelectedOutIt>
static cudaError_t THRUST_RUNTIME_FUNCTION
doit_step(void * d_temp_storage,
size_t & temp_storage_bytes,
ItemsIt items,
StencilIt stencil,
SelectedOutIt selected_out,
RejectedOutIt rejected_out,
Predicate predicate,
NumSelectedOutIt num_selected_out,
Size num_items,
cudaStream_t stream,
bool debug_sync)
{
using core::AgentLauncher;
using core::AgentPlan;
using core::get_agent_plan;
typedef AgentLauncher<
PartitionAgent<ItemsIt,
StencilIt,
SelectedOutIt,
RejectedOutIt,
Predicate,
Size,
NumSelectedOutIt> >
partition_agent;
typedef typename partition_agent::ScanTileState ScanTileState;
typedef AgentLauncher<
InitAgent<ScanTileState, NumSelectedOutIt, Size> >
init_agent;
using core::get_plan;
typename get_plan<init_agent>::type init_plan = init_agent::get_plan();
typename get_plan<partition_agent>::type partition_plan = partition_agent::get_plan(stream);
int tile_size = partition_plan.items_per_tile;
size_t num_tiles = (num_items + tile_size - 1) / tile_size;
size_t vshmem_storage = core::vshmem_size(partition_plan.shared_memory_size,
num_tiles);
cudaError_t status = cudaSuccess;
if (num_items == 0)
return status;
size_t allocation_sizes[2] = {0, vshmem_storage};
status = ScanTileState::AllocationSize(static_cast<int>(num_tiles), allocation_sizes[0]);
CUDA_CUB_RET_IF_FAIL(status);
void* allocations[2] = {NULL, NULL};
status = cub::AliasTemporaries(d_temp_storage,
temp_storage_bytes,
allocations,
allocation_sizes);
CUDA_CUB_RET_IF_FAIL(status);
if (d_temp_storage == NULL)
{
return status;
}
ScanTileState tile_status;
status = tile_status.Init(static_cast<int>(num_tiles), allocations[0], allocation_sizes[0]);
CUDA_CUB_RET_IF_FAIL(status);
init_agent ia(init_plan, num_tiles, stream, "partition::init_agent", debug_sync);
char *vshmem_ptr = vshmem_storage > 0 ? (char *)allocations[1] : NULL;
partition_agent pa(partition_plan, num_items, stream, vshmem_ptr, "partition::partition_agent", debug_sync);
ia.launch(tile_status, num_tiles, num_selected_out);
CUDA_CUB_RET_IF_FAIL(cudaPeekAtLastError());
pa.launch(items,
stencil,
selected_out,
rejected_out,
predicate,
num_items,
num_selected_out,
tile_status,
num_tiles);
CUDA_CUB_RET_IF_FAIL(cudaPeekAtLastError());
return status;
}
template <typename Derived,
typename InputIt,
typename StencilIt,
typename SelectedOutIt,
typename RejectedOutIt,
typename Predicate>
THRUST_RUNTIME_FUNCTION
pair<SelectedOutIt, RejectedOutIt>
partition(execution_policy<Derived>& policy,
InputIt first,
InputIt last,
StencilIt stencil,
SelectedOutIt selected_result,
RejectedOutIt rejected_result,
Predicate predicate)
{
typedef typename iterator_traits<InputIt>::difference_type size_type;
size_type num_items = static_cast<size_type>(thrust::distance(first, last));
size_t temp_storage_bytes = 0;
cudaStream_t stream = cuda_cub::stream(policy);
bool debug_sync = THRUST_DEBUG_SYNC_FLAG;
cudaError_t status;
status = doit_step(NULL,
temp_storage_bytes,
first,
stencil,
selected_result,
rejected_result,
predicate,
reinterpret_cast<size_type*>(NULL),
num_items,
stream,
debug_sync);
cuda_cub::throw_on_error(status, "partition failed on 1st step");
size_t allocation_sizes[2] = {sizeof(size_type), temp_storage_bytes};
void * allocations[2] = {NULL, NULL};
size_t storage_size = 0;
status = core::alias_storage(NULL,
storage_size,
allocations,
allocation_sizes);
cuda_cub::throw_on_error(status, "partition failed on 1st alias_storage");
// Allocate temporary storage.
thrust::detail::temporary_array<thrust::detail::uint8_t, Derived>
tmp(policy, storage_size);
void *ptr = static_cast<void*>(tmp.data().get());
status = core::alias_storage(ptr,
storage_size,
allocations,
allocation_sizes);
cuda_cub::throw_on_error(status, "partition failed on 2nd alias_storage");
size_type* d_num_selected_out
= thrust::detail::aligned_reinterpret_cast<size_type*>(allocations[0]);
status = doit_step(allocations[1],
temp_storage_bytes,
first,
stencil,
selected_result,
rejected_result,
predicate,
d_num_selected_out,
num_items,
stream,
debug_sync);
cuda_cub::throw_on_error(status, "partition failed on 2nd step");
status = cuda_cub::synchronize(policy);
cuda_cub::throw_on_error(status, "partition failed to synchronize");
size_type num_selected = 0;
if (num_items > 0)
{
num_selected = get_value(policy, d_num_selected_out);
}
return thrust::make_pair(selected_result + num_selected,
rejected_result + num_items - num_selected);
}
template <typename Derived,
typename Iterator,
typename StencilIt,
typename Predicate>
THRUST_RUNTIME_FUNCTION
Iterator partition_inplace(execution_policy<Derived>& policy,
Iterator first,
Iterator last,
StencilIt stencil,
Predicate predicate)
{
typedef typename iterator_traits<Iterator>::difference_type size_type;
typedef typename iterator_traits<Iterator>::value_type value_type;
size_type num_items = thrust::distance(first, last);
// Allocate temporary storage.
thrust::detail::temporary_array<value_type, Derived> tmp(policy, num_items);
cuda_cub::uninitialized_copy(policy, first, last, tmp.begin());
pair<Iterator, single_output_tag> result =
partition(policy,
tmp.data().get(),
tmp.data().get() + num_items,
stencil,
first,
single_output_tag(),
predicate);
size_type num_selected = result.first - first;
return first + num_selected;
}
} // namespace __partition
///// copy
//-------------------------
// Thrust API entry points
//-------------------------
__thrust_exec_check_disable__
template <class Derived,
class InputIt,
class StencilIt,
class SelectedOutIt,
class RejectedOutIt,
class Predicate>
pair<SelectedOutIt, RejectedOutIt> __host__ __device__
partition_copy(execution_policy<Derived> &policy,
InputIt first,
InputIt last,
StencilIt stencil,
SelectedOutIt selected_result,
RejectedOutIt rejected_result,
Predicate predicate)
{
pair<SelectedOutIt, RejectedOutIt> ret = thrust::make_pair(selected_result, rejected_result);
if (__THRUST_HAS_CUDART__)
{
ret = __partition::partition(policy,
first,
last,
stencil,
selected_result,
rejected_result,
predicate);
}
else
{
#if !__THRUST_HAS_CUDART__
ret = thrust::partition_copy(cvt_to_seq(derived_cast(policy)),
first,
last,
stencil,
selected_result,
rejected_result,
predicate);
#endif
}
return ret;
}
__thrust_exec_check_disable__
template <class Derived,
class InputIt,
class SelectedOutIt,
class RejectedOutIt,
class Predicate>
pair<SelectedOutIt, RejectedOutIt> __host__ __device__
partition_copy(execution_policy<Derived> &policy,
InputIt first,
InputIt last,
SelectedOutIt selected_result,
RejectedOutIt rejected_result,
Predicate predicate)
{
pair<SelectedOutIt, RejectedOutIt> ret = thrust::make_pair(selected_result, rejected_result);
if (__THRUST_HAS_CUDART__)
{
ret = __partition::partition(policy,
first,
last,
__partition::no_stencil_tag(),
selected_result,
rejected_result,
predicate);
}
else
{
#if !__THRUST_HAS_CUDART__
ret = thrust::partition_copy(cvt_to_seq(derived_cast(policy)),
first,
last,
selected_result,
rejected_result,
predicate);
#endif
}
return ret;
}
__thrust_exec_check_disable__
template <class Derived,
class InputIt,
class SelectedOutIt,
class RejectedOutIt,
class Predicate>
pair<SelectedOutIt, RejectedOutIt> __host__ __device__
stable_partition_copy(execution_policy<Derived> &policy,
InputIt first,
InputIt last,
SelectedOutIt selected_result,
RejectedOutIt rejected_result,
Predicate predicate)
{
pair<SelectedOutIt, RejectedOutIt> ret = thrust::make_pair(selected_result, rejected_result);
if (__THRUST_HAS_CUDART__)
{
ret = __partition::partition(policy,
first,
last,
__partition::no_stencil_tag(),
selected_result,
rejected_result,
predicate);
}
else
{
#if !__THRUST_HAS_CUDART__
ret = thrust::stable_partition_copy(cvt_to_seq(derived_cast(policy)),
first,
last,
selected_result,
rejected_result,
predicate);
#endif
}
return ret;
}
__thrust_exec_check_disable__
template <class Derived,
class InputIt,
class StencilIt,
class SelectedOutIt,
class RejectedOutIt,
class Predicate>
pair<SelectedOutIt, RejectedOutIt> __host__ __device__
stable_partition_copy(execution_policy<Derived> &policy,
InputIt first,
InputIt last,
StencilIt stencil,
SelectedOutIt selected_result,
RejectedOutIt rejected_result,
Predicate predicate)
{
pair<SelectedOutIt, RejectedOutIt> ret = thrust::make_pair(selected_result, rejected_result);
if (__THRUST_HAS_CUDART__)
{
ret = __partition::partition(policy,
first,
last,
stencil,
selected_result,
rejected_result,
predicate);
}
else
{
#if !__THRUST_HAS_CUDART__
ret = thrust::stable_partition_copy(cvt_to_seq(derived_cast(policy)),
first,
last,
stencil,
selected_result,
rejected_result,
predicate);
#endif
}
return ret;
}
/// inplace
__thrust_exec_check_disable__
template <class Derived,
class Iterator,
class StencilIt,
class Predicate>
Iterator __host__ __device__
partition(execution_policy<Derived> &policy,
Iterator first,
Iterator last,
StencilIt stencil,
Predicate predicate)
{
Iterator ret = first;
if (__THRUST_HAS_CUDART__)
{
ret = __partition::partition_inplace(policy, first, last, stencil, predicate);
}
else
{
#if !__THRUST_HAS_CUDART__
ret = thrust::partition(cvt_to_seq(derived_cast(policy)),
first,
last,
stencil,
predicate);
#endif
}
return ret;
}
__thrust_exec_check_disable__
template <class Derived,
class Iterator,
class Predicate>
Iterator __host__ __device__
partition(execution_policy<Derived> &policy,
Iterator first,
Iterator last,
Predicate predicate)
{
Iterator ret = first;
if (__THRUST_HAS_CUDART__)
{
ret = __partition::partition_inplace(policy,
first,
last,
__partition::no_stencil_tag(),
predicate);
}
else
{
#if !__THRUST_HAS_CUDART__
ret = thrust::partition(cvt_to_seq(derived_cast(policy)),
first,
last,
predicate);
#endif
}
return ret;
}
__thrust_exec_check_disable__
template <class Derived,
class Iterator,
class StencilIt,
class Predicate>
Iterator __host__ __device__
stable_partition(execution_policy<Derived> &policy,
Iterator first,
Iterator last,
StencilIt stencil,
Predicate predicate)
{
Iterator result = first;
if (__THRUST_HAS_CUDART__)
{
result = __partition::partition_inplace(policy,
first,
last,
stencil,
predicate);
// partition returns rejected values in reverese order
// so reverse the rejected elements to make it stable
cuda_cub::reverse(policy, result, last);
}
else
{
#if !__THRUST_HAS_CUDART__
result = thrust::stable_partition(cvt_to_seq(derived_cast(policy)),
first,
last,
stencil,
predicate);
#endif
}
return result;
}
__thrust_exec_check_disable__
template <class Derived,
class Iterator,
class Predicate>
Iterator __host__ __device__
stable_partition(execution_policy<Derived> &policy,
Iterator first,
Iterator last,
Predicate predicate)
{
Iterator result = first;
if (__THRUST_HAS_CUDART__)
{
result = __partition::partition_inplace(policy,
first,
last,
__partition::no_stencil_tag(),
predicate);
// partition returns rejected values in reverese order
// so reverse the rejected elements to make it stable
cuda_cub::reverse(policy, result, last);
}
else
{
#if !__THRUST_HAS_CUDART__
result = thrust::stable_partition(cvt_to_seq(derived_cast(policy)),
first,
last,
predicate);
#endif
}
return result;
}
template <class Derived,
class ItemsIt,
class Predicate>
bool __host__ __device__
is_partitioned(execution_policy<Derived> &policy,
ItemsIt first,
ItemsIt last,
Predicate predicate)
{
ItemsIt boundary = cuda_cub::find_if_not(policy, first, last, predicate);
ItemsIt end = cuda_cub::find_if(policy,boundary,last,predicate);
return end == last;
}
} // namespace cuda_cub
THRUST_END_NS
#endif
| [
"p.richmond@sheffield.ac.uk"
] | p.richmond@sheffield.ac.uk |
2add73e180461126874ceaf47ca640a9871c3000 | d6face59a153b062f1a86b75fc377fdb5f5a52d4 | /src/out/linux-x64x11_devel/gen/bindings/browser/source/cobalt/h5vcc/v8c_h5vcc_deep_link_event_target.h | f99b89fa0f6c71fc1b75f775ec609dd07ab7f35b | [
"BSD-3-Clause"
] | permissive | blockspacer/cobalt-clone-28052019 | 27fd44e64104e84a4a72d67ceaa8bafcfa72b4a8 | b94e4f78f0ba877fc15310648c72c9c4df8b0ae2 | refs/heads/master | 2022-10-26T04:35:33.702874 | 2019-05-29T11:07:12 | 2019-05-29T11:54:58 | 188,976,123 | 0 | 2 | null | 2022-10-03T12:37:17 | 2019-05-28T07:22:56 | null | UTF-8 | C++ | false | false | 1,628 | h |
// Copyright 2019 The Cobalt Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// clang-format off
// This file has been auto-generated by bindings/code_generator_cobalt.py. DO NOT MODIFY!
// Auto-generated from template: bindings/v8c/templates/interface.h.template
#ifndef V8cH5vccDeepLinkEventTarget_h
#define V8cH5vccDeepLinkEventTarget_h
#include "base/containers/hash_tables.h"
#include "base/lazy_instance.h"
#include "base/memory/ref_counted.h"
#include "base/threading/thread_checker.h"
#include "cobalt/base/polymorphic_downcast.h"
#include "cobalt/script/wrappable.h"
#include "cobalt/h5vcc/h5vcc_deep_link_event_target.h"
#include "cobalt/script/v8c/v8c_global_environment.h"
#include "v8/include/v8.h"
namespace cobalt {
namespace h5vcc {
class V8cH5vccDeepLinkEventTarget {
public:
static v8::Local<v8::Object> CreateWrapper(v8::Isolate* isolate, const scoped_refptr<script::Wrappable>& wrappable);
static v8::Local<v8::FunctionTemplate> GetTemplate(v8::Isolate* isolate);
};
} // namespace h5vcc
} // namespace cobalt
#endif // V8cH5vccDeepLinkEventTarget_h
| [
"trofimov_d_a@magnit.ru"
] | trofimov_d_a@magnit.ru |
be39afe2c12a6c530fa1cd4d748f7e63e10d55b2 | 5251c97dca338de263d75f987df4db3774e820fa | /C++/include/MNRLNetwork.hpp | d430d1429cb25710614f461b777ad46b48375514 | [
"BSD-3-Clause"
] | permissive | jackwadden/mnrl | 52da2517eaba0ffb3ab5fe23bafb592e4e1b9bd7 | 23a8bf8164e381686f74299b5650bb65010cf92b | refs/heads/master | 2023-05-26T22:55:39.871613 | 2017-08-04T16:04:34 | 2017-08-04T16:04:34 | 99,261,487 | 0 | 0 | null | 2017-08-03T18:06:18 | 2017-08-03T18:06:18 | null | UTF-8 | C++ | false | false | 4,559 | hpp | // Kevin Angstadt
// angstadt {at} virginia.edu
//
// MNRLNetwork Object
#ifndef MNRLNETWORK_HPP
#define MNRLNETWORK_HPP
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <fstream>
#include "MNRLDefs.hpp"
#include "MNRLError.hpp"
#include "MapIterator.hpp"
namespace MNRL {
class MNRLNode;
class MNRLState;
class MNRLHState;
class MNRLUpCounter;
class MNRLBoolean;
class MNRLNetwork {
public:
MNRLNetwork(std::string id);
virtual ~MNRLNetwork();
virtual void exportToFile(std::string filename);
MapIterator<std::map<std::string,std::shared_ptr<MNRLNode>>> getNodeIterator();
std::map<std::string,std::shared_ptr<MNRLNode>> getNodes();
std::shared_ptr<MNRLNode> getNodeById(std::string id);
std::shared_ptr<MNRLNode> addNode(std::shared_ptr<MNRLNode> theNode);
std::shared_ptr<MNRLState> addState(
std::shared_ptr<std::vector<std::pair<std::string,std::string>>> outputSymbols,
MNRLDefs::EnableType enable,
std::string id,
bool report,
int reportId,
bool latched,
std::shared_ptr<std::map<std::string,std::string>> attributes
);
std::shared_ptr<MNRLState> addState(
std::shared_ptr<std::vector<std::pair<std::string,std::string>>> outputSymbols,
MNRLDefs::EnableType enable,
std::string id,
bool report,
int reportId,
bool latched
);
std::shared_ptr<MNRLHState> addHState(
std::string symbols,
MNRLDefs::EnableType enable,
std::string id,
bool report,
int reportId,
bool latched,
std::shared_ptr<std::map<std::string,std::string>> attributes
);
std::shared_ptr<MNRLHState> addHState(
std::string symbols,
MNRLDefs::EnableType enable,
std::string id,
bool report,
std::string reportId,
bool latched,
std::shared_ptr<std::map<std::string,std::string>> attributes
);
std::shared_ptr<MNRLHState> addHState(
std::string symbols,
MNRLDefs::EnableType enable,
std::string id,
bool report,
bool latched,
std::shared_ptr<std::map<std::string,std::string>> attributes
);
std::shared_ptr<MNRLHState> addHState(
std::string symbols,
MNRLDefs::EnableType enable,
std::string id,
bool report,
int reportId,
bool latched
);
std::shared_ptr<MNRLHState> addHState(
std::string symbols,
MNRLDefs::EnableType enable,
std::string id,
bool report,
std::string reportId,
bool latched
);
std::shared_ptr<MNRLHState> addHState(
std::string symbols,
MNRLDefs::EnableType enable,
std::string id,
bool report,
bool latched
);
std::shared_ptr<MNRLUpCounter> addUpCounter(
int threshold,
MNRLDefs::CounterMode mode,
std::string id,
bool report,
int reportId,
std::shared_ptr<std::map<std::string,std::string>> attributes
);
std::shared_ptr<MNRLUpCounter> addUpCounter(
int threshold,
MNRLDefs::CounterMode mode,
std::string id,
bool report,
int reportId
);
std::shared_ptr<MNRLBoolean> addBoolean(
MNRLDefs::BooleanMode booleanType,
MNRLDefs::EnableType enable,
std::string id,
bool report,
int reportId,
std::shared_ptr<std::map<std::string,std::string>> attributes
);
std::shared_ptr<MNRLBoolean> addBoolean(
MNRLDefs::BooleanMode booleanType,
MNRLDefs::EnableType enable,
std::string id,
bool report,
int reportId
);
void addConnection(std::string src, std::string src_port, std::string dest, std::string dest_port);
void removeConnection(std::string src, std::string src_port, std::string dest, std::string dest_port);
std::string getId();
protected:
std::string id;
std::map <std::string,std::shared_ptr<MNRLNode>> nodes;
unsigned long nodes_added;
std::string getUniqueNodeId(std::string id);
};
}
#endif
| [
"kaa2nx@virginia.edu"
] | kaa2nx@virginia.edu |
7c5da16ba0d57e6f9322c2e6f627e92702cba615 | 4b154e683c575081533db5af1941ea66dc6dc9bf | /gazebo/physics/bullet/BulletHinge2Joint.hh | f1f8adf2fcdc93575f0870a785accc2a4480d7be | [
"Apache-2.0"
] | permissive | jonbinney/gazebo_ros_wrapper | 60e8ce882462ec43a3320ef1fd4f720618eb856a | 1ee65727c79c6838cc940b0fe1a190b8e0b53e3b | refs/heads/indigo-devel | 2021-01-22T21:13:42.477373 | 2014-06-09T22:12:07 | 2014-06-09T22:12:07 | 20,611,038 | 1 | 0 | null | 2014-06-09T22:12:07 | 2014-06-08T06:30:47 | C++ | UTF-8 | C++ | false | false | 3,492 | hh | /*
* Copyright (C) 2012-2014 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/* Desc: A hinge joint with 2 degrees of freedom
* Author: Nate Koenig, Andrew Howard
* Date: 21 May 2003
*/
#ifndef _BULLETHINGE2JOINT_HH_
#define _BULLETHINGE2JOINT_HH_
#include "gazebo/math/Angle.hh"
#include "gazebo/math/Vector3.hh"
#include "gazebo/physics/Hinge2Joint.hh"
#include "gazebo/physics/bullet/BulletJoint.hh"
#include "gazebo/physics/bullet/BulletPhysics.hh"
class btHinge2Constraint;
namespace gazebo
{
namespace physics
{
/// \ingroup gazebo_physics
/// \addtogroup gazebo_physics_bullet Bullet Physics
/// \{
/// \brief A two axis hinge joint
class BulletHinge2Joint : public Hinge2Joint<BulletJoint>
{
/// \brief Constructor
public: BulletHinge2Joint(btDynamicsWorld *world, BasePtr _parent);
/// \brief Destructor
public: virtual ~BulletHinge2Joint();
// Documentation inherited.
protected: virtual void Load(sdf::ElementPtr _sdf);
// Documentation inherited.
public: virtual void Init();
/// \brief Get anchor point
public: virtual math::Vector3 GetAnchor(int _index) const;
/// \brief Set the first axis of rotation
public: virtual void SetAxis(int _index, const math::Vector3 &_axis);
/// \brief Get first axis of rotation
public: virtual math::Vector3 GetAxis(int _index) const;
/// \brief Get angle of rotation about first axis
public: math::Angle GetAngle(int _index) const;
/// \brief Get rate of rotation about first axis
public: double GetVelocity(int _index) const;
/// \brief Set the velocity of an axis(index).
public: virtual void SetVelocity(int _index, double _angle);
/// \brief Set the max allowed force of an axis(index).
public: virtual void SetMaxForce(int _index, double _t);
/// \brief Get the max allowed force of an axis(index).
public: virtual double GetMaxForce(int _index);
/// \brief Set the high stop of an axis(index).
public: virtual void SetHighStop(int _index, const math::Angle &_angle);
/// \brief Set the low stop of an axis(index).
public: virtual void SetLowStop(int _index, const math::Angle &_angle);
/// \brief Get the high stop of an axis(index).
public: virtual math::Angle GetHighStop(int _index);
/// \brief Get the low stop of an axis(index).
public: virtual math::Angle GetLowStop(int _index);
/// \brief Get the axis of rotation
public: virtual math::Vector3 GetGlobalAxis(int _index) const;
/// \brief Get the angle of rotation
public: virtual math::Angle GetAngleImpl(int _index) const;
/// \brief Set the torque
protected: virtual void SetForceImpl(int _index, double _torque);
/// \brief Pointer to bullet hinge2 constraint
private: btHinge2Constraint *bulletHinge2;
};
/// \}
}
}
#endif
| [
"jon.binney@gmail.com"
] | jon.binney@gmail.com |
4b2e92c4f8629c87c6662b115175b01043c77d03 | 76d79f3dcea37e32dd9234e245d41a12b76cc1ef | /TASS/Inc/Plugin/PluginLoader.h | dfa689a2bf50613d9148a30a4c7d15a6163e0d84 | [] | no_license | YuriiBerehuliak/TASS | 5013dc4fb9f20d0aa98774c090bc2fa932622b6d | bc5d75cf57dadca46e92c75b8b21d8f084d86dfd | refs/heads/master | 2021-08-31T16:06:39.842114 | 2017-12-22T01:16:13 | 2017-12-22T01:16:13 | 111,031,403 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 274 | h | #ifndef _LIBRARY_LOADER_
#define _LIBRARY_LOADER_
#include "PluginInfo.h"
#include "string"
class PluginLoader
{
public:
static PluginInfo* loadPlugin( const char * path);
static void unloadPlugin(PluginInfo* plInfo);
};
#endif /* _LIBRARY_LOADER_ */
| [
"noreply@github.com"
] | YuriiBerehuliak.noreply@github.com |
7d1c7a32672e74fef63f838b8a08eec7bdda917f | bd36ae032ff4ee898964a735158d2d6ff7880a6e | /main/music/MIDIPlayer.h | 7b36e2b9be2fac1933c1e088a3b5f8457bc63fa2 | [] | no_license | RandyParedis/autoplay | c377ad07e64320113483a478cefd77186ecca1a8 | fa5a5a742b122ecb46c8d1608296f0b8dfd78840 | refs/heads/master | 2020-03-30T13:29:02.898049 | 2019-01-25T16:24:23 | 2019-01-25T16:24:23 | 151,274,363 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,779 | h | /*
* This 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 3 of the License, or
* any later version.
* The software 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 the software. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2018, Randy Paredis
*
* Created on 27/10/2018
*/
#ifndef AUTOPLAY_MIDIPLAYER_H
#define AUTOPLAY_MIDIPLAYER_H
#include "../util/Config.h"
#include "Score.h"
#include <memory>
namespace autoplay {
namespace music {
/**
* The MIDIPlayer class makes use of the RtMidi library, which allows for output
* ports to be detected and
* sound to be played.
*
* @note This class is a singleton class, e.g. it can/should only be
* instantiated once!
*
* @note It is possible some static is generated when first playing the
* sound.
* Also, sometimes the sound may not be played at all.
*/
class MIDIPlayer
{
public:
/**
* Deleted copy constructor
*/
MIDIPlayer(const MIDIPlayer&) = delete;
/**
* Deleted copy assignment
*/
MIDIPlayer& operator=(const MIDIPlayer&) = delete;
public:
/**
* Gets the instance of the MIDIPlayer in a thread-safe way.
* @return The singleton instance.
*/
static std::shared_ptr<MIDIPlayer> instance();
/**
* Log all output port information.
* @param config The Config of the system
*
* @note The implementation of this function is based upon the midiprobe file from RtMidi,
* created by Gary Scavone, 2003-2012.
*/
void probe(const util::Config& config) const;
/**
* Play a certain Score
* @param score The Score to play
* @param config The Config of the system
*/
void play(const Score& score, const util::Config& config) const;
private:
/**
* The default constructor is private, which allows this class to be
* instantiated only once.
*/
MIDIPlayer() = default;
};
}
}
#endif // AUTOPLAY_MIDIPLAYER_H
| [
"randy.paredis@student.uantwerpen.be"
] | randy.paredis@student.uantwerpen.be |
949404c346850ed8b8d914554377a60517da57b6 | a9e923353fac938e7ad83b05ae1fa7717c240343 | /nofx/nofx_ofStyle/nofx_dependencies.cc | 3eeff231f39455fbdb5135843d3958dcfefc8e62 | [
"MIT"
] | permissive | 3p3r/nofx | f7dfc5cc8d283aa1e4e9cf53068c1016a99b30c1 | 7abc9da3d4fc0f5b72c6b3d591a08cf44d00277e | refs/heads/master | 2021-05-30T07:49:50.985812 | 2015-07-13T17:35:14 | 2015-07-13T17:35:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 583 | cc | #include "nofx_dependencies.h"
v8::Persistent<v8::Function> DEP_ofColor;
namespace nofx
{
namespace ClassWrappers
{
NAN_METHOD(nofx_dependencies)
{
if (args.Length() != 1)
{
NanThrowTypeError("ofStyle module has dependencies. Please pass the right dependencies first.");
}
NanAssignPersistent(DEP_ofColor, v8::Handle<v8::Function>::Cast(
args[0]->ToObject()->Get(NanNew("ofColor"))));
NanReturnValue(args.This());
} // !nofx_dependencies
} // !namespace OfMatrix4x4
} // !namespace nofx | [
"sepehr.laal@gmail.com"
] | sepehr.laal@gmail.com |
fb604ac64aa3269e01fb3884592f0bab2adc49fb | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/printscan/wia/drivers/video/filter/stillf.cpp | 9baadcffb097dad107ec1020329f27ec53a10d91 | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 19,547 | cpp | /*****************************************************************************
*
* (C) COPYRIGHT MICROSOFT CORPORATION, 1998-2000
*
* TITLE: stillf.cpp
*
* VERSION: 1.1
*
* AUTHOR: WilliamH (created)
* RickTu
*
* DATE: 9/7/98
*
* DESCRIPTION: This module implements video stream capture filter.
* It implements CStillFilter objects.
* implements IID_IStillGraph interface provided for the caller
*
*****************************************************************************/
#include <precomp.h>
#pragma hdrstop
HINSTANCE g_hInstance;
extern "C" BOOL WINAPI DllEntryPoint(HINSTANCE hInstance, ULONG ulReason, LPVOID pv);
/*****************************************************************************
DllMain
<Notes>
*****************************************************************************/
BOOL
DllMain(HINSTANCE hInstance,
DWORD dwReason,
LPVOID lpReserved)
{
switch (dwReason)
{
case DLL_PROCESS_ATTACH:
{
//
// Init Debug subsystem
//
DBG_INIT(hInstance);
//
// Requires '{' and '}' since DBG_FN is an object with a
// constructor and a destructor.
//
DBG_FN("DllMain - ProcessAttach");
//
// We do not need thread attach/detach calls
//
DisableThreadLibraryCalls(hInstance);
//
// Record what instance we are
//
g_hInstance = hInstance;
}
break;
case DLL_PROCESS_DETACH:
{
//
// Requires '{' and '}' since DBG_FN is an object with a
// constructor and a destructor.
//
DBG_FN("DllMain - ProcessDetach");
}
break;
}
return DllEntryPoint(hInstance, dwReason, lpReserved);
}
///////////////////////////////
// sudPinTypes
//
// template definitions for CClassFactorySample
//
const AMOVIESETUP_MEDIATYPE sudPinTypes =
{
&MEDIATYPE_Video, // major media type GUID
&MEDIASUBTYPE_NULL // subtype GUID
};
///////////////////////////////
// psudPins
//
const AMOVIESETUP_PIN psudPins[] =
{
{
// CStillInputPin
L"Input", // pin name
FALSE, // not rendered
FALSE, // not output pin
FALSE, // not allow none
FALSE, // not allow many
&CLSID_NULL, // connect to any filter
L"Output", // connect to output pin
1, // one media type
&sudPinTypes // the media type
},
{
// CStillInputPin
L"Output", // pin name
FALSE, // not rendered
TRUE, // not output pin
FALSE, // not allow none
FALSE, // not allow many
&CLSID_NULL, // connect to any filter
L"Input", // connect to input pin
1, // one media type
&sudPinTypes // the media type
}
};
///////////////////////////////
// sudStillFilter
//
const AMOVIESETUP_FILTER sudStillFilter =
{
&CLSID_STILL_FILTER, // filter clsid
L"WIA Stream Snapshot Filter", // filter name
MERIT_DO_NOT_USE, //
2, // two pins
psudPins, // our pins
};
///////////////////////////////
// g_Templates
//
CFactoryTemplate g_Templates[1] =
{
{
L"WIA Stream Snapshot Filter", // filter name
&CLSID_STILL_FILTER, // filter clsid
CStillFilter::CreateInstance, // API used to create filter instances
NULL, // no init function provided.
&sudStillFilter // the filter itself
},
};
int g_cTemplates = sizeof(g_Templates) / sizeof(g_Templates[0]);
/*****************************************************************************
DllRegisterServer
Used to register the classes provided in this dll.
*****************************************************************************/
STDAPI DllRegisterServer()
{
return AMovieDllRegisterServer2(TRUE);
}
/*****************************************************************************
DllUnregisterServer
Used to unregister classes provided by this dll.
*****************************************************************************/
STDAPI
DllUnregisterServer()
{
return AMovieDllRegisterServer2(FALSE);
}
/*****************************************************************************
CStillFilter::CreateInstance
CreateInstance API to create CStillFilter instances
*****************************************************************************/
CUnknown* WINAPI CStillFilter::CreateInstance(LPUNKNOWN pUnk,
HRESULT *phr )
{
return new CStillFilter(TEXT("Stream Snapshot Filter"), pUnk, phr );
}
#ifdef DEBUG
/*****************************************************************************
DisplayMediaType
<Notes>
*****************************************************************************/
void DisplayMediaType(const CMediaType *pmt)
{
//
// Dump the GUID types and a short description
//
DBG_TRC(("<--- CMediaType 0x%x --->",pmt));
DBG_PRT(("Major type == %S",
GuidNames[*pmt->Type()]));
DBG_PRT(("Subtype == %S (%S)",
GuidNames[*pmt->Subtype()],GetSubtypeName(pmt->Subtype())));
DBG_PRT(("Format size == %d",pmt->cbFormat));
DBG_PRT(("Sample size == %d",pmt->GetSampleSize()));
//
// Dump the generic media types
//
if (pmt->IsFixedSize())
{
DBG_PRT(("==> This media type IS a fixed size sample"));
}
else
{
DBG_PRT(("==> This media type IS NOT a fixed size sample >"));
}
if (pmt->IsTemporalCompressed())
{
DBG_PRT(("==> This media type IS temporally compressed"));
}
else
{
DBG_PRT(("==> This media type IS NOT temporally compressed"));
}
}
#endif
/*****************************************************************************
DefaultGetBitsCallback
<Notes>
*****************************************************************************/
void DefaultGetBitsCallback(int Count,
LPARAM lParam)
{
SetEvent((HANDLE)lParam);
}
/*****************************************************************************
CStillFilter constructor
<Notes>
*****************************************************************************/
CStillFilter::CStillFilter(TCHAR *pObjName,
LPUNKNOWN pUnk,
HRESULT *phr) :
m_pInputPin(NULL),
m_pOutputPin(NULL),
m_pbmi(NULL),
m_pBits(NULL),
m_BitsSize(0),
m_bmiSize(0),
m_pCallback(NULL),
CBaseFilter(pObjName, pUnk, &m_Lock, CLSID_STILL_FILTER)
{
DBG_FN("CStillFilter::CStillFilter");
// create our input and output pin
m_pInputPin = new CStillInputPin(TEXT("WIA Still Input Pin"),
this,
phr,
L"Input");
if (!m_pInputPin)
{
DBG_ERR(("Unable to create new CStillInputPin!"));
*phr = E_OUTOFMEMORY;
return;
}
m_pOutputPin = new CStillOutputPin(TEXT("WIA Still Output Pin"),
this,
phr,
L"Output");
if (!m_pOutputPin)
{
DBG_ERR(("Unable to create new CStillOutputPin!"));
*phr = E_OUTOFMEMORY;
return;
}
}
/*****************************************************************************
CStillFilter desctructor
<Notes>
*****************************************************************************/
CStillFilter::~CStillFilter()
{
DBG_FN("CStillFilter::~CStillFilter");
if (m_pInputPin)
{
delete m_pInputPin;
m_pInputPin = NULL;
}
if (m_pOutputPin)
{
if (m_pOutputPin->m_pMediaUnk)
{
m_pOutputPin->m_pMediaUnk->Release();
m_pOutputPin->m_pMediaUnk = NULL;
}
delete m_pOutputPin;
m_pOutputPin = NULL;
}
if (m_pbmi)
{
delete [] m_pbmi;
m_pbmi = NULL;
}
if (m_pBits)
{
delete [] m_pBits;
m_pBits = NULL;
}
}
/*****************************************************************************
CStillFilter::NonDelegatingQueryInterface
Add our logic to the base class QI.
*****************************************************************************/
STDMETHODIMP
CStillFilter::NonDelegatingQueryInterface(REFIID riid,
void **ppv)
{
DBG_FN("CStillFilter::NonDelegatingQueryInterface");
ASSERT(this!=NULL);
ASSERT(ppv!=NULL);
HRESULT hr;
if (!ppv)
{
hr = E_INVALIDARG;
}
else if (riid == IID_IStillSnapshot)
{
hr = GetInterface((IStillSnapshot *)this, ppv);
}
else
{
hr = CBaseFilter::NonDelegatingQueryInterface(riid, ppv);
}
return hr;
}
/*****************************************************************************
CStillFilter::GetPinCount
<Notes>
*****************************************************************************/
int
CStillFilter::GetPinCount()
{
return 2; // input & output
}
/*****************************************************************************
CStillFilter::GetPin
<Notes>
*****************************************************************************/
CBasePin*
CStillFilter::GetPin( int n )
{
ASSERT(this!=NULL);
if (0 == n)
{
ASSERT(m_pInputPin!=NULL);
return (CBasePin *)m_pInputPin;
}
else if (1 == n)
{
ASSERT(m_pOutputPin!=NULL);
return (CBasePin *)m_pOutputPin;
}
return NULL;
}
/*****************************************************************************
CStillFilter::Snapshot
<Notes>
*****************************************************************************/
STDMETHODIMP
CStillFilter::Snapshot( ULONG TimeStamp )
{
DBG_FN("CStillFilter::Snapshot");
ASSERT(this!=NULL);
ASSERT(m_pInputPin!=NULL);
HRESULT hr = E_POINTER;
if (m_pInputPin)
{
hr = m_pInputPin->Snapshot(TimeStamp);
}
CHECK_S_OK(hr);
return hr;
}
/*****************************************************************************
CStillFilter::GetBitsSize
<Notes>
*****************************************************************************/
STDMETHODIMP_(DWORD)
CStillFilter::GetBitsSize()
{
DBG_FN("CStillFilter::GetBitsSize");
ASSERT(this!=NULL);
return m_BitsSize;
}
/*****************************************************************************
CStillFilter::GetBitmapInfoSize
<Notes>
*****************************************************************************/
STDMETHODIMP_(DWORD)
CStillFilter::GetBitmapInfoSize()
{
DBG_FN("CStillFilter::GetBitmapInfoSize");
ASSERT(this!=NULL);
return m_bmiSize;
}
/*****************************************************************************
CStillFilter::GetBitmapInfo
<Notes>
*****************************************************************************/
STDMETHODIMP
CStillFilter::GetBitmapInfo( BYTE* Buffer, DWORD BufferSize )
{
DBG_FN("CStillFilter::GetBitmapInfo");
ASSERT(this !=NULL);
ASSERT(m_pbmi !=NULL);
if (BufferSize && !Buffer)
return E_INVALIDARG;
if (BufferSize < m_bmiSize)
return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
if (!m_pbmi)
return E_UNEXPECTED;
memcpy(Buffer, m_pbmi, m_bmiSize);
return NOERROR;
}
/*****************************************************************************
CStillFilter::GetBitmapInfoHeader
<Notes>
*****************************************************************************/
STDMETHODIMP
CStillFilter::GetBitmapInfoHeader( BITMAPINFOHEADER *pbmih )
{
DBG_FN("CStillFilter::GetBitmapInfoHeader");
ASSERT(this !=NULL);
ASSERT(m_pbmi !=NULL);
ASSERT(pbmih !=NULL);
HRESULT hr;
if (!pbmih)
{
hr = E_INVALIDARG;
}
else if (!m_pbmi)
{
hr = E_POINTER;
}
else
{
*pbmih = *(BITMAPINFOHEADER*)m_pbmi;
hr = S_OK;
}
CHECK_S_OK(hr);
return hr;
}
/*****************************************************************************
CStillFilter::SetSamplingSize
<Notes>
*****************************************************************************/
STDMETHODIMP
CStillFilter::SetSamplingSize( int Size )
{
DBG_FN("CStillFilter::SetSamplingSize");
ASSERT(this !=NULL);
ASSERT(m_pInputPin !=NULL);
HRESULT hr = E_POINTER;
if (m_pInputPin)
{
hr = m_pInputPin->SetSamplingSize(Size);
}
CHECK_S_OK(hr);
return hr;
}
/*****************************************************************************
CStillFilter::GetSamplingSize
<Notes>
*****************************************************************************/
STDMETHODIMP_(int)
CStillFilter::GetSamplingSize()
{
DBG_FN("CStillFilter::GetSamplingSize");
ASSERT(this !=NULL);
ASSERT(m_pInputPin !=NULL);
HRESULT hr = E_POINTER;
if (m_pInputPin)
{
hr = m_pInputPin->GetSamplingSize();
}
CHECK_S_OK(hr);
return hr;
}
/*****************************************************************************
CStillFilter::RegisterSnapshotCallback
This function registers a notification callback for newly
arrived frames. Without registering a callback, all captured
frames are discarded.
*****************************************************************************/
STDMETHODIMP
CStillFilter::RegisterSnapshotCallback( LPSNAPSHOTCALLBACK pCallback,
LPARAM lParam
)
{
DBG_FN("CStillFilter::RegisterSnapshotCallback");
ASSERT(this != NULL);
HRESULT hr = S_OK;
m_Lock.Lock();
if (pCallback && !m_pCallback)
{
m_pCallback = pCallback;
m_CallbackParam = lParam;
}
else if (!pCallback)
{
m_pCallback = NULL;
m_CallbackParam = 0;
}
else if (m_pCallback)
{
DBG_TRC(("registering snapshot callback when it is already registered"));
hr = E_INVALIDARG;
}
m_Lock.Unlock();
CHECK_S_OK(hr);
return hr;
}
/*****************************************************************************
CStillFilter::DeliverSnapshot
This function is called from the input pin whenever a new frame is captured.
The given parameter points to the pixel data (BITMAPINFOHEADER is already
cached in *m_pbmi). A new DIB is allocated to store away the newly arrived
bits. The new bits are ignored, however, if the callback is not registered.
*****************************************************************************/
HRESULT
CStillFilter::DeliverSnapshot(HGLOBAL hDib)
{
DBG_FN("CStillFilter::DeliverSnapshot");
ASSERT(this !=NULL);
ASSERT(hDib !=NULL);
HRESULT hr = S_OK;
if (hDib == NULL)
{
hr = E_POINTER;
CHECK_S_OK2(hr, ("CStillFilter::DeliverSnapshot received NULL param"));
}
if (hr == S_OK)
{
m_Lock.Lock();
if (m_pCallback && hDib)
{
BOOL bSuccess = TRUE;
bSuccess = (*m_pCallback)(hDib, m_CallbackParam);
}
m_Lock.Unlock();
}
return hr;
}
/*****************************************************************************
CStillFilter::InitializeBitmapInfo
This function intialize allocates a BITMAPINFO and copies BITMAPINFOHEADER
and necessary color table or color mask fromt the given VIDEOINFO.
*****************************************************************************/
HRESULT
CStillFilter::InitializeBitmapInfo( BITMAPINFOHEADER *pbmiHeader )
{
DBG_FN("CStillFilter::InitializeBitmapInfo");
ASSERT(this !=NULL);
ASSERT(pbmiHeader !=NULL);
HRESULT hr = E_OUTOFMEMORY;
if (!pbmiHeader)
{
hr = E_INVALIDARG;
}
else
{
int ColorTableSize = 0;
m_bmiSize = pbmiHeader->biSize;
if (pbmiHeader->biBitCount <= 8)
{
//
// If biClrUsed is zero, it indicates (1 << biBitCount) entries
//
if (pbmiHeader->biClrUsed)
ColorTableSize = pbmiHeader->biClrUsed * sizeof(RGBQUAD);
else
ColorTableSize = ((DWORD)1 << pbmiHeader->biBitCount) *
sizeof(RGBQUAD);
m_bmiSize += ColorTableSize;
}
//
// color mask
//
if (BI_BITFIELDS == pbmiHeader->biCompression)
{
//
// 3 dword of mask
//
m_bmiSize += 3 * sizeof(DWORD);
}
//
// now calculate bits size
// each scanline must be 32 bits aligned.
//
m_BitsSize = (((pbmiHeader->biWidth * pbmiHeader->biBitCount + 31)
& ~31) >> 3)
* ((pbmiHeader->biHeight < 0) ? -pbmiHeader->biHeight:
pbmiHeader->biHeight);
m_DIBSize = m_bmiSize + m_BitsSize;
if (m_pbmi)
{
delete [] m_pbmi;
}
m_pbmi = new BYTE[m_bmiSize];
if (m_pbmi)
{
BYTE *pColorTable = ((BYTE*)pbmiHeader + (WORD)(pbmiHeader->biSize));
//
// Copy BITMAPINFOHEADER
//
memcpy(m_pbmi, pbmiHeader, pbmiHeader->biSize);
//
// copy the color table or color masks if there are any
//
if (BI_BITFIELDS == pbmiHeader->biCompression)
{
memcpy(m_pbmi + pbmiHeader->biSize,
pColorTable,
3 * sizeof(DWORD));
}
if (ColorTableSize)
{
memcpy(m_pbmi + pbmiHeader->biSize,
pColorTable,
ColorTableSize);
}
hr = S_OK;
}
}
CHECK_S_OK(hr);
return hr;
}
| [
"seta7D5@protonmail.com"
] | seta7D5@protonmail.com |
9beea9a0a309b4f32a6fbd928f542579a05ab2f4 | 3fea899f7ad6280029745809e73d033c67d64866 | /questao 3/Funcionario.cpp | 2509ad512fa8552731c5174fa03e4b59a86debc9 | [] | no_license | GiovanniBru/roteiro10 | 94665ece8386defccec88bbbec64929a75e7c0e8 | ad4f71165853a41471106802296c2e1fbdf9839b | refs/heads/master | 2021-08-08T15:02:49.792047 | 2017-11-10T14:43:26 | 2017-11-10T14:43:26 | 110,250,606 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 457 | cpp | #include <iostream>
#include "Funcionario.h"
using namespace std;
/*Funcionario::Funcionario(string n, int m){
set_nome(n);
set_matricula(m);
}*/
void Funcionario::set_nome(string n){
nome = n;
}
void Funcionario::set_matricula(int m){
if(m < 0){
cout << "Erro na matricula." << endl;
}else{
matricula = m;
}
}
string Funcionario::get_nome(){
return nome;
}
int Funcionario::get_matricula(){
return matricula;
}
| [
"noreply@github.com"
] | GiovanniBru.noreply@github.com |
1e21656747d3b18938896a6eef13052a61cfbd64 | c53695d1a2f7de2ae6e3555c8dd098e2b99e0b16 | /interface.cpp | 99ff75e59d9b75a93f94317b14602133026889bd | [] | no_license | mkmik/myindex | 2bfb76c3e13f4ea11a616b10bd834c0bdf9efd3a | 369fdda309d4d3cc3c5b60cb531f85566275c0c5 | refs/heads/master | 2021-05-26T15:28:02.763468 | 2010-09-09T09:31:53 | 2010-09-09T09:31:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 812 | cpp | #include "soapindexServiceObject.h"
struct Namespace namespaces[] =
{ // {"ns-prefix", "ns-name"}
{"SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/"}, // MUST be first
{"SOAP-ENC", "http://schemas.xmlsoap.org/soap/encoding/"}, // MUST be second
{"xsi", "http://www.w3.org/2001/XMLSchema-instance"}, // MUST be third
{"xsd", "http://www.w3.org/2001/XMLSchema"}, // 2001 XML Schema
{"ns1", "urn:xmethods-delayed-quotes"}, // given by the service description
{"ns", "urn:driver"},
{NULL, NULL} // end of table
};
int main()
{
// create soap context and serve one CGI-based request:
soap_serve(soap_new());
/*
indexServiceService service;
service.serve();
*/
return 0;
}
int ns__lookup(struct soap *soap, char * &response)
{
response = "ciao";
return SOAP_OK;
}
| [
"marko.mikulicic@isti.cnr.it"
] | marko.mikulicic@isti.cnr.it |
dddd30b2b27f01a62e5f886babe68243c9d1fb74 | 6754fedd87afba36ec8f004825bb852b00ac8fb2 | /src/boost/functional/hash/deque.hpp | 06d23c2200847925d44180b7a169e4732c376694 | [
"BSD-3-Clause",
"BSL-1.0"
] | permissive | cpmech/vismatrix | 4e7b8a3e0448f4c9565fa649e9c9af0e05707346 | a4994864d3592cfa2db24119427fad096303fb4f | refs/heads/main | 2021-08-15T21:52:56.975004 | 2020-09-24T00:55:35 | 2020-09-24T00:55:35 | 54,020,206 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 921 | hpp |
// Copyright 2005-2008 Daniel James.
// 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)
// Based on Peter Dimov's proposal
// http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2005/n1756.pdf
// issue 6.18.
#if !defined(BOOST_FUNCTIONAL_HASH_DEQUE_HPP)
#define BOOST_FUNCTIONAL_HASH_DEQUE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
#if defined(__EDG__)
#elif defined(_MSC_VER) || defined(__BORLANDC__) || defined(__DMC__)
#pragma message("Warning: boost/functional/hash/deque.hpp is deprecated, use boost/functional/hash.hpp instead.")
#elif defined(__GNUC__) || defined(__HP_aCC) || \
defined(__SUNPRO_CC) || defined(__IBMCPP__)
#warning "boost/functional/hash/deque.hpp is deprecated, use boost/functional/hash.hpp instead."
#endif
#include <boost/functional/hash.hpp>
#endif
| [
"dorival.pedroso@gmail.com"
] | dorival.pedroso@gmail.com |
449cd4ab0c5d06a54cb35aaf9c9a7ab3e1170224 | 6408cfc725bc63d4cc0f3bafa231be2a968d7323 | /ReadData_Matlab/write_data.cpp | 676545689877a1263ce1aabaec3c6dcfe1d40b99 | [] | no_license | FrancesZhou/XMTC_SLEEC | c9f90b3eec23aadd0410005fca192c2943171a0c | bc9d74ff4aaf6d662039b484e09e632b7c447357 | refs/heads/master | 2021-09-15T00:41:07.152519 | 2018-05-23T03:14:29 | 2018-05-23T03:14:29 | 113,753,521 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,229 | cpp | #include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <mex.h>
#define NAME_LEN 100000
using namespace std;
void mexFunction(int nlhs, mxArray* plhs[], int rlhs, const mxArray* prhs[])
{
mxAssert(nrhs==3,"Required and allowed arguments: mex_feature_mat, mex_label_mat, text_data_file_name");
mxArray* ft_mat = (mxArray*) prhs[0];
mxArray* lbl_mat = (mxArray*) prhs[1];
char file_name[NAME_LEN];
mxGetString(prhs[2],file_name,NAME_LEN);
FILE* fout = fopen(file_name,"w");
int num_inst = mxGetN(ft_mat);
int num_ft = mxGetM(ft_mat);
int num_lbl = mxGetM(lbl_mat);
fprintf(fout,"%d %d %d\n",num_inst,num_ft,num_lbl);
mwIndex* ft_Ir = mxGetIr(ft_mat);
mwIndex* ft_Jc = mxGetJc(ft_mat);
double* ft_Pr = mxGetPr(ft_mat);
mwIndex* lbl_Ir = mxGetIr(lbl_mat);
mwIndex* lbl_Jc = mxGetJc(lbl_mat);
double* lbl_Pr = mxGetPr(lbl_mat);
for(int i=0; i<num_inst; i++)
{
for(int j=lbl_Jc[i]; j<lbl_Jc[i+1]; j++)
{
int lbl = lbl_Ir[j];
if(j==lbl_Jc[i])
fprintf(fout,"%d",lbl);
else
fprintf(fout,",%d",lbl);
}
for(int j=ft_Jc[i]; j<ft_Jc[i+1]; j++)
{
fprintf(fout," %d:%f",ft_Ir[j],ft_Pr[j]);
}
fprintf(fout,"\n");
}
fclose(fout);
}
| [
"zhouxian@sjtu.edu.cn"
] | zhouxian@sjtu.edu.cn |
28d20c4ed82b078bc2c9fc71043fbb5da520a705 | 785739694ad05053f7ded3b60dcd8e46b2ab0505 | /LiFi textReader/blink_led.ino/blink_led.ino.ino | e1ea5498c1c6f7af035bbae1fb63311e3e110d41 | [] | no_license | premangshuC/LiFi | e5425e4c5c7ac5165820552e3dc78b1142cbb0d9 | 7df5e72b4b28d0ed8006381743ec7641b6f38069 | refs/heads/master | 2020-04-12T09:00:19.017061 | 2018-05-09T08:03:47 | 2018-05-09T08:03:47 | 63,570,246 | 2 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 404 | ino | void setup() {
// initialize digital pin 13 as an output.
pinMode(13, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
| [
"premangshuchanda@gmail.com"
] | premangshuchanda@gmail.com |
1d10bde8c3609e8db320b46c58a498f649f8332b | eb40a068cef3cabd7a0df37a0ec2bde3c1e4e5ae | /dnn/src/rocm/relayout/relayout_contiguous.cpp | bc4314836ca31ca26b4557e411cfc061c2c87aae | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | permissive | tpoisonooo/MegEngine | ccb5c089a951e848344f136eaf10a5c66ae8eb6f | b8f7ad47419ef287a1ca17323fd6362c6c69445c | refs/heads/master | 2022-11-07T04:50:40.987573 | 2021-05-27T08:55:50 | 2021-05-27T08:55:50 | 249,964,363 | 1 | 0 | NOASSERTION | 2021-05-27T08:55:50 | 2020-03-25T11:48:35 | null | UTF-8 | C++ | false | false | 2,947 | cpp | /**
* \file dnn/src/rocm/relayout/relayout_contiguous.cpp
* MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
*
* Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#include "hcc_detail/hcc_defs_prologue.h"
#include "src/rocm/relayout/relayout_contiguous.h.hip"
#include "src/common/utils.h"
namespace megdnn {
namespace rocm {
namespace contiguous_intl {
template <int ndim, typename ctype>
void ParamElemVisitor<ndim, ctype, CONTIG_OTHER>::host_init(
const TensorND& rv, int /*grid_size*/, int /*block_size*/) {
megdnn_assert(rv.layout.ndim && rv.layout.ndim <= ndim);
m_ptr = rv.ptr<ctype>();
for (size_t i = 0; i < rv.layout.ndim; ++i) {
m_stride[i] = rv.layout.stride[i];
if (i + 1 < rv.layout.ndim)
m_shape_highdim[i] = rv.layout.shape[i + 1];
}
for (int i = rv.layout.ndim - 1; i < ndim - 1; ++i) {
m_shape_highdim[i] = 1;
}
for (int i = rv.layout.ndim; i < ndim; ++i) {
m_stride[i] = 0;
}
}
template <int ndim, typename ctype>
void ParamElemVisitor<ndim, ctype, CONTIG_FULL>::host_init(const TensorND& rv,
int /*grid_size*/,
int /*block_size*/) {
megdnn_assert_contiguous(rv.layout);
m_ptr = rv.ptr<ctype>();
}
#define INST(ndim, ctype, ctg) template class ParamElemVisitor<ndim, ctype, ctg>
#define INST_FOR_CTYPE MEGDNN_FOREACH_TENSOR_NDIM(ndim_cb)
#define ndim_cb(_ndim) \
INST(_ndim, ct, CONTIG_OTHER); \
INST(_ndim, ct, CONTIG_FULL);
#define ct dt_byte
INST_FOR_CTYPE
#undef ct
#define ct dt_int32
INST_FOR_CTYPE
#undef ct
#define ct dt_float16
INST_FOR_CTYPE
#undef ct
#undef ndim_cb
#undef INST_FOR_CTYPE
#undef INST
} // namespace contiguous_intl
void get_last_contiguous_launch_spec(const void* /*kern*/, size_t size,
size_t contiguous_size, int* grid_size,
int* block_size) {
safe_size_in_kern(size);
const uint32_t blocks = 256;
*block_size = blocks;
int a = size / (blocks * (contiguous_size - 1)),
b = (size - 1) / (blocks * contiguous_size) + 1;
*grid_size = std::max(a, b);
if (!*grid_size) {
*block_size = std::min<int>(std::max<int>(size / 64, 1) * 32, 1024);
*grid_size = std::max<int>(size / *block_size, 1);
}
// because we unroll contiguous_size times in the kernel
megdnn_assert(static_cast<size_t>(*block_size) * *grid_size *
contiguous_size >=
size);
}
} // namespace rocm
} // namespace megdnn
// vim: ft=cpp syntax=cpp.doxygen
| [
"megengine@megvii.com"
] | megengine@megvii.com |
f4b611f878cd68acc0a95e6be465ae5c426328c0 | 731f016c6823c3a3d340b5f4f82fcfdb2fcaf025 | /FlameShot/selectiontool.cpp | 4d9a8d9f3d0a6e16f5b69ec8788fcf109fbd4cd6 | [] | no_license | SindenDev/ScreenShot | 536f390fb3759e6afb66ba71fd68be9f75e00ee9 | 15756e5b4ecede3c082f6e31773e527d37cde2ad | refs/heads/master | 2022-07-25T18:41:21.169560 | 2020-05-15T11:38:00 | 2020-05-15T11:38:00 | 259,273,203 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,576 | cpp |
#include "selectiontool.h"
#include <QPainter>
namespace {
#define PADDING_VALUE 2
}
SelectionTool::SelectionTool(QObject *parent) : AbstractTwoPointTool(parent) {
m_supportsDiagonalAdj = true;
}
bool SelectionTool::closeOnButtonPressed() const {
return false;
}
QIcon SelectionTool::icon(const QColor &background, bool inEditor) const {
Q_UNUSED(inEditor);
return QIcon(iconPath(background) + "square-outline.svg");
}
QString SelectionTool::name() const {
return QStringLiteral("矩形选择");
}
QString SelectionTool::nameID() {
return QLatin1String("");
}
QString SelectionTool::description() const {
return QStringLiteral("设置选区");
}
CaptureTool* SelectionTool::copy(QObject *parent) {
return new SelectionTool(parent);
}
void SelectionTool::process(QPainter &painter, const QPixmap &pixmap, bool recordUndo) {
if (recordUndo) {
updateBackup(pixmap);
}
painter.setPen(QPen(m_color, m_thickness));
painter.drawRect(QRect(m_points.first, m_points.second));
}
void SelectionTool::paintMousePreview(QPainter &painter, const CaptureContext &context) {
painter.setPen(QPen(context.color, PADDING_VALUE + context.thickness));
painter.drawLine(context.mousePos, context.mousePos);
}
void SelectionTool::drawStart(const CaptureContext &context) {
m_color = context.color;
m_thickness = context.thickness + PADDING_VALUE;
m_points.first = context.mousePos;
m_points.second = context.mousePos;
}
void SelectionTool::pressed(const CaptureContext &context) {
Q_UNUSED(context);
}
| [
"zhangxintian@imsightmed.com"
] | zhangxintian@imsightmed.com |
78ee1a61b7ecba3dc2a4b72da4c10d5d0b885fc9 | dbcd2006f283fcb469524d92d884024fa11345ac | /storage/diskmgr/services/storage_service/interface/src/storage_service_stub.cpp | 15c2e389d0046de18df33ffb5839530470582b37 | [
"Apache-2.0"
] | permissive | openharmony-gitee-mirror/distributeddatamgr_file | 380e4841a943d548f810081d86b661d6b099a9b6 | 1e624bbc3850815fa1b2642c67123b7785bec6a1 | refs/heads/master | 2023-08-20T11:39:22.117760 | 2021-10-25T01:53:50 | 2021-10-25T01:53:50 | 400,051,638 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,845 | cpp | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "fbe_crypto.h"
#include "interface/storage_service_callback_proxy.h"
#include "ipc/storage_service_task_proxy.h"
#include "storage_hilog.h"
#include "storage_service_stub.h"
namespace OHOS {
void RemoteReturnInt(MessageParcel &reply, int32_t errcode)
{
reply.WriteInt32(errcode);
if (errcode != ERR_NONE) {
SSLOG_E("remote error code =%{public}d ", errcode);
}
}
int32_t StorageServiceStub::OnRemoteRequest(uint32_t code,
MessageParcel &data,
MessageParcel &reply,
MessageOption &option)
{
auto remoteDescriptor = data.ReadInterfaceToken();
if (GetDescriptor() != remoteDescriptor) {
return ERR_INVALID_STATE;
}
int32_t errCode = ERR_NONE;
SSLOG_I("StorageServiceStub::OnRemoteRequest code : %{public}d", code);
switch (code) {
case SS_DOMOUNT: errCode = StorageServiceStub::HandleMount(data, reply); break;
case SS_UNMOUNT: errCode = StorageServiceStub::HandleUnMount(data, reply); break;
case SS_FORMAT: errCode = HandleFormat(data, reply); break;
case SS_REGISTERCALLBACK: errCode = HandleRegisterStorageServiceCallback(data, reply); break;
case SS_PARTITION: errCode = HandlePartition(data, reply); break;
case SS_RESET: errCode = HandleReset(reply); break;
case SS_USERADDED: errCode = HandleUserAdded(data, reply); break;
case SS_USERREMOVED: errCode = HandleUserRemoved(data, reply); break;
case SS_USERSTARTED: errCode = HandleUserStarted(data, reply); break;
case SS_USERSTOPED: errCode = HandleUserStoped(data, reply); break;
case SS_MOVESTORAGE: errCode = HandleMoveStorage(data, reply); break;
case SS_BENCHMARK: errCode = HandleBenchMark(data, reply); break;
case SS_CRYPTO_ENABLE: errCode = HandleCryptoEnable(reply); break;
case SS_CRYPTO_INITIALIZE: errCode = HandleCryptoInitialize(reply); break;
case SS_CRYPTO_CREATEKEY: errCode = HandleCryptoCreateKey(data, reply); break;
case SS_CRYPTO_DELETEKEY: errCode = HandleCryptoDeleteKey(data, reply); break;
case SS_CRYPTO_ADDAUTHKEY: errCode = HandleCryptoAddAuthKey(data, reply); break;
case SS_CRYPTO_DELAUTHKEY: errCode = HandleCryptoDelAuthKey(data, reply); break;
case SS_CRYPTO_UNLOCKKEY: errCode = HandleCryptoUnlockKey(data, reply); break;
case SS_CRYPTO_LOCKKEY: errCode = HandleCryptoLockKey(data, reply); break;
case SS_CRYPTO_INITUSERSPACE: errCode = HandleCryptoInitUserSpace(data, reply); break;
case SS_CRYPTO_REMOVEUSERSPACE: errCode = HandleCryptoRemoveUserSpace(data, reply); break;
case SS_CRYPTO_UPDATEAUTHKEY: errCode = HandleCryptoUpdateAuthKey(data, reply); break;
case SS_IDLEFSTRIM: errCode = HandleIdleFsTrim(reply); break;
case SS_RUNIDLEMAINTAIN: errCode = HandleRunIdleMaintain(reply); break;
case SS_ABORTIDLEMAINTAIN: errCode = HandleAbortIdleMaintain(reply); break;
case SS_PERSISTFSTAB: errCode = HandlePersistFstab(data, reply); break;
case SS_ISENCRYPTED: errCode = HandleIsEncrypted(data, reply); break;
default: {
SSLOG_I("StorageServiceStub::OnRemoteRequest default");
errCode = IPCObjectStub::OnRemoteRequest(code, data, reply, option);
break;
}
}
return errCode;
}
int32_t StorageServiceStub::HandleMount(MessageParcel &data, MessageParcel &reply)
{
SSLOG_I("StorageServiceStub::OnRemoteRequest SS_DOMount");
bool ret = false;
std::string volId = data.ReadString();
int32_t mountFlags = data.ReadInt32();
int32_t mountUserId = data.ReadInt32();
SSLOG_I("StorageServiceStub::OnRemoteRequest: %{public}s MountFlags %{public}d MountUserId "
"%{public}d",
volId.c_str(), mountFlags, mountUserId);
ret = Mount(volId, mountFlags, mountUserId);
if (!reply.WriteBool(ret)) {
SSLOG_E("write failed");
return TRANSACTION_ERR;
}
return NO_ERROR;
}
int32_t StorageServiceStub::HandleUnMount(MessageParcel &data, MessageParcel &reply)
{
SSLOG_I("StorageServiceStub::OnRemoteRequest SS_UNMOUNT");
bool ret = false;
std::string volId = data.ReadString();
SSLOG_I("StorageServiceStub::OnRemoteRequest: %{public}s", volId.c_str());
ret = UnMount(volId);
if (!reply.WriteBool(ret)) {
SSLOG_E("write failed");
return TRANSACTION_ERR;
}
return NO_ERROR;
}
int32_t StorageServiceStub::HandleFormat(MessageParcel &data, MessageParcel &reply)
{
SSLOG_I("StorageServiceStub::OnRemoteRequest SS_FORMAT");
std::string volId = data.ReadString();
std::string fsType = data.ReadString();
SSLOG_I("StorageServiceStub::OnRemoteRequest:volId is %{public}s,fsType is %{public}s", volId.c_str(),
fsType.c_str());
bool ret = false;
ret = Format(volId, fsType);
if (!reply.WriteBool(ret)) {
SSLOG_E("write failed");
return TRANSACTION_ERR;
}
return NO_ERROR;
}
int32_t StorageServiceStub::HandlePersistFstab(MessageParcel &data, MessageParcel &reply)
{
SSLOG_I("StorageServiceStub::OnRemoteRequest SS_PERSISTFSTAB");
bool ret = false;
std::string fstab = data.ReadString();
SSLOG_I("StorageServiceStub::OnRemoteRequest: fstab::%{public}s ", fstab.c_str());
ret = PersistFstab(fstab);
if (!reply.WriteBool(ret)) {
SSLOG_E("write failed");
return TRANSACTION_ERR;
}
return NO_ERROR;
}
int32_t StorageServiceStub::HandleIsEncrypted(MessageParcel &data, MessageParcel &reply)
{
SSLOG_I("StorageServiceStub::OnRemoteRequest SS_ISENCRYPTED");
bool ret = false;
std::string filePath = data.ReadString();
SSLOG_I("StorageServiceStub::OnRemoteRequest: SS_ISENCRYPTED::%{public}s ", filePath.c_str());
ret = IsEncrypted(filePath);
if (!reply.WriteBool(ret)) {
SSLOG_E("write failed");
return TRANSACTION_ERR;
}
return NO_ERROR;
}
int32_t StorageServiceStub::HandleRegisterStorageServiceCallback(MessageParcel &data, MessageParcel &reply)
{
sptr<IRemoteObject> object = data.ReadRemoteObject();
if (object != nullptr) {
SSLOG_E("remote object is not null");
}
sptr<IStorageServiceCallback> storageServiceCallback = iface_cast<IStorageServiceCallback>(object);
bool ret = false;
if (!storageServiceCallback) {
SSLOG_E("Get IStorageServiceCallback failed");
return TRANSACTION_ERR;
} else {
ret = RegisterStorageServiceCallback(storageServiceCallback);
}
if (!reply.WriteBool(ret)) {
SSLOG_E("write failed");
return TRANSACTION_ERR;
}
return NO_ERROR;
}
int32_t StorageServiceStub::HandlePartition(MessageParcel &data, MessageParcel &reply)
{
bool ret = false;
std::string diskId = data.ReadString();
int32_t partitionType = data.ReadInt32();
int32_t ratio = data.ReadInt32();
ret = Partition(diskId, partitionType, ratio);
if (!reply.WriteBool(ret)) {
SSLOG_E("write failed");
return TRANSACTION_ERR;
}
return NO_ERROR;
}
int32_t StorageServiceStub::HandleUserAdded(MessageParcel &data, MessageParcel &reply)
{
bool ret = false;
int32_t userId = data.ReadInt32();
int32_t userSerial = data.ReadInt32();
ret = UserAdded(userId, userSerial);
if (!reply.WriteBool(ret)) {
SSLOG_E("write failed");
return TRANSACTION_ERR;
}
return NO_ERROR;
}
int32_t StorageServiceStub::HandleUserRemoved(MessageParcel &data, MessageParcel &reply)
{
bool ret = false;
int32_t userId = data.ReadInt32();
ret = UserRemoved(userId);
if (!reply.WriteBool(ret)) {
SSLOG_E("write failed");
return TRANSACTION_ERR;
}
return NO_ERROR;
}
int32_t StorageServiceStub::HandleUserStarted(MessageParcel &data, MessageParcel &reply)
{
bool ret = false;
int32_t userId = data.ReadInt32();
SSLOG_E("__func%{public}s, userId is %{public}d", __func__, userId);
ret = UserStarted(userId);
SSLOG_E(" __func%{public}s, ret is %{public}d", __func__, ret);
if (!reply.WriteBool(ret)) {
SSLOG_E("write failed");
return TRANSACTION_ERR;
}
return NO_ERROR;
}
int32_t StorageServiceStub::HandleUserStoped(MessageParcel &data, MessageParcel &reply)
{
bool ret = false;
int32_t userId = data.ReadInt32();
ret = UserStoped(userId);
if (!reply.WriteBool(ret)) {
SSLOG_E("write failed");
return TRANSACTION_ERR;
}
return NO_ERROR;
}
int32_t StorageServiceStub::HandleMoveStorage(MessageParcel &data, MessageParcel &reply)
{
bool ret = false;
std::string fromVolId = data.ReadString();
std::string toVolId = data.ReadString();
sptr<IRemoteObject> object = data.ReadRemoteObject();
sptr<IStorageServiceTask> storageServiceTask = iface_cast<IStorageServiceTask>(object);
ret = MoveStorage(fromVolId, toVolId, storageServiceTask);
if (!reply.WriteBool(ret)) {
SSLOG_E("write failed");
return TRANSACTION_ERR;
}
return NO_ERROR;
}
int32_t StorageServiceStub::HandleBenchMark(MessageParcel &data, MessageParcel &reply)
{
bool ret = false;
std::string volId = data.ReadString();
sptr<IRemoteObject> object = data.ReadRemoteObject();
sptr<IStorageServiceTask> storageServiceTask = iface_cast<IStorageServiceTask>(object);
ret = BenchMark(volId, storageServiceTask);
if (!reply.WriteBool(ret)) {
SSLOG_E("write failed");
return TRANSACTION_ERR;
}
return NO_ERROR;
}
int32_t StorageServiceStub::HandleReset(MessageParcel &reply)
{
SSLOG_E("HandleReset");
bool ret = false;
ret = Reset();
SSLOG_E("HandleReset: %{public}d", ret);
if (!reply.WriteBool(ret)) {
SSLOG_E("write failed");
return TRANSACTION_ERR;
}
return NO_ERROR;
}
int32_t StorageServiceStub::HandleCryptoEnable(MessageParcel &reply)
{
SSLOG_I("HandleFbeEnable STARTING....(From gby)");
bool ret = false;
ret = CryptoEnable();
if (!reply.WriteBool(ret)) {
SSLOG_E("write failed");
return TRANSACTION_ERR;
}
SSLOG_I("HandleFbeEnable END....(From gby)");
return NO_ERROR;
}
int32_t StorageServiceStub::HandleCryptoInitialize(MessageParcel &reply)
{
SSLOG_I("HandleInitUser0 STARTING....(From gby)");
bool ret = false;
ret = CryptoInitialize();
if (!reply.WriteBool(ret)) {
SSLOG_E("write failed");
return TRANSACTION_ERR;
}
SSLOG_I("HandleInitUser0 END....(From gby)");
return NO_ERROR;
}
int32_t StorageServiceStub::HandleCryptoCreateKey(MessageParcel &data, MessageParcel &reply)
{
SSLOG_I("HandleInitUser0 STARTING....(From gby)");
bool ret = false;
int32_t userId = data.ReadInt32();
ret = CryptoCreateKey(userId);
if (!reply.WriteBool(ret)) {
SSLOG_E("write failed");
return TRANSACTION_ERR;
}
SSLOG_I("HandleInitUser0 END....(From gby)");
return NO_ERROR;
}
int32_t StorageServiceStub::HandleCryptoDeleteKey(MessageParcel &data, MessageParcel &reply)
{
SSLOG_I("HandleInitUser0 STARTING....(From gby)");
bool ret = false;
int32_t userId = data.ReadInt32();
ret = CryptoDeleteKey(userId);
if (!reply.WriteBool(ret)) {
SSLOG_E("write failed");
return TRANSACTION_ERR;
}
SSLOG_I("HandleInitUser0 END....(From gby)");
return NO_ERROR;
}
int32_t StorageServiceStub::HandleCryptoAddAuthKey(MessageParcel &data, MessageParcel &reply)
{
SSLOG_I("HandleInitUser0 STARTING....(From gby)");
bool ret = false;
int32_t userId = data.ReadInt32();
const std::string token = data.ReadString();
const std::string secret = data.ReadString();
ret = CryptoAddAuthKey(userId, token, secret);
if (!reply.WriteBool(ret)) {
SSLOG_E("write failed");
return TRANSACTION_ERR;
}
SSLOG_I("HandleInitUser0 END....(From gby)");
return NO_ERROR;
}
int32_t StorageServiceStub::HandleCryptoDelAuthKey(MessageParcel &data, MessageParcel &reply)
{
SSLOG_I("HandleInitUser0 STARTING....(From gby)");
bool ret = false;
int32_t userId = data.ReadInt32();
const std::string token = data.ReadString();
const std::string secret = data.ReadString();
ret = CryptoDelAuthKey(userId, token, secret);
if (!reply.WriteBool(ret)) {
SSLOG_E("write failed");
return TRANSACTION_ERR;
}
SSLOG_I("HandleInitUser0 END....(From gby)");
return NO_ERROR;
}
int32_t StorageServiceStub::HandleCryptoUnlockKey(MessageParcel &data, MessageParcel &reply)
{
SSLOG_I("HandleInitUser0 STARTING....(From gby)");
bool ret = false;
int32_t userId = data.ReadInt32();
const std::string token = data.ReadString();
const std::string secret = data.ReadString();
ret = CryptoUnlockKey(userId, token, secret);
if (!reply.WriteBool(ret)) {
SSLOG_E("write failed");
return TRANSACTION_ERR;
}
SSLOG_I("HandleInitUser0 END....(From gby)");
return NO_ERROR;
}
int32_t StorageServiceStub::HandleCryptoLockKey(MessageParcel &data, MessageParcel &reply)
{
SSLOG_I("HandleInitUser0 STARTING....(From gby)");
bool ret = false;
int32_t userId = data.ReadInt32();
ret = CryptoLockKey(userId);
if (!reply.WriteBool(ret)) {
SSLOG_E("write failed");
return TRANSACTION_ERR;
}
SSLOG_I("HandleInitUser0 END....(From gby)");
return NO_ERROR;
}
int32_t StorageServiceStub::HandleCryptoUpdateAuthKey(MessageParcel &data, MessageParcel &reply)
{
SSLOG_I("HandleInitUser0 STARTING....(From gby)");
bool ret = false;
int32_t userId = data.ReadInt32();
const std::string token = data.ReadString();
const std::string secret = data.ReadString();
ret = CryptoUpdateAuthKey(userId, token, secret);
if (!reply.WriteBool(ret)) {
SSLOG_E("write failed");
return TRANSACTION_ERR;
}
SSLOG_I("HandleInitUser0 END....(From gby)");
return NO_ERROR;
}
int32_t StorageServiceStub::HandleCryptoInitUserSpace(MessageParcel &data, MessageParcel &reply)
{
SSLOG_I("HandleInitUser0 STARTING....(From gby)");
bool ret = false;
const std::string uuid = data.ReadString();
int32_t userId = data.ReadInt32();
int32_t flag = data.ReadInt32();
ret = CryptoInitUserSpace(uuid, userId, flag);
if (!reply.WriteBool(ret)) {
SSLOG_E("write failed");
return TRANSACTION_ERR;
}
SSLOG_I("HandleInitUser0 END....(From gby)");
return NO_ERROR;
}
int32_t StorageServiceStub::HandleCryptoRemoveUserSpace(MessageParcel &data, MessageParcel &reply)
{
SSLOG_I("HandleInitUser0 STARTING....(From gby)");
bool ret = false;
const std::string uuid = data.ReadString();
int32_t userId = data.ReadInt32();
int32_t flag = data.ReadInt32();
ret = CryptoRemoveUserSpace(uuid, userId, flag);
if (!reply.WriteBool(ret)) {
SSLOG_E("write failed");
return TRANSACTION_ERR;
}
SSLOG_I("HandleInitUser0 END....(From gby)");
return NO_ERROR;
}
int32_t StorageServiceStub::HandleIdleFsTrim(MessageParcel &reply)
{
bool ret = false;
sptr<IStorageServiceTask> storageServiceTask;
ret = IdleFsTrim(storageServiceTask);
if (!reply.WriteBool(ret)) {
SSLOG_E("write failed");
return TRANSACTION_ERR;
}
return NO_ERROR;
}
int32_t StorageServiceStub::HandleRunIdleMaintain(MessageParcel &reply)
{
bool ret = false;
sptr<IStorageServiceTask> storageServiceTask;
ret = RunIdleMaintain(storageServiceTask);
if (!reply.WriteBool(ret)) {
SSLOG_E("write failed");
return TRANSACTION_ERR;
}
return NO_ERROR;
}
int32_t StorageServiceStub::HandleAbortIdleMaintain(MessageParcel &reply)
{
bool ret = false;
sptr<IStorageServiceTask> storageServiceTask;
ret = AbortIdleMaintain(storageServiceTask);
if (!reply.WriteBool(ret)) {
SSLOG_E("write failed");
return TRANSACTION_ERR;
}
return NO_ERROR;
}
} // namespace OHOS
| [
"panqiangbiao@163.com"
] | panqiangbiao@163.com |
8cd56224cd88c0f56fcd45fab4279353e3cab531 | c48dcd857a3369a7a86fd0eaef971bff9633b67f | /trunk/zat/lib/zstring.cc | 90ad3bcb68dccdbb3088e157b0bc5e8267e7a002 | [] | no_license | BackupTheBerlios/zat-dev-svn | fae6db3477cae636cff8147c59d9c3ee17c76681 | cf86ec1a6a90fff3c822446fda5884ef1c61d4a1 | refs/heads/master | 2020-04-14T21:08:26.085862 | 2005-04-18T08:27:46 | 2005-04-18T08:27:46 | 40,802,317 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,721 | cc | // Zat Assembler Toolchain.
// Copyright (C) 2004-2005 Justin Forest <justin.forest@gmail.com>
//
// $Id$
#include <stdarg.h>
#include <stdio.h>
#include "zstring.h"
void zstring::capsize()
{
for (std::string::iterator it = begin(); it != end(); ++it)
*it = ::toupper(*it);
}
unsigned int zstring::hash() const
{
unsigned int value = 0;
for (std::string::const_iterator it = begin(); it != end(); ++it)
value = value * 31 + static_cast<unsigned char>(*it);
return value;
}
bool zstring::has_path() const
{
for (std::string::const_iterator it = begin(); it != end(); ++it) {
#ifdef _WIN32
if (*it == '\\')
return true;
#endif
if (*it == '/')
return true;
}
return false;
}
zstring zstring::gettok(const char *&src, char sep)
{
const char *org = src, *end;
while (*src != '\0' && *src != sep)
++src;
end = src;
if (*src == sep)
++src;
return zstring(org, end - org);
}
bool zstring::operator == (const char *src) const
{
const_iterator it;
for (it = begin(); it != end() && *src != 0; ++it, ++src)
if (::toupper(*it) != ::toupper(*src))
break;
return (it == end() && *src == 0);
}
zstring& zstring::operator = (const zstring &src)
{
*(std::string *)this = src;
return *this;
}
zstring& zstring::format(const char *format, ...)
{
char *tmp;
va_list vl;
va_start(vl, format);
vasprintf(&tmp, format, vl);
va_end(vl);
*this = tmp;
free(tmp);
return *this;
}
zstring& zstring::trim(char c)
{
std::string::const_iterator src = begin();
std::string::iterator dst = begin();
while (src != end() && *src == ' ')
++src;
while (src != end())
*dst++ = *src++;
while (dst != begin() && *(dst - 1) == c)
--dst;
resize(dst - begin());
return *this;
}
| [
"hex@75074d0f-cef1-0310-aeb8-8f850d70955c"
] | hex@75074d0f-cef1-0310-aeb8-8f850d70955c |
46aec409877fc714bf7424e36c435a9003c76a73 | 94fd014cbe631100439127fc90a175e39c1d7366 | /Sem Título4.cpp | 87b1cd826fa81f052cddf8687f2fd42c426ef4fe | [
"MIT"
] | permissive | Mraimundo/Programa-o-II | 4ca1a80eb7fd74004c75066d5e0fb27c83735970 | 6b908ce99a22ff887884f2b07b65e83c6e456200 | refs/heads/master | 2020-06-26T02:01:02.984011 | 2019-07-29T16:45:56 | 2019-07-29T16:45:56 | 199,491,501 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 509 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int verifica (int n1, int n2){
int result;
if(n1>n2)
return n1;
else
return n2;
}
int verifica_2 (int n1, int n2, int n3){
int result;
if(verifica(n1, n2) > n3){
return verifica(n1, n2);
}
else
return n3;
}
int main(){
int resultado, num, num2, num3;
printf("Digite 3 numeros:\n");
scanf("%d %d %d", &num, &num2, &num3);
resultado=verifica_2(num, num2, num3);
printf("O maior numero eh: %d", resultado);
}
| [
"mouzinho.raimundo@idsestudantes.org"
] | mouzinho.raimundo@idsestudantes.org |
d1828468970eafb3e06d258243168fd00cb53bc7 | 4cbcff3fc9e753ae7a043ce442f52b0524117d82 | /GoBang/Resources.hpp | 238cec6c6da1db9abda18be436521550183e1aa0 | [] | no_license | scyxiaoh/GoBang | d4ea51530676dd000f522f7d95e8b9dc57cd3df8 | d3a60160c84388ab0c59d5ea3049dc1aacc9d72d | refs/heads/master | 2020-03-26T02:47:04.708439 | 2018-10-24T20:53:13 | 2018-10-24T20:53:13 | 144,423,761 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 417 | hpp | //
// Resources.hpp
// GoBang
//
// Created by Kevin Sun on 2018/10/15.
//
#ifndef Resources_hpp
#define Resources_hpp
#include <stdio.h>
#include <QGraphicsObject>
class Resources {
public:
class Image {
public:
static QImage whitePiece();
static QImage blackPiece();
static QImage titleBackGround();
static QImage gameBackGround();
};
};
#endif /* Resources_hpp */
| [
"cykevinsun@gmail.com"
] | cykevinsun@gmail.com |
f8f4c514069d4d30651a9860ede0833ebeedc38b | 6dc5f480c3dcad8693726cbfa24cba66b6cb3184 | /src/rtk_sub_node.cpp | fc931a90cf8ea5d766081fda6e7fc82e79e9268c | [] | no_license | climb0079climb0079/rtk_driver | a821be3ce2f1966a257475891897b1361160418d | be65b7e016648701049198c53be7cebfddca2743 | refs/heads/master | 2022-09-29T11:45:12.460687 | 2020-06-05T06:36:10 | 2020-06-05T06:36:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 864 | cpp | #include "ros/ros.h"
#include "std_msgs/String.h"
#include "sensor_msgs/NavSatFix.h"
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
void gpsCallback(const sensor_msgs::NavSatFix& gps_msgs) {
//ROS_INFO("I heard time:[%ld], lat:[%lf], lng:[%lf], height[%lf]", gps_msgs.header.stamp, gps_msgs.longitude, gps_msgs.latitude, gps_msgs.altitude);
cout << std::setprecision(15) << gps_msgs.latitude << " " << gps_msgs.longitude << " " << gps_msgs.altitude << endl;
ofstream fs("/home/xl/rtk_pose_llh.txt", ios::app);
fs << std::setprecision(15) << gps_msgs.latitude << " " << gps_msgs.longitude << " " << gps_msgs.altitude << endl;
}
int main(int argc,char **argv) {
ros::init(argc, argv, "listener");
ros::NodeHandle n;
ros::Subscriber my_sub = n.subscribe("gps_pub",50, gpsCallback);
ros::spin();
return 0;
}
| [
"1393089237@qq.com"
] | 1393089237@qq.com |
fab914b9405043bdd859dbda2fd0561e99086c5b | ac1c9fbc1f1019efb19d0a8f3a088e8889f1e83c | /out/release/gen/third_party/blink/public/mojom/service_worker/service_worker_provider.mojom-shared.cc | 1d12cc8b9c9ed59d35be20b057168b934fb8a290 | [
"BSD-3-Clause"
] | permissive | xueqiya/chromium_src | 5d20b4d3a2a0251c063a7fb9952195cda6d29e34 | d4aa7a8f0e07cfaa448fcad8c12b29242a615103 | refs/heads/main | 2022-07-30T03:15:14.818330 | 2021-01-16T16:47:22 | 2021-01-16T16:47:22 | 330,115,551 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,767 | cc | // third_party/blink/public/mojom/service_worker/service_worker_provider.mojom-shared.cc is auto generated by mojom_bindings_generator.py, do not edit
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable:4065)
#endif
#include "third_party/blink/public/mojom/service_worker/service_worker_provider.mojom-shared.h"
#include <utility>
#include "base/logging.h"
#include "base/stl_util.h" // for base::size()
#include "mojo/public/cpp/bindings/lib/validate_params.h"
#include "mojo/public/cpp/bindings/lib/validation_context.h"
#include "mojo/public/cpp/bindings/lib/validation_errors.h"
#include "mojo/public/cpp/bindings/lib/validation_util.h"
#include "third_party/blink/public/mojom/service_worker/service_worker_provider.mojom-params-data.h"
namespace blink {
namespace mojom {
namespace internal {
// static
bool ServiceWorkerProviderInfoForClient_Data::Validate(
const void* data,
mojo::internal::ValidationContext* validation_context) {
if (!data)
return true;
if (!ValidateStructHeaderAndClaimMemory(data, validation_context))
return false;
// NOTE: The memory backing |object| may be smaller than |sizeof(*object)| if
// the message comes from an older version.
const ServiceWorkerProviderInfoForClient_Data* object = static_cast<const ServiceWorkerProviderInfoForClient_Data*>(data);
static constexpr struct {
uint32_t version;
uint32_t num_bytes;
} kVersionSizes[] = {{ 0, 24 }};
if (object->header_.version <=
kVersionSizes[base::size(kVersionSizes) - 1].version) {
// Scan in reverse order to optimize for more recent versions.
for (int i = base::size(kVersionSizes) - 1; i >= 0; --i) {
if (object->header_.version >= kVersionSizes[i].version) {
if (object->header_.num_bytes == kVersionSizes[i].num_bytes)
break;
ReportValidationError(
validation_context,
mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER);
return false;
}
}
} else if (object->header_.num_bytes <
kVersionSizes[base::size(kVersionSizes) - 1].num_bytes) {
ReportValidationError(
validation_context,
mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER);
return false;
}
if (!mojo::internal::ValidateHandleOrInterfaceNonNullable(
object->host_remote, 1, validation_context)) {
return false;
}
if (!mojo::internal::ValidateHandleOrInterface(object->host_remote,
validation_context)) {
return false;
}
if (!mojo::internal::ValidateHandleOrInterfaceNonNullable(
object->client_receiver, 2, validation_context)) {
return false;
}
if (!mojo::internal::ValidateHandleOrInterface(object->client_receiver,
validation_context)) {
return false;
}
return true;
}
ServiceWorkerProviderInfoForClient_Data::ServiceWorkerProviderInfoForClient_Data()
: header_({sizeof(*this), 0}) {}
// static
bool ServiceWorkerProviderInfoForStartWorker_Data::Validate(
const void* data,
mojo::internal::ValidationContext* validation_context) {
if (!data)
return true;
if (!ValidateStructHeaderAndClaimMemory(data, validation_context))
return false;
// NOTE: The memory backing |object| may be smaller than |sizeof(*object)| if
// the message comes from an older version.
const ServiceWorkerProviderInfoForStartWorker_Data* object = static_cast<const ServiceWorkerProviderInfoForStartWorker_Data*>(data);
static constexpr struct {
uint32_t version;
uint32_t num_bytes;
} kVersionSizes[] = {{ 0, 40 }};
if (object->header_.version <=
kVersionSizes[base::size(kVersionSizes) - 1].version) {
// Scan in reverse order to optimize for more recent versions.
for (int i = base::size(kVersionSizes) - 1; i >= 0; --i) {
if (object->header_.version >= kVersionSizes[i].version) {
if (object->header_.num_bytes == kVersionSizes[i].num_bytes)
break;
ReportValidationError(
validation_context,
mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER);
return false;
}
}
} else if (object->header_.num_bytes <
kVersionSizes[base::size(kVersionSizes) - 1].num_bytes) {
ReportValidationError(
validation_context,
mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER);
return false;
}
if (!mojo::internal::ValidateHandleOrInterfaceNonNullable(
object->host_remote, 1, validation_context)) {
return false;
}
if (!mojo::internal::ValidateHandleOrInterface(object->host_remote,
validation_context)) {
return false;
}
if (!mojo::internal::ValidateHandleOrInterface(object->script_loader_factory_remote,
validation_context)) {
return false;
}
if (!mojo::internal::ValidateHandleOrInterface(object->cache_storage,
validation_context)) {
return false;
}
if (!mojo::internal::ValidateHandleOrInterfaceNonNullable(
object->browser_interface_broker, 4, validation_context)) {
return false;
}
if (!mojo::internal::ValidateHandleOrInterface(object->browser_interface_broker,
validation_context)) {
return false;
}
return true;
}
ServiceWorkerProviderInfoForStartWorker_Data::ServiceWorkerProviderInfoForStartWorker_Data()
: header_({sizeof(*this), 0}) {}
// static
bool ServiceWorkerWorkerClient_OnControllerChanged_Params_Data::Validate(
const void* data,
mojo::internal::ValidationContext* validation_context) {
if (!data)
return true;
if (!ValidateStructHeaderAndClaimMemory(data, validation_context))
return false;
// NOTE: The memory backing |object| may be smaller than |sizeof(*object)| if
// the message comes from an older version.
const ServiceWorkerWorkerClient_OnControllerChanged_Params_Data* object = static_cast<const ServiceWorkerWorkerClient_OnControllerChanged_Params_Data*>(data);
static constexpr struct {
uint32_t version;
uint32_t num_bytes;
} kVersionSizes[] = {{ 0, 16 }};
if (object->header_.version <=
kVersionSizes[base::size(kVersionSizes) - 1].version) {
// Scan in reverse order to optimize for more recent versions.
for (int i = base::size(kVersionSizes) - 1; i >= 0; --i) {
if (object->header_.version >= kVersionSizes[i].version) {
if (object->header_.num_bytes == kVersionSizes[i].num_bytes)
break;
ReportValidationError(
validation_context,
mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER);
return false;
}
}
} else if (object->header_.num_bytes <
kVersionSizes[base::size(kVersionSizes) - 1].num_bytes) {
ReportValidationError(
validation_context,
mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER);
return false;
}
if (!::blink::mojom::internal::ControllerServiceWorkerMode_Data
::Validate(object->mode, validation_context))
return false;
return true;
}
ServiceWorkerWorkerClient_OnControllerChanged_Params_Data::ServiceWorkerWorkerClient_OnControllerChanged_Params_Data()
: header_({sizeof(*this), 0}) {}
// static
bool ServiceWorkerWorkerClientRegistry_RegisterWorkerClient_Params_Data::Validate(
const void* data,
mojo::internal::ValidationContext* validation_context) {
if (!data)
return true;
if (!ValidateStructHeaderAndClaimMemory(data, validation_context))
return false;
// NOTE: The memory backing |object| may be smaller than |sizeof(*object)| if
// the message comes from an older version.
const ServiceWorkerWorkerClientRegistry_RegisterWorkerClient_Params_Data* object = static_cast<const ServiceWorkerWorkerClientRegistry_RegisterWorkerClient_Params_Data*>(data);
static constexpr struct {
uint32_t version;
uint32_t num_bytes;
} kVersionSizes[] = {{ 0, 16 }};
if (object->header_.version <=
kVersionSizes[base::size(kVersionSizes) - 1].version) {
// Scan in reverse order to optimize for more recent versions.
for (int i = base::size(kVersionSizes) - 1; i >= 0; --i) {
if (object->header_.version >= kVersionSizes[i].version) {
if (object->header_.num_bytes == kVersionSizes[i].num_bytes)
break;
ReportValidationError(
validation_context,
mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER);
return false;
}
}
} else if (object->header_.num_bytes <
kVersionSizes[base::size(kVersionSizes) - 1].num_bytes) {
ReportValidationError(
validation_context,
mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER);
return false;
}
if (!mojo::internal::ValidateHandleOrInterfaceNonNullable(
object->client, 1, validation_context)) {
return false;
}
if (!mojo::internal::ValidateHandleOrInterface(object->client,
validation_context)) {
return false;
}
return true;
}
ServiceWorkerWorkerClientRegistry_RegisterWorkerClient_Params_Data::ServiceWorkerWorkerClientRegistry_RegisterWorkerClient_Params_Data()
: header_({sizeof(*this), 0}) {}
// static
bool ServiceWorkerWorkerClientRegistry_CloneWorkerClientRegistry_Params_Data::Validate(
const void* data,
mojo::internal::ValidationContext* validation_context) {
if (!data)
return true;
if (!ValidateStructHeaderAndClaimMemory(data, validation_context))
return false;
// NOTE: The memory backing |object| may be smaller than |sizeof(*object)| if
// the message comes from an older version.
const ServiceWorkerWorkerClientRegistry_CloneWorkerClientRegistry_Params_Data* object = static_cast<const ServiceWorkerWorkerClientRegistry_CloneWorkerClientRegistry_Params_Data*>(data);
static constexpr struct {
uint32_t version;
uint32_t num_bytes;
} kVersionSizes[] = {{ 0, 16 }};
if (object->header_.version <=
kVersionSizes[base::size(kVersionSizes) - 1].version) {
// Scan in reverse order to optimize for more recent versions.
for (int i = base::size(kVersionSizes) - 1; i >= 0; --i) {
if (object->header_.version >= kVersionSizes[i].version) {
if (object->header_.num_bytes == kVersionSizes[i].num_bytes)
break;
ReportValidationError(
validation_context,
mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER);
return false;
}
}
} else if (object->header_.num_bytes <
kVersionSizes[base::size(kVersionSizes) - 1].num_bytes) {
ReportValidationError(
validation_context,
mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER);
return false;
}
if (!mojo::internal::ValidateHandleOrInterfaceNonNullable(
object->host, 1, validation_context)) {
return false;
}
if (!mojo::internal::ValidateHandleOrInterface(object->host,
validation_context)) {
return false;
}
return true;
}
ServiceWorkerWorkerClientRegistry_CloneWorkerClientRegistry_Params_Data::ServiceWorkerWorkerClientRegistry_CloneWorkerClientRegistry_Params_Data()
: header_({sizeof(*this), 0}) {}
} // namespace internal
} // namespace mojom
} // namespace blink
#if defined(_MSC_VER)
#pragma warning(pop)
#endif | [
"xueqi@zjmedia.net"
] | xueqi@zjmedia.net |
9cba702b44cf2d38d965a805c7676d9951d7cf98 | 5d15e7dfba2b8d6b9a8bb14973d4907b753d3ab9 | /Lab5/Controller.h | a91f9ba1cc41beb17a94bb4d44a86cebc8ac266c | [] | no_license | giurgiumatei/Object-Oriented-Programming | b7957c9e14711ec4910563104d114a70d874b9b2 | 2ab019f1b7f9aaa03b634453fbe2ac2914320923 | refs/heads/main | 2023-03-10T00:14:25.892419 | 2021-02-22T14:53:57 | 2021-02-22T14:53:57 | 341,146,129 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 598 | h | #pragma once
#include "Repository.h"
class Controller
{
private:
Repository repository;
public:
Controller(Repository repository) :repository{ repository } {}
bool add_movie_controller(string title, string genre,unsigned int year_of_release,unsigned int likes, string trailer);
bool remove_movie_controller(string title);
bool update_movie_controller(string title, string genre,unsigned int year_of_release,unsigned int likes, string trailer);
DynamicVector<Movie> get_data_controller()
{
return this->repository.get_data_repository();
}
}; | [
"noreply@github.com"
] | giurgiumatei.noreply@github.com |
df3612facfc6218f65a273eb6cb54840c50ada01 | f3941393ecaa96f8a55ef0cee84e5b174cf44715 | /devel/include/industrial_msgs/StopMotionResponse.h | 2a785cbbfce4e960897ef507cc62f1d037953a04 | [] | no_license | BareSteffen/ROSGRP6 | d46c7de97a732adf66b88986dfec3529c8fdbbaa | aa5f11d0118cf071e43a068c0ee07ae98ec0f04e | refs/heads/master | 2023-01-29T02:00:38.403893 | 2020-12-16T09:24:03 | 2020-12-16T09:24:03 | 321,366,070 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,985 | h | // Generated by gencpp from file industrial_msgs/StopMotionResponse.msg
// DO NOT EDIT!
#ifndef INDUSTRIAL_MSGS_MESSAGE_STOPMOTIONRESPONSE_H
#define INDUSTRIAL_MSGS_MESSAGE_STOPMOTIONRESPONSE_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
#include <industrial_msgs/ServiceReturnCode.h>
namespace industrial_msgs
{
template <class ContainerAllocator>
struct StopMotionResponse_
{
typedef StopMotionResponse_<ContainerAllocator> Type;
StopMotionResponse_()
: code() {
}
StopMotionResponse_(const ContainerAllocator& _alloc)
: code(_alloc) {
(void)_alloc;
}
typedef ::industrial_msgs::ServiceReturnCode_<ContainerAllocator> _code_type;
_code_type code;
typedef boost::shared_ptr< ::industrial_msgs::StopMotionResponse_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::industrial_msgs::StopMotionResponse_<ContainerAllocator> const> ConstPtr;
}; // struct StopMotionResponse_
typedef ::industrial_msgs::StopMotionResponse_<std::allocator<void> > StopMotionResponse;
typedef boost::shared_ptr< ::industrial_msgs::StopMotionResponse > StopMotionResponsePtr;
typedef boost::shared_ptr< ::industrial_msgs::StopMotionResponse const> StopMotionResponseConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::industrial_msgs::StopMotionResponse_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::industrial_msgs::StopMotionResponse_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace industrial_msgs
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False}
// {'industrial_msgs': ['/home/ros/catkin_ws/src/industrial_core/industrial_msgs/msg'], 'trajectory_msgs': ['/opt/ros/kinetic/share/trajectory_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::industrial_msgs::StopMotionResponse_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::industrial_msgs::StopMotionResponse_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::industrial_msgs::StopMotionResponse_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::industrial_msgs::StopMotionResponse_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::industrial_msgs::StopMotionResponse_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::industrial_msgs::StopMotionResponse_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::industrial_msgs::StopMotionResponse_<ContainerAllocator> >
{
static const char* value()
{
return "50b1f38f75f5677e5692f3b3e7e1ea48";
}
static const char* value(const ::industrial_msgs::StopMotionResponse_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x50b1f38f75f5677eULL;
static const uint64_t static_value2 = 0x5692f3b3e7e1ea48ULL;
};
template<class ContainerAllocator>
struct DataType< ::industrial_msgs::StopMotionResponse_<ContainerAllocator> >
{
static const char* value()
{
return "industrial_msgs/StopMotionResponse";
}
static const char* value(const ::industrial_msgs::StopMotionResponse_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::industrial_msgs::StopMotionResponse_<ContainerAllocator> >
{
static const char* value()
{
return "industrial_msgs/ServiceReturnCode code\n\
\n\
\n\
================================================================================\n\
MSG: industrial_msgs/ServiceReturnCode\n\
# Service return codes for simple requests. All ROS-Industrial service\n\
# replies are required to have a return code indicating success or failure\n\
# Specific return codes for different failure should be negative.\n\
int8 val\n\
\n\
int8 SUCCESS = 1\n\
int8 FAILURE = -1\n\
\n\
";
}
static const char* value(const ::industrial_msgs::StopMotionResponse_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::industrial_msgs::StopMotionResponse_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.code);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct StopMotionResponse_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::industrial_msgs::StopMotionResponse_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::industrial_msgs::StopMotionResponse_<ContainerAllocator>& v)
{
s << indent << "code: ";
s << std::endl;
Printer< ::industrial_msgs::ServiceReturnCode_<ContainerAllocator> >::stream(s, indent + " ", v.code);
}
};
} // namespace message_operations
} // namespace ros
#endif // INDUSTRIAL_MSGS_MESSAGE_STOPMOTIONRESPONSE_H
| [
"steffenlarsen78@gmail.com"
] | steffenlarsen78@gmail.com |
f2b04e88a23488252d9734bea5fac34ff476caf1 | a4253c9ba4d188969daca9a180a61ce631741965 | /old codes/_290104_UGVcontroler7/OperationMode.ino | 8b8af998ac917719a1c0c6e416559d9674f2f901 | [
"BSD-3-Clause"
] | permissive | KTD-prototype/Lambda | 7e52310325526c01ebb12fd23dd256801b821358 | ca45bb8d68251b7871e5edf58253b76f0898d272 | refs/heads/master | 2020-04-29T18:42:40.361967 | 2019-04-14T12:53:04 | 2019-04-14T12:53:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,365 | ino | /*
ロボットからの返答に基づき、ロボットの動作モードを判定
*/
void OperationMode(byte value) {
switch (value) {
case 0:
lcd.setCursor(0, 0);
lcd.println("mode : stop");
lcd.setCursor(0, 1);
lcd.println(" ");
break;
case 1:
lcd.setCursor(0, 0);
lcd.print("mode : remote");
lcd.setCursor(0, 1);
lcd.println(RMotor1);
lcd.setCursor(4, 1);
lcd.println(RMotor2);
lcd.setCursor(8, 1);
lcd.println(LMotor1);
lcd.setCursor(12, 1);
lcd.println(LMotor2);
break;
case 2:
lcd.setCursor(0, 0);
lcd.println("mode : stop");
lcd.setCursor(0, 1);
lcd.println(" ");
break;
case 3:
/*
if (JOY_send.read() == 'H') {
low = JOY_send.read();
high = JOY_send.read();
faceX = makeWord(high, low);
}
else{
faceX = JOY_send.read();
}
if (JOY_send.read() == 'H') {
low = JOY_send.read();
high = JOY_send.read();
faceY = makeWord(high, low);
}
else{
faceY = JOY_send.read();
}
*/
lcd.setCursor(0, 0);
lcd.println("mode : auto");
/*
lcd.setCursor(0, 1);
lcd.println(faceX);
lcd.setCursor(5, 1);
lcd.println(faceY);
*/
break;
case 'S':
lcd.println("S");
break;
default:
lcd.println("wait");
}
}
/*
モータードライバへの指令値をプリントアウト
もっと直感的にわかりやすい数字にしたいなあ。。。
*/
void PrintMotor(int value1, int value2, int value3, int value4) {
Serial.print(value1);
Serial.print(" || ");
Serial.print(value2);
Serial.print(" || ");
Serial.print(value3);
Serial.print(" || ");
Serial.print(value4);
Serial.print(" || ");
}
/*
ジョイスティックの読み取りデータ(を4で割ったもの)を出力
*/
void PrintJOYsignal(int val1, int val2, int val3, int val4, int val5, int val6) {
Serial.print(val1);
Serial.print(" || ");
Serial.print(val2);
Serial.print(" || ");
Serial.print(val3);
Serial.print(" || ");
Serial.print(val4);
Serial.print(" || ");
Serial.print(val5);
Serial.print(" || ");
Serial.print(val6);
Serial.println("");
}
| [
"hozu.kazu.hozu@gmail.com"
] | hozu.kazu.hozu@gmail.com |
69191c2683872ab1447c7069272b20ed5d7dd427 | 7e896ad5558f838c89c65ab9d6559b35071acd27 | /P04/Source/Datos/Delincuente.cpp | 8df9a3aaadaf7b94faa79d1be8b572a87f1c566b | [
"MIT"
] | permissive | gorkinovich/LP2 | 6aa17d797ca377447070d997a695758f20376af1 | a756b2e064a29a7f624885299c082e9c02e384ea | refs/heads/master | 2022-06-17T01:43:47.641358 | 2022-06-08T14:09:30 | 2022-06-08T14:09:30 | 49,684,302 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 2,280 | cpp | //----------------------------------------------------------------------
// Gorka Suárez García - Ing. Tec. Inf. de Gestión 2º B.
// Práctica 04 - Grupo 03.
//----------------------------------------------------------------------
#pragma hdrstop
#include "Delincuente.h"
#pragma package(smart_init)
Delincuente::Delincuente ()
{
this->delitosCometidos = new ListaOrdenada<Delitos>();
this->delitosConcretos = new ListaOrdenada<std::string>();
}
Delincuente::Delincuente (std::string id, std::string nombre, CaraComun * cara,
ListaOrdenada<Delitos> * cometidos,
ListaOrdenada<std::string> * concretos)
: Persona (id, nombre, cara)
{
this->delitosCometidos = cometidos;
this->delitosConcretos = concretos;
}
Delincuente::Delincuente (const Delincuente & obj)
{
this->CopyFrom(obj);
}
Delincuente::~Delincuente ()
{
if(this->delitosCometidos != NULL)
delete this->delitosCometidos;
if(this->delitosConcretos != NULL)
delete this->delitosConcretos;
}
void Delincuente::CopyFrom (const Delincuente & obj)
{
*(this->delitosCometidos) = *(obj.delitosCometidos);
*(this->delitosConcretos) = *(obj.delitosConcretos);
this->Persona::CopyFrom(obj);
}
Persona & Delincuente::operator = (const Persona & obj)
{
this->CopyFrom((Delincuente &) obj);
return (*this);
}
Delincuente & Delincuente::operator = (const Delincuente & obj)
{
this->CopyFrom(obj);
return (*this);
}
bool Delincuente::estaDelitosCometidos (const Delito unDelito) const
{
Delitos aux(unDelito);
return this->delitosCometidos->estaElemento(aux);
}
ListaOrdenada<Delitos> * Delincuente::getDelitosCometidos (void)
{
return this->delitosCometidos;
}
ListaOrdenada<std::string> * Delincuente::getDelitosConcretos (void)
{
return this->delitosConcretos;
}
void Delincuente::setDelitosCometidos (ListaOrdenada<Delitos> * delitos)
{
if(this->delitosCometidos != NULL)
delete this->delitosCometidos;
this->delitosCometidos = delitos;
}
void Delincuente::setDelitosConcretos (ListaOrdenada<std::string> * delitos)
{
if(this->delitosConcretos != NULL)
delete this->delitosConcretos;
this->delitosConcretos = delitos;
}
void Delincuente::setCara (CaraComun * cara)
{
this->Persona::setCara(cara);
} | [
"alexander.lessman@gmail.com"
] | alexander.lessman@gmail.com |
b75a78fb2024d5ae4436e16dc19b05b4a646e044 | 21ed6143340b9ab7f9c5937898f65b9914c0d6c0 | /include/Thread/ACond.hh | 6bef73576ba10aff142e76f111e9dba171f71594 | [] | no_license | guitehub/tek2-cpp_bomberman | 71486f8edd58778a5b11c6a112eb7e35bf47439c | d4a74ef32072269c841d5a1bf2a1a0f6d2a7b56f | refs/heads/master | 2022-09-09T12:18:10.440460 | 2020-04-19T14:56:08 | 2020-04-19T14:56:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 723 | hh | //
// ACond.hh for bomber in /home/chanut_g/rendu/cpp_bomberman/include/Thread
//
// Made by Guillaume
// Login <chanut_g@epitech.net>
//
// Started on Mon May 26 15:50:45 2014 Guillaume
// Last update Mon May 26 15:51:00 2014 Guillaume
//
#ifndef ACOND_HH_
# define ACOND_HH_
class ACond
{
protected:
bool _isLock;
bool _isInit;
public:
ACond();
virtual ~ACond() {}
virtual void create(void) = 0;
virtual void destroy(void) = 0;
virtual void wait(void) = 0;
virtual int waitTimer(long) = 0;
virtual void signal(void) = 0;
virtual void broadcast(void) = 0;
virtual void unlock(void) = 0;
virtual bool getIsInit(void) const;
virtual bool getIsLock(void) const;
};
#endif
| [
"guillaume.p.chanut@gmail.com"
] | guillaume.p.chanut@gmail.com |
d2799e4c6e25309adc50b74ff774d3d7a6c0a490 | 7601f733578ce0a7017d13579ae32bd666327436 | /PixelConfigDBInterface/include/PixelConfigInterface.h | 7248fb05d8e5745a14734a10f986fd7a8a725b72 | [] | no_license | radtek/PixelOnlineSoftware | 03c50f9cda443f95b83b2f5709edeb39e4cad148 | 7a7ae00f724df4998135f3176db60dfc81cfeb3b | refs/heads/master | 2021-02-26T12:08:27.890083 | 2015-08-20T21:38:35 | 2015-08-20T21:38:35 | 245,524,297 | 1 | 0 | null | 2020-03-06T22:01:13 | 2020-03-06T22:01:12 | null | UTF-8 | C++ | false | false | 39,055 | h | #ifndef PixelConfigInterface_h
#define PixelConfigInterface_h
/*
$Author: menasce $
$Date: 2009/11/17 15:12:22 $
$Revision: 1.77 $
*/
#include <stdlib.h>
#include <iostream>
#include <string>
#include <set>
#include "PixelConfigDBInterface/include/PixelConfigDBInterface.h" // was DB
#include "CalibFormats/SiPixelObjects/interface/PixelTimeFormatter.h"
#include "CalibFormats/SiPixelObjects/interface/PixelConfigFile.h"
#include "CalibFormats/SiPixelObjects/interface/PixelConfigKey.h"
#include "CalibFormats/SiPixelObjects/interface/PixelConfigDoc.info"
#include <cstdlib>
//typedef int PixelConfigKey;
/*template <class K> */
/*! \defgroup AbstractConfigurationInterface "Configuration Objects Interface"
* \brief The class describing an abstact interface to the "Configuration Objects".
*
* Configuration Objects represent the knowledge of the whole CMS Pixel %Detector at
* any given time. This knowledge is made persistent in two alternative ways:<br/>
* <ul>
* <li> a file-based set of configurations, stored in an appropriate hierarchy of
* folders, indexed by a main "configuration key"
* <li> a full fledged Oracle Database, were the %Detector status is represented by
* a complex set of relational tables.
* </ul>
* The "Configuration Objects Interface" encompasses both of these persistency methodologies.
* In particular ...
*
* @{
* \class PixelConfigInterface PixelConfigInterface.h "interface/PixelConfigInterface.h"
* \brief The concrete class describing the "file-based configuration" interface
*/
class PixelConfigInterface {
public:
PixelConfigInterface(){getMode();}
PixelConfigInterface(bool mode){setMode(mode);}
//==============================================================================
static void setMode(bool m)
{
//cout << __LINE__ << "]\t[PixelConfigInterface::setMode()]\t\t " << endl ;
if(getMode() != m)
{
getMode() = m;
if(getMode() == true)
{
pixelConfigDB().connect();
}
else
{
pixelConfigDB().disconnect();
}
}
}
//==============================================================================
static void setKeyAlias(pos::PixelConfigKey key, std::string theAlias)
{
if(getMode())
{
pixelConfigDB().setKeyAlias(key, theAlias);
}
else
{;}
}
//==============================================================================
static void setGlobalKey(pos::PixelConfigKey key)
{
if(getGlobalKey().key() != key.key())
{
getGlobalKey() = key;
}
}
//==============================================================================
template <class T>
static void get(T* &pixelObject,
std::string path,
pos::PixelConfigKey key)
{
std::string mthn = "[PixelConfigInterface.h::get(scalar)]\t\t\t " ;
std::stringstream arg ; arg << "PixelConfigInterface::get(T*) T=" << typeid(pixelObject).name() ;
pos::PixelTimeFormatter * timer = new pos::PixelTimeFormatter(arg.str()) ;
setGlobalKey(key) ;
if(getMode())
{
pixelConfigDB().connect();
pixelConfigDB().get(pixelObject,path,key);
}
else
{
pos::PixelConfigFile::get(pixelObject,path,key);
}
timer->stopTimer() ;
delete timer ;
}
//==============================================================================
template <class T>
static void get(T* &pixelObject,std::string path,unsigned int version)
{
if(getMode())
{
//pixelConfigDB().connect();
pixelConfigDB().getByVersion(pixelObject,path,version);
}
else{
pos::PixelConfigFile::get(pixelObject,path,version);
}
}
//==============================================================================
template <class T>
static void get(std::map<std::string, T*> &objects,pos::PixelConfigKey key)
{
setGlobalKey(key) ;
std::stringstream arg ; arg << "PixelConfigInterface::get(map<string,T*>) T=" << typeid(objects).name() ;
pos::PixelTimeFormatter * timer = new pos::PixelTimeFormatter(arg.str()) ;
if(getMode())
{
pixelConfigDB().get(objects, key) ;
}
else
{
pos::PixelConfigFile::get(objects,key);
}
timer->stopTimer() ;
delete timer ;
}
//==============================================================================
template <class T>
static bool configurationDataExists(T* &pixelObject,
std::string path,
pos::PixelConfigKey key)
{
std::stringstream arg ; arg << "PixelConfigInterface::configurationDataExists(T*) T=" << typeid(pixelObject).name() ;
pos::PixelTimeFormatter * timer = new pos::PixelTimeFormatter(arg.str()) ;
bool retStatus = false ;
if(getMode())
{
retStatus = pixelConfigDB().configurationDataExists(pixelObject,path,key);
}
else
{
retStatus = pos::PixelConfigFile::configurationDataExists(pixelObject,path,key);
}
timer->stopTimer() ;
delete timer ;
return retStatus ;
}
//==============================================================================
static std::vector<std::pair<std::string, unsigned int> > getAliases()
{
std::string mthn = "]\t[PixelConfigInterface::getAliases()]\t\t\t " ;
pos::PixelTimeFormatter * timer = new pos::PixelTimeFormatter("PixelConfigInterface::getAliases()") ;
std::vector<std::pair<std::string, unsigned int> > aliases ;
if(getMode())
{
if( DEBUG_CONFIG_DB ) cout << __LINE__ << mthn << "Using DataBase connection" << endl ;
aliases = pixelConfigDB().getAliases() ;
}
else
{
if( DEBUG_CONFIG_DB ) cout << __LINE__ << mthn << "Using files " << endl ;
aliases = pos::PixelConfigFile::getAliases();
}
timer->stopTimer() ;
delete timer ;
return aliases ;
}
//==============================================================================
static std::vector<std::vector<std::string> > getAliasesWithCommentsAndDate()
{
std::string mthn = "]\t[PixelConfigInterface::getAliasesWithCommentsAndDate()]\t " ;
pos::PixelTimeFormatter * timer = new pos::PixelTimeFormatter("[PixelConfigInterface::getAliasesWithCommentsAndDate()]") ;
std::vector<std::vector<std::string > > aliases ;
if(getMode())
{
if( DEBUG_CONFIG_DB ) cout << __LINE__ << mthn << "Using DataBase connection" << endl ;
aliases = pixelConfigDB().getAliasesWithCommentsAndDate() ;
}
else
{
if( DEBUG_CONFIG_DB ) cout << __LINE__ << mthn << "Using files " << endl ;
vector<string> tmp ;
tmp.push_back("CONFIG_KEY_ID" ) ; // 0
tmp.push_back("CONFIG_KEY" ) ; // 1
tmp.push_back("KEY_ALIAS_ID" ) ; // 2
tmp.push_back("CONFIG_ALIAS" ) ; // 3
tmp.push_back("CONFIG_KEY_TYPE" ) ; // 4
tmp.push_back("RECORD_INSERTION_TIME") ; // 5
tmp.push_back("COMMENT_DESCRIPTION" ) ; // 6
tmp.push_back("PROVENANCE" ) ; // 7
tmp.push_back("AUTHOR" ) ; // 8
aliases.push_back(tmp) ;
std::vector<std::pair<std::string, unsigned int> > aliasesNoCommentsAndDate = pos::PixelConfigFile::getAliases();
for(std::vector<std::pair<std::string, unsigned int> >::iterator it = aliasesNoCommentsAndDate.begin();
it != aliasesNoCommentsAndDate.end() ; it++)
{
tmp.clear() ;
stringstream ss ;
ss.str("") ;
ss << it->second ;
tmp.push_back("Unavailable for files") ; // 0 CONFIG_KEY_ID, fake for files
tmp.push_back(ss.str()) ; // 1 CONFIG_KEY, GLOBAL KEY NUMBER
tmp.push_back("Unavailable for files") ; // 2 KEY_ALIAS_ID, fake for files
tmp.push_back(it->first) ; // 3 CONFIG_KEY_ALIAS, Alias
tmp.push_back("Unavailable for files") ; // 4 CONFIG_KEY_TYPE, fake for files
tmp.push_back("01/01/1970 00:00:00") ; // 5 RECORD_INSERTION_TYPE, fake for files
tmp.push_back("Q29tbWVudHMgYXJlIHVuYXZhaWxhYmxlIGZvciBmaWxlcw==") ; // 6 COMMENT_DESCRIPTION, fake for files (base64 encoded)
tmp.push_back("Provenance unavailable for files") ; // 7 PROVENANCE, fake for files
tmp.push_back("Author is unavailable for files") ; // 8 AUTHOR, fake for files
aliases.push_back(tmp) ;
}
}
timer->stopTimer() ;
delete timer ;
return aliases ;
}
//==============================================================================
static bool getVersionAliases(std::string configAlias,
unsigned int &key,
std::vector<std::pair<std::string,std::string> > &versionAliases)
{
pos::PixelTimeFormatter * timer = new pos::PixelTimeFormatter("PixelConfigInterface::getVersionAliases()") ;
bool retStatus = false ;
if(getMode())
{
retStatus = pixelConfigDB().getVersionAliases(configAlias, key, versionAliases) ;
}
else
{
retStatus = pos::PixelConfigFile::getVersionAliases(configAlias,
key,
versionAliases);
}
timer->stopTimer() ;
delete timer ;
return retStatus ;
}
//==============================================================================
static void forceAliasesReload(bool mode)
{
if(getMode())
{
cout << __LINE__ << "]\t[PixelConfigInterface::forceAliasesReload()]\t\t No such function implemented yet for DB access" << endl ;
}
else
{
pos::PixelConfigFile::forceAliasesReload(mode);
}
}
//==============================================================================
static std::map<std::string, unsigned int> getAliases_map()
{
pos::PixelTimeFormatter * timer = new pos::PixelTimeFormatter("PixelConfigInterface::getAliases_map()") ;
std::map<std::string, unsigned int> aliasMap ;
if(getMode())
{
aliasMap = pixelConfigDB().getAliases_map() ;
}
else
{
aliasMap = pos::PixelConfigFile::getAliases_map();
}
timer->stopTimer() ;
delete timer ;
return aliasMap ;
}
//==============================================================================
static void addAlias(std::string alias, unsigned int key)
{
pos::PixelTimeFormatter * timer = new pos::PixelTimeFormatter("PixelConfigInterface::addAlias(string,unsigned int)") ;
if(getMode())
{
pixelConfigDB().addAlias(alias, key) ;
}
else
{
pos::PixelConfigFile::addAlias(alias,key);
}
timer->stopTimer() ;
delete timer ;
return ;
}
//==============================================================================
static void addAlias(std::string alias, unsigned int key,
std::vector<std::pair<std::string, std::string> > versionaliases)
{
pos::PixelTimeFormatter * timer = new pos::PixelTimeFormatter("PixelConfigInterface::addAlias(string,unsigned int,vector)") ;
if(getMode())
{
pixelConfigDB().addAlias(alias,key,versionaliases);
}
else
{
pos::PixelConfigFile::addAlias(alias,key,versionaliases);
}
timer->stopTimer() ;
delete timer ;
return ;
}
//==============================================================================
static void addVersionAlias(std::string path, unsigned int version, std::string alias)
{
pos::PixelTimeFormatter * timer = new pos::PixelTimeFormatter("PixelConfigInterface::addVersionAlias()") ;
if(getMode())
{
pixelConfigDB().addVersionAlias(path, version, alias) ;
}
else
{
pos::PixelConfigFile::addVersionAlias(path,version,alias);
}
timer->stopTimer() ;
delete timer ;
return ;
}
//==============================================================================
static void addComment(std::string comment)
{
pos::PixelTimeFormatter * timer = new pos::PixelTimeFormatter("PixelConfigInterface::addComment(string)") ;
if(getMode())
{
pixelConfigDB().addComment( comment) ;
}
else
{
std::cout << __LINE__ << "]\t[PixelConfigInterface::addComment()]\t\t Not implemented for file-based repository" << std::endl ;
}
timer->stopTimer() ;
delete timer ;
return ;
}
//==============================================================================
static void addAuthor(std::string author)
{
pos::PixelTimeFormatter * timer = new pos::PixelTimeFormatter("PixelConfigInterface::addAuthor(string)") ;
if(getMode())
{
pixelConfigDB().addAuthor( author) ;
}
else
{
std::cout << __LINE__ << "]\t[PixelConfigInterface::addAuthor()]\t\t Not implemented for file-based repository" << std::endl ;
}
timer->stopTimer() ;
delete timer ;
return ;
}
//==============================================================================
static unsigned int clone(unsigned int oldkey, std::string path, unsigned int version)
{
unsigned int newkey ;
pos::PixelTimeFormatter * timer = new pos::PixelTimeFormatter("PixelConfigInterface::clone()") ;
if(getMode())
{
newkey = pixelConfigDB().clone(oldkey, path, version) ;
}
else
{
pos::PixelConfigList iList = pos::PixelConfigFile::getConfig() ;
newkey = iList.clone(oldkey,path,version);
iList.writefile() ;
}
timer->stopTimer() ;
delete timer ;
return newkey ;
}
//==============================================================================
static unsigned int makeKey(std::vector<std::pair<std::string, unsigned int> > versions)
{
unsigned int newkey ;
pos::PixelTimeFormatter * timer = new pos::PixelTimeFormatter("PixelConfigInterface::makeKey()") ;
if(getMode())
{
newkey = pixelConfigDB().makeKey(versions);
}
else
{
newkey = pos::PixelConfigFile::makeKey(versions);
}
timer->stopTimer() ;
delete timer ;
return newkey ;
}
//==============================================================================
static unsigned int getVersion(std::string path,std::string alias)
{
if(getMode())
{
pos::pathVersionAliasMmap vData ;
vData = pixelConfigDB().getVersionData() ;
for(pos::pathVersionAliasMmap::iterator it = vData.begin() ; it != vData.end() ; it++)
{
/* cout << "|" << it->first << "|\t" */
/* << "|" << path << "|" << endl ; */
if(it->first == path)
{
for(pos::vectorVAPairs::iterator va = it->second.begin() ; va != it->second.end() ; va++)
{
/* cout << "|" << va->second << "|\t" */
/* << "|" << alias << "|" << endl ; */
if(va->second == alias)
return va->first ;
}
}
}
std::cout << __LINE__ << "]\t[PixelConfigInterface::getVersion(path, alias)]\t Fatal, no version found for path "
<< "|" << path << "|" << " and alias |" << alias << "|" << std::endl ;
assert(0) ;
}
else
{
return pos::PixelConfigFile::getVersion(path, alias);
}
}
//==============================================================================
//Returns the different objects and their versions for a given configuration
static std::vector<std::pair< std::string, unsigned int> > getVersions(pos::PixelConfigKey key)
{
pos::PixelTimeFormatter * timer = new pos::PixelTimeFormatter("PixelConfigInterface::getVersions()") ;
std::vector<std::pair< std::string, unsigned int> > versions ;
if(getMode())
{
versions = pixelConfigDB().getVersions(key) ;
}
else
{
versions = pos::PixelConfigFile::getVersions(key);
}
timer->stopTimer() ;
delete timer ;
return versions ;
}
//==============================================================================
static std::vector<std::vector< std::string> > getVersionsWithCommentsAndDate(pos::PixelConfigKey key)
{
/**
View: CMS_PXL_PIXEL_VIEW_OWNER.CONF_KEY_DATASET_MAP_V
Name Null? Type
0 CONFIG_KEY_ID NOT NULL NUMBER(38)
1 KEY_NAME NOT NULL VARCHAR2(80)
2 CONDITION_DATA_SET_ID NOT NULL NUMBER(38)
3 KIND_OF_CONDITION_ID NOT NULL NUMBER(38)
4 KIND_OF_CONDITION_NAME NOT NULL VARCHAR2(40)
5 CONDITION_VERSION VARCHAR2(40)
6 IS_MOVED_TO_HISTORY NOT NULL CHAR(1)
7 INSERTI_TIME
8 COMMENT_DESCRIPTION
9 AUTHOR
*/
std::string mthn = "]\t[PixelConfigInterface::getVersionsWithCommentsAndDate()]\t " ;
pos::PixelTimeFormatter * timer = new pos::PixelTimeFormatter("PixelConfigInterface::getVersionsWithCommentsAndDate()") ;
std::vector<std::vector< std::string> > versions ;
if(getMode())
{
versions = pixelConfigDB().getVersionsWithCommentsAndDate(key) ;
}
else
{
std::vector<std::pair< std::string, unsigned int> > versionsPartial ;
vector<string> header,tmp ;
header.push_back("CONFIG_KEY_ID");
header.push_back("KEY_NAME");
header.push_back("CONDITION_DATA_SET_ID");
header.push_back("KIND_OF_CONDITION_ID");
header.push_back("KIND_OF_CONDITION_NAME");
header.push_back("CONDITION_VERSION");
header.push_back("IS_MOVED_TO_HISTORY");
header.push_back("INSERT_TIME");
header.push_back("COMMENT_DESCRIPTION");
header.push_back("AUTHOR");
versions.push_back(header) ;
versionsPartial = pos::PixelConfigFile::getVersions(key);
for(std::vector<std::pair<std::string, unsigned int> >::iterator it = versionsPartial.begin();
it != versionsPartial.end() ; it++)
{
tmp.clear() ;
stringstream ss ;
ss.str("") ;
tmp.push_back("fake") ; // CONFIG_KEY_ID
tmp.push_back("fake") ; // KEY_NAME
tmp.push_back("fake") ; // CONDITION_DATA_SET_ID
tmp.push_back("fake") ; // KIND_OF_CONDITION_ID
tmp.push_back(it->first) ; // KIND_OF_CONDITION_NAME
ss << it->second ; //
tmp.push_back(ss.str()) ; // CONDITION_VERSION
tmp.push_back("fake") ; // IS_MOVED_TO_HISTORY
tmp.push_back("01/01/1970 00:00:00") ; // RECORD_INSERTION_TIME
tmp.push_back("Q29tbWVudHMgYXJlIHVuYXZhaWxhYmxlIGZvciBmaWxlcw==") ; // COMMENT_DESCRIPTION base64_encode("Comments are unavailable for files")
tmp.push_back("Author is unavailable for files") ; // AUTHOR "QXV0aG9yIGlzIHVuYXZhaWxhYmxlIGZvciBmaWxlcw=="
versions.push_back(tmp) ;
}
}
timer->stopTimer() ;
delete timer ;
return versions ;
}
//==============================================================================
//Returns the different objects and their versions for a given configuration
static std::map<std::string,std::vector<std::pair< std::string, unsigned int> > > getFullVersions()
{
pos::PixelTimeFormatter * timer = new pos::PixelTimeFormatter("PixelConfigInterface::getFullVersions()") ;
std::map<std::string,std::vector<std::pair< std::string, unsigned int> > > result ;
if(getMode())
{
return pixelConfigDB().getFullVersions() ;
}
else
{
std::vector <std::pair<std::string, unsigned int> > aList = pos::PixelConfigFile::getAliases();
for(std::vector<std::pair<std::string, unsigned int> >::iterator itKey=aList.begin(); itKey!=aList.end(); itKey++ )
{
{
pos::PixelConfigKey globalKey((*itKey).second) ;
vector<pair<string, unsigned int> > vList = pos::PixelConfigFile::getVersions(globalKey) ;
std::stringstream keyString ;
keyString.str("") ;
keyString << globalKey.key() ;
result[keyString.str()] = vList ;
}
}
}
timer->stopTimer() ;
delete timer ;
return result ;
}
//==============================================================================
static std::map<std::string,std::vector<std::pair< std::string, std::string> > > getKeyAliasVersionAliases(int start, int howMany, int &total)
{
std::string mthn = "]\t[PixelConfigInterface::getKeyAliasVersionAliases()] " ;
pos::PixelTimeFormatter * timer = new pos::PixelTimeFormatter("PixelConfigInterface::getKeyAliasVersionAliases()") ;
std::map<std::string,std::vector<std::pair< std::string, std::string> > > result ;
if(getMode())
{
result = pixelConfigDB().getKeyAliasVersionAliases(start, howMany, total) ;
}
else
{
pos::PixelAliasList aList = pos::PixelConfigFile::getAlias() ;
total = aList.nAliases() ;
cout << __LINE__ << mthn << "Total aliases found: " << total << endl ;
std::map<std::string, std::vector<std::pair<std::string, std::string> > > serviceMap ;
for(int i = 0 ; i < total ; i++)
{
serviceMap[aList.name(i)] = aList.operator[](i).versionAliases() ;
std::cout << __LINE__ << mthn << i << "\t" << aList.name(i) << "\t" << aList.key(i) << std::endl ;
}
std::map<std::string, std::vector<std::pair<std::string, std::string> > >::iterator kakv_it = serviceMap.begin() ;
int count = 0 ;
for(; kakv_it != serviceMap.end() ; kakv_it++)
{
std::cout << __LINE__ << mthn << " " << (*kakv_it).first << " <- " << std::endl ;
if(count >= start && count < (start+howMany))
{
result[(*kakv_it).first] = (*kakv_it).second ;
}
count++ ;
}
}
timer->stopTimer() ;
delete timer ;
return result ;
}
//==============================================================================
static std::map<std::string,std::vector<std::string> > getKeyAliasVersionAliases(int &total)
{
std::string mthn = "]\t[PixelConfigInterface::getKeyAliasVersionAliases()] " ;
pos::PixelTimeFormatter * timer = new pos::PixelTimeFormatter("PixelConfigInterface::getKeyAliasVersionAliases(int&)") ;
std::map<std::string,std::vector<std::string> > result ;
if(getMode())
{
result = pixelConfigDB().getKeyAliasVersionAliases(total) ;
}
else
{
pos::PixelAliasList aList = pos::PixelConfigFile::getAlias() ;
total = aList.nAliases() ;
for(int i = 0 ; i < total ; i++)
{
std::vector<std::pair<std::string, std::string> > vaPair = aList.operator[](i).versionAliases() ;
for(std::vector<std::pair<std::string, std::string> >::iterator it=vaPair.begin(); it!=vaPair.end(); it++)
{
stringstream ss ;
result[aList.name(i)].push_back((*it).first ) ;
result[aList.name(i)].push_back((*it).second ) ;
result[aList.name(i)].push_back("1970, Jan 01 - 00:00:00" ) ;
result[aList.name(i)].push_back("Q29tbWVudHMgYXJlIHVuYXZhaWxhYmxlIGZvciBmaWxlcw==") ;
result[aList.name(i)].push_back("Author is not available for files" ) ;
ss.str("") ;
ss << aList.key(i) ;
result[aList.name(i)].push_back(ss.str()) ;
}
}
}
timer->stopTimer() ;
delete timer ;
return result ;
}
//==============================================================================
static std::map<unsigned int, std::vector<std::vector< std::string> > > getConfGivenKoc(std::map<std::string, std::string> kocs,
int start,
int howMany,
int from,
int to,
int &total)
{
std::string mthn = "]\t[PixelConfigInterface::getConfGivenKoc()]\t\t " ;
std::string mode = kocs["MODE"] ;
pos::PixelTimeFormatter * timer = new pos::PixelTimeFormatter("PixelConfigInterface::getConfGivenKoc()") ;
std::map<unsigned int, std::vector<std::vector< std::string> > > result ;
if(getMode())
{
std::map<std::string, std::string> query;
for(std::map<std::string, std::string>::iterator it=kocs.begin(); it!=kocs.end(); it++)
{
if( (*it).first == "start" ||
(*it).first == "limit" ||
(*it).first == "MODE" ||
(*it).second == "ANY" ) continue ;
query[(*it).first] = (*it).second ;
}
result = pixelConfigDB().getConfGivenKoc(query, start, howMany, from, to, total) ;
}
else
{
unsigned int expected = 0 ;
for(std::map<std::string, std::string>::iterator it=kocs.begin(); it!=kocs.end(); it++)
{
if( (*it).first != "start" &&
(*it).first != "limit" &&
(*it).first != "MODE" &&
(*it).second != "ANY" ) expected++ ;
}
static pos::PixelConfigList &list = pos::PixelConfigFile::getConfig() ;
total = list.size();
int counter = 0 ;
for(unsigned int key=0; key<(unsigned int)total; key++)
{
pos::PixelConfigKey globalKey(key) ;
vector<pair<string, unsigned int> > vList = pos::PixelConfigFile::getVersions(globalKey) ;
std::vector<std::vector< std::string> > newvList ;
bool accept = true ;
unsigned int found = 0 ;
for(vector<pair<string, unsigned int> >::iterator i=vList.begin(); i!=vList.end(); i++)
{
std::string fieldName = (*i).first ;
for(unsigned int k=0; k<fieldName.size(); k++)
{
fieldName[k] = std::toupper(fieldName[k]) ;
}
if( kocs[fieldName] == "ANY" || ( kocs[fieldName].size() > 0 &&
(unsigned int)atoi(kocs[fieldName].c_str()) == (*i).second) )
{
if( kocs[fieldName] != "ANY" && (unsigned int)atoi(kocs[fieldName].c_str()) == (*i).second) found++ ;
}
else
{
accept = false ;
}
//if( key == 6753 ) cout << __LINE__ << mthn << key << "]\t" << (*i).first << " --> " << kocs[fieldName] << endl ;
std::vector< std::string> tmp ;
std::stringstream s ; s << (*i).second ;
tmp.push_back("") ; // 0 CONFIG_KEY_ID
tmp.push_back("") ; // 1 KEY_NAME
tmp.push_back("") ; // 2 CONDITION_DATA_SET_ID
tmp.push_back("") ; // 3 KIND_OF_CONDITION_ID
tmp.push_back((*i).first) ; // 4 KIND_OF_CONDITION_NAME
tmp.push_back(s.str()) ; // 5 CONDITION_VERSION
tmp.push_back("") ; // 6 IS_MOVED_TO_HISTORY
tmp.push_back("") ; // 7 RECORD_INSERTION_TIME
tmp.push_back("") ; // 8 COMMENT_DESCRIPTION base46_encode("Comments are unavailable for files")
tmp.push_back("") ; // 9 AUTHOR
if( i == vList.begin() ) newvList.push_back(tmp) ; // Add a dummy record: this is to comply with DB version,
newvList.push_back(tmp) ; // where first vector element is actually a list of FIELD names
}
if( accept )
{
// cout << __LINE__ << mthn << key << "]\tmode: " << mode << endl ;
if( mode == "STRICT" )
{
if( found != expected )
{
// cout << __LINE__ << mthn << key << "]\tExpected: " << expected << " found: " << found << endl ;
continue ;
}
}
counter++ ;
if( counter < start || counter > start + howMany ) continue ;
// std::stringstream keyString ;
// keyString.str("") ;
// keyString << globalKey.key() ;
result[globalKey.key()] = newvList ;
}
}
}
timer->stopTimer() ;
delete timer ;
return result ;
}
//==============================================================================
static std::map<std::string,std::vector<std::vector< std::string> > > getFullCfgs(int start,
int howMany,
int from,
int to,
int &total)
{
std::string mthn = "]\t[PixelConfigInterface::getFullCfgs()]\t\t\t " ;
pos::PixelTimeFormatter * timer = new pos::PixelTimeFormatter("PixelConfigInterface::getFullCfgs()") ;
std::map<std::string,std::vector<std::vector< std::string> > > result ;
if(getMode())
{
result = pixelConfigDB().getFullCfgs(start, howMany, from, to, total) ;
}
else
{
// if( from < start ) {from = start ;}
// if( to > start+howMany ) {to = start+howMany;}
static pos::PixelConfigList &list = pos::PixelConfigFile::getConfig() ;
total = list.size();
for(unsigned int key=0; key<(unsigned int)total; key++)
{
if( from == -2147483647 && (key >= (unsigned int)start && key < (unsigned int)(start+howMany)) ||
from != -2147483647 && (key >= (unsigned int)from && key <= (unsigned int)to) )
{
pos::PixelConfigKey globalKey(key) ;
vector<pair<string, unsigned int> > vList = pos::PixelConfigFile::getVersions(globalKey) ;
std::vector<std::vector< std::string> > newvList ;
for(vector<pair<string, unsigned int> >::iterator i=vList.begin(); i!=vList.end(); i++)
{
std::vector< std::string> tmp ;
std::stringstream s ; s << (*i).second ;
tmp.push_back("") ; // 0 CONFIG_KEY_ID
tmp.push_back("") ; // 1 KEY_NAME
tmp.push_back("") ; // 2 CONDITION_DATA_SET_ID
tmp.push_back("") ; // 3 KIND_OF_CONDITION_ID
tmp.push_back((*i).first) ; // 4 KIND_OF_CONDITION_NAME
tmp.push_back(s.str()) ; // 5 CONDITION_VERSION
tmp.push_back("") ; // 6 IS_MOVED_TO_HISTORY
tmp.push_back("1970, Jan 01 - 00:00:00") ; // 7 RECORD_INSERTION_TIME
tmp.push_back("Q29tbWVudHMgYXJlIHVuYXZhaWxhYmxlIGZvciBmaWxlcw==") ; // 8 COMMENT_DESCRIPTION base46_encode("Comments are unavailable for files")
tmp.push_back("Author is unavailable for files") ; // 9 AUTHOR
newvList.push_back(tmp) ;
}
std::stringstream keyString ;
keyString.str("") ;
keyString << globalKey.key() ;
result[keyString.str()] = newvList ;
}
}
}
timer->stopTimer() ;
delete timer ;
return result ;
}
//==============================================================================
static std::string uploadStatus(std::string uploadedFile)
{
if(getMode())
{
return pixelConfigDB().uploadStatus(uploadedFile) ;
}
else
{
return std::string("true") ;
}
}
//==============================================================================
template <class T>
static int put( T* pixelObject,int configurationFileVersion, std::string path)
{
std::stringstream arg ; arg << "PixelConfigInterface::put(T*,int,string) T=" << typeid(pixelObject).name() ;
pos::PixelTimeFormatter * timer = new pos::PixelTimeFormatter(arg.str()) ;
int retStatus = 0 ;
if(getMode())
{
retStatus = pixelConfigDB().put(pixelObject,configurationFileVersion) ;
}
else
{
retStatus = put(pixelObject, path) ;
}
timer->stopTimer() ;
delete timer ;
return retStatus;
}
//==============================================================================
template <class T>
static int put(T* pixelObject,std::string label)
{
std::stringstream arg ; arg << "PixelConfigInterface::put(T*,string) T=" << typeid(pixelObject).name() ;
pos::PixelTimeFormatter * timer = new pos::PixelTimeFormatter(arg.str()) ;
int retStatus = 0 ;
if(getMode())
{
retStatus = pixelConfigDB().put(pixelObject,getGlobalKey()) ;
}
else
{
retStatus = pos::PixelConfigFile::put(pixelObject, label);
}
timer->stopTimer() ;
delete timer ;
return retStatus;
}
//==============================================================================
static std::vector<std::string> getVersionAliases(std::string path)
{
if(getMode())
{
return pixelConfigDB().getVersionAliases(path);
}
else
{
//assert(0);
return pos::PixelConfigFile::getVersionAliases(path);
}
}
//==============================================================================
template <class T>
static int put(std::vector<T*> objects,std::string label)
{
std::stringstream arg ; arg << "PixelConfigInterface::put(vector<T*>,string) T=" << typeid(objects).name() ;
pos::PixelTimeFormatter * timer = new pos::PixelTimeFormatter(arg.str()) ;
int retStatus = 0 ;
if(getMode())
{
retStatus = pixelConfigDB().put(objects,getGlobalKey()) ;
}
else
{
retStatus = pos::PixelConfigFile::put(objects, label);
}
timer->stopTimer() ;
delete timer ;
return retStatus;
}
//==============================================================================
template <class T>
static int put(std::vector<T*> objects, int configurationFileVersion, std::string path)
{
std::stringstream arg ; arg << "PixelConfigInterface::put(vector<T*>,int,string) T=" << typeid(objects).name() ;
pos::PixelTimeFormatter * timer = new pos::PixelTimeFormatter(arg.str()) ;
int retStatus = 0 ;
if(getMode())
{
retStatus = pixelConfigDB().put(objects,configurationFileVersion) ;
}
else
{
retStatus = put(objects, path) ;
}
timer->stopTimer() ;
delete timer ;
return retStatus;
}
//==============================================================================
static pos::pathVersionAliasMmap getVersionData()
{
pos::PixelTimeFormatter * timer = new pos::PixelTimeFormatter("PixelConfigInterface::getVersionData()") ;
pos::pathVersionAliasMmap vData ;
if(getMode())
{
vData = pixelConfigDB().getVersionData() ;
}
else
{
vData = pos::PixelConfigFile::getVersionData();
}
timer->stopTimer() ;
delete timer ;
return vData ;
}
//==============================================================================
static pos::pathVersionAliasMmap getVersionData(string koc)
{
pos::PixelTimeFormatter * timer = new pos::PixelTimeFormatter("PixelConfigInterface::getVersionData(string)") ;
pos::pathVersionAliasMmap vData ;
if(getMode())
{
vData = pixelConfigDB().getVersionData(koc) ;
}
else
{
vData = pos::PixelConfigFile::getVersionData(koc);
}
timer->stopTimer() ;
delete timer ;
return vData ;
}
//==============================================================================
static std::vector<std::vector<std::string> > getVersionDataWithComments(string koc)
{
pos::PixelTimeFormatter * timer = new pos::PixelTimeFormatter("PixelConfigInterface::getVersionDataWithComments(string)") ;
std::map<std::string, std::vector<std::pair< unsigned int, string> > > vData ;
std::vector<std::vector<std::string> > result ;
if(getMode())
{
result = pixelConfigDB().getVersionDataWithComments(koc) ;
}
else
{
std::vector<std::string> tmp ;
tmp.push_back("VERSION_ALIAS");
tmp.push_back("VERSION");
tmp.push_back("COMMENT_DESCRIPTION");
tmp.push_back("RECORD_INSERTION_TIME");
tmp.push_back("RECORD_INSERTION_USER");
tmp.push_back("KIND_OF_CONDITION");
result.push_back(tmp) ;
tmp.clear() ;
stringstream ss ;
pos::PixelConfigFile::forceAliasesReload(true) ;
vData = pos::PixelConfigFile::getVersionData(koc);
for(std::map<std::string, std::vector<std::pair< unsigned int, string> > >::iterator it = vData.begin() ;
it != vData.end() ; it++)
{
for(std::vector<std::pair< unsigned int, string> >::iterator itt = it->second.begin() ;
itt != it->second.end() ; itt++)
{
tmp.clear() ;
tmp.push_back(itt->second) ;
ss.str("") ;
ss << itt->first ;
tmp.push_back(ss.str()) ;
tmp.push_back("Q29tbWVudHMgYXJlIHVuYXZhaWxhYmxlIGZvciBmaWxlcw==") ;
tmp.push_back("01/01/1970 00:00:00") ;
tmp.push_back("Author is unavailable for files") ;
tmp.push_back(it->first) ;
result.push_back(tmp) ;
}
}
return result ;
}
timer->stopTimer() ;
delete timer ;
return result;
}
//==============================================================================
static std::set<unsigned int> getExistingVersions(string koc)
{
pos::PixelTimeFormatter * timer = new pos::PixelTimeFormatter("PixelConfigInterface::getExistingVersions(string)") ;
std::set<unsigned int> result ;
if(getMode())
{
result = pixelConfigDB().getExistingVersions(koc) ;
}
else
{
pos::PixelConfigList iList = pos::PixelConfigFile::getConfig();
for(unsigned int i = 0 ; i < iList.size() ; i++)
{
unsigned int version ;
if(iList[i].find(koc, version) != -1)
{
result.insert(version) ;
}
}
}
timer->stopTimer() ;
delete timer ;
return result ;
}
//==============================================================================
static std::vector<pos::pathAliasPair> getConfigAliases(std::string path)
{
// if(getMode())
// {
// return PixelConfigDBInterface::getConfigAliases(path);
// }
// else
// {
return pos::PixelConfigFile::getConfigAliases(path);
// }
}
//==============================================================================
static bool& getMode()
{
static bool mode = std::string(getenv("PIXELCONFIGURATIONBASE"))=="DB";
// cout << __LINE__ << "]\t[PixelconfigInterface::getMode()]\t\t " << "Setting mode to: " << mode << endl ;
if(mode) pixelConfigDB().connect();
// static bool mode = false ;
return mode;
}
//==============================================================================
static pos::PixelConfigKey& getGlobalKey()
{
static pos::PixelConfigKey lastUsedKey_(0); //for now make -1 initial value
return lastUsedKey_;
}
//==============================================================================
static std::string commit(int newKey)
{
if(getMode())
{
return pixelConfigDB().commitToDB(newKey) ;
}
else
{
std::cout << __LINE__ << "]\t[PixelConfigFile::commit()]\t\t\t Not implemented for file-based repository" << std::endl ;
return ("") ;
}
}
private:
static PixelConfigDBInterface& pixelConfigDB(){
static PixelConfigDBInterface aPixelConfigDB;
return aPixelConfigDB;
}
};
/* @} */
#endif
| [
"oaz2@cornell.edu"
] | oaz2@cornell.edu |
d1bcd1e9aac2c6bdc1ef978a31c1f5ff95012c7f | b9514762eb348e2447ad69534e5955acfa0649af | /Source/Lutefisk3D/Input/Controls.h | c0eaafffa43b89261b4d26a6840bf72aa537c96c | [
"Apache-2.0",
"BSD-2-Clause",
"Zlib",
"MIT",
"LicenseRef-scancode-khronos",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Prashant-Jonny/lutefisk3d | d2c23c463e14a9845e9cb183004e53fa789cd86d | 397f188689f7410a331782992ded4204ab11b0b2 | refs/heads/master | 2020-12-03T07:54:34.221642 | 2015-10-28T08:42:20 | 2015-10-28T08:42:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,130 | h | //
// Copyright (c) 2008-2015 the Urho3D project.
//
// 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.
//
#pragma once
#include "../Core/Variant.h"
namespace Urho3D
{
/// %Controls sent over the network.
class Controls
{
public:
/// Construct.
Controls();
/// Destruct.
~Controls();
/// Reset to initial state.
void Reset();
/// Set or release buttons.
void Set(unsigned buttons, bool down = true)
{
if (down)
buttons_ |= buttons;
else
buttons_ &= ~buttons;
}
/// Check if a button is held down.
bool IsDown(unsigned button) const
{
return (buttons_ & button) != 0;
}
/// Check if a button was pressed on this frame. Requires previous frame's controls.
bool IsPressed(unsigned button, const Controls& previousControls) const { return (buttons_ & button) != 0 && (previousControls.buttons_ & button) == 0; }
/// Button state.
unsigned buttons_;
/// Mouse yaw.
float yaw_;
/// Mouse pitch.
float pitch_;
/// Extra control data.
VariantMap extraData_;
};
}
| [
"nemerle5@gmail.com"
] | nemerle5@gmail.com |
a36d04c76a3109634121c2580d504745bcfc6ac5 | 4090aed9b69d1e355b40a6db6a138f34353197a0 | /excursion.cpp | be33131bb53ff6efe12d33f7579aacc16c2ff063 | [] | no_license | HongyuHe/OJ | 0ecb72c4a87ac8ac5dc90210be0fbd71c6843f64 | f8713ed4e374fdbc783c7c683020a1c23f42b3ad | refs/heads/master | 2020-03-31T17:14:30.991344 | 2018-10-10T01:17:27 | 2018-10-10T01:17:27 | 152,414,016 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 551 | cpp | #include <iostream>
#include <vector>
using namespace std;
typedef long long ll;
int main() {
vector<ll> count(3, 0);
string s;
cin >> s;
for(auto& i : s) {
count[i-'0']++;
}
ll swaps = 0;
for(auto& i : s) {
if(i == '0') {
count[0]--;
}
else {
swaps += count[0];
}
}
for(auto& i : s) {
if(i == '1') {
count[1]--;
}
if(i == '2') {
swaps += count[1];
}
}
cout << swaps << endl;
}
| [
"mikepf97@gmail.com"
] | mikepf97@gmail.com |
51abb84c2a5606db3855d3aa5a7dfbd697cf230b | 784e683fe0239f991228e0d7632ace5cc2f55ad8 | /resource/examples/advanced/InducedPolarization/PolAnalyzer.cxx | b38c1ea7fda1a7ca17754affdeaa662780fd5a78 | [] | no_license | rheask8246/megalib | 5751ee8e5b00bc6c9a0cacea2c1d82a600f08336 | a681302a429aa4a9cb1201c00db1d964fb92a056 | refs/heads/master | 2021-07-23T14:13:32.687763 | 2019-01-11T05:41:49 | 2019-01-11T05:41:49 | 239,953,431 | 0 | 0 | null | 2020-02-12T07:39:40 | 2020-02-12T07:39:39 | null | UTF-8 | C++ | false | false | 13,117 | cxx | /*
* PolAnalyzer.cxx
*
*
* Copyright (C) by Andreas Zoglauer.
* All rights reserved.
*
*
* This code implementation is the intellectual property of
* Andreas Zoglauer.
*
* By copying, distributing or modifying the Program (or any work
* based on the Program) you indicate your acceptance of this statement,
* and all its terms.
*
*/
// Standard
#include <iostream>
#include <string>
#include <sstream>
#include <csignal>
#include <cstdlib>
using namespace std;
// ROOT
#include <TROOT.h>
#include <TMath.h>
#include <TEnv.h>
#include <TSystem.h>
#include <TApplication.h>
#include <TStyle.h>
#include <TCanvas.h>
#include <TH1.h>
#include <TH2.h>
// MEGAlib
#include "MGlobal.h"
#include "MStreams.h"
#include "MGeometryRevan.h"
#include "MDDetector.h"
#include "MFileEventsEvta.h"
#include "MDVolumeSequence.h"
#include "MRERawEvent.h"
#include "MRESE.h"
/******************************************************************************/
class PolAnalyzer
{
public:
/// Default constructor
PolAnalyzer();
/// Default destructor
~PolAnalyzer();
/// Parse the command line
bool ParseCommandLine(int argc, char** argv);
/// Analyze what eveer needs to be analyzed...
bool Analyze();
/// Interrupt the analysis
void Interrupt() { m_Interrupt = true; }
private:
/// True, if the analysis needs to be interrupted
bool m_Interrupt;
/// The sim file name with polarization input
TString m_PolFileName;
/// The sim file name with unpolarization input
TString m_NotPolFileName;
/// The geometry file name
TString m_GeometryFileName;
/// The minimum energy
double m_EnergyMin;
/// The maximum energy
double m_EnergyMax;
};
/******************************************************************************/
double Modulation(double* x, double* par)
{
return par[0] + par[1]*cos(2*(x[0]-par[2] + 90.0)*c_Rad);
};
/******************************************************************************
* Default constructor
*/
PolAnalyzer::PolAnalyzer() : m_Interrupt(false), m_EnergyMin(0), m_EnergyMax(1000000)
{
gStyle->SetPalette(1, 0);
}
/******************************************************************************
* Default destructor
*/
PolAnalyzer::~PolAnalyzer()
{
// Intentionally left blanck
}
/******************************************************************************
* Parse the command line
*/
bool PolAnalyzer::ParseCommandLine(int argc, char** argv)
{
ostringstream Usage;
Usage<<endl;
Usage<<" Usage: PolAnalyzer <options>"<<endl;
Usage<<" General options:"<<endl;
Usage<<" -p: sim file name with polarized data"<<endl;
Usage<<" -u: sim file name with UN-polarized data"<<endl;
Usage<<" -g: geometry file name"<<endl;
Usage<<" -e: energy min, energy max"<<endl;
Usage<<" -h: print this help"<<endl;
Usage<<endl;
string Option;
// Check for help
for (int i = 1; i < argc; i++) {
Option = argv[i];
if (Option == "-h" || Option == "--help" || Option == "?" || Option == "-?") {
cout<<Usage.str()<<endl;
return false;
}
}
// Now parse the command line options:
for (int i = 1; i < argc; i++) {
Option = argv[i];
// First check if each option has sufficient arguments:
// Single argument
if (Option == "-p" || Option == "-u" || Option == "-g") {
if (!((argc > i+1) &&
(argv[i+1][0] != '-' || isalpha(argv[i+1][1]) == 0))){
cout<<"Error: Option "<<argv[i][1]<<" needs a second argument!"<<endl;
cout<<Usage.str()<<endl;
return false;
}
}
// Multiple arguments template
else if (Option == "-e") {
if (!((argc > i+2) &&
(argv[i+1][0] != '-' || isalpha(argv[i+1][1]) == 0) &&
(argv[i+2][0] != '-' || isalpha(argv[i+2][1]) == 0))){
cout<<"Error: Option "<<argv[i][1]<<" needs two arguments!"<<endl;
cout<<Usage.str()<<endl;
return false;
}
}
// Then fulfill the options:
if (Option == "-p") {
m_PolFileName = argv[++i];
cout<<"Accepting file name with polarized data: "<<m_PolFileName<<endl;
} else if (Option == "-u") {
m_NotPolFileName = argv[++i];
cout<<"Accepting file name with UN-polarized data: "<<m_NotPolFileName<<endl;
} else if (Option == "-g") {
m_GeometryFileName = argv[++i];
cout<<"Accepting geometry file name: "<<m_GeometryFileName<<endl;
} else if (Option == "-e") {
m_EnergyMin = atof(argv[++i]);
m_EnergyMax = atof(argv[++i]);
cout<<"Accepting energy limits: "<<m_EnergyMin<<" & " <<m_EnergyMax<<endl;
} else {
cout<<"Error: Unknown option \""<<Option<<"\"!"<<endl;
cout<<Usage.str()<<endl;
return false;
}
}
if (m_PolFileName == "") {
cout<<"Error: Please give a file name!"<<endl;
return false;
}
if (m_GeometryFileName == "") {
cout<<"Error: Please give a geometry file name!"<<endl;
return false;
}
return true;
}
/******************************************************************************
* Do whatever analysis is necessary
*/
bool PolAnalyzer::Analyze()
{
if (m_Interrupt == true) return false;
// Load geometry:
MGeometryRevan Geometry;
if (Geometry.ScanSetupFile(m_GeometryFileName.Data()) == true) {
cout<<"Geometry "<<Geometry.GetName()<<" loaded!"<<endl;
Geometry.ActivateNoising(false);
Geometry.SetGlobalFailureRate(0.0);
} else {
cout<<"Loading of geometry "<<Geometry.GetName()<<" failed!!"<<endl;
return false;
}
TH1D* SpectralHist = new TH1D("Spectrum", "Spectrum", 100, m_EnergyMin, m_EnergyMax);
SpectralHist->SetXTitle("Energy in keV");
SpectralHist->SetYTitle("counts");
int PolBins = 90;
TH1D* PolAzimuthHist = new TH1D("AzimuthalPol", "Azimuthal scatter angle distribution of polarized data", PolBins, -180.0, 180);
PolAzimuthHist->SetXTitle("Azimuthal scatter angle in degree");
PolAzimuthHist->SetYTitle("counts");
PolAzimuthHist->SetMinimum(0);
TH1D* NotPolAzimuthHist = new TH1D("AzimuthalNotPol", "Azimuthal scatter angle distribution of UN-polarized data", PolBins, -180.0, 180);
NotPolAzimuthHist->SetXTitle("Azimuthal scatter angle in degree");
NotPolAzimuthHist->SetYTitle("counts");
NotPolAzimuthHist->SetMinimum(0);
TH1D* CorrectedAzimuthHist = new TH1D("CorrectedPolarizationSignature", "Corrected polarization signature", PolBins, -180.0, 180);
CorrectedAzimuthHist->SetXTitle("Azimuthal scatter angle in degree");
CorrectedAzimuthHist->SetYTitle("corrected counts");
CorrectedAzimuthHist->SetMinimum(0);
MRERawEvent* Event = 0;
// Open the polarized file
MFileEventsEvta PolData(&Geometry);
if (PolData.Open(m_PolFileName.Data()) == false) {
mlog<<"Unable to open file "<<m_PolFileName<<endl;
return false;
}
while ((Event = PolData.GetNextEvent()) != 0) {
// Determine the energy deposit in CZT:
int NHits = 0;
double Energy = 0.0;
MVector WeightedPos;
for (int r = 0; r < Event->GetNRESEs(); ++r) {
if (Event->GetRESEAt(r)->GetDetector() == 8) {
++NHits;
Energy += Event->GetRESEAt(r)->GetEnergy();
WeightedPos += Event->GetRESEAt(r)->GetPosition()*Event->GetRESEAt(r)->GetEnergy();
}
}
if (NHits > 0) {
if (Energy > m_EnergyMin && Energy < m_EnergyMax) {
WeightedPos[0] /= NHits;
WeightedPos[1] /= NHits;
WeightedPos[2] /= NHits;
double Azimuth = WeightedPos.Phi();
SpectralHist->Fill(Energy);
PolAzimuthHist->Fill(Azimuth*c_Deg);
}
}
delete Event;
}
// Open the polarized file
MFileEventsEvta NotPolData(&Geometry);
if (NotPolData.Open(m_NotPolFileName.Data()) == false) {
mlog<<"Unable to open file "<<m_NotPolFileName<<endl;
return false;
}
while ((Event = NotPolData.GetNextEvent()) != 0) {
// Determine the energy deposit in CZT:
int NHits = 0;
double Energy = 0.0;
MVector WeightedPos;
for (int r = 0; r < Event->GetNRESEs(); ++r) {
if (Event->GetRESEAt(r)->GetDetector() == 8) {
++NHits;
Energy += Event->GetRESEAt(r)->GetEnergy();
WeightedPos += Event->GetRESEAt(r)->GetPosition()*Event->GetRESEAt(r)->GetEnergy();
}
}
if (NHits > 0) {
if (Energy > m_EnergyMin && Energy < m_EnergyMax) {
WeightedPos[0] /= NHits;
WeightedPos[1] /= NHits;
WeightedPos[2] /= NHits;
double Azimuth = WeightedPos.Phi();
SpectralHist->Fill(Energy);
NotPolAzimuthHist->Fill(Azimuth*c_Deg);
}
}
delete Event;
}
// Normalize both to counts/deg:
for (int b = 1; b <= PolAzimuthHist->GetNbinsX(); ++b) {
if (PolAzimuthHist->GetBinContent(b) == 0) {
mgui<<"You don't have enough statistics: Some bins are zero!"<<endl;
return false;
}
PolAzimuthHist->SetBinContent(b, PolAzimuthHist->GetBinContent(b)/PolAzimuthHist->GetBinWidth(b));
}
for (int b = 1; b <= NotPolAzimuthHist->GetNbinsX(); ++b) {
if (NotPolAzimuthHist->GetBinContent(b) == 0) {
mgui<<"You don't have enough statistics: Some bins are zero!"<<endl;
return false;
}
NotPolAzimuthHist->SetBinContent(b, NotPolAzimuthHist->GetBinContent(b)/NotPolAzimuthHist->GetBinWidth(b));
}
// Correct the image:
double Mean = PolAzimuthHist->Integral()/CorrectedAzimuthHist->GetNbinsX();
// The scaling is necessary, since we cannot assume that pol and background have been measured for exactly the same time...
Mean *= NotPolAzimuthHist->Integral()/PolAzimuthHist->Integral();
for (int b = 1; b <= CorrectedAzimuthHist->GetNbinsX(); ++b) {
CorrectedAzimuthHist->SetBinContent(b, PolAzimuthHist->GetBinContent(b)/NotPolAzimuthHist->GetBinContent(b)*Mean);
}
/*
TCanvas* SpectralCanvas = new TCanvas();
SpectralCanvas->cd();
SpectralHist->Draw();
SpectralCanvas->Update();
TCanvas* PolAzimuthCanvas = new TCanvas();
PolAzimuthCanvas->cd();
PolAzimuthHist->Draw();
PolAzimuthCanvas->Update();
TCanvas* NotPolAzimuthCanvas = new TCanvas();
NotPolAzimuthCanvas->cd();
NotPolAzimuthHist->Draw();
NotPolAzimuthCanvas->Update();
*/
// Try to fit a cosinus
TCanvas* CorrectedAzimuthCanvas = new TCanvas();
CorrectedAzimuthCanvas->cd();
TF1* Lin = new TF1("LinearModulation", "pol0", -180*0.99, 180*0.99);
CorrectedAzimuthHist->Fit(Lin, "RQFI");
TF1* Mod = new TF1("Modulation", Modulation, -180*0.99, 180*0.99, 3);
Mod->SetParNames("Offset (#)", "Scale (#)", "Shift (deg)");
Mod->SetParameters(Lin->GetParameter(0), 0.5, 0);
Mod->SetParLimits(1, 0, 10000000);
Mod->SetParLimits(2, -200, 200);
CorrectedAzimuthHist->Fit(Mod, "RQ");
CorrectedAzimuthHist->Draw();
CorrectedAzimuthCanvas->Update();
double Modulation = fabs(Mod->GetParameter(1)/Mod->GetParameter(0));
double ModulationError = sqrt((Mod->GetParError(1)*Mod->GetParError(1))/(Mod->GetParameter(0)*Mod->GetParameter(0)) +
(Mod->GetParError(0)*Mod->GetParError(0)*Mod->GetParameter(1)*Mod->GetParameter(1))/
(Mod->GetParameter(0)*Mod->GetParameter(0)*Mod->GetParameter(0)*Mod->GetParameter(0)));
double PolarizationAngle = Mod->GetParameter(2);
double PolarizationAngleError = Mod->GetParError(2);
while (PolarizationAngle < 0) PolarizationAngle += 180;
while (PolarizationAngle > 180) PolarizationAngle -= 180;
mout<<endl;
mout<<"Polarization analysis:"<<endl;
mout<<endl;
mout<<"Modulation: "<<Modulation<<"+-"<<ModulationError<<endl;
mout<<"Polarization angle: ("<<PolarizationAngle<<"+-"<<PolarizationAngleError<<") deg"<<endl;
mout<<endl;
CorrectedAzimuthHist->Draw();
CorrectedAzimuthCanvas->Update();
return true;
}
/******************************************************************************/
PolAnalyzer* g_Prg = 0;
int g_NInterruptCatches = 1;
/******************************************************************************/
/******************************************************************************
* Called when an interrupt signal is flagged
* All catched signals lead to a well defined exit of the program
*/
void CatchSignal(int a)
{
if (g_Prg != 0 && g_NInterruptCatches-- > 0) {
cout<<"Catched signal Ctrl-C (ID="<<a<<"):"<<endl;
g_Prg->Interrupt();
} else {
abort();
}
}
/******************************************************************************
* Main program
*/
int main(int argc, char** argv)
{
// Catch a user interupt for graceful shutdown
// signal(SIGINT, CatchSignal);
// Initialize global MEGALIB variables, especially mgui, etc.
MGlobal::Initialize();
TApplication PolAnalyzerApp("PolAnalyzerApp", 0, 0);
g_Prg = new PolAnalyzer();
if (g_Prg->ParseCommandLine(argc, argv) == false) {
cerr<<"Error during parsing of command line!"<<endl;
return -1;
}
if (g_Prg->Analyze() == false) {
cerr<<"Error during analysis!"<<endl;
return -2;
}
PolAnalyzerApp.Run();
cout<<"Program exited normally!"<<endl;
return 0;
}
/*
* Cosima: the end...
******************************************************************************/
| [
"andreas@megalibtoolkit.com"
] | andreas@megalibtoolkit.com |
761eb02ef49431d2e2ee7a320b9f78882365368b | fca08f1452c0bdaf22a1714b3aaaa867cdaf2b63 | /Sudoku.h | ba235e6b0f0b3311b3928224b30ad502352881e1 | [] | no_license | jenny121095/pd-Sudoku | e4e5b77b8c4e3b95853f9dd3f662a99afbf42663 | fa65265e880ef1e5cbd2701de34c8f1b48d00d82 | refs/heads/master | 2021-01-20T21:12:48.728126 | 2016-07-16T03:48:25 | 2016-07-16T03:48:25 | 63,463,635 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 418 | h | #include <cstdio>
#include <cstdlib>
#include <ctime>
#define sudokusize 9
class Sudoku
{
public:
Sudoku();
void ReadIn();
int Solve();
int find(int i,int j);
void GiveQuestion();
private:
int map[sudokusize][sudokusize];
int res[sudokusize][sudokusize];
int givequestion[sudokusize][sudokusize];
int zero;
int depth;
int Answer;
struct BT
{
int x;
int y;
}record[81];
int lx;
int ly;
};
| [
"noreply@github.com"
] | jenny121095.noreply@github.com |
4c863289f625a57726206a87037856d9c608a121 | eb5456a1d1465fb33dd51566cb7d05be116b6f1b | /WebServer_VD3.cpp | a04705ea960d6f64102d8e6679f01060f52ae3a2 | [] | no_license | ndq3004/SocketQ | 194fcb095c0ba561c085f80c986e8f8386d3ce8c | 2a807d1bc5b694c4f03d17ebb60bfa5b9316d8e0 | refs/heads/master | 2020-04-10T16:16:41.311707 | 2018-12-10T08:21:18 | 2018-12-10T08:21:18 | 161,140,004 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,194 | cpp | // WebServer.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include "winsock2.h"
int main()
{
WSADATA wsa;
WSAStartup(MAKEWORD(2, 2), &wsa);
SOCKET listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
SOCKADDR_IN addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(8080);
bind(listener, (SOCKADDR *)&addr, sizeof(addr));
listen(listener, 5);
while (1)
{
SOCKET client = accept(listener, NULL, NULL);
char buf[1024];
int ret;
// Nhan yeu cau tu trinh duyet
ret = recv(client, buf, sizeof(buf), 0);
buf[ret] = 0;
printf("%s", buf);
/*char cmd[16], path[1024];
sscanf(buf, "%s %s", cmd, path);*/
if (strncmp(buf + 4, "/xinchao", 8) == 0)
{
// Tra ket qua cho trinh duyet
char *header = "HTTP/1.1 200 OK\nContent-Type: text/html\n\n";
send(client, header, strlen(header), 0);
char *content = "<html><body><h1>Xin chao</h1></body></html>";
send(client, content, strlen(content), 0);
}
else if (strncmp(buf + 4, "/hello", 6) == 0)
{
// Tra ket qua cho trinh duyet
char *header = "HTTP/1.1 200 OK\nContent-Type: text/html\n\n";
send(client, header, strlen(header), 0);
char *content = "<html><body><h1>Hello</h1></body></html>";
send(client, content, strlen(content), 0);
}
else if (strncmp(buf + 4, "/image", 6) == 0 || strncmp(buf + 4, "/favicon.ico", 12) == 0)
{
// Tra ket qua cho trinh duyet
char *header = "HTTP/1.1 200 OK\nContent-Type: image/jpg\n\n";
send(client, header, strlen(header), 0);
FILE *f = fopen("C:\\test_server\\city.jpg", "rb");
while (1)
{
ret = fread(buf, 1, sizeof(buf), f);
if (ret > 0)
send(client, buf, ret, 0);
else
break;
}
fclose(f);
}
else
{
// Tra ket qua cho trinh duyet
char *header = "HTTP/1.1 200 OK\nContent-Type: text/html\n\n";
send(client, header, strlen(header), 0);
char *content = "<html><body><h1>Yeu cau khong duoc ho tro</h1></body></html>";
send(client, content, strlen(content), 0);
}
// Dong ket noi
closesocket(client);
}
closesocket(listener);
WSACleanup();
return 0;
}
| [
"ndq3004@gmail.com"
] | ndq3004@gmail.com |
78ce830aa4aaca857a008d330cae6f57386bbf6f | a3634de7800ae5fe8e68532d7c3a7570b9c61c5b | /schedule1.cpp | fb34f2f0d7740ec82a48ca98c2a50d35c20c7975 | [] | no_license | MayankChaturvedi/competitive-coding | a737a2a36b8aa7aea1193f2db4b32b081f78e2ba | 9e9bd21de669c7b7bd29a262b29965ecc80ad621 | refs/heads/master | 2020-03-18T01:39:29.447631 | 2018-02-19T15:04:32 | 2018-02-19T15:04:32 | 134,152,930 | 0 | 1 | null | 2018-05-20T13:27:35 | 2018-05-20T13:27:34 | null | UTF-8 | C++ | false | false | 1,043 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{ int t;
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin>>t;
while(t--)
{ int n, k;
cin>>n>>k;
string x;
cin>>x;
int i=0, j=0;
while(k--)
{ int lenmax=0, imax=0;
if(j==n)
{ i=0;
j=0;
}
while(j<n)
{ if(x[i]==x[j])
j++;
else
{ if(j-i>lenmax)
{ lenmax=j-i;
imax=i;
}
i=j;
}
}
if(j==n && x[j-1]==x[i] && j-i>lenmax)
{ lenmax=j-i;
imax=i;
}
if(lenmax==1)
break;
if(x[imax+ (lenmax)/2]=='1')
x[imax+ (lenmax)/2]='0';
else
x[imax+ (lenmax)/2]='1';
//x[imax+ (lenmax)/2]=!x[imax+ (lenmax)/2];
//cout<<lenmax<<endl;
}
int ans=0; i=0; j=0;
while(j<n)
{ if(x[i]==x[j])
j++;
else
{ ans=max(ans,j-i);
i=j;
}
}
if(j==n && x[j-1]==x[i] )
{ ans=max(ans,j-i);
}
cout<<ans<<'\n';
}
return 0;
}
| [
"f20160006@goa.bits-pilani.ac.in"
] | f20160006@goa.bits-pilani.ac.in |
d9f8b2172fe2e39d1d7c9535e5424b5511196158 | 5c34abe10630b23da8ba7d1cbce38bda53a4b6fa | /CalibSvc/src/test/UseTkrAlign.cxx | 47229bd2c46f7d6cb30bcd47cde9381d07c81fac | [] | no_license | fermi-lat/GlastRelease-scons-old | cde76202f706b1c8edbf47b52ff46fe6204ee608 | 95f1daa22299272314025a350f0c6ef66eceda08 | refs/heads/master | 2021-07-23T02:41:48.198247 | 2017-05-09T17:27:58 | 2017-05-09T17:27:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,975 | cxx | //$Header$
#include <stdio.h>
#include "GaudiKernel/Algorithm.h"
#include "GaudiKernel/AlgFactory.h"
#include "GaudiKernel/IDataProviderSvc.h"
#include "GaudiKernel/Service.h"
#include "GaudiKernel/MsgStream.h"
#include "GaudiKernel/SmartDataPtr.h"
#include "CalibSvc/ICalibPathSvc.h"
#include "CalibData/Tkr/TkrTowerAlignCalib.h"
#include "CalibData/Tkr/TkrInternalAlignCalib.h"
#include "CalibData/CalibTime.h"
#include "idents/TkrId.h"
/**
@file UseTkr.cxx
Simple algorithm to test functioning of "the other" TDS,
Tkr alignment (both inter-tower and internal to towers)
*/
/**
@class UseTkrAlign
Algorithm exemplifying retrieval and use of Tkr calibration quantities
*/
namespace {
void outputAlign(MsgStream& log, const CLHEP::Hep3Vector& disp,
const CLHEP::Hep3Vector& rot) {
double x = disp.x(), y = disp.y(), z = disp.z();
log << " disp=(" << x << ", " << y << ", " << z << ") " << endreq;
x = rot.x(); y = rot.y(); z = rot.z();
log << " rot=(" << x << ", " << y << ", " << z << ") ";
log << endreq << endreq;
}
}
class UseTkrAlign : public Algorithm {
public:
UseTkrAlign(const std::string& name, ISvcLocator* pSvcLocator);
StatusCode initialize();
StatusCode execute();
StatusCode finalize();
private:
/// Helper functions called by execute
void processInter(CalibData::TkrTowerAlignCalib* pNew,
const std::string& path);
void processIntra(CalibData::TkrInternalAlignCalib* pNew,
const std::string& path);
IDataProviderSvc* m_pCalibDataSvc;
ICalibPathSvc* m_pCalibPathSvc;
std::string m_pathInter;
std::string m_pathIntra;
int m_towerSer;
int m_internalSer;
};
/// Instantiation of a static factory to create instances of this algorithm
//static const AlgFactory<UseTkrAlign> Factory;
//const IAlgFactory& UseTkrAlignFactory = Factory;
DECLARE_ALGORITHM_FACTORY(UseTkrAlign);
UseTkrAlign::UseTkrAlign(const std::string& name,
ISvcLocator* pSvcLocator )
: Algorithm(name, pSvcLocator), m_pCalibDataSvc(0),
m_towerSer(-1), m_internalSer(-1)
{
// Declare properties here.
}
StatusCode UseTkrAlign::initialize() {
StatusCode sc;
MsgStream log(msgSvc(), name());
log << MSG::INFO << "Initialize()" << endreq;
// So far don't have any properties, but in case we do some day..
setProperties();
sc = service("CalibDataSvc", m_pCalibDataSvc, true);
if ( !sc.isSuccess() ) {
log << MSG::ERROR
<< "Could not get IDataProviderSvc interface of CalibDataSvc"
<< endreq;
return sc;
}
sc = service("CalibDataSvc", m_pCalibPathSvc, true);
if ( !sc.isSuccess() ) {
log << MSG::ERROR
<< "Could not get ICalibPathSvc interface of CalibDataSvc"
<< endreq;
return sc;
}
m_pathInter =
m_pCalibPathSvc->getCalibPath(ICalibPathSvc::Calib_TKR_TowerAlign,
std::string("vanilla") );
m_pathIntra =
m_pCalibPathSvc->getCalibPath(ICalibPathSvc::Calib_TKR_InternalAlign,
std::string("vanilla") );
// Get properties from the JobOptionsSvc
sc = setProperties();
return StatusCode::SUCCESS;
}
StatusCode UseTkrAlign::execute( ) {
MsgStream log(msgSvc(), name());
DataObject *pObject;
m_pCalibDataSvc->retrieveObject(m_pathInter, pObject);
CalibData::TkrTowerAlignCalib* pTowerAlign = 0;
pTowerAlign = dynamic_cast<CalibData::TkrTowerAlignCalib *> (pObject);
if (!pTowerAlign) {
log << MSG::ERROR << "Dynamic cast to TkrTowerAlignCalib failed" << endreq;
return StatusCode::FAILURE;
}
int newSerNo = pTowerAlign->getSerNo();
if (newSerNo != m_towerSer) {
log << MSG::INFO << "Processing new tower align after retrieveObject"
<< endreq;
m_towerSer = newSerNo;
processInter(pTowerAlign, m_pathInter);
}
m_pCalibDataSvc->updateObject(pObject);
pTowerAlign = 0;
try {
pTowerAlign = dynamic_cast<CalibData::TkrTowerAlignCalib *> (pObject);
}
catch (...) {
log << MSG::ERROR
<< "Dynamic cast to TkrTowerAlignCalib after update failed" << endreq;
return StatusCode::FAILURE;
}
newSerNo = pTowerAlign->getSerNo();
if (newSerNo != m_towerSer) {
log << MSG::INFO << "Processing new tower align after update"
<< endreq;
m_towerSer = newSerNo;
processInter(pTowerAlign, m_pathInter);
}
DataObject *pObject2;
CalibData::TkrInternalAlignCalib* pInternalAlign = 0;
m_pCalibDataSvc->retrieveObject(m_pathIntra, pObject2);
pInternalAlign = dynamic_cast<CalibData::TkrInternalAlignCalib *> (pObject2);
if (!pInternalAlign) {
log << MSG::ERROR << "Dynamic cast to TkrInternalAlignCalib failed"
<< endreq;
return StatusCode::FAILURE;
}
newSerNo = pInternalAlign->getSerNo();
if (newSerNo != m_internalSer) {
log << MSG::INFO << "Processing new internal align after retrieveObject"
<< endreq;
m_internalSer = newSerNo;
processIntra(pInternalAlign, m_pathIntra);
}
m_pCalibDataSvc->updateObject(pObject2);
pInternalAlign = 0;
try {
pInternalAlign = dynamic_cast<CalibData::TkrInternalAlignCalib *> (pObject2);
}
catch (...) {
log << MSG::ERROR
<< "Dynamic cast to TkrInternalAlignCalib after update failed" << endreq;
return StatusCode::FAILURE;
}
newSerNo = pInternalAlign->getSerNo();
if (newSerNo != m_internalSer) {
log << MSG::INFO << "Processing new internal align after update"
<< endreq;
m_internalSer = newSerNo;
processIntra(pInternalAlign, m_pathIntra);
}
return StatusCode::SUCCESS;
}
void UseTkrAlign::processInter(CalibData::TkrTowerAlignCalib* pNew,
const std::string& path) {
bool done = false;
MsgStream log(msgSvc(), name());
log << MSG::INFO << "Retrieved with path " << path << endreq
<< "Serial #" << pNew->getSerNo() << endreq;
log << MSG::INFO << "Vstart: " << (pNew->validSince()).hour(true)
<< " Vend: " << (pNew->validTill()).hour(true) << endreq;
std::string vStart = pNew->getValidStart()->getString();
std::string vEnd = pNew->getValidEnd()->getString();
log << MSG::INFO << "(Vstart, Vend) as ascii from CalibTime objects: "
<< endreq;
log << MSG::INFO << "(" << vStart << ", " << vEnd << ")" << endreq;
CLHEP::Hep3Vector disp, rot;
if (!done) {
done = true;
for (unsigned ix = 0; ix < 16; ix++) {
pNew->getTowerAlign(ix, disp, rot);
log << MSG::INFO << "Tower alignment for tower #" << ix << ":"
<< endreq;
outputAlign(log, disp, rot);
}
}
}
void UseTkrAlign::processIntra(CalibData::TkrInternalAlignCalib* pNew,
const std::string& path) {
bool done = false;
MsgStream log(msgSvc(), name());
log << MSG::INFO << "Retrieved with path " << path << endreq
<< "Serial #" << pNew->getSerNo() << endreq;
log << MSG::INFO << "Vstart: " << (pNew->validSince()).hour(true)
<< " Vend: " << (pNew->validTill()).hour(true) << endreq;
std::string vStart = pNew->getValidStart()->getString();
std::string vEnd = pNew->getValidEnd()->getString();
log << MSG::INFO << "(Vstart, Vend) as ascii from CalibTime objects: "
<< endreq;
log << MSG::INFO << "(" << vStart << ", " << vEnd << ")" << endreq;
if (!done) {
// fetch some random values
done = true;
unsigned tower = 1;
unsigned tray = 1;
CLHEP::Hep3Vector disp, rot;
StatusCode ok = pNew->getTrayAlign(tower, tray, disp, rot);
log << "Constants for tower" << tower << ", tray " << tray << ": "
<< endreq;
outputAlign(log, disp, rot);
tray = 3;
ok = pNew->getTrayAlign(tower, tray, disp, rot);
log << "Constants for tower" << tower << ", tray " << tray << ": "
<< endreq;
outputAlign(log, disp, rot);
tray = 5;
unsigned face = 0;
ok = pNew->getFaceAlign(tower, tray, face, disp, rot);
log << "Constants for tower" << tower << ", tray " << tray
<< "face " << face << ": "
<< endreq;
outputAlign(log, disp, rot);
tower = 6; tray=16; face=0;
unsigned ladder = 1;
unsigned wafer = 2;
ok = pNew->getLadderAlign(tower, tray, face, ladder, disp, rot);
log << "Constants for tower" << tower << ", tray " << tray
<< "face " << face << "ladder " << ladder << ": "
<< endreq;
outputAlign(log, disp, rot);
ok = pNew->getWaferAlign(tower, tray, face, ladder, wafer, disp, rot);
log << "Constants for tower" << tower << ", tray " << tray
<< "face " << face << "ladder " << ladder << "wafer " << wafer
<< ": "
<< endreq;
outputAlign(log, disp, rot);
}
}
StatusCode UseTkrAlign::finalize( ) {
MsgStream log(msgSvc(), name());
log << MSG::INFO
<< " Finalize UseTkrAlign "
<< endreq;
return StatusCode::SUCCESS;
}
| [
""
] | |
136a24b84f97865e27b5a5eca1961f8dc8d1f552 | 64a1533f4541b76181cd6d3cec3b28876c969250 | /jonathanpr/attila/attila.cpp | 74c3a9756d3ae5a42e51b23353ba822ef356d2e3 | [] | no_license | drkvogel/retrasst | df1db3330115f6e2eea7afdb869e070a28c1cae8 | ee952fe39cf1a00998b00a09ca361fc7c83fa336 | refs/heads/master | 2020-05-16T22:53:26.565996 | 2014-08-01T16:52:16 | 2014-08-01T16:52:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,829 | cpp | #include <stdlib.h>
#include "randdefs.h"
#include "xbasic.h"
#include "xcgi.h"
#include "xdb.h"
#include "xquery.h"
#include "xencode.h"
#include "randutil.h"
#include "model.h"
#include "view.h"
//---------------------------------------------------------------------------
static RAND_UTIL *ru = NULL;
static XDB *db = NULL;
//---------------------------------------------------------------------------
// REPORT TO LOG FILE.
static void report( const std::string & problem )
{
ru->getCGI()->log( problem.c_str() );
}
static void run( void )
{
XCGI * params = ru->getCGI( );
Model info( params );
try
{
info.parse(params);
info.check( db, ru,params);
info.logResult( db, params );
}
catch( const std::string &problem ) {
report( problem + '\n' );
}
catch( const std::exception &error ) {
report( error.what() + '\n' );
}
const View * page = info.nextStage( );
page->sendHTML( );
delete page;
}
//---------------------------------------------------------------------------
int main( int argc, char **argv )
{
XCGI cgi( argc, argv );
cgi.writeHeader( XCGI::typeHtml );
std::string e;
ru = new RAND_UTIL( &cgi );
#ifndef __BORLANDC__
db = ru->openDB( "erg_attila" );
#else
db = ru->openDB( "dice_erg::erg_attila" );
#endif
if ( ru->isValid() )
{
std::vector<std::string> sty;
sty.push_back( "attila.css" );
ru->htmlBeginDoc( "Attila Randomisation", sty );
ru->htmlBeginBody( );
#ifndef _DEBUG
if ( ru->approvedIP() )
#endif
{
run();
}
ru->htmlEndBody( );
ru->htmlEndDoc();
}
else
{
printf(ru->getLastError().c_str());
printf( "\nError initiating" );
}
XDELETE( ru );
cgi.end();
return( EXIT_SUCCESS );
}
//---------------------------------------------------------------------------
| [
"chris.bird@ctsu.ox.ac.uk"
] | chris.bird@ctsu.ox.ac.uk |
c6a493af7e1f9da24c0880f56d98b0f9a3de6a13 | 021d05847e6618f1e4c86ab462e1afe851fe8634 | /homework_3.cpp | 528bad8ddef8ddd3db8d36debc165d06b812cdc5 | [] | no_license | yiyanglin0102/CS368 | 808a3f42e72de350961e6302ba373e9ef35d6304 | 07ef43fecdcb89d51ea3d47e357900afaea095ab | refs/heads/master | 2022-03-06T23:53:24.880651 | 2019-10-10T06:02:30 | 2019-10-10T06:02:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,540 | cpp | #include <iostream>
#include <map>
#include <vector>
#include <set>
#include <string>
#include <time.h> // time
#include <cstdlib>
using namespace std;
// don't change this function
// purpose: prints a map of the cave to the console
// input: the printable map a vector of strings
// output: none - console output of the cave diagram
void Print_Cave_Diagram(const vector<string> &cave_diagram){
for (auto s : cave_diagram)
cout<<s <<endl;
}
// Implement these functions below
// Do not change the function prototpyes
void Initialize_Cave(map<vector<int>, set<string> > &cave);
void Print_Square(map<vector<int>, set<string> > &cave);
void Get_Cave_Diagram(map<vector<int>, set<string> > &cave, vector<string> &cave_diagram);
// sample main function
int main() {
map<vector<int>, set<string> > cave;
Initialize_Cave(cave);
Print_Square(cave);
vector<string> cave_diagram;
Get_Cave_Diagram(cave, cave_diagram);
Print_Cave_Diagram(cave_diagram);
return 0;
}
// add the player, ladder, wumpus, pits, gold, stench, breeze to the map
// input:
// output:
void Initialize_Cave(map<vector<int>, set<string> > &cave) {
srand(time(NULL));
// place the "ladder" in row 1 column 1
cave[{1,1}].insert("ladder");
// place the "player" at the same location as the ladder
cave[{1,1}].insert("player");
// place the "wumpus" - can't be in the same square as the ladder
int random1 = 2+(rand()%3);
int random2 = 2+(rand()%3);
cave[{random1,random2}].insert("wumpus");
// place the 3 "pits" - can't be in the same square as the ladder, wumpus, or another pit
int random3 = 2+(rand()%3);
int random4 = 2+(rand()%3);
int random5 = 2+(rand()%3);
int random6 = 2+(rand()%3);
int random7 = 2+(rand()%3);
int random8 = 2+(rand()%3);
while(random1 == random3 && random2 == random4)
{
random3 = 2+(rand()%3);
random4 = 2+(rand()%3);
}
cave[{random3,random4}].insert("pit");
while(random3 == random5 && random4 == random6)
{
random5 = 2+(rand()%3);
random6 = 2+(rand()%3);
}
cave[{random5,random6}].insert("pit");
while(random5 == random7 && random6 == random8)
{
random7 = 2+(rand()%3);
random8 = 2+(rand()%3);
}
cave[{random7,random8}].insert("pit");
// place the "gold" - can't be in the same square as a pit or the ladder
int random9 = 2+(rand()%3);
int random10 = 2+(rand()%3);
while((random9 == random3 && random10 == random4) || (random9 == random5 && random10 == random6) || (random9 == random7 && random10 == random8))
{
random9 = 2+(rand()%3);
random10 = 2+(rand()%3);
}
cave[{random9,random10}].insert("gold");
// place the "stench" squares to the left, right, up, and down from the wumpus
cave[{random1,random2+1}].insert("stench");
cave[{random1,random2-1}].insert("stench");
cave[{random1-1,random2}].insert("stench");
cave[{random1+1,random2}].insert("stench");
// place the "breeze" squares to the left, right, up, and down from the three pits
cave[{random3,random4+1}].insert("breeze");
cave[{random3,random4-1}].insert("breeze");
cave[{random3-1,random4}].insert("breeze");
cave[{random3+1,random4}].insert("breeze");
cave[{random5,random6+1}].insert("breeze");
cave[{random5,random6-1}].insert("breeze");
cave[{random5-1,random6}].insert("breeze");
cave[{random5+1,random6}].insert("breeze");
cave[{random7,random8+1}].insert("breeze");
cave[{random7,random8-1}].insert("breeze");
cave[{random7-1,random8}].insert("breeze");
cave[{random7+1,random8}].insert("breeze");
}
// print the contents of the square
// input:
// output:
void Print_Square(map<vector<int>, set<string> > &cave) {
for (int r=1; r<=4; r++) {
for (int c=1; c<=4; c++) {
cout << r<< ", "<< c << endl;
cout << "This part of the cave contains" << endl;
if(cave[{r,c}].empty() != false)
{
cout<<" nothing"<<endl<<endl;
}
if (cave[{r,c}].empty() == false)
{
for(set<string>::iterator it = cave[{r,c}].begin(); it != cave[{r,c}].end(); it++)
{
cout<<" "<<*it<<endl;
}
cout<<endl;
}
}
}
}
// build a vector of strings where each string in the vector represents one row of the cave output
// input:
// output:
void Get_Cave_Diagram(map<vector<int>, set<string> > &cave, vector<string> &cave_diagram) {
int cell_rows = 5;
int cell_columns = 11;
int total_rows = cell_rows*4 + 1;
int total_columns = cell_columns*4 + 1;
// fill in with vertical cell divisions
for (int r=0; r<total_rows; r++) {
string row(total_columns, ' ');
for (int c=0; c<total_columns; c+=cell_columns) {
row[c] = '|';
}
cave_diagram.push_back(row);
}
// udpate horizontal rows with '-'
for (int i=0; i<total_rows; i+=cell_rows) {
cave_diagram[i] = string(total_columns, '-');
}
// update cell corners with '+'
for (int r=0; r<total_rows; r+=cell_rows) {
for (int c=0; c<total_columns; c+=cell_columns) {
cave_diagram[r][c]='+';
}
}
// replace the part of the string with the cell contents
for (int c=1; c<=4; c++)
{
for (int r=1; r<=4; r++)
{
for(set<string>::iterator it = cave[{r,c}].begin(); it != cave[{r,c}].end(); it++)
{
string word = *it;
for(int i=0; i< word.length(); i++)
{
char letter = word.at(i);
if(r == 1 && c == 1)
{
if(cave_diagram[2].at(3+i) != ' ')
{
cave_diagram[3].at(3+i) = letter;
}
else if(cave_diagram[1].at(3+i) != ' ')
{
cave_diagram[2].at(3+i) = letter;
}
else
cave_diagram[1].at(3+i) = letter;
}
if(r == 1 && c == 2)
{
if(cave_diagram[2].at(14+i) != ' ')
{
cave_diagram[3].at(14+i) = letter;
}
else if(cave_diagram[1].at(14+i) != ' ')
{
cave_diagram[2].at(14+i) = letter;
}
else
cave_diagram[1].at(14+i) = letter;
}
if(r == 1 && c == 3)
{
if(cave_diagram[2].at(25+i) != ' ')
{
cave_diagram[3].at(25+i) = letter;
}
else if(cave_diagram[1].at(25+i) != ' ')
{
cave_diagram[2].at(25+i) = letter;
}
else
cave_diagram[1].at(25+i) = letter;
}
if(r == 1 && c == 4)
{
if(cave_diagram[2].at(36+i) != ' ')
{
cave_diagram[3].at(36+i) = letter;
}
else if(cave_diagram[1].at(36+i) != ' ')
{
cave_diagram[2].at(36+i) = letter;
}
else
cave_diagram[1].at(36+i) = letter;
}
if(r == 2 && c == 1)
{
if(cave_diagram[7].at(3+i) != ' ')
{
cave_diagram[8].at(3+i) = letter;
}
else if(cave_diagram[6].at(3+i) != ' ')
{
cave_diagram[7].at(3+i) = letter;
}
else
cave_diagram[6].at(3+i) = letter;
}
if(r == 2 && c == 2)
{
if(cave_diagram[7].at(14+i) != ' ')
{
cave_diagram[8].at(14+i) = letter;
}
else if(cave_diagram[6].at(14+i) != ' ')
{
cave_diagram[7].at(14+i) = letter;
}
else
cave_diagram[6].at(14+i) = letter;
}
if(r == 2 && c == 3)
{
if(cave_diagram[7].at(25+i) != ' ')
{
cave_diagram[8].at(25+i) = letter;
}
else if(cave_diagram[6].at(25+i) != ' ')
{
cave_diagram[7].at(25+i) = letter;
}
else
cave_diagram[6].at(25+i) = letter;
}
if(r == 2 && c == 4)
{
if(cave_diagram[7].at(36+i) != ' ')
{
cave_diagram[8].at(36+i) = letter;
}
else if(cave_diagram[6].at(36+i) != ' ')
{
cave_diagram[7].at(36+i) = letter;
}
else
cave_diagram[6].at(36+i) = letter;
}
if(r == 3 && c == 1)
{
if(cave_diagram[12].at(3+i) != ' ')
{
cave_diagram[13].at(3+i) = letter;
}
else if(cave_diagram[11].at(3+i) != ' ')
{
cave_diagram[12].at(3+i) = letter;
}
else
cave_diagram[11].at(3+i) = letter;
}
if(r == 3 && c == 2)
{
if(cave_diagram[12].at(14+i) != ' ')
{
cave_diagram[13].at(14+i) = letter;
}
else if(cave_diagram[11].at(14+i) != ' ')
{
cave_diagram[12].at(14+i) = letter;
}
else
cave_diagram[11].at(14+i) = letter;
}
if(r == 3 && c == 3)
{
if(cave_diagram[12].at(25+i) != ' ')
{
cave_diagram[13].at(25+i) = letter;
}
else if(cave_diagram[11].at(25+i) != ' ')
{
cave_diagram[12].at(25+i) = letter;
}
else
cave_diagram[11].at(25+i) = letter;
}
if(r == 3 && c == 4)
{
if(cave_diagram[12].at(36+i) != ' ')
{
cave_diagram[13].at(36+i) = letter;
}
else if(cave_diagram[11].at(36+i) != ' ')
{
cave_diagram[12].at(36+i) = letter;
}
else
cave_diagram[11].at(36+i) = letter;
}
if(r == 4 && c == 1)
{
if(cave_diagram[17].at(3+i) != ' ')
{
cave_diagram[18].at(3+i) = letter;
}
else if(cave_diagram[16].at(3+i) != ' ')
{
cave_diagram[17].at(3+i) = letter;
}
else
cave_diagram[16].at(3+i) = letter;
}
if(r == 4 && c == 2)
{
if(cave_diagram[17].at(14+i) != ' ')
{
cave_diagram[18].at(14+i) = letter;
}
else if(cave_diagram[16].at(14+i) != ' ')
{
cave_diagram[17].at(14+i) = letter;
}
else
cave_diagram[16].at(14+i) = letter;
}
if(r == 4 && c == 3)
{
if(cave_diagram[17].at(25+i) != ' ')
{
cave_diagram[18].at(25+i) = letter;
}
else if(cave_diagram[16].at(25+i) != ' ')
{
cave_diagram[17].at(25+i) = letter;
}
else
cave_diagram[16].at(25+i) = letter;
}
if(r == 4 && c == 4)
{
if(cave_diagram[17].at(36+i) != ' ')
{
cave_diagram[18].at(36+i) = letter;
}
else if(cave_diagram[16].at(36+i) != ' ')
{
cave_diagram[17].at(36+i) = letter;
}
else
cave_diagram[16].at(36+i) = letter;
}
}
}
}
}
}
| [
"yiyanglin@YiYang-Lins-MacBook.local"
] | yiyanglin@YiYang-Lins-MacBook.local |
1e1fd808169f2a2f264cf57750d18ecb19c922bd | eab70ad1a99d2542f0328baed80b554c76c7a1e5 | /SDLEngine/GComboHandler.cpp | 9fdf8594ce74f9976341064171d46ab00f09b3bd | [] | no_license | EZroot/StarShooter | 4874bf6c8848119478bcba8081acc55b944bced2 | 7d17d05961444a75eb90810130a52721b9c5d442 | refs/heads/master | 2021-12-14T21:25:05.604006 | 2021-11-20T02:26:41 | 2021-11-20T02:26:41 | 151,177,023 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,223 | cpp | #include "GComboHandler.h"
#include "ELog.h"
GComboHandler::GComboHandler()
{
}
GComboHandler::~GComboHandler()
{
}
void GComboHandler::AddKill()
{
killCounter++;
}
void GComboHandler::AddScore(int score)
{
switch(killMultiplier)
{
case 2:
playerScore += score * 2;
break;
case 3:
playerScore += score * 3;
break;
case 4:
playerScore += score * 4;
break;
case 5:
playerScore += score * 5;
break;
default:
playerScore += score;
break;
}
}
void GComboHandler::UpdateCombos(float updateStep)
{
//If we just killed someone
if (killCounter > (prevCounter+1))
{
prevCounter = killCounter; //record kill
shakeCamera = true;
//check if our timer is running for a multiplier
if (killMultiplier <= 3 && killTimer > 0) //limit multiplier to 3
{
killMultiplier++; //go up a multiplier
}
//reset timer
killTimer = 60;
}
//Update timer
if (killTimer > 0)
{
killTimer -= 1;
}
//End camera shake
if (killTimer <= 50)
{
//Default camera shake
shakeCamera = false;
}
//End multiplier
if (killTimer <= 0)
{
killMultiplier = 0;
killTimer = 0;
}
}
int GComboHandler::killCounter = 0;
int GComboHandler::killMultiplier = 0;
int GComboHandler::playerScore = 0; | [
"utohaha@gmail.com"
] | utohaha@gmail.com |
20d67f69017c42a3220345bf2ae40d36b8d24ef5 | 07191b583c3a78c397931aeff47ffa53155da549 | /Library/Vector3.h | 9c5c58d2cd3e682c790a24cbb5ee858136278027 | [
"MIT"
] | permissive | allenbrubaker/raytracer | f3289dd3933cc566270458c1e07287eb281c2b06 | 29b3af0fc26ea95998a32ae0ec5d6f48eb433e9e | refs/heads/master | 2021-01-20T04:47:24.488026 | 2014-11-19T04:46:05 | 2014-11-19T04:46:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,672 | h | #ifndef VECTOR3_H
#define VECTOR3_H
#include <math.h>
#include <stdlib.h>
#include <assert.h>
#include <iostream.h>
#include <iomanip.h>
class Vector3 {
public:
Vector3() { e[0] = 0; e[1] = 0; e[2] = 0;}
Vector3(float e0, float e1, float e2) {e[0]=e0; e[1]=e1; e[2]=e2;}
float x() const { return e[0]; }
float y() const { return e[1]; }
float z() const { return e[2]; }
void setX(float a) { e[0] = a; }
void setY(float a) { e[1] = a; }
void setZ(float a) { e[2] = a; }
inline Vector3(const Vector3 &v) {
e[0] = v.e[0]; e[1] = v.e[1]; e[2] = v.e[2];
}
const Vector3& operator+() const { return *this; }
Vector3 operator-() const { return Vector3(-e[0], -e[1], -e[2]); }
float& operator[](int i) { return e[i]; }
float operator[](int i) const { return e[i];}
Vector3& operator+=(const Vector3 &v2);
Vector3& operator-=(const Vector3 &v2);
Vector3& operator*=(const float t);
Vector3& operator/=(const float t);
float length() const { return sqrt(e[0]*e[0] + e[1]*e[1] + e[2]*e[2]); }
float squaredLength() const { return e[0]*e[0] + e[1]*e[1] + e[2]*e[2]; }
void makeUnitVector();
float minComponent() const { return e[indexOfMinComponent()]; }
float maxComponent() const { return e[indexOfMaxComponent()]; }
float maxAbsComponent() const { return e[indexOfMaxAbsComponent()]; }
float minAbsComponent() const { return e[indexOfMinAbsComponent()]; }
int indexOfMinComponent() const {
return (e[0]< e[1] && e[0]< e[2]) ? 0 : (e[1] < e[2] ? 1 : 2);
}
int indexOfMinAbsComponent() const {
if (fabs(e[0]) < fabs(e[1]) && fabs(e[0]) < fabs(e[2]))
return 0;
else if (fabs(e[1]) < fabs(e[2]))
return 1;
else
return 2;
}
int indexOfMaxComponent() const {
return (e[0]> e[1] && e[0]> e[2]) ? 0 : (e[1] > e[2] ? 1 : 2);
}
int indexOfMaxAbsComponent() const {
if (fabs(e[0]) > fabs(e[1]) && fabs(e[0]) > fabs(e[2]))
return 0;
else if (fabs(e[1]) > fabs(e[2]))
return 1;
else
return 2;
}
float e[3];
};
inline bool operator==(const Vector3 &t1, const Vector3 &t2) {
return ((t1[0]==t2[0])&&(t1[1]==t2[1])&&(t1[2]==t2[2]));
}
inline bool operator!=(const Vector3 &t1, const Vector3 &t2) {
return ((t1[0]!=t2[0])||(t1[1]!=t2[1])||(t1[2]!=t2[2]));
}
inline istream &operator>>(istream &is, Vector3 &t) {
is >> t[0] >> t[1] >> t[2];
return is;
}
inline ostream &operator<<(ostream &os, const Vector3 &t) {
os << t[0] << " " << t[1] << " " << t[2];
return os;
}
inline Vector3 unitVector(const Vector3& v) {
float k = 1.0f / sqrt(v.e[0]*v.e[0] + v.e[1]*v.e[1] + v.e[2]*v.e[2]);
return Vector3(v.e[0]*k, v.e[1]*k, v.e[2]*k);
}
inline void Vector3::makeUnitVector() {
float k = 1.0f / sqrt(e[0]*e[0] + e[1]*e[1] + e[2]*e[2]);
e[0] *= k; e[1] *= k; e[2] *= k;
}
inline Vector3 operator+(const Vector3 &v1, const Vector3 &v2) {
return Vector3( v1.e[0] + v2.e[0], v1.e[1] + v2.e[1], v1.e[2] + v2.e[2]);
}
inline Vector3 operator-(const Vector3 &v1, const Vector3 &v2) {
return Vector3( v1.e[0] - v2.e[0], v1.e[1] - v2.e[1], v1.e[2] - v2.e[2]);
}
inline Vector3 operator*(float t, const Vector3 &v) {
return Vector3(t*v.e[0], t*v.e[1], t*v.e[2]);
}
inline Vector3 operator*(const Vector3 &v, float t) {
return Vector3(t*v.e[0], t*v.e[1], t*v.e[2]);
}
inline Vector3 operator/(const Vector3 &v, float t) {
return Vector3(v.e[0]/t, v.e[1]/t, v.e[2]/t);
}
inline float dot(const Vector3 &v1, const Vector3 &v2) {
return v1.e[0] *v2.e[0] + v1.e[1] *v2.e[1] + v1.e[2] *v2.e[2];
}
inline Vector3 cross(const Vector3 &v1, const Vector3 &v2) {
return Vector3( (v1.e[1]*v2.e[2] - v1.e[2]*v2.e[1]),
(v1.e[2]*v2.e[0] - v1.e[0]*v2.e[2]),
(v1.e[0]*v2.e[1] - v1.e[1]*v2.e[0]));
}
inline Vector3& Vector3::operator+=(const Vector3 &v){
e[0] += v.e[0];
e[1] += v.e[1];
e[2] += v.e[2];
return *this;
}
inline Vector3& Vector3::operator-=(const Vector3& v) {
e[0] -= v.e[0];
e[1] -= v.e[1];
e[2] -= v.e[2];
return *this;
}
inline Vector3& Vector3::operator*=(const float t) {
e[0] *= t;
e[1] *= t;
e[2] *= t;
return *this;
}
inline Vector3& Vector3::operator/=(const float t) {
e[0] /= t;
e[1] /= t;
e[2] /= t;
return *this;
}
inline
Vector3 reflect(const Vector3& in, const Vector3& normal)
{
// assumes unit length normal
return in - normal * (2 * dot(in, normal));
}
inline float cos_theta(const Vector3& u, const Vector3& v)
{
return dot(u,v) / (u.length()*v.length());
}
#endif
| [
"allenbrubaker@gmail.com"
] | allenbrubaker@gmail.com |
fd385161ae28adbbb1e9172134478351be102639 | 4442c37280e426d963304e5863cb25c96fff9e2a | /include/cefal/instances/monoid/with_functions.h | f1bb3877379a70e3010d2f2bd7b989a3bd4adf40 | [
"BSD-3-Clause"
] | permissive | codereport/cefal | 2f2cee47897636dab2fc391492e5e66fd67d9d1b | e5b37ffff77d9b9a147c7aa6e3bb8d64b77ed212 | refs/heads/master | 2021-05-19T16:24:21.738435 | 2020-03-31T23:55:01 | 2020-03-31T23:55:01 | 252,025,749 | 0 | 0 | BSD-3-Clause | 2020-03-31T23:53:50 | 2020-03-31T23:53:49 | null | UTF-8 | C++ | false | false | 2,439 | h | /* Copyright 2020, Dennis Kormalev
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holders nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#pragma once
#include "cefal/common.h"
#include "cefal/monoid.h"
#include <algorithm>
#include <type_traits>
namespace cefal::instances {
namespace detail {
template <typename T>
struct MonoidFromFunctionsExists {
using type = T;
};
} // namespace detail
template <detail::HasMonoidMethods T>
struct Monoid<T> {
static T empty() { return T::empty(); }
template <typename T1, typename T2>
static T append(T1&& left, T2&& right) {
static_assert(std::is_same_v<std::remove_cvref_t<T1>, T>, "Argument type should be the same as monoid");
static_assert(std::is_same_v<std::remove_cvref_t<T2>, T> || std::is_same_v<std::remove_cvref_t<T2>, helpers::SingletonFrom<T>>,
"Argument type should be the same as monoid");
return std::forward<T1>(left).append(std::forward<T2>(right));
}
};
} // namespace cefal::instances
| [
"kormalev.denis@gmail.com"
] | kormalev.denis@gmail.com |
68d9669e578175abdf62a9a4e58c61b65204b303 | 80cf6334fb1330b74998423da1bd1cd7700d42f5 | /cpp_flySingleTracer_multiTask/classes/MVideoManager.hpp | de602771459023a948bf9aeaee827e37093b127c | [
"MIT"
] | permissive | yzyw0702/flySleepPrograms | 144750e58b83699b472d5b0ffe1feb30e05f6c3a | 402a31261963992dc8439e4326cb7bca5487c684 | refs/heads/master | 2020-04-17T04:30:44.112879 | 2019-01-19T05:27:10 | 2019-01-19T05:27:10 | 166,233,063 | 2 | 0 | null | 2019-01-18T03:09:17 | 2019-01-17T13:46:51 | Python | UTF-8 | C++ | false | false | 8,178 | hpp | #ifndef _MVIDEOMANAGER_HPP_
#define _MVIDEOMANAGER_HPP_
#include "MMacros.h"
#include "MDataManager.hpp"
using namespace cv;
class MVideoManager { //singleton
private:
/* I/O communication with MDataManager */
string data_rootPath; // root path of video clips, configurations etc.
vector<string> _VNameClips; // name list of clips
vector<int> _VLenClips; // length list of clips
int _iLastClip; // index of clip traced last time
int _iLastFrIC; // index of frame traced last time (in last clip)
bool _isStartFromDenovo; // switch on when start from de novo
bool _isStartFromLatest; // switch on when start from latest
cv::VideoCapture* _pClip; // video pointer
int _iFrIC; // frame index within current clip
int _iClip; // clip index
int _cFrIC; // frame number of current clip
int _cTtFr; // total frame number of clips
int _cClips; // clip number
int _fps; // frame per second
int _cps; // call per second
int _jump; // frames jump per call
private: // init operations
// default
void init_default() {
data_rootPath = ".\\";
_iLastClip = 0;
_iLastFrIC = 0;
_isStartFromDenovo = false;
_isStartFromLatest = false;
_iFrIC = 1;
_cFrIC = 0;
_cTtFr = 0;
_cClips = 0;
_cps = 1;
_pClip = new VideoCapture;
}
// initialization
/// <summary>
/// init data manager
/// </summary>
/// <param name="pManData"> data manager pointer </param>
/// <return> false=failed, true=success </return>
bool init_with(
int cps = 1
) {
_cTtFr = 0;
string fListOfClips = data_rootPath + string("list.txt");
appendVideoSeries(fListOfClips); // load video series
_pClip = new VideoCapture; // get initial video
int isContinueFromLast=0;//discuss which time point to start
//cout<<"Do you want to continue from last tracing progress?\n"
// <<"[0=no, 1=yes] Your answer = ";
//cin>>isContinueFromLast;
if (isContinueFromLast)
initFromLatest();
else
initFromDeNovo();
_cClips = (int) _VNameClips.size();//get video info
_cFrIC = (int) _pClip->get(CV_CAP_PROP_FRAME_COUNT);
_fps = (int) _pClip->get(CV_CAP_PROP_FPS);
if(isContinueFromLast) _iClip = _iLastClip;
else _iClip = _iLastClip = 0;
if(isContinueFromLast) {
_iLastFrIC -= (_iLastFrIC % _fps); // adjust to nearest keyframe
_iFrIC = max(_iLastFrIC - mod_dynamic_length, 0 ); // reserve a number of frames to compute bg
} else {
_iFrIC = _iLastFrIC = 1;
}
_cps = cps; // get cps and jump length
_jump = _fps/_cps - 1;
if(!_pClip->set(CV_CAP_PROP_POS_FRAMES,_iFrIC)) { // set frame pointer to required position
cout<<"video pointer failed to reset to "<<_iFrIC<<endl;
} return true;
}
public: // constructors
MVideoManager( const char* rootPath=".\\", int cps=1 ) {
init_default();
initRootPath(rootPath);
init_with(cps);
}
public: // append operations
bool appendClip(string& fNameClip) {
string pathClips = data_rootPath + fNameClip;
if ((int)_access(pathClips.c_str(), 0) == 0) { //check if exist
// register this clip
_VNameClips.push_back(pathClips);
// collect clip info
VideoCapture cap(pathClips);
int currLen = (int)cap.get(CV_CAP_PROP_FRAME_COUNT);
_VLenClips.push_back(currLen);
//cout << pathClips << ": successfully loaded.\n";
// refresh total frame number
_cTtFr += currLen;
cap.release();
return true;
} else {
cout << pathClips << ": cannot be accessed.\n";
return false;
}
}
//bind videos by selection
void appendVideoSeries(string& fNameClips = string()) {
//ask list of input video
string fidxVid;
if( fNameClips.size() > 0 ) {
fidxVid = fNameClips;
} else {
cout<<"input video list: ";
cin>>fidxVid;
}
// establish an input file stream
ifstream fsIdxVid(fidxVid,ios::in);
//scan list
string nameVid;
int cOkLoaded=0,cNotLoaded=0;
while(getline(fsIdxVid,nameVid)) {
if(appendClip(nameVid)) {
cOkLoaded++;
} else {
cNotLoaded++;
}
}
cout << "\t" <<cOkLoaded<<" files loaded; " <<cNotLoaded<<" files failed.\n";
}
public: // play operations
//start a new trace
void initFromDeNovo() {
_pClip->open(_VNameClips[0]);
}
//continue trace from last time
void initFromLatest() {
//set video
if( (int)_access_s("traceRange.txt",0) != 0 ) {
initFromDeNovo();
} else {
_pClip->open( _VNameClips[_iLastClip] );
}
}
public: // set operations
void initRootPath(const char* rootPath) {
data_rootPath = rootPath;
}
//reset frame pointer
//## necessary before start tracking
bool resetTimer(int iClip = -1,int iFrInClip=-1) {
// set clip idx
if(iClip >= 0) {
_iClip = iClip;
}
_pClip->release();
_pClip->open(_VNameClips[_iClip]);
_cFrIC = _VLenClips[_iClip];
// set frame idx
if(iFrInClip > 0) {
_iFrIC = iFrInClip;
}
else {
_iFrIC = 0;
}
return _pClip->set(CV_CAP_PROP_POS_FRAMES,_iFrIC);
}
bool resetContinuousTimer(int iFr) {
int cFr = 0;
for (_iClip = 0; cFr <= iFr; _iClip++) {
cFr += _VLenClips[_iClip];
}
_iClip--; // go back to current clip
cFr -= _VLenClips[_iClip]; // remove the extra clip length
_iFrIC = iFr - cFr; // locate exact frame idx in current clip
_pClip->release(); // reopen clip pointer at this clip, at this frame
_pClip->open(_VNameClips[_iClip]);
return _pClip->set(CV_CAP_PROP_POS_FRAMES, _iFrIC);
}
//switch to next vieo if required
//## true: next video is available
//## false: the end of all videos
bool setNextVideo() {
//close current video
_pClip->release();
_iClip++;
//check and set to the next
if(_iClip < _cClips) { //go to next video
_iLastClip = _iClip;
_pClip->open(_VNameClips[_iClip]);
//refresh In-Clip properties
_cFrIC = (int) _pClip->get(CV_CAP_PROP_FRAME_COUNT);
_iFrIC = 0;
return true;
} else { //the END of clip series
return false;
}
}
public: // get operations
// write stream
void writeData(MDataManager* pManData) {
char data[64];
sprintf(data,"%d\t%d\n",_iClip,_iFrIC);
(*pManData->vid_pIofsTimes) << data;
}
// export configuration to data manager
void exportConfig(MDataManager* pManData) {
FileStorage* pFsConfig = new FileStorage(pManData->data_fConfig, FileStorage::APPEND);
if(!pFsConfig->isOpened()) { // avoid invalid storage
cout << "Export vid_config failed!\n";
return;
}
(*pFsConfig) << "vid_iClipOfLast" << _iLastClip;
(*pFsConfig) << "vid_iFrICOfLast" << _iLastFrIC;
(*pFsConfig) << "vid_VNameOfClips" << _VNameClips;
(*pFsConfig) << "vid_VLenOfClips" << _VLenClips;
(*pFsConfig) << "vid_callPerSeconds" << _cps;
// instantly save it
pFsConfig->release();
}
//get cps-based frame, change video if necessary
//## true: frame acquired;
//## false: reach the video end
bool readPerCall(Mat& fr){
//get frame if available
_pClip->read(fr);
//get video pointer position
for(int i=0;i<_jump;i++) {
if(_iFrIC + i > _cFrIC - _jump + 1) {
break;
} _pClip->grab();
}
//refresh time
_iFrIC += 1 + _jump;
if (_iFrIC >= _cFrIC - _jump + 1) {
if( !setNextVideo() ) {
return false;
}
cout << "switch to clip: " << _VNameClips[_iClip] << endl;
} return true;
}
void setCps(int cps) {
_cps = cps;
_jump = _fps / _cps - 1;
}
void setJump(int jump) {
_jump = jump;
_cps = _fps / (_jump + 1);
}
string getRootPath() {
return data_rootPath;
}
//get call per second
int getCps() {
return _cps;
}
//get frame per second
int getFps() {
return _fps;
}
// get total frame number
int getLength() {
return _cTtFr;
}
//get video pointer
VideoCapture* getClipPtr() {
return _pClip;
}
//get indices of Video and frame
void getTime(int& iVid, int& iFr) {
iVid = _iClip;
iFr = _iFrIC;
}
};
#endif | [
"noreply@github.com"
] | yzyw0702.noreply@github.com |
2f672054055474c674eb962a4b214a6abb86406a | 8dc84558f0058d90dfc4955e905dab1b22d12c08 | /third_party/blink/renderer/core/dom/idle_deadline.cc | 371bd32be33fd2eadd0069cb8e45ce77baaabdb4 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"LGPL-2.0-only",
"BSD-2-Clause",
"LGPL-2.1-only",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | permissive | meniossin/src | 42a95cc6c4a9c71d43d62bc4311224ca1fd61e03 | 44f73f7e76119e5ab415d4593ac66485e65d700a | refs/heads/master | 2022-12-16T20:17:03.747113 | 2020-09-03T10:43:12 | 2020-09-03T10:43:12 | 263,710,168 | 1 | 0 | BSD-3-Clause | 2020-05-13T18:20:09 | 2020-05-13T18:20:08 | null | UTF-8 | C++ | false | false | 1,096 | cc | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/dom/idle_deadline.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/core/timing/performance.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
namespace blink {
IdleDeadline::IdleDeadline(double deadline_seconds, CallbackType callback_type)
: deadline_seconds_(deadline_seconds), callback_type_(callback_type) {}
double IdleDeadline::timeRemaining() const {
double time_remaining = deadline_seconds_ - CurrentTimeTicksInSeconds();
if (time_remaining < 0) {
return 0;
} else if (Platform::Current()
->CurrentThread()
->Scheduler()
->ShouldYieldForHighPriorityWork()) {
return 0;
}
return 1000.0 * Performance::ClampTimeResolution(time_remaining);
}
} // namespace blink
| [
"arnaud@geometry.ee"
] | arnaud@geometry.ee |
8bc5515db11bcc76490914c83a5c0ba2c10ea5b0 | 55a56b8abfa4bc18f0ff21622472879a98b2cbc9 | /Rozgrzewka3/SigmoidFunction.cpp | 5ce3ab12844714ac29547d941bea5fe1301c913b | [] | no_license | lorthal/IAD1 | e4cf335e7a3255cc62594445790bf896a7367c9c | adb922fc41325887f3c427baa4ac2ee2262b352b | refs/heads/master | 2020-03-10T17:49:30.658980 | 2019-04-01T11:25:08 | 2019-04-01T11:25:08 | 129,509,438 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 388 | cpp | #include "stdafx.h"
#include "SigmoidFunction.h"
#include "math.h"
double SigmoidFunction::GetResult(const double &input)
{
return 1 / (1 + exp(-input));
}
double SigmoidFunction::GetDerivativeFromInput(const double &input)
{
return GetResult(input) * (1 - GetResult(input));
}
double SigmoidFunction::GetDerivativeFromOutput(const double &output)
{
return (1 - output) * output;
}
| [
"bkluchcinski@gmail.com"
] | bkluchcinski@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.