blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 117 | path stringlengths 3 268 | src_encoding stringclasses 34
values | length_bytes int64 6 4.23M | score float64 2.52 5.19 | int_score int64 3 5 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | text stringlengths 13 4.23M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
a3306b230aa3082705a6a08873f44a95343ef0e2 | C++ | denofiend/acm | /pku/1157/5036244_CE.cc | UTF-8 | 1,467 | 2.65625 | 3 | [] | no_license | // 1157(pku)
#include <iostream>
#define INF -200
#define MAXN 110
using namespace std;
template <class T> void out(T x, int n){ for (int i = 0; i < n; i ++) cout << x[i] << ' '; cout << endl; }
template <class T> void out(T x, int n, int m){ for (int i = 0; i < n; i ++) out(x[i], m); cout << endl; }
int main(){
int F, V;
int val[MAXN][MAXN], f[MAXN][MAXN];
int i, j, k;
while (2 == scanf("%d %d", &F, &V))
{
for (i = 1; i <= F; i ++)
{
for (j = 1; j <= V; j ++)
{
scanf("%d", &val[i][j]);
}
}
// for (i = 1; i <= V; i ++) f[i][i] = f[i - 1][i - 1] + val[i][i];
// //out(f, V + 1, F + 1);
// for (i = 1; i <= V; i ++)
// {
// for (j = 1; j < i; j ++)
// {
// f[i][j] = max(f[i - 1][j - 1] + val[j][i], f[i - 1][j]);
// }
// }
for (j = 1; j <= V; ++j) f[1][j] = val[j];
for (i = 2; i <= F; ++i)
{
for (j = i; j <= V; ++j)
{
f[i][j] = 0;
for (k = i; k < j; ++k)
{
f[i][j] = max(f[i][j], f[i-1][k]+val[i][j]);
}
}
}
int ans = 0;
for (i = F; i <= V; ++i)
if (ans < f[F][i]) ans = f[F][i]);
//out(f, V + 1, F + 1);
printf("%d\n", f[V][F]);
}
return 0;
}
| true |
fa131bd78fd43c0223d4143a3e197d2413cac9a0 | C++ | MariosKoni/4InARow | /Game/Game.hh | UTF-8 | 1,812 | 2.703125 | 3 | [] | no_license | #pragma once
#include "../Player/Player.hh"
#include "../Data/getData.hh"
#include "../NPC/NPC.hh"
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <string>
#include <list>
#include <utility>
#include <vector>
#include <memory>
#include <filesystem>
#include <thread>
class Game {
private:
std::filesystem::path p = std::filesystem::current_path();
std::string path;
int maxRounds;
int currentRound;
int choice;
int i;
bool canPlay = true;
int sock;
unsigned short int port;
struct sockaddr_in server_addr;
struct hostent *serv;
std::thread wConn;
std::vector<std::unique_ptr<Player>> pls;
std::unique_ptr<getData> map;
std::vector<std::pair<int, int>> spaces;
public:
Game(bool); //Constructor of the main class. Takes a bool that determines if it's a new or an old game
bool play(); //main game method
bool updateGame(); //method to erase vector and current round as well as check if the game has ended (round wise)
void checkAvailable(); //method that checks the available spots for the balls to be
bool checkIfPlayerWon(char); //Check if a player has won
void resetGame(); //Calls map.reset() and increments the round
void checkWinner(); //Checks who has won the game
void save(); //Saves data of current game to file
bool load(); //Loads a snapshot of the game and continues from there
bool getCanPlay(); //Returns the value of the attribute
void remindPlayer(); //Reminds player/players of the info they gave to the system
int getChoice(); //Returns the value of the choice
int getI(); //Returns i
void clientInit(unsigned short int, std::string&); // Initialize client
void sendClientToServer(std::unique_ptr<Player>&); // Send client to server
//void recvMsg(int);
std::thread& getwConnThread();
};
| true |
0da28d483f6cc4636de7d40f3ce633d06edbc1d2 | C++ | ajunlonglive/Hands-On-Design-Patterns-with-Qt-5 | /ch02/MySkipIterator/main.cpp | UTF-8 | 807 | 3.3125 | 3 | [
"MIT"
] | permissive | #include <QCoreApplication>
#include <QDebug>
#include "MySkipIterator.h"
int main(int argc, char *argv[])
{
Q_UNUSED(argc)
Q_UNUSED(argv)
// create our list
QList<int> list {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
// Create a SkipIterator for the list
MySkipIterator<int> listIter(&list, 1);
qDebug() << list; // display the list
// try traversing the list with skips 1 to 6
for (int i = 1; i < 7; ++i)
{
QList<int> items;
listIter.first();
listIter.setSkipValue(i);
while (listIter.hasNext()) // check if we can get another
{
items << listIter.currentElement();
listIter.next();
}
qDebug() << i << ":" << items;
}
return 0;
}
| true |
b6c191aad1f9a8a11980c539a0fe3efc7d825f18 | C++ | bragalucas1/ED | /pratica1/teste.cpp | UTF-8 | 880 | 3.25 | 3 | [] | no_license | #include <iostream>
using namespace std;
void encontraPosicoes(const int numeros[],int posicoes[], int n){
for(int i=0;i<n;i++){ //para cada numero i, descobre em qual posicao de numeros[] ele se encontra
for(int j=0;j<n;j++){//varre o array procurando a posicao onde i se encontra
if(numeros[j]==i){
posicoes[i] = j; //o numero i se encontra na posicao j do array...
break;
}
}
}
}
int main(){
int n;
cin >> n;
int *numeros = new int[n];
int *posicoes = new int[n];
//le a permutacao de numeros.
for(int i=0;i<n;i++) cin >> numeros[i];
for(int i=0;i<1000000;i++) { //Vamos medir o tempo de 1000 chamadas ! NAO altere isso!!!
encontraPosicoes(numeros,posicoes,n);
}
for(int i=0;i<n;i++) cout << posicoes[i] << " ";
cout << "\n";
delete []numeros;
delete []posicoes;
return 0;
} | true |
b9b73e90511b2ccdb8450a9a5937bd54bc88e6fa | C++ | rezavai92/Dimikoj-Problem-Solutions | /PerfectNumber2.cpp | UTF-8 | 780 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include <math.h>
using namespace std;
bool IsPrime (long int n){
if (n>1){
for (int i=2;i <= sqrt(n);i++){
if (n%i==0){
return false;
}
}
}
else {
return false;
}
return true;
}
bool IsPerfect ( long int n){
long int sum=1;
for ( long int i=2;i<=sqrt(n) ;i++ ){
if (n%i==0 && (n/i)!=i) {
sum+=i+(n/i);
}
else if (n%i==0 && (n/i)==i) {
sum+=i;
}
}
if (sum==n && n>1){
return true;
}
return false;
}
int main (){
int T;
cin>>T;
while (T--){
long int n;
cin>>n;
for (long int i=2;i<=n;i++){
if (IsPrime(i)&& i!= 11){
long long int perfect = (round(pow(2,i))-1) * round(pow(2,(i-1)));
if (perfect<=n){
cout<<perfect<<endl;
}
else{
break;
}
}
}
if (T!=0){
cout<<endl;
}
}}
| true |
b86cf9bf5daffe318834a86b4829272313414b1e | C++ | ckanibal/InertialSensors | /BMP085.cpp | UTF-8 | 2,115 | 2.546875 | 3 | [
"MIT"
] | permissive | // BMP085.cpp
#include "BMP085.h"
void initBMP085(int device, BMP085 *data) {
data->ac1 = readRegisterInt(device, 0xAA);
data->ac2 = readRegisterInt(device, 0xAC);
data->ac3 = readRegisterInt(device, 0xAE);
data->ac4 = readRegisterInt(device, 0xB0);
data->ac5 = readRegisterInt(device, 0xB2);
data->ac6 = readRegisterInt(device, 0xB4);
data->b1 = readRegisterInt(device, 0xB6);
data->b2 = readRegisterInt(device, 0xB6);
data->mb = readRegisterInt(device, 0xBA);
data->mc = readRegisterInt(device, 0xBC);
data->md = readRegisterInt(device, 0xBE);
}
void readTemperature(int device, unsigned int *data) {
setRegister(device, 0xF4, 0x2E); // request temperature
delay(5); // wait for the sensor to provide the data
*data = readRegisterInt(device, 0xF6);
}
void readPressure(int device, unsigned long *data) {
unsigned char msb, lsb, xlsb;
setRegister(device, 0xF4, 0x34);
delay(5);
msb = readRegister(device, 0xF6);
lsb = readRegister(device, 0xF7);
xlsb = readRegister(device, 0xF8);
*data = (((unsigned long) msb << 16) | ((unsigned long) lsb << 8) | (unsigned long) xlsb);
}
float getTemperature(unsigned int raw, BMP085 *data) {
long x1, x2;
x1 = (((long)raw - (long)data->ac6)*(long)data->ac5) >> 15;
x2 = ((long)data->mc << 11)/(x1 + data->md);
data->b5 = x1 + x2;
float temp = ((data->b5 + 8)>>4);
temp = temp /10;
return temp;
}
unsigned long getPressure(unsigned long raw, BMP085 *data) {
long x1, x2, x3, b3, b6, p;
unsigned long b4, b7;
b6 = data->b5 - 4000;
// Calculate B3
x1 = (data->b2 * (b6 * b6)>>12)>>11;
x2 = (data->ac2 * b6)>>11;
x3 = x1 + x2;
b3 = (((((long)data->ac1)*4 + x3)) + 2)>>2;
// Calculate B4
x1 = (data->ac3 * b6)>>13;
x2 = (data->b1 * ((b6 * b6)>>12))>>16;
x3 = ((x1 + x2) + 2)>>2;
b4 = (data->ac4 * (unsigned long)(x3 + 32768))>>15;
b7 = ((unsigned long)(raw - b3) * 50000);
if (b7 < 0x80000000) {
p = (b7<<1)/b4;
} else {
p = (b7/b4)<<1;
}
x1 = (p>>8) * (p>>8);
x1 = (x1 * 3038)>>16;
x2 = (-7357 * p)>>16;
p += (x1 + x2 + 3791)>>4;
return p;
}
| true |
552712900081ad0c1063c9b1a78e2a07132d8cc8 | C++ | ermahechap/Algorithms | /Homeworks/Fibonnacci/Fibo.cpp | UTF-8 | 1,460 | 3.3125 | 3 | [] | no_license | #include<bits/stdc++.h>
#define ll long long
using namespace std;
template<typename Type>
Type fibo(Type n){
Type a=0,b=1,temp;
for(Type i = 0 ;i<n;i++){
temp = b;//temp swap
b = a+b;
a = temp;
}
return a;
}
template<typename Type>
bool overflow(Type n){
return n<0;
}
int main(){
ll n;
cout<<"Fibo tester, input number > ";
cin>>n;
cout<<"fibo("<<n<<") = "<<fibo(n)<<'\n';
cout<<"-----Testing Basic Overflows------\n";
for(short i = 0 ; i<=SHRT_MAX;i++){
if(overflow(fibo(i))){
cout<<"> short overflows at: "<<i<<'\n';
break;
}
}
for(int i = 0 ; i<=INT_MAX;i++){
if(overflow(fibo(i))){
cout<<"> int overflows at: "<<i<<'\n';
break;
}
}
for(ll i = 0 ; i<=LLONG_MAX;i++){
if(overflow(fibo(i))){
cout<<"> long long overflows at: "<<i<<'\n';
break;
}
}
cout<<"-----Testing Unsigned Overflows------\n";
unsigned short last=0;
for(unsigned short i = 0 ; i<=USHRT_MAX;i++){
unsigned short cur = fibo(i);
if(cur<last){
cout<<"> unsigned short overflows at: "<<i<<'\n';
break;
}
last = cur;
}
unsigned int last1=0;
for(unsigned int i = 0 ; i<=UINT_MAX;i++){
unsigned int cur = fibo(i);
if(cur<last1){
cout<<"> unsigned int overflows at: "<<i<<'\n';
break;
}
last1 = cur;
}
unsigned ll last2=0;
for(unsigned ll i = 0 ; i<=ULLONG_MAX;i++){
unsigned ll cur = fibo(i);
if(cur<last2){
cout<<"> unsigned short overflows at: "<<i<<'\n';
break;
}
last2 = cur;
}
}
| true |
7ff7b12e15bea2f1eecf0d9d30593cc7f52e08f6 | C++ | vereddassa/HW9_CPP | /field.cpp | UTF-8 | 1,259 | 3.28125 | 3 | [] | no_license | /* Includes */
#include "field.h"
#include "ip.h"
#include "port.h"
#include <iostream>
#include <cstring>
Field::Field(String pattern, field_type type ) : pattern(pattern), type(type){
}
Field::Field(String pattern) {
this->pattern = pattern ;
this ->type = GENERIC;
}
Field::~Field() {}
field_type Field::get_type() const {
return this->type;
}
bool Field::set_value(String val) {
if (this->type == IP){
return ((Ip*)this)->set_value(val);
}
if( this->type == PORT){
return ((Port*)this)->set_value(val);
}
return false;
}
bool Field::match_value(String val) const {
if (this->type == IP){
return ((Ip*)this)->match_value(val);
}
if( this->type == PORT){
return ((Port*)this)->match_value(val);
}
return false;
}
bool Field::match(String packet) {
size_t field_cnt=0;
String *str_arr=NULL;
/* Now we place the packet's sub fields in the array */
packet.split(",=",&str_arr,&field_cnt);
if(field_cnt == 0){
delete[] str_arr;
return false;
}
/* checking each sub field if it matches the rule */
for(size_t i=0; i<field_cnt; i++){
if(str_arr[i].trim().equals(this->pattern.trim())){
bool res = this->match_value(str_arr[i+1].trim());
delete[] str_arr;
return res;
}
}
delete[] str_arr;
return false;
}
| true |
38bdc27a93b4e702dceaff3b6b626dbfb5606c65 | C++ | redheli/g2o_frontend | /g2o_frontend/sensor_data/sensor_handler.h | UTF-8 | 530 | 2.8125 | 3 | [] | no_license | #ifndef SENSORHANDLER_H_
#define SENSORHANDLER_H_
#include "sensor.h"
#include "priority_data_queue.h"
class SensorHandler {
public:
SensorHandler();
virtual Sensor* sensor() { return _sensor;}
virtual const Sensor* sensor() const { return _sensor;}
virtual bool setQueue(PriorityDataQueue* queue_) = 0;
virtual bool setSensor(Sensor* sensor_) {_sensor = sensor_; return true;}
virtual void registerCallback() = 0;
protected:
Sensor* _sensor;
PriorityDataQueue* _queue;
};
#endif //SENSORHANDLER_H_
| true |
c2790a61a1e02c0b8dec77cc56cf47c2e033a7e7 | C++ | cucxabong/algorithm | /c-cpp/basics/Algorithms/dijkstra.cpp | UTF-8 | 1,394 | 3.359375 | 3 | [] | no_license | // Simple Dijkstra implementation in C++
#include <iostream>
#include <queue>
using namespace std;
const int INF = 1e9;
typedef pair<int, int> pii;
void init(int *&path, int *&dist, int v) {
if (dist)
delete dist;
if (path)
delete path;
dist = new int[v];
path = new int[v];
for (int i = 0; i < v; i++) {
dist[i] = INF;
path[i] = -1;
}
}
struct comp {
bool operator() (const pii &a, const pii &b) {
return a.second > b.second;
}
};
void dijkstra(int *&path, vector<pii> *graph, int *&dist, const int v, const int src) {
priority_queue<pii, vector<pii>, comp> pq;
init(path, dist, v);
dist[src] = 0;
pq.push(make_pair(src, 0));
while (!pq.empty()) {
int u = pq.top().first;
pq.pop();
for (int i = 0; i < graph[u].size(); i++) {
int v = graph[u][i].first;
int w = graph[u][i].second;
if (dist[v] > dist[u] + w) {
dist[v] = dist[u] + w;
path[v] = u;
pq.push(make_pair(v, dist[v]));
}
}
}
}
/*
// Sample input
6 10
0 1 1
1 2 5
1 3 2
1 5 7
2 5 1
3 0 2
3 2 1
3 4 4
4 3 3
5 4 1
*/
int main() {
vector<pii> *graph;
int V, E, u, v, w;
int *dist, *path;
dist = NULL;
path = NULL;
cin >> V >> E;
graph = new vector<pii>[V];
for (int i = 0; i < E; i++) {
cin >> u >> v >> w;
graph[u].push_back(make_pair(v, w));
}
dijkstra(path, graph, dist, V, 0);
for (int i = 0; i < V; i++) {
cout << path[i] << " ";
}
return 0;
}
| true |
cb5eb9d8fefa406c9481ff80bdcc8d36d74843e1 | C++ | DevonPW/ConsoleStuff | /ConsoleStuff/main.cpp | UTF-8 | 865 | 3.015625 | 3 | [] | no_license | #include <stdlib.h>
#include <Windows.h>
#include <Tchar.h>
HANDLE wHnd; // Handle to write to the console.
HANDLE rHnd; // Handle to read from the console.
void main() {
// Set up the handles for reading/writing:
wHnd = GetStdHandle(STD_OUTPUT_HANDLE);
rHnd = GetStdHandle(STD_INPUT_HANDLE);
// Change the window title:
SetConsoleTitle(TEXT("Win32 Console Control Demo"));
// Set up the required window size:
SMALL_RECT windowSize = { 0, 0, 124, 41 };//{.Left, .Top, .Right, .Bottom}
// Change the console window size:
SetConsoleWindowInfo(wHnd, TRUE, &windowSize);
// Create a COORD to hold the buffer size:
COORD bufferSize = { 125, 42 };
// Change the internal buffer size:
SetConsoleScreenBufferSize(wHnd, bufferSize);
//set to fullscreen mode
SetConsoleDisplayMode(wHnd, CONSOLE_FULLSCREEN_MODE, &bufferSize);
system("pause");
}
| true |
c577738deaf051ad24ed99c849d2d4c7939b234a | C++ | nob13/smallcalc | /libsmallcalc/smallcalc/types.h | UTF-8 | 1,899 | 3 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <boost/unordered_map.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/function.hpp>
#include <boost/foreach.hpp>
#include "MathFunctions.h"
namespace sc {
using boost::shared_ptr;
using boost::unordered_map;
using boost::function;
typedef std::string String;
/// Small extensions to unorderd_map which finds a given key and returns it
/// assuming the value is a shared_ptr
template <class Key, class Type> shared_ptr<Type> findValuePtr(const unordered_map<Key, shared_ptr<Type> > & map, const String & key){
typename unordered_map<Key,shared_ptr<Type> >::const_iterator i = map.find (key);
if (i == map.end()) return shared_ptr<Type> ();
return shared_ptr<Type> (i->second);
}
/// Variable names
typedef int VariableId;
struct VariableIdMapping {
VariableIdMapping () : nextVariableId (1) {}
VariableId variableIdFor (const String & name) const;
typedef boost::unordered_map<String, VariableId> VariableNameMap; ///< Maps variable names to Ids
typedef boost::unordered_map<VariableId, String> ReverseVariableNameMap; ///< Maps variable Ids to names
mutable VariableNameMap variableIds;
mutable ReverseVariableNameMap variableNames;
mutable VariableId nextVariableId;
};
namespace error {
enum Error {
NoError = 0,
NotSupported,
Parser_ParanthesisMismatch, ///< Too much closing or wrong paranthesis count
Parser_NoValidToken,
Parser_NoTokens, ///< No tokens given
Parser_WrongArgumentCount, ///< Function applied with wrong number of arguments
Parser_UnknownFunction,
Eval_BadType, ///< Expression's check fails
Eval_InvalidOperation, ///< Cannot evaluate this expression (e.g. multiplying an error)
Eval_UnboundVariable, ///< Cannot evaluate variable; its unbound
Eval_DivisionByZero, ///< Division by Zero error
};
}
typedef error::Error Error;
using error::NoError;
typedef Fraction<int64_t> Fraction64;
}
| true |
d30420416d1047b4391ff494a0ff6ec0a6dc2201 | C++ | pine/BestDocumenter | /src/github/response/author.h | UTF-8 | 1,284 | 2.515625 | 3 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | #pragma once
#include <string>
#include <picojson.h>
#include "util.h"
using namespace picojson;
namespace github {
namespace response {
class Author;
using AuthorPtr = util::Ptr<Author>;
using AuthorArrayPtr = util::ArrayPtr<Author>;
class Author {
public:
std::string login;
int64_t id;
std::string avatarUrl;
// ----------------------------------------------------------------
template<class T = Author>
static util::Ptr<T> inflate(value val, std::string* err) {
auto res = std::make_shared<T>();
if (val.is<value::object>()) {
auto& obj = val.get<object>();
if (obj["login"].is<std::string>()) {
res->login = obj["login"].get<std::string>();
}
if (obj["id"].is<int64_t>()) {
res->id = obj["id"].get<int64_t>();
}
if (obj["avatar_url"].is<std::string>()) {
res->avatarUrl = obj["avatar_url"].get<std::string>();
}
}
return std::move(res);
}
};
}
}
| true |
f57c65faf41aea8a3e5ea4fc4831c107335537b9 | C++ | hexahedron74/C--Practice | /구조체를 이용한 친구 관리 프로그램.cpp | UHC | 1,970 | 3.609375 | 4 | [] | no_license | #include <stdio.h>
#define MAX_COUNT 6
typedef struct People
{
char name[14];
unsigned short int age;
float height;
float weight;
} Person;
int AddFriend(Person *p_friend, int count)
{
if(count < MAX_COUNT) {
p_friend = p_friend + count;
printf("\nο ģ Էϼ\n");
printf("1. ̸ : ");
scanf("%s", p_friend -> name);
printf("2. : ");
scanf("%hu", &p_friend -> age);
printf("3. Ű : ");
scanf("%f", &p_friend -> height);
printf("4. : ");
scanf ("%f", &p_friend -> weight);
printf("Է Ϸ߽ϴ. \n\n");
return 1;
} else {
printf("ִ ο ʰϿ Է ϴ. \n");
printf("ִ %d մϴ. \n\n", MAX_COUNT);
}
return 0;
}
void ShowFriendList(Person *p_friend, int count)
{
int i;
if(count > 0) {
printf("\nϵ ģ \n");
printf("==============================================\n");
for(i = 0; i < count; i++) {
printf("̸ - %-14s, - %3d, Ű - %6.2f, - %6.2f\n", p_friend -> name, p_friend -> age,
p_friend -> height, p_friend -> weight);
p_friend++;
}
printf("==============================================\n\n");
} else {
printf("\nϵ ģ ϴ.\n\n");
}
}
int main()
{
Person friends[MAX_COUNT];
int count = 0, num;
while(1) {
printf(" [] \n");
printf("==================\n");
printf("1. ģ ߰ \n");
printf("2. ģ \n");
printf("3. \n");
printf("==================\n");
printf("ȣ : ");
scanf("%d", &num);
if(num == 1) {
if(1 == AddFriend(friends, count)) count++;
} else if(num == 2) {
ShowFriendList(friends, count);
} else if (num == 3) {
break;
} else {
printf("1~3ȣ ֽϴ!!\n\n");
}
}
}
| true |
98b2725fad2d49af646c83030d685e9605c6467c | C++ | floriandotorg/MinecraftCpp | /abstract_block.hpp | UTF-8 | 269 | 2.625 | 3 | [] | no_license | #pragma once
#include <memory>
#include <glm/vec3.hpp>
class abstract_block
{
public:
typedef std::shared_ptr<abstract_block> ptr;
virtual ~abstract_block() {}
virtual void update(double dt) {}
virtual void draw(const glm::vec3 &pos) const = 0;
};
| true |
f99305b57b72c9d8ef331357157f8a571887d784 | C++ | BITERP/PinkRabbitMQ | /src/amqpcpp/reliable.h | UTF-8 | 8,634 | 2.703125 | 3 | [
"BSD-3-Clause",
"MIT"
] | permissive | /**
* Reliable.h
*
* A channel wrapper based on AMQP::Throttle that allows message callbacks to be installed
* on the publishes, to be called when they are confirmed by the message broker.
*
* @author Michael van der Werve <michael.vanderwerve@mailerq.com>
* @copyright 2020 Copernica BV
*/
/**
* Header guard
*/
#pragma once
/**
* Includes
*/
#include "deferredpublish.h"
#include "tagger.h"
#include <memory>
/**
* Begin of namespaces
*/
namespace AMQP {
/**
* Class definition
*/
template <typename BASE=Tagger>
class Reliable : public BASE
{
private:
// make sure it is a proper channel
static_assert(std::is_base_of<Tagger, BASE>::value, "base should be derived from a confirmed channel.");
/**
* Set of open deliverytags. We want a normal set (not unordered_set) because
* removal will be cheaper for whole ranges.
* @var size_t
*/
std::map<size_t, std::shared_ptr<DeferredPublish>> _handlers;
/**
* Called when the deliverytag(s) are acked
* @param deliveryTag
* @param multiple
*/
void onAck(uint64_t deliveryTag, bool multiple) override
{
// monitor the object, watching for destruction since these ack/nack handlers
// could destruct the object
Monitor monitor(this);
// single element is simple
if (!multiple)
{
// find the element
auto iter = _handlers.find(deliveryTag);
// we did not find it (this should not be possible, unless somebody explicitly called)
// the base-class publish methods for some reason.
if (iter == _handlers.end()) return BASE::onAck(deliveryTag, multiple);
// call the ack handler
iter->second->reportAck();
// if the monitor is no longer valid, we stop (we're done)
if (!monitor) return;
// erase it from the map
_handlers.erase(iter);
}
// do multiple at once
else
{
// call the handlers
for (auto iter = _handlers.begin(); iter != _handlers.end(); iter++)
{
// make sure this is the right deliverytag, if we've passed it we leap out
if (iter->first > deliveryTag) break;
// call the handler
iter->second->reportAck();
// if we were destructed in the meantime, we leap out
if (!monitor) return;
}
// erase all acknowledged items
_handlers.erase(_handlers.begin(), _handlers.upper_bound(deliveryTag));
}
// make sure the object is still valid
if (!monitor) return;
// call base handler as well
BASE::onAck(deliveryTag, multiple);
}
/**
* Called when the deliverytag(s) are nacked
* @param deliveryTag
* @param multiple
*/
void onNack(uint64_t deliveryTag, bool multiple) override
{
// monitor the object, watching for destruction since these ack/nack handlers
// could destruct the object
Monitor monitor(this);
// single element is simple
if (!multiple)
{
// find the element
auto iter = _handlers.find(deliveryTag);
// we did not find it (this should not be possible, unless somebody explicitly called)
// the base-class publish methods for some reason.
if (iter == _handlers.end()) return BASE::onNack(deliveryTag, multiple);
// call the ack handler
iter->second->reportNack();
// if the monitor is no longer valid, we stop (we're done)
if (!monitor) return;
// erase it from the map
_handlers.erase(iter);
}
// nack multiple elements
else
{
// call the handlers
for (auto iter = _handlers.begin(); iter != _handlers.end(); iter++)
{
// make sure this is the right deliverytag, if we've passed it we leap out
if (iter->first > deliveryTag) break;
// call the handler
iter->second->reportNack();
// if we were destructed in the meantime, we leap out
if (!monitor) return;
}
// erase all negatively acknowledged items
_handlers.erase(_handlers.begin(), _handlers.upper_bound(deliveryTag));
}
// if the object is no longer valid, return
if (!monitor) return;
// call the base handler
BASE::onNack(deliveryTag, multiple);
}
/**
* Method that is called to report an error
* @param message
*/
void reportError(const char *message) override
{
// monitor the object, watching for destruction since these ack/nack handlers
// could destruct the object
Monitor monitor(this);
// move the handlers out
auto handlers = std::move(_handlers);
// iterate over all the messages
// call the handlers
for (const auto &iter : handlers)
{
// call the handler
iter.second->reportError(message);
// if we were destructed in the meantime, we leap out
if (!monitor) return;
}
// if the monitor is no longer valid, leap out
if (!monitor) return;
// call the base handler
BASE::reportError(message);
}
public:
/**
* Constructor
* @param channel
* @param throttle
*/
template <typename ...Args>
Reliable(Args &&...args) : BASE(std::forward<Args>(args)...) {}
/**
* Deleted copy constructor, deleted move constructor
* @param other
*/
Reliable(const Reliable &other) = delete;
Reliable(Reliable &&other) = delete;
/**
* Deleted copy assignment, deleted move assignment
* @param other
*/
Reliable &operator=(const Reliable &other) = delete;
Reliable &operator=(Reliable &&other) = delete;
/**
* Virtual destructor
*/
virtual ~Reliable() = default;
/**
* Method to check how many messages are still unacked.
* @return size_t
*/
virtual size_t unacknowledged() const override { return _handlers.size(); }
/**
* Publish a message to an exchange. See amqpcpp/channel.h for more details on the flags.
* Delays actual publishing depending on the publisher confirms sent by RabbitMQ.
*
* @param exchange the exchange to publish to
* @param routingkey the routing key
* @param envelope the full envelope to send
* @param message the message to send
* @param size size of the message
* @param flags optional flags
* @return bool
*/
DeferredPublish &publish(const std::string &exchange, const std::string &routingKey, const std::string &message, int flags = 0) { return publish(exchange, routingKey, Envelope(message.data(), message.size()), flags); }
DeferredPublish &publish(const std::string &exchange, const std::string &routingKey, const char *message, size_t size, int flags = 0) { return publish(exchange, routingKey, Envelope(message, size), flags); }
DeferredPublish &publish(const std::string &exchange, const std::string &routingKey, const char *message, int flags = 0) { return publish(exchange, routingKey, Envelope(message, strlen(message)), flags); }
/**
* Publish a message to an exchange. See amqpcpp/channel.h for more details on the flags.
* Delays actual publishing depending on the publisher confirms sent by RabbitMQ.
*
* @param exchange the exchange to publish to
* @param routingkey the routing key
* @param envelope the full envelope to send
* @param message the message to send
* @param size size of the message
* @param flags optional flags
*/
DeferredPublish &publish(const std::string &exchange, const std::string &routingKey, const Envelope &envelope, int flags = 0)
{
// publish the entire thing, and remember if it failed at any point
uint64_t tag = BASE::publish(exchange, routingKey, envelope, flags);
// create the publish deferred object, if we got no tag we failed
auto handler = std::make_shared<DeferredPublish>(tag == 0);
// add it to the open handlers
_handlers[tag] = handler;
// return the dereferenced handler
return *handler;
}
};
/**
* End of namespaces
*/
}
| true |
f28394d16097eb2b60b396cd6b989b29f4ab163d | C++ | alpha74/iIB | /Programming/Linked_List/Remove_Duplicates_from_Sorted_List.cpp | UTF-8 | 905 | 3.390625 | 3 | [] | no_license | // Check for curr and next element val. Iterate to next only when next is not equal to curr.
// Take care when node is NULL.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
ListNode* Solution::deleteDuplicates(ListNode* A)
{
if( A == NULL )
return A ;
else if( A -> next == NULL )
return A ;
else
{
ListNode *temp = A;
ListNode *del ;
while( A != NULL )
{
if( ( A -> next != NULL ) && A -> val == ( A -> next -> val ))
{
del = A -> next ;
A -> next = del -> next ;
delete del ;
}
else
A = A -> next ;
}
return temp ;
}
}
| true |
278e84f6642c0d8d04497b775979f64290fe2392 | C++ | zszyellow/leetcode | /Cpp/1213.intersection-of-three-sorted-arrays.cpp | UTF-8 | 536 | 2.65625 | 3 | [
"MIT"
] | permissive | class Solution {
public:
vector<int> arraysIntersection(vector<int>& arr1, vector<int>& arr2, vector<int>& arr3) {
vector<int> res;
vector<int> counts(2002, 0);
for (int i = 0; i < arr1.size(); i++){
counts[arr1[i]]++;
}
for (int i = 0; i < arr2.size(); i++){
counts[arr2[i]]++;
}
for (int i = 0; i < arr3.size(); i++){
if (++ counts[arr3[i]] == 3) res.push_back(arr3[i]);
}
return res;
}
}; | true |
d9caf27c309930bf4177302343089826f4540895 | C++ | Tudor67/Competitive-Programming | /LeetCode/Problems/Algorithms/#210_CourseScheduleII_sol3_40ms_13.6MB.cpp | UTF-8 | 1,898 | 3.15625 | 3 | [
"MIT"
] | permissive | class Solution {
public:
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
// build the graph
vector<vector<int>> next_nodes(numCourses);
for(const vector<int>& v: prerequisites){
next_nodes[v[1]].push_back(v[0]);
}
// topological sort
vector<int> in_degree(numCourses, 0);
for(int node = 0; node < numCourses; ++node){
for(int next_node: next_nodes[node]){
++in_degree[next_node];
}
}
queue<int> q;
for(int node = 0; node < numCourses; ++node){
if(in_degree[node] == 0){
q.push(node);
}
}
vector<int> pos(numCourses, -1);
int idx = 0;
while(!q.empty()){
int node = q.front();
q.pop();
pos[node] = idx;
++idx;
for(int next_node: next_nodes[node]){
--in_degree[next_node];
if(in_degree[next_node] == 0){
q.push(next_node);
}
}
}
// check if the answer is valid
bool is_valid = true;
vector<int> answer(numCourses);
for(int node = 0; is_valid && node < numCourses; ++node){
if(pos[node] == -1){
is_valid = false;
}
else{
answer[pos[node]] = node;
}
for(int next_node: next_nodes[node]){
if(pos[node] > pos[next_node]){
is_valid = false;
break;
}
}
}
if(!is_valid){
answer.clear();
}
return answer;
}
}; | true |
51a1750f49dc1e96bcbf92c553de42ede4cea078 | C++ | tarn1902/AIE-Bootstrap-Projects | /OpenGL Direct Lighting/Source/GraphicsEngine/Mesh.cpp | UTF-8 | 16,791 | 3.140625 | 3 | [
"MIT"
] | permissive | /*----------------------------------------
File Name: Mesh.cpp
Purpose: Functions of mesh class
Author: Tarn Cooper
Modified: 19 April 2020
------------------------------------------
Copyright 2020 Tarn Cooper.
-----------------------------------*/
#include "Mesh.h"
#include <gl_core_4_4.h>
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include <iostream>
//-----------------------------------------------------------
// Constructs Mesh class
//-----------------------------------------------------------
Mesh::Mesh()
{
triCount = 0;
vao = 0;
vbo = 0;
ibo = 0;
}
//-----------------------------------------------------------
// Destructs Mesh class
//-----------------------------------------------------------
Mesh::~Mesh()
{
glDeleteVertexArrays(1, &vao);
glDeleteBuffers(1, &vbo);
glDeleteBuffers(1, &ibo);
}
//-----------------------------------------------------------
// Makes a triangle mesh
// position0 (glm::vec4): What is the first point position?
// position1 (glm::vec4): What is the second point position?
// position2 (glm::vec4): What is the third point position?
// vertices (Vertex[]): What is the array of vertex?
// count (int): How many Vertex are in array?
//-----------------------------------------------------------
int Mesh::MakeTri(glm::vec4 positon0, glm::vec4 positon1, glm::vec4 positon2, Vertex vertices[], int count)
{
int startCount = count;
vertices[count++] = Vertex{ positon0 };
vertices[count++] = Vertex{ positon1 };
vertices[count++] = Vertex{ positon2 };
if (startCount % 2 == 0)
{
vertices[startCount + 0].texCoord = { 0, 0 };
vertices[startCount + 1].texCoord = { 1, 0 };
vertices[startCount + 2].texCoord = { 0, 1 };
}
else
{
vertices[startCount + 0].texCoord = { 0, 1 };
vertices[startCount + 1].texCoord = { 1, 0 };
vertices[startCount + 2].texCoord = { 1, 1 };
}
glm::vec3 a = positon1 - positon0;
glm::vec3 b = positon2 - positon0;
glm::vec4 newNormal = { a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x, 0 };
vertices[startCount + 0].normal = newNormal;
vertices[startCount + 1].normal = newNormal;
vertices[startCount + 2].normal = newNormal;
return count;
}
//-----------------------------------------------------------
// Makes a quad mesh
// position0 (glm::vec4): What is the first point position?
// position1 (glm::vec4): What is the second point position?
// position2 (glm::vec4): What is the third point position?
// position3 (glm::vec4): What is the fourth point position?
// vertices (Vertex[]): What is the array of vertex?
// count (int): How many Vertex are in array?
//-----------------------------------------------------------
int Mesh::MakeQuad(glm::vec4 positon0, glm::vec4 positon1, glm::vec4 positon2, glm::vec4 positon3, Vertex vertices[], int count)
{
int startCount = count;
count = MakeTri(positon1, positon0, positon3, vertices, count);
count = MakeTri(positon3, positon0, positon2, vertices, count);
return count;
}
//-----------------------------------------------------------
// Makes a disc mesh
// position (glm::vec4): What is the position?
// vertices (Vertex[]): What is the array of vertex?
// count (int): How many Vertex are in array?
//-----------------------------------------------------------
int Mesh::MakeDisc(glm::vec3 position, float radius, Vertex vertices[], int count)
{
int segments = 10;
float segmentSize = (2 * glm::pi<float>()) / segments;
glm::vec4 position0 = glm::vec4(position, 1);
glm::vec4 position1;
glm::vec4 position2;
for (int i = 0; i < segments; ++i)
{
position1 = glm::vec4(glm::sin(i * segmentSize) * radius, position.y, glm::cos(i * segmentSize) * radius, 1);
position2 = glm::vec4(glm::sin((i + 1) * segmentSize) * radius, position.y, glm::cos((i + 1) * segmentSize) * radius, 1);
count = MakeTri(position0, position1, position2, vertices, count);
}
return count;
}
//-----------------------------------------------------------
// Makes and initializes a disc mesh
// radius (float): What is the radius of disk?
// center (glm:vec3): Where is center of disk?
//-----------------------------------------------------------
void Mesh::InitialiseDisc(float radius, glm::vec3 center)
{
const int size = 30;
int segments = 10;
float segmentSize = (2 * glm::pi<float>()) / segments;
Vertex vertices[size];
int count = 0;
glm::vec4 position0 = glm::vec4(center, 1);
glm::vec4 position1;
glm::vec4 position2;
for (int i = 0; i < segments; ++i)
{
position1 = glm::vec4(glm::sin(i * segmentSize) * radius, center.y, glm::cos(i * segmentSize) * radius, 1);
position2 = glm::vec4(glm::sin((i + 1) * segmentSize) * radius, center.y, glm::cos((i + 1) * segmentSize) * radius, 1);
count = MakeTri(position0, position1, position2, vertices, count);
}
Initialise(count, vertices);
}
//-----------------------------------------------------------
// Makes and initializes a quad mesh
// width (float): What is the width of quad?
// length (float): What is the length of quad?
// center (glm:vec3): Where is center of quad?
//-----------------------------------------------------------
void Mesh::InitialiseQuad(float width, float length, glm::vec3 center)
{
const int size = 6;
Vertex vertices[size];
int count = 0;
glm::vec4 position0 = { center.x + width / 2, center.y, center.z + length / 2, 1 };
glm::vec4 position1 = { center.x - width / 2, center.y,center.z + length / 2, 1 };
glm::vec4 position2 = { center.x + width / 2, center.y,center.z - length / 2, 1 };
glm::vec4 position3 = { center.x - width / 2, center.y,center.z - length / 2, 1 };
count = MakeTri(position1, position0, position3, vertices, count);
count = MakeTri(position3, position0, position2, vertices, count);
Initialise(size, vertices);
}
//-----------------------------------------------------------
// Makes and initializes a cube mesh
// width (float): What is the width of cube?
// length (float): What is the length of cube?
// height (float): What is the height of cube?
// center (glm:vec3): Where is center of cube?
//-----------------------------------------------------------
void Mesh::InitialiseBox(float width, float height, float length, glm::vec3 center)
{
const int size = 6 * 6;
Vertex vertices[size];
int count = 0;
glm::vec4 position0 = { center.x + width / 2, center.y + height / 2, center.z + length / 2, 1 };
glm::vec4 position1 = { center.x - width / 2, center.y + height / 2,center.z + length / 2, 1 };
glm::vec4 position2 = { center.x + width / 2, center.y + height / 2,center.z - length / 2, 1 };
glm::vec4 position3 = { center.x - width / 2, center.y + height / 2,center.z - length / 2, 1 };
glm::vec4 position4 = { center.x + width / 2, center.y - height / 2, center.z + length / 2, 1 };
glm::vec4 position5 = { center.x - width / 2, center.y - height / 2,center.z + length / 2, 1 };
glm::vec4 position6 = { center.x + width / 2, center.y - height / 2,center.z - length / 2, 1 };
glm::vec4 position7 = { center.x - width / 2, center.y - height / 2,center.z - length / 2, 1 };
//Top
count = MakeQuad(position0, position1, position2, position3, vertices, count);
//Bottom
count = MakeQuad(position5, position4, position7, position6, vertices, count);
//Left
count = MakeQuad(position0, position2, position4, position6, vertices, count);
//Forward
count = MakeQuad(position1, position0, position5, position4, vertices, count);
//Back
count = MakeQuad(position2, position3, position6, position7, vertices, count);
//Right
count = MakeQuad(position3, position1, position7, position5, vertices, count);
Initialise(size, vertices);
}
//-----------------------------------------------------------
// Makes and initializes a cylinder mesh
// radius (float): What is the radius of cylidner?
// height (float): What is the height of cylinder?
// center (glm:vec3): Where is center of cylinder?
//-----------------------------------------------------------
void Mesh::InitialiseCylinder(float height, float radius, glm::vec3 center)
{
const int size = 120;
int segments = 10;
float segmentSize = (2 * glm::pi<float>()) / segments;
Vertex vertices[size];
int count = 0;
glm::vec4 position0 = glm::vec4(center.x, center.y + height / 2, center.z, 1);
glm::vec4 position1 = glm::vec4(center.x, center.y - height / 2, center.z, 1);
glm::vec4 position2;
glm::vec4 position3;
glm::vec4 position4;
glm::vec4 position5;
for (int i = 0; i < segments; ++i)
{
//Top Disk
position2 = glm::vec4(glm::sin(i * segmentSize) * radius, position0.y, glm::cos(i * segmentSize) * radius, 1);
position3 = glm::vec4(glm::sin((i + 1) * segmentSize) * radius, position0.y, glm::cos((i + 1) * segmentSize) * radius, 1);
//Bottom Disk
position4 = glm::vec4(glm::sin(i * segmentSize) * radius, position1.y, glm::cos(i * segmentSize) * radius, 1);
position5 = glm::vec4(glm::sin((i + 1) * segmentSize) * radius, position1.y, glm::cos((i + 1) * segmentSize) * radius, 1);
//Create
count = MakeTri(position0, position2, position3, vertices, count);
count = MakeTri(position1, position5, position4, vertices, count);
count = MakeQuad(position2, position3, position4, position5, vertices, count);
}
Initialise(count, vertices);
}
//-----------------------------------------------------------
// Makes and initializes a sphere mesh
// radius (float): What is the radius of sphere?
// center (glm:vec3): Where is center of sphere?
//-----------------------------------------------------------
void Mesh::InitialiseSphere(float radius, glm::vec3 center)
{
const int size = 300;
int sectorCount = 6;
int stackCount = 6;
float sectorStep = 2 * glm::pi<float>() / sectorCount;
float stackStep = glm::pi<float>() / stackCount;
float sectorAngle, sectorAngleAlt;
float stackAngle, stackAngleAlt;
Vertex vertices[size];
int count = 0;
glm::vec4 position0;
glm::vec4 position1;
glm::vec4 position2;
glm::vec4 position3;
//Does each stack
for (int i = 0; i <= stackCount; ++i)
{
stackAngle = glm::pi<float>() / 2 - i * stackStep;
stackAngleAlt = glm::pi<float>() / 2 - (i + 1) * stackStep;
//Does each sector
for (int j = 0; j <= sectorCount; ++j)
{
sectorAngle = j * sectorStep;
sectorAngleAlt = (j + 1) * sectorStep;
position0 = glm::vec4(radius * glm::cos(stackAngle) * glm::cos(sectorAngle), radius * glm::cos(stackAngle) * glm::sin(sectorAngle), radius * glm::sin(stackAngle), 1);
position1 = glm::vec4(radius * glm::cos(stackAngle) * glm::cos(sectorAngleAlt), radius * glm::cos(stackAngle) * glm::sin(sectorAngleAlt), radius * glm::sin(stackAngle), 1);
position2 = glm::vec4(radius * glm::cos(stackAngleAlt) * glm::cos(sectorAngle), radius * glm::cos(stackAngleAlt) * glm::sin(sectorAngle), radius * glm::sin(stackAngleAlt), 1);
position3 = glm::vec4(radius * glm::cos(stackAngleAlt) * glm::cos(sectorAngleAlt), radius * glm::cos(stackAngleAlt) * glm::sin(sectorAngleAlt), radius * glm::sin(stackAngleAlt), 1);
if (i != 0)
{
count = MakeTri(position1, position0, position2, vertices, count);
}
if (i != (stackCount))
{
count = MakeTri(position1, position2, position3, vertices, count);
}
}
}
Initialise(count, vertices);
}
//-----------------------------------------------------------
// Makes and initializes a pyramid mesh
// width (float): What is the width of pyramid?
// height (float): What is the height of pyramid?
// length (float): What is the length of pyramid?
// center (glm:vec3): Where is center of pyramid?
//-----------------------------------------------------------
void Mesh::InitialisePyramid(float width, float height, float length, glm::vec3 center)
{
const int size = 6 * 6;
Vertex vertices[size];
int count = 0;
//Base
glm::vec4 position0 = { center.x + width / 2, center.y - height / 2, center.z + length / 2, 1 };
glm::vec4 position1 = { center.x - width / 2, center.y - height / 2,center.z + length / 2, 1 };
glm::vec4 position2 = { center.x + width / 2, center.y - height / 2,center.z - length / 2, 1 };
glm::vec4 position3 = { center.x - width / 2, center.y - height / 2,center.z - length / 2, 1 };
//Tip
glm::vec4 position4 = { center.x, center.y + height / 2, center.z, 1 };
//Bottom
count = MakeQuad(position1, position0, position3, position2, vertices, count);
count = MakeTri(position4, position1, position0, vertices, count);
count = MakeTri(position4, position0, position2, vertices, count);
count = MakeTri(position4, position2, position3, vertices, count);
count = MakeTri(position4, position3, position1, vertices, count);
Initialise(count, vertices);
}
//-----------------------------------------------------------
// Makes and initializes a cone mesh
// height (float): What is the height of cone?
// radius (float): What is the radius of cone?
// center (glm:vec3): Where is center of cone?
//-----------------------------------------------------------
void Mesh::InitialiseCone(float radius, float height, glm::vec3 center)
{
const int size = 120;
int segments = 10;
float segmentSize = (2 * glm::pi<float>()) / segments;
Vertex vertices[size];
int count = 0;
glm::vec4 position0;
glm::vec4 position1;
glm::vec4 position2 = { center.x, center.y + height / 2, center.z, 1 };
glm::vec4 position3 = { center.x, center.y - height / 2, center.z, 1 };
for (int i = 0; i < segments; ++i)
{
//Bottom Disk
position0 = glm::vec4(glm::sin(i * segmentSize) * radius, center.y - height / 2, glm::cos(i * segmentSize) * radius, 1);
position1 = glm::vec4(glm::sin((i + 1) * segmentSize) * radius, center.y - height / 2, glm::cos((i + 1) * segmentSize) * radius, 1);
count = MakeTri(position3, position1, position0, vertices, count);
count = MakeTri(position2, position0, position1, vertices, count);
}
Initialise(count, vertices);
}
//-----------------------------------------------------------
// Makes and initializes a grid mesh
// width (float): What is the width of grid?
// length (float): What is the length of grid?
// columns (int): How many in columns?
// width (float): How many in columns?
// center (glm:vec3): Where is center of grid?
//-----------------------------------------------------------
void Mesh::InitialiseGrid(float width, float length, int columns, int rows, glm::vec3 center)
{
const int size = 24;
Vertex vertices[size];
int count = 0;
for (int i = 0; i < columns; i++)
{
for (int j = 0; j < rows; j++)
{
glm::vec4 position0 = glm::vec4(center.x + (i * width), center.y, center.z + (j * length), 1);
glm::vec4 position1 = glm::vec4(center.x + ((i + 1) * width), center.y, center.z + ((j)* length), 1);
glm::vec4 position2 = glm::vec4(center.x + (i * width), center.y, center.z + ((j + 1) * length), 1);
glm::vec4 position3 = glm::vec4(center.x + ((i + 1) * width), center.y, center.z + ((j + 1) * length), 1);
count = MakeQuad(position0, position1, position2, position3, vertices, count);
}
}
Initialise(count, vertices);
}
//-----------------------------------------------------------
// Draws mesh to screen
//-----------------------------------------------------------
void Mesh::Draw()
{
glBindVertexArray(vao);
if (ibo != 0)
{
glDrawElements(GL_TRIANGLES, 3 * triCount, GL_UNSIGNED_INT, 0);
}
else
{
glDrawArrays(GL_TRIANGLES, 0, 3 * triCount);
}
}
//-----------------------------------------------------------
// Initialises through each point to create mesh
// vertexCount (unsigned int): How many vertices?
// vertices (const Vertex*): What is the pointer to vertices array?
// indexCount (unsigned int): How many indices?
// indices (const Vertex*): What is the pointer to indices array?
//-----------------------------------------------------------
void Mesh::Initialise(unsigned int vertexCount, const Vertex * vertices, unsigned int indexCount, unsigned int* indices)
{
assert(vao == 0);
glGenBuffers(1, &vbo);
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, vertexCount * sizeof(Vertex), vertices, GL_STATIC_DRAW);
// enable third element as texture
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE,
sizeof(Vertex), (void*)32);
// enable second element as normal
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_TRUE,
sizeof(Vertex), (void*)16);
// enable first element as position
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE,
sizeof(Vertex), 0);
if (indexCount != 0)
{
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,
indexCount * sizeof(unsigned int), indices, GL_STATIC_DRAW);
triCount = indexCount / 3;
}
else
{
triCount = vertexCount / 3;
}
glBindVertexArray(0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
} | true |
2a98a84109dc9defaf93ced87053234a100cd8f7 | C++ | MarkMan0/MotionPlanner1D | /Tests/StepperTests.cpp | UTF-8 | 1,029 | 2.59375 | 3 | [] | no_license | #include "CppUnitTest.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
#include "../MotionPlanner1D/Stepper.h"
#include "../MotionPlanner1D/Stepper.cpp"
namespace MotionPlannerTests {
TEST_CLASS(StepperTests) {
TEST_METHOD(TestStepper) {
Stepper stepper(1.0/100);
Assert::AreEqual(0.0, stepper.get_position(), L"Position not 0 at start");
Assert::AreEqual(static_cast<std::int64_t>(0), stepper.get_steps(), L"Steps not 0 at start");
stepper.set_enabled(false);
Assert::ExpectException<std::runtime_error>([&stepper] { stepper.apply_step(); }, L"Apply step with enabled_ false did not throw");
stepper.set_enabled();
for (int i = 0; i < 100; ++i) {
stepper.apply_step();
}
Assert::AreEqual(1.0, stepper.get_position(), L"Position not correct");
Assert::AreEqual(static_cast<std::int64_t>(100), stepper.get_steps(), L"Steps not correct");
}
};
}
| true |
4009f9696f21b74456fba506c0d69d629b66c30f | C++ | SayHey/MiniFlow | /MiniFlow/TensorScalar.h | UTF-8 | 2,795 | 3.375 | 3 | [] | no_license | #pragma once
#include "Common.h"
namespace miniflow
{
class TensorScalar
{
/*
PLACEHOLDER CLASS for the purpose of debugginc of the computational graph.
Is basically a Scalar that supports all the functions of generic Tensor.
*/
public:
Scalar value_;
TensorScalar() :
value_(0)
{}
TensorScalar(Scalar value) :
value_(value)
{}
Scalar operator[](int) const
{
return value_;
}
Scalar& operator[](int)
{
return value_;
}
// Element-wise tensor operations
friend TensorScalar operator+(TensorScalar const& t1, TensorScalar const& t2)
{
return t1.value_ + t2.value_;
}
friend TensorScalar operator-(TensorScalar const& t1, TensorScalar const& t2)
{
return t1.value_ - t2.value_;
}
friend TensorScalar operator*(TensorScalar const& t1, TensorScalar const& t2)
{
return t1.value_ * t2.value_;
}
friend TensorScalar operator/(TensorScalar const& t1, TensorScalar const& t2)
{
return t1.value_ / t2.value_;
}
void operator+=(const TensorScalar& t)
{
*this = *this + t;
}
void operator-=(const TensorScalar& t)
{
*this = *this - t;
}
void operator*=(const TensorScalar& t)
{
*this = *this * t;
}
void operator/=(const TensorScalar& t)
{
*this = *this / t;
}
// Element-wise operations with scalars
friend TensorScalar operator+(TensorScalar const& t, Scalar s)
{
return t.value_ + s;
}
friend TensorScalar operator+(Scalar s, TensorScalar const& t)
{
return t + s;
}
friend TensorScalar operator-(TensorScalar const& t, Scalar s)
{
return t.value_ - s;
}
friend TensorScalar operator-(Scalar s, TensorScalar const& t)
{
return s - t.value_;
}
friend TensorScalar operator*(TensorScalar const& t, Scalar s)
{
return s * t.value_;
}
friend TensorScalar operator*(Scalar s, TensorScalar const& t)
{
return t * s;
}
friend TensorScalar operator/(Scalar s, TensorScalar const& t)
{
return s / t.value_;
}
friend TensorScalar operator/(TensorScalar const& t, Scalar s)
{
return t * 1 / s;
}
friend TensorScalar operator-(TensorScalar const& t)
{
return t * -1;
}
// Special functions
friend TensorScalar sum(TensorScalar const& t)
{
return TensorScalar(t.value_);
}
friend TensorScalar mean(TensorScalar const& t)
{
return TensorScalar(t.value_);
}
friend TensorScalar exp(const TensorScalar& t)
{
return pow(EXP, t.value_);
}
friend TensorScalar sqr(const TensorScalar& t)
{
return t * t;
}
friend TensorScalar dot(const TensorScalar& t1, const TensorScalar& t2)
{
return TensorScalar(t1.value_ * t2.value_);
}
friend TensorScalar transpose(TensorScalar const& input)
{
return TensorScalar(input.value_);
}
};
} | true |
ba7b3ead16e513849d677fa5a7f1a4ae06e3679f | C++ | mubashir-dev/DataStructures | /Random Text String Generator.cpp | ISO-8859-3 | 1,104 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <windows.h>
#include <ctime>
using namespace std;
char genRandom(){
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int stringLength = sizeof(alphanum) - 1;
return alphanum[rand() % stringLength];
}
int main(){
SetConsoleTitle("Random text string Generator. mausy131 2013");
srand(time(0));
std::string Str;
int length = 0;
cout << "Enter the length of the string:" << endl;
cin >> length;
for(int i = 0; i < length; ++i){
//cout << genRandom << endl; // You can delete the // and put // for Str += genRandom
Str =Str + genRandom(); // All characters in genRandom will be copied to Str.
// I did this because I needed it for a project.
}
cout << "This is your random serial:" << endl;
cout << Str << endl; // Str holds the same as genRandom since all the characters have been copied. You can comment this out with the // if you use cout << genRandom();
cout << endl;
system("PAUSE");
return 0;
}
| true |
db1b285ca7f31e6bb36fa4bd07001b54e1cab2d8 | C++ | linwenb/leetcode | /pascals-triangle.cpp | UTF-8 | 890 | 3.765625 | 4 | [] | no_license | /*
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
*/
class Solution {
public:
vector<vector<int> > generate(int numRows) {
vector<vector<int>> ans;
if (numRows == 0) return ans;
vector<int> row;
row.push_back(1); // first row
ans.push_back(row);
for (int i = 0; i < numRows - 1; i++) {
row.clear();
row.push_back(1); // the first element is always 1
for (int j = 0; j < i; j++) row.push_back(ans[i][j] + ans[i][j + 1]);
row.push_back(1); // the last element is always 1
ans.push_back(row);
}
return ans;
} // O(n^2) time, O(n) space
}; | true |
06d97068c04ec9c250703b21e1978c6b48dd87a6 | C++ | MathProgrammer/CodeChef | /Contests/Long Challenge/2012 09 September SEP12/Programs/Queries About Numbers.cpp | UTF-8 | 3,180 | 3.0625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
const int MAX_N = 1e6;
vector <int> primes;
void sieve()
{
vector <int> is_prime(MAX_N, true);
is_prime[0] = is_prime[1] = false;
for(int i = 2; i < MAX_N; i++)
{
if(is_prime[i])
{
primes.push_back(i);
}
for(int j = 0; j < primes.size() && i*1LL*primes[j] < MAX_N; j++)
{
is_prime[i*primes[j]] = false;
if(i%primes[j] == 0)
{
break;
}
}
}
}
void factorise(long long n, map <long long, int> &exponent)
{
for(int i = 0; i < primes.size() && primes[i]*1LL*primes[i] <= n; i++)
{
while(n%primes[i] == 0)
{
exponent[primes[i]]++;
n /= primes[i];
}
}
if(n > 1)
{
exponent[n] = 1;
}
}
long long no_of_factors(map <long long, int> &exponent)
{
long long answer = 1;
for(auto it = exponent.begin(); it != exponent.end(); it++)
{
answer *= (it->second + 1);
}
return answer;
}
long long get_divisor_n_multiple_k(long long n, long long k, map <long long, int> &factors_n, map <long long, int> &common_factors)
{
if(n < k || n%k != 0)
{
return 0;
}
long long answer = 1;
for(auto it = factors_n.begin(); it != factors_n.end(); it++)
{
long long factor = it->first;
int extra_exponent = (factors_n[factor] - common_factors[factor]);
answer *= (1 + extra_exponent);
}
return answer;
}
int get_exponent(long long n, long long p)
{
int exponent = 0;
while(n%p == 0)
{
exponent++;
n /= p;
}
return exponent;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
sieve();
long long n;
int no_of_queries;
cin >> n >> no_of_queries;
map <long long, int> factors_n;
factorise(n, factors_n);
for(int i = 1; i <= no_of_queries; i++)
{
const int COMMON_DIVISOR = 1, DIVISOR_N_MULTIPLE_K = 2, DIVISOR_N_NON_MULTIPLE_K = 3;
int query;
long long k;
cin >> query >> k;
map <long long, int> common_factors;
for(auto it = factors_n.begin(); it != factors_n.end(); it++)
{
common_factors[it->first] = min(it->second, get_exponent(k, it->first));
}
long long answer = 0;
switch(query)
{
case COMMON_DIVISOR:
{
answer = no_of_factors(common_factors);
break;
}
case DIVISOR_N_MULTIPLE_K:
{
answer = get_divisor_n_multiple_k(n, k, factors_n, common_factors);
break;
}
case DIVISOR_N_NON_MULTIPLE_K:
{
long long divisors_n = no_of_factors(factors_n);
long long divisors_n_multiple_k = get_divisor_n_multiple_k(n, k, factors_n, common_factors);
answer = divisors_n - divisors_n_multiple_k;
break;
}
}
cout << answer << "\n";
}
return 0;
}
| true |
00a24bcae06d35bb34fee13f0ed3dead6af75f27 | C++ | shipduck/cham-cham-cham | /cli/src/cbes/sample_component.cpp | UTF-8 | 3,870 | 2.6875 | 3 | [] | no_license | // Ŭnicode please
#include "stdafx.h"
#include "sample_component.h"
CompHealthProxy::CompHealthProxy()
: Active(false)
{
std::fill(InitialHP.begin(), InitialHP.end(), nullptr);
std::fill(CurrentHP.begin(), CurrentHP.end(), nullptr);
}
CompHealthList::CompHealthList(int poolSize)
: Parent(poolSize)
{
InitialHPList_Head.resize(poolSize);
InitialHPList_Torso.resize(poolSize);
CurrentHPList_Head.resize(poolSize);
CurrentHPList_Torso.resize(poolSize);
}
int CompHealthList::create(const healt_value_t hp)
{
int compId = Parent::create();
CompHealthProxy comp = getComp(compId);
for(int i = 0 ; i < cNumBodyParts ; ++i) {
*comp.InitialHP[i] = hp;
*comp.CurrentHP[i] = hp;
}
return compId;
}
void CompHealthList::initMsgHandler()
{
registerMsgFunc(this, &CompHealthList::onDestroyMessage);
}
void CompHealthList::onDestroyMessage(int compId, SDestroyMessage *msg)
{
//component message 사용 예제 코드
CompHealthProxy comp = getComp(compId);
if(comp.Active == false) {
return;
}
for(int i = 0 ; i < cNumBodyParts ; ++i) {
*comp.CurrentHP[i] = 0;
}
}
void CompHealthList::startUp()
{
initMsgHandler();
}
void CompHealthList::shutDown()
{
}
void CompHealthList::update(int ms)
{
}
CompHealthProxy CompHealthList::getComp(int compId) const
{
CompHealthProxy comp;
if(ActiveList[compId] == true) {
comp.Active = true;
comp.InitialHP[head] = const_cast<int*>(&InitialHPList_Head[compId]);
comp.InitialHP[torso] = const_cast<int*>(&InitialHPList_Torso[compId]);
comp.CurrentHP[head] = const_cast<int*>(&CurrentHPList_Head[compId]);
comp.CurrentHP[torso] = const_cast<int*>(&CurrentHPList_Torso[compId]);
} else {
comp.Active = false;
}
return comp;
}
CompHealthList::healt_value_t CompHealthList::getInitialHealthAt(int compId, const bodyPart_e part) const
{
CompHealthProxy comp = getComp(compId);
return *comp.InitialHP[part];
}
void CompHealthList::setInitialHealthAt(int compId, const bodyPart_e part, const healt_value_t hp)
{
CompHealthProxy comp = getComp(compId);
*comp.InitialHP[part] = hp;
}
CompHealthList::healt_value_t CompHealthList::getHealthAt(int compId, const bodyPart_e part) const
{
CompHealthProxy comp = getComp(compId);
return *comp.CurrentHP[part];
}
void CompHealthList::setHealthAt(int compId, const bodyPart_e part, const healt_value_t hp)
{
CompHealthProxy comp = getComp(compId);
*comp.CurrentHP[part] = hp;
}
bool CompHealthList::isWounded(int compId) const
{
CompHealthProxy comp = getComp(compId);
for(int i = 0 ; i < cNumBodyParts ; ++i) {
if(*comp.InitialHP[i] != *comp.CurrentHP[i]) {
return true;
}
}
return false;
}
void CompHealthList::reset(int compId)
{
CompHealthProxy comp = getComp(compId);
for(int i = 0 ; i < cNumBodyParts ; ++i) {
comp.CurrentHP[i] = comp.InitialHP[i];
}
}
void CompHealth::init(int hp)
{
std::fill(InitialHP.begin(), InitialHP.end(), hp);
std::fill(CurrentHP.begin(), CurrentHP.end(), hp);
}
CompHealth::healt_value_t CompHealth::getInitialHealthAt(const bodyPart_e part) const
{
return InitialHP[part];
}
void CompHealth::setInitialHealthAt(const bodyPart_e part, const healt_value_t hp)
{
InitialHP[part] = hp;
}
CompHealth::healt_value_t CompHealth::getHealthAt(const bodyPart_e part) const
{
return CurrentHP[part];
}
void CompHealth::setHealthAt(const bodyPart_e part, const healt_value_t hp)
{
CurrentHP[part] = hp;
}
bool CompHealth::isWounded() const
{
for(int i = 0 ; i < cNumBodyParts ; ++i) {
if(CurrentHP[i] != InitialHP[i]) {
return true;
}
}
return false;
}
void CompHealth::reset()
{
for(int i = 0 ; i < cNumBodyParts ; ++i) {
CurrentHP[i] = InitialHP[i];
}
}
void CompVisualSphere::init(float radius)
{
this->radius = radius;
}
void CompVisualSphere::render() const
{
printf("render sphere with radius %f\n", radius);
}
void CompVisualSphere::update(int ms)
{
render();
}
| true |
d68516ee0feda1bfebced678c9175769f1dee973 | C++ | raychen1155/program-problem-3-alan-lee-and-rahul-singh | /program problem 3/program problem 3/Alan_lee program problem 3.cpp | UTF-8 | 1,151 | 3.375 | 3 | [] | no_license | /*
/*
Rahul Singh and Alan Lee - 1st period
Program Problem 3
Using a 3 digit number to put create separate varibles
*/
// Libraries
#include <iostream> // gives access to cin, cout, endl, <<, >>, boolalpha, noboolalpha
#include <conio.h> // gives access to _khbit, (), and _getch () for pause ()
// namespace
using namespace std;
//functions ()
void pause() {
cout << "Press any key to continue . . .";
while (!_kbhit());
_getch();
cout << '\n';
}
// main
int main() {
int y = 1;
while (y < 31)
{
int x;
cout << "Enter 3-digit number" << endl;
cin >> x;
int c = x % 10;
int b = (x / 10) % 10;
int a = (x / 100);
bool ascending = a != b && b != c;
bool descending = ascending;
if (a > b)
ascending = false;
else
descending = false;
if (b > c)
ascending = false;
else
descending = false;
if (ascending)
cout << "The number " << x << " is ascending. \n" << endl;
else if (descending)
cout << "The number " << x << " is descending. \n" << endl;
else
cout << "The number " << x << " is neither ascending or descending. \n" << endl;
y++;
_getch();
}
return 0;
}
| true |
6b9182456c7ee1e3869a472410c972df61926d71 | C++ | Snaked96/computerNetworksProject-2-2016 | /libs/CRC16.hpp | UTF-8 | 1,661 | 3 | 3 | [] | no_license | #ifndef _CRC16_HPP_
#define _CRC16_HPP_
//Librer�as
#include "Protocol.hpp"
#define POLY bitset<5>(string("11000000000000101"))
//10011
template <const size_t MAX_CHAR_PER_MSG, const size_t TAM_TRAMA>
class CRC16 : public Protocol< MAX_CHAR_PER_MSG, TAM_TRAMA >
{
public:
void encode( string &data );
int decode( string &data );
string remainder( const string &data );
};
template <const size_t MAX_CHAR_PER_MSG, const size_t TAM_TRAMA>
void CRC16<MAX_CHAR_PER_MSG, TAM_TRAMA>::encode( string &data )
{
data += remainder( data );
}
template <const size_t MAX_CHAR_PER_MSG, const size_t TAM_TRAMA>
string CRC16<MAX_CHAR_PER_MSG, TAM_TRAMA>::remainder( const string &data1 )
{
string data = data1;
for( size_t i = 1; i < POLY.size() ; i++ )
data += "0";
for ( size_t i = 0; i < data.size()-POLY.size()+1 ; i++ )
if( data[i] == '1' )
data = data.substr( 0, i ) + ( bitset<5>( data.substr( i, POLY.size() ) ) ^ POLY ).to_string() + data.substr( i + POLY.size() );
return( data.substr( data.size()- POLY.size() + 1 ) );
}
template <const size_t MAX_CHAR_PER_MSG, const size_t TAM_TRAMA>
int CRC16<MAX_CHAR_PER_MSG, TAM_TRAMA>::decode( string &data )
{
string theweeknd = remainder(data);
for( size_t i = 0 ; i < theweeknd.size() ; i++)
if( theweeknd[i] == '1' )
return( 0 );
data.erase( data.size() - POLY.size() + 1 );
return( 1 );
}
#endif // _CRC16_HPP_
| true |
113e419f2862ad204304d6b1345f944477aed1cc | C++ | lsiddiqsunny/programming-contest | /Codeforces/Hello 2019/2.cpp | UTF-8 | 1,042 | 2.71875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int Set(int N,int pos)
{
return N=N | (1<<pos);
}
int reset(int N,int pos)
{
return N= N & ~(1<<pos);
}
bool check(int N,int pos)
{
return (bool)(N & (1<<pos));
}
int main()
{
int n;
cin>>n;
int a[n];
int sum=0;
for(int i=0; i<n; i++)
{
cin>>a[i];
sum+=a[i];
}
if(sum==360)
{
cout<<"YES"<<endl;
return 0;
}
int po=1;
for(int i=1; i<=n; i++)
{
po*=2;
}
for(int i=0; i<po; i++)
{
int nowsum=0,nowsum1=0;;
for(int j=0; j<n; j++)
{
if(check(i,j))
{
nowsum+=a[j];
}
else
{
nowsum1+=a[j];
}
}
nowsum%=360;
nowsum1%=360;
if(nowsum==nowsum1)
{
cout<<"YES"<<endl;
return 0;
}
}
cout<<"NO"<<endl;
return 0;
}
| true |
32faacd55e359296a6348ecb733f633f9120ca7c | C++ | NizaVolair/C-Plus-Plus_Fantasy_Tournament | /Blue.cpp | UTF-8 | 2,537 | 3.296875 | 3 | [] | no_license | /****************************************************************************************
**Program Filename: Blue.cpp
**Author: Niza Volair
**Date: 05-06-15
**Description: Blue class inplimentation files
**Input: none
**Output: integer representing damage
***************************************************************************************/
#include "Hero.hpp"
#include "Blue.hpp"
#include <string>
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
using std::string;
/****************************************************************************************
**Function: attack
**Description: This is a method which allows an attacker to deduct points from defender's
**strength depending on randomized dice rolls
**Parameters: Pointer to a hero (defender)
**Pre-Conditions: two heros created, dice rolling functions created
**Post-Conditions: defender's strength is accurately changed and points are returned
*****************************************************************************************/
int Blue::attack(Hero *defender)
{ //Create variables for the atack and defense scores, damage and adjusted strength
int attack, defense, newStrength;
int damage = 0;
//Use roll methods for defense and attack check for a cut achilles tendon
if((this->achilles()) == false)
{ attack = (this->rollAttackDice());
}
else if ((this->achilles()) == true)
{ attack = ((this->rollAttackDice())/2);
}
defense = (defender->rollDefendDice());
//Check for -1 flag for Shadow evasion
if(defense == (-1))
{ damage = 0;
}
else
{ //Use attack defense scores to find damage
damage = ((attack - defense) - (defender->getArmor()));
}
//The attack was not successful if less than or equal to 0
if(damage <= 0)
{ damage = 0;
}
//If there was damage get new strength
else
{ newStrength = ((defender->getStrength()) - damage);
defender->setStrength(newStrength);
//Add damage to attackers points
this->setPoints(points + damage);
//If damage greater than strength declare death the defender has died
//mend attacker achillies
if(defender->getStrength() <= 0)
{ //Add killer bonus to attackers points and adjust damage to include kill bonus
this->setPoints(points + killBonus);
damage += killBonus;
//Call heal function to heal attacker if needed
this->heal();
if(this->achilles() == true)
{ this->cutAchilles(false);
}
}
}
//Return the damage
return damage;
}
| true |
493887a547fe0858e9f1c96c3818b2a1ad5e2245 | C++ | d8euAI8sMs/util-cpp-common | /include/util/common/geom/point.h | UTF-8 | 8,292 | 2.875 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <afxwin.h>
#include <util/common/ptr.h>
#include <util/common/math/scalar.h>
#include <util/common/geom/geom_fwd.h>
#include <type_traits>
#include <iostream>
namespace geom
{
/*****************************************************/
/* some common operations */
/*****************************************************/
/* use forward implementation of functions instead of
just forward declaration to make code shorter */
template
<
typename _X1, typename _Y1,
typename _X2, typename _Y2
>
inline double distance
(
point < _X1, _Y1 > const & p1,
point < _X2, _Y2 > const & p2
)
{
return math::norm(p1 - p2);
}
template
<
typename _X1, typename _Y1,
typename _X2, typename _Y2
>
inline double sqdistance
(
point < _X1, _Y1 > const & p1,
point < _X2, _Y2 > const & p2
)
{
return math::sqnorm(p1 - p2);
}
/*****************************************************/
/* point */
/*****************************************************/
template
<
typename X,
typename Y = X
>
struct point
{
using ptr_t = util::ptr_t < point > ;
template < class ... T > static ptr_t create(T && ... t) { return util::create < typename ptr_t::element_type > (std::forward < T > (t) ...); }
using x_type = X;
using y_type = Y;
x_type x;
y_type y;
point(x_type x, y_type y)
: x(x), y(y)
{
}
template < typename _X, typename _Y >
point(_X x, _Y y)
: point(static_cast < X > (x),
static_cast < Y > (y))
{
}
point()
: point(x_type{}, y_type{})
{
}
template < typename _X, typename _Y >
point(point < _X, _Y > const & o)
: point(static_cast < X > (o.x),
static_cast < Y > (o.y))
{
}
template < typename = std::enable_if_t <
is_planar < point > :: value > >
operator POINT () const
{
return{ (LONG)x, (LONG)y };
}
/* to be precise, emptiness checking is incorrect;
we leave this type of checking untouched
because some legacy code (plot::xxx) depends
on it */
bool empty() const
{
return ((x == x_type{}) && (y == y_type{}));
}
template < typename _X, typename _Y >
bool operator == (point < _X, _Y > const & o) const
{
return (x == o.x) && (y == o.y);
}
template < typename _X, typename _Y >
bool operator != (point < _X, _Y > const & o) const
{
return (x != o.x) || (y != o.y);
}
template < typename _X, typename _Y >
auto operator - (point < _X, _Y > const & o) const
-> point < std::remove_const_t < decltype(x - o.x) >,
std::remove_const_t < decltype(y - o.y) > >
{
return { x - o.x, y - o.y };
}
template < typename _X, typename _Y >
auto operator + (point < _X, _Y > const & o) const
-> point < std::remove_const_t < decltype(x - o.x) >,
std::remove_const_t < decltype(y - o.y) > >
{
return { x + o.x, y + o.y };
}
template < typename _X, typename _Y >
point & operator -= (point < _X, _Y > const & o)
{
x -= o.x;
y -= o.y;
return *this;
}
template < typename _X, typename _Y >
point & operator += (point < _X, _Y > const & o)
{
x += o.x;
y += o.y;
return *this;
}
template < typename = std::enable_if_t <
! std::is_unsigned < X > :: value &&
! std::is_unsigned < Y > :: value && > >
auto operator - () const
-> point < std::remove_const_t < decltype(- x) >,
std::remove_const_t < decltype(- y) > >
{
return { - x, - y };
}
template < typename _Z >
auto operator * (_Z n)
-> point < std::remove_const_t < decltype(x * n) >,
std::remove_const_t < decltype(y * n) > >
{
return { x * n, y * n };
}
template < typename _Z >
auto operator / (_Z n)
-> point < std::remove_const_t < decltype(x / n) >,
std::remove_const_t < decltype(y / n) > >
{
return { x / n, y / n };
}
double length() const
{
return math::norm(*this);
}
template < typename = std::enable_if_t <
is_planar < point > :: value > >
double angle() const
{
return atan2(static_cast < double > (y),
static_cast < double > (x));
}
template < typename _X, typename _Y >
double distance(point < _X, _Y > const & o) const
{
return geom::distance(*this, o);
}
template < typename _X, typename _Y >
double distance(_X x, _Y y) const
{
return geom::distance(*this, make_point(x, y));
}
auto rotate (double radians) const
-> point < std::remove_const_t < decltype(x * 1. - y * 1.) >,
std::remove_const_t < decltype(x * 1. + y * 1.) > >
{
double sine = std::sin(radians);
double cosine = std::cos(radians);
auto & p = *this;
return
{
p.x * cosine - p.y * sine,
p.x * sine + p.y * cosine
};
}
template < typename _X, typename _Y >
auto rotate
(
double radians,
const point < _X, _Y > & at
) const
-> std::remove_const_t < decltype((std::declval<point>() - at).rotate(radians) + at) >
{
return (*this - at).rotate(radians) + at;
}
};
/*****************************************************/
/* factory functions */
/*****************************************************/
template < typename _X, typename _Y >
inline auto make_point(_X x, _Y y)
-> point < std::remove_const_t < _X >,
std::remove_const_t < _Y > >
{
return { x, y };
}
/*****************************************************/
/* type traits */
/*****************************************************/
template < typename _X, typename _Y >
struct is_planar < point < _X, _Y > >
: std::integral_constant < bool,
std::is_convertible < _X, double > :: value &&
std::is_convertible < _Y, double > :: value >
{
};
/*****************************************************/
/* formatting */
/*****************************************************/
template < typename _Elem, typename _Traits,
typename _X, typename _Y >
std::basic_ostream < _Elem, _Traits > & operator <<
(
std::basic_ostream < _Elem, _Traits > & os,
const point < _X, _Y > & p
)
{
return os << "(" << p.x << ", " << p.y << ")";
}
}
namespace math
{
/*****************************************************/
/* scalar point operations */
/*****************************************************/
template < typename _X, typename _Y >
inline double norm(geom::point < _X, _Y > const & p)
{
return std::sqrt(sqnorm(p));
}
template < typename _X, typename _Y >
inline double sqnorm(geom::point < _X, _Y > const & p)
{
return sqnorm(p.x) + sqnorm(p.y);
}
template < typename _X, typename _Y >
inline geom::point < _X, _Y > conjugate(geom::point < _X, _Y > const & p)
{
return { conjugate(p.x), conjugate(p.y) };
}
}
| true |
79e27ade55d101be6c45fdedaa1414b67968a62c | C++ | Dragonfire3900/forward-fitting | /headers/Asimov.h | UTF-8 | 112,603 | 2.515625 | 3 | [] | no_license | //
// Asimov.h
// Erin Conley (erin.conley@duke.edu)
//
#ifndef Asimov_h
#define Asimov_h
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// InterpolateChi2Hist: Outputs an TH2D objects with number of row/column bins
// equal to numBins. Interpolates the bin content using
// histToInterpolate, and stores the bin content if it
// passes a cut defined by chi2cut
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
TH2D* InterpolateChi2Hist(TH2D* histToInterpolate, Int_t numBins, Double_t chi2cut){
TString name_interpolated = (TString)( histToInterpolate->GetName() ) + "_inter";
TString title_interpolated = (TString)( histToInterpolate->GetTitle() ) + " (interpolated)";
Double_t xmin = histToInterpolate->GetXaxis()->GetXmin();
Double_t xmax = histToInterpolate->GetXaxis()->GetXmax();
Double_t ymin = histToInterpolate->GetYaxis()->GetXmin();
Double_t ymax = histToInterpolate->GetYaxis()->GetXmax();
//hardcode the number of bins because I doubt they will ever need to change
Int_t binCol = numBins;
Int_t binRow = numBins;
TH2D *h_interpolated = new TH2D(name_interpolated, title_interpolated, binCol, xmin, xmax, binRow, ymin, ymax);
//loop over the bins
for(int col = 1; col <= binCol; ++col){
for(int row = 1; row <= binRow; ++row){
//get the actual x, y for this col, row bin position
double x = h_interpolated->GetXaxis()->GetBinCenter(col);
double y = h_interpolated->GetYaxis()->GetBinCenter(row);
//find the interpolated chi2 value
double interbin = histToInterpolate->Interpolate(x, y);
//if the interpolated chi2 value passes the cut, fill the hist
if(interbin < chi2cut) h_interpolated->SetBinContent(col, row, interbin);
}//end loop over rows
}//end loop over columns
return h_interpolated;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// findAreaOfContour: Calculates the area contained by the countor defined by
// the given TH2D object
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Double_t findAreaOfContour(TH2D *hist){
Double_t area = -99.0;
TCanvas *c = new TCanvas("c","c",1000,700);
//specific contour set here for sensitivity study
double contours[1];
contours[0] = 0.001;
hist->SetContour(1, contours);
hist->Draw("CONT LIST");
c->Update();
TObjArray *conts = (TObjArray*)gROOT->GetListOfSpecials()->FindObject("contours");
TList* contLevel = NULL;
Int_t nGraphs = 0;
Int_t TotalConts = 0;
if(conts == NULL){
std::cout << "*** No Contours Were Extracted!" << std::endl;
TotalConts = 0;
}
else TotalConts = conts->GetSize();
//std::cout << "TotalConts = " << TotalConts << std::endl;
for(int iCont = 0; iCont < TotalConts; ++iCont){
contLevel = (TList*)conts->At(iCont);
if(contLevel->GetSize() > 0){
area = 0;
TIter next(contLevel);
TObject* obj =0;
while(( obj = next() )){
area += ((TGraph*)obj)->Integral();
}
}
}
delete c;
return area;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// AsimovMethod: Produces chi2-minimized flux parameter measurements and plots
// for a supernova located distanceSN from Earth. The supernova is
// defined by a test spectrum with SNOwGLoBES smearing ts,
// nue-Ar40 cross section ts_xscn, and post-smearing efficiency
// model ts_effic. The detector assumptions are defined by a grid
// described by its parameter bounds (grid), SNOwGLoBES smearing
// (grid_smear), nue-Ar40 cross section model (grid_xscn), and
// efficiency model (grid_xscn).
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void AsimovMethod(Double_t distanceSN, TString grid, TString grid_smear, TString grid_xscn, TString grid_effic, TString ts, TString ts_xscn, TString ts_effic){
std::cout << "Producing sensitivity plots for a " << distanceSN << "kpc supernova and the following input parameters:" << std::endl;
std::cout << " Grid: " << grid << " with smearing " << grid_smear << ", xscn " << grid_xscn << ", and effic " << grid_effic << std::endl;
std::cout << " Test spectrum: " << ts << " with xscn " << ts_xscn << " and effic " << ts_effic << std::endl;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// DEFINE INPUTS
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
TString test_spect_filename = "input/test_spectra/pinched_test_smeared_sum_" + ts + "_" + ts_xscn + "_" + ts_effic + ".dat";
TString smeareddir = "input/" + grid + "/smear_" + grid_smear + "_" + grid_xscn + "_" + grid_effic;
TString pinchedinfo = "input/pinched_info/pinched_info_" + grid + ".dat";
TString gridinfo = "input/grid_info/grid_info_" + grid + ".dat";
//define output file
TString distanceStr; distanceStr.Form("%.2lf", distanceSN);
TString outfile = "out/chi2plots_" + grid + "_smear" + grid_smear + "_" + grid_xscn + "_" + grid_effic + "_spectra" + ts + "_" + ts_xscn + "_" + ts_effic + "_" + distanceStr + "kpc.root";
Double_t alpha_true = 2.5;
Double_t e0_true = 9.5; //mev
Double_t lum_true = 5e52; //ergs
Double_t massfact = 1.0;//2.4; //see the full DUNE far detector response
Double_t chi2_90contour = 4.61; //pdg 2018
//use same style settings that Kate used
gStyle->SetOptStat(0);
gStyle->SetPalette(1,0);
//set random seed
gRandom->SetSeed(0);
//define tree for output file
Double_t tr_alpha;
Double_t tr_e0;
Double_t tr_lum;
Double_t tr_chi2;
Double_t tr_dof;
Double_t tr_numGridElementsAlphavsE0;
Double_t tr_numGridElementsLumvsE0;
Double_t tr_numGridElementsLumvsAlpha;
Double_t tr_numGoodGridElementsAlphavsE0;
Double_t tr_numGoodGridElementsLumvsE0;
Double_t tr_numGoodGridElementsLumvsAlpha;
TTree *tr = new TTree("data", "data");
tr->Branch("alpha", &tr_alpha, "alpha/D");
tr->Branch("e0", &tr_e0, "e0/D");
tr->Branch("lum", &tr_lum, "lum/D");
tr->Branch("chi2", &tr_chi2, "chi2/D");
tr->Branch("dof", &tr_dof, "dof/D");
tr->Branch("numgrid_alphavse0", &tr_numGridElementsAlphavsE0, "numgrid_alphavse0/D");
tr->Branch("numgrid_lumvse0", &tr_numGridElementsLumvsE0, "numgrid_lumvse0/D");
tr->Branch("numgrid_lumvsalpha", &tr_numGridElementsLumvsAlpha, "numgrid_lumvsalpha/D");
tr->Branch("numgood_alphavse0", &tr_numGoodGridElementsAlphavsE0, "numgood_alphavse0/D");
tr->Branch("numgood_lumvse0", &tr_numGoodGridElementsLumvsE0, "numgood_lumvse0/D");
tr->Branch("numgood_lumvsalpha", &tr_numGoodGridElementsLumvsAlpha, "numgood_lumvsalpha/D");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// DEFINE GRID BOUNDS
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//define the bounds of the grid
Double_t first_alpha;
Double_t last_alpha;
Double_t step_alpha;
Double_t first_e0;
Double_t last_e0;
Double_t step_e0;
Double_t factor = 1e53;
Double_t first_lum;
Double_t last_lum;
Double_t step_lum;
//open grid_info.dat
ifstream gin;
gin.open(gridinfo);
Int_t ig = 0;
while(1){
gin >> first_alpha >> last_alpha >> step_alpha >> first_e0 >> last_e0 >> step_e0 >> first_lum >> last_lum >> step_lum;
if(!gin.good()) break;
++ig;
}
gin.close();
Double_t minalpha = first_alpha - step_alpha/2.0;
Double_t maxalpha = last_alpha + step_alpha/2.0;
Double_t mine0 = first_e0 - step_e0/2.0;
Double_t maxe0 = last_e0 + step_e0/2.0;
Double_t minlum = first_lum - step_lum/2.0;
Double_t maxlum = last_lum + step_lum/2.0;
Double_t minalpha2 = first_alpha - step_alpha*2.0;
Double_t maxalpha2 = last_alpha + step_alpha*2.0;
Double_t mine02 = first_e0 - step_e0*2.0;
Double_t maxe02 = last_e0 + step_e0*2.0;
Double_t minlum2 = first_lum - step_lum*2.0;
Double_t maxlum2 = last_lum + step_lum*2.0;
Int_t numalphabins = int((last_alpha - first_alpha)/step_alpha)+1;
Int_t nume0bins = int((last_e0 - first_e0)/step_e0)+1;
Int_t numlumbins = (last_lum - first_lum)/(step_lum) + 1;
//Range of physical parameters
Double_t mingoodalpha = first_alpha;//1.0;
Double_t maxgoodalpha = last_alpha;//7.0;
Double_t mingoode0 = first_e0;//0.0;
Double_t maxgoode0 = last_e0;//20.;
std::cout << "The " << grid << " grid follows this definition:" << std::endl;
std::cout << " Alpha: [" << first_alpha << ", " << last_alpha << "] with " << step_alpha << " spacing" << std::endl;
std::cout << " E0: [" << first_e0 << ", " << last_e0 << "] with " << step_e0 << " spacing" << std::endl;
std::cout << " Luminosity: [" << first_lum << ", " << last_lum << "] with " << step_lum << " spacing" << std::endl;
std::cout << "The parameter-fitting algorithm will consider the following physical range for alpha and E0:" << std::endl;
std::cout << " Alpha: [" << mingoodalpha << ", " << maxgoodalpha << "]" << std::endl;
std::cout << " E0: [" << mingoode0 << ", " << maxgoode0 << "]" << std::endl;
//std::cout << numalphabins << " " << nume0bins << " " << numlumbins << std::endl;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// READ PINCHING PARAMETERS
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//open the pinched parameter file
ifstream pin;
pin.open(pinchedinfo);
//define arrays, iterators to keep the parameters
const Int_t maxflux = 350000;
std::vector<Int_t> pnum; pnum.resize(maxflux);
std::vector<Double_t> anue; anue.resize(maxflux);
std::vector<Double_t> bnue; bnue.resize(maxflux);
std::vector<Double_t> cnue; cnue.resize(maxflux);
std::vector<Double_t> anuebar; anuebar.resize(maxflux);
std::vector<Double_t> bnuebar; bnuebar.resize(maxflux);
std::vector<Double_t> cnuebar; cnuebar.resize(maxflux);
std::vector<Double_t> anux; anux.resize(maxflux);
std::vector<Double_t> bnux; bnux.resize(maxflux);
std::vector<Double_t> cnux; cnux.resize(maxflux);
std::cout << "Reading flux parameters: ";
Int_t ip = 0;
while(1){
pin >> pnum[ip] >> anue[ip] >> anuebar[ip] >> anux[ip] >> bnue[ip] >> bnuebar[ip] >> bnux[ip] >> cnue[ip] >> cnuebar[ip] >> cnux[ip];
if(!pin.good()) break;
//std::cout << pnum[ip]<<" "<<anue[ip]<<" "<<anuebar[ip]<<" "<<anux[ip]<<" "<<bnue[ip]<<" "<<bnuebar[ip]<<" "<<bnux[ip]<<" "<<cnue[ip]<<" "<<cnuebar[ip]<<" "<<cnux[ip]<<std::endl;
++ip;
}
pin.close();
std::cout << "The " << grid << " grid contains " << ip << " fluxes." << std::endl;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// MAKE CHI2 MAP
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
TH1D* test_spectrum = fill_spect_hist(test_spect_filename,"test_spectrum",distanceSN, massfact);
//now we loop over templates in the grid
Int_t iFlux; //iterator over the grid
Int_t numfluxes = ip; //total number of fluxes we care about
const Int_t maxhist = maxflux;
Double_t chi2min = 100000000000.0;
Int_t dofbest;
Int_t ifbest;
Double_t chi2;
Int_t dof;
//keep values of chi2 for each flux
std::vector<Double_t> chi2values; chi2values.resize(maxhist);
//test
std::vector<Double_t> chi2values_tmp; std::vector<Int_t> iflux_tmp;
for(iFlux = 0; iFlux < numfluxes; ++iFlux){
// Do not go outside the limits
if(anue[iFlux] <= maxgoodalpha && bnue[iFlux] <= maxgoode0 && anue[iFlux] >= mingoodalpha && bnue[iFlux] >= mingoode0 ){
//define filename
TString pargridfilename = smeareddir+"/pinched_"+TString::Format("%d",iFlux)+"_smeared_sum.dat";
TString histname = "pinched_"+grid + "_" + grid_smear + "_" + grid_xscn + "_" + grid_effic + "_" + ts + "_" + ts_xscn + "_" + ts_effic + "_" + distanceStr + "kpc_"+TString::Format("%d",iFlux);
TH1D *pargridhist = fill_spect_hist(pargridfilename, histname, distanceSN, massfact);
mychi2(test_spectrum,pargridhist,&chi2,&dof);
// chi2 here is not per dof
// chi2 /= dof;
//save value
chi2values[iFlux] = chi2/dof;
//cout << "Chi2 "<< iFlux<<" "<< chi2<<" "<<dof<<endl;
if (chi2<chi2min) {
chi2min = chi2;
dofbest = dof;
ifbest = iFlux;
}
chi2values_tmp.emplace_back(chi2);
iflux_tmp.emplace_back(iFlux);
}
}
std::cout << "Best-fit measurement: (" << anue[ifbest] << ", " << bnue[ifbest] << ", " << cnue[ifbest] << ") with reduced chi2 = " << chi2min/dofbest << std::endl;
int index = std::distance(chi2values_tmp.begin(), std::min_element(chi2values_tmp.begin(), chi2values_tmp.end()) );
//now I want to make plots of chi2 vs parameter for the other two parameters
//at their fixed truth values!
std::vector<double> alphachi2;
std::vector<double> alphavals;
TString titlealpha("Minimum reduced #chi^{2} vs. #alpha;#alpha;Reduced #chi^{2}");
TString namealpha("Chi2VsAlpha");
std::vector<double> e0chi2;
std::vector<double> e0vals;
TString titlee0("Minimum reduced #chi^{2} vs. #LT E_{#nu} #GT;#LT E_{#nu} #GT (MeV);Reduced #chi^{2}");
TString namee0("Chi2VsE0");
std::vector<double> lumchi2;
std::vector<double> lumvals;
TString titlelum("Minimum reduced #chi^{2} vs. #varepsilon;#varepsilon (10^{53} erg);Reduced #chi^{2}");
TString namelum("Chi2VsLum");
//we also want to keep the alpha, e0, lum values corresponding to "good" chi2 values
TH2D *hAllowedRegion_AlphaVsE0 = new TH2D("alphavse0", ";#LT E_{#nu} #GT (MeV);#alpha", nume0bins, mine0, maxe0, numalphabins, minalpha, maxalpha );
TH2D *hAllowedRegion_LumVsE0 = new TH2D("lumvse0", ";#LT E_{#nu} #GT (MeV);#varepsilon (10^{53} erg)", nume0bins, mine0, maxe0, numlumbins, minlum/factor, maxlum/factor );
TH2D *hAllowedRegion_LumVsAlpha = new TH2D("lumvsalpha", ";#alpha;#varepsilon (10^{53} erg)", numalphabins, minalpha, maxalpha, numlumbins, minlum/factor, maxlum/factor );
TH2D *hAllowedRegion_AlphaVsE0_90Cut = new TH2D("alphavse0_90cut", ";#LT E_{#nu} #GT (MeV);#alpha", nume0bins, mine0, maxe0, numalphabins, minalpha, maxalpha );
TH2D *hAllowedRegion_LumVsE0_90Cut = new TH2D("lumvse0_90cut", ";#LT E_{#nu} #GT (MeV);#varepsilon (10^{53} erg)", nume0bins, mine0, maxe0, numlumbins, minlum/factor, maxlum/factor );
TH2D *hAllowedRegion_LumVsAlpha_90Cut = new TH2D("lumvsalpha_90cut", ";#alpha;#varepsilon (10^{53} erg)", numalphabins, minalpha, maxalpha, numlumbins, minlum/factor, maxlum/factor );
//set to zero
tr_numGoodGridElementsAlphavsE0 = 0;
tr_numGoodGridElementsLumvsE0 = 0;
tr_numGoodGridElementsLumvsAlpha = 0;
for(Double_t iAlpha = first_alpha; iAlpha <= last_alpha+step_alpha; iAlpha += step_alpha){
//iAlpha tells us the alpha value we care about
std::vector<double> chi2vals;
for(iFlux = 0; iFlux < numfluxes; ++iFlux){
//check to make sure we're at the right alpha value, and that alpha/E0 are physical
Int_t diff = ( anue[iFlux] - iAlpha )*100.0;
//if(diff == 0.0){
if(diff == 0.0 && anue[iFlux] <= maxgoodalpha && bnue[iFlux] <= maxgoode0 && anue[iFlux] >= mingoodalpha && bnue[iFlux] >= mingoode0){
chi2vals.emplace_back(chi2values[iFlux]);
}
}
//std::cout << iAlpha << " " << chi2vals.size() << std::endl;
//now we find the minimum chi2 from these values
if(chi2vals.size() > 0){
size_t iSmallest = std::distance(chi2vals.begin(), std::min_element( chi2vals.begin(), chi2vals.end() ));
alphavals.emplace_back( iAlpha );
alphachi2.emplace_back( chi2vals[iSmallest] );
//std::cout << iAlpha << " " << chi2vals[iSmallest] << std::endl;
}
//2D plot
for(Double_t iE0 = first_e0; iE0 <= last_e0; iE0 += step_e0){
std::vector<double> chi2vals2d;
for(iFlux = 0; iFlux < numfluxes; ++iFlux){
//check to make sure we're at the right alpha value, and that alpha/E0 are physical
Int_t diffalpha = ( anue[iFlux] - iAlpha )*100.0;
Int_t diffe0 = ( bnue[iFlux] - iE0 )*100.0;
//if(diffalpha == 0.0 && diffe0 == 0.0){
if(diffalpha == 0.0 && diffe0 == 0.0 && anue[iFlux] <= maxgoodalpha && bnue[iFlux] <= maxgoode0 && anue[iFlux] >= mingoodalpha && bnue[iFlux] >= mingoode0){
chi2vals2d.emplace_back(chi2values[iFlux]);
}
}
//std::cout << iAlpha << " " << iE0 << " " << chi2vals2d.size() << std::endl;
if(chi2vals2d.size() > 0){
size_t iSmallest = std::distance(chi2vals2d.begin(), std::min_element( chi2vals2d.begin(), chi2vals2d.end() ));
//std::cout << iAlpha << " " << iE0 << " " << chi2vals2d[iSmallest] << std::endl;
Double_t toFill = chi2vals2d[iSmallest];
if(toFill == 0.0) toFill = 1e-20;
if(toFill <= chi2_90contour){
++tr_numGoodGridElementsAlphavsE0;
hAllowedRegion_AlphaVsE0_90Cut->Fill(iE0, iAlpha, toFill);
}
hAllowedRegion_AlphaVsE0->Fill(iE0, iAlpha, toFill);
}
chi2vals2d = std::vector<double>();
}
//2D plot:
for(Double_t iLum = first_lum; iLum <= last_lum+step_lum; iLum += step_lum){
std::vector<double> chi2vals2d;
for(iFlux = 0; iFlux < numfluxes; ++iFlux){
//check to make sure we're at the right alpha value, and that alpha/E0 are physical
Int_t diffalpha = ( anue[iFlux] - iAlpha )*100.0;
Int_t difflum = ( cnue[iFlux]/factor - iLum/factor )*100.0;
//if(diffalpha == 0.0 && difflum == 0.0){
if(diffalpha == 0.0 && difflum == 0.0 && anue[iFlux] <= maxgoodalpha && bnue[iFlux] <= maxgoode0 && anue[iFlux] >= mingoodalpha && bnue[iFlux] >= mingoode0){
chi2vals2d.emplace_back(chi2values[iFlux]);
}
}
//std::cout << iAlpha << " " << iLum << " " << chi2vals2d.size() << std::endl;
if(chi2vals2d.size() > 0){
size_t iSmallest = std::distance(chi2vals2d.begin(), std::min_element( chi2vals2d.begin(), chi2vals2d.end() ));
//std::cout << iAlpha << " " << iLum << " " << chi2vals2d[iSmallest] << std::endl;
Double_t toFill = chi2vals2d[iSmallest];
if(toFill == 0.0) toFill = 1e-20;
if(toFill <= chi2_90contour){
++tr_numGoodGridElementsLumvsAlpha;
hAllowedRegion_LumVsAlpha_90Cut->Fill(iAlpha, iLum/factor, toFill);
}
hAllowedRegion_LumVsAlpha->Fill(iAlpha, iLum/factor, toFill);
}
chi2vals2d = std::vector<double>();
}
chi2vals = std::vector<double>();
}
for(Double_t iE0 = first_e0; iE0 <= last_e0; iE0 += step_e0){
//iE0 tells us the E0 value we care about
std::vector<double> chi2vals;
for(iFlux = 0; iFlux < numfluxes; ++iFlux){
//check to make sure we're at the right alpha value, and that alpha/E0 are physical
Int_t diffe0 = ( bnue[iFlux] - iE0 )*100.0;
//if(diffe0 == 0.0){
if(diffe0 == 0.0 && anue[iFlux] <= maxgoodalpha && bnue[iFlux] <= maxgoode0 && anue[iFlux] >= mingoodalpha && bnue[iFlux] >= mingoode0){
chi2vals.emplace_back(chi2values[iFlux]);
}
}
//now we find the minimum chi2 from these values
if(chi2vals.size() > 0){
size_t iSmallest = std::distance(chi2vals.begin(), std::min_element( chi2vals.begin(), chi2vals.end() ));
e0vals.emplace_back( iE0 );
e0chi2.emplace_back( chi2vals[iSmallest] );
//std::cout << iE0 << " " << chi2vals[iSmallest] << std::endl;
}
//2D plot
for(Double_t iLum = first_lum; iLum <= last_lum+step_lum; iLum += step_lum){
std::vector<double> chi2vals2d;
for(iFlux = 0; iFlux < numfluxes; ++iFlux){
//check to make sure we're at the right e0 value, and that alpha/E0 are physical
Int_t diffe0 = ( bnue[iFlux] - iE0 )*100.0;
Int_t difflum = ( cnue[iFlux]/factor - iLum/factor )*100.0;
//if(diffe0 == 0.0 && difflum == 0.0){
if(diffe0 == 0.0 && difflum == 0.0 && anue[iFlux] <= maxgoodalpha && bnue[iFlux] <= maxgoode0 && anue[iFlux] >= mingoodalpha && bnue[iFlux] >= mingoode0){
chi2vals2d.emplace_back(chi2values[iFlux]);
}
}
if(chi2vals2d.size() > 0){
size_t iSmallest = std::distance(chi2vals2d.begin(), std::min_element( chi2vals2d.begin(), chi2vals2d.end() ));
//std::cout << iE0 << " " << iLum << " " << chi2vals2d[iSmallest] << std::endl;
Double_t toFill = chi2vals2d[iSmallest];
if(toFill == 0.0) toFill = 1e-20;
if(toFill <= chi2_90contour){
++tr_numGoodGridElementsLumvsE0;
hAllowedRegion_LumVsE0_90Cut->Fill(iE0, iLum/factor, toFill);
}
hAllowedRegion_LumVsE0->Fill(iE0, iLum/factor, toFill);
}
chi2vals2d = std::vector<double>();
}
chi2vals = std::vector<double>();
}
for(Double_t iLum = first_lum; iLum <= last_lum+step_lum; iLum += step_lum){
//iLum tells us the luminosity value we care about
std::vector<double> chi2vals;
for(iFlux = 0; iFlux < numfluxes; ++iFlux){
//check to make sure we're at the right lum value, and that alpha/E0 are physical
Int_t difflum = ( cnue[iFlux]/factor - iLum/factor )*100.0;
//if(cnue[iFlux] == iLum){
if(difflum == 0.0){
if(anue[iFlux] < maxgoodalpha && bnue[iFlux] < maxgoode0 && anue[iFlux] > mingoodalpha && bnue[iFlux] > mingoode0) chi2vals.emplace_back(chi2values[iFlux]);
}
}
//now we find the minimum chi2 from these values
if(chi2vals.size() > 0){
size_t iSmallest = std::distance(chi2vals.begin(), std::min_element( chi2vals.begin(), chi2vals.end() ));
lumvals.emplace_back( iLum/factor );
lumchi2.emplace_back( chi2vals[iSmallest] );
//std::cout << iLum << " " << chi2vals[iSmallest] << std::endl;
}
chi2vals = std::vector<double>();
}
TGraph *g_Chi2VsAlpha = makeTGraphFromVectors(alphavals, alphachi2, titlealpha);
TGraph *g_Chi2VsE0 = makeTGraphFromVectors(e0vals, e0chi2, titlee0);
TGraph *g_Chi2VsLum = makeTGraphFromVectors(lumvals, lumchi2, titlelum);
hAllowedRegion_AlphaVsE0->GetXaxis()->CenterTitle();
hAllowedRegion_AlphaVsE0->GetXaxis()->SetTitleSize(0.05);
hAllowedRegion_AlphaVsE0->GetYaxis()->CenterTitle();
hAllowedRegion_AlphaVsE0->GetYaxis()->SetTitleSize(0.05);
hAllowedRegion_LumVsE0->GetXaxis()->CenterTitle();
hAllowedRegion_LumVsE0->GetXaxis()->SetTitleSize(0.04);
hAllowedRegion_LumVsE0->GetYaxis()->CenterTitle();
hAllowedRegion_LumVsE0->GetYaxis()->SetTitleSize(0.04);
hAllowedRegion_LumVsAlpha->GetXaxis()->CenterTitle();
hAllowedRegion_LumVsAlpha->GetXaxis()->SetTitleSize(0.05);
hAllowedRegion_LumVsAlpha->GetYaxis()->CenterTitle();
hAllowedRegion_LumVsAlpha->GetYaxis()->SetTitleSize(0.05);
//change boundaries
hAllowedRegion_AlphaVsE0->GetXaxis()->SetRangeUser(mine02, maxe02);
hAllowedRegion_AlphaVsE0->GetYaxis()->SetRangeUser(minalpha2, maxalpha2);
hAllowedRegion_LumVsE0->GetXaxis()->SetRangeUser(mine02, maxe02);
hAllowedRegion_LumVsE0->GetYaxis()->SetRangeUser(minlum2/factor, maxlum2/factor);
hAllowedRegion_LumVsAlpha->GetXaxis()->SetRangeUser(minalpha2, maxalpha2);
hAllowedRegion_LumVsAlpha->GetYaxis()->SetRangeUser(minlum2/factor, maxlum2/factor);
hAllowedRegion_AlphaVsE0_90Cut->GetXaxis()->SetRangeUser(mine02, maxe02);
hAllowedRegion_AlphaVsE0_90Cut->GetYaxis()->SetRangeUser(minalpha2, maxalpha2);
hAllowedRegion_LumVsE0_90Cut->GetXaxis()->SetRangeUser(mine02, maxe02);
hAllowedRegion_LumVsE0_90Cut->GetYaxis()->SetRangeUser(minlum2/factor, maxlum2/factor);
hAllowedRegion_LumVsAlpha_90Cut->GetXaxis()->SetRangeUser(minalpha2, maxalpha2);
hAllowedRegion_LumVsAlpha_90Cut->GetYaxis()->SetRangeUser(minlum2/factor, maxlum2/factor);
//limit 1D plots to ~5 sigma
//if(g_Chi2VsAlpha->GetYaxis()->GetXmax() > 25.0) g_Chi2VsAlpha->SetMaximum(25.0);
//if(g_Chi2VsE0->GetYaxis()->GetXmax() > 25.0) g_Chi2VsE0->SetMaximum(25.0);
//if(g_Chi2VsLum->GetYaxis()->GetXmax() > 25.0) g_Chi2VsLum->SetMaximum(25.0);
//set names
g_Chi2VsAlpha->SetName(namealpha);
g_Chi2VsE0->SetName(namee0);
g_Chi2VsLum->SetName(namelum);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// SAVE PLOTS
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//fill tree here
tr_alpha = anue[ifbest];
tr_e0 = bnue[ifbest];
tr_lum = cnue[ifbest]/factor;
tr_chi2 = chi2min;
tr_dof = dofbest;
tr_numGridElementsAlphavsE0 = numalphabins*nume0bins;
tr_numGridElementsLumvsE0 = numlumbins*nume0bins;
tr_numGridElementsLumvsAlpha = numalphabins*numlumbins;
tr->Fill();
TFile *fout = new TFile(outfile, "recreate");
tr->Write();
g_Chi2VsAlpha->Write();
g_Chi2VsE0->Write();
g_Chi2VsLum->Write();
hAllowedRegion_AlphaVsE0->Write();
hAllowedRegion_AlphaVsE0_90Cut->Write();
hAllowedRegion_LumVsE0->Write();
hAllowedRegion_LumVsE0_90Cut->Write();
hAllowedRegion_LumVsAlpha->Write();
hAllowedRegion_LumVsAlpha_90Cut->Write();
fout->Close();
//delete
delete test_spectrum;
delete hAllowedRegion_AlphaVsE0;
delete hAllowedRegion_AlphaVsE0_90Cut;
delete hAllowedRegion_LumVsE0;
delete hAllowedRegion_LumVsE0_90Cut;
delete hAllowedRegion_LumVsAlpha;
delete hAllowedRegion_LumVsAlpha_90Cut;
delete g_Chi2VsAlpha;
delete g_Chi2VsE0;
delete g_Chi2VsLum;
//deallocate vectors
pnum = std::vector<Int_t>();
anue = std::vector<Double_t>();
bnue = std::vector<Double_t>();
cnue = std::vector<Double_t>();
anuebar = std::vector<Double_t>();
bnuebar = std::vector<Double_t>();
cnuebar = std::vector<Double_t>();
anux = std::vector<Double_t>();
bnux = std::vector<Double_t>();
cnux = std::vector<Double_t>();
chi2values = std::vector<Double_t>();
alphavals = std::vector<double>();
alphachi2 = std::vector<double>();
e0vals = std::vector<double>();
e0chi2 = std::vector<double>();
lumvals = std::vector<double>();
lumchi2 = std::vector<double>();
//add line to separate the terminal output(s)
std::cout << "--------------------------------" << std::endl;
}//end function
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// AsimovMethodStepEfficStudy: Produces chi2-minimized flux parameter
// measurements and plots for a supernova located
// distanceSN from Earth. The grid and test spectrum
// are both described using the same smearing
// (smear), nue-Ar40 cross section model (xscn), and
// post-smearing efficiency model (effic) which must
// be a "step efficiency" model, i.e., 100%
// detection efficiency above some threshold. The
// grid detection threshold (grid_shift) and test
// spectrum threshold (ts_shift) can be different
// values.
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void AsimovMethodStepEfficStudy(Double_t distanceSN, TString grid, TString smear, TString xscn, TString effic, Double_t grid_shift, Double_t ts_shift){
std::cout << "Step efficiency study for a " << distanceSN << "kpc supernova, grid " << grid << ", and the following:" << std::endl;
std::cout << " Smearing " << smear << ", xscn " << xscn << ", and effic " << effic << std::endl;
std::cout << " Grid efficiency threshold " << grid_shift << " MeV; test spectrum efficiency threshold " << ts_shift << " MeV." << std::endl;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// DEFINE INPUTS
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
TString test_spect_filename = "input/test_spectra/pinched_test_smeared_sum_" + smear + "_" + xscn + "_" + effic + ".dat";
TString smeareddir = "input/" + grid + "/smear_" + smear + "_" + xscn + "_" + effic;
TString pinchedinfo = "input/pinched_info/pinched_info_" + grid + ".dat";
TString gridinfo = "input/grid_info/grid_info_" + grid + ".dat";
//define output file
TString distanceStr; distanceStr.Form("%.2lf", distanceSN);
TString gridShiftStr; gridShiftStr.Form("%.1lf", grid_shift);
TString tsShiftStr; tsShiftStr.Form("%.1lf", ts_shift);
TString outfile = "out/chi2plots_" + grid + "_smear" + smear + "_" + xscn + "_" + effic + gridShiftStr + "MeV_spectra" + smear + "_" + xscn + "_" + effic + tsShiftStr + "MeV_" + distanceStr + "kpc.root";
Double_t alpha_true = 2.5;
Double_t e0_true = 9.5; //mev
Double_t lum_true = 5e52; //ergs
Double_t massfact = 1.0;//2.4; //see the full DUNE far detector response
Double_t chi2_90contour = 4.61; //pdg 2018
//use same style settings that Kate used
gStyle->SetOptStat(0);
gStyle->SetPalette(1,0);
//set random seed
gRandom->SetSeed(0);
//define tree for output file
Double_t tr_alpha;
Double_t tr_e0;
Double_t tr_lum;
Double_t tr_chi2;
Double_t tr_dof;
TTree *tr = new TTree("data", "data");
tr->Branch("alpha", &tr_alpha, "alpha/D");
tr->Branch("e0", &tr_e0, "e0/D");
tr->Branch("lum", &tr_lum, "lum/D");
tr->Branch("chi2", &tr_chi2, "chi2/D");
tr->Branch("dof", &tr_dof, "dof/D");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// DEFINE GRID BOUNDS
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//define the bounds of the grid
Double_t first_alpha;
Double_t last_alpha;
Double_t step_alpha;
Double_t first_e0;
Double_t last_e0;
Double_t step_e0;
Double_t factor = 1e53;
Double_t first_lum;
Double_t last_lum;
Double_t step_lum;
//open grid_info.dat
ifstream gin;
gin.open(gridinfo);
Int_t ig = 0;
while(1){
gin >> first_alpha >> last_alpha >> step_alpha >> first_e0 >> last_e0 >> step_e0 >> first_lum >> last_lum >> step_lum;
if(!gin.good()) break;
++ig;
}
gin.close();
Double_t minalpha = first_alpha - step_alpha/2.0;
Double_t maxalpha = last_alpha + step_alpha/2.0;
Double_t mine0 = first_e0 - step_e0/2.0;
Double_t maxe0 = last_e0 + step_e0/2.0;
Double_t minlum = first_lum - step_lum/2.0;
Double_t maxlum = last_lum + step_lum/2.0;
Double_t minalpha2 = first_alpha - step_alpha*2.0;
Double_t maxalpha2 = last_alpha + step_alpha*2.0;
Double_t mine02 = first_e0 - step_e0*2.0;
Double_t maxe02 = last_e0 + step_e0*2.0;
Double_t minlum2 = first_lum - step_lum*2.0;
Double_t maxlum2 = last_lum + step_lum*2.0;
Int_t numalphabins = int(last_alpha - first_alpha)/step_alpha+1;
Int_t nume0bins = int(last_e0 - first_e0)/step_e0+1;
Int_t numlumbins = (last_lum - first_lum)/(step_lum) + 1;
//Range of physical parameters
Double_t mingoodalpha = first_alpha;//1.0;
Double_t maxgoodalpha = last_alpha;//7.0;
Double_t mingoode0 = first_e0;//0.0;
Double_t maxgoode0 = last_e0;//20.;
std::cout << "The " << grid << " grid follows this definition:" << std::endl;
std::cout << " Alpha: [" << first_alpha << ", " << last_alpha << "] with " << step_alpha << " spacing" << std::endl;
std::cout << " E0: [" << first_e0 << ", " << last_e0 << "] with " << step_e0 << " spacing" << std::endl;
std::cout << " Luminosity: [" << first_lum << ", " << last_lum << "] with " << step_lum << " spacing" << std::endl;
std::cout << "The parameter-fitting algorithm will consider the following physical range for alpha and E0:" << std::endl;
std::cout << " Alpha: [" << mingoodalpha << ", " << maxgoodalpha << "]" << std::endl;
std::cout << " E0: [" << mingoode0 << ", " << maxgoode0 << "]" << std::endl;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// READ PINCHING PARAMETERS
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//open the pinched parameter file
ifstream pin;
pin.open(pinchedinfo);
//define arrays, iterators to keep the parameters
const Int_t maxflux = 350000;
std::vector<Int_t> pnum; pnum.resize(maxflux);
std::vector<Double_t> anue; anue.resize(maxflux);
std::vector<Double_t> bnue; bnue.resize(maxflux);
std::vector<Double_t> cnue; cnue.resize(maxflux);
std::vector<Double_t> anuebar; anuebar.resize(maxflux);
std::vector<Double_t> bnuebar; bnuebar.resize(maxflux);
std::vector<Double_t> cnuebar; cnuebar.resize(maxflux);
std::vector<Double_t> anux; anux.resize(maxflux);
std::vector<Double_t> bnux; bnux.resize(maxflux);
std::vector<Double_t> cnux; cnux.resize(maxflux);
std::cout << "Reading flux parameters: ";
Int_t ip = 0;
while(1){
pin >> pnum[ip] >> anue[ip] >> anuebar[ip] >> anux[ip] >> bnue[ip] >> bnuebar[ip] >> bnux[ip] >> cnue[ip] >> cnuebar[ip] >> cnux[ip];
if(!pin.good()) break;
//std::cout << pnum[ip]<<" "<<anue[ip]<<" "<<anuebar[ip]<<" "<<anux[ip]<<" "<<bnue[ip]<<" "<<bnuebar[ip]<<" "<<bnux[ip]<<" "<<cnue[ip]<<" "<<cnuebar[ip]<<" "<<cnux[ip]<<std::endl;
++ip;
}
pin.close();
std::cout << "The " << grid << " grid contains " << ip << " fluxes." << std::endl;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// MAKE CHI2 MAP
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
TH1D* test_spectrum = shift_spect_hist(test_spect_filename,"test_spectrum",distanceSN, massfact, ts_shift);
//now we loop over templates in the grid
Int_t iFlux; //iterator over the grid
Int_t numfluxes = ip; //total number of fluxes we care about
const Int_t maxhist = maxflux;
Double_t chi2min = 100000000000.0;
Int_t dofbest;
Int_t ifbest;
Double_t chi2;
Int_t dof;
//keep values of chi2 for each flux
std::vector<Double_t> chi2values; chi2values.resize(maxhist);
for(iFlux = 0; iFlux < numfluxes; ++iFlux){
// Do not go outside the limits
if(anue[iFlux] <= maxgoodalpha && bnue[iFlux] <= maxgoode0 && anue[iFlux] >= mingoodalpha && bnue[iFlux] >= mingoode0 ){
//define filename
TString pargridfilename = smeareddir+"/pinched_"+TString::Format("%d",iFlux)+"_smeared_sum.dat";
TString histname = "pinched_"+grid + "_" + smear + "_" + xscn + "_" + effic + gridShiftStr + "_" + smear + "_" + xscn + "_" + effic + tsShiftStr + "_" + distanceStr + "kpc_"+TString::Format("%d",iFlux);
//TH1D *pargridhist = fill_spect_hist(pargridfilename, histname, distanceSN, massfact);
TH1D *pargridhist = shift_spect_hist(pargridfilename, histname, distanceSN, massfact, grid_shift);
mychi2(test_spectrum,pargridhist,&chi2,&dof);
// chi2 here is not per dof
// chi2 /= dof;
//save value
chi2values[iFlux] = chi2/dof;
if(chi2 == 0.0){
//Double_t chi2test; Int_t doftest;
//switch the order of pargridhist, test_spectrum
//if they are truly identical, then chi2 == 0
mychi2(pargridhist, test_spectrum, &chi2, &dof);
}
//std::cout << anue[iFlux] << " " << bnue[iFlux] << " " << cnue[iFlux] << " " << chi2/dof << std::endl;
//cout << "Chi2 "<< iFlux<<" "<< chi2<<" "<<dof<<endl;
if (chi2<chi2min) {
chi2min = chi2;
dofbest = dof;
ifbest = iFlux;
}
}
}
//fill tree here
tr_alpha = anue[ifbest];
tr_e0 = bnue[ifbest];
tr_lum = cnue[ifbest]/factor;
tr_chi2 = chi2min;
tr_dof = dofbest;
tr->Fill();
std::cout << "Best-fit measurement: (" << anue[ifbest] << ", " << bnue[ifbest] << ", " << cnue[ifbest] << ") with reduced chi2 = " << chi2min/dofbest << std::endl;
//now I want to make plots of chi2 vs parameter for the other two parameters
//at their fixed truth values!
std::vector<double> alphachi2;
std::vector<double> alphavals;
TString titlealpha("Minimum reduced #chi^{2} vs. #alpha;#alpha;Reduced #chi^{2}");
TString namealpha("Chi2VsAlpha");
std::vector<double> e0chi2;
std::vector<double> e0vals;
TString titlee0("Minimum reduced #chi^{2} vs. #LT E_{#nu} #GT;#LT E_{#nu} #GT (MeV);Reduced #chi^{2}");
TString namee0("Chi2VsE0");
std::vector<double> lumchi2;
std::vector<double> lumvals;
TString titlelum("Minimum reduced #chi^{2} vs. #epsilon;#epsilon (10^{53} erg);Reduced #chi^{2}");
TString namelum("Chi2VsLum");
//we also want to keep the alpha, e0, lum values corresponding to "good" chi2 values
TH2D *hAllowedRegion_AlphaVsE0 = new TH2D("alphavse0", ";#LT E_{#nu} #GT (MeV);#alpha", nume0bins, mine0, maxe0, numalphabins, minalpha, maxalpha );
TH2D *hAllowedRegion_LumVsE0 = new TH2D("lumvse0", ";#LT E_{#nu} #GT (MeV);#epsilon (10^{53} erg)", nume0bins, mine0, maxe0, numlumbins, minlum/factor, maxlum/factor );
TH2D *hAllowedRegion_LumVsAlpha = new TH2D("lumvsalpha", ";#alpha;#epsilon (10^{53} erg)", numalphabins, minalpha, maxalpha, numlumbins, minlum/factor, maxlum/factor );
TH2D *hAllowedRegion_AlphaVsE0_90Cut = new TH2D("alphavse0_90cut", ";#LT E_{#nu} #GT (MeV);#alpha", nume0bins, mine0, maxe0, numalphabins, minalpha, maxalpha );
TH2D *hAllowedRegion_LumVsE0_90Cut = new TH2D("lumvse0_90cut", ";#LT E_{#nu} #GT (MeV);#epsilon (10^{53} erg)", nume0bins, mine0, maxe0, numlumbins, minlum/factor, maxlum/factor );
TH2D *hAllowedRegion_LumVsAlpha_90Cut = new TH2D("lumvsalpha_90cut", ";#alpha;#epsilon (10^{53} erg)", numalphabins, minalpha, maxalpha, numlumbins, minlum/factor, maxlum/factor );
for(Double_t iAlpha = first_alpha; iAlpha <= last_alpha+step_alpha; iAlpha += step_alpha){
//iAlpha tells us the alpha value we care about
std::vector<double> chi2vals;
for(iFlux = 0; iFlux < numfluxes; ++iFlux){
//check to make sure we're at the right alpha value, and that alpha/E0 are physical
Int_t diff = ( anue[iFlux] - iAlpha )*100.0;
if(diff == 0.0 && anue[iFlux] <= maxgoodalpha && bnue[iFlux] <= maxgoode0 && anue[iFlux] >= mingoodalpha && bnue[iFlux] >= mingoode0){
chi2vals.emplace_back(chi2values[iFlux]);
}
}
//std::cout << iAlpha << " " << chi2vals.size() << std::endl;
//now we find the minimum chi2 from these values
if(chi2vals.size() > 0){
size_t iSmallest = std::distance(chi2vals.begin(), std::min_element( chi2vals.begin(), chi2vals.end() ));
alphavals.emplace_back( iAlpha );
alphachi2.emplace_back( chi2vals[iSmallest] );
//std::cout << iAlpha << " " << chi2vals[iSmallest] << std::endl;
}
//2D plot
for(Double_t iE0 = first_e0; iE0 <= last_e0; iE0 += step_e0){
std::vector<double> chi2vals2d;
for(iFlux = 0; iFlux < numfluxes; ++iFlux){
//check to make sure we're at the right alpha value, and that alpha/E0 are physical
Int_t diffalpha = ( anue[iFlux] - iAlpha )*100.0;
Int_t diffe0 = ( bnue[iFlux] - iE0 )*100.0;
if(diffalpha == 0.0 && diffe0 == 0.0 && anue[iFlux] <= maxgoodalpha && bnue[iFlux] <= maxgoode0 && anue[iFlux] >= mingoodalpha && bnue[iFlux] >= mingoode0){
chi2vals2d.emplace_back(chi2values[iFlux]);
}
}
//std::cout << iAlpha << " " << iE0 << " " << chi2vals2d.size() << std::endl;
if(chi2vals2d.size() > 0){
size_t iSmallest = std::distance(chi2vals2d.begin(), std::min_element( chi2vals2d.begin(), chi2vals2d.end() ));
//std::cout << iAlpha << " " << iE0 << " " << chi2vals2d[iSmallest] << std::endl;
Double_t toFill = chi2vals2d[iSmallest];
if(toFill == 0.0) toFill = 1e-20;
if(toFill <= chi2_90contour) hAllowedRegion_AlphaVsE0_90Cut->Fill(iE0, iAlpha, toFill);
hAllowedRegion_AlphaVsE0->Fill(iE0, iAlpha, toFill);
}
chi2vals2d = std::vector<double>();
}
//2D plot:
for(Double_t iLum = first_lum; iLum <= last_lum+step_lum; iLum += step_lum){
std::vector<double> chi2vals2d;
for(iFlux = 0; iFlux < numfluxes; ++iFlux){
//check to make sure we're at the right alpha value, and that alpha/E0 are physical
Int_t diffalpha = ( anue[iFlux] - iAlpha )*100.0;
Int_t difflum = ( cnue[iFlux]/factor - iLum/factor )*100.0;
if(diffalpha == 0.0 && difflum == 0.0 && anue[iFlux] <= maxgoodalpha && bnue[iFlux] <= maxgoode0 && anue[iFlux] >= mingoodalpha && bnue[iFlux] >= mingoode0){
chi2vals2d.emplace_back(chi2values[iFlux]);
}
}
//std::cout << iAlpha << " " << iLum << " " << chi2vals2d.size() << std::endl;
if(chi2vals2d.size() > 0){
size_t iSmallest = std::distance(chi2vals2d.begin(), std::min_element( chi2vals2d.begin(), chi2vals2d.end() ));
//std::cout << iAlpha << " " << iLum << " " << chi2vals2d[iSmallest] << std::endl;
Double_t toFill = chi2vals2d[iSmallest];
if(toFill == 0.0) toFill = 1e-20;
if(toFill <= chi2_90contour) hAllowedRegion_LumVsAlpha_90Cut->Fill(iAlpha, iLum/factor, toFill);
hAllowedRegion_LumVsAlpha->Fill(iAlpha, iLum/factor, toFill);
}
chi2vals2d = std::vector<double>();
}
chi2vals = std::vector<double>();
}
for(Double_t iE0 = first_e0; iE0 <= last_e0; iE0 += step_e0){
//iE0 tells us the E0 value we care about
std::vector<double> chi2vals;
for(iFlux = 0; iFlux < numfluxes; ++iFlux){
//check to make sure we're at the right alpha value, and that alpha/E0 are physical
Int_t diffe0 = ( bnue[iFlux] - iE0 )*100.0;
if(diffe0 == 0.0 && anue[iFlux] <= maxgoodalpha && bnue[iFlux] <= maxgoode0 && anue[iFlux] >= mingoodalpha && bnue[iFlux] >= mingoode0){
//if(bnue[iFlux] == iE0 && anue[iFlux] < maxgoodalpha && bnue[iFlux] < maxgoode0 && anue[iFlux] > mingoodalpha && bnue[iFlux] > mingoode0){
chi2vals.emplace_back(chi2values[iFlux]);
}
}
//now we find the minimum chi2 from these values
if(chi2vals.size() > 0){
size_t iSmallest = std::distance(chi2vals.begin(), std::min_element( chi2vals.begin(), chi2vals.end() ));
e0vals.emplace_back( iE0 );
e0chi2.emplace_back( chi2vals[iSmallest] );
//std::cout << iE0 << " " << chi2vals[iSmallest] << std::endl;
}
//2D plot
for(Double_t iLum = first_lum; iLum <= last_lum+step_lum; iLum += step_lum){
std::vector<double> chi2vals2d;
for(iFlux = 0; iFlux < numfluxes; ++iFlux){
//check to make sure we're at the right e0 value, and that alpha/E0 are physical
Int_t diffe0 = ( bnue[iFlux] - iE0 )*100.0;
Int_t difflum = ( cnue[iFlux]/factor - iLum/factor )*100.0;
if(diffe0 == 0.0 && difflum == 0.0 && anue[iFlux] <= maxgoodalpha && bnue[iFlux] <= maxgoode0 && anue[iFlux] >= mingoodalpha && bnue[iFlux] >= mingoode0){
chi2vals2d.emplace_back(chi2values[iFlux]);
}
}
if(chi2vals2d.size() > 0){
size_t iSmallest = std::distance(chi2vals2d.begin(), std::min_element( chi2vals2d.begin(), chi2vals2d.end() ));
//std::cout << iE0 << " " << iLum << " " << chi2vals2d[iSmallest] << std::endl;
Double_t toFill = chi2vals2d[iSmallest];
if(toFill == 0.0) toFill = 1e-20;
if(toFill <= chi2_90contour) hAllowedRegion_LumVsE0_90Cut->Fill(iE0, iLum/factor, toFill);
hAllowedRegion_LumVsE0->Fill(iE0, iLum/factor, toFill);
}
chi2vals2d = std::vector<double>();
}
chi2vals = std::vector<double>();
}
for(Double_t iLum = first_lum; iLum <= last_lum+step_lum; iLum += step_lum){
//iLum tells us the luminosity value we care about
std::vector<double> chi2vals;
for(iFlux = 0; iFlux < numfluxes; ++iFlux){
//check to make sure we're at the right lum value, and that alpha/E0 are physical
Int_t difflum = ( cnue[iFlux]/factor - iLum/factor )*100.0;
//if(cnue[iFlux] == iLum){
if(difflum == 0.0){
if(anue[iFlux] <= maxgoodalpha && bnue[iFlux] <= maxgoode0 && anue[iFlux] >= mingoodalpha && bnue[iFlux] >= mingoode0) chi2vals.emplace_back(chi2values[iFlux]);
}
}
//now we find the minimum chi2 from these values
if(chi2vals.size() > 0){
size_t iSmallest = std::distance(chi2vals.begin(), std::min_element( chi2vals.begin(), chi2vals.end() ));
lumvals.emplace_back( iLum/factor );
lumchi2.emplace_back( chi2vals[iSmallest] );
//std::cout << iLum << " " << chi2vals[iSmallest] << std::endl;
}
chi2vals = std::vector<double>();
}
TGraph *g_Chi2VsAlpha = makeTGraphFromVectors(alphavals, alphachi2, titlealpha);
TGraph *g_Chi2VsE0 = makeTGraphFromVectors(e0vals, e0chi2, titlee0);
TGraph *g_Chi2VsLum = makeTGraphFromVectors(lumvals, lumchi2, titlelum);
hAllowedRegion_AlphaVsE0->GetXaxis()->CenterTitle();
hAllowedRegion_AlphaVsE0->GetXaxis()->SetTitleSize(0.05);
hAllowedRegion_AlphaVsE0->GetYaxis()->CenterTitle();
hAllowedRegion_AlphaVsE0->GetYaxis()->SetTitleSize(0.05);
hAllowedRegion_LumVsE0->GetXaxis()->CenterTitle();
hAllowedRegion_LumVsE0->GetXaxis()->SetTitleSize(0.04);
hAllowedRegion_LumVsE0->GetYaxis()->CenterTitle();
hAllowedRegion_LumVsE0->GetYaxis()->SetTitleSize(0.04);
hAllowedRegion_LumVsAlpha->GetXaxis()->CenterTitle();
hAllowedRegion_LumVsAlpha->GetXaxis()->SetTitleSize(0.05);
hAllowedRegion_LumVsAlpha->GetYaxis()->CenterTitle();
hAllowedRegion_LumVsAlpha->GetYaxis()->SetTitleSize(0.05);
//change boundaries
hAllowedRegion_AlphaVsE0->GetXaxis()->SetRangeUser(mine02, maxe02);
hAllowedRegion_AlphaVsE0->GetYaxis()->SetRangeUser(minalpha2, maxalpha2);
hAllowedRegion_LumVsE0->GetXaxis()->SetRangeUser(mine02, maxe02);
hAllowedRegion_LumVsE0->GetYaxis()->SetRangeUser(minlum2/factor, maxlum2/factor);
hAllowedRegion_LumVsAlpha->GetXaxis()->SetRangeUser(minalpha2, maxalpha2);
hAllowedRegion_LumVsAlpha->GetYaxis()->SetRangeUser(minlum2/factor, maxlum2/factor);
hAllowedRegion_AlphaVsE0_90Cut->GetXaxis()->SetRangeUser(mine02, maxe02);
hAllowedRegion_AlphaVsE0_90Cut->GetYaxis()->SetRangeUser(minalpha2, maxalpha2);
hAllowedRegion_LumVsE0_90Cut->GetXaxis()->SetRangeUser(mine02, maxe02);
hAllowedRegion_LumVsE0_90Cut->GetYaxis()->SetRangeUser(minlum2/factor, maxlum2/factor);
hAllowedRegion_LumVsAlpha_90Cut->GetXaxis()->SetRangeUser(minalpha2, maxalpha2);
hAllowedRegion_LumVsAlpha_90Cut->GetYaxis()->SetRangeUser(minlum2/factor, maxlum2/factor);
//limit 1D plots to ~5 sigma
//if(g_Chi2VsAlpha->GetYaxis()->GetXmax() > 25.0) g_Chi2VsAlpha->SetMaximum(25.0);
//if(g_Chi2VsE0->GetYaxis()->GetXmax() > 25.0) g_Chi2VsE0->SetMaximum(25.0);
//if(g_Chi2VsLum->GetYaxis()->GetXmax() > 25.0) g_Chi2VsLum->SetMaximum(25.0);
//set names
g_Chi2VsAlpha->SetName(namealpha);
g_Chi2VsE0->SetName(namee0);
g_Chi2VsLum->SetName(namelum);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// SAVE PLOTS
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
TFile *fout = new TFile(outfile, "recreate");
tr->Write();
g_Chi2VsAlpha->Write();
g_Chi2VsE0->Write();
g_Chi2VsLum->Write();
hAllowedRegion_AlphaVsE0->Write();
hAllowedRegion_AlphaVsE0_90Cut->Write();
hAllowedRegion_LumVsE0->Write();
hAllowedRegion_LumVsE0_90Cut->Write();
hAllowedRegion_LumVsAlpha->Write();
hAllowedRegion_LumVsAlpha_90Cut->Write();
fout->Close();
//delete
delete test_spectrum;
delete hAllowedRegion_AlphaVsE0;
delete hAllowedRegion_AlphaVsE0_90Cut;
delete hAllowedRegion_LumVsE0;
delete hAllowedRegion_LumVsE0_90Cut;
delete hAllowedRegion_LumVsAlpha;
delete hAllowedRegion_LumVsAlpha_90Cut;
delete g_Chi2VsAlpha;
delete g_Chi2VsE0;
delete g_Chi2VsLum;
//deallocate vectors
pnum = std::vector<Int_t>();
anue = std::vector<Double_t>();
bnue = std::vector<Double_t>();
cnue = std::vector<Double_t>();
anuebar = std::vector<Double_t>();
bnuebar = std::vector<Double_t>();
cnuebar = std::vector<Double_t>();
anux = std::vector<Double_t>();
bnux = std::vector<Double_t>();
cnux = std::vector<Double_t>();
chi2values = std::vector<Double_t>();
alphavals = std::vector<double>();
alphachi2 = std::vector<double>();
e0vals = std::vector<double>();
e0chi2 = std::vector<double>();
lumvals = std::vector<double>();
lumchi2 = std::vector<double>();
std::cout << "------------------------------------------------------" << std::endl;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// AsimovMethodScaled: Produces chi2-minimized flux parameter measurements and
// plots for a supernova located distanceSN from Earth. The
// supernova is defined by a test spectrum with SNOwGLoBES
// smearing ts, nue-Ar40 cross section ts_xscn, and post-
// smearing efficiency model ts_effic. The energy scale of
// the test spectrum can be shifted by setting the ts_scale
// parameter in the range (-1, 1). The detector assumptions
// are defined by a grid described by its parameter bounds
// (grid), SNOwGLoBES smearing (grid_smear), nue-Ar40 cross
// section model (grid_xscn), and efficiency model
// (grid_xscn). The energy scale for each of the grid
// elements can be shifted by setting the grid_scale
// parameter in the range (-1, 1).
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void AsimovMethodScaled(Double_t distanceSN, TString grid, TString grid_smear, Double_t grid_scale, TString grid_xscn, TString grid_effic, TString ts, Double_t ts_scale, TString ts_xscn, TString ts_effic){
std::cout << "Producing sensitivity plots for a " << distanceSN << "kpc supernova and the following input parameters:" << std::endl;
std::cout << " Grid: " << grid << " with smearing " << grid_smear << ", scaling " << grid_scale << "%, xscn " << grid_xscn << ", and effic " << grid_effic << std::endl;
std::cout << " Test spectrum: " << ts << " with scaling " << ts_scale << "%, xscn " << ts_xscn << " and effic " << ts_effic << std::endl;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// DEFINE INPUTS
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
TString test_spect_filename = "input/test_spectra/pinched_test_smeared_sum_" + ts + "_" + ts_xscn + "_" + ts_effic + ".dat";
TString smeareddir = "input/" + grid + "/smear_" + grid_smear + "_" + grid_xscn + "_" + grid_effic;
TString pinchedinfo = "input/pinched_info/pinched_info_" + grid + ".dat";
TString gridinfo = "input/grid_info/grid_info_" + grid + ".dat";
//define output file
TString distanceStr; distanceStr.Form("%.2lf", distanceSN);
//need to define the percent;
TString scaleGridStr; scaleGridStr.Form("%.0lf",grid_scale);
TString scaleGridPercent;
if(grid_scale > 0) scaleGridPercent = "+" + scaleGridStr + "Percent";
else if(grid_scale < 0) scaleGridPercent = scaleGridStr + "Percent";
TString scaleTSStr; scaleTSStr.Form("%.0lf",ts_scale);
TString scaleTSPercent;
if(ts_scale > 0) scaleTSPercent = "+" + scaleTSStr + "Percent";
else if(ts_scale < 0) scaleTSPercent = scaleTSStr + "Percent";
//then scalePercent should be nothing if scale_dc == 0.0
TString outfile = "out/chi2plots_" + grid + "_smear" + grid_smear + scaleGridPercent + "_" + grid_xscn + "_" + grid_effic + "_spectra" + ts + scaleTSPercent + "_" + ts_xscn + "_" + ts_effic + "_" + distanceStr + "kpc.root";
std::cout << "Output file: " << outfile << std::endl;
//define true parameters
Double_t alpha_true = 2.5;
Double_t e0_true = 9.5; //mev
Double_t lum_true = 5e52; //ergs
Double_t massfact = 1.0;//2.4; //see the full DUNE far detector response
Double_t chi2_90contour = 4.61; //pdg 2018
//use same style settings that Kate used
gStyle->SetOptStat(0);
gStyle->SetPalette(1,0);
//set random seed
gRandom->SetSeed(0);
//define tree for output file
Double_t tr_alpha;
Double_t tr_e0;
Double_t tr_lum;
Double_t tr_chi2;
Double_t tr_dof;
TTree *tr = new TTree("data", "data");
tr->Branch("alpha", &tr_alpha, "alpha/D");
tr->Branch("e0", &tr_e0, "e0/D");
tr->Branch("lum", &tr_lum, "lum/D");
tr->Branch("chi2", &tr_chi2, "chi2/D");
tr->Branch("dof", &tr_dof, "dof/D");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// DEFINE GRID BOUNDS
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//define the bounds of the grid
Double_t first_alpha;
Double_t last_alpha;
Double_t step_alpha;
Double_t first_e0;
Double_t last_e0;
Double_t step_e0;
Double_t factor = 1e53;
Double_t first_lum;
Double_t last_lum;
Double_t step_lum;
//open grid_info.dat
ifstream gin;
gin.open(gridinfo);
Int_t ig = 0;
while(1){
gin >> first_alpha >> last_alpha >> step_alpha >> first_e0 >> last_e0 >> step_e0 >> first_lum >> last_lum >> step_lum;
if(!gin.good()) break;
++ig;
}
gin.close();
Double_t minalpha = first_alpha - step_alpha/2.0;
Double_t maxalpha = last_alpha + step_alpha/2.0;
Double_t mine0 = first_e0 - step_e0/2.0;
Double_t maxe0 = last_e0 + step_e0/2.0;
Double_t minlum = first_lum - step_lum/2.0;
Double_t maxlum = last_lum + step_lum/2.0;
Double_t minalpha2 = first_alpha - step_alpha*2.0;
Double_t maxalpha2 = last_alpha + step_alpha*2.0;
Double_t mine02 = first_e0 - step_e0*2.0;
Double_t maxe02 = last_e0 + step_e0*2.0;
Double_t minlum2 = first_lum - step_lum*2.0;
Double_t maxlum2 = last_lum + step_lum*2.0;
Int_t numalphabins2 = int(maxalpha2 - minalpha2)/step_alpha+1;
Int_t nume0bins2 = int(maxe02 - mine02)/step_e0+1;
Int_t numlumbins2 = (maxlum2 - minlum2)/(step_lum) + 1;
Int_t numalphabins = int(last_alpha - first_alpha)/step_alpha+1;
Int_t nume0bins = int(last_e0 - first_e0)/step_e0+1;
Int_t numlumbins = (last_lum - first_lum)/(step_lum) + 1;
//Range of physical parameters
Double_t mingoodalpha = first_alpha;//1.0;
Double_t maxgoodalpha = last_alpha;//7.0;
Double_t mingoode0 = first_e0;//0.0;
Double_t maxgoode0 = last_e0;//20.;
std::cout << "The " << grid << " grid follows this definition:" << std::endl;
std::cout << " Alpha: [" << first_alpha << ", " << last_alpha << "] with " << step_alpha << " spacing" << std::endl;
std::cout << " E0: [" << first_e0 << ", " << last_e0 << "] with " << step_e0 << " spacing" << std::endl;
std::cout << " Luminosity: [" << first_lum << ", " << last_lum << "] with " << step_lum << " spacing" << std::endl;
std::cout << "The parameter-fitting algorithm will consider the following physical range for alpha and E0:" << std::endl;
std::cout << " Alpha: [" << mingoodalpha << ", " << maxgoodalpha << "]" << std::endl;
std::cout << " E0: [" << mingoode0 << ", " << maxgoode0 << "]" << std::endl;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// READ PINCHING PARAMETERS
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//open the pinched parameter file
ifstream pin;
pin.open(pinchedinfo);
//define arrays, iterators to keep the parameters
const Int_t maxflux = 350000;
std::vector<Int_t> pnum; pnum.resize(maxflux);
std::vector<Double_t> anue; anue.resize(maxflux);
std::vector<Double_t> bnue; bnue.resize(maxflux);
std::vector<Double_t> cnue; cnue.resize(maxflux);
std::vector<Double_t> anuebar; anuebar.resize(maxflux);
std::vector<Double_t> bnuebar; bnuebar.resize(maxflux);
std::vector<Double_t> cnuebar; cnuebar.resize(maxflux);
std::vector<Double_t> anux; anux.resize(maxflux);
std::vector<Double_t> bnux; bnux.resize(maxflux);
std::vector<Double_t> cnux; cnux.resize(maxflux);
std::cout << "Reading flux parameters: ";
Int_t ip = 0;
while(1){
//Int_t p1;
//Double_t a1, a2, a3, b1, b2, b3, c1, c2, c3;
//pin >> p1 >> a1 >> a2 >> a3 >> b1 >> b2 >> b3 >> c1 >> c2 >> c3;
pin >> pnum[ip] >> anue[ip] >> anuebar[ip] >> anux[ip] >> bnue[ip] >> bnuebar[ip] >> bnux[ip] >> cnue[ip] >> cnuebar[ip] >> cnux[ip];
if(!pin.good()) break;
//std::cout << pnum[ip]<<" "<<anue[ip]<<" "<<anuebar[ip]<<" "<<anux[ip]<<" "<<bnue[ip]<<" "<<bnuebar[ip]<<" "<<bnux[ip]<<" "<<cnue[ip]<<" "<<cnuebar[ip]<<" "<<cnux[ip]<<std::endl;
++ip;
}
pin.close();
std::cout << "The " << grid << " grid contains " << ip << " fluxes." << std::endl;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// FIND BEST-FIT PARAMETERS
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//test spectrum already made with the appropriate scaling, so don't need to change this
//TH1D* test_spectrum = fill_spect_hist(test_spect_filename,"test_spectrum",distanceSN, massfact);
TH1D* test_spectrum = scale_spect_hist(test_spect_filename, ts_scale, "test_spectrum", distanceSN, massfact);
//now we loop over templates in the grid
Int_t iFlux; //iterator over the grid
Int_t numfluxes = ip; //total number of fluxes we care about
const Int_t maxhist = maxflux;
//define array to hold the hists
//TH1D** pargridhist;
//pargridhist = new TH1D*[maxhist];
Double_t chi2min = 100000000000.0;
Int_t dofbest;
Int_t ifbest;
Double_t chi2;
Int_t dof;
//keep values of chi2 for each flux
//Double_t* chi2values = new Double_t[maxhist];
//Double_t chi2values[maxhist];
std::vector<Double_t> chi2values; chi2values.resize(maxhist);
for(iFlux = 0; iFlux < numfluxes; ++iFlux){
// Do not go outside the limits
if(anue[iFlux] <= maxgoodalpha && bnue[iFlux] <= maxgoode0 && anue[iFlux] >= mingoodalpha && bnue[iFlux] >= mingoode0 ){
//define filename
TString pargridfilename = smeareddir+"/pinched_"+TString::Format("%d",iFlux)+"_smeared_sum.dat";
//TString histname = "pinched_"+TString::Format("%d",iFlux);
TString histname = "pinched_"+grid + "_" + grid_smear + TString::Format("%.2lf",grid_scale)+ "_" + ts + "_"+TString::Format("%d",iFlux);
TH1D* pargridhist = scale_spect_hist(pargridfilename, grid_scale, histname, distanceSN, massfact);
//mychi2(test_spectrum,pargridhist[iFlux],&chi2,&dof);
mychi2(test_spectrum,pargridhist,&chi2,&dof);
// chi2 here is not per dof
// chi2 /= dof;
//save value
chi2values[iFlux] = chi2/dof;
//std::cout << anue[iFlux] << " " << bnue[iFlux] << " " << cnue[iFlux] << " " << chi2/dof << std::endl;
//cout << "Chi2 "<< iFlux<<" "<< chi2<<" "<<dof<<endl;
if (chi2<chi2min) {
chi2min = chi2;
dofbest = dof;
ifbest = iFlux;
}
//pargridhist[iFlux]->Draw("SAME");
delete pargridhist;
}
}
//fill tree here
tr_alpha = anue[ifbest];
tr_e0 = bnue[ifbest];
tr_lum = cnue[ifbest]/factor;
tr_chi2 = chi2min;
tr_dof = dofbest;
tr->Fill();
std::cout << "Best-fit measurement: (" << anue[ifbest] << ", " << bnue[ifbest] << ", " << cnue[ifbest] << ") with reduced chi2 = " << chi2min/dofbest << std::endl;
//now I want to make plots of chi2 vs parameter for the other two parameters
//at their fixed truth values!
std::vector<double> alphachi2;
std::vector<double> alphavals;
TString titlealpha("Minimum reduced #chi^{2} vs. #alpha;#alpha;Reduced #chi^{2}");
TString namealpha("Chi2VsAlpha");
std::vector<double> e0chi2;
std::vector<double> e0vals;
TString titlee0("Minimum reduced #chi^{2} vs. #LT E_{#nu} #GT;#LT E_{#nu} #GT (MeV);Reduced #chi^{2}");
TString namee0("Chi2VsE0");
std::vector<double> lumchi2;
std::vector<double> lumvals;
TString titlelum("Minimum reduced #chi^{2} vs. #epsilon;#epsilon (10^{53} erg);Reduced #chi^{2}");
TString namelum("Chi2VsLum");
//we also want to keep the alpha, e0, lum values corresponding to "good" chi2 values
TH2D *hAllowedRegion_AlphaVsE0 = new TH2D("alphavse0", ";#LT E_{#nu} #GT (MeV);#alpha", nume0bins, mine0, maxe0, numalphabins, minalpha, maxalpha );
TH2D *hAllowedRegion_LumVsE0 = new TH2D("lumvse0", ";#LT E_{#nu} #GT (MeV);#epsilon (10^{53} erg)", nume0bins, mine0, maxe0, numlumbins, minlum/factor, maxlum/factor );
TH2D *hAllowedRegion_LumVsAlpha = new TH2D("lumvsalpha", ";#alpha;#epsilon (10^{53} erg)", numalphabins, minalpha, maxalpha, numlumbins, minlum/factor, maxlum/factor );
TH2D *hAllowedRegion_AlphaVsE0_90Cut = new TH2D("alphavse0_90cut", ";#LT E_{#nu} #GT (MeV);#alpha", nume0bins, mine0, maxe0, numalphabins, minalpha, maxalpha );
TH2D *hAllowedRegion_LumVsE0_90Cut = new TH2D("lumvse0_90cut", ";#LT E_{#nu} #GT (MeV);#epsilon (10^{53} erg)", nume0bins, mine0, maxe0, numlumbins, minlum/factor, maxlum/factor );
TH2D *hAllowedRegion_LumVsAlpha_90Cut = new TH2D("lumvsalpha_90cut", ";#alpha;#epsilon (10^{53} erg)", numalphabins, minalpha, maxalpha, numlumbins, minlum/factor, maxlum/factor );
for(Double_t iAlpha = first_alpha; iAlpha <= last_alpha+step_alpha; iAlpha += step_alpha){
//iAlpha tells us the alpha value we care about
std::vector<double> chi2vals;
for(iFlux = 0; iFlux < numfluxes; ++iFlux){
//check to make sure we're at the right alpha value, and that alpha/E0 are physical
Int_t diff = ( anue[iFlux] - iAlpha )*100.0;
if(diff == 0.0 && anue[iFlux] <= maxgoodalpha && bnue[iFlux] <= maxgoode0 && anue[iFlux] >= mingoodalpha && bnue[iFlux] >= mingoode0){
chi2vals.emplace_back(chi2values[iFlux]);
}
}
//std::cout << iAlpha << " " << chi2vals.size() << std::endl;
//now we find the minimum chi2 from these values
if(chi2vals.size() > 0){
size_t iSmallest = std::distance(chi2vals.begin(), std::min_element( chi2vals.begin(), chi2vals.end() ));
alphavals.emplace_back( iAlpha );
alphachi2.emplace_back( chi2vals[iSmallest] );
//std::cout << iAlpha << " " << chi2vals[iSmallest] << std::endl;
}
//2D plot
for(Double_t iE0 = first_e0; iE0 <= last_e0; iE0 += step_e0){
std::vector<double> chi2vals2d;
for(iFlux = 0; iFlux < numfluxes; ++iFlux){
//check to make sure we're at the right alpha value, and that alpha/E0 are physical
Int_t diffalpha = ( anue[iFlux] - iAlpha )*100.0;
Int_t diffe0 = ( bnue[iFlux] - iE0 )*100.0;
if(diffalpha == 0.0 && diffe0 == 0.0 && anue[iFlux] <= maxgoodalpha && bnue[iFlux] <= maxgoode0 && anue[iFlux] >= mingoodalpha && bnue[iFlux] >= mingoode0){
chi2vals2d.emplace_back(chi2values[iFlux]);
}
}
//std::cout << iAlpha << " " << iE0 << " " << chi2vals2d.size() << std::endl;
if(chi2vals2d.size() > 0){
size_t iSmallest = std::distance(chi2vals2d.begin(), std::min_element( chi2vals2d.begin(), chi2vals2d.end() ));
//std::cout << iAlpha << " " << iE0 << " " << chi2vals2d[iSmallest] << std::endl;
if(chi2vals2d[iSmallest] <= chi2_90contour) hAllowedRegion_AlphaVsE0_90Cut->Fill(iE0, iAlpha, chi2vals2d[iSmallest]);
hAllowedRegion_AlphaVsE0->Fill(iE0, iAlpha, chi2vals2d[iSmallest]);
}
}
//2D plot:
for(Double_t iLum = first_lum; iLum <= last_lum+step_lum; iLum += step_lum){
std::vector<double> chi2vals2d;
for(iFlux = 0; iFlux < numfluxes; ++iFlux){
//check to make sure we're at the right alpha value, and that alpha/E0 are physical
Int_t diffalpha = ( anue[iFlux] - iAlpha )*100.0;
Int_t difflum = ( cnue[iFlux]/factor - iLum/factor )*100.0;
if(diffalpha == 0.0 && difflum == 0.0 && anue[iFlux] <= maxgoodalpha && bnue[iFlux] <= maxgoode0 && anue[iFlux] >= mingoodalpha && bnue[iFlux] >= mingoode0){
chi2vals2d.emplace_back(chi2values[iFlux]);
}
}
//std::cout << iAlpha << " " << iLum << " " << chi2vals2d.size() << std::endl;
if(chi2vals2d.size() > 0){
size_t iSmallest = std::distance(chi2vals2d.begin(), std::min_element( chi2vals2d.begin(), chi2vals2d.end() ));
//std::cout << iAlpha << " " << iLum << " " << chi2vals2d[iSmallest] << std::endl;
if(chi2vals2d[iSmallest] <= chi2_90contour) hAllowedRegion_LumVsAlpha_90Cut->Fill(iAlpha, iLum/factor, chi2vals2d[iSmallest]);
hAllowedRegion_LumVsAlpha->Fill(iAlpha, iLum/factor, chi2vals2d[iSmallest]);
}
}
//de-allocate vectors here
chi2vals = std::vector<double>();
}
for(Double_t iE0 = first_e0; iE0 <= last_e0; iE0 += step_e0){
//iE0 tells us the E0 value we care about
std::vector<double> chi2vals;
for(iFlux = 0; iFlux < numfluxes; ++iFlux){
//check to make sure we're at the right alpha value, and that alpha/E0 are physical
Int_t diffe0 = ( bnue[iFlux] - iE0 )*100.0;
if(diffe0 == 0.0 && anue[iFlux] <= maxgoodalpha && bnue[iFlux] <= maxgoode0 && anue[iFlux] >= mingoodalpha && bnue[iFlux] >= mingoode0){
chi2vals.emplace_back(chi2values[iFlux]);
}
}
//now we find the minimum chi2 from these values
if(chi2vals.size() > 0){
size_t iSmallest = std::distance(chi2vals.begin(), std::min_element( chi2vals.begin(), chi2vals.end() ));
e0vals.emplace_back( iE0 );
e0chi2.emplace_back( chi2vals[iSmallest] );
//std::cout << iE0 << " " << chi2vals[iSmallest] << std::endl;
}
//2D plot
for(Double_t iLum = first_lum; iLum <= last_lum+step_lum; iLum += step_lum){
std::vector<double> chi2vals2d;
for(iFlux = 0; iFlux < numfluxes; ++iFlux){
//check to make sure we're at the right e0 value, and that alpha/E0 are physical
Int_t diffe0 = ( bnue[iFlux] - iE0 )*100.0;
Int_t difflum = ( cnue[iFlux]/factor - iLum/factor )*100.0;
if(diffe0 == 0.0 && difflum == 0.0 && anue[iFlux] <= maxgoodalpha && bnue[iFlux] <= maxgoode0 && anue[iFlux] >= mingoodalpha && bnue[iFlux] >= mingoode0){
chi2vals2d.emplace_back(chi2values[iFlux]);
}
}
if(chi2vals2d.size() > 0){
size_t iSmallest = std::distance(chi2vals2d.begin(), std::min_element( chi2vals2d.begin(), chi2vals2d.end() ));
//std::cout << iE0 << " " << iLum << " " << chi2vals2d[iSmallest] << std::endl;
if(chi2vals2d[iSmallest] <= chi2_90contour) hAllowedRegion_LumVsE0_90Cut->Fill(iE0, iLum/factor, chi2vals2d[iSmallest]);
hAllowedRegion_LumVsE0->Fill(iE0, iLum/factor, chi2vals2d[iSmallest]);
}
}
//de-allocate vectors here
chi2vals = std::vector<double>();
}
for(Double_t iLum = first_lum; iLum <= last_lum+step_lum; iLum += step_lum){
//iLum tells us the luminosity value we care about
std::vector<double> chi2vals;
for(iFlux = 0; iFlux < numfluxes; ++iFlux){
//check to make sure we're at the right lum value, and that alpha/E0 are physical
Int_t difflum = ( cnue[iFlux]/factor - iLum/factor )*100.0;
//if(cnue[iFlux] == iLum){
if(difflum == 0.0){
if(anue[iFlux] <= maxgoodalpha && bnue[iFlux] <= maxgoode0 && anue[iFlux] >= mingoodalpha && bnue[iFlux] >= mingoode0) chi2vals.emplace_back(chi2values[iFlux]);
}
}
//now we find the minimum chi2 from these values
if(chi2vals.size() > 0){
size_t iSmallest = std::distance(chi2vals.begin(), std::min_element( chi2vals.begin(), chi2vals.end() ));
lumvals.emplace_back( iLum/factor );
lumchi2.emplace_back( chi2vals[iSmallest] );
//std::cout << iLum << " " << chi2vals[iSmallest] << std::endl;
}
//de-allocate vectors here
chi2vals = std::vector<double>();
}
TGraph *g_Chi2VsAlpha = makeTGraphFromVectors(alphavals, alphachi2, titlealpha);
TGraph *g_Chi2VsE0 = makeTGraphFromVectors(e0vals, e0chi2, titlee0);
TGraph *g_Chi2VsLum = makeTGraphFromVectors(lumvals, lumchi2, titlelum);
hAllowedRegion_AlphaVsE0->GetXaxis()->CenterTitle();
hAllowedRegion_AlphaVsE0->GetXaxis()->SetTitleSize(0.05);
hAllowedRegion_AlphaVsE0->GetYaxis()->CenterTitle();
hAllowedRegion_AlphaVsE0->GetYaxis()->SetTitleSize(0.05);
hAllowedRegion_LumVsE0->GetXaxis()->CenterTitle();
hAllowedRegion_LumVsE0->GetXaxis()->SetTitleSize(0.04);
hAllowedRegion_LumVsE0->GetYaxis()->CenterTitle();
hAllowedRegion_LumVsE0->GetYaxis()->SetTitleSize(0.04);
hAllowedRegion_LumVsAlpha->GetXaxis()->CenterTitle();
hAllowedRegion_LumVsAlpha->GetXaxis()->SetTitleSize(0.05);
hAllowedRegion_LumVsAlpha->GetYaxis()->CenterTitle();
hAllowedRegion_LumVsAlpha->GetYaxis()->SetTitleSize(0.05);
//change boundaries
hAllowedRegion_AlphaVsE0->GetXaxis()->SetRangeUser(mine02, maxe02);
hAllowedRegion_AlphaVsE0->GetYaxis()->SetRangeUser(minalpha2, maxalpha2);
hAllowedRegion_LumVsE0->GetXaxis()->SetRangeUser(mine02, maxe02);
hAllowedRegion_LumVsE0->GetYaxis()->SetRangeUser(minlum2/factor, maxlum2/factor);
hAllowedRegion_LumVsAlpha->GetXaxis()->SetRangeUser(minalpha2, maxalpha2);
hAllowedRegion_LumVsAlpha->GetYaxis()->SetRangeUser(minlum2/factor, maxlum2/factor);
hAllowedRegion_AlphaVsE0_90Cut->GetXaxis()->SetRangeUser(mine02, maxe02);
hAllowedRegion_AlphaVsE0_90Cut->GetYaxis()->SetRangeUser(minalpha2, maxalpha2);
hAllowedRegion_LumVsE0_90Cut->GetXaxis()->SetRangeUser(mine02, maxe02);
hAllowedRegion_LumVsE0_90Cut->GetYaxis()->SetRangeUser(minlum2/factor, maxlum2/factor);
hAllowedRegion_LumVsAlpha_90Cut->GetXaxis()->SetRangeUser(minalpha2, maxalpha2);
hAllowedRegion_LumVsAlpha_90Cut->GetYaxis()->SetRangeUser(minlum2/factor, maxlum2/factor);
//set names
g_Chi2VsAlpha->SetName(namealpha);
g_Chi2VsE0->SetName(namee0);
g_Chi2VsLum->SetName(namelum);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// SAVE PLOTS
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
TFile *fout = new TFile(outfile, "recreate");
tr->Write();
g_Chi2VsAlpha->Write();
g_Chi2VsE0->Write();
g_Chi2VsLum->Write();
hAllowedRegion_AlphaVsE0->Write();
hAllowedRegion_AlphaVsE0_90Cut->Write();
hAllowedRegion_LumVsE0->Write();
hAllowedRegion_LumVsE0_90Cut->Write();
hAllowedRegion_LumVsAlpha->Write();
hAllowedRegion_LumVsAlpha_90Cut->Write();
fout->Close();
//delete
delete test_spectrum;
delete hAllowedRegion_AlphaVsE0;
delete hAllowedRegion_AlphaVsE0_90Cut;
delete hAllowedRegion_LumVsE0;
delete hAllowedRegion_LumVsE0_90Cut;
delete hAllowedRegion_LumVsAlpha;
delete hAllowedRegion_LumVsAlpha_90Cut;
delete g_Chi2VsAlpha;
delete g_Chi2VsE0;
delete g_Chi2VsLum;
//deallocate vectors
pnum = std::vector<Int_t>();
anue = std::vector<Double_t>();
bnue = std::vector<Double_t>();
cnue = std::vector<Double_t>();
anuebar = std::vector<Double_t>();
bnuebar = std::vector<Double_t>();
cnuebar = std::vector<Double_t>();
anux = std::vector<Double_t>();
bnux = std::vector<Double_t>();
cnux = std::vector<Double_t>();
chi2values = std::vector<Double_t>();
alphavals = std::vector<double>();
alphachi2 = std::vector<double>();
e0vals = std::vector<double>();
e0chi2 = std::vector<double>();
lumvals = std::vector<double>();
lumchi2 = std::vector<double>();
//add line to separate the terminal output(s)
std::cout << "--------------------------------" << std::endl;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// AsimovMethodSNDistance: Produces chi2-minimized flux parameter measurements
// and plots for a supernova located distanceSN +/-
// distanceUncertainty from Earth. The supernova is
// defined by a test spectrum with SNOwGLoBES smearing
// ts, nue-Ar40 cross section ts_xscn, and post-smearing
// efficiency model ts_effic. The detector assumptions
// are defined by a grid described by its parameter
// bounds (grid), SNOwGLoBES smearing (grid_smear),
// nue-Ar40 cross section model (grid_xscn), and
// efficiency model (grid_effic).
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void AsimovMethodSNDistance(Double_t distanceSN, Double_t distanceUncertainty, TString grid, TString grid_smear, TString grid_xscn, TString grid_effic, TString ts, TString ts_xscn, TString ts_effic){
std::cout << "Producing sensitivity plots for a " << distanceSN << " +/- " << distanceSN*distanceUncertainty << " kpc supernova and the following input parameters:" << std::endl;
std::cout << " Grid: " << grid << " with smearing " << grid_smear << ", xscn " << grid_xscn << ", and effic " << grid_effic << std::endl;
std::cout << " Test spectrum: " << ts << " with xscn " << ts_xscn << " and effic " << ts_effic << std::endl;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// DEFINE INPUTS
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
TString test_spect_filename = "input/test_spectra/pinched_test_smeared_sum_" + ts + "_" + ts_xscn + "_" + ts_effic + ".dat";
TString smeareddir = "input/" + grid + "/smear_" + grid_smear + "_" + grid_xscn + "_" + grid_effic;
TString pinchedinfo = "input/pinched_info/pinched_info_" + grid + ".dat";
TString gridinfo = "input/grid_info/grid_info_" + grid + ".dat";
//define output file
TString distanceStr; distanceStr.Form("%.2lf", distanceSN);
TString distanceUncertaintyStr; distanceUncertaintyStr.Form("%.2lf", distanceUncertainty);
TString outfile = "out/chi2plots_" + grid + "_smear" + grid_smear + "_" + grid_xscn + "_" + grid_effic + "_spectra" + ts + "_" + ts_xscn + "_" + ts_effic + "_" + distanceStr + "kpc_" + distanceUncertaintyStr + "uncertain.root";
Double_t alpha_true = 2.5;
Double_t e0_true = 9.5; //mev
Double_t lum_true = 5e52; //ergs
Double_t massfact = 1.0;//2.4; //see the full DUNE far detector response
Double_t chi2_90contour = 4.61; //pdg 2018
//use same style settings that Kate used
gStyle->SetOptStat(0);
gStyle->SetPalette(1,0);
//set random seed
gRandom->SetSeed(0);
//define tree for output file
Double_t tr_alpha;
Double_t tr_e0;
Double_t tr_lum;
Double_t tr_chi2;
Double_t tr_dof;
Double_t tr_numGridElementsAlphavsE0;
Double_t tr_numGridElementsLumvsE0;
Double_t tr_numGridElementsLumvsAlpha;
Double_t tr_numGoodGridElementsAlphavsE0;
Double_t tr_numGoodGridElementsLumvsE0;
Double_t tr_numGoodGridElementsLumvsAlpha;
TTree *tr = new TTree("data", "data");
tr->Branch("alpha", &tr_alpha, "alpha/D");
tr->Branch("e0", &tr_e0, "e0/D");
tr->Branch("lum", &tr_lum, "lum/D");
tr->Branch("chi2", &tr_chi2, "chi2/D");
tr->Branch("dof", &tr_dof, "dof/D");
tr->Branch("numgrid_alphavse0", &tr_numGridElementsAlphavsE0, "numgrid_alphavse0/D");
tr->Branch("numgrid_lumvse0", &tr_numGridElementsLumvsE0, "numgrid_lumvse0/D");
tr->Branch("numgrid_lumvsalpha", &tr_numGridElementsLumvsAlpha, "numgrid_lumvsalpha/D");
tr->Branch("numgood_alphavse0", &tr_numGoodGridElementsAlphavsE0, "numgood_alphavse0/D");
tr->Branch("numgood_lumvse0", &tr_numGoodGridElementsLumvsE0, "numgood_lumvse0/D");
tr->Branch("numgood_lumvsalpha", &tr_numGoodGridElementsLumvsAlpha, "numgood_lumvsalpha/D");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// DEFINE GRID BOUNDS
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//define the bounds of the grid
Double_t first_alpha;
Double_t last_alpha;
Double_t step_alpha;
Double_t first_e0;
Double_t last_e0;
Double_t step_e0;
Double_t factor = 1e53;
Double_t first_lum;
Double_t last_lum;
Double_t step_lum;
//open grid_info.dat
ifstream gin;
gin.open(gridinfo);
Int_t ig = 0;
while(1){
gin >> first_alpha >> last_alpha >> step_alpha >> first_e0 >> last_e0 >> step_e0 >> first_lum >> last_lum >> step_lum;
if(!gin.good()) break;
++ig;
}
gin.close();
Double_t minalpha = first_alpha - step_alpha/2.0;
Double_t maxalpha = last_alpha + step_alpha/2.0;
Double_t mine0 = first_e0 - step_e0/2.0;
Double_t maxe0 = last_e0 + step_e0/2.0;
Double_t minlum = first_lum - step_lum/2.0;
Double_t maxlum = last_lum + step_lum/2.0;
Double_t minalpha2 = first_alpha - step_alpha*2.0;
Double_t maxalpha2 = last_alpha + step_alpha*2.0;
Double_t mine02 = first_e0 - step_e0*2.0;
Double_t maxe02 = last_e0 + step_e0*2.0;
Double_t minlum2 = first_lum - step_lum*2.0;
Double_t maxlum2 = last_lum + step_lum*2.0;
Int_t numalphabins = int(last_alpha - first_alpha)/step_alpha+1;
Int_t nume0bins = int(last_e0 - first_e0)/step_e0+1;
Int_t numlumbins = (last_lum - first_lum)/(step_lum) + 1;
//Range of physical parameters
Double_t mingoodalpha = first_alpha;//1.0;
Double_t maxgoodalpha = last_alpha;//7.0;
Double_t mingoode0 = first_e0;//0.0;
Double_t maxgoode0 = last_e0;//20.;
std::cout << "The " << grid << " grid follows this definition:" << std::endl;
std::cout << " Alpha: [" << first_alpha << ", " << last_alpha << "] with " << step_alpha << " spacing" << std::endl;
std::cout << " E0: [" << first_e0 << ", " << last_e0 << "] with " << step_e0 << " spacing" << std::endl;
std::cout << " Luminosity: [" << first_lum << ", " << last_lum << "] with " << step_lum << " spacing" << std::endl;
std::cout << "The parameter-fitting algorithm will consider the following physical range for alpha and E0:" << std::endl;
std::cout << " Alpha: [" << mingoodalpha << ", " << maxgoodalpha << "]" << std::endl;
std::cout << " E0: [" << mingoode0 << ", " << maxgoode0 << "]" << std::endl;
//std::cout << numalphabins << " " << nume0bins << " " << numlumbins << std::endl;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// READ PINCHING PARAMETERS
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//open the pinched parameter file
ifstream pin;
pin.open(pinchedinfo);
//define arrays, iterators to keep the parameters
const Int_t maxflux = 350000;
std::vector<Int_t> pnum; pnum.resize(maxflux);
std::vector<Double_t> anue; anue.resize(maxflux);
std::vector<Double_t> bnue; bnue.resize(maxflux);
std::vector<Double_t> cnue; cnue.resize(maxflux);
std::vector<Double_t> anuebar; anuebar.resize(maxflux);
std::vector<Double_t> bnuebar; bnuebar.resize(maxflux);
std::vector<Double_t> cnuebar; cnuebar.resize(maxflux);
std::vector<Double_t> anux; anux.resize(maxflux);
std::vector<Double_t> bnux; bnux.resize(maxflux);
std::vector<Double_t> cnux; cnux.resize(maxflux);
std::cout << "Reading flux parameters: ";
Int_t ip = 0;
while(1){
pin >> pnum[ip] >> anue[ip] >> anuebar[ip] >> anux[ip] >> bnue[ip] >> bnuebar[ip] >> bnux[ip] >> cnue[ip] >> cnuebar[ip] >> cnux[ip];
if(!pin.good()) break;
++ip;
}
pin.close();
std::cout << "The " << grid << " grid contains " << ip << " fluxes." << std::endl;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// MAKE CHI2 MAP
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
TH1D* test_spectrum = fill_spect_hist(test_spect_filename,"test_spectrum",distanceSN, massfact);
//now we loop over templates in the grid
Int_t iFlux; //iterator over the grid
Int_t numfluxes = ip; //total number of fluxes we care about
const Int_t maxhist = maxflux;
Double_t chi2min = 100000000000.0;
Int_t dofbest;
Int_t ifbest;
Double_t chi2;
Int_t dof;
//keep values of chi2 for each flux
std::vector<Double_t> chi2values; chi2values.resize(maxhist);
//test
std::vector<Double_t> chi2values_tmp; std::vector<Int_t> iflux_tmp;
for(iFlux = 0; iFlux < numfluxes; ++iFlux){
// Do not go outside the limits
if(anue[iFlux] <= maxgoodalpha && bnue[iFlux] <= maxgoode0 && anue[iFlux] >= mingoodalpha && bnue[iFlux] >= mingoode0 ){
//define filename
TString pargridfilename = smeareddir+"/pinched_"+TString::Format("%d",iFlux)+"_smeared_sum.dat";
TString histname = "pinched_"+grid + "_" + grid_smear + "_" + grid_xscn + "_" + grid_effic + "_" + ts + "_" + ts_xscn + "_" + ts_effic + "_" + distanceStr + "kpc_" + distanceUncertaintyStr + "uncertain_"+TString::Format("%d",iFlux);
TH1D *pargridhist = fill_spect_hist(pargridfilename, histname, distanceSN, massfact);
mychi2_distuncertainty(test_spectrum,pargridhist,distanceSN*distanceUncertainty,&chi2,&dof);
// chi2 here is not per dof
// chi2 /= dof;
//save value
chi2values[iFlux] = chi2/dof;
//cout << "Chi2 "<< iFlux<<" "<< chi2<<" "<<dof<<endl;
if (chi2<chi2min) {
chi2min = chi2;
dofbest = dof;
ifbest = iFlux;
}
chi2values_tmp.emplace_back(chi2);
iflux_tmp.emplace_back(iFlux);
}
}
std::cout << "Best-fit measurement: (" << anue[ifbest] << ", " << bnue[ifbest] << ", " << cnue[ifbest] << ") with reduced chi2 = " << chi2min/dofbest << std::endl;
int index = std::distance(chi2values_tmp.begin(), std::min_element(chi2values_tmp.begin(), chi2values_tmp.end()) );
//std::cout << "Lowest chi2 = " << chi2values_tmp[index] << " " << iflux_tmp[index] << ": (" << anue[iflux_tmp[index]] << ", " << bnue[iflux_tmp[index]] << ", " << cnue[iflux_tmp[index]] << ")" << std::endl;
//now I want to make plots of chi2 vs parameter for the other two parameters
//at their fixed truth values!
std::vector<double> alphachi2;
std::vector<double> alphavals;
TString titlealpha("Minimum reduced #chi^{2} vs. #alpha;#alpha;Reduced #chi^{2}");
TString namealpha("Chi2VsAlpha");
std::vector<double> e0chi2;
std::vector<double> e0vals;
TString titlee0("Minimum reduced #chi^{2} vs. #LT E_{#nu} #GT;#LT E_{#nu} #GT (MeV);Reduced #chi^{2}");
TString namee0("Chi2VsE0");
std::vector<double> lumchi2;
std::vector<double> lumvals;
TString titlelum("Minimum reduced #chi^{2} vs. #varepsilon;#varepsilon (10^{53} erg);Reduced #chi^{2}");
TString namelum("Chi2VsLum");
//we also want to keep the alpha, e0, lum values corresponding to "good" chi2 values
TH2D *hAllowedRegion_AlphaVsE0 = new TH2D("alphavse0", ";#LT E_{#nu} #GT (MeV);#alpha", nume0bins, mine0, maxe0, numalphabins, minalpha, maxalpha );
TH2D *hAllowedRegion_LumVsE0 = new TH2D("lumvse0", ";#LT E_{#nu} #GT (MeV);#varepsilon (10^{53} erg)", nume0bins, mine0, maxe0, numlumbins, minlum/factor, maxlum/factor );
TH2D *hAllowedRegion_LumVsAlpha = new TH2D("lumvsalpha", ";#alpha;#varepsilon (10^{53} erg)", numalphabins, minalpha, maxalpha, numlumbins, minlum/factor, maxlum/factor );
TH2D *hAllowedRegion_AlphaVsE0_90Cut = new TH2D("alphavse0_90cut", ";#LT E_{#nu} #GT (MeV);#alpha", nume0bins, mine0, maxe0, numalphabins, minalpha, maxalpha );
TH2D *hAllowedRegion_LumVsE0_90Cut = new TH2D("lumvse0_90cut", ";#LT E_{#nu} #GT (MeV);#varepsilon (10^{53} erg)", nume0bins, mine0, maxe0, numlumbins, minlum/factor, maxlum/factor );
TH2D *hAllowedRegion_LumVsAlpha_90Cut = new TH2D("lumvsalpha_90cut", ";#alpha;#varepsilon (10^{53} erg)", numalphabins, minalpha, maxalpha, numlumbins, minlum/factor, maxlum/factor );
//set to zero
tr_numGoodGridElementsAlphavsE0 = 0;
tr_numGoodGridElementsLumvsE0 = 0;
tr_numGoodGridElementsLumvsAlpha = 0;
for(Double_t iAlpha = first_alpha; iAlpha <= last_alpha+step_alpha; iAlpha += step_alpha){
//iAlpha tells us the alpha value we care about
std::vector<double> chi2vals;
for(iFlux = 0; iFlux < numfluxes; ++iFlux){
//check to make sure we're at the right alpha value, and that alpha/E0 are physical
Int_t diff = ( anue[iFlux] - iAlpha )*100.0;
if(diff == 0.0 && anue[iFlux] <= maxgoodalpha && bnue[iFlux] <= maxgoode0 && anue[iFlux] >= mingoodalpha && bnue[iFlux] >= mingoode0){
chi2vals.emplace_back(chi2values[iFlux]);
}
}
//std::cout << iAlpha << " " << chi2vals.size() << std::endl;
//now we find the minimum chi2 from these values
if(chi2vals.size() > 0){
size_t iSmallest = std::distance(chi2vals.begin(), std::min_element( chi2vals.begin(), chi2vals.end() ));
alphavals.emplace_back( iAlpha );
alphachi2.emplace_back( chi2vals[iSmallest] );
//std::cout << iAlpha << " " << chi2vals[iSmallest] << std::endl;
}
//2D plot
for(Double_t iE0 = first_e0; iE0 <= last_e0; iE0 += step_e0){
std::vector<double> chi2vals2d;
for(iFlux = 0; iFlux < numfluxes; ++iFlux){
//check to make sure we're at the right alpha value, and that alpha/E0 are physical
Int_t diffalpha = ( anue[iFlux] - iAlpha )*100.0;
Int_t diffe0 = ( bnue[iFlux] - iE0 )*100.0;
if(diffalpha == 0.0 && diffe0 == 0.0 && anue[iFlux] <= maxgoodalpha && bnue[iFlux] <= maxgoode0 && anue[iFlux] >= mingoodalpha && bnue[iFlux] >= mingoode0){
chi2vals2d.emplace_back(chi2values[iFlux]);
}
}
//std::cout << iAlpha << " " << iE0 << " " << chi2vals2d.size() << std::endl;
if(chi2vals2d.size() > 0){
size_t iSmallest = std::distance(chi2vals2d.begin(), std::min_element( chi2vals2d.begin(), chi2vals2d.end() ));
//std::cout << iAlpha << " " << iE0 << " " << chi2vals2d[iSmallest] << std::endl;
Double_t toFill = chi2vals2d[iSmallest];
if(toFill == 0.0) toFill = 1e-20;
if(toFill <= chi2_90contour){
++tr_numGoodGridElementsAlphavsE0;
hAllowedRegion_AlphaVsE0_90Cut->Fill(iE0, iAlpha, toFill);
}
hAllowedRegion_AlphaVsE0->Fill(iE0, iAlpha, toFill);
}
chi2vals2d = std::vector<double>();
}
//2D plot:
for(Double_t iLum = first_lum; iLum <= last_lum+step_lum; iLum += step_lum){
std::vector<double> chi2vals2d;
for(iFlux = 0; iFlux < numfluxes; ++iFlux){
//check to make sure we're at the right alpha value, and that alpha/E0 are physical
Int_t diffalpha = ( anue[iFlux] - iAlpha )*100.0;
Int_t difflum = ( cnue[iFlux]/factor - iLum/factor )*100.0;
if(diffalpha == 0.0 && difflum == 0.0 && anue[iFlux] <= maxgoodalpha && bnue[iFlux] <= maxgoode0 && anue[iFlux] >= mingoodalpha && bnue[iFlux] >= mingoode0){
chi2vals2d.emplace_back(chi2values[iFlux]);
}
}
if(chi2vals2d.size() > 0){
size_t iSmallest = std::distance(chi2vals2d.begin(), std::min_element( chi2vals2d.begin(), chi2vals2d.end() ));
Double_t toFill = chi2vals2d[iSmallest];
if(toFill == 0.0) toFill = 1e-20;
if(toFill <= chi2_90contour){
++tr_numGoodGridElementsLumvsAlpha;
hAllowedRegion_LumVsAlpha_90Cut->Fill(iAlpha, iLum/factor, toFill);
}
hAllowedRegion_LumVsAlpha->Fill(iAlpha, iLum/factor, toFill);
}
chi2vals2d = std::vector<double>();
}
chi2vals = std::vector<double>();
}
for(Double_t iE0 = first_e0; iE0 <= last_e0; iE0 += step_e0){
//iE0 tells us the E0 value we care about
std::vector<double> chi2vals;
for(iFlux = 0; iFlux < numfluxes; ++iFlux){
//check to make sure we're at the right alpha value, and that alpha/E0 are physical
Int_t diffe0 = ( bnue[iFlux] - iE0 )*100.0;
if(diffe0 == 0.0 && anue[iFlux] <= maxgoodalpha && bnue[iFlux] <= maxgoode0 && anue[iFlux] >= mingoodalpha && bnue[iFlux] >= mingoode0){
chi2vals.emplace_back(chi2values[iFlux]);
}
}
//now we find the minimum chi2 from these values
if(chi2vals.size() > 0){
size_t iSmallest = std::distance(chi2vals.begin(), std::min_element( chi2vals.begin(), chi2vals.end() ));
e0vals.emplace_back( iE0 );
e0chi2.emplace_back( chi2vals[iSmallest] );
//std::cout << iE0 << " " << chi2vals[iSmallest] << std::endl;
}
//2D plot
for(Double_t iLum = first_lum; iLum <= last_lum+step_lum; iLum += step_lum){
std::vector<double> chi2vals2d;
for(iFlux = 0; iFlux < numfluxes; ++iFlux){
//check to make sure we're at the right e0 value, and that alpha/E0 are physical
Int_t diffe0 = ( bnue[iFlux] - iE0 )*100.0;
Int_t difflum = ( cnue[iFlux]/factor - iLum/factor )*100.0;
if(diffe0 == 0.0 && difflum == 0.0 && anue[iFlux] <= maxgoodalpha && bnue[iFlux] <= maxgoode0 && anue[iFlux] >= mingoodalpha && bnue[iFlux] >= mingoode0){
chi2vals2d.emplace_back(chi2values[iFlux]);
}
}
if(chi2vals2d.size() > 0){
size_t iSmallest = std::distance(chi2vals2d.begin(), std::min_element( chi2vals2d.begin(), chi2vals2d.end() ));
//std::cout << iE0 << " " << iLum << " " << chi2vals2d[iSmallest] << std::endl;
Double_t toFill = chi2vals2d[iSmallest];
if(toFill == 0.0) toFill = 1e-20;
if(toFill <= chi2_90contour){
++tr_numGoodGridElementsLumvsE0;
hAllowedRegion_LumVsE0_90Cut->Fill(iE0, iLum/factor, toFill);
}
hAllowedRegion_LumVsE0->Fill(iE0, iLum/factor, toFill);
}
chi2vals2d = std::vector<double>();
}
chi2vals = std::vector<double>();
}
for(Double_t iLum = first_lum; iLum <= last_lum+step_lum; iLum += step_lum){
//iLum tells us the luminosity value we care about
std::vector<double> chi2vals;
for(iFlux = 0; iFlux < numfluxes; ++iFlux){
//check to make sure we're at the right lum value, and that alpha/E0 are physical
Int_t difflum = ( cnue[iFlux]/factor - iLum/factor )*100.0;
//if(cnue[iFlux] == iLum){
if(difflum == 0.0){
if(anue[iFlux] <= maxgoodalpha && bnue[iFlux] <= maxgoode0 && anue[iFlux] >= mingoodalpha && bnue[iFlux] >= mingoode0) chi2vals.emplace_back(chi2values[iFlux]);
}
}
//now we find the minimum chi2 from these values
if(chi2vals.size() > 0){
size_t iSmallest = std::distance(chi2vals.begin(), std::min_element( chi2vals.begin(), chi2vals.end() ));
lumvals.emplace_back( iLum/factor );
lumchi2.emplace_back( chi2vals[iSmallest] );
//std::cout << iLum << " " << chi2vals[iSmallest] << std::endl;
}
chi2vals = std::vector<double>();
}
TGraph *g_Chi2VsAlpha = makeTGraphFromVectors(alphavals, alphachi2, titlealpha);
TGraph *g_Chi2VsE0 = makeTGraphFromVectors(e0vals, e0chi2, titlee0);
TGraph *g_Chi2VsLum = makeTGraphFromVectors(lumvals, lumchi2, titlelum);
hAllowedRegion_AlphaVsE0->GetXaxis()->CenterTitle();
hAllowedRegion_AlphaVsE0->GetXaxis()->SetTitleSize(0.05);
hAllowedRegion_AlphaVsE0->GetYaxis()->CenterTitle();
hAllowedRegion_AlphaVsE0->GetYaxis()->SetTitleSize(0.05);
hAllowedRegion_LumVsE0->GetXaxis()->CenterTitle();
hAllowedRegion_LumVsE0->GetXaxis()->SetTitleSize(0.04);
hAllowedRegion_LumVsE0->GetYaxis()->CenterTitle();
hAllowedRegion_LumVsE0->GetYaxis()->SetTitleSize(0.04);
hAllowedRegion_LumVsAlpha->GetXaxis()->CenterTitle();
hAllowedRegion_LumVsAlpha->GetXaxis()->SetTitleSize(0.05);
hAllowedRegion_LumVsAlpha->GetYaxis()->CenterTitle();
hAllowedRegion_LumVsAlpha->GetYaxis()->SetTitleSize(0.05);
//change boundaries
hAllowedRegion_AlphaVsE0->GetXaxis()->SetRangeUser(mine02, maxe02);
hAllowedRegion_AlphaVsE0->GetYaxis()->SetRangeUser(minalpha2, maxalpha2);
hAllowedRegion_LumVsE0->GetXaxis()->SetRangeUser(mine02, maxe02);
hAllowedRegion_LumVsE0->GetYaxis()->SetRangeUser(minlum2/factor, maxlum2/factor);
hAllowedRegion_LumVsAlpha->GetXaxis()->SetRangeUser(minalpha2, maxalpha2);
hAllowedRegion_LumVsAlpha->GetYaxis()->SetRangeUser(minlum2/factor, maxlum2/factor);
hAllowedRegion_AlphaVsE0_90Cut->GetXaxis()->SetRangeUser(mine02, maxe02);
hAllowedRegion_AlphaVsE0_90Cut->GetYaxis()->SetRangeUser(minalpha2, maxalpha2);
hAllowedRegion_LumVsE0_90Cut->GetXaxis()->SetRangeUser(mine02, maxe02);
hAllowedRegion_LumVsE0_90Cut->GetYaxis()->SetRangeUser(minlum2/factor, maxlum2/factor);
hAllowedRegion_LumVsAlpha_90Cut->GetXaxis()->SetRangeUser(minalpha2, maxalpha2);
hAllowedRegion_LumVsAlpha_90Cut->GetYaxis()->SetRangeUser(minlum2/factor, maxlum2/factor);
//limit 1D plots to ~5 sigma
//if(g_Chi2VsAlpha->GetYaxis()->GetXmax() > 25.0) g_Chi2VsAlpha->SetMaximum(25.0);
//if(g_Chi2VsE0->GetYaxis()->GetXmax() > 25.0) g_Chi2VsE0->SetMaximum(25.0);
//if(g_Chi2VsLum->GetYaxis()->GetXmax() > 25.0) g_Chi2VsLum->SetMaximum(25.0);
//set names
g_Chi2VsAlpha->SetName(namealpha);
g_Chi2VsE0->SetName(namee0);
g_Chi2VsLum->SetName(namelum);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// SAVE PLOTS
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//fill tree here
tr_alpha = anue[ifbest];
tr_e0 = bnue[ifbest];
tr_lum = cnue[ifbest]/factor;
tr_chi2 = chi2min;
tr_dof = dofbest;
tr_numGridElementsAlphavsE0 = numalphabins*nume0bins;
tr_numGridElementsLumvsE0 = numlumbins*nume0bins;
tr_numGridElementsLumvsAlpha = numalphabins*numlumbins;
tr->Fill();
TFile *fout = new TFile(outfile, "recreate");
tr->Write();
g_Chi2VsAlpha->Write();
g_Chi2VsE0->Write();
g_Chi2VsLum->Write();
hAllowedRegion_AlphaVsE0->Write();
hAllowedRegion_AlphaVsE0_90Cut->Write();
hAllowedRegion_LumVsE0->Write();
hAllowedRegion_LumVsE0_90Cut->Write();
hAllowedRegion_LumVsAlpha->Write();
hAllowedRegion_LumVsAlpha_90Cut->Write();
fout->Close();
//delete
delete test_spectrum;
delete hAllowedRegion_AlphaVsE0;
delete hAllowedRegion_AlphaVsE0_90Cut;
delete hAllowedRegion_LumVsE0;
delete hAllowedRegion_LumVsE0_90Cut;
delete hAllowedRegion_LumVsAlpha;
delete hAllowedRegion_LumVsAlpha_90Cut;
delete g_Chi2VsAlpha;
delete g_Chi2VsE0;
delete g_Chi2VsLum;
//deallocate vectors
pnum = std::vector<Int_t>();
anue = std::vector<Double_t>();
bnue = std::vector<Double_t>();
cnue = std::vector<Double_t>();
anuebar = std::vector<Double_t>();
bnuebar = std::vector<Double_t>();
cnuebar = std::vector<Double_t>();
anux = std::vector<Double_t>();
bnux = std::vector<Double_t>();
cnux = std::vector<Double_t>();
chi2values = std::vector<Double_t>();
alphavals = std::vector<double>();
alphachi2 = std::vector<double>();
e0vals = std::vector<double>();
e0chi2 = std::vector<double>();
lumvals = std::vector<double>();
lumchi2 = std::vector<double>();
//add line to separate the terminal output(s)
std::cout << "--------------------------------" << std::endl;
}//end function
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// SaveBestFitElement: Produces chi2-minimized flux parameter measurements and
// plots for a supernova located distanceSN from Earth.
// Saves test spectrum and best-fit plot in a file.
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void SaveBestFitElement(Double_t distanceSN, TString grid, TString grid_smear, TString grid_xscn, TString grid_effic, TString ts_smear, TString ts_xscn, TString ts_effic){
//grid element we care about
Double_t true_alpha = 2.5;
Double_t true_e0 = 9.5;
Double_t true_lum = 0.5;
std::cout << "Producing best-fit plot for a " << distanceSN << "kpc supernova and the following input parameters:" << std::endl;
std::cout << " Grid: " << grid << " with smearing " << grid_smear << ", xscn " << grid_xscn << ", and effic " << grid_effic << std::endl;
std::cout << " Test spectrum: " << ts_smear << ", xscn " << ts_xscn << " and effic " << ts_effic << std::endl;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// DEFINE INPUTS
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//define string to hold grid parameters
TString grid_pars = "smear_" + grid_smear + "_" + grid_xscn + "_" + grid_effic;
TString ts_pars = ts_smear + "_" + ts_xscn + "_" + ts_effic;
TString test_spect_filename = "input/test_spectra/pinched_test_smeared_sum_" + ts_pars + ".dat";
TString smeareddir = "input/" + grid + "/" + grid_pars;
TString pinchedinfo = "input/pinched_info/pinched_info_" + grid + ".dat";
TString gridinfo = "input/grid_info/grid_info_" + grid + ".dat";
//define output file
TString distanceStr; distanceStr.Form("%.2lf", distanceSN);
//output file name
TString outfilename = "asimov_bestfit_" + grid_pars + "_" + ts_pars + ".root";
Double_t massfact = 1.0;//2.4; //see the full DUNE far detector response
Double_t chi2_90contour = 4.61; //pdg 2018
//use same style settings that Kate used
gStyle->SetOptStat(0);
gStyle->SetPalette(1,0);
//set random seed
gRandom->SetSeed(0);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// DEFINE GRID BOUNDS
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//define the bounds of the grid
Double_t first_alpha;
Double_t last_alpha;
Double_t step_alpha;
Double_t first_e0;
Double_t last_e0;
Double_t step_e0;
Double_t factor = 1e53;
Double_t first_lum;
Double_t last_lum;
Double_t step_lum;
//open grid_info.dat
ifstream gin;
gin.open(gridinfo);
Int_t ig = 0;
while(1){
gin >> first_alpha >> last_alpha >> step_alpha >> first_e0 >> last_e0 >> step_e0 >> first_lum >> last_lum >> step_lum;
if(!gin.good()) break;
++ig;
}
gin.close();
Double_t minalpha = first_alpha - step_alpha/2.0;
Double_t maxalpha = last_alpha + step_alpha/2.0;
Double_t mine0 = first_e0 - step_e0/2.0;
Double_t maxe0 = last_e0 + step_e0/2.0;
Double_t minlum = first_lum - step_lum/2.0;
Double_t maxlum = last_lum + step_lum/2.0;
Double_t minalpha2 = first_alpha - step_alpha*2.0;
Double_t maxalpha2 = last_alpha + step_alpha*2.0;
Double_t mine02 = first_e0 - step_e0*2.0;
Double_t maxe02 = last_e0 + step_e0*2.0;
Double_t minlum2 = first_lum - step_lum*2.0;
Double_t maxlum2 = last_lum + step_lum*2.0;
Int_t numalphabins = int(last_alpha - first_alpha)/step_alpha+1;
Int_t nume0bins = int(last_e0 - first_e0)/step_e0+1;
Int_t numlumbins = (last_lum - first_lum)/(step_lum) + 1;
//Range of physical parameters
Double_t mingoodalpha = first_alpha;//1.0;
Double_t maxgoodalpha = last_alpha;//7.0;
Double_t mingoode0 = first_e0;//0.0;
Double_t maxgoode0 = last_e0;//20.;
std::cout << "The " << grid << " grid follows this definition:" << std::endl;
std::cout << " Alpha: [" << first_alpha << ", " << last_alpha << "] with " << step_alpha << " spacing" << std::endl;
std::cout << " E0: [" << first_e0 << ", " << last_e0 << "] with " << step_e0 << " spacing" << std::endl;
std::cout << " Luminosity: [" << first_lum << ", " << last_lum << "] with " << step_lum << " spacing" << std::endl;
std::cout << "The parameter-fitting algorithm will consider the following physical range for alpha and E0:" << std::endl;
std::cout << " Alpha: [" << mingoodalpha << ", " << maxgoodalpha << "]" << std::endl;
std::cout << " E0: [" << mingoode0 << ", " << maxgoode0 << "]" << std::endl;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// READ PINCHING PARAMETERS
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//open the pinched parameter file
ifstream pin;
pin.open(pinchedinfo);
//define arrays, iterators to keep the parameters
const Int_t maxflux = 350000;
std::vector<Int_t> pnum; pnum.resize(maxflux);
std::vector<Double_t> anue; anue.resize(maxflux);
std::vector<Double_t> bnue; bnue.resize(maxflux);
std::vector<Double_t> cnue; cnue.resize(maxflux);
std::vector<Double_t> anuebar; anuebar.resize(maxflux);
std::vector<Double_t> bnuebar; bnuebar.resize(maxflux);
std::vector<Double_t> cnuebar; cnuebar.resize(maxflux);
std::vector<Double_t> anux; anux.resize(maxflux);
std::vector<Double_t> bnux; bnux.resize(maxflux);
std::vector<Double_t> cnux; cnux.resize(maxflux);
std::cout << "Reading flux parameters: " << std::endl;
Int_t ip = 0;
while(1){
//Int_t p1;
//Double_t a1, a2, a3, b1, b2, b3, c1, c2, c3;
//pin >> p1 >> a1 >> a2 >> a3 >> b1 >> b2 >> b3 >> c1 >> c2 >> c3;
pin >> pnum[ip] >> anue[ip] >> anuebar[ip] >> anux[ip] >> bnue[ip] >> bnuebar[ip] >> bnux[ip] >> cnue[ip] >> cnuebar[ip] >> cnux[ip];
if(!pin.good()) break;
//std::cout << pnum[ip]<<" "<<anue[ip]<<" "<<anuebar[ip]<<" "<<anux[ip]<<" "<<bnue[ip]<<" "<<bnuebar[ip]<<" "<<bnux[ip]<<" "<<cnue[ip]<<" "<<cnuebar[ip]<<" "<<cnux[ip]<<std::endl;
++ip;
}
pin.close();
std::cout << "This grid contains " << ip << " fluxes." << std::endl;
std::vector<TH1D*> histos;
TH1D* test_spectrum = fill_spect_hist(test_spect_filename,"test_spectrum",distanceSN, massfact);
//TString tslabel = "Test Spectrum: (" + TString::Format("%.1lf", true_alpha) + ", " + TString::Format("%.1lf", true_e0) + ", " + TString::Format("%.2lf", true_lum) + "e53)";
histos.emplace_back(test_spectrum);
//now we loop over templates in the grid
Int_t iFlux; //iterator over the grid
Int_t numfluxes = ip; //total number of fluxes we care about
const Int_t maxhist = maxflux;
Double_t chi2min = 100000000000.0;
Int_t dofbest;
Int_t ifbest;
Double_t chi2;
Int_t dof;
for(iFlux = 0; iFlux < numfluxes; ++iFlux){
// Do not go outside the limits
if(anue[iFlux] <= maxgoodalpha && bnue[iFlux] <= maxgoode0 && anue[iFlux] >= mingoodalpha && bnue[iFlux] >= mingoode0 ){
//define filename
TString pargridfilename = smeareddir+"/pinched_"+TString::Format("%d",iFlux)+"_smeared_sum.dat";
TString histname = "pinched_"+grid + "_" + grid_smear + "_" + grid_xscn + "_" + grid_effic + "_" + ts_smear + "_" + ts_xscn + "_" + ts_effic + "_" + distanceStr + "kpc_"+TString::Format("%d",iFlux);
TH1D *pargridhist = fill_spect_hist(pargridfilename, histname, distanceSN, massfact);
mychi2(test_spectrum,pargridhist,&chi2,&dof);
if (chi2<chi2min) {
chi2min = chi2;
dofbest = dof;
ifbest = iFlux;
}
}
}
std::cout << "Best-fit measurement: (" << anue[ifbest] << ", " << bnue[ifbest] << ", " << cnue[ifbest] << ") with reduced chi2 = " << chi2min/dofbest << std::endl;
TString bffilename = smeareddir+"/pinched_"+TString::Format("%d",ifbest)+"_smeared_sum.dat";
TString bfname = "best_fit_" + TString::Format("%.1lf", anue[ifbest]) + "_" + TString::Format("%.1lf", bnue[ifbest]) + "_" + TString::Format("%.2lf", cnue[ifbest]/factor) + "e53";
TH1D *bfhist = fill_spect_hist(bffilename, bfname, distanceSN, massfact);
histos.emplace_back(bfhist);
//save in ROOT file
TFile *fout = new TFile(outfilename, "recreate");
for(size_t i = 0; i < histos.size(); ++i) histos[i]->Write();
fout->Close();
//delete
delete test_spectrum;
delete bfhist;
//deallocate vectors
pnum = std::vector<Int_t>();
anue = std::vector<Double_t>();
bnue = std::vector<Double_t>();
cnue = std::vector<Double_t>();
anuebar = std::vector<Double_t>();
bnuebar = std::vector<Double_t>();
cnuebar = std::vector<Double_t>();
anux = std::vector<Double_t>();
bnux = std::vector<Double_t>();
cnux = std::vector<Double_t>();
//add line to separate the terminal output(s)
std::cout << "--------------------------------" << std::endl;
}
#endif /* Asimov_h */
| true |
c401af0191d89acfc58b37043be804992c054977 | C++ | nealjmc/OldSchoolWork | /Files/Assignment1-Comp1100-master/assignment1CarModel.cpp | UTF-8 | 1,905 | 3.5625 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <iomanip>
using namespace std;
//Neal McAneney
/*
Start Date 09/29/17
End Date 09/29/17
Assignment 1
Write a program that analyzes a car’s fuel usage. The program asks the user to input the type of car (i.e. model), the
number of litres of gas in the tank, and the fuel efficiency in kilometres per litre.
Print the output similar to the following: (where the X’s represent string data and 9’s represent numeric data).
Model: XXXXXXXXXXXXXXXXXXXXXXXX
Litres per tank Kms per litre Price per litre Cost per tank Distance per tank
999 999 999.99 999.99 9999
*/
int main()
{
//Declaring variables
string carModel;
double litresPerTank, fuelEfficiency, travelDistance, costPerTank;
const double pricePerLitre = 109.9;
//This is the price of gas as of: 09/29/17 - 10:51Am @ 1120 Sydenham Rd near Hwy 401 Exit 613.
//Resource: http://www.ontariogasprices.com/Kingston/index.aspx
//Input
cout << "Enter you car model: ";
getline(cin, carModel);
cout << endl;
cout << "Enter litres per tank: ";
cin >> litresPerTank;
cout << endl;
cout << "Enter fuel efficiency(litre/100km): ";
cin >> fuelEfficiency;
cout << endl;
//process
costPerTank = (litresPerTank * pricePerLitre) / 100;
travelDistance =(litresPerTank * 100)/ fuelEfficiency;
//output
system("cls");
cout << "Model: " << carModel << endl << endl;
cout << right << setw(11) << "Litres/Tank" << setw(13) << "Litre/100km" << setw(14) << "Price/Litre" << setw(12) << "Cost/Tank" << setw(20) << "Distance/tank(km)" << endl;
cout << right << setprecision(4) << setw(11) << litresPerTank << setw(13) << fuelEfficiency << setw(14) << pricePerLitre << setw(12) << costPerTank << setw(20) << travelDistance << endl << endl;
cout << "Program Ended Successfully " << endl;
system("pause");
}
| true |
d528492839ca4eb8beb9f4f86a82bc4b5c285ecf | C++ | iRobot42/Deitels-Cpp-10e | /05 - Control Statements Part II. Logical Operators/05.30 - DollarAmount Constructor with Two Parameters/DollarAmount.h | UTF-8 | 978 | 3.484375 | 3 | [] | no_license | // Exercise 5.30: DollarAmount.h
#include <cmath>
#include <string>
class DollarAmount {
public:
explicit DollarAmount( int64_t dollars, int64_t cents ) {
amount = dollars * 100 + ( cents >= 0 && cents < 100 ? cents
: throw ( "Incorrect number of cents" ) );
}
void add( DollarAmount right ) {
amount += right.amount;
}
void subtract( DollarAmount right ) {
amount -= right.amount;
}
void addInterest( int rate, int divisor ) {
int64_t iAmount{ ( amount * rate + divisor / 2 ) / divisor };
DollarAmount interest{ iAmount / 100, iAmount % 100 };
add( interest );
}
std::string toString() const {
std::string dollars{ std::to_string( amount / 100 ) };
std::string cents{ std::to_string( std::abs( amount % 100 ) ) };
return dollars + "." + ( cents.size() == 1 ? "0" : "" ) + cents;
}
private:
int64_t amount{};
}; | true |
22494fc9d9cae23769ced2b2f6cb3ee3be44a0cd | C++ | mfirmin/c5sc | /src/envAction.cpp | UTF-8 | 924 | 2.515625 | 3 | [
"MIT"
] | permissive |
#include "envAction.h"
#include "environment.h"
#include "object.h"
#include "entity.h"
void toggleVisible(std::string s)
{
Entity* ent = (env->getEntities().find(s)->second);
ent->setVisible(!(ent->isVisible()));
for (std::vector<Object*>::iterator iter = ent->getBodies().begin(); iter != ent->getBodies().end(); iter++)
{
(*iter)->setVisible(ent->isVisible());
}
}
void toggleCollidable(std::string s)
{
Entity* ent = (env->getEntities().find(s)->second);
ent->setCollidable(!(ent->isCollidable()));
for (std::vector<Object*>::iterator iter = ent->getBodies().begin(); iter != ent->getBodies().end(); iter++)
{
(*iter)->setCollidable(ent->isCollidable());
}
}
void EnvAction::performAction()
{
if (!done)
{
for (auto it = actions.begin(); it != actions.end(); it++)
{
(*it)();
}
done = true;
}
}
| true |
84f72cc85c4437201417a8d49d3e346ae6d942c3 | C++ | seidlman1029/AdventOfCode2019 | /Day1.h | UTF-8 | 625 | 3.203125 | 3 | [] | no_license | #pragma once
#include <iostream>
#include "Util.h"
namespace AOC {
void Part1()
{
const auto masses = ReadLines("Inputs/day1pt1.txt");
int fuel = 0;
for (const int& mass : masses)
fuel += (mass / 3) - 2;
std::cout << fuel << std::endl;
}
void Part2()
{
const auto masses = ReadLines("Inputs/day1pt1.txt");
int total_fuel = 0;
for (const int& mass : masses) {
int module_fuel = (mass / 3) - 2;
int fuel_fuel = (module_fuel / 3) - 2;
while (fuel_fuel > 0) {
module_fuel += fuel_fuel;
fuel_fuel = (fuel_fuel / 3) - 2;
}
total_fuel += module_fuel;
}
std::cout << total_fuel << std::endl;
}
}
| true |
5ad040e8460b0ca672ca67f2d368f258f92bfcb7 | C++ | TyrantDA/2DGraphics | /Enemy.cpp | UTF-8 | 929 | 2.703125 | 3 | [] | no_license | #include "Enemy.h"
#include "Engine.h"
Enemy::Enemy(float x, float y, float h, float w, float distance)
{
xpos = x;
ypos = y;
height = h;
width = w;
originX = x;
originY = y;
moveDistance = distance;
speed = 500;
textureFix();
}
bool Enemy::drop()
{
if (ypos < 1000)
{
ypos = originY;
xpos -= speed * detalTime;
return true;
}
return false;
}
bool Enemy::collide()
{
for (Actor* a : colList) {
if (isCol(a))
{
return true;
}
}
return false;
}
void Enemy::update()
{
xpos -= speed * detalTime;
moveSoFar -= speed;
if (abs(moveSoFar) > moveDistance)
speed = -speed;
if (grounded)
{
if (ypos != originY)
{
speed = -speed;
ypos = ypos + 20;
grounded = false;
}
}
if (!collide())
{
ypos -= 100 * detalTime;
}
else if (collide())
{
originY = ypos;
grounded = true;
}
}
float Enemy::getSpeed() {
return speed;
}
Enemy::~Enemy()
{
}
| true |
1f65b61daaad605b87b19fab4eb06a984ced3afd | C++ | WooLyung/Blue | /Input.h | UHC | 869 | 2.5625 | 3 | [] | no_license | #pragma once
#include"Math.h"
#include"KeyCode.h"
//TODO: rawinput
#define KEY_MAXCOUNT 256
class Input
{
private:
LPDIRECTINPUT8A directInput_;
LPDIRECTINPUTDEVICE8A keyboard_;
LPDIRECTINPUTDEVICE8A mouse_;
BYTE keyStateL_[KEY_MAXCOUNT];
BYTE keyStateR_[KEY_MAXCOUNT];
DIMOUSESTATE mouseState_;
BYTE rgbButtonsL_[4];
public:
Input();
~Input();
void Update(void);
KeyState GetKeyState(KeyCode key);
#define DIK_MOUSELBUTTON 0 // Ŭ
#define DIK_MOUSERBUTTON 1 // Ŭ
#define DIK_MOUSEMBUTTON 2 // Ŭ
#define DIK_MOUSEXBUTTON 3 // ȮưŬ
KeyState GetMouseState(MouseCode key);
Point2F GetMousePos() const;
long GetMouseDeltaX(void) const;
long GetMouseDeltaY(void) const;
// ( < 0) (-120, -240, -360 ...), ø( > 0) (120, 240, 360 ...)
int GetMouseWheel(void) const;
};
| true |
499e9e81dad3ac9878df0ee445a6f86301138b64 | C++ | cr7as7/coding1 | /matrixexponentiation.cpp | UTF-8 | 664 | 2.75 | 3 | [] | no_license | void mult(vector<vector<int>> &p,vector<vector<int>> &q,int m)
{vector<vector<int>> c(3,vector<int> (3,0));
int a11,a12,a13,a21,a22,a23,a31,a32,a33;
int i,j,k,sum;
for (i = 0; i <= 2; i++) {
for (j = 0; j <= 2; j++) {
sum = 0;
for (k = 0; k <= 2; k++) {
sum = (sum+(p[i][k] * q[k][j])%m)%m;
}
c[i][j] = sum;
}
}
p=c;
}
void power(vector<vector<int>> &p,int n,int a,int b,int c,int m)
{
if(n==0||n==1)
return;
power(p,n/2,a,b,c,m);
mult(p,p,m);
if(n%2==1)
{
vector<vector<int>> q{{a,b,c},{1,0,0},{0,0,1}};
mult(p,q,m);
}
} | true |
d1a616a727f8217c7b5d7f0d6fea8d832d829c1b | C++ | jeanyves-b/projet_nachos | /code/network/nettest.cc | UTF-8 | 4,300 | 2.84375 | 3 | [
"MIT-Modern-Variant"
] | permissive | // nettest.cc
// Test out message delivery between two "Nachos" machines,
// using the Post Office to coordinate delivery.
//
// Two caveats:
// 1. Two copies of Nachos must be running, with machine ID's 0 and 1:
// ./nachos -m 0 -o 1 &
// ./nachos -m 1 -o 0 &
//
// 2. You need an implementation of condition variables,
// which is *not* provided as part of the baseline threads
// implementation. The Post Office won't work without
// a correct implementation of condition variables.
//
// Copyright (c) 1992-1993 The Regents of the University of California.
// All rights reserved. See copyright.h for copyright notice and limitation
// of liability and disclaimer of warranty provisions.
#include "copyright.h"
#include "network.h"
#include "system.h"
#include "network.h"
#include "post.h"
#include "interrupt.h"
// Test out message delivery, by doing the following:
// 1. send a message to the machine with ID "farAddr", at mail box #0
// 2. wait for the other machine's message to arrive (in our mailbox #0)
// 3. send an acknowledgment for the other machine's message
// 4. wait for an acknowledgement from the other machine to our
// original message
void
MailTest(int farAddr)
{
PacketHeader outPktHdr, inPktHdr;
MailHeader outMailHdr, inMailHdr;
const char *data = "Hello there!";
const char *ack = "Got it!";
char buffer[MaxMailSize];
// construct packet, mail header for original message
// To: destination machine, mailbox 0
// From: our machine, reply to: mailbox 1
outPktHdr.to = farAddr;
outMailHdr.to = 0;
outMailHdr.from = 1;
outMailHdr.length = strlen(data) + 1;
// Send the first message
postOffice->SendFiable(outPktHdr, outMailHdr, data);
// Wait for the first message from the other machine
postOffice->Receive(0, &inPktHdr, &inMailHdr, buffer);
printf("Got \"%s\" from %d, box %d\n",buffer,inPktHdr.from,inMailHdr.from);
fflush(stdout);
// Send acknowledgement to the other machine (using "reply to" mailbox
// in the message that just arrived
outPktHdr.to = inPktHdr.from;
outMailHdr.to = inMailHdr.from;
outMailHdr.length = strlen(ack) + 1;
postOffice->SendFiable(outPktHdr, outMailHdr, ack);
// Wait for the ack from the other machine to the first message we sent.
postOffice->Receive(1, &inPktHdr, &inMailHdr, buffer);
printf("Got \"%s\" from %d, box %d\n",buffer,inPktHdr.from,inMailHdr.from);
fflush(stdout);
// Then we're done!
interrupt->Halt();
}
// Teste l'envoi de gros message (900 octets) so us forme de token que la
// première machine (celle ayant l'id 0) enverra d'abord
// puis attendra, alors que les autres machines (id supérieur à 0)
// attendront de recevoir le message avant de l'envoyer. La dernière
// machine renverra vers 0.
// Ce test est utile pour tester un anneau.
// option -m <machine id> -ri <taille de l'anneau>
void
RingMailTest(int size)
{
char *data = new char[200];
char *buffer = new char[200];
unsigned i;
for(i = 0; i < 195; i++) {
data[i] = postOffice->getNetAddr() == 0? 'a' + (i%26) : 'z' - (i%26);
}
data[i++] = '#';
data[i++] = 'E';
data[i++] = 'N';
data[i++] = 'D';
data[i] = '\0';
// To: destination machine, mailbox 0
// From: our machine, reply to: mailbox 1
if (postOffice->getNetAddr()==0)
postOffice->SendUnfixedSize(data, 200, 1, 1, 0);
// Wait for the message from the other machine
postOffice->ReceiveUnfixedSize(0, buffer, 200);
printf("Got \"%s\"\n",buffer);
fflush(stdout);
if (postOffice->getNetAddr()!=0)
postOffice->SendUnfixedSize(data, 200, 1, postOffice->getNetAddr()+1==size?0:postOffice->getNetAddr() + 1, 0);
// Then we're done!
interrupt->Halt();
}
// Envoie un fichier vers la machine indiquée
// option -m <adresse machine> -fs <nom du fichier> <adresse distance>
void
FileSendTest(const char* file, int farAddr)
{
postOffice->SendFile(file, 1, farAddr, 0);
printf("Fichier \"%s\" envoyé à \"%d\" avec succès.\n", file, farAddr);
fflush(stdout);
// Then we're done!
interrupt->Halt();
}
// Reçoit un fichier et le mets à l'endroit indiqué
// option -m <adresse machine> -fr <nom du fichier>
void
FileReceiveTest(const char* to)
{
postOffice->ReceiveFile(0, to);
printf("Fichier reçu placé en: %s\n", to);
fflush(stdout);
// Then we're done!
interrupt->Halt();
}
| true |
13c0e608588dc6e071bb770d99dac101a43cd9d1 | C++ | yukti99/Data-Structures-and-Algorithms | /Hashing/hash.cpp | UTF-8 | 2,098 | 4.03125 | 4 | [] | no_license | /*
Hash Table in C
- Collisions resolved using chaining (Linked list)
*/
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
struct Node{
int key;
struct Node* next;
};
struct Hash{
struct Node* head;
int count;
};
struct Hash *hash_table = NULL ;
int hashFunc(int key){
return (key % SIZE);
}
struct Node* CreateNode(int key){
struct Node* h = (struct Node*)malloc(sizeof(struct Node));
h->key = key;
h->next = NULL;
return h;
}
void insert(int key){
struct Node* temp = CreateNode(key);
int h = hashFunc(key);
// entry of first element at that index
if (hash_table[h].head == NULL ){
hash_table[h].head = temp;
hash_table[h].count = 1;
return ;
}
temp->next = hash_table[h].head;
hash_table[h].head = temp;
/*
struct Node* p = hash_table[h].head;
while(p->next != NULL){
p = p->next;
}
p->next = temp;*/
hash_table[h].count++;
}
void display(){
printf("\nTHE HASH TABLE OF SIZE %d :\n\n",SIZE);
struct Node *p = NULL;
int i=0;
for(i=0;i<SIZE;i++){
if (hash_table[i].count == 0)
continue;
p = hash_table[i].head;
while(p!= NULL){
printf("%d ",p->key);
p = p->next;
}
printf("\n");
}
printf("\n");
}
int main(){
printf("\n\tHASH TABLE\n");
int i=0,x,choice;
int a[] = {0,1,2,3,4,5,6,7,8,9};
while(1){
printf("\n\tWhat do you want to do?\n\n");
printf("\t1. Insertion\n");
printf("\t2. Display\n");
printf("\t3. Quit\n");
printf("\tEnter your choice : ");
scanf("%d", &choice);
switch(choice){
case 1:
printf("Enter the Element to be inserted in Hash Table = ");
scanf("%d",&x);
insert(x);
break;
case 2:
display();
break;
case 3:
printf("\nThank you!!\n");
exit(0);
default:
printf("\nWrong choice!\n");
}
}
/*
insert(hash_table,0);
insert(hash_table,1);
insert(hash_table,2);
insert(hash_table,3);
insert(hash_table,4);
insert(hash_table,5);
insert(hash_table,7);
insert(hash_table,6);
insert(hash_table,15);
insert(hash_table,11);
insert(hash_table,27);
display(hash_table);*/
return 0;
}
| true |
f6bb16b12d233420ab66eabd845dd4a13b0c7bac | C++ | ckgod/algorithmCpp | /고속도로 설계하기.cpp | UTF-8 | 1,411 | 2.96875 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct edge {
int a, b;
int weight;
bool already;
};
bool comp(edge e1, edge e2) {
return e1.weight < e2.weight;
}
int n;
int board[202][202];
vector<edge> edgeList;
vector<edge> mst;
int parent[202];
int sumCost, cnt;
int find(int n) {
if (n == parent[n]) return n;
else return parent[n] = find(parent[n]);
}
void merge(int n1, int n2) {
n1 = find(n1);
n2 = find(n2);
if (n1 != n2) {
parent[n2] = n1;
}
}
int main() {
cin.tie(NULL);
ios::sync_with_stdio(false);
cin >> n;
for (int i = 1; i <= n; i++) {
parent[i] = i;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cin >> board[i][j];
if (i < j) {
if (board[i][j] < 0) {
edgeList.push_back({ i,j,-board[i][j], true });
}
else {
edgeList.push_back({ i,j,board[i][j] , false });
}
}
}
}
sort(edgeList.begin(), edgeList.end(), comp);
for (int i = 0; i < edgeList.size(); i++) {
edge e = edgeList[i];
if (e.already) {
sumCost += e.weight;
merge(e.a, e.b);
}
}
for (int i = 0; i < edgeList.size(); i++) {
edge e = edgeList[i];
if (find(e.a) != find(e.b)) {
sumCost += e.weight;
cnt++;
mst.push_back(e);
merge(e.a, e.b);
}
}
cout << sumCost << " " << cnt << "\n";
for (int i = 0; i < mst.size(); i++) {
cout << mst[i].a << " " << mst[i].b << "\n";
}
return 0;
} | true |
bb85d9a4eae0ea12c5e9e4dd542dcb2394674a0e | C++ | kritirikhi/DataStructuresAndAlgorithms | /RemoveDuplicates.cpp | UTF-8 | 566 | 3.34375 | 3 | [] | no_license | #include<iostream>
using namespace std;
void removeDuplicate(char input[],int i,char output[],int j){
// base case
if(input[i]=='\0'){
output[j]='\0';
cout<<output;
return;
}
// recursive case
if(input[i]==input[i+1]){
output[j]=input[i];
removeDuplicate(input,i+2,output,j+1);
}
else{
output[j]=input[i];
removeDuplicate(input,i+1,output,j+1);
}
}
int main() {
char input[1000];
cin>>input;
char output[1000];
removeDuplicate(input,0,output,0);
return 0;
} | true |
35e9b59c7c20cfd1d1a0ac1be25130a8a70b427f | C++ | AABHINAAV/InterviewPrep | /Queue/Deque_Using_Circular_Array.cpp | UTF-8 | 2,900 | 3.875 | 4 | [
"MIT"
] | permissive | //Circular linked list using Array
#include<iostream>
#include<vector>
using namespace std;
struct CLL{
vector<int> arr;
int rear = -1;
int beg = -1;
int n = 0;
CLL(int n){
arr.resize(n);
this->n = n;
}
};
bool isFull(CLL* head){
if( head->beg == head->rear+1 ||
head->beg == 0 && head->rear == head->n-1)
return true;
else
return false;
}
bool isEmpty(CLL *head){
if(head->beg == -1 )
return true;
else
return false;
}
//for displaying the elements
void disp(CLL *head){
for(int i = 0; i<head->n; i++)
cout<<head->arr[i]<<" ";
cout<<endl;
}
//for insertion in End
void insertEnd(CLL *head,int data){
cout<<endl<<"*********************PUSH******************\n";
cout<<"Before data:"<<data<<" beg:"<<head->beg<<" rear:"<<head->rear<<endl;
if(isFull(head))
return;
if(head->beg == -1)
head->beg =head->rear = 0;
else if(head->rear == head->n - 1)
head->rear = 0;
else
head->rear ++;
head->arr[head->rear] = data;
cout<<"After data:"<<data<<" beg:"<<head->beg<<" rear:"<<head->rear<<endl;
disp(head);
}
//insertion at Begining
void insertBegin(CLL *head,int data){
cout<<endl<<"*********************PUSH******************\n";
cout<<"Before data:"<<data<<" beg:"<<head->beg<<" rear:"<<head->rear<<endl;
if(isFull(head))
return;
if(head->beg == -1)
head->beg =head->rear = 0;
//update the writable index for front position
else if(head->beg == 0)
head->beg = head->n -1;
else
head->beg --;
//push the element
head->arr[head->beg] = data;
cout<<"After data:"<<data<<" beg:"<<head->beg<<" rear:"<<head->rear<<endl;
disp(head);
}
//for deletion in begining
void delBegin(CLL *head){
cout<<endl<<"*********************POP******************\n";
cout<<"Before beg:"<<head->beg<<" rear:"<<head->rear<<endl;
if(isEmpty(head))
return;
if(head->beg == head->rear)
head->beg =head->rear = -1;
else if(head->beg == head->n -1)
head->beg = 0;
else
head->beg++;
cout<<"After beg:"<<head->beg<<" rear:"<<head->rear<<endl;
disp(head);
}
//deleteion at end
void deleteEnd(CLL *head){
cout<<endl<<"*********************POP******************\n";
cout<<"Before beg:"<<head->beg<<" rear:"<<head->rear<<endl;
if(isEmpty(head))
return;
if(head->beg == head->rear)
head->beg = head->rear = -1;
else if(head->rear == 0)
head->rear = head->n -1 ;
else
head->rear--;
cout<<"After beg:"<<head->beg<<" rear:"<<head->rear<<endl;
disp(head);
}
int main(){
CLL *head = new CLL(5);
insertEnd(head,1);
insertEnd(head,2);
insertEnd(head,3);
delBegin(head);
delBegin(head);
//insertEnd(head,3);
insertEnd(head,4);
insertEnd(head,5);
insertEnd(head,6);
insertEnd(head,7);
insertEnd(head,8);
disp(head);
cout<<" **beg:"<<head->beg<<" rear:"<<head->rear<<endl;
delBegin(head);
delBegin(head);
delBegin(head);
deleteEnd(head);deleteEnd(head);
insertBegin(head,44);
insertEnd(head,55);
disp(head);
return 0;
}
| true |
a5f46acdd27cda28caaadd1a29f8350c06225e28 | C++ | codelibra/comp-programming | /c-programs/subsetsum2.cpp | UTF-8 | 736 | 2.96875 | 3 | [] | no_license | //shivi..coding is adictive!!
#include<shiviheaders.h>
using namespace std;
void Generate(int arr[],int ans[],int N,int sz,int index,int sum,int target)
{
if(index>N) return;
if(sum==target)
{
for(int i=0;i<sz;++i)
cout<<ans[i]<<" ";
cout<<endl;
Generate(arr,ans,N,sz-1,index+1,sum-ans[sz-1],target);
}
else
{
for(int i=index;i<N;++i)
{
if(arr[i]+sum<=target)
{
ans[sz]=arr[i];
Generate(arr,ans,N,sz+1,i+1,sum+arr[i],target);
}
else
break;
}
}
}
void SubsetSum(int arr[],int N,int target)
{
int *ans=new int[N];
sort(arr,arr+N);
Generate(arr,ans,N,0,0,0,target);
}
int main()
{
int weights[] = {10, 5, 10, 15, 12, 20, 15};
int target = 15;
SubsetSum(weights,7,target);
}
| true |
f7a82401e81899dcfac97f6538313268e5ca0532 | C++ | Group-3/Pacman | /code/Pacman/BlueEffect.cpp | UTF-8 | 372 | 2.6875 | 3 | [] | no_license | #include "BlueEffect.h"
BlueEffect::BlueEffect()
: BuffEffect(300)
{
counter = 10.0f;
}
void BlueEffect::update(double dt)
{
//make the owner invernable to ghosts
BuffEffect::setMultiplier(2.0f);
counter -= dt;
}
BlueEffect::~BlueEffect()
{
//this will not work if the effectlist has multiple
//instances of the same effect
BuffEffect::setMultiplier(1.0f);
} | true |
750f4cbc2c305f5b68950bcec1599ede8451566e | C++ | imnhk/problem-solving | /baekjoon/1931_meeting_room_alloc.cpp | UTF-8 | 659 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Meeting {
int begin, end;
};
bool CompareEndTime(Meeting a, Meeting b) {
if (a.end == b.end)
return a.begin < b.begin;
return a.end < b.end;
}
int main()
{
ios::sync_with_stdio(0); cin.tie(0);
int N, lastMeetEnd = 0, answer = 0;
cin >> N;
vector<Meeting> meeting(N);
for (int i = 0; i < N; i++)
cin >> meeting[i].begin >> meeting[i].end;
sort(meeting.begin(), meeting.end(), CompareEndTime);
for (int i = 0; i < N; i++)
{
if (meeting[i].begin >= lastMeetEnd) {
lastMeetEnd = meeting[i].end;
answer++;
}
}
cout << answer;
return 0;
} | true |
232214d684c69f9f4f6fc05b390603dcfad02639 | C++ | SmileGobo/CPPFactoryAndConfigure | /app/src/Factory.cpp | UTF-8 | 723 | 2.90625 | 3 | [
"BSL-1.0"
] | permissive | #include "Factory.h"
#include <stdexcept>
#include "Serial.h"
#include "Ethernet.h"
template <typename T>
struct Creator{
Transport::Ptr operator() (std::uint32_t id){
return std::make_shared<T>(id);
}
};
constexpr std::size_t type2index(Transport::Type t){
return static_cast<std::size_t>(t);
}
Factory::Factory():
_ctors({
nullptr,
nullptr
})
{
_ctors[type2index(Transport::Type::Serial)] = Creator<Serial>();
_ctors[type2index(Transport::Type::Ethernet)] = Creator<Ethernet>();
}
Transport::Ptr Factory::create(const Transport::Type type, uint32_t id) {
if (type == Transport::Type::Max){
return nullptr;
}
return _ctors[type2index(type)](id);
}
| true |
ebcc5736b5247d3d580beb8a20b2096c66f75c70 | C++ | cty41/Titan | /TitanCore/include/TiRenderQueueGroup.h | UTF-8 | 1,944 | 2.875 | 3 | [] | no_license | #ifndef __TITAN_RENDERQUEUE_GROUP__HH
#define __TITAN_RENDERQUEUE_GROUP__HH
#include "TiPrerequisites.h"
#include "TiRenderQueue.h"
#include "TiIteratorWrapper.h"
namespace Titan
{
class _DllExport RenderQueueGroup : public GeneralAlloc
{
public:
struct RenderQueueEntry
{
uint64 sortKey;
Renderable* renderable;
Pass* rendPass;
RenderQueueEntry(Renderable* rend, Pass* pass, uint64 key)
:renderable(rend),rendPass(pass), sortKey(key)
{}
};
struct _DllExport EntrySortMore
{
bool operator()(const RenderQueueEntry& a, const RenderQueueEntry& b) const
{
return a.sortKey > b.sortKey;
}
};
struct _DllExport EntrySortLess
{
bool operator()(const RenderQueueEntry& a, const RenderQueueEntry& b) const
{
return a.sortKey < b.sortKey;
}
};
public:
typedef vector<RenderQueueEntry>::type RenderQueueEntryVec;
typedef VectorIterator<RenderQueueEntryVec> RenderQueueEntryVecIterator;
public:
RenderQueueGroup(RenderQueue* parent, uint type);
~RenderQueueGroup();
void addRenderable(Renderable* rend, ushort priority);
void clear();
void sort();
void setSortStrategy(RenderQueue::SortStrategy ss){ mStrategy = ss;}
RenderQueueEntryVecIterator getOpaqueEntryIterator() { return RenderQueueEntryVecIterator(mOpaqueEntryVec.begin(), mOpaqueEntryVec.end());}
RenderQueueEntryVecIterator getSortedTransparentEntryIterator() { return RenderQueueEntryVecIterator(mSortedTransparentEntryVec.begin(), mSortedTransparentEntryVec.end());}
RenderQueueEntryVecIterator getUnsortedTransparentEntryIterator() { return RenderQueueEntryVecIterator(mUnsortedTransparentEntryVec.begin(), mUnsortedTransparentEntryVec.end());}
protected:
RenderQueue* mParentQueue;
RenderQueueEntryVec mOpaqueEntryVec;
RenderQueueEntryVec mSortedTransparentEntryVec;
RenderQueueEntryVec mUnsortedTransparentEntryVec;
uint mType;
uint mStrategy;
};
}
#endif | true |
c5c9fa78d7a346d421e412a85ec93f6fd25a2bd7 | C++ | yzq986/cntt2016-hw1 | /TC-SRM-590-div1-500/oysq.cpp | UTF-8 | 1,553 | 2.53125 | 3 | [] | no_license | #line 2 "XorCards.cpp"
#include <bits/stdc++.h>
using namespace std;
#define ui unsigned
#define ll long long
#define pii std::pair<int,int>
#define mp std::make_pair
#define fi first
#define se second
#define SZ(x) (int)(x).size()
#define pb push_back
template<class T>inline void chkmax(T &x, const T &y) {if(x < y) x = y;}
template<class T>inline void chkmin(T &x, const T &y) {if(x > y) x = y;}
const int B = 50;
ll bit[B];
int s[B];
class XorCards {
public:
ll numberOfWays(vector<ll> v, ll k) {
ll ex = 1;
memset(bit, 0, sizeof bit);
// 求出线性基
for(auto a : v) {
bool fl = false;
for(int i = B - 1; i >= 0; --i)
if(a >> i & 1) {
if(bit[i]) a ^= bit[i];
else {
bit[i] = a;
fl = true;
break;
}
}
if(!fl) ex <<= 1;// 额外的数可以随便加上或者不加上
}
// 前缀和
for(int i = 0; i < B; ++i)
s[i] = (bit[i] > 0) + (i ? s[i - 1] : 0);
ll ret = 0, cur = 0;
for(int i = B - 1; i >= 0; --i)
if(k >> i & 1) {
if(bit[i]) {
ret += 1ll << (s[i] - 1);// 这一位可以变成0,后面的随便选
if(!(cur >> i & 1)) cur ^= bit[i];// 让cur >= k
}
else {
if(!(cur >> i & 1)) {// cur一定 < k,后面的随便选
ret += 1ll << s[i];
break;
}
}
}
else {
if(cur >> i & 1) {
if(bit[i]) cur ^= bit[i];// 可以把这一位变成0
else break;// 不能变成0,那么cur一定 > k
}
}
if(cur == k) ret++;// 之前统计的是 < k的答案
return ret * ex;
}
};
| true |
10a817e67798d0b10d990f42c6118368c90195cc | C++ | antongulikov/cpp-cgdk | /model/Player.cpp | UTF-8 | 752 | 2.6875 | 3 | [] | no_license | #include "Player.h"
using namespace model;
Player::Player()
: id(-1), me(false), strategyCrashed(false), score(-1), remainingActionCooldownTicks(-1) { }
Player::Player(long long id, bool me, bool strategyCrashed, int score, int remainingActionCooldownTicks)
: id(id), me(me), strategyCrashed(strategyCrashed), score(score),
remainingActionCooldownTicks(remainingActionCooldownTicks) { }
long long Player::getId() const {
return id;
}
bool Player::isMe() const {
return me;
}
bool Player::isStrategyCrashed() const {
return strategyCrashed;
}
int Player::getScore() const {
return score;
}
int Player::getRemainingActionCooldownTicks() const {
return remainingActionCooldownTicks;
}
| true |
f197abeaff934a926e5239099b2c8711570fc46c | C++ | victorh1705/Trabalho02_CG | /CG/src/src/AbstractGeom.cpp | UTF-8 | 606 | 2.515625 | 3 | [] | no_license | #include "AbstractGeom.h"
AbstractGeom::AbstractGeom()
{
//ctor
}
AbstractGeom::~AbstractGeom()
{
//dtor
}
bool AbstractGeom::colisaoX(float var){
if(this->GetalturaInicialX() > var && var < this->GetalturaFinalX()){
return true;
}
return false;
}
bool AbstractGeom::colisaoY(float var){
if(this->GetalturaInicialY() > var && var < this->GetalturaFinalY()){
return true;
}
return false;
}
bool AbstractGeom::colisaoZ(float var){
if(this->GetalturaInicialZ() > var && var < this->GetalturaFinalZ()){
return true;
}
return false;
}
| true |
548e17771391fb7f8246a8501811fa3500c53ea4 | C++ | scotty3785/ssrt-quadcopter | /motor_test.ino | UTF-8 | 2,683 | 2.90625 | 3 | [] | no_license | /*
Two Prop Power Adjust
Two ESCs are connected to the Ardupilot.
The Throttle channel is used to set the power to each motor
The roll channel is used to slightly offset the power from
the left or right motor.
If the roll level is moved to the left the right motor will
be given more power and the left motor less, tilting the jig
to the left.
by Scott Thomson (10 May 2012)
*/
#include <Arduino_Mega_ISR_Registry.h>
#include <APM_RC.h>
#include <FastSerial.h>
Arduino_Mega_ISR_Registry isr_registry
APM_RC_APM1 APM_RC;
/* Modes used during the main loop */
#define INIT 0 //Initialise unit
#define MAIN 1 //Normal Operation
/* Input Channels from Reciever */
#define THROTTLE 0
#define PITCH 1
#define ROLL 2
#define YAW 3
#define SWITCH 4
/* Default scale values */
#define SF 0.01 //Scale Factor to generate delta value (/100)
int mode; //used to select mode of operation.
int pitch_trim = 0; //the centred value of pitch
int delta = 0; //the value used to adjust left/right motors.
int rc_data[8]; //Stores all 8 channels of RC data
int motor1; //Value for Left Hand motor
int motor2; //Value for Right Hand motor
void setup()
{
isr_registry.init();
APM_RC.Init(&isr_registry);
APM_RC.enable_out(CH_1);
APM_RC.enable_out(CH_2);
APM_RC.enable_out(CH_3);
APM_RC.enable_out(CH_4);
APM_RC.enable_out(CH_5);
APM_RC.enable_out(CH_6);
APM_RC.enable_out(CH_7);
APM_RC.enable_out(CH_8);
Serial.begin(115200);
Serial.println("Motor Balance Test");
mode = INIT;
Serial.print("Initialising");
delay(1000);
}
void loop()
{
switch(mode)
{
case INIT:
if (APM_RC.GetState == 1)
{
//If we have done 5 seconds on Init, move to main mode
if (millis() > 5000)
{
mode = MAIN;
Serial.println("");
}
else
{
//pitch_trim is the value of the pitch lever when it is centred
pitch_trim = APM_RC.InputCh(PITCH);
Serial.print("*");
}
}
break;
case MAIN:
if (APM_RC.GetState == 1)
{
//Read in the values from all 8 RX channels
for (int i = 0; i < 8;i++)
{
rc_data[i] = APM_RC.InputCh(i);
}
/*Generate the difference between the trim value and our present value
Multiply this by a scale factor to reduce the size of it so we don't
end up hitting the floor.*/
delta = (pitch_trim - rc_data[PITCH]) * SF;
motor1 = (rc_data[THROTTLE] - delta);
motor2 = (rc_data[THROTTLE] + delta);
APM_RC.OutputCh(CH1,motor1);
APM_RC.OutputCh(CH2,motor2);
Serial.printf_P(PSTR("t:%04d p:%04d m1:%04d m2:%04d\n"),(int)rc_data[THROTTLE],(int)rc_data[PITCH],(int)motor1,(int)motor2);
}
break;
};
} | true |
6a0270114d7347e78fda157d23a4b31b77732b70 | C++ | MeowningMaster-Study/threaded_eval | /main.cpp | UTF-8 | 3,223 | 3.5625 | 4 | [] | no_license | #include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
#include <cmath>
using namespace std;
void f(double x, double &ret, mutex &m) {
lock_guard<mutex> g(m); // блокируем доступ к ret для других потоков
this_thread::sleep_for(chrono::seconds(5 + rand()%15)); // "засыпает" на 5-20 (случайно) секунд
ret = x; //возвращает x
} // тут вызываеться деструктор lock_guard и он освобождает нашу переменную
void g(double x, double &ret, mutex &m) {
lock_guard<mutex> g(m); // блокируем доступ к ret для других потоков
ret = sqrt(x); // возвращает корень квадратный из x
} // тут вызываеться деструктор lock_guard и он освобождает нашу переменную
int main() {
double x;
cout << "Введіть x: ";
cin >> x;
srand((unsigned int)time(0)); // иниициализирует рандомизатор что бы использовать его в f
double r1, r2; // переменные в которые мы будем возвращать результаты вычислений функций
mutex m1, m2; // переменные-гаранты которые обеспечивают что только один поток будет менять выходные переменные одновременно
thread t1(f, x, ref(r1), ref(m1)), t2(g, x, ref(r2), ref(m2)); // создает и запускает потоки для f и g
this_thread::sleep_for(chrono::milliseconds(5)); // даем время потокам заблокировать всё что им нужно, похоже на костыль но работает
auto start = chrono::steady_clock::now(); // засекаем начало
bool l1 = false, l2 = false; // заблокированы ли переменные нашим основным потоком
bool ask = true; // стоит ли спрашивать
while (!(l1 && l2)) { // ждем доступа к переменным r1 и r2
if (!l1) {
l1 = m1.try_lock();
}
if (!l2) {
l2 = m2.try_lock();
}
if (chrono::steady_clock::now() > start + 10s) { // если прошло 10 секунд
if (ask) {
cout << "Пройшло 10 секунд, продовжити обчислення? 1 - так, 2 - ні, 3 - більше не запитувати: ";
int a;
cin >> a;
switch(a) {
case 2:
abort(); // завершаем программу и все дочерние потоки
break;
case 3:
ask = false; // больше не спрашиваем
break;
}
}
start = chrono::steady_clock::now();
}
}
cout << r1 * r2 << endl;
// ждём завершения потоков
t1.join();
t2.join();
return 0;
} | true |
2c299064603790a46085b83319309e7e5ba3dffa | C++ | xulzee/LeetCodeProjectCPP | /source/autumn-recruitment/300. Longest Increasing Subsequence.cpp | UTF-8 | 1,441 | 3.375 | 3 | [] | no_license | //
// Created by liuze.xlz on 2019-08-26.
//
#include "utils.h"
class Solution {
public:
// [10,9,2,5,3,7,101,18] -> [2,3,7,101]
int lengthOfLIS(vector<int> &nums) {
return BinaryDynamicProcess(nums);
}
int process(vector<int> &nums, int cur) {
int ret = 1;
for (int i = cur - 1; i >= 0; --i) {
if (nums[i] < nums[cur]) {
ret = max(ret, 1 + process(nums, i));
}
}
return ret;
}
int DynamicProcess(vector<int> &nums) {
vector<int> dp(nums.size() + 1, 1);
int res = 0;
for (int i = 1; i < nums.size(); ++i) {
int ret = 1;
for (int j = i - 1; j >= 0; --j) {
if (nums[j] < nums[i]) {
ret = max(ret, 1 + dp[j]);
}
}
dp[i] = ret;
res = max(res, ret);
}
return res;
}
int BinaryDynamicProcess(vector<int> &nums) {
vector<int> dp(nums.size(), 0);
int res = 0;
for (auto &num : nums) {
int i = lower_bound(dp.begin(), dp.begin() + res, num) - dp.begin();
dp[i] = num;
if (i == res){
++res;
}
}
return res;
}
};
int main() {
vector<int> nums = {0, 8, 4, 12, 2};
// vector<int> nums = {10, 9, 2, 5, 3, 7, 101, 18};
cout << Solution().lengthOfLIS(nums) << endl;
}
| true |
a5d63fe243d1910ee4f1b2ced7e9878ff661cb64 | C++ | hoatuno/runningpet | /box.cpp | UTF-8 | 3,343 | 2.53125 | 3 | [] | no_license | #include <SDL.h>
#include <string>
#include <time.h>
#include "box.h"
#include "utils.h"
const int GROUND = 500;
void Jumping( SDL_Renderer* &renderer, SDL_Rect& pet,int &foot,bool &StartJump){ // Hàm giúp nhảy lên 100px rồi rơi xuống
int boxstep ;
foot+=1; // foot để giúp nhảy lên 1px sau mỗi frame
boxstep=0.16*foot*foot - 9*foot;// 0 <= boxstep <= 50
pet.y=GROUND + boxstep ;
if(foot>=56) { foot =0; StartJump =0; } // 9*foot and >=56 || 8*foot and >=50
}
void Animachar (bool& StartJump, int& time1){ // tạo chuyển động của nhân vật
if(!StartJump)time1++;
else time1=6;
if(time1>11)time1=0;
}
void RunningBarrier( SDL_Renderer* &renderer, SDL_Rect& pos,int &state, string Barri[],long& score ){
{
// Hàm nhận vào một cửa sổ, một render, một chướng ngại vật và vị trí của nó,
// chướng ngại vật sẽ đi từ phải qua trái và giải phòng
srand(time(NULL));
int rapid= (score >800) ? (score-300)/500 : 0;
int step= -5 -rapid;
pos.x += step;
Showimage( Barri[state].c_str() , renderer, pos );
if (pos.x <= -60) {
state = rand()%5 + 0; // biến state để random barrier trong khoảng nhỏ
pos.x= 1000;
cout << step <<endl;
}
}
}
void PlaygameEvent(SDL_Event e, bool& StartJump, bool&quit){ //Thông báo sự kiện phím
//xử lý các thao tác ban đầu với phím
//khi game đang chạy
if (e.type == SDL_QUIT) { quit=0; cout << "QUIT GAME!" << endl; }
if (e.type == SDL_KEYDOWN) {
switch (e.key.keysym.sym){
case SDLK_SPACE :{
cout << "space" << endl;
StartJump =1;
Playchunk("music/jump.ogg");
}break;
default: break;
}
if (e.type == SDL_KEYUP) { }
}
}
void KeyPressedplayagain( SDL_Event e, long& score, bool& gamerunning, bool&quit)
{
if (e.type == SDL_QUIT) {quit =0; gamerunning=0; cout << "QUIT GAME!" << endl; }
if (e.type == SDL_KEYDOWN)
if (e.key.keysym.sym == SDLK_KP_ENTER) {
score=0;
gamerunning=1;
cout << "PLAY AGAIN!" << endl;
}
}
void KeyPresstostart( SDL_Event e,bool &starting, bool &quit)
{
if (e.type == SDL_QUIT) { quit=0;cout << "QUIT GAME!" << endl; }
if (e.type == SDL_KEYDOWN) if (e.key.keysym.sym == SDLK_SPACE) {
starting =0;
cout << "START GAME!" << endl; }
}
bool accident(SDL_Rect& pet, SDL_Rect& ba ) // kiem tra va cham giữa 2 rect
// x, y là điểm ở góc phần tư thứ III
{
int Ax= pet.x+pet.w;
int Ay= pet.y-5;
int Bx= pet.x;
int By= pet.y-5;
if( Ax>=ba.x+5 && Ax <= ba.x+ba.w-5 &&
Ay>=ba.y-ba.h+10 && Ay <= ba.y) return 1;
if( Bx>=ba.x+5 && Bx <= ba.x+ba.w-5 &&
By>=ba.y-ba.h+10 && By <= ba.y) return 1;
return 0;
}
| true |
6a62c979c209d25423a0d7b11a779c632bed7687 | C++ | jordsti/stipersist | /StiPersist/FieldsObject.h | UTF-8 | 2,741 | 2.890625 | 3 | [] | no_license | #ifndef FIELDSOBJECT_H
#define FIELDSOBJECT_H
#include "Persistable.h"
namespace StiPersist
{
/// \class FieldsObject
/// \brief Implementation of Persistable. This class is used to populate container element has a FieldsObject
class FieldsObject :
public Persistable
{
public:
/// \brief Constructor
FieldsObject();
/// \brief Destructor
virtual ~FieldsObject();
/// \brief Implementation of Persistable
void fromFields(void);
/// \brief Create fields from Chunk
/// \param chunk Data Chunk
void fromChunk(Data::Chunk *chunk);
/// \brief Set String Value
/// \param fname Field Name
/// \param value String Value
void setString(std::string fname, std::string value);
/// \brief Set Integer Value
/// \param fname Field Name
/// \param value Integer Value
void setInt(std::string fname, int value);
/// \brief Set Double Value
/// \param fname Field Name
/// \param value Double Value
void setDouble(std::string fname, double value);
/// \brief Set Float Value
/// \param fname Field Name
/// \param value Float Value
void setFloat(std::string fname, float value);
/// \brief Set Raw Value
/// \param fname Field Name
/// \param value Raw Value
/// \param length Data Length
void setRaw(std::string fname, char *value, unsigned int length);
/// \brief Set unsigned Integer Value
/// \param fname Field Name
/// \param value unsigned Integer Value
void setUInt(std::string fname, unsigned int value);
/// \brief Set Bool Value
/// \param fname Field Name
/// \param value Bool Value
void setBool(std::string fname, bool value);
/// \brief Get String Value
/// \param fname Field Name
/// \return String
std::string getString(std::string fname);
/// \brief Get Integer Value
/// \param fname Field Name
/// \return Integer
int getInt(std::string fname);
/// \brief Get Double Value
/// \param fname Field Name
/// \return Double
double getDouble(std::string fname);
/// \brief Get Float Value
/// \param fname Field Name
/// \return Float
float getFloat(std::string fname);
/// \brief Get Raw Value
/// \param fname Field Name
/// \return Raw
char* getRaw(std::string fname);
/// \brief Get Unsigned Integer Value
/// \param fname Field Name
/// \return Unsigned Integer
unsigned int getUInt(std::string fname);
/// \brief Get Bool Value
/// \param fname Field Name
/// \return Bool
bool getBool(std::string fname);
/// \brief Get all fields information
/// \return List of Field Info
std::list<Data::FieldInfo*>* getFieldsName(void);
protected:
/// \brief Implementation of IPersist
void populateFields(void);
};
}
#endif | true |
48e6c06725c19c59510ed0275dcdadf09c1d510d | C++ | azyabugoff/CPP_42_pool | /CPP_module_03/frag_trap_ex02/ClapTrap.hpp | UTF-8 | 1,473 | 2.6875 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ClapTrap.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sesnowbi <sesnowbi@student.21-school.ru +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/08/12 12:35:54 by sesnowbi #+# #+# */
/* Updated: 2021/08/12 18:52:41 by sesnowbi ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef CLAPTRAP_HPP
# define CLAPTRAP_HPP
#include <string>
class ClapTrap
{
protected:
std::string name;
int hit_pts;
int energy_pts;
int damage;
public:
ClapTrap();
ClapTrap(std::string const name);
ClapTrap(const ClapTrap &obj);
ClapTrap &operator = (const ClapTrap &obj);
~ClapTrap();
std::string getName() const;
int getHP() const;
int getEnergy() const;
int getDamage() const;
void attack(std::string const &target);
void takeDamage(unsigned int amount);
void beRepaired(unsigned int amount);
};
#endif
| true |
0050dd3b2d419cd6bd4ab41de55b40c5bba9ca22 | C++ | shivral/cf | /0300/70/379a.cpp | UTF-8 | 347 | 2.984375 | 3 | [
"Unlicense"
] | permissive | #include <iostream>
void answer(unsigned v)
{
std::cout << v << '\n';
}
void solve(unsigned a, unsigned b)
{
unsigned c = 0, d = 0;
while (a != 0) {
c += a;
d += a;
a = d / b;
d %= b;
}
answer(c);
}
int main()
{
unsigned a, b;
std::cin >> a >> b;
solve(a, b);
return 0;
}
| true |
0aff08a31e9b9bb70024065628689aa79c3d1f4e | C++ | lud99/botw-unexplored | /source/Graphics/BasicVertices.h | UTF-8 | 4,892 | 2.953125 | 3 | [] | no_license | #pragma once
#include <glm/vec3.hpp>
#include <glm/gtc/type_precision.hpp>
namespace BasicVertices {
namespace Cube {
enum Faces {
Left,
Right,
Bottom,
Top,
Back,
Front
};
const static glm::u8vec3 TopVertices[4] = {
glm::u8vec3(0, 1, 1),
glm::u8vec3(1, 1, 1),
glm::u8vec3(1, 1, 0),
glm::u8vec3(0, 1, 0),
};
const static glm::u8vec3 BottomVertices[4] = {
glm::u8vec3(0, 0, 1),
glm::u8vec3(1, 0, 1),
glm::u8vec3(1, 0, 0),
glm::u8vec3(0, 0, 0),
};
const static glm::u8vec3 LeftVertices[4] = {
glm::u8vec3(0, 0, 0),
glm::u8vec3(0, 0, 1),
glm::u8vec3(0, 1, 1),
glm::u8vec3(0, 1, 0),
};
const static glm::u8vec3 RightVertices[4] = {
glm::u8vec3(1, 0, 0),
glm::u8vec3(1, 0, 1),
glm::u8vec3(1, 1, 1),
glm::u8vec3(1, 1, 0),
};
const static glm::u8vec3 FrontVertices[4] = {
glm::u8vec3(0, 0, 1),
glm::u8vec3(1, 0, 1),
glm::u8vec3(1, 1, 1),
glm::u8vec3(0, 1, 1),
};
const static glm::u8vec3 BackVertices[4] = {
glm::u8vec3(0, 0, 0),
glm::u8vec3(1, 0, 0),
glm::u8vec3(1, 1, 0),
glm::u8vec3(0, 1, 0),
};
inline const glm::u8vec3* GetFace(int id)
{
switch (id)
{
case Faces::Left: return LeftVertices;
case Faces::Right: return RightVertices;
case Faces::Bottom: return BottomVertices;
case Faces::Top: return TopVertices;
case Faces::Back: return BackVertices;
case Faces::Front: return FrontVertices;
}
return nullptr;
}
const static uint16_t Indices[6] = {
0, 1, 2,
2, 3, 0
};
const static glm::vec3 FullCube[36] = {
glm::vec3(-1.0f, 1.0f, -1.0f),
glm::vec3(-1.0f, -1.0f, -1.0f),
glm::vec3(1.0f, -1.0f, -1.0f),
glm::vec3(1.0f, -1.0f, -1.0f),
glm::vec3(1.0f, 1.0f, -1.0f),
glm::vec3(-1.0f, 1.0f, -1.0f),
glm::vec3(-1.0f, -1.0f, 1.0f),
glm::vec3(-1.0f, -1.0f, -1.0f),
glm::vec3(-1.0f, 1.0f, -1.0f),
glm::vec3(-1.0f, 1.0f, -1.0f),
glm::vec3(-1.0f, 1.0f, 1.0f),
glm::vec3(-1.0f, -1.0f, 1.0f),
glm::vec3(1.0f, -1.0f, -1.0f),
glm::vec3(1.0f, -1.0f, 1.0f),
glm::vec3(1.0f, 1.0f, 1.0f),
glm::vec3(1.0f, 1.0f, 1.0f),
glm::vec3(1.0f, 1.0f, -1.0f),
glm::vec3(1.0f, -1.0f, -1.0f),
glm::vec3(-1.0f, -1.0f, 1.0f),
glm::vec3(-1.0f, 1.0f, 1.0f),
glm::vec3(1.0f, 1.0f, 1.0f),
glm::vec3(1.0f, 1.0f, 1.0f),
glm::vec3(1.0f, -1.0f, 1.0f),
glm::vec3(-1.0f, -1.0f, 1.0f),
glm::vec3(-1.0f, 1.0f, -1.0f),
glm::vec3(1.0f, 1.0f, -1.0f),
glm::vec3(1.0f, 1.0f, 1.0f),
glm::vec3(1.0f, 1.0f, 1.0f),
glm::vec3(-1.0f, 1.0f, 1.0f),
glm::vec3(-1.0f, 1.0f, -1.0f),
glm::vec3(-1.0f, -1.0f, -1.0f),
glm::vec3(-1.0f, -1.0f, 1.0f),
glm::vec3(1.0f, -1.0f, -1.0f),
glm::vec3(1.0f, -1.0f, -1.0f),
glm::vec3(-1.0f, -1.0f, 1.0f),
glm::vec3(1.0f, -1.0f, 1.0)
};
};
namespace Quad {
const static glm::vec3 Face[4] = {
glm::vec3(-0.5f, -0.5f, 0),
glm::vec3(0.5f, -0.5f, 0),
glm::vec3(0.5f, 0.5f, 0),
glm::vec3(-0.5f, 0.5f, 0),
};
const static uint16_t Indices[6] = {
0, 1, 2,
2, 3, 0
};
const static glm::vec2 TextureCoordinates[4] = {
glm::vec2(0.0f, 0.0f),
glm::vec2(1.0f, 0.0f),
glm::vec2(1.0f, 1.0f),
glm::vec2(0.0f, 1.0f),
};
inline void Construct(glm::vec3 positions[4], float width, float height, float z = 0.0f, bool center = true)
{
if (center)
{
positions[0] = glm::vec3(-width / 2, -height / 2, z);
positions[1] = glm::vec3( width / 2, -height / 2, z);
positions[2] = glm::vec3( width / 2, height / 2, z);
positions[3] = glm::vec3(-width / 2, height / 2, z);
} else
{
positions[0] = glm::vec3(0.0f, 0.0f, z);
positions[1] = glm::vec3(width, 0.0f, z);
positions[2] = glm::vec3(width, height, z);
positions[3] = glm::vec3(0.0f, height, z);
}
}
inline void Construct(glm::vec3 positions[4], glm::vec2 origin, float width, float height)
{
positions[0] = glm::vec3(origin.x - width / 2, origin.y - height / 2, 0.0f);
positions[1] = glm::vec3(origin.x + width / 2, origin.y - height / 2, 0.0f);
positions[2] = glm::vec3(origin.x + width / 2, origin.y + height / 2, 0.0f);
positions[3] = glm::vec3(origin.x - width / 2, origin.y + height / 2, 0.0f);
}
inline void ConstructFromBottomleft(glm::vec3 positions[4], glm::vec2 origin, float width, float height)
{
positions[0] = glm::vec3(origin.x, origin.y + height, 0.0f);
positions[1] = glm::vec3(origin.x, origin.y, 0.0f);
positions[2] = glm::vec3(origin.x + width, origin.y, 0.0f);
positions[3] = glm::vec3(origin.x + width, origin.y + height, 0.0f);
}
}
}; | true |
eb9b5c28a89ef45ec7841414d1353fb0510a2139 | C++ | frnkthtnk101/redisticting_game | /cpp/Tract.h | UTF-8 | 2,193 | 2.78125 | 3 | [] | no_license | /*
* Tract.h
*
* Author: scarbors, frnkthtnk100
*/
#include <map>
#include <memory>
#include <set>
#include <string>
#include <vector>
#ifndef TRACT_H_
#define TRACT_H_
using namespace std;
namespace AIProj
{
typedef size_t tractId; //fid
typedef std::string tractMetric;
class Tract
{
public:
Tract (tractId, size_t,size_t, int, std::map<tractMetric,size_t>);
virtual ~Tract ();
const tractId& getId() const { return tractId_; } ;
int getPopulation(void) const { return population_; };
//void addNeighbors(const std::set<tractId> &nghbor) { neighboringTracts_ = nghbor; } ;
void addNeighbor(std::shared_ptr<Tract> nghbor) { if(nghbor->getId() != tractId_ ) neighboringTracts_.insert(nghbor); } ;
std::set<std::shared_ptr<Tract> > getNeighbors(void) const { return neighboringTracts_; }; //Return by copy
const std::set<std::shared_ptr<Tract> > & getNeighborsByRef(void) const { return neighboringTracts_; }; //Return by copy
//void addAttributes(std::vector<std::pair<tractMetric,size_t> >);
//void addAttribute( const tractMetric&,size_t);
bool hasAttribute(const tractMetric&) const;
size_t getAttributeValue(const tractMetric&) const;
double getAttributeFraction(const tractMetric&) const;
const std::map<tractMetric,size_t>& getAttributeMap(void) const { return attributeMap_; };
const std::map<tractMetric,double>& getAttributeFractionMap(void) const { return attributeFraction_; };
void setDistrictId(const size_t &did) { districtId_ = did; };
size_t getDistrictId( void ) const { return districtId_; };
double getCohesionValue( const size_t &did) const;
size_t getCountyId(void) const { return countyId_; };
size_t getFullTract(void) const { return fullTract_; };
private:
tractId tractId_;
size_t districtId_;
size_t countyId_;
size_t fullTract_;
int population_;
std::map<tractMetric,size_t> attributeMap_;
std::map<tractMetric,double> attributeFraction_;
std::set<std::shared_ptr<Tract> > neighboringTracts_;
};
} /* namespace AIProj */
#endif /* TRACT_H_ */
| true |
63302f088124b0cd1f5cd3c2c76b8765008cb4cf | C++ | sergiyilnytsky/Black-Jack | /Black Jack/Deck.cpp | UTF-8 | 789 | 3.609375 | 4 | [] | no_license | #include "Deck.h"
#include <iostream>
#include <algorithm>
#include <cassert>
Deck::Deck()
{
int card = 0;
for (int suit = 0; suit < Card::MAX_SUITS; ++suit)
{
for (int rank = 0; rank < Card::MAX_RANKS; ++rank)
{
m_deck[card] = Card(static_cast<Card::CardRank>(rank), static_cast<Card::CardSuit>(suit));
++card;
}
}
}
void Deck::swapCards(Card &card1, Card &card2)
{
std::swap(card1, card2);
}
void Deck::printDeck() const
{
for (const auto &card : m_deck)
{
card.printCard();
std::cout << " ";
}
std::cout << std::endl;
}
void Deck::shuffleDeck()
{
for (int i = 0; i < 52; ++i)
{
int randomCard = rand() % 51;
swapCards(m_deck[i], m_deck[randomCard]);
}
}
const Card& Deck::dealCard()
{
assert(m_cardIndex < 52);
return m_deck[m_cardIndex++];
}
| true |
65d881394095b31d4ef343be5706853a3e4b1fe9 | C++ | panda3d/panda3d | /panda/src/express/virtualFileMount.cxx | UTF-8 | 9,644 | 2.578125 | 3 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | /**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file virtualFileMount.cxx
* @author drose
* @date 2002-08-03
*/
#include "virtualFileMount.h"
#include "virtualFileSimple.h"
#include "virtualFileSystem.h"
#include "zStream.h"
using std::iostream;
using std::istream;
using std::ostream;
using std::string;
TypeHandle VirtualFileMount::_type_handle;
/**
*
*/
VirtualFileMount::
~VirtualFileMount() {
nassertv(_file_system == nullptr);
}
/**
* Constructs and returns a new VirtualFile instance that corresponds to the
* indicated filename within this mount point. The returned VirtualFile
* object does not imply that the given file actually exists; but if the file
* does exist, then the handle can be used to read it.
*/
PT(VirtualFile) VirtualFileMount::
make_virtual_file(const Filename &local_filename,
const Filename &original_filename, bool implicit_pz_file,
int open_flags) {
Filename local(local_filename);
if (original_filename.is_text()) {
local.set_text();
} else {
local.set_binary();
}
PT(VirtualFileSimple) file =
new VirtualFileSimple(this, local, implicit_pz_file, open_flags);
file->set_original_filename(original_filename);
if ((open_flags & VirtualFileSystem::OF_create_file) != 0) {
create_file(local);
} else if ((open_flags & VirtualFileSystem::OF_make_directory) != 0) {
make_directory(local);
}
return file;
}
/**
* Attempts to create the indicated file within the mount, if it does not
* already exist. Returns true on success (or if the file already exists), or
* false if it cannot be created.
*/
bool VirtualFileMount::
create_file(const Filename &file) {
return false;
}
/**
* Attempts to delete the indicated file or directory within the mount. This
* can remove a single file or an empty directory. It will not remove a
* nonempty directory. Returns true on success, false on failure.
*/
bool VirtualFileMount::
delete_file(const Filename &file) {
return false;
}
/**
* Attempts to rename the contents of the indicated file to the indicated
* file. Both filenames will be within the mount. Returns true on success,
* false on failure. If this returns false, this will be attempted again with
* a copy-and-delete operation.
*/
bool VirtualFileMount::
rename_file(const Filename &orig_filename, const Filename &new_filename) {
return false;
}
/**
* Attempts to copy the contents of the indicated file to the indicated file.
* Both filenames will be within the mount. Returns true on success, false on
* failure. If this returns false, the copy will be performed by explicit
* read-and-write operations.
*/
bool VirtualFileMount::
copy_file(const Filename &orig_filename, const Filename &new_filename) {
return false;
}
/**
* Attempts to create the indicated file within the mount, if it does not
* already exist. Returns true on success, or false if it cannot be created.
* If the directory already existed prior to this call, may return either true
* or false.
*/
bool VirtualFileMount::
make_directory(const Filename &file) {
return false;
}
/**
* Returns true if the named file or directory may be written to, false
* otherwise.
*/
bool VirtualFileMount::
is_writable(const Filename &file) const {
return false;
}
/**
* Fills up the indicated pvector with the contents of the file, if it is a
* regular file. Returns true on success, false otherwise.
*/
bool VirtualFileMount::
read_file(const Filename &file, bool do_uncompress,
vector_uchar &result) const {
result.clear();
istream *in = open_read_file(file, do_uncompress);
if (in == nullptr) {
express_cat.info()
<< "Unable to read " << file << "\n";
return false;
}
std::streamsize file_size = get_file_size(file, in);
if (file_size > 0) {
result.reserve((size_t)file_size);
}
bool okflag = VirtualFile::simple_read_file(in, result);
close_read_file(in);
if (!okflag) {
express_cat.info()
<< "Error while reading " << file << "\n";
}
return okflag;
}
/**
* Writes the indicated data to the file, if it is a writable file. Returns
* true on success, false otherwise.
*/
bool VirtualFileMount::
write_file(const Filename &file, bool do_compress,
const unsigned char *data, size_t data_size) {
ostream *out = open_write_file(file, do_compress, true);
if (out == nullptr) {
express_cat.info()
<< "Unable to write " << file << "\n";
return false;
}
out->write((const char *)data, data_size);
bool okflag = (!out->fail());
close_write_file(out);
if (!okflag) {
express_cat.info()
<< "Error while writing " << file << "\n";
}
return okflag;
}
/**
* Opens the file for reading. Returns a newly allocated istream on success
* (which you should eventually delete when you are done reading). Returns
* NULL on failure.
*
* If do_uncompress is true, the file is also decompressed on-the-fly using
* zlib.
*/
istream *VirtualFileMount::
open_read_file(const Filename &file, bool do_uncompress) const {
istream *result = open_read_file(file);
#ifdef HAVE_ZLIB
if (result != nullptr && do_uncompress) {
// We have to slip in a layer to decompress the file on the fly.
IDecompressStream *wrapper = new IDecompressStream(result, true);
result = wrapper;
}
#endif // HAVE_ZLIB
return result;
}
/**
* Closes a file opened by a previous call to open_read_file(). This really
* just deletes the istream pointer, but it is recommended to use this
* interface instead of deleting it explicitly, to help work around compiler
* issues.
*/
void VirtualFileMount::
close_read_file(istream *stream) const {
VirtualFileSystem::close_read_file(stream);
}
/**
* Opens the file for writing. Returns a newly allocated ostream on success
* (which you should eventually delete when you are done writing). Returns
* NULL on failure.
*/
ostream *VirtualFileMount::
open_write_file(const Filename &file, bool truncate) {
return nullptr;
}
/**
* Opens the file for writing. Returns a newly allocated ostream on success
* (which you should eventually delete when you are done writing). Returns
* NULL on failure.
*
* If do_compress is true, the file is also compressed on-the-fly using zlib.
*/
ostream *VirtualFileMount::
open_write_file(const Filename &file, bool do_compress, bool truncate) {
ostream *result = open_write_file(file, truncate);
#ifdef HAVE_ZLIB
if (result != nullptr && do_compress) {
// We have to slip in a layer to compress the file on the fly.
OCompressStream *wrapper = new OCompressStream(result, true);
result = wrapper;
}
#endif // HAVE_ZLIB
return result;
}
/**
* Works like open_write_file(), but the file is opened in append mode. Like
* open_write_file, the returned pointer should eventually be passed to
* close_write_file().
*/
ostream *VirtualFileMount::
open_append_file(const Filename &file) {
return nullptr;
}
/**
* Closes a file opened by a previous call to open_write_file(). This really
* just deletes the ostream pointer, but it is recommended to use this
* interface instead of deleting it explicitly, to help work around compiler
* issues.
*/
void VirtualFileMount::
close_write_file(ostream *stream) {
VirtualFileSystem::close_write_file(stream);
}
/**
* Opens the file for writing. Returns a newly allocated iostream on success
* (which you should eventually delete when you are done writing). Returns
* NULL on failure.
*/
iostream *VirtualFileMount::
open_read_write_file(const Filename &file, bool truncate) {
return nullptr;
}
/**
* Works like open_read_write_file(), but the file is opened in append mode.
* Like open_read_write_file, the returned pointer should eventually be passed
* to close_read_write_file().
*/
iostream *VirtualFileMount::
open_read_append_file(const Filename &file) {
return nullptr;
}
/**
* Closes a file opened by a previous call to open_read_write_file(). This
* really just deletes the iostream pointer, but it is recommended to use this
* interface instead of deleting it explicitly, to help work around compiler
* issues.
*/
void VirtualFileMount::
close_read_write_file(iostream *stream) {
VirtualFileSystem::close_read_write_file(stream);
}
/**
* Populates the SubfileInfo structure with the data representing where the
* file actually resides on disk, if this is knowable. Returns true if the
* file might reside on disk, and the info is populated, or false if it does
* not (or it is not known where the file resides), in which case the info is
* meaningless.
*/
bool VirtualFileMount::
get_system_info(const Filename &file, SubfileInfo &info) {
return false;
}
/**
* See Filename::atomic_compare_and_exchange_contents().
*/
bool VirtualFileMount::
atomic_compare_and_exchange_contents(const Filename &file, string &orig_contents,
const string &old_contents,
const string &new_contents) {
return false;
}
/**
* See Filename::atomic_read_contents().
*/
bool VirtualFileMount::
atomic_read_contents(const Filename &file, string &contents) const {
return false;
}
/**
*
*/
void VirtualFileMount::
output(ostream &out) const {
out << get_type();
}
/**
*
*/
void VirtualFileMount::
write(ostream &out) const {
out << *this << " on /" << get_mount_point() << "\n";
}
| true |
978247ddb76bfefd01267e92ede20fcad25a3c9b | C++ | viaduct/telim_tmsd | /value_event.h | UTF-8 | 884 | 2.640625 | 3 | [] | no_license | #pragma once
#include "value_alias.h"
namespace telimtmsd {
template <typename T> class Value;
template <typename T> class ValueSubject;
enum class ValueEventType : char
{
Set_B,
Set_A
};
template <typename T>
class ValueEvent
{
public:
using Type = ValueEventType;
ValueEvent(Value<T>* value, ValueSubject<T>* subject) :
m_value(value),
m_subject(subject)
{
}
void setType(Type value) { m_type = value; }
Type type() const { return m_type; }
auto value() const { return m_value; }
auto subject() const { return m_subject; }
bool isFromSubject() const { return m_subject; }
private:
Value<T>* m_value;
ValueSubject<T>* m_subject;
Type m_type;
};
using IntValueEvent = ValueEvent<IntValueAlias>;
using FloatValueEvent = ValueEvent<FloatValueAlias>;
using StringValueEvent = ValueEvent<StringValueAlias>;
using BoolValueEvent = ValueEvent<BoolValueAlias>;
}
| true |
9b1e45b37d0bde6aae4be62954364397863c1f90 | C++ | G-Reg26/TetrisCPP | /TetrisCPP/game.cpp | UTF-8 | 5,466 | 2.65625 | 3 | [] | no_license | #include "game.h"
Game::Game(int board[22][12], unsigned int boardHeight, unsigned int boardWidth, sf::Vector2f blockSize)
{
this->boardHeight = boardHeight;
this->boardWidth = boardWidth;
this->blockSize = blockSize;
for (int i = 0; i < this->boardHeight; i++) {
for (int j = 0; j < this->boardWidth; j++) {
this->board[i][j] = board[i][j];
if (this->board[i][j] == 1) {
sf::RectangleShape block = sf::RectangleShape(blockSize);
float x = blockSize.x * j;
float y = blockSize.y * i;
block.setPosition(sf::Vector2f(x, y));
block.setOutlineThickness(0.5f);
block.setOutlineColor(sf::Color::Black);
border.push_back(block);
}
}
}
speed = 1.0f;
timer = 1.0f;
inputBuffer = 0.0f;
left = false;
right = false;
space = false;
resetTetromino();
}
void Game::update(float dT)
{
timer += dT * speed;
// reset board
for (int i = 1; i < boardHeight - 1; i++) {
for (int j = 1; j < boardWidth - 1; j++) {
if (board[i][j] != 1) {
board[i][j] = 0;
}
}
}
int y = tetrominoPos.y;
int x = tetrominoPos.x;
input(dT, x);
collsionCheck(x, y);
if (y < 0) {
gameOver();
return;
}
bool stopPiece = false;
for (int i = y; i < y + 4; i++) {
for (int j = x; j < x + 4; j++) {
if (i >= 1) {
if (tetromino.getTetromino()[i - y][j - x] == 2) {
if (board[i + 1][j] == 1) {
stopPiece = true;
}
board[i][j] = 2;
}
}
}
}
//printBoard();
if ((int)timer >= 1) {
checkBoard();
tetrominoPos.y++;
if (stopPiece) {
for (int i = y; i < y + 4; i++) {
for (int j = x; j < x + 4; j++) {
if (board[i][j] == 2) {
board[i][j] = 1;
}
}
}
resetTetromino();
}
timer = 0.0f;
}
std::list<sf::RectangleShape>::iterator iterator = blocks.begin();
for (int i = 1; i < boardHeight - 1; i++) {
for (int j = 1; j < boardWidth - 1; j++) {
if (board[i][j] != 0) {
(*iterator).setPosition(sf::Vector2f(j * blockSize.x, i * blockSize.y));
iterator++;
}
}
}
}
void Game::draw(sf::RenderWindow * window)
{
for (std::list<sf::RectangleShape>::iterator it = border.begin(); it != border.end(); it++) {
window->draw(*it);
}
for (std::list<sf::RectangleShape>::iterator it = blocks.begin(); it != blocks.end(); it++) {
window->draw(*it);
}
}
void Game::input(float dT, int &x) {
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) {
speed = 5.0f;
}
else {
speed = 1.0f;
}
// move left and right
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A) && !right) {
left = true;
if (inputBuffer == 0.0f) {
x--;
}
inputBuffer += dT;
if (inputBuffer > 0.2f) {
inputBuffer = 0.0f;
}
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::D) && !left) {
right = true;
if (inputBuffer == 0.0f) {
x++;
}
inputBuffer += dT;
if (inputBuffer > 0.2f) {
inputBuffer = 0.0f;
}
}
else {
left = false;
right = false;
inputBuffer = 0.0f;
}
// rotate piece
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) {
if (!space) {
tetromino.rotate();
space = true;
}
}
else {
space = false;
}
}
void Game::resetTetromino()
{
tetromino.setTetromino(&blocks);
tetrominoPos = sf::Vector2i(boardWidth / 4, 1);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (tetromino.getTetromino()[i][j] == 2) {
sf::RectangleShape currentBlock = sf::RectangleShape(blockSize);
currentBlock.setOutlineThickness(0.5f);
currentBlock.setOutlineColor(sf::Color::Black);
blocks.push_back(currentBlock);
}
}
}
}
void Game::collsionCheck(int &x, int &y) {
for (int j = x; j < x + 4; j++) {
bool shiftLeft = false;
bool shiftRight = false;
for (int i = y; i < y + 4; i++) {
if (tetromino.getTetromino()[i - y][j - x] == 2) {
if (j < 1) { // tetromino block is out of bounds
shiftRight = true;
}
else if (j > 10) {
shiftLeft = true;
}
else {
if (board[i][j] == 1) { // target x position is on a block
if ((int)tetrominoPos.x > x) { // if moving left
shiftRight = true;
}
else if ((int)tetrominoPos.x < x) {
shiftLeft = true;
}
}
}
}
}
if (shiftRight) {
x++;
}
else if (shiftLeft) {
x--;
}
}
tetrominoPos.x = x;
for (int i = y; i < y + 4; i++) {
bool shiftUp = false;
for (int j = x; j < x + 4; j++) {
if (j > 0 && j < 12) {
if (tetromino.getTetromino()[i - y][j - x] == 2 && board[i][j] == 1) {
shiftUp = true;
}
}
}
if (shiftUp) {
y--;
}
}
tetrominoPos.y = y;
}
void Game::printBoard() {
system("CLS");
for (int i = 0; i < 22; i++) {
for (int j = 0; j < 12; j++) {
std::cout << board[i][j];
}
std::cout << std::endl;
}
}
void Game::checkBoard()
{
for (int i = 1; i < 21; i++) {
int count = 0;
for (int j = 1; j < 11; j++) {
if (board[i][j] == 1) {
count++;
}
}
if (count == 10) {
shiftBoard(i);
for (int k = 0; k < 10; k++) {
blocks.pop_back();
}
}
}
}
void Game::shiftBoard(int i)
{
for (int y = i; y >= 1; y--) {
for (int x = 1; x < 11; x++) {
if (y > 1) {
board[y][x] = board[y - 1][x];
}
else {
board[y][x] = 0;
}
}
}
}
void Game::gameOver()
{
for (int i = 1; i < boardHeight - 1; i++) {
for (int j = 1; j < boardWidth - 1; j++) {
if (board[i][j] != 0) {
board[i][j] = 0;
}
}
}
int n = blocks.size();
for (int i = 0; i < n; i++) {
blocks.pop_back();
}
resetTetromino();
}
| true |
6401695c30b4cef55e4e2bbdb0514fe971d299e5 | C++ | SantoshDardige5121/Data-Structure-Assignment | /Assignment_8_Queue/8.cpp | UTF-8 | 1,699 | 4.21875 | 4 | [] | no_license | /*8. Write a program to implement queue using array. Implement functions for below operations.
a. Insert element in queue
b. Remove element from queue.
c. Print elements of queue.
d. Check if queue is full
e. Check if queue is empty.*/
#include<iostream>
using namespace std;
class Queue
{
int size;
int front,rear;
int arr[10];
public:
Queue();
Queue(int);
void insert(int);
void remove();
bool isfull();
bool isempty();
void display();
};
Queue::Queue()
{
int i;
size=4;
front=rear=-1;
for(int i=0;i<=size;i++)
{
arr[i]=0;
}
}
Queue::Queue(int s)
{
size=s;
}
void Queue::insert(int n)
{
int i,j;
//cout<<front<<"front-------Rear"<<rear<<endl;
if(!isfull())
{
if(front==-1)
{
front=0;
}
rear++;
arr[rear]=n;
}
else
{
cout<<"Overflow"<<endl;
}
// cout<<front<<"front-------Rear"<<rear<<endl;
}
void Queue::remove()
{
// cout<<front<<"front-------Rear"<<rear<<endl;
if(front < 4)
{
front++;
}
else
{
cout<<"underflow"<<endl;
}
// cout<<front<<"front-------Rear"<<rear<<endl;
}
void Queue::display()
{
for(int i=front;i<=rear;i++)
{
cout<<arr[i]<<"-->";
}
cout<<endl;
}
bool Queue::isfull()
{
return rear==size-1;
}
bool Queue::isempty()
{
return rear=front;
}
int main()
{
int ch,n;
Queue q;
while(1)
{
cout<<"Enter the option:"<<endl;
cout<<"1.Insert:"<<endl;
cout<<"2.Remove:"<<endl;
cout<<"3.Display:"<<endl;
cout<<"4.Exit."<<endl;
cin>>ch;
switch(ch)
{
case 1:
cout<<"Enter the Element:"<<endl;
cin>>n;
q.insert(n);
break;
case 2:
q.remove();
break;
case 3: q.display();
break;
case 4:
exit(0);
}
}
return 0;
}
| true |
f20f4441b9b888718f6321dc5ed9e33ac81e35d8 | C++ | ambroseL/Architecture_Pattern | /New/Classes/Controller/ObjSpawner.h | GB18030 | 664 | 2.703125 | 3 | [] | no_license | #ifndef _ObjSpawner_H_
#define _ObjSpawner_H_
#include "EntityObj.h"
/**
*
*
*#include "EntityObj.h"
*-llib
*
* ʵ
*
* @seesomething
*/
class ObjSpawner
{
EntityObj* prototype; /* ԭ */
public:
// ڿƺ
/**
*ι캯
*/
ObjSpawner(EntityObj* prototype);
/**
*
*/
~ObjSpawner();
//
/**
*
*/
EntityObj* spawnEntity();
/**
*÷ķԭ
*@parameter prototype
*/
void setPrototype(EntityObj* prototype);
};
#endif
| true |
e230c858c0f70a9848d92dcd167b52d579848f82 | C++ | wzx140/slice_image | /include/ImageRender.h | UTF-8 | 1,438 | 2.578125 | 3 | [] | no_license | //
// Created by wzx on 18-11-5.
//
#ifndef RELICE_MOUSE_IMAGERENDER_H
#define RELICE_MOUSE_IMAGERENDER_H
#include <vtkRenderWindowInteractor.h>
#include <vtkSmartPointer.h>
#include <vtkImageReslice.h>
#include "ImageInteractionCallback.h"
/**
* render the image
*/
class ImageRender : public vtkObject {
private:
/**
* the path to load the image
*/
std::string path;
/**
* the interactor window class ImageInteractionCallback may use to refresh
*/
vtkSmartPointer<vtkRenderWindowInteractor> interactor;
/**
*used to slice the image, class ImageInteractionCallback may use it to update the slice
*/
vtkSmartPointer<vtkImageReslice> reslice;
public:
static ImageRender *New();
ImageRender();
/**
* set the path of the image
* @param path the path of the data
*/
void setPath(const std::string &path);
/**
* load the data, in order to pass the data to interactor
*/
void load();
/**
* add observer to listen mouse event
* @param callback the object must inherit vtkCommand
*/
void addObserver(vtkSmartPointer<ImageInteractionCallback> callback);
/**
* start to display in window
*/
void start();
const vtkSmartPointer<vtkRenderWindowInteractor> &getInteractor() const;
const vtkSmartPointer<vtkImageReslice> &getReslice() const;
};
#endif //RELICE_MOUSE_IMAGERENDER_H
| true |
a77b4fe53c5b8d498ac5f6685af7145146bbdc84 | C++ | sachinsinghsk13/Data-Structures-And-Algorithms-C-CPP-2020 | /dsa.cpp | UTF-8 | 382 | 2.640625 | 3 | [] | no_license | #include <iostream>
#include "tree/splay-tree.h"
using namespace std;
int main()
{
splay_tree t;
t.insert(24, 10);
t.insert(13, 11);
t.insert(17, 12);
t.insert(25, 13);
t.insert(34, 14);
t.insert(22, 15);
t.insert(20, 16);
t.insert(14, 17);
t.insert(29, 18);
cout << t.get_top() << endl; // 29
cout << t.search(25) << endl;
cout << t.get_top() << endl;
return 0;
} | true |
edd63b9722e149d4d55dead5f9d6274b48e22795 | C++ | pushpender673/GKSSudoPlacementSolutions | /painterPartitionProblem_binarySearch/painterPartitionProblem.cpp | UTF-8 | 910 | 2.796875 | 3 | [] | no_license |
#include<bits/stdc++.h>
using namespace std;
#define nl printf("\n")
int painterPartitionB(int a[], int n,int k){
int hi = accumulate(a,a+n,0);
int lo = *max_element(a,a+n);
// printf("low : %d hi:%d\n",lo,hi);
while(lo<hi){
int x = lo+(hi-lo)/2;
int required_worker=1, curr_workload=0;
for(int i =0;i<n;i++){
if((curr_workload+a[i]) <=x)
{
curr_workload+=a[i];
} else {
curr_workload = a[i];
++required_worker;
}
}
if(required_worker<=k){
hi = x;
} else {
lo = x+1;
}
}
return lo;
}
int main()
{
int t;
cin>>t;
while(t--){
int k,n;
cin>>k>>n;
int a[n];
for(int i =0;i<n;i++)
{
cin>>a[i];
}
printf("%d\n", painterPartitionB(a,n,k));
}
return 0;
}
| true |
63ce28962e42a609df766d1c9b20f8919b0fa580 | C++ | jinto/fakesat | /fsat.cpp | UTF-8 | 1,211 | 2.890625 | 3 | [] | no_license | /*
* Fake Sat
*/
#include <QApplication>
#include <QPushButton>
#include <QWidget>
#include <QTimer>
#include <QMouseEvent>
#include "sky.h"
#define TIMER_GAP (10)
Sky::Sky(int atimer_gap, char* imgfile, QWidget *parent) : QWidget(parent)
{
QPalette palette;
palette.setBrush(this->backgroundRole(), QBrush(QImage(imgfile)));
this->setPalette(palette);
pos_x = 0;
pos_y = 0;
this->timer_gap = atimer_gap;
}
void Sky::moveSat()
{
pos_x++;
pos_y++;
update();
}
void Sky::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Escape) {
qApp->quit();
}
else{
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(moveSat()));
timer->start(timer_gap);
}
}
void Sky::paintEvent(QPaintEvent * /* event */)
{
QPainter painter(this);
QPen pen(Qt::white, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
painter.setPen(pen);
painter.drawPoint(pos_x,pos_y);
}
int main(int argc, char *argv[])
{
if (argc < 3) {
printf("Usage: fakesat timer_gap background.jpg\n\n");
return -1;
}
QApplication app(argc, argv);
int timer_gap = atoi(argv[1]);
Sky sky(timer_gap, argv[2]);
sky.showFullScreen();
sky.show();
return app.exec();
}
| true |
097c506b32370fcf78b91fe46432bb025f175aed | C++ | atonmbiak/projects | /praktikum9/websocketclient.h | UTF-8 | 1,126 | 2.546875 | 3 | [] | no_license | #ifndef WEBSOCKETCLIENT_H
#define WEBSOCKETCLIENT_H
#include <QTCore>
#include <QtWebSockets/QtWebSockets>
class WebSocketClient : public QObject
{
Q_OBJECT
Q_PROPERTY(bool connecting READ connecting NOTIFY stateChanged)
Q_PROPERTY(bool connected READ connected NOTIFY stateChanged)
Q_PROPERTY(QString username READ username WRITE setUsername NOTIFY usernameChanged)
Q_PROPERTY(QString url READ url WRITE setUrl NOTIFY urlChanged)
QWebSocket m_socket;
QString m_username;
QString m_url;
public:
explicit WebSocketClient(QObject*parent = 0);
virtual ~WebSocketClient();
Q_INVOKABLE void sendMessage(const QString &textMessage);
Q_INVOKABLE void open();
Q_INVOKABLE void close();
bool connecting() const;
bool connected() const;
QString username() const;
void setUsername(QString username);
QString url() const;
void setUrl(QString url);
signals:
void newMessageReceived(QJsonObject messageObject);
void stateChanged();
void usernameChanged(QString username);
void urlChanged(QString url);
};
#endif // WEBSOCKETCLIENT_H
| true |
e25d37ce75fa96a765907da4eea94e3ba56c9583 | C++ | Greenclonk/World-of-Files | /WorldOfFiles/FileWorld.cpp | UTF-8 | 1,302 | 2.890625 | 3 | [] | no_license | #include "pch.h"
#include "Gameplay/FileWorld.h"
#include <fstream>
FileWorld::FileWorld()
{
name = L"invalid";
places = std::vector<Place>();
}
FileWorld::FileWorld(String _name, std::vector<Place> _places)
{
name = _name;
places = std::vector<Place>(_places);
}
String FileWorld::GetWorldName()
{
return name;
}
std::vector<Place> FileWorld::GetPlaces()
{
return places;
}
Place FileWorld::GetPlaceAt(int _ID)
{
for (std::vector<Place>::iterator it = places.begin(); it != places.end(); it++)
{
if ((*it).GetID() == _ID)
{
return (*it);
}
}
return Place();
}
Place FileWorld::GetPlaceCalled(String _name)
{
for (std::vector<Place>::iterator it = places.begin(); it != places.end(); it++)
{
if ((*it).GetName() == _name)
{
return (*it);
}
}
return Place();
}
Place::Place()
{
ID = -1;
name = L"invalid";
description = L"invalid";
connections = std::vector<int>();
}
Place::Place(int _ID, String _name, String _description, std::vector<int> _places)
{
ID = _ID;
name = _name;
description = _description;
connections = std::vector<int>(_places);
}
String Place::GetName()
{
return name;
}
String Place::GetDescription()
{
return description;
}
int Place::GetID()
{
return ID;
}
std::vector<int> Place::GetConnections()
{
return connections;
}
| true |
6357ba16b0e58ccd7ba849fb412b99425c91b3e3 | C++ | CJunette/CPP_Learning | /008/课程/8.2_OperatorOverload_001/8.2_OperatorOverload_001/8.2_OperatorOverload_001.cpp | UTF-8 | 2,359 | 4.0625 | 4 | [] | no_license | // 8.2_OperatorOverload_001.cpp : This file contains the 'main' function. Program execution begins and ends there.
//运算符重载的相关内容
//运算符重载只能重载已有的运算符。重载不会改变运算符的优先级。
//另外成员访问运算符“.”、成员指针运算符“.*”、作用域分辨符“::”、三目运算符“?:”不能被重载。
//重载可以将运算符重载为类的非静态成员函数,也可以重载为类外的非成员函数。
//首先讨论将双目运算符重载为类的非静态成员函数。
//对于任意双目操作符B,有表达式“oprd1 B oprd2”,其中oprd1为A类对象,则B应该被重载为A类的成员函数(如果A类不是自定义类而是基本类型,则需要将B重载为非成员函数),形参类型应该是oprd2所属的类型。
//经过重载后,上述表达式相当于“oprd1.operator B(oprd2)”。
#include <iostream>
using namespace std;
class Complex
{
public:
Complex(double real = 0, double imagine = 0):
real(real), imag(imagine)
{
}
//重载运算符时,“operator”和运算符中间需要有一个空格。形参表中的参数个数是原有的操作数个数减1(后置单目运算符除外。)
Complex operator +(const Complex &c) const
{
double r = real + c.real;
double i = imag + c.imag;
return Complex(r, i);
}
Complex operator -(const Complex &c) const
{
double r = real - c.real;
double i = imag - c.imag;
return Complex(r, i);
}
//关于虚数与实数的运算符重载。
Complex operator +(double const &r) const
{
double re = real + r;
return Complex(re, imag);
}
Complex operator -(double const &r) const
{
double re = real - r;
return Complex(re, imag);
}
void display() const
{
cout << "(" << real << ", " << imag << ")" << endl;
}
private:
double real;
double imag;
};
int main()
{
Complex c1(5, 4), c2(2, 10), c3;
cout << "c1 = ";
c1.display();
cout << "c2 = ";
c2.display();
c3 = c1 - c2;
cout << "c3 = c1 - c2 = ";
c3.display();
c3 = c1 + c2;
cout << "c3 = c1 + c2 = ";
c3.display();
c3 = c1 + 1;
cout << "c3 = c1 + 1 = ";
c3.display();
}
| true |
810f82a89d894b3333098d09bb43ff16a604cdf5 | C++ | CharLLCH/works_of_CPlusPlus | /build_qsort/build_qsort.hpp | UTF-8 | 21,987 | 3.421875 | 3 | [] | no_license | /**
* @file build_qsort.hpp
* trying to build a better quick sort.
*/
#ifndef _build_qsort_mm_h_
#define _build_qsort_mm_h_ 1
#include <functional>
#include <algorithm>
#include <iterator>
/****************************************************************************
* the quick sort algorithm is conceptually very simple, yet at the same time
* can be tricky to implement correctly and efficiently.
*
* the main problem is that the running time of quick sort in the worst case
* is quadratic. a secondary problem is that some authors of quick sort test
* their creation using only uniformly distributed randomized sequences,
* accidentally avoiding worst case behavior.
*
* the algorithm is: select a value (the pivot) from the sequence, divide the
* sequence into to subsequences predicated on each element's relation to the
* pivot value. repeat for subsequences.
****************************************************************************/
/****************************************************************************
* partitioning.
*
* partitioning is the core of the quicksort algorithm. there are numerous
* partitioning functions that behave in their own unique ways.
*
* the functions here take a comparison functor to make them more general,
* but for discussion we will assume the comparison is always less<int>().
*
* quicksort is very particular about the behavior of the partition function.
* the partition it expects is [ less or equal | greater or equal ].
*
* this does not mean we cannot make it work with other types of partitions,
* but it will usually require special handling of edge cases.
*
* @note as long as pivot is within the minimum and maximum values of the
* sequence being partitioned, these functions will never return last, since
* some value will always be not-less than the pivot.
****************************************************************************/
template<typename For, typename Cmp>
For partition_standard(For first, For last,
typename std::iterator_traits<For>::value_type pivot, Cmp comp)
/* partition.
*
* @note this is what std::partition does as far as behavior. the signature
* has been changed to take an argument and comparison object instead of a
* predicate, but is equivalent to,
*
* std::partition(first, last, std::bind2nd(comp, pivot));
*
* the partiton generated is [ less | not-less ], unfortunately this is not
* what the quicksort algorithm specifies, but we can still make it work.
*
* @note this function is not used, instead we will use std::partition.
*/
{
first = std::find_if_not(first, last, std::bind2nd(comp, pivot));
for ( For next = first; next != last; ++next )
if (comp(*next, pivot))
{
std::iter_swap(first, next);
++first;
}
return first;
}
template<typename Ran, typename Cmp>
Ran partition_squeeze(Ran first, Ran last,
typename std::iterator_traits<Ran>::value_type pivot, Cmp comp)
/* bi-directional partition.
*
* @note this is an unguarded partition (i.e. pivot must be within minimum
* and maximum sequence values; sequence length is not zero).
*
* for this to converge as used in quicksort, this must never return first.
* the easiest way to enforce this, is to not use *first as the pivot.
*
* however, *first may be used if it is not the lowest value or not unique.
* median of three enforces this automatically.
*
* @note this function behaves as specified by the quicksort algorithm,
* (i.e. [ less or equal | greater or equal ]).
*/
{
while ( true )
{
while ( comp(*first, pivot) )
++first;
--last;
while ( comp(pivot, *last) )
--last;
if (first < last)
std::iter_swap(first, last);
else
return first;
++first;
}
}
template <typename For, typename Cmp>
std::pair<For, For>
partition3_forward(For first, For last,
typename std::iterator_traits<For>::value_type pivot, Cmp comp)
/* forward 3-way partitioning.
*
* @note 3-way partitioning is a technique used to improve performance when
* a sequence contains many identical keys. in the case of all equal keys,
* quicksort using 3-way partition will complete in linear time.
*
* normally the subsequences share a boundary, here values equal to pivot
* are already in final sorted order, therefore, they may be omitted from
* further evaluation (i.e. the sequence [lower,upper)).
*
* @return iterator pair specifying equal range for values equal to pivot.
*/
{
For lower = std::partition(first, last, std::bind2nd(comp, pivot));
For upper = std::partition(lower, last,
std::not1(std::bind1st(comp, pivot)));
return std::pair<For, For>(lower, upper);
}
template <typename Bi, typename Cmp>
std::pair<Bi, Bi>
partition3_dijkstra(Bi first, Bi last,
typename std::iterator_traits<Bi>::value_type pivot, Cmp comp)
/* Dijkstra 3-way partitioning.
*
* @note all of the optimizations i've tried to apply actually make this
* run slower (e.g. find_first_not).
*
* @return iterator pair specifying equal range for values equal to pivot.
*/
{
for ( Bi next = first; next != last; )
if (comp(pivot, *next))
{
std::iter_swap(next, --last);
}
else
{
if (comp(*next, pivot))
{
std::iter_swap(next, first);
++first;
}
++next;
}
return std::pair<Bi, Bi>(first, last);
}
template <typename Ran, typename Cmp>
std::pair<Ran, Ran>
partition3_bentley_mcilroy(Ran first, Ran last,
typename std::iterator_traits<Ran>::value_type pivot, Cmp comp)
/* Bentley-McIlroy 3-way partitioning.
*
* @note this is an unguarded partition (i.e. pivot must be within minimum
* and maximum sequence values; sequence length is not zero).
*
* this generates the partition in two parts. first values less and greater
* are partitioned, any equal values encountered are moved to the edges of
* the sequence. the second stage rotates the equal values into position.
*
* 1st: [ equal | less | greater | equal ]
* 2nd: [ less | equal | equal | greater ]
*
* @return iterator pair specifying equal range for values equal to pivot.
*/
{
Ran l_head = first;
Ran l_tail = first;
Ran r_head = last;
Ran r_tail = last;
while ( true )
{
while (comp(*l_tail, pivot))
++l_tail;
--r_head;
while (comp(pivot, *r_head))
--r_head;
if (l_tail < r_head)
std::iter_swap(l_tail, r_head);
else
break;
// compact equal to sequence front.
if (!comp(*l_tail, pivot))
{
std::iter_swap(l_tail, l_head);
++l_head;
}
// compact equal to sequence back.
if (!comp(pivot, *r_head))
{
--r_tail;
std::iter_swap(r_head, r_tail);
}
++l_tail;
}
// adjust right head.
//
// @note loop exited before swap. r_head references a value less than
// or equal to pivot; increment to correct.
++r_head;
// rotate equal to partition points.
//
// @note if head and tail are equal, then all elements are equal to
// pivot; omit swaps, set range to sequence limits.
if (l_head == l_tail)
l_tail = first;
else
{
while ( first != l_head )
std::iter_swap(--l_head, --l_tail);
}
if (r_head == r_tail)
r_head = last;
else
{
while ( r_tail != last )
std::iter_swap(r_tail++, r_head++);
}
return std::pair<Ran, Ran>(l_tail, r_head);
}
/****************************************************************************
* pivot selection.
*
* ideally the pivot would be the actual median value. unfortunately the best
* way to find it, is to perform a sort on the sequence and select the middle
* value. since sorting is the problem we're trying to solve, this is not an
* option.
*
* there are selection methods that are able to locate the median in linear
* time, however, they are complex enough that in practice they usually give
* negative gains.
*
* about the best we can do efficiently, is to try and avoid selecting the
* worst pivot at each level. there are two common solutions.
*
* the first is stochastic sampling (selecting an element at random with all
* elements having an equal probablility of being chosen), which has been
* shown to avoid worst case with high probablility.
*
* the second is median selection (selecting a number of samples and using
* some heuristic determine the best choice), the most common being median of
* three. this works well with sorted and reverse sorted inputs.
*
* implementations may use combinations of these. there is a lot of room for
* experimentation in pivot selection. try new things.
****************************************************************************/
template<typename Ran>
inline Ran iter_random(Ran first, Ran last)
/* stochastic sampling.
*
* @note while this is easy to implement and does a good job at avoiding
* worst case partitions, it also does a good job of avoiding best case.
* because pivot selection is completely random, no consideration is given
* to ordering.
*
* by using std::rand() this function has side effects. this should usually
* be avoided in library code.
*/
{
return first + std::rand() % (last - first);
}
template<typename In, typename Cmp>
inline In iter_median_3(In a, In b, In c, Cmp comp)
/* median of three selection.
*
* @note this is less resistant to some patterns, but in the average case
* performs very well. unlike randomized selection, this tries to estimate
* the actual median value.
*
* @note this function expects iterators to reference valid objects.
*/
{
auto it_comp = [comp] (In a, In b) { return comp(*a, *b); };
if (comp(*b, *c))
return std::min(std::max(a, b, it_comp), c, it_comp);
else
return std::max(std::min(a, b, it_comp), c, it_comp);
}
template<typename Ran, typename Cmp>
inline Ran iter_median_9(Ran first, Ran split, Ran last, Cmp comp)
/* median of nine selection.
*
* @note takes more samples in an attempt to estimate the median value.
* this improves the estimate and further insulates from problematic
* patterns, and may be stacked even more (i.e. median of twelve,
* twenty-seven, etc.).
*
* thresholds are those specified by Bentley & McIlroy.
*
* @note this function accepts a range. split is expected to be the
* sequence midpoint (i.e. (last - first) / 2).
*/
{
if (last - first <= 7)
return split;
if (last - first <= 40)
return iter_median_3(first, split, last-1, comp);
auto d = (last - first) / 8;
Ran a = iter_median_3(first, first+d, first+d*2, comp);
Ran b = iter_median_3(split-d, split, split+d, comp);
Ran c = iter_median_3(last-d*2, last-d, last-1, comp);
return iter_median_3(a, b, c, comp);
}
/****************************************************************************
* quicksort implementation.
*
* the following functions are used as test cases. the signatures have been
* changed to accept an indent parameter to allow for 'pretty printing' when
* viewing partitions as binary trees.
****************************************************************************/
#include <iostream>
#include <iomanip>
template<typename For>
void print_partition(For first, For last, int indent)
/* output partition data. */
{
#ifdef BUILD_QSORT_PRINT_PARTITION
typedef typename std::iterator_traits<For>::value_type value_type;
if (indent)
std::cout << std::setw(indent) << ' ';
std::copy(first, last, std::ostream_iterator<value_type>(std::cout, " "));
std::cout << std::endl;
#endif
}
template<typename Ran>
void qsort_v1(Ran first, Ran last, int indent = 0)
/* quicksort (base implementation).
*
* @note this uses naive pivot selection and std::partition, which doesn't
* have the specified behavior and must be corrected for.
*
* unfortunately this is the version i see most often. unless a variety of
* test cases are used, one might be fooled into thinking this version is
* good enough. it isn't.
*
* if all keys are equal, this function's running time is quadratic.
*/
{
typedef typename std::iterator_traits<Ran>::value_type value_type;
// sequence of size <= 1 is already sorted (base case).
if (last - first <= 1)
return;
// select pivot.
//
// @note we select the middle element here. this will work better
// when dealing with sorted sequences, and although problem cases are
// less common than when using the first element, it's still a poor
// choice.
Ran pivot = first + (last - first)/2;
// save pivot.
//
// @note we can safely swap the pivot to the rear of the sequence
// and expect it to remain in place (element is already in sorted
// position and will not be moved).
std::iter_swap(pivot, last-1);
// partition. lower bound with respect to pivot.
//
// @note we skip evaluating the last element, but it's not a
// requirement for correct operation (element is already in sorted
// position and will not be moved).
Ran lower = std::partition(first, last-1,
std::bind2nd(std::less<value_type>(), *(last-1)));
Ran upper = lower+1;
// restore pivot.
//
// @note by replacing this element we're sort of doing a halfassed
// version of 3-way partitioning, where we only worry about the
// placement of one element.
//
// this allows us to skip this element in future iterations, and
// it's what guarantees this version of quicksort will converge.
std::iter_swap(lower, last-1);
// view partition (preorder).
//
// @note allows us to view partitions in tree structure.
print_partition(first, last, indent);
// repeat for subsequences.
qsort_v1(first, lower, indent);
qsort_v1(upper, last, indent + (upper-first)*2);
}
template<typename Ran>
void qsort_v2(Ran first, Ran last, int indent = 0)
/* quicksort (specified partition).
*
* @note this uses the squeeze partition which has the behavior specified
* by the algorithm.
*
* the squeeze also improves running time when all keys are equal. in the
* case of identical keys this function's running time is n*log(n).
*/
{
typedef typename std::iterator_traits<Ran>::value_type value_type;
if (last - first <= 1)
return;
// select pivot.
Ran pivot = first + (last - first)/2;
// partition.
//
// @note notice there is no need to shuffle anything around to
// guarantee convergance.
Ran lower = partition_squeeze(first, last, *pivot,
std::less<value_type>());
Ran upper = lower;
// view partition (preorder).
print_partition(first, last, indent);
// repeat for subsequences.
qsort_v2(first, lower, indent);
qsort_v2(upper, last, indent + (upper-first)*2);
}
template<typename Ran>
void qsort_v3(Ran first, Ran last, int indent = 0)
/* quick sort (3-way partition).
*
* @note 3-way partitioning improves running time when all keys are equal.
* in the case of identical keys this function's running time is linear.
*/
{
typedef typename std::iterator_traits<Ran>::value_type value_type;
if (last - first <= 1)
return;
// select pivot.
Ran pivot = first + (last - first)/2;
// partition.
//
// @note this returns a range specifying the equal range (upper/lower
// bound) for elements equal to pivot.
std::pair<Ran, Ran> eq = partition3_forward(first, last, *pivot,
std::less<value_type>());
// view partition (preorder).
print_partition(first, last, indent);
// repeat for subsequences.
//
// @note omitting the sequence [eq.first,eq.second).
qsort_v3(first, eq.first, indent);
qsort_v3(eq.second, last, indent + (eq.second-first)*2);
}
template<typename Ran>
void qsort_v4(Ran first, Ran last, int indent = 0)
/* quicksort (3-way partition, median of three pivot selection).
*
* @note this uses the same partition as version 3, only improving pivot
* selection to demonstrate the difference it can make.
*/
{
typedef typename std::iterator_traits<Ran>::value_type value_type;
if (last - first <= 1)
return;
// sequence midpoint.
Ran split = first + (last - first)/2;
// select pivot.
//
// @note using median of three selection.
Ran pivot = iter_median_3(first, split, last-1,
std::less<value_type>());
// swap pivot to sequence midpoint.
//
// @note many versions don't do this. sometimes (not always) this can
// make a big difference. since this is an estimate of the actual
// median, it makes sense to place it at the midpoint.
std::iter_swap(pivot, split);
pivot = split;
// partition.
//
// @note same partition as version 3.
std::pair<Ran, Ran> eq = partition3_forward(first, last, *pivot,
std::less<value_type>());
// view partition (preorder).
print_partition(first, last, indent);
// repeat for subsequences.
qsort_v4(first, eq.first, indent);
qsort_v4(eq.second, last, indent + (eq.second-first)*2);
}
template<typename Ran>
void qsort_v5(Ran first, Ran last, int indent = 0)
/* quicksort (3-way partition, randomized pivot selection).
*
* @note this is the one function that we will be using randomized pivot
* selection with, only because this particular algorithm seems to do so
* much better with it.
*/
{
typedef typename std::iterator_traits<Ran>::value_type value_type;
if (last - first <= 1)
return;
// select pivot.
//
// @note randomization gets much better results in this case over
// median of three selection.
//
// we don't do any swapping like with median of three because we know
// nothing about this value or how it relates to the sequence.
Ran pivot = iter_random(first, last);
// partition.
//
// @note using Dijkstra 3-way partition.
std::pair<Ran, Ran> eq = partition3_dijkstra(first, last, *pivot,
std::less<value_type>());
// view partition (preorder).
print_partition(first, last, indent);
// repeat for subsequences.
qsort_v5(first, eq.first, indent);
qsort_v5(eq.second, last, indent + (eq.second-first)*2);
}
template<typename Ran>
void qsort_v6(Ran first, Ran last, int indent = 0)
/* quicksort (3-way partition, median of nine pivot selection).
*
* @note this uses what is considered the fastest 3-way partition scheme,
* along with the median selection recommend for this algorithm.
*/
{
typedef typename std::iterator_traits<Ran>::value_type value_type;
if (last - first <= 1)
return;
// sequence midpoint.
Ran split = first + (last - first)/2;
// select pivot.
//
// @note using median of nine selection. notice we don't swap the
// pivot to the midpoint; does not make a difference in this case
// (does when using median of three).
Ran pivot = iter_median_9(first, split, last,
std::less<value_type>());
// partition.
//
// @note using Bentley-McIlroy 3-way partition.
std::pair<Ran, Ran> eq = partition3_bentley_mcilroy(first, last,
*pivot, std::less<value_type>());
// view partition (preorder).
print_partition(first, last, indent);
// repeat for subsequences.
qsort_v6(first, eq.first, indent);
qsort_v6(eq.second, last, indent + (eq.second-first)*2);
}
/****************************************************************************
* final notes.
*
* you may be suprised when you see the final implementation of quicksort
* (@see qsort.hpp) at some of the choices that have been made. the reason it
* is not a copy of version 6 here, is that while version 6 may perform best
* within the test suite, the suite is designed to generate sequences that
* intentionally break quicksort - these are not the common case.
*
* any quicksort function should perform reasonably well in all test cases,
* but you should not tune your code for these. tune your code on real world
* data sets, then use the test suite to verify you haven't made any breaking
* changes.
*
* the final quicksort performs better than version 6 in the average case,
* and the code is small and simple, which is a plus IMO when it comes to
* templated code that must appear in header files.
*
* the techniques that it implements that were not covered here are, switch
* to insertion sort for small sequences and monitering depth and switching
* to heap sort (std::partial_sort) when some threshold is exceeded. (i.e.
* implements introspective sort). the insertion sort is the final version
* from the build_isort project (also available on PSC).
****************************************************************************/
/****************************************************************************
* implementation notes.
*
* some implementations prefer to swap the pivot with some sequence element,
* use a reference to that element as the pivot during partitioning, and
* afterwards swap the pivot element to it's final position (@see qsort_v1).
*
* i believe this is an outmoded trick from the 70's that saves a tiny amount
* of memory and a single comparison, but creates aliasing issues that are of
* more concern in modern programming, therefore, taking a local temporary is
* prefered here.
*
* ...
*
* if you've studied quicksort, chances are, you've seen every algorithm used
* here, only in different form, since most implementations use indexing with
* inclusive sequences.
*
* here we use pointers and exclusive sequences, and while this may initially
* seem confusing, i believe this is a superior way to implement these
* algorithms in C and C++.
*
* using pointers directly, allow us to track fewer variables than indexing,
* are easier to generalize in C and are simple to translate to iterators in
* C++.
*
* sequences here are more naturally represented as exclusive. the partition
* function returns a shared boundary(s). the inclusive model needs special
* adjustment to correct overlapping and 'out of range' boundaries for both
* internal and initial user calls.
****************************************************************************/
#endif // _build_qsort_mm_h_
| true |
fec467bcbb2a5893010560c2a305048530aa4113 | C++ | youlive789/AlgorithmStudy | /BackJoon/sort/11931.cpp | UTF-8 | 429 | 3.296875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int count;
cin >> count;
vector<int> container;
while (count--) {
int tmp;
cin >> tmp;
container.push_back(tmp);
}
sort(container.begin(), container.end(), greater<int>());
for (auto ele : container) {
cout << ele << "\n";
}
return 0;
} | true |
243dbe7b6d5fe603a8b5b7ecf627f743a29740d5 | C++ | hbrulin/CPP_Modules | /tests/operator/main.cpp | UTF-8 | 860 | 3.40625 | 3 | [] | no_license | #include "duree.hpp"
using namespace std;
int main()
{
Duree duree1(0, 10, 28), duree2(0, 15, 2);
if (duree1 == duree2)
{
cout << "Les durees sont égales" << endl;
}
else
{
cout << "Les durees ne sont pas égales" << endl;
}
if (duree1 != duree2)
{
cout << "Les durees ne sont toujours pas égales" << endl;
}
if (duree1 < duree2)
{
cout << "Duree1 est inférieure à Duree2" << endl;
}
if (duree2 > duree1)
{
cout << "Duree2 est supérieure à Duree1" << endl;
}
Duree duree3(11, 10, 10), duree4(10, 10, 10);
if (duree3 <= duree4)
{
cout << "Duree3 est inférieure ou égale à Duree4" << endl;
}
if (duree3 >= duree4)
{
cout << "Duree3 est supérieure ou égale à Duree4" << endl;
}
return (0);
} | true |
1f063259056eca0c409f76950dc4195f97694b39 | C++ | macczy/SceneBuilder | /SceneBuilder/Objects/TernaryExpression.h | UTF-8 | 846 | 2.953125 | 3 | [] | no_license | #pragma once
#include <string>
#include "../Util/Token.h"
#include "LogicalExpression.h"
#include "Expression.h"
class TernaryExpression {
public:
TernaryExpression(const Position& position, LogicalSubExpressionPtr& condition, Expression& ifTrue, Expression& ifFalse)
: condition(std::move(condition)), expressionIfTrue(std::move(ifTrue)), expressionIfFalse(std::move(ifFalse)), position(position) {};
const Expression& getTrueExpression() const { return expressionIfTrue; }
const Expression& getFalseExpression() const { return expressionIfFalse; }
const LogicalSubExpression* getCondition() const { return condition.get(); }
const Position& getPosition() const { return position; }
~TernaryExpression() {};
private:
Position position;
LogicalSubExpressionPtr condition;
Expression expressionIfTrue;
Expression expressionIfFalse;
}; | true |
d758c32f1ac7b1565f8afbace58e92a8ca1023e1 | C++ | evchin/sql | /includes/bplustree/multimap.h | UTF-8 | 4,937 | 3.3125 | 3 | [] | no_license | /*
* Author: Evelyn Chin
* Project: Map + Multimap
* Project Purpose: A Map / Multimap Class built up from a BPlusTree class.
* File Purpose: Multimap Interface.
*/
#ifndef MULTIMAP_H
#define MULTIMAP_H
#include "bplustree.h"
template <typename K, typename V>
struct MPair
{
K key;
vector<V> value_list;
MPair(const K& k=K()) : key(k) {}
MPair(const K& k, const V& v) : key(k)
{
value_list += v;
}
MPair(const K& k, const vector<V>& vlist) : key(k), value_list(vlist) {}
MPair& operator+=(const V& value)
{
value_list += value;
return *this;
}
MPair& operator+=(const vector<V>& values)
{
value_list += values;
return *this;
}
friend ostream& operator <<(ostream& outs, const MPair<K, V>& print_me)
{
outs << "(" << print_me.key << ", " << print_me.value_list << ")";
return outs;
}
friend bool operator ==(const MPair<K, V>& lhs, const MPair<K, V>& rhs)
{
return lhs.key == rhs.key;
}
friend bool operator !=(const MPair<K, V>& lhs, const MPair<K, V>& rhs)
{
return lhs.key != rhs.key;
}
friend bool operator < (const MPair<K, V>& lhs, const MPair<K, V>& rhs)
{
return lhs.key < rhs.key;
}
friend bool operator <= (const MPair<K, V>& lhs, const MPair<K, V>& rhs)
{
return lhs.key <= rhs.key;
}
friend bool operator > (const MPair<K, V>& lhs, const MPair<K, V>& rhs)
{
return lhs.key > rhs.key;
}
friend bool operator >= (const MPair<K, V>& lhs, const MPair<K, V>& rhs)
{
return lhs.key >= rhs.key;
}
friend MPair<K, V> operator + (const MPair<K, V>& lhs, const MPair<K, V>& rhs)
{
assert(lhs.key == rhs.key);
return MPair<K, V>(lhs.key, lhs.value + rhs.value);
}
};
template <typename K, typename V>
class MMap
{
public:
typedef BPlusTree<MPair<K, V> > map_base;
class Iterator
{
public:
friend class MMap;
Iterator(typename map_base::Iterator it) : _it(it) {}
bool null()
{
return _it.is_null();
}
Iterator operator ++(int unused)
{
Iterator temp(_it);
_it++;
return temp;
}
Iterator operator ++()
{
_it++;
return *this;
}
MPair<K, V> operator *()
{
return *_it;
}
friend bool operator ==(const Iterator& lhs, const Iterator& rhs)
{
return lhs._it == rhs._it;
}
friend bool operator !=(const Iterator& lhs, const Iterator& rhs)
{
return lhs._it != rhs._it;
}
private:
typename map_base::Iterator _it;
};
MMap(){}
// Iterators
Iterator begin()
{
return Iterator(mmap.begin());
}
Iterator end()
{
return Iterator(mmap.end());
}
// Capacity
int size() const
{
return mmap.size();
}
bool empty() const
{
return mmap.empty();
}
// Element Access
const vector<V>& operator[](const K& key) const
{
MPair<K, V> pair(key);
return mmap.get(pair).value_list;
}
vector<V>& operator[](const K& key)
{
MPair<K, V> pair(key);
return mmap.get(pair).value_list;
}
// Modifiers
void insert(const K& k, const V& v)
{
MPair<K, V> pair(k, v);
Iterator it(mmap.find(pair));
if (!it.null()) get(k) += v;
else mmap.insert(pair);
}
void erase(const K& key)
{
mmap.remove(MPair<K, V>(key));
}
void clear()
{
mmap.clear_tree();
}
// Operations:
bool contains(const K& key) const
{
return mmap.contains(MPair<K, V>(key));
}
vector<V>& get(const K& key)
{
return mmap.get(MPair<K, V>(key)).value_list;
}
Iterator find(const K& key)
{
return mmap.find(MPair<K, V>(key));
}
int count(const K& key)
{
Iterator it(mmap.find(MPair<K,V>(key)));
if (it._it == nullptr) return 0;
return (*it).value_list.size();
}
bool is_valid()
{
return mmap.is_valid();
}
Iterator lower_bound(const K& key)
{
return Iterator(mmap.lower_bound(key));
}
Iterator upper_bound(const K& key)
{
return Iterator(mmap.upper_bound(key));
}
// equal_range
friend ostream& operator<<(ostream& outs, const MMap<K, V>& print_me)
{
outs<<print_me.mmap<<endl;
return outs;
}
void print_lookup()
{
int width = 10;
for (Iterator it = begin(); it != end(); it++)
{
cout << setw(width) << (*it).key << " : ";
cout << (*it).value_list << endl;
}
}
private:
BPlusTree<MPair<K, V> > mmap;
};
#endif // MULTIMAP_H | true |
579d8b3180ef2b0ea2d76b8eefad197a14b13f66 | C++ | mge-engine/mge | /src/mge/graphics/swap_chain.hpp | UTF-8 | 686 | 2.609375 | 3 | [
"MIT"
] | permissive | // mge - Modern Game Engine
// Copyright (c) 2017-2023 by Alexander Schroeder
// All rights reserved.
#pragma once
#include "mge/graphics/context_object.hpp"
namespace mge {
/**
* @brief A swap chain is a series of virtual frame buffers.
*
* Commonly, a swap chain is used for frame rate stabilization
* by using double, or even triple buffering.
*/
class MGEGRAPHICS_EXPORT swap_chain : public context_object
{
protected:
explicit swap_chain(render_context& context);
public:
virtual ~swap_chain();
/**
* @brief Presents the next frame buffer.
*/
virtual void present() = 0;
};
} // namespace mge | true |
f1ca49006eb91d0517ef044f6ede3151b078b3ff | C++ | Fuma13/CPHEngineProject | /Project01/FourDirectionsMovement.cpp | UTF-8 | 1,730 | 2.984375 | 3 | [] | no_license | #include "FourDirectionsMovement_InputWord.h"
FourDirectionsMovement_InputWord::FourDirectionsMovement_InputWord(int count_gameStates) : InputWord(count_gameStates)
{
x_velocity = 0;
y_velocity = 0;
}
InputEvent* FourDirectionsMovement_InputWord::update(SDL_Event _event)
{
FourDirectionsMovement_InputEvent* fourDirectionalMovementEvent = new FourDirectionsMovement_InputEvent();
event_current = _event;
switch(_event.type)
{
case SDL_KEYDOWN:
switch (_event.key.keysym.sym)
{
//north
case SDLK_w:
y_velocity = -1;
break;
//east
case SDLK_d:
x_velocity = 1;
break;
//south
case SDLK_s:
y_velocity = 1;
break;
//west
case SDLK_a:
x_velocity = -1;
break;
default:
break;
}
break;
case SDL_KEYUP:
switch(_event.key.keysym.sym){
case SDLK_w:
if( y_velocity < 0 )
y_velocity = 0;
break;
case SDLK_d:
if( x_velocity > 0 )
x_velocity = 0;
break;
case SDLK_s:
if( y_velocity > 0 )
y_velocity = 0;
break;
case SDLK_a:
if( x_velocity < 0 )
x_velocity = 0;
break;
default:
break;
}
break;
default:
// TODO warn that an event that is not useful has been sent, and this should not happen!!!
cout << "WARNING: An InputWord has received an input event that is not handled in the switch/case" << endl;
break;
}
fourDirectionalMovementEvent->set_x_velocity(x_velocity);
fourDirectionalMovementEvent->set_y_velocity(y_velocity);
fourDirectionalMovementEvent->set_eventHasOccured(true);
return fourDirectionalMovementEvent;
}
| true |
7e417265fc5dcb2df0aea6e24993b30b46969708 | C++ | Coffier/SoftRender | /SoftRender/Draw.h | GB18030 | 9,468 | 2.703125 | 3 | [] | no_license |
#ifndef DRAW_H
#define DRAW_H
#include "FrameBuffer.h"
#include "Model.h"
#include "Camera.h"
#include "Clip.h"
#include "BlinnPhongShader.h"
enum RenderMode {
Line,
Fill
};
enum Face {
Back,
Front
};
//Ⱦ
//ͼԪ
class Draw {
private:
int Width;
int Height;
FrameBuffer *FrontBuffer;
std::vector<glm::vec4> ViewPlanes;
bool faceCull;
Face cullMod;
RenderMode renderMod;
public:
Draw(const int &w, const int &h) :
Width(w),Height(h),
FrontBuffer(nullptr),
faceCull(false),
cullMod(Back),
renderMod(Fill)
{
ViewPlanes.resize(6, glm::vec4(0));
}
~Draw(){
if (FrontBuffer)
delete FrontBuffer;
FrontBuffer = nullptr;
}
void Init() {
if (FrontBuffer)
delete FrontBuffer;
FrontBuffer = new FrameBuffer(Width, Height);
}
void Resize(const int& w, const int &h) {
Width = w;
Height = h;
FrontBuffer->Resize(w, h);
}
void ClearBuffer(const glm::vec4 &color) {
FrontBuffer->ClearColorBuffer(color);
}
#pragma region Statemachine
void EnableCull(Face f) {
faceCull = true;
cullMod = f;
}
void DisableCull() {
faceCull = false;
}
void changeRenderMode() {
if (renderMod == Fill)
renderMod = Line;
else
renderMod = Fill;
}
void UpdateViewPlanes() {
ViewingFrustumPlanes(ViewPlanes, ProjectMatrix * ViewMatrix);
}
#pragma endregion Statemachine
#pragma region Pipeline
//ӳ
void PerspectiveDivision(V2F & v) {
v.windowPos /= v.windowPos.w;
v.windowPos.w = 1.0f;
v.windowPos.z = (v.windowPos.z + 1.0) * 0.5;
}
//ռ
bool ViewCull(const glm::vec4 &v1, const glm::vec4 &v2, const glm::vec4 &v3) {
glm::vec3 minPoint, maxPoint;
minPoint.x = min(v1.x, min(v2.x, v3.x));
minPoint.y = min(v1.y, min(v2.y, v3.y));
minPoint.z = min(v1.z, min(v2.z, v3.z));
maxPoint.x = max(v1.x, max(v2.x, v3.x));
maxPoint.y = max(v1.y, max(v2.y, v3.y));
maxPoint.z = max(v1.z, max(v2.z, v3.z));
// Near Far ʱֻȫڵ
if (!Point2Plane(minPoint, ViewPlanes[4]) || !Point2Plane(maxPoint, ViewPlanes[4])) {
return false;
}
if (!Point2Plane(minPoint, ViewPlanes[5]) || !Point2Plane(maxPoint, ViewPlanes[5])) {
return false;
}
if (!Point2Plane(minPoint, ViewPlanes[0]) && !Point2Plane(maxPoint, ViewPlanes[0])) {
return false;
}
if (!Point2Plane(minPoint, ViewPlanes[1]) && !Point2Plane(maxPoint, ViewPlanes[1])) {
return false;
}
if (!Point2Plane(minPoint, ViewPlanes[2]) && !Point2Plane(maxPoint, ViewPlanes[2])) {
return false;
}
if (!Point2Plane(minPoint, ViewPlanes[3]) && !Point2Plane(maxPoint, ViewPlanes[3])) {
return false;
}
return true;
}
//
bool FaceCull(Face face, const glm::vec4 &v1, const glm::vec4 &v2, const glm::vec4 &v3) {
glm::vec3 tmp1 = glm::vec3(v2.x - v1.x, v2.y - v1.y, v2.z - v1.z);
glm::vec3 tmp2 = glm::vec3(v3.x - v1.x, v3.y - v1.y, v3.z - v1.z);
//˵õ
glm::vec3 normal = glm::normalize(glm::cross(tmp1, tmp2));
glm::vec3 view = glm::normalize(glm::vec3(v1.x - camera->Position.x, v1.y - camera->Position.y, v1.z - camera->Position.z));
if (cullMod == Back)
return glm::dot(normal, view) < 0;
else
return glm::dot(normal, view) > 0;
}
void DrawModel(Model &model) {
for (int i = 0; i < model.objects.size(); i++) {
DrawObject(model.objects[i]);
}
}
void DrawObject(Object &obj) {
if (obj.mesh.EBO.empty()) {
return;
}
currentMat = &obj.material;
for (int i = 0; i < obj.mesh.EBO.size(); i += 3) {
Vertex p1, p2, p3;
p1 = obj.mesh.VBO[obj.mesh.EBO[i]];
p2 = obj.mesh.VBO[obj.mesh.EBO[i + 1]];
p3 = obj.mesh.VBO[obj.mesh.EBO[i + 2]];
V2F v1, v2, v3;
v1 = currentMat->shader->VertexShader(p1);
v2 = currentMat->shader->VertexShader(p2);
v3 = currentMat->shader->VertexShader(p3);
if (!ViewCull(v1.worldPos / v1.Z, v2.worldPos / v2.Z, v3.worldPos / v3.Z)) {
continue;
}
//ӳ 任NDC
PerspectiveDivision(v1);
PerspectiveDivision(v2);
PerspectiveDivision(v3);
//üɶ
std::vector<V2F> clipingVertexs = SutherlandHodgeman(v1, v2, v3);
//յ
int n = clipingVertexs.size() - 3 + 1;
for (int i = 0; i < n; i++) {
V2F v1 = clipingVertexs[0];
V2F v2 = clipingVertexs[i + 1];
V2F v3 = clipingVertexs[i + 2];
v1.windowPos = ViewPortMatrix * v1.windowPos;
v2.windowPos = ViewPortMatrix * v2.windowPos;
v3.windowPos = ViewPortMatrix * v3.windowPos;
//
if (faceCull && !FaceCull(Back, v1.worldPos / v1.Z, v2.worldPos / v2.Z, v3.worldPos / v3.Z)) {
continue;
}
if (renderMod == Line) {
DrawLine(v1, v2);
DrawLine(v2, v3);
DrawLine(v3, v1);
}
else {
ScanLineTriangle(v1, v2, v3);
}
}
}
}
void Show() {
glDrawPixels(Width, Height, GL_RGBA, GL_UNSIGNED_BYTE, FrontBuffer->colorBuffer.data());
}
#pragma endregion Pipeline
#pragma region Rasterization
//ɨ㷨
//ΣΪƽ
void ScanLineTriangle(const V2F &v1, const V2F &v2, const V2F &v3) {
std::vector<V2F> arr = { v1,v2,v3 };
if (arr[0].windowPos.y > arr[1].windowPos.y) {
V2F tmp = arr[0];
arr[0] = arr[1];
arr[1] = tmp;
}
if (arr[1].windowPos.y > arr[2].windowPos.y) {
V2F tmp = arr[1];
arr[1] = arr[2];
arr[2] = tmp;
}
if (arr[0].windowPos.y > arr[1].windowPos.y) {
V2F tmp = arr[0];
arr[0] = arr[1];
arr[1] = tmp;
}
//arr[0] arr[2]
//мȣǵ
if (equal(arr[1].windowPos.y, arr[2].windowPos.y)) {
DownTriangle(arr[1], arr[2], arr[0]);
}//
else if (equal(arr[1].windowPos.y, arr[0].windowPos.y)) {
UpTriangle(arr[1], arr[0], arr[2]);
}
else {
float weight = (arr[2].windowPos.y - arr[1].windowPos.y) / (arr[2].windowPos.y - arr[0].windowPos.y);
V2F newEdge = V2F::lerp(arr[2], arr[0], weight);
UpTriangle(arr[1], newEdge, arr[2]);
DownTriangle(arr[1], newEdge, arr[0]);
}
}
void UpTriangle(const V2F &v1, const V2F &v2, const V2F &v3) {
V2F left, right, top;
left = v1.windowPos.x > v2.windowPos.x ? v2 : v1;
right = v1.windowPos.x > v2.windowPos.x ? v1 : v2;
top = v3;
left.windowPos.x = int(left.windowPos.x);
int dy = top.windowPos.y - left.windowPos.y;
int nowY = top.windowPos.y;
//²ֵ
for (int i = dy; i >= 0; i--) {
float weight = 0;
if (dy != 0) {
weight = (float)i / dy;
}
V2F newLeft = V2F::lerp(left, top, weight);
V2F newRight = V2F::lerp(right, top, weight);
newLeft.windowPos.x = int(newLeft.windowPos.x);
newRight.windowPos.x = int(newRight.windowPos.x + 0.5);
newLeft.windowPos.y = newRight.windowPos.y = nowY;
ScanLine(newLeft, newRight);
nowY--;
}
}
void DownTriangle(const V2F &v1, const V2F &v2, const V2F &v3) {
V2F left, right, bottom;
left = v1.windowPos.x > v2.windowPos.x ? v2 : v1;
right = v1.windowPos.x > v2.windowPos.x ? v1 : v2;
bottom = v3;
int dy = left.windowPos.y - bottom.windowPos.y;
int nowY = left.windowPos.y;
//²ֵ
for (int i = 0; i < dy; i++) {
float weight = 0;
if (dy != 0) {
weight = (float)i / dy;
}
V2F newLeft = V2F::lerp(left, bottom, weight);
V2F newRight = V2F::lerp(right, bottom, weight);
newLeft.windowPos.x = int(newLeft.windowPos.x);
newRight.windowPos.x = int(newRight.windowPos.x + 0.5);
newLeft.windowPos.y = newRight.windowPos.y = nowY;
ScanLine(newLeft, newRight);
nowY--;
}
}
void ScanLine(const V2F &left, const V2F &right) {
int length = right.windowPos.x - left.windowPos.x;
for (int i = 0; i < length; i++) {
V2F v = V2F::lerp(left, right, (float)i / length);
v.windowPos.x = left.windowPos.x + i;
v.windowPos.y = left.windowPos.y;
//Ȳ
float depth = FrontBuffer->GetDepth(v.windowPos.x, v.windowPos.y);
if (v.windowPos.z < depth) {
float z = v.Z;
v.worldPos /= z;
v.texcoord /= z;
v.color /= z;
v.normal /= z;
FrontBuffer->WritePoint(v.windowPos.x, v.windowPos.y, currentMat->shader->FragmentShader(v));
FrontBuffer->WriteDepth(v.windowPos.x, v.windowPos.y, v.windowPos.z);
}
}
}
//bresenhamLine 㷨
void DrawLine(const V2F &from, const V2F &to)
{
int dx = to.windowPos.x - from.windowPos.x;
int dy = to.windowPos.y - from.windowPos.y;
int Xstep = 1, Ystep = 1;
if (dx < 0)
{
Xstep = -1;
dx = -dx;
}
if (dy < 0)
{
Ystep = -1;
dy = -dy;
}
int currentX = from.windowPos.x;
int currentY = from.windowPos.y;
V2F tmp;
//бС1
if (dy <= dx)
{
int P = 2 * dy - dx;
for (int i = 0; i <= dx; ++i)
{
tmp = V2F::lerp(from, to, ((float)(i) / dx));
FrontBuffer->WritePoint(currentX, currentY, glm::vec4(255, 0, 0, 0));
currentX += Xstep;
if (P <= 0)
P += 2 * dy;
else
{
currentY += Ystep;
P += 2 * (dy - dx);
}
}
}
//бʴ1öԳԻ
else
{
int P = 2 * dx - dy;
for (int i = 0; i <= dy; ++i)
{
tmp = V2F::lerp(from, to, ((float)(i) / dy));
FrontBuffer->WritePoint(currentX, currentY, glm::vec4(255, 0, 0, 0));
currentY += Ystep;
if (P <= 0)
P += 2 * dx;
else
{
currentX += Xstep;
P -= 2 * (dy - dx);
}
}
}
}
#pragma endregion Rasterization
};
#endif | true |
9a1993ec1efd5fba03f173c7c022cf4285729772 | C++ | fly8wo/Code---- | /code/试图变a.cpp | UTF-8 | 129 | 3.0625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int a = 34;
a=a*5;
cout<<a<<endl;
return 0;
}
| true |
93b8b46914bff22231ef3502d125484ab0d1322a | C++ | waghaditya/SmartPal | /Arduino/MQTT.ino | UTF-8 | 1,849 | 2.859375 | 3 | [] | no_license |
char* string2char(String command){
if(command.length()!=0){
char *p = const_cast<char*>(command.c_str());
return p;
}
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
// if(String(topic) == str_mac){
// // Switch on the LED if an 1 was received as first character
// if ((char)payload[0] == '1') {
// digitalWrite(RELAY, LOW); // Turn the LED on (Note that LOW is the voltage level
// // but actually the LED is on; this is because
// // it is active low on the ESP-01)
// stat = 1;
// }
// else if((char)payload[0] =='0') {
// stat = 0;
// digitalWrite(RELAY, HIGH); // Turn the LED off by making the voltage HIGH
// }
// }
}
void setup_mqtt(){
find_mac();
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");
client.subscribe(string2char(str_mac));
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void mqtt_check_connection(){
if (!client.connected()) {
reconnect();
}
client.loop();
}
void mqtt_send(String topic,String msg){
client.publish(string2char(topic),string2char(msg));
}
| true |
e212d0518ecf596b721a20f3420e8a01f42e413e | C++ | giaosame/LeetCode | /solutions1-50/problem21.cpp | UTF-8 | 456 | 3.5625 | 4 | [] | no_license | // 21. Merge Two Sorted Lists
#include "../utils.h"
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode pre_head(0);
ListNode * pre = &pre_head;
while (l1 && l2)
{
if (l1->val < l2->val)
{
pre->next = l1;
l1 = l1->next;
}
else
{
pre->next = l2;
l2 = l2->next;
}
pre = pre->next;
}
if (l1)
pre->next = l1;
if (l2)
pre->next = l2;
return pre_head.next;
}
}; | true |
1bfacc7fae17aaabecd5c2857ff0acc7cf101364 | C++ | donhenton/code-attic | /cpp/micropather/ModelManager.cpp | UTF-8 | 4,150 | 2.546875 | 3 | [] | no_license | #include "StdAfx.h"
#include ".\modelmanager.h"
#include "XYTrace.h"
#include <stdio.h>
#include <math.h>
#include <vector>
CModelManager::CModelManager(void)
{
m_quads = NULL;
int m_width = 0;
int m_height = 0;
m_currentStartIdx = m_currentEndIdx = -1;
}
CModelManager::~CModelManager(void)
{
if (m_quads)
{
delete [] m_quads;
m_quads = NULL;
}
}
void CModelManager::Init(int width, int height)
{
m_width = width;
m_height = height;
//char info[128];
int v = 0;
m_quads = new CMapQuad[m_width * m_height];
for(int j=0;j<m_height;j++)
{
for(int i=0;i<m_width;i++)
{
m_quads[j*m_width + i].m_x = i;
m_quads[j*m_width + i].m_y = j;
v = j*m_width + i;
m_quads[j*m_width + i].m_id = v;
//sprintf(info,"idx %d (%d,%d)\n",v,i,j);
//WriteTrace(TraceDebug,_T(info));
}
}
}
void CModelManager::processSelect(int row, int col, int selectType)
{
/*
global
int const MAP_SETUP = 0;
int const MARK_START = 1;
int const MARK_END = 2;
int const DRAW_PATH = 3;
*/
CMapQuad* currentQuad = &m_quads[col*m_width + row];
switch(selectType)
{
case MAP_SETUP:
if (currentQuad->m_state == STATE_EMPTY)
{
currentQuad->m_state = STATE_GREEN;
break;
}
if (currentQuad->m_state == STATE_GREEN)
{
currentQuad->m_state = STATE_YELLOW;
break;
}
if (currentQuad->m_state == STATE_YELLOW)
{
currentQuad->m_state = STATE_RED;
break;
}
if (currentQuad->m_state == STATE_RED)
{
currentQuad->m_state = STATE_EMPTY;
break;
}
break;
case MARK_START:
currentQuad->m_state = STATE_START;
if (m_currentStartIdx > -1)
m_quads[m_currentStartIdx].m_state = STATE_EMPTY;
m_currentStartIdx = col*m_width + row;
break;
case MARK_END:
currentQuad->m_state = STATE_END;
if (m_currentEndIdx > -1)
m_quads[m_currentEndIdx].m_state = STATE_EMPTY;
m_currentEndIdx = col*m_width + row;
break;
}
}
int CModelManager::getStateForCell(int row, int col)
{
return m_quads[col*m_width + row].m_state;
}
POINT CModelManager::getStartLocation()
{
POINT newPoint;
newPoint.x = newPoint.y = -1;
if (this->m_currentStartIdx > -1)
{
newPoint.x = m_quads[m_currentStartIdx].m_x;
newPoint.y = m_quads[m_currentStartIdx].m_y;
}
return newPoint;
}
POINT CModelManager::getEndLocation()
{
POINT newPoint;
newPoint.x = newPoint.y = -1;
if (this->m_currentEndIdx > -1)
{
newPoint.x = m_quads[m_currentEndIdx].m_x;
newPoint.y = m_quads[m_currentEndIdx].m_y;
}
return newPoint;
}
float CModelManager::LeastCostEstimate( void* nodeStart, void* nodeEnd )
{
float estimate = 0.0f;
CMapQuad* endQuad = (CMapQuad*) nodeEnd;
CMapQuad* startQuad = (CMapQuad*) nodeStart;
int dx = startQuad->m_x - endQuad->m_x;
int dy = startQuad->m_y - endQuad->m_y;
estimate = (float) sqrt( (double)(dx*dx) + (double)(dy*dy) );
return estimate;
}
void CModelManager::PrintStateInfo(void * quadptr)
{
CMapQuad* quad = (CMapQuad*) quadptr;
quad->PrintStateInfo();
}
void CModelManager::AdjacentCost(void *node,vector<StateCost> *neighbors)
{
const int dx[4] = { 1, 0, -1, 0 };
const int dy[4] = { 0, 1, 0, -1 };
CMapQuad* quad = (CMapQuad*) node;
for( int i=0; i<4; ++i )
{
int nx = quad->m_x + dx[i];
int ny = quad->m_y + dy[i];
if (nx < 0 || ny < 0 || nx >= m_width || ny >= m_height || quad->m_state == STATE_RED)
{
//not a neighbor
}
else
{
CMapQuad* neighborQuad = getQuad(nx,ny);
float penalty = neighborQuad->getPenalty();
StateCost nodeCost = {(void *) neighborQuad,penalty };
neighbors->push_back( nodeCost );
}
}
}
CMapQuad* CModelManager::getQuad(int row, int col)
{
return &m_quads[col*m_width + row];
}
void CModelManager::resetModel(void)
{
m_currentEndIdx = m_currentStartIdx = -1;
for(int j=0;j< m_height;j++)
{
for(int i=0;i<m_width;i++)
{
getQuad(i,j)->m_state = STATE_EMPTY;
}
}
}
| true |
3084c0edefa5b79b5c2d6bc938b45186080c6c94 | C++ | dragonfly9113/learn_advanced_cpluplus_programming | /Sec8_C++11_Amazing_Features/Object.cpp | UTF-8 | 259 | 3.125 | 3 | [
"MIT"
] | permissive | // Name : Object.cpp
#include <iostream>
using namespace std;
class Test {
int id{3};
string name{"Mike"};
public:
void print() {
cout << id << ": " << name << endl;
}
};
int main() {
Test test;
test.print();
return 0;
}
| true |
11fd3c25fd484e740e1846b910a8fd7510df6790 | C++ | jgillham/AwesomeRobot | /exp/armCTRL/armctrl.cpp | UTF-8 | 2,761 | 2.59375 | 3 | [] | no_license | /**
Notes:
Is this arduino code? No
Sends angles down through the serial port to the arduino.
*/
#include "opencv2/opencv.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
#include <cmath>
#include <SerialStream.h>
using namespace LibSerial;
using namespace std;
using namespace cv;
int RRR(double xn, double yn);
void open();
int canny_threshold = 50;
SerialStream ardu;
int main(int argc, char** argv)
{
VideoCapture cap(0);
// if( !cap.isOpened());
// return -1;
namedWindow( "test",1);
Mat frame;
while(1)
{
cap >> frame;
if(frame.empty())
break;
imshow( "test", frame);
if(waitKey(30) >= 0) break;
}
Mat src_gray;
// frame = imread("filename000.jpg");
/// Convert it to gray
cvtColor( frame, src_gray, CV_BGR2GRAY );
/// Reduce the noise so we avoid false circle detection
GaussianBlur( src_gray, src_gray, Size(9, 9), 2, 2 );
vector<Vec3f> circles;
/// Apply the Hough Transform to find the circles
HoughCircles( src_gray, circles, CV_HOUGH_GRADIENT, 1, src_gray.rows/8, canny_threshold, 100, 0, 0 );
/// Draw the circles detected
for( size_t i = 0; i < circles.size(); i++ )
{
Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
int radius = cvRound(circles[i][2]);
// cout << circles[i][0] / 33 -5<< "," << circles[i][1] / 33;
// circle center
circle( frame, center, 3, Scalar(0,255,0), -1, 8, 0 );
// circle outline
circle( frame, center, radius, Scalar(0,0,255), 3, 8, 0 );
}
/// Show your results
namedWindow( "Hough Circle Transform Demo", CV_WINDOW_AUTOSIZE );
imshow( "Hough Circle Transform Demo", frame );
cout << 5 - circles[0][0] / 33 << "," << circles[0][1] / 33 << "\n";
RRR(5 - circles[0][0] / 33, circles[0][1] / 33);
waitKey(0);
return 0;
}
int RRR(double xn, double yn)
{
double x, y, z, r, s, D;
double theta1, theta2, theta3;
double a2 = 3.8, a3 = 5, d = 3.5;
// char inChar;
/* cout << "x: ";
cin >> x;
cout << "y: ";
cin >> y;
cout << "z: ";
cin >> z;*/
x = xn;
y = yn;
z = 0.8;
r = sqrt((x*x) + (y*y));
s = z - d;
theta1 = (atan2(y,x))*57.2957795;
D = ((r*r) + (s*s) -(a2*a2) - (a3*a3))/(2*a2*a3);
theta3 = atan2(-sqrt(1 - D*D),D);
theta2 = atan2(s, r) -atan2(a3*sin(theta3), a2+a3*cos(theta3));
open();
ardu << (int)theta1 << "," << (int)(90 -theta2 * 57.2957795) << ","
<< (int)(-theta3 *57.2957795)<< "f";
cout << (int)theta1 << "," << (int)(90 -theta2 * 57.2957795) << ","
<< (int)(-theta3 *57.2957795)<< "\n";
return 0;
}
void open()
{
ardu.Open("/dev/ttyACM0");
ardu.SetBaudRate(SerialStreamBuf::BAUD_9600);
ardu.SetCharSize(SerialStreamBuf::CHAR_SIZE_8);
}
| true |
6fc7e1a39b71595bfed331284e13280195481ea3 | C++ | cfleveratto/networkTowers | /List.h | UTF-8 | 2,475 | 3.84375 | 4 | [] | no_license | #ifndef INCLUDED_LIST
#define INCLUDED_LIST
#include <iostream>
using namespace std;
template <class T>
class List {
//Class Invarient(CI): elements points to an array of
//numElements objects allocated on the heap where
//numElements > 0;
//Otherwise elements points to NULL
private:
T * elements; //this will point to a list of T type
//objects allocated on the heap.
int numElements; //this will hold the amount of elements
public:
//PRE: None
//POST: this object is empty.
List<T> () {
elements = NULL;
numElements = 0;
};
//PRE: listMax is the maximum amount of T type objects in
//an array that elements points to.
List<T> (int listMax) {
elements = new T[listMax];
numElements = 0;
};
//PRE: L is a defined List<T> object
//POST: this object is a deep copy of L and has a satisfied CI.
List<T> (const List<T> & L) {
elements = new T[L.numElements];
for (int index = 0; (index < numElements); index++) {
elements[index] = L.elements[index];
}
numElements = L.numElements;
};
//PRE: L is a defined List<T> object
//POST: RV is a reference to a List object that is a deep
//copy of L.
List & operator = (const List<T> & L) {
if (numElements != 0) {
delete [] elements;
}
elements = new T[L.numElements];
for (int index = 0; (index < L.numElements); index++) {
elements[index] = L.elements[index];
}
numElements = L.numElements;
return (*this);
};
//PRE: element is a T type object
//POST: element was added to elements[index]
void addElement(const T & element, int index) {
elements[index] = element;
numElements++;
};
//deconstructor
//PRE: None
//POST: deletes the objects that are stored in an array
//that elements points to.
~List<T> () {
delete [] elements;
};
friend ofstream & operator << (ofstream & stream,
const List<T> & L) {
for (int index = 0; (index < L.numElements); index++) {
stream << "List Data"
<< L.elements[index] << endl;
}
stream << "List amount of elements: "
<< L.numElements << endl;
return (stream);
};
friend ostream & operator << (ostream & stream,
const List<T> & L) {
for (int index = 0; (index < L.numElements); index++) {
stream << "List Data: "
<< L.elements[index] << endl;
}
stream << "List amount of elements: "
<< L.numElements << endl;
return (stream);
};
};
#endif
| true |
f620eb99c1d1044e1b80e0207feb382faf4b7243 | C++ | omni-compiler/ClangXcodeML | /tests/run/new_array.src.cpp | UTF-8 | 270 | 3.09375 | 3 | [] | no_license | #include <stdio.h>
class ClassA {
public:
int member_i;
};
int
main() {
ClassA *pa = new ClassA[10];
for (int i = 0; i < 10; ++i) {
pa[i].member_i = i;
}
for (int i = 0; i < 10; ++i) {
printf("%d\n", pa[i].member_i);
}
delete[] pa;
return 0;
}
| true |
a6b30ff3336edc0b8b408bef4a679605e137dc1c | C++ | showmic96/Online-Judge-Solution | /LightOJ/1186/12168699_AC_4ms_1688kB.cpp | UTF-8 | 755 | 2.859375 | 3 | [] | no_license | // In the name of Allah the Most Merciful.
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(void)
{
int t , c = 0;
scanf("%d",&t);
while(t--){
int n;
scanf("%d",&n);
vector<int>v1 , v2;
for(int i=0;i<n;i++){
int in;
scanf("%d",&in);
v1.push_back(in);
}
for(int i=0;i<n;i++){
int in;
scanf("%d",&in);
v2.push_back(in);
}
int ans = 0;
for(int i=0;i<n;i++){
int temp = (v2[i]-v1[i]-1);
ans^=temp;
}
printf("Case %d: ",++c);
if(!ans)printf("black wins\n");
else printf("white wins\n");
}
return 0;
}
| true |
0a46adf12cc93ac547dc69ab5025e57ca1197bac | C++ | abhishek0410/Opencv | /04_Accessing_Pixels/main.cpp | UTF-8 | 1,845 | 3.1875 | 3 | [] | no_license | //In this experiment ,we are going to play with the individual pixels of the image.
#include<opencv2/opencv.hpp>
#include<stdint.h>
using namespace std;
using namespace cv ;
int main(){
/* //********UNCOMMENT TO SEE PART 1 ************
//Part 1 : In this part ,we are going to :
//1a : Load the image in grayscale
//1b : Transform the pixels , we will reduce the pixel intensity by 1/2 .
//1c : Display both the images side by side :
//1a :
Mat original = imread("sample.jpg",CV_LOAD_IMAGE_GRAYSCALE);
Mat modified = imread("sample.jpg",CV_LOAD_IMAGE_GRAYSCALE);
//1b.
for(int row = 0 ; row<modified.rows; row++){
for(int col = 0; col <modified.cols; col ++){
modified.at<uint8_t>(row,col) = modified.at<uint8_t>(row,col) * 0.5f;
}
}
//1c : Display both images :
namedWindow("Display1" , WINDOW_AUTOSIZE);
namedWindow("Display2" , WINDOW_AUTOSIZE);
imshow("Display1",original);
imshow("Display2",modified);
waitKey();
*/
//Part 2 ; Iterating over the colored object
//2a : Load the image in grayscale
//2b : Transform the pixels , we will reduce the pixel intensity by 1/2 .
//2c : Display both the images side by side :
//2a . Load the image
Mat original2 = imread("sample.jpg", CV_LOAD_IMAGE_COLOR);
Mat modified2 = imread("sample.jpg",CV_LOAD_IMAGE_COLOR);
//2b. Transform the image :
for(int row = 0 ; row< modified2.rows; row++){
for (int col = 0 ; col< modified2.cols; col++){
//Removing the blue color
modified2.at<cv::Vec3b>(row, col)[0] = modified2.at<cv::Vec3b>(row,col)[0] *0;
}
}
//2c. Displaying the image :
namedWindow("Display1" , WINDOW_AUTOSIZE);
namedWindow("Display2" , WINDOW_AUTOSIZE);
imshow("Display1",original2);
imshow("Display2",modified2);
waitKey();
return 0 ;
} | true |
5bb62ad1dafc6b74c74c511a10307a3cebe701e4 | C++ | Fajcon/JIMP | /lab7/arrayfill/ArrayFill.cpp | UTF-8 | 970 | 3.359375 | 3 | [] | no_license | //
// Created by ficon on 17.04.18.
//
#include <cstdlib>
#include "ArrayFill.h"
namespace arrays {
IncrementalFill::IncrementalFill(int start, int step) : start(start), step(step) {}
int IncrementalFill::Value(int index) const {
int result = start + index*step;
return result;
}
int UniformFill::Value(int index) const {
return value_;
}
RandomFill::RandomFill() {
}
int RandomFill::Value(int index) const {
std::rand();
return 0;
}
void FillArray(size_t size, const ArrayFill &filler, std::vector<int> *v) {
v->clear();
v->reserve(size);
for (size_t i = 0; i < size; i++) {
v->emplace_back(filler.Value(i));
}
}
SquaredFill::SquaredFill(int a , int b) {
a_ = a;
b_ = b;
}
int SquaredFill::Value(int index) const {
int result;
result = a_*(index*index)+b_;
return result;
}
} | true |
a6e21dbc2125f35e3ac4dddacbb84e467b0eba22 | C++ | alexmaraval/projecteuler | /project_euler_cpp/project_euler_cpp/pb023.cpp | UTF-8 | 1,985 | 3.84375 | 4 | [] | no_license | //
// pb023.cpp
// project_euler_cpp
//
// Created by Alexandre Maraval on 13.12.17.
// Copyright © 2017 Alexandre Maraval. All rights reserved.
//
#include "pb023.hpp"
bool is_abundant(int n)
{
// first find divisors and sum them
int sum = 0;
for(int i=1; i<n; i++)
{
if(n%i == 0)
{
sum += i;
}
}
// then compare it to n
return(sum > n);
}
void pb023()
{
std::vector<int> abundant_numbers = {};
std::vector<int> sum2abundant = {};
// find all abundant numbers below 28123
for(int i=1; i<28123; i++)
{
if(is_abundant(i))
{
abundant_numbers.push_back(i);
}
}
// record all sums of two abundant numbers s.t. the sum is lower than 28123
int absum = 0;
for(int i=0; i<abundant_numbers.size(); i++)
{
for(int j=i; j<abundant_numbers.size(); j++)
{
absum = abundant_numbers[i]+abundant_numbers[j];
if(absum <= 28123)
{
sum2abundant.push_back(absum);
}
}
}
// Method 1:
// creating a set object sorts and deletes the duplicates
// and dump it back into the original container
// std::set<int> absumset(sum2abundant.begin(), sum2abundant.end());
// sum2abundant.assign(absumset.begin(), absumset.end());
// Method 2:
// directly sort and erase duplicates using vector functions
std::sort(sum2abundant.begin(),sum2abundant.end());
sum2abundant.erase(std::unique(sum2abundant.begin(), sum2abundant.end()), sum2abundant.end());
int abindex = 0;
int solution = 0;
for(int i=1; i<=sum2abundant[sum2abundant.size()-1]; i++)
{
if(i == sum2abundant[abindex])
{
abindex++;
}
else
{
solution += i;
}
}
std::cout << "PB023 : sum of all numbers that cannot be written as the sum of tw abundant numbers is : 4179871" << std::endl;
}
| true |
043f4ceb9dcc5963958b284d720a6f5e754ef416 | C++ | khanna7/BARS | /transmission_model/src/TestingConfigurator.cpp | UTF-8 | 3,941 | 2.53125 | 3 | [] | no_license | /*
* TestingConfigurator.cpp
*
* Created on: Oct 11, 2017
* Author: nick
*/
#include <vector>
#include <exception>
#include "boost/algorithm/string.hpp"
#include "Parameters.h"
#include "TestingConfigurator.h"
using namespace std;
namespace TransModel {
repast::NumberGenerator* create_gen(float rate) {
BinomialGen coverage(repast::Random::instance()->engine(), boost::random::binomial_distribution<>(1, rate));
return new repast::DefaultNumberGenerator<BinomialGen>(coverage);
}
TestingConfigurator::TestingConfigurator(ProbDist<TestingDist>& lt_dist, ProbDist<TestingDist>& gte_dist,
float age_threshold, float lt_non_tester_rate, float gte_non_tester_rate) : lt_dist_{lt_dist}, gte_dist_{gte_dist},
threshold{age_threshold}, lt_gen{create_gen(lt_non_tester_rate)}, gte_gen{create_gen(gte_non_tester_rate)}
{
}
TestingConfigurator::~TestingConfigurator() {}
void TestingConfigurator::configurePerson(std::shared_ptr<Person> p, double size_of_timestep) {
configurePerson(p, size_of_timestep, repast::Random::instance()->nextDouble());
}
void TestingConfigurator::configurePerson(std::shared_ptr<Person> p, double size_of_timestep, double draw) {
ProbDist<TestingDist>* dist = nullptr;
repast::NumberGenerator* gen = nullptr;
if (p->age() < threshold) {
dist = <_dist_;
gen = lt_gen;
} else {
dist = >e_dist_;
gen = gte_gen;
}
bool testable = ((int) gen->next()) == 0;
double test_prob = 0;
if (testable) {
test_prob = dist->draw(draw).next(size_of_timestep);
}
p->updateDiagnoser(test_prob, testable);
}
const double TWO_YEARS = 730;
TestingDist::TestingDist(int min, int max) : min_(min), max_(max) {
}
double TestingDist::next(double size_of_timestep) {
double val = repast::Random::instance()->createUniIntGenerator(min_, max_).next();
return val / TWO_YEARS * size_of_timestep;
}
// range is min-max of tests within the last two years
TestingDist create_dist(std::string& range) {
vector<string> tokens;
boost::split(tokens, range, boost::is_any_of("-"));
if (tokens.size() != 2) {
throw std::invalid_argument("Bad testing.prob definition: " + range);
}
try {
int min = stoi(tokens[0]);
int max = stoi(tokens[1]);
return TestingDist(min, max);
} catch (invalid_argument& e) {
throw std::invalid_argument("Bad testing.prob definition: " + range);
}
}
ProbDist<TestingDist> create_prob_dist(const std::string& key_prefix) {
ProbDistCreator<TestingDist> creator;
vector<string> lag_keys;
Parameters::instance()->getKeys(key_prefix, lag_keys);
for (auto& key : lag_keys) {
string val = Parameters::instance()->getStringParameter(key);
vector<string> tokens;
boost::split(tokens, val, boost::is_any_of("|"));
if (tokens.size() != 2) {
throw std::invalid_argument("Bad testing.prob definition: " + val);
}
//std::cout << tokens[0] << ", " << tokens[1] << std::endl;
TestingDist dist = create_dist(tokens[0]);
double frac = stod(tokens[1]);
creator.addItem(frac, dist);
}
return creator.createProbDist();
}
TestingConfigurator create_testing_configurator() {
ProbDist<TestingDist> lt_dist = create_prob_dist(TESTING_PROB_PREFIX_LT);
ProbDist<TestingDist> gte_dist = create_prob_dist(TESTING_PROB_PREFIX_GTE);
double lt_non_tester_rate = Parameters::instance()->getDoubleParameter(NON_TESTERS_PROP_LT);
double gte_non_tester_rate = Parameters::instance()->getDoubleParameter(NON_TESTERS_PROP_GTE);
float age_threshold = Parameters::instance()->getFloatParameter(INPUT_AGE_THRESHOLD);
return TestingConfigurator(lt_dist, gte_dist, age_threshold, lt_non_tester_rate, gte_non_tester_rate);
}
} /* namespace TransModel */
| true |
1a327bfb3e5e78fdde007a87c813446680cd61fe | C++ | TheMarlboroMan/cheap-shooter | /class/aplicacion/proyectil/proyectil.h | UTF-8 | 1,939 | 2.96875 | 3 | [] | no_license | #ifndef PROYECTIL_H
#define PROYECTIL_H
#include "../no_jugador/no_jugador.h"
class Proyectil:public No_jugador
{
private:
const Actor * origen;
/*
Cuando un proyecil es de una facción NO chocará con ella.
*/
unsigned short int potencia;
unsigned short int color;
unsigned short int faccion;
float velocidad;
// bool rebota;
//El constructor es privado: para crearlos los traemos por los métodos estáticos que hay.
Proyectil();
void establecer_dimensiones(unsigned short int);
void actualizar_representacion();
static Proyectil * nuevo_proyectil(unsigned short int=D_NORMAL);
protected:
void establecer_representacion();
void establecer_caracteristicas();
public:
// void establecer_potencia(unsigned short int=1, unsigned short int=0);
void establecer_potencia(unsigned short int v) {potencia=v;}
void establecer_velocidad(float);
void establecer_color(unsigned short int);
void establecer_faccion(unsigned short int p_faccion) {this->faccion=p_faccion;}
enum colores{
C_ROJO,
C_AZUL,
C_VERDE,
C_VIOLETA,
C_MAX_COLOR};
enum dimensiones{
D_PEQUENO=8,
D_NORMAL=16,
D_GRANDE=32,
D_MAX_DIMENSIONES};
virtual ~Proyectil();
unsigned short int acc_potencia() const {return this->potencia;}
virtual bool puede_rebotar() const {return false;}
bool es_disparado_por(Actor * p_actor) const {return this->origen==p_actor;}
bool es_de_faccion(unsigned int p_facc) const
{
return p_facc & this->faccion;
}
void cuentame() {std::cout<<"SOY PROYECTIL"<<std::endl;}
virtual unsigned short int obtener_tipo_colision() const {return Actor::T_TIPO_COLISION_PROYECTIL;}
static Proyectil * generar(const Actor&, DLibH::Vector_2d, unsigned short int=D_NORMAL, int=0, int=0);
static Proyectil * generar(const Actor&, const Actor&, unsigned short int=D_NORMAL, int=0, int=0, int=0);
static Proyectil * generar(int, int, const Actor&, DLibH::Vector_2d, unsigned short int=D_NORMAL);
};
#endif
| true |
b8da9ac63b5a0e04dc6fba01c4c71529bfb3c413 | C++ | AlbertoCasasOrtiz/UCM-Informatica_grafica-Practica_3 | /Cilindro.h | ISO-8859-2 | 1,282 | 3.109375 | 3 | [] | no_license | #ifndef CILINDRO_H
#define CILINDRO_H
#include "ObjetoCompuesto3D.h"
#include "Color.h"
/*
Clase cilindro. Genera un cilindro.
*/
class Cilindro : public ObjetoCompuesto3D{
private:
/*Objeto cuadratico generado para el cilindro.*/
GLUquadricObj *quadratic;
/*Parmetros del cilindro.*/
GLfloat baseRadius, topRadius, height;
/*Partes que forman el cilindro.*/
GLint slices, stacks;
/*Color del cilindro.*/
Color * color;
public:
/****************/
/*Constructoras.*/
/****************/
/*Constructora de la clase cilindro.*/
Cilindro(GLfloat baseRadius, GLfloat topRadius, GLfloat height, GLint slices, GLint stacks, Color *color) {
this->baseRadius = baseRadius;
this->topRadius = topRadius;
this->height = height;
this->slices = slices;
this->stacks = stacks;
this->color = color;
this->quadratic = gluNewQuadric();
}
/*Destructora de la clase cilindro.*/
~Cilindro() {
gluDeleteQuadric(quadratic);
delete this->color;
}
/**********************
*Mtodos de la clase.*
**********************/
/*Mtodo que dibuja el cilindro.*/
void dibuja() {
glRotatef(-90.0, 1.0, 0.0, 0.0);
glColor3f(color->getR(), color->getG(), color->getB());
gluCylinder(quadratic, baseRadius, topRadius, height, slices, stacks);
}
};
#endif
| true |
d44e4a686d9b3a6af349d7ecd1489649d525ee11 | C++ | yuqi-lee/program-design | /oj_ex/Analyzing_algorithm.cpp | UTF-8 | 852 | 3.28125 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
void _counter(long* arraylist, long n, long i);
int main()
{
long i, j;
while (scanf("%ld %ld", &i, &j) != EOF)
{
long num = j - i + 1;
long arraylist[num];
long counter = 0;
for (long k = 0; k < num; k++)
{
_counter(arraylist, k, i);
counter = arraylist[k] > counter ? arraylist[k] : counter;
}
cout << i << " " << j << " " << counter << endl;
}
return(0);
}
void _counter(long* arraylist, long n, long i)
{
long counter = 0;
long number = n + i;
while (true)
{
counter++;
if (number == 1)
break;
else if (number % 2 == 0)
number = number / 2;
else
number = number * 3 + 1;
}
arraylist[n] = counter;
return;
}
| true |
4eb068d046a7afc5ae773de3e4d5aaaac3cee384 | C++ | gilbertoalexsantos/judgesolutions | /Solved/UVA/@UVA 10806 - Dijkstra, Dijkstra./10806 - Dijkstra, Dijkstra..cpp | UTF-8 | 2,335 | 2.578125 | 3 | [] | no_license | //Author: Gilberto A. dos Santos
//Website: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1747
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
typedef pair<int,int> ii;
const int MAX = 101;
const int INF = 1e9;
int qt_verts, qt_edges;
int source, sink;
vector<int> graph[MAX];
int edge[MAX][MAX];
void clear() {
for(int i = 1; i <= qt_verts; i++) {
graph[i].clear();
for(int j = 1; j <= qt_verts; j++) {
edge[i][j] = INF;
}
}
}
int dijkstra() {
priority_queue<ii> pq;
pq.push(ii(0,source));
int dist[qt_verts+1], path[qt_verts+1];
for(int i = 1; i <= qt_verts; i++) {
dist[i] = INF;
path[i] = -1;
}
dist[source] = 0;
while(!pq.empty()) {
int u = pq.top().second, w = -pq.top().first; pq.pop();
if(dist[u] < w)
continue;
if(u == sink)
break;
for(int i = 0; i < graph[u].size(); i++) {
int v = graph[u][i], nw = edge[u][v];
if(dist[v] > dist[u]+nw) {
path[v] = u;
dist[v] = dist[u]+nw;
pq.push(ii(-dist[v],v));
}
}
}
stack<int> p;
int t = sink;
while(t != -1) {
p.push(t);
t = path[t];
}
int u = source;
while(!p.empty()) {
int v = p.top(); p.pop();
edge[u][v] = INF;
edge[v][u] *= -1;
u = v;
}
return dist[sink];
}
int bellman() {
int dist[qt_verts+1];
for(int i = 1; i <= qt_verts; i++) {
dist[i] = INF;
}
dist[source] = 0;
for(int i = 0; i < qt_verts-1; i++) {
for(int u = 1; u <= qt_verts; u++) {
for(int j = 0; j < graph[u].size(); j++) {
int v = graph[u][j], w = edge[u][v];
dist[v] = min(dist[v],dist[u]+w);
}
}
}
return dist[sink];
}
int solve() {
int d1 = dijkstra();
int d2 = bellman();
if(d1 == INF || d2 == INF)
return -1;
return d1 + d2;
}
int main() {
while(scanf("%d",&qt_verts) && qt_verts) {
clear();
source = 1, sink = qt_verts;
scanf("%d",&qt_edges);
for(int i = 0; i < qt_edges; i++) {
int u, v, w; scanf("%d %d %d",&u,&v,&w);
graph[u].push_back(v); graph[v].push_back(u);
edge[u][v] = edge[v][u] = w;
}
int ans = solve();
if(ans == -1) printf("Back to jail\n");
else printf("%d\n",ans);
}
}
| true |
9b3d7a97aff0438db5165342a983d63ed678a638 | C++ | inbei/smf | /src/framework/primitives/SMFSystemMemoryBufferFactory.cpp | UTF-8 | 1,481 | 2.546875 | 3 | [] | no_license |
#include "SMFSystemMemoryBufferFactory.h"
namespace surveon
{
namespace mf
{
static SystemMemoryMediaBufferFactory s_SystemMemoryMediaBufferFactory;
IMediaBufferFactory* getSystemMemoryMediaBufferFactory(void)
{
return &s_SystemMemoryMediaBufferFactory;
}
//====================================================================================
IMediaBuffer* SystemMemoryMediaBufferFactory::createMediaBuffer(size_t size, uint8 aligment)
{
return m_MediaBufferFactory.create<SystemMemoryMediaBuffer>(size, aligment);
}
void SystemMemoryMediaBufferFactory::destroyMediaBuffer(IMediaBuffer* pBuffer)
{
m_MediaBufferFactory.destroy(pBuffer);
}
IVideoBuffer* SystemMemoryMediaBufferFactory::createVideoBuffer(uint16 width, uint16 height, MediaSubType format, uint8 aligment)
{
if(width == 0 || height == 0)
{
SMF_THROW_EXCEPT(InvalidParametersException,
"Invalid size: width = " << width << " height = " << height);
}
if(format != SMF_VIDEO_FORMAT_RGBA && format != SMF_VIDEO_FORMAT_YUV420 &&
format != SMF_VIDEO_FORMAT_YV12 )
{
SMF_THROW_EXCEPT(InvalidParametersException, "Invalid format " << format);
}
return m_VideoBufferFactory.create<SystemMemoryVideoBuffer>
(width, height, format, aligment);
}
void SystemMemoryMediaBufferFactory::destroyVideoBuffer(IVideoBuffer* pBuffer)
{
m_VideoBufferFactory.destroy(pBuffer);
}
} // namespace mf
} // namespace surveon
| true |