blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
247
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 4
111
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
58
| visit_date
timestamp[ns]date 2015-07-25 18:16:41
2023-09-06 10:45:08
| revision_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| github_id
int64 3.89k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 25
values | gha_event_created_at
timestamp[ns]date 2012-06-07 00:51:45
2023-09-14 21:58:52
⌀ | gha_created_at
timestamp[ns]date 2008-03-27 23:40:48
2023-08-24 19:49:39
⌀ | gha_language
stringclasses 159
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
10.5M
| extension
stringclasses 111
values | filename
stringlengths 1
195
| text
stringlengths 7
10.5M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
742f14ae25436a105afd5d4ac9dc89ab769b0cca
|
7e6afb4986a53c420d40a2039240f8c5ed3f9549
|
/libs/graphs/include/mrpt/graphs/CVisualizer.h
|
27984578b29f73c0a2a724d5f31aff9f2a1a2b5f
|
[
"BSD-3-Clause"
] |
permissive
|
MRPT/mrpt
|
9ea3c39a76de78eacaca61a10e7e96646647a6da
|
34077ec74a90b593b587f2057d3280ea520a3609
|
refs/heads/develop
| 2023-08-17T23:37:29.722496
| 2023-08-17T15:39:54
| 2023-08-17T15:39:54
| 13,708,826
| 1,695
| 646
|
BSD-3-Clause
| 2023-09-12T22:02:53
| 2013-10-19T21:09:23
|
C++
|
UTF-8
|
C++
| false
| false
| 3,130
|
h
|
CVisualizer.h
|
/* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| https://www.mrpt.org/ |
| |
| Copyright (c) 2005-2023, Individual contributors, see AUTHORS file |
| See: https://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See: https://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#pragma once
#include <mrpt/containers/yaml.h>
#include <mrpt/graphs/CNetworkOfPoses.h>
#include <mrpt/opengl/CGridPlaneXY.h>
#include <mrpt/opengl/CPointCloud.h>
#include <mrpt/opengl/CSetOfLines.h>
#include <mrpt/opengl/CSetOfObjects.h>
#include <mrpt/opengl/CSimpleLine.h>
#include <mrpt/opengl/stock_objects.h>
namespace mrpt::graphs::detail
{
/** \brief Base class for C*Visualizer classes.
*
* By default provides visualization for a CNetowrkOfPoses containing nodes and
* edges as constructed by a single agent/robot. Derived classes can inherit
* and partially modify the class behavior
*/
template <
class CPOSE, // Type of edges
class MAPS_IMPLEMENTATION, // Use std::map<> vs. std::vector<>
class NODE_ANNOTATIONS = mrpt::graphs::detail::TNodeAnnotations,
class EDGE_ANNOTATIONS = mrpt::graphs::detail::edge_annotations_empty>
class CVisualizer
{
public:
using GRAPH_T = mrpt::graphs::CNetworkOfPoses<
CPOSE, MAPS_IMPLEMENTATION, NODE_ANNOTATIONS, EDGE_ANNOTATIONS>;
/**\brief Constructor
*/
CVisualizer(const GRAPH_T& graph_in);
/**\brief Destructor
*/
virtual ~CVisualizer();
/**\brief Common visualization stuff for all derived classes
*
* Function delegates visualization tasks to the draw* methods according to
* the user preferences
*
*/
virtual void getAs3DObject(
mrpt::opengl::CSetOfObjects::Ptr& object,
const mrpt::containers::yaml& viz_params) const;
protected:
/**\name Work-splitting methods
* \brief Smaller functions that do add very specific parts to the visual
* representation
*
* Following functions take an optional mrpt::containers::yaml instance
* containing visualization parameters
*/
/**\{ */
virtual void drawGroundGrid(
mrpt::opengl::CSetOfObjects::Ptr& object,
const mrpt::containers::yaml* viz_params = nullptr) const;
virtual void drawNodeCorners(
mrpt::opengl::CSetOfObjects::Ptr& object,
const mrpt::containers::yaml* viz_params = nullptr) const;
virtual void drawNodePoints(
mrpt::opengl::CSetOfObjects::Ptr& object,
const mrpt::containers::yaml* viz_params = nullptr) const;
virtual void drawEdgeRelPoses(
mrpt::opengl::CSetOfObjects::Ptr& object,
const mrpt::containers::yaml* viz_params = nullptr) const;
virtual void drawEdges(
mrpt::opengl::CSetOfObjects::Ptr& object,
const mrpt::containers::yaml* viz_params = nullptr) const;
/**\} */
bool m_is_3D_graph;
const GRAPH_T& m_graph;
};
} // namespace mrpt::graphs::detail
#include <mrpt/graphs/CVisualizer_impl.h>
|
7a1ab07258d882215fef25067cd9b4f7e6466672
|
78d2562d7490f19a11223dadd3e5c07e4ebc4cdd
|
/include/group6_rwa5/priority_order.h
|
989c7d204393d0ef03f463e5002a303c760e022c
|
[] |
no_license
|
iskalasrinivas/group6_rwa5
|
42725fd1d5b08a46703179c64d3e98d6bcfca623
|
22b5bfb0069ac3772e978fc955e1d6e22ef887fd
|
refs/heads/master
| 2021-06-13T22:41:53.995116
| 2020-04-23T22:12:10
| 2020-04-23T22:12:10
| 254,457,321
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,273
|
h
|
priority_order.h
|
/**
* @file include/competition.h
* @brief Header file for competition
* @author Saurav Kumar
* @author Raja Srinivas
* @author Sanket Acharya
* @author Dinesh Kadirimangalam
* @author Preyash Parikh
* @copyright 2020
*
**BSD 3-Clause License
*
*Copyright (c) 2020
*All rights reserved.
*
*Redistribution and use in source and binary forms, with or without
*modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
*THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
*AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
*IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
*FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
*DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
*SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
*CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
*OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
*OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef GROUP6_RWA5_PRIORITYORDER_H
#define GROUP6_RWA5_PRIORITYORDER_H
#include <ros/ros.h>
#include <queue>
#include <order_part.h>
class PriorityOrder
{
public:
PriorityOrder();
~PriorityOrder();
private:
auto comp = [](OrderPart* a, OrderPart* b ) { return a->getPriority() > b->getPriority();};
std::priority_queue<OrderPart*, std::vector<OrderPart*>, decltype(comp)>> priority_queue_(comp);
};
#endif //GROUP6_RWA5_PRIORITYORDER_H
|
de46f6e14f4ed545747a4ce1b5c764357d50f0d2
|
3047545349bf224a182b2c33bf1f110aef1ce9b6
|
/Transims60/Relocate/Plan_Processor.cpp
|
9f78777ec5623091569868abd74b6f088c4a9941
|
[] |
no_license
|
qingswu/Transim
|
585afe71d9666557cff53f6683cf54348294954c
|
f182d1639a4db612dd7b43a379a3fa344c2de9ea
|
refs/heads/master
| 2021-01-10T21:04:50.576267
| 2015-04-08T19:07:28
| 2015-04-08T19:07:28
| 35,232,171
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,165
|
cpp
|
Plan_Processor.cpp
|
//*********************************************************
// Plan_Processor.cpp - plan processing thread
//*********************************************************
#include "Relocate.hpp"
#ifdef THREADS
//---------------------------------------------------------
// Plan_Processor operator
//---------------------------------------------------------
void Relocate::Plan_Processor::operator()()
{
int number;
Plan_Ptr plan_ptr;
while (1) {
plan_ptr = exe->plan_queue.Get_Work (number);
if (plan_ptr == 0) break;
exe->Process_Plan (plan_ptr);
exe->plan_queue.Put_Result (plan_ptr, number);
}
}
//---------------------------------------------------------
// Save_Plan operator
//---------------------------------------------------------
void Relocate::Save_Plan::operator()()
{
Plan_Ptr plan_ptr;
Plan_File *new_file = (Plan_File *) exe->System_File_Handle (NEW_PLAN);
while (1) {
plan_ptr = exe->plan_queue.Get_Result ();
if (plan_ptr == 0) break;
if (plan_ptr->Index () != 0) {
new_file->Write_Plan (*plan_ptr);
}
delete plan_ptr;
exe->plan_queue.Finished ();
}
}
#endif
|
3d728e91873e6d5d0925e490de906bdb3f5910a7
|
a0c8daadc766aae14c8e8246e747035e140c2baa
|
/speech/include/speech.hpp
|
b6ff17e96659f49f887456c079bf2fe6453722e1
|
[] |
permissive
|
kenzanin/speech
|
78dc2c705a1080999746858bcaa23ac86ef432df
|
59a4546ecccf6f147a80c3971054169f9feacaa0
|
refs/heads/main
| 2023-08-25T21:12:19.563320
| 2021-10-08T07:02:05
| 2021-10-08T07:02:05
| 390,218,640
| 0
| 1
|
CC0-1.0
| 2021-07-29T14:28:45
| 2021-07-28T04:57:30
|
C++
|
UTF-8
|
C++
| false
| false
| 792
|
hpp
|
speech.hpp
|
/*
Authored by Suka Isnaini on 9th of August 2021
Created for PT Sejahtera Empati Pratama
All Copyrights belong to PT Sejahtera Empati Pratama
*/
#include <string>
#ifndef SPEECH_HPP
#define SPEECH_HPP
#if defined(_WIN32) || defined(_WIN64) || defined(__WIN32__) || \
defined(__MINGW32__)
#define DLLEXPORT __declspec(dllexport)
#define ADDCALL __stdcall
#ifdef _MSVC_VER
#endif
#else
#define DLLEXPORT
#define ADDCALL
#define fopen_s(pFile, filename, mode) \
((*(pFile)) = fopen((filename), (mode))) == NULL
typedef int errno_t;
#endif
#ifdef __cplusplus
extern "C" {
#endif
DLLEXPORT int ADDCALL PitchAnalyzer(char* const, char* const);
DLLEXPORT char* ADDCALL PitchAnalyzer2(const char*);
#ifdef __cplusplus
}
#endif
#endif // SPEECH_HPP
|
1f194b5c02cb2a57663d0ec38c7d5650146614d4
|
5f6c47e58f4377423e1fa064ddeb92d02e17c967
|
/双向传输文件(只需知道server的ip和端口号,client的ip和端口号会在通信中传输给server;无通信反馈,每500B数据200ms延时,大文件耗时)/TCPtest/TCPclient/TCPclient/MyData.h
|
df54101d02c3643c95c57db81a27157a1ceb6860
|
[] |
no_license
|
themostfreeboy/TCP
|
e38ffcb44da8d9460145c4d8b7b3116210028a9e
|
541026531bbc68c279e4fa77f88dc5b8fb57cc47
|
refs/heads/master
| 2020-03-08T13:29:16.708134
| 2018-04-05T04:33:20
| 2018-04-05T04:33:20
| 128,159,176
| 1
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 2,407
|
h
|
MyData.h
|
#ifndef __MYDATA_H
#define __MYDATA_H
#include <string>
#include <winsock.h>
#include "md5_file.h"
#pragma comment(lib,"wsock32.lib")
class MySocketClient//Socket编程Client客户端类
{
public:
char server_ip[256];//server服务器ip地址
int server_port;//server服务器端口号
char client_ip[256];//client客户端ip地址
int client_port;//client客户端端口号
SOCKET sock_client;//连接的指针
SOCKADDR_IN addrserver;//存储server服务器的相关信息
MySocketClient();//构造函数
bool Start();//完成client客户端相关配置并建立连接
bool Finish();//断开连接释放资源
bool Send(const char sendbuf[],int length);//向server服务器发送数据
bool SendClientIPPort();//向server服务器发送client客户端的ip地址和端口号
bool SendFile(const char filepath[],int sleeptime);//向server服务器发送文件(由于没有通信反馈,传输大文件易丢包)
};
class MySocketServer//Socket编程Server服务器类
{
public:
char server_ip[256];//server服务器ip地址
int server_port;//server服务器端口号
char client_ip[256];//client客户端ip地址
int client_port;//client客户端端口号
bool listening;//用于控制是否监听
SOCKET sock_server;//连接的指针
SOCKET sock_client;//连接的指针
SOCKADDR_IN addrclient;//存储client客户端的相关信息
SOCKADDR_IN addrserver;//存储server服务器的相关信息
MySocketServer();//构造函数
bool StartThread();//新启用一个线程来执行Start函数
bool Finish();//断开连接释放资源
bool Receive(char receivebuf[],int length);//从client客户端接收数据
bool ReceiveClientIPPort();//从client客户端接收client客户端的ip地址和端口号
bool ReceiveFile(const char filepath[]);//从client客户端接收文件(由于没有通信反馈,传输大文件易丢包)
private:
bool Start();//完成server服务器相关配置并开始监听
static UINT ProcessForStart(LPVOID pParam);//为了开启Start函数的多线程而加的辅助函数
};
bool GetLocalIP(char ip[]);//获取本机ip地址
bool StringPlus(char original_string[],const char plus_string[],int &num);//为了避免original_string数组中已经含有0('\0')导致strcat失效
int StringCheck(const char original_string[],const char check_string[],const int num);//为了避免original_string数组中已经含有0('\0')导致strstr失效
#endif
|
4ce4dfddd8d014bfafb03a8d8b882b9b0751c8ed
|
3c6c4b88b2d80571a7af36eb8cd9241433cf6a58
|
/Longest Common Subsequence/15 Longest Increasing Subsequence - Memoization.cpp
|
5af7b2b4f5e2a679e5d84c193335c37c9f463294
|
[] |
no_license
|
rajatreigns/Dynamic-Programming
|
86ef769377650fd91708f1552aff0371f072ebea
|
0079784608bd477eddf7261cb57e2356c2bed8e6
|
refs/heads/main
| 2023-04-28T05:54:15.634546
| 2021-05-22T12:27:16
| 2021-05-22T12:27:16
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,223
|
cpp
|
15 Longest Increasing Subsequence - Memoization.cpp
|
#include <bits/stdc++.h>
#include<math.h>
#define ll long long int
#define N '\n'
#define ull unsigned long long int
#define forp(i,a,b) for(int i=(int)a;i<(int)b;i++)
#define forpe(i,a,b) for(int i=(int)a;i<=(int)b;i++)
#define pb push_back
#define M 1000000007
using namespace std;
// Longest Increasing Subsequence - Memoized
// https://www.geeksforgeeks.org/longest-increasing-subsequence-dp-3/
int dp[1001][1001] ;
int rec(int a[], int n, int x) {
if(n == -1) {
return 0 ;
}
if(dp[n][x] != -1) {
return dp[n][x] ;
}
if(a[n] < x) {
return dp[n][x] = max(rec(a, n - 1, x) , 1 + rec(a, n - 1, a[n]));
}
else {
return dp[n][x] = rec(a, n - 1, x) ;
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
#endif
int T;
cin >> T;
while(T--)
{
memset(dp, -1, sizeof(dp)) ;
int n, i ;
cin >> n ;
int a[n] ;
for( i = 0 ; i < n ; i++) cin >> a[i] ;
cout << rec(a, n - 1, 10000) << N ;
}
return 0;
}
|
e9c855a37acb514925dd2a590fccb0990f5d8f29
|
30d632410d540e925867950306e7dadfa57feb00
|
/client/connectiondialog.cpp
|
e5e21cc884950f7333b3cc6540d62aab2b5e728c
|
[] |
no_license
|
smokfyz/gui_1h2020-battleship
|
e7a259be1d35243e5c86a5da4f0668ce2e3c5b25
|
6a740f1fad3f24349b82d9e4018572f7b402c059
|
refs/heads/master
| 2022-08-10T20:12:17.344855
| 2020-05-24T22:42:33
| 2020-05-24T22:42:33
| 255,596,589
| 0
| 1
| null | 2020-05-25T12:12:31
| 2020-04-14T11:58:16
|
C++
|
UTF-8
|
C++
| false
| false
| 3,399
|
cpp
|
connectiondialog.cpp
|
#include "connectiondialog.h"
ConnectionDialog::ConnectionDialog(QWidget* parent) :
QDialog(parent)
{
this->setFixedSize(280, 150);
this->setWindowTitle("Start the game");
applyButton = new QPushButton("Apply", this);
cancelButton = new QPushButton("Cancel", this);
QLabel *addrLabel = new QLabel("Host:", this);
QLabel *loginLabel = new QLabel("Login:", this);
QLabel *passLabel = new QLabel("Password:", this);
addressTextBox = new QLineEdit(this);
loginTextBox = new QLineEdit(this);
passwordTextBox = new QLineEdit(this);
QGridLayout *layout = new QGridLayout(this);
QHBoxLayout *buttonsLayout = new QHBoxLayout(this);
layout->addWidget(addrLabel, 0, 0);
layout->addWidget(addressTextBox, 0, 1);
layout->addWidget(loginLabel, 1, 0);
layout->addWidget(loginTextBox, 1, 1);
layout->addWidget(passLabel, 2, 0);
layout->addWidget(passwordTextBox, 2, 1);
buttonsLayout->addWidget(applyButton);
buttonsLayout->addWidget(cancelButton);
layout->addItem(buttonsLayout, 3, 0, 1, 2);
setLayout(layout);
passwordTextBox->setEchoMode(QLineEdit::Password);
applyButton->setDefault(true);
loginTextBox->installEventFilter(this);
passwordTextBox->installEventFilter(this);
addrLabel->setVisible(false);
addressTextBox->setVisible(false);
connect(applyButton, SIGNAL(clicked()), this, SLOT(accept()));
connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject()));
}
ConnectionDialog::~ConnectionDialog()
{
}
void ConnectionDialog::setAddressString(const QString &address, quint16 port)
{
setAddressString(QHostAddress(address), port);
}
void ConnectionDialog::setAddressString(const QHostAddress &address, quint16 port)
{
if (!addressTextBox)
{
return;
}
addressTextBox->setText(QString("%1:%2").arg(address.toString()).arg(port));
}
void ConnectionDialog::setLogin(const QString &login)
{
loginTextBox->setText(login);
}
void ConnectionDialog::setPassword(const QString &password)
{
passwordTextBox->setText(password);
}
QString ConnectionDialog::getAddress() const
{
return address;
}
QString ConnectionDialog::getLogin() const
{
return login;
}
QString ConnectionDialog::getPassword() const
{
return password;
}
quint16 ConnectionDialog::getPort()
{
return port;
}
void ConnectionDialog::accept()
{
QHostAddress addr( addressTextBox->text().replace(QRegExp(":.*"), ""));
bool isOk;
port = addressTextBox->text().replace(QRegExp(".*:"), "").toUShort(&isOk);
login = loginTextBox->text();
password = passwordTextBox->text();
if (!addr.isNull() && isOk)
{
address = addr.toString();
qDebug("Server address and port: %s:%d", qPrintable(address), port);
done(QDialog::Accepted);
return;
}
QMessageBox::warning(this, "Warning", "Specify the valid IPv4 address");
addressTextBox->setFocus();
}
bool ConnectionDialog::eventFilter(QObject *object, QEvent *event)
{
if (event->type() == QEvent::MouseButtonPress)
{
if (object == loginTextBox)
{
loginTextBox->selectAll();
return true;
}
if (object == passwordTextBox)
{
passwordTextBox->selectAll();
return true;
}
return false;
}
return QDialog::eventFilter( object, event );
}
|
6fd8203324c5ab2f4bda8dc54f302968677a0230
|
eca634ce6477e5680987dfc6536f6fdd93c58db6
|
/Repertoire/Multithreading/ThreadingUnitTest.cpp
|
2e1a6706d0d970bda3d75888cf6249789b8ea899
|
[] |
no_license
|
tectronics/surface-physics
|
ba2ed585406f9e9955aeabc6d343cedeb41c2f61
|
f5f2af539aee7483ae28f4edec4b7b62edfa2d61
|
refs/heads/master
| 2018-01-11T15:03:08.166454
| 2014-10-02T19:44:33
| 2014-10-02T19:44:33
| 45,230,360
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,105
|
cpp
|
ThreadingUnitTest.cpp
|
// ThreadingUnitTest.cpp : Defines the entry point for the console application.
//
#include "windows.h"
#include<stdio.h>
#include <process.h>
class Barrier {
volatile long numThreads;
volatile long numThreadsEntered_Barrier;
volatile long numThreadsExited_Barrier;
HANDLE entranceSemaphore;
HANDLE exitSemaphore;
public:
Barrier(int numThreadsToSync) :
numThreads(numThreadsToSync),
numThreadsEntered_Barrier(0),
numThreadsExited_Barrier(0)
{
entranceSemaphore = CreateSemaphore(NULL,0,4096,NULL);
exitSemaphore = CreateSemaphore(NULL,0,4096,NULL);
}
~Barrier()
{ }
void wait(){
LONG prev;
// Wait until all threads enter the Barrier
if (InterlockedIncrement(&numThreadsEntered_Barrier) < numThreads)
WaitForSingleObject(entranceSemaphore,INFINITE);
else {
numThreadsExited_Barrier = 0;
//single_thread_callback();
ReleaseSemaphore(entranceSemaphore, numThreads-1, &prev);
}
//all_threads_callback();
// Wait until all threads exit the Barrier
if (InterlockedIncrement(&numThreadsExited_Barrier) < numThreads)
WaitForSingleObject(exitSemaphore,INFINITE);
else {
numThreadsEntered_Barrier = 0;
ReleaseSemaphore(exitSemaphore, numThreads-1, &prev);
}
}
void openBarrier()
{
LONG prev1, prev2;
ReleaseSemaphore(entranceSemaphore, 4096, &prev1); //thsi must be made max, as if sem drops to 0(as wait release threads), remaining threads remain halted
ReleaseSemaphore(exitSemaphore, 4096, &prev2);
numThreadsEntered_Barrier = 0;
numThreadsExited_Barrier = 0;
}
void setMaxCount(long numThreadsToSync)
{ numThreads = numThreadsToSync; }
long getMaxCount()
{ return numThreads; };
};
/**
* The Bump_BulletBase to create and manage a BulletBase
*/
class Base
{
//#pragma message("Base included")
int baseID;
volatile unsigned int count;
//thread specific stuff;
HANDLE hThread;
unsigned threadID;
bool keepRunningThread;
CRITICAL_SECTION critsec;
public:
static Barrier *simStepBarrier;
bool threadRunning;
Base(int id)
{
baseID = id;
count = 0;
InitializeCriticalSection(&critsec);
}
~Base()
{
printf_s("Base::ended %d\n", baseID);
CloseHandle(hThread);
DeleteCriticalSection(&critsec);
};
void MemberFunc(UINT i) // A member function
{
printf_s("Base: %d, count=%d \n", baseID, count);
count++;
}
int init()
{
keepRunningThread = true;
hThread = (HANDLE)_beginthreadex(NULL , 0, &runBaseThread, this, 0, &threadID);
return 0;
}
int exit()
{
keepRunningThread = false;
//while(threadRunning)
// Sleep(10);
printf_s("Base: %d, count=%d \n", baseID, count);
return 0;
}
static unsigned __stdcall runBaseThread(void *param)
{
Base* This = (Base*)param;
printf_s("Base::MemberFunc : %d STARTING\n", This->baseID);
This->threadRunning = true;
while(This->keepRunningThread){
This->MemberFunc(0); // call a member function
simStepBarrier->wait();
}
printf_s("Base::MemberFunc : %d ENDING\n", This->baseID);
Sleep(100);
This->threadRunning = false;
_endthreadex(0);
return 0;
}
};
Barrier * Base::simStepBarrier = NULL;
int main(int argc, char* argv[])
{
Barrier simStepBarrier(4);
Base *ptrBase[3];
Base::simStepBarrier = &simStepBarrier;
//Start base threads
ptrBase[0] = new Base(1);
ptrBase[1] = new Base(2);
ptrBase[2] = new Base(3);
ptrBase[0]->init();
ptrBase[1]->init();
ptrBase[2]->init();
for(int i=0; i<10; i++)
simStepBarrier.wait();
//New base
ptrBase[0]->exit();
ptrBase[1]->exit();
ptrBase[2]->exit();
//Release all threads for exit rush if this thread is also synced
simStepBarrier.openBarrier();
for(int i=0; i<3; i++)
while(ptrBase[i]->threadRunning);
//Safe to delete now
delete ptrBase[0];
delete ptrBase[1];
delete ptrBase[2];
return 0;
}
|
6a65e5db6ecd2940bd34449039433982733b1e26
|
78c0d4b62bba3dd1cfed499625a7b6b719e8c91c
|
/src/main.cpp
|
154bec2919a2165417c0c83c3274b540a1f23322
|
[] |
no_license
|
Xavier-Pisco/TourMateApp
|
0f0d850cb2fb4517f3d4ab073375ec1d0b027dcf
|
d6780a225bba36f750a2cf8fbb235efc986b7a70
|
refs/heads/master
| 2023-04-30T15:22:27.223725
| 2020-05-27T13:48:24
| 2020-05-27T13:48:24
| 368,233,430
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 384
|
cpp
|
main.cpp
|
#include "application/Application.h"
#include <csignal>
#include <iostream>
using namespace std;
int main() {
signal(SIGINT, SIG_IGN); // this is being used to ignore the SIGINT signal sent by GraphViewer
Application app;
app.mainMenu();
cout << "getchar" << endl;
getchar(); // this is so the program exits successfully (due to GraphViewer)
return 0;
}
|
03c3a163fe463ec75903379e0bdcf68eed694c15
|
3b03cc4858d548a9135545dff952b1baf7e7aec2
|
/plugins/sdm/sdm/CreateSDFields.hpp
|
9c0849b1acd6ea31ea3ee773a87cf734ad0c872f
|
[] |
no_license
|
uabti/coolfluid3
|
04364a468a18038e8a21ea4960bbcc033958c2b2
|
31c78a10a3b506212ae5367f1d47326bf35c5bd0
|
refs/heads/master
| 2021-01-15T19:34:41.090988
| 2013-04-29T12:26:31
| 2013-04-29T12:26:31
| 3,153,698
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,401
|
hpp
|
CreateSDFields.hpp
|
// Copyright (C) 2010-2011 von Karman Institute for Fluid Dynamics, Belgium
//
// This software is distributed under the terms of the
// GNU Lesser General Public License version 3 (LGPLv3).
// See doc/lgpl.txt and doc/gpl.txt for the license text.
#ifndef cf3_sdm_CreateSDFields_hpp
#define cf3_sdm_CreateSDFields_hpp
////////////////////////////////////////////////////////////////////////////////
#include "solver/Action.hpp"
#include "sdm/LibSDM.hpp"
////////////////////////////////////////////////////////////////////////////////
namespace cf3 {
namespace sdm {
//////////////////////////////////////////////////////////////////////////////
/// This class defines an action that creates a space in the mesh
/// with sdm shape functions, and a configurable order of polynomial.
/// Default polynomial order = 0.
/// that returns information about the mesh
/// @author Willem Deconinck
class sdm_API CreateSDFields : public solver::Action
{
public: // functions
/// constructor
CreateSDFields( const std::string& name );
/// Gets the Class name
static std::string type_name() { return "CreateSDFields"; }
virtual void execute();
}; // end CreateSDFields
////////////////////////////////////////////////////////////////////////////////
} // sdm
} // cf3
////////////////////////////////////////////////////////////////////////////////
#endif // cf3_sdm_CreateSDFields_hpp
|
a199dc8ec35b88c41e9b0ed6917576ed2d8dd388
|
aa5bde78ca59672ec5f7953100a511f14dc23716
|
/xdbd-sql-parser/XdbdSqlCatalogFunction.cpp
|
c60be64101bfa56df6178c3904d4291ed8d42350
|
[] |
no_license
|
miranvodnik/xdbd
|
5dbb530a7db3b8575cbe87e37bbe90e2a7b5bced
|
ae4ab6bb53b11c307951c6b9c67bbfa59cb42c5c
|
refs/heads/main
| 2023-04-03T18:51:18.963054
| 2021-04-18T14:36:21
| 2021-04-18T14:36:21
| 358,135,606
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,329
|
cpp
|
XdbdSqlCatalogFunction.cpp
|
/*
* XdbdSqlCatalogFunction.cpp
*
* Created on: 4. feb. 2016
* Author: miran
*/
#include <sqlxdbd.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <XdbdSqlCatalogFunction.h>
namespace xml_db_daemon
{
XdbdSqlCatalogFunction::XdbdSqlCatalogFunction(sql_statement* p_sql_statement, int ecount)
{
Reset ();
m_sql_statement = p_sql_statement;
}
XdbdSqlCatalogFunction::~XdbdSqlCatalogFunction()
{
}
void XdbdSqlCatalogFunction::Reset()
{
m_sql_statement = 0;
m_sql_set_statement = 0;
m_sql_catalog = 0;
m_shmSize = 0;
m_hdrSize = 0;
}
int XdbdSqlCatalogFunction::BindParameters (XdbdShmSegment* shmSegment)
{
return 0;
}
int XdbdSqlCatalogFunction::ExecuteCatalogStatement (XdbdShmSegment* shmSegment)
{
return 0;
}
int XdbdSqlCatalogFunction::CreatePreparedSet (XdbdShmSegment* shmSegment)
{
int result = -1;
do
{
m_hdrSize = xdbdalign (6 * sizeof (int), long);
unsigned char* shmAddr = (unsigned char*) shmSegment->Resize (m_hdrSize);
unsigned char* addr = shmAddr;
if (addr == MAP_FAILED)
{
xdbdErrReport (SC_XDBD, SC_ERR, err_info ("mmap (%d) failed, errno = %d"), m_hdrSize, errno);
break;
}
unsigned char* buff = addr;
((int*)buff) [g_shmSizeIndex] = m_hdrSize;
((int*)buff) [g_parCountIndex] = 0;
((int*)buff) [g_parSizeIndex] = 0;
((int*)buff) [g_colCountIndex] = 0;
((int*)buff) [g_colSizeIndex] = 0;
((int*)buff) [g_rowCountIndex] = 0;
shmSegment->hdrSize(m_hdrSize);
result = 0;
#if defined (_DEBUG)
dump (addr, shmsize);
#endif
}
while (false);
return result;
}
int XdbdSqlCatalogFunction::Prepare (XdbdShmSegment* shmSegment, bool create)
{
m_sql_statement->Traverse(this);
if (create)
CreatePreparedSet (shmSegment);
return (m_sql_catalog == 0) ? -1 : 0;
}
int XdbdSqlCatalogFunction::Execute (XdbdShmSegment* shmSegment)
{
return 0;
}
#define CLASSNAME XdbdSqlCatalogFunction
#define sql_catalog_CallbackDefined
void CLASSNAME::Invoke_sql_catalog_Callback (SqlCallbackReason reason, unsigned int kind, sql_catalog* p_sql_catalog)
{
switch (reason)
{
case DefaultCallbackReason:
break;
case TraversalPrologueCallbackReason:
m_sql_catalog = p_sql_catalog;
break;
case TraversalEpilogueCallbackReason:
break;
}
}
#include "SqlCompilerCallbackImpls.template"
} /* namespace xml_db_daemon */
|
042efa03f23052358cfc3b99e93049f6f98b6890
|
3ffce592216241206f3f7025ccde5540beedf43e
|
/include/Matrix2D.h
|
441c08f2a5b640f30fd1dcf612b526874f0e35be
|
[] |
no_license
|
ogsdave/PatchMatch
|
323b0bb8e238dc2ee31cb7f97a4f1dfdeb48428d
|
8730f318248b296baf10728776790163034c5a31
|
refs/heads/master
| 2020-08-04T16:01:54.850218
| 2019-02-05T09:29:17
| 2019-02-05T09:29:17
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,151
|
h
|
Matrix2D.h
|
#ifndef __MATRIX_2D_H__
#define __MATRIX_2D_H__
#include <vector>
template <typename T>
class Matrix2D
{
public:
Matrix2D();
Matrix2D(unsigned int rows, unsigned int cols);
Matrix2D(unsigned int rows, unsigned int cols, const T& def);
T& operator()(unsigned int row, unsigned int col);
const T& operator()(unsigned int row, unsigned int col) const;
unsigned int rows;
unsigned int cols;
private:
// 用vector实现的二维数组
std::vector<std::vector<T>> data;
};
template <typename T>
Matrix2D<T>::Matrix2D() {}
template <typename T>
Matrix2D<T>::Matrix2D(unsigned int rows, unsigned int cols)
: rows(rows), cols(cols), data(rows, std::vector<T>(cols)) { }
template <typename T>
Matrix2D<T>::Matrix2D(unsigned int rows, unsigned int cols, const T &def)
: rows(rows), cols(cols), data(rows, std::vector<T>(cols, def)) { }
template <typename T>
inline T& Matrix2D<T>::operator()(unsigned int row, unsigned int col)
{
return data[row][col];
}
template <typename T>
inline const T& Matrix2D<T>::operator()(unsigned int row, unsigned int col) const
{
return data[row][col];
}
#endif //__MATRIX_2D_H__
|
f72e6fc1590376940eff91db70665f1a2106df2b
|
db6c1ca997e3928888b071cd0b21d275cd9e0b57
|
/KruskalAlgorithm.cpp
|
06dec488073e7e76259236e35701229e9baccc4f
|
[] |
no_license
|
leve1997/Razni_kodovi
|
d23ea861705957f95a37e81ad8a69a55017b090f
|
78e505975e432826c14214dcaf31017e68277133
|
refs/heads/master
| 2021-05-17T12:22:02.415868
| 2020-10-14T08:44:56
| 2020-10-14T08:44:56
| 250,773,754
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,480
|
cpp
|
KruskalAlgorithm.cpp
|
#include<vector>
#include<set>
#include<utility>
#include<iostream>
#include<limits>
#include<algorithm>
#include "DisjointSetImpl.h"
#define inf INT_MAX/2
void KruskalMST (std::vector<std::pair <int, std::pair <int, int> > > & edges, int n, std::vector <std::vector <int> > & Parent) {
std::sort(edges.begin(), edges.end());
DisjointSet ds(n);
int brojac = 0;
for (auto it = edges.begin(); it != edges.end(); it++) {
int u = it->second.first;
int v = it->second.second;
int tezina = it->first;
int rep_u = ds.Find(u);
int rep_v = ds.Find(v);
if (rep_u != rep_v) {
Parent[brojac][0] = u;
Parent[brojac][1] = v;
Parent[brojac++][2] = tezina;
ds.Unija(rep_u, rep_v);
}
if (brojac == n - 1) break;
}
}
int main () {
int n, m;
std::cin >> n >> m;
std::vector <int> p(3);
std::vector<std::vector <int> > Parent(n - 1, p);
std::vector <std::pair <int, std::pair <int, int> > > edges;
edges.reserve(m);
std::cout << "Unesi graf" <<std::endl;
int a, b, c;
for (int i = 0; i < m; i++) {
std::cin >> a >> b >>c;
edges.push_back({c, {a, b}});
}
KruskalMST(edges, n, Parent);
for (int i = 0; i < Parent.size(); i++)
std::cout << Parent[i][0] << " <-> " << Parent[i][1] << " = " << Parent[i][2] << std::endl;
return 0;
}
|
83f550fb52b3dc44b7b6451d11fea010d3715acb
|
7f25ac596812ed201f289248de52d8d616d81b93
|
/haihongS/2016/07/2016_07_02.cpp
|
89b787721a4d4b5b9cb459573f2c3158cd128d6d
|
[] |
no_license
|
AplusB/ACEveryDay
|
dc6ff890f9926d328b95ff536abf6510cef57eb7
|
e958245213dcdba8c7134259a831bde8b3d511bb
|
refs/heads/master
| 2021-01-23T22:15:34.946922
| 2018-04-07T01:45:20
| 2018-04-07T01:45:20
| 58,846,919
| 25
| 49
| null | 2016-07-14T10:38:25
| 2016-05-15T06:08:55
|
C++
|
UTF-8
|
C++
| false
| false
| 1,598
|
cpp
|
2016_07_02.cpp
|
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <vector>
#include <map>
using namespace std;
typedef long long ll;
const int maxn=2e6+9;
const int inf=2e9+9;
int isprime[maxn];
int use[1000],own[maxn];
int pre();
int main()
{
pre();
int n,k;
while(~scanf("%d%d",&n,&k))
{
map<int,int> aha;
aha.clear();
memset(use,0,sizeof(use));
memset(own,0,sizeof(own));
int cnt=0;
int num=k;
for(int i=2;i*i<=k;i++)
{
if(num<=1) break;
if(isprime[i]==-1) continue;
if(num%i!=0) continue;
use[cnt++]=i;
while(num%i==0)
{
num/=i;
aha[i]+=1;
}
}
if(isprime[num]==1)
{
use[cnt++]=num;
aha[num]+=1;
}
/*
for(int i=0;i<cnt;i++)
{
printf("%d %d %d\n",i,use[i],aha[use[i]]);
}
*/
map<int,int> act;
act.clear();
for(int i=0;i<n;i++)
{
int c;
scanf("%d",&c);
if(own[c]==1) continue;
own[c]=1;
for(int j=0;j<cnt;j++)
{
int tmp=0;
while(c%use[j]==0)
{
c/=use[j];
tmp+=1;
}
act[use[j]]=max(act[use[j]],tmp);
}
}
int ans=1;
for(int i=0;i<cnt;i++)
{
if(aha[use[i]]>act[use[i]])
{
ans=-1;
break;
}
}
if(ans==1)
printf("Yes\n");
else
printf("No\n");
}
return 0;
}
int pre()
{
memset(isprime,0,sizeof(isprime));
isprime[1]=-1;
for(int i=2;i<maxn;i++)
{
if(isprime[i]==-1)
continue;
int flag=1;
for(int j=2;j*j<=i;j++)
{
if(i%j==0)
{
flag=-1;break;
}
}
if(flag==-1) continue;
isprime[i]=1;
for(int j=2*i;j<maxn;j+=i)
{
isprime[j]=-1;
}
}
return 0;
}
|
8ec14b7e1a49b66078d2ddd227de46df93a75656
|
403bf375dd26e8f64498ff54546f53febcda2966
|
/SymbolReader.h
|
0b54437d9ed233ea955229ee735606d40eafaf9e
|
[] |
no_license
|
dimitrijejankov/elf-class-reader
|
7289409f79bf73cfea89c30dffc2046c5bf5d1bf
|
5f852042df9689ad5999efa3cd8984c93837f3b8
|
refs/heads/master
| 2020-03-21T14:19:10.032448
| 2018-06-27T16:55:02
| 2018-06-27T16:55:02
| 138,651,573
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,653
|
h
|
SymbolReader.h
|
//
// Created by dimitrije on 6/24/18.
//
#ifndef TESTINGCLASSSTUFF_SYMBOLREADER_H
#define TESTINGCLASSSTUFF_SYMBOLREADER_H
#include <libelf.h>
#include <gelf.h>
#include <string>
#include <libdwarf/dwarf.h>
#include <libdwarf/libdwarf.h>
#include <vector>
#include <memory>
struct attributeType {
attributeType() = default;
/**
* Constructor with parameters
* @param name - the name of the type
* @param size - the size of the type in bytes
*/
attributeType(const std::string &name, size_t size) : name(name), size(size) {}
/**
* The name of the type
*/
std::string name;
/**
* The size of the type
*/
size_t size = 0;
};
struct attributeInfo {
/**
* The name of the attribute
*/
std::string name;
/**
* The size of the attribute
*/
size_t size;
/**
* The offset of the attribute
*/
size_t offset;
/**
* The type of the attribute
*/
std::string type;
};
struct methodInfo {
/**
* The name of the method
*/
std::string name;
/**
* The symbol of the method
*/
std::string symbol;
/**
* The return type of the method
*/
attributeType returnType;
/**
* The parameters of the method
*/
std::vector<attributeType> parameters;
};
struct classInfo {
/**
* Define the default constructor
*/
classInfo() {
attributes = std::make_shared<std::vector<attributeInfo>>();
methods = std::make_shared<std::vector<methodInfo>>();
}
/**
* The class name with the full namespace specification
*/
std::string className;
/**
* The attributes of the class
*/
std::shared_ptr<std::vector<attributeInfo>> attributes;
/**
* The methods of the class
*/
std::shared_ptr<std::vector<methodInfo>> methods;
};
class SymbolReader {
public:
/**
* Initialize the SymbolReader
*/
explicit SymbolReader();
/**
* Destroy the SymbolReader
*/
virtual ~SymbolReader();
/**
* Loads the file returns false if it fails or true if it can be loaded
* @return true if it succeed false otherwise
*/
bool load(std::string &fileName);
/**
*
* @param typeInfo
* @return
*/
classInfo getClassInformation(const std::type_info &typeInfo);
/**
*
* @param typeSpec
* @return
*/
classInfo getClassInformation(const std::string &typeSpec);
private:
/**
* Is this loaded
*/
bool isLoaded;
/**
* The name of file we are opening
*/
std::string fileName;
/**
* The file table index of the file we need to load
*/
int fd = -1;
/**
* The dwarf resource
*/
int dwarfRes = DW_DLV_ERROR;
Dwarf_Debug dbg = nullptr;
Dwarf_Error error;
Dwarf_Handler errhand = nullptr;
Dwarf_Ptr errarg = nullptr;
bool realTypeName(const std::type_info& typeInfo, std::string &typeName);
classInfo analyzeFile(std::vector<std::string> &realName);
void getDieAndSiblings(Dwarf_Debug dbg, Dwarf_Die in_die, int in_level, std::vector<std::string> &hierarchy, classInfo &ret);
bool isClassSymbol(Dwarf_Debug dbg, Dwarf_Die print_me, std::string &realName);
bool isNamespaceOrClass(Dwarf_Debug dbg, Dwarf_Die print_me, std::string &realName);
bool isAttributeSymbol(Dwarf_Die print_me);
bool isMethodSymbol(Dwarf_Die print_me);
void parseAttribute(Dwarf_Die cur_die, classInfo &ret);
attributeType getType(Dwarf_Die cur_die, std::string &previousName, unsigned int isPointer);
void extractClassInfo(Dwarf_Debug dbg, Dwarf_Die in_die, std::vector<std::string> &hierarchy, classInfo &ret);
void parseMethod(Dwarf_Die curDie, classInfo &info);
};
#endif //TESTINGCLASSSTUFF_SYMBOLREADER_H
|
6cf75266ad71815d1713c1b3ed7176ffc5e89cc8
|
1ebdd29688a516483e4f5f367a0d2aeea80bb411
|
/Commandmodel.cpp
|
63c10dcff1c9335eacb419856c588c6e4772bdd9
|
[] |
no_license
|
muxuewen/DesignMode
|
186c08c4c91b26e15ef8032965d37983642aae3a
|
48bef2dcc5b89bed7bf2898e91309123bea60a8c
|
refs/heads/master
| 2020-04-30T14:30:49.725045
| 2019-06-24T08:04:44
| 2019-06-24T08:04:44
| 176,892,926
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,480
|
cpp
|
Commandmodel.cpp
|
#include <iostream>
#include <string>
#include <vector>
using namespace std;
#define SAFE_DELETE(p) if(p){delete p;p = NULL;}
class Receiver
{
public:
void runcommand1()
{
cout << "first cmd" << endl;
}
void runcommand2()
{
cout << "second cmd" << endl;
}
};
class Command
{
public:
Command(Receiver* recv) :m_receiver(recv){}
virtual void Execute() = 0;
protected:
Receiver* m_receiver;
};
class ConcreteCommand1:public Command
{
public:
ConcreteCommand1(Receiver* recv) :Command(recv){}
virtual void Execute()
{
m_receiver->runcommand1();
}
};
class ConcreteCommand2 : public Command
{
public:
ConcreteCommand2(Receiver* recv) :Command(recv){}
virtual void Execute()
{
m_recv->runcommand2();
}
private:
Receiver* m_recv;
};
class Invoker
{
public:
void SetCmd(Command* cmd)
{
m_Command.push_back(cmd);
cout << "add cmd" << endl;
}
void Notify()
{
if (m_Command.empty())
return;
vector<Command*>::iterator iter;
for (iter = m_Command.begin(); iter != m_Command.end(); ++iter)
{
(*iter)->Execute();
}
}
private:
vector<Command*> m_Command;
};
int main(void)
{
Receiver* pRecv = new Receiver();
Command* cmd1 = new ConcreteCommand1(pRecv);
Command* cmd2 = new ConcreteCommand2(pRecv);
Invoker* pInvk = new Invoker();
pInvk->SetCmd(cmd1);
pInvk->SetCmd(cmd2);
pInvk->Notify();
//system("PAUSE");
getchar();
return 0;
}
|
49881638a116bfc6a04c578873bc5e93484b91eb
|
0eff74b05b60098333ad66cf801bdd93becc9ea4
|
/second/download/httpd/gumtree/httpd_repos_function_2399_httpd-2.2.23.cpp
|
8a0259b41bed95c9731c87fc6b831d9fcc4438b0
|
[] |
no_license
|
niuxu18/logTracker-old
|
97543445ea7e414ed40bdc681239365d33418975
|
f2b060f13a0295387fe02187543db124916eb446
|
refs/heads/master
| 2021-09-13T21:39:37.686481
| 2017-12-11T03:36:34
| 2017-12-11T03:36:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 370
|
cpp
|
httpd_repos_function_2399_httpd-2.2.23.cpp
|
static void ap_start_shutdown(void)
{
/* If the user tries to shut us down twice in quick succession then we
* may well get triggered while we are working through previous attempt
* to shutdown. We won't worry about even reporting it as it seems a little
* pointless.
*/
if (shutdown_pending == 1)
return;
shutdown_pending = 1;
}
|
43a5c351c74e62ef7bdadfe3890455889f58dd9f
|
4e38faaa2dc1d03375010fd90ad1d24322ed60a7
|
/include/RED4ext/Scripting/Natives/Generated/game/data/Vehicle_Record.hpp
|
8e41cc91b125370fd0f036f614e5a7a5686910f6
|
[
"MIT"
] |
permissive
|
WopsS/RED4ext.SDK
|
0a1caef8a4f957417ce8fb2fdbd821d24b3b9255
|
3a41c61f6d6f050545ab62681fb72f1efd276536
|
refs/heads/master
| 2023-08-31T08:21:07.310498
| 2023-08-18T20:51:18
| 2023-08-18T20:51:18
| 324,193,986
| 68
| 25
|
MIT
| 2023-08-18T20:51:20
| 2020-12-24T16:17:20
|
C++
|
UTF-8
|
C++
| false
| false
| 723
|
hpp
|
Vehicle_Record.hpp
|
#pragma once
// clang-format off
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/Scripting/Natives/Generated/game/data/SpawnableObject_Record.hpp>
namespace RED4ext
{
namespace game::data
{
struct Vehicle_Record : game::data::SpawnableObject_Record
{
static constexpr const char* NAME = "gamedataVehicle_Record";
static constexpr const char* ALIAS = "Vehicle_Record";
uint8_t unk78[0x158 - 0x78]; // 78
};
RED4EXT_ASSERT_SIZE(Vehicle_Record, 0x158);
} // namespace game::data
using gamedataVehicle_Record = game::data::Vehicle_Record;
using Vehicle_Record = game::data::Vehicle_Record;
} // namespace RED4ext
// clang-format on
|
0bd6b4b2b5d56d31eef8b6eecd152bb70aacd393
|
e40d6a8fe45dd4d769c2bcf27e4df3730d0a624a
|
/JUTGE/X30986_ca/S002-AC.cc
|
5ba44e2c251cfc8d16f1ee54b493f53c38dcc4af
|
[] |
no_license
|
masedo/FIB
|
bc193a840fb56b8181d2be1585799fef180b58df
|
084bfa233a3ea079a41ba28686f44be644b65be3
|
refs/heads/master
| 2021-09-12T18:14:16.497501
| 2018-04-19T19:43:31
| 2018-04-19T19:43:31
| 104,089,287
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 951
|
cc
|
S002-AC.cc
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
struct Paraula {
int num;
string lletres;
};
bool comp (const Paraula& a, const Paraula& b) {
if (a.num == b.num) return a.lletres < b.lletres;
else return a.num > b.num;
};
int main() {
int n;
while (cin >> n) {
vector <string> P(n);
for (int i = 0; i < n; ++i) {
cin >> P[i];
}
sort (P.begin(), P.end());
vector <Paraula> W;
int j = 0;
bool primer_p = false;
for (int i = 0; i < n; ++i) {
if (primer_p and P[i] == W[j].lletres) ++W[j].num;
else {
if (primer_p) ++j;
primer_p = true;
Paraula par;
par.num = 1;
par.lletres = P[i];
W.push_back(par);
}
}
sort (W.begin(), W.end(), comp);
int s = W.size();
for (int i = 0; i < s; ++i) {
cout << W[i].num << " " << W[i].lletres << endl;
}
cout << "----------" << endl;
}
}
|
d804443e4509e4e9a9d834b66879d05e5ea2ef6e
|
ff383401324de6a733c57014925e1db9e153b822
|
/Difficulty/Hard/[76] Minimum Window Substring/solution.cpp
|
14ad62b237b1b28462ed9834a427900307eab5c9
|
[] |
no_license
|
ForSign/Leetcode-1
|
7af7a74c9a5c01c7e67faa5f6e5874f4d3902565
|
9a2d41fb15304cc7aaff5a36aced5dc0ab6d3745
|
refs/heads/master
| 2023-03-15T20:21:07.254494
| 2020-10-14T08:04:24
| 2020-10-14T08:04:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,297
|
cpp
|
solution.cpp
|
/*
* @lc app=leetcode id=76 lang=cpp
*
* [76] Minimum Window Substring
*/
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;
class Solution {
public:
string minWindow(string s, string t) {
vector<int> map(128, 0);
for(auto c : t) ++map[c];
int begin = 0, end = 0, min_len = INT_MAX, min_begin = 0, counter = t.size(), s_size = s.size();
while (end < s_size) {
if (map[s[end]] > 0)
--counter;
--map[s[end]];
++end;
while (counter == 0){
if (end - begin < min_len){
min_begin = begin;
min_len = end - begin;
}
map[s[begin]]++;
if (map[s[begin]] > 0)
counter++;
++begin;
}
}
if (min_len != INT_MAX)
return s.substr(min_begin, min_len);
return "";
}
};
// bad implementation, Time Limit Exceeded
class Solution {
public:
string minWindow(string s, string t) {
unordered_map<char, int> t_hash_table;
vector<int> positions;
for(auto& c : t)
t_hash_table[c]++;
for(int i = 0; i < s.size(); ++i){
if (t_hash_table.find(s[i]) != t_hash_table.end())
positions.push_back(i);
}
if(positions.empty()) return "";
int t_len = t.size();
for(int length = t_len; length <= s.size(); length++){
if (positions.size() < t_len)
return "";
for(int i = positions[0]; i <= positions[positions.size() - t_len]; ++i){
if(i + length > s.size())
break;
else{
if (isValid(s.substr(i, length), t_hash_table))
return s.substr(i, length);
}
}
}
return "";
}
bool isValid(const string& s, const unordered_map<char, int>& ht){
auto ht_tmp = ht;
for (auto& c : s){
if (ht_tmp.find(c) != ht_tmp.end())
--ht_tmp[c];
}
for (auto& t : ht_tmp){
if (t.second > 0)
return false;
}
return true;
}
};
|
b46bfa742572e69939d349ebb0755459a605539a
|
a08ce0bec53d41ae51e768dcfb4ba686c62245e5
|
/FKSvr3Common/Source/FKMd5Ex.cpp
|
9d08863f5b59509ea093eb9dd4e6795715f8713b
|
[] |
no_license
|
adan830/FKServer3
|
2816e67fc5ed25dc476a9e750800071b2dd9632d
|
cf760b747c1a453a91298fef10fe39aac202e407
|
refs/heads/master
| 2021-05-05T20:17:27.881799
| 2017-03-16T07:39:20
| 2017-03-16T07:39:20
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,535
|
cpp
|
FKMd5Ex.cpp
|
/**
* created: 2013-4-6 23:51
* filename: FKMd5Ex
* author: FreeKnight
* Copyright (C):
* purpose:
*/
//------------------------------------------------------------------------
#include "../Include/Endec/FKMd5Ex.h"
#include <stdio.h>
#include <string.h>
#include "../Include/FKVsVer8Define.h"
//------------------------------------------------------------------------
bool MD5Data(const void* pData,size_t size,MD5_DIGEST *pMD5 )
{
MD5_CTX context;
MD5Init (&context);
MD5Update (&context, (unsigned char*)pData, size);
MD5Final (&context,pMD5);
return true;
}
//------------------------------------------------------------------------
bool MD5File(const char* pszFile,MD5_DIGEST *pMD5 )
{
FILE* fp =0;
errno_t err = fopen_s(&fp,pszFile,"rb");
if(!fp || err!=0) return false;
unsigned char buffer[8192];
size_t len;
fseek(fp,0,SEEK_END);
len = ftell(fp);
fseek(fp,0,SEEK_SET);
MD5_CTX context;
MD5Init (&context);
while( len ){
size_t readLen = (len < 8192 ? len : 8192);
if(1 != fread(buffer,readLen,1,fp)){
MD5Final (&context,pMD5);
if (fp){fclose(fp);fp=NULL;}
return false;
}
len -= readLen;
MD5Update (&context, buffer, readLen);
}
MD5Final (&context,pMD5);
if (fp){fclose(fp);fp=NULL;}
return true;
}
//------------------------------------------------------------------------
bool MD5String(const char* string,MD5_DIGEST* pMD5 )
{
size_t size = strlen(string);
return MD5Data(string,size,pMD5);
}
//------------------------------------------------------------------------
|
7195c8a070b8ff7204218f23028aec9f69c2e503
|
4d964c6c4445e5cddf192248a0c2fc964d956ef9
|
/plugins/trash/trashwidget.cpp
|
d9d8059d7cfa0d3c33c4e0835fe3e12a247e22bf
|
[] |
no_license
|
wangyingtaodeepin/dde-dock
|
25149fa4433bf5fac885384cf71c6b19684235fd
|
0c597c6597d6c25f32a65ffabde6bb3066088630
|
refs/heads/master
| 2021-01-12T16:17:56.553562
| 2016-10-24T03:10:42
| 2016-10-24T03:10:42
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,938
|
cpp
|
trashwidget.cpp
|
#include "constants.h"
#include "trashwidget.h"
#include <QPainter>
#include <QIcon>
#include <QApplication>
#include <QDragEnterEvent>
#include <QJsonDocument>
DWIDGET_USE_NAMESPACE
TrashWidget::TrashWidget(QWidget *parent)
: QWidget(parent),
m_popupApplet(new PopupControlWidget(this))
{
QIcon::setThemeName("deepin");
m_popupApplet->setVisible(false);
connect(m_popupApplet, &PopupControlWidget::emptyChanged, this, &TrashWidget::updateIcon);
updateIcon();
setAcceptDrops(true);
}
QWidget *TrashWidget::popupApplet()
{
return m_popupApplet;
}
QSize TrashWidget::sizeHint() const
{
return QSize(26, 26);
}
const QString TrashWidget::contextMenu() const
{
QList<QVariant> items;
items.reserve(2);
QMap<QString, QVariant> open;
open["itemId"] = "open";
open["itemText"] = tr("Open");
open["isActive"] = true;
items.push_back(open);
if (!m_popupApplet->empty())
{
QMap<QString, QVariant> empty;
empty["itemId"] = "empty";
empty["itemText"] = tr("Empty");
empty["isActive"] = true;
items.push_back(empty);
}
QMap<QString, QVariant> menu;
menu["items"] = items;
menu["checkableMenu"] = false;
menu["singleCheck"] = false;
return QJsonDocument::fromVariant(menu).toJson();
}
int TrashWidget::trashItemCount() const
{
return m_popupApplet->trashItems();
}
void TrashWidget::invokeMenuItem(const QString &menuId, const bool checked)
{
Q_UNUSED(checked);
if (menuId == "open")
m_popupApplet->openTrashFloder();
else if (menuId == "empty")
m_popupApplet->clearTrashFloder();
}
void TrashWidget::dragEnterEvent(QDragEnterEvent *e)
{
if (e->mimeData()->hasFormat("RequestDock"))
return e->accept();
if (e->mimeData()->hasFormat("text/uri-list"))
return e->accept();
}
void TrashWidget::dropEvent(QDropEvent *e)
{
if (e->mimeData()->hasFormat("RequestDock"))
return removeApp(e->mimeData()->data("AppKey"));
if (e->mimeData()->hasFormat("text/uri-list"))
{
const QMimeData *mime = e->mimeData();
for (auto url : mime->urls())
moveToTrash(url);
}
}
void TrashWidget::paintEvent(QPaintEvent *e)
{
QWidget::paintEvent(e);
QPainter painter(this);
painter.drawPixmap(rect().center() - m_icon.rect().center(), m_icon);
}
void TrashWidget::resizeEvent(QResizeEvent *e)
{
QWidget::resizeEvent(e);
updateIcon();
}
void TrashWidget::mousePressEvent(QMouseEvent *e)
{
const QPoint dis = e->pos() - rect().center();
if (e->button() != Qt::RightButton || dis.manhattanLength() > std::min(width(), height()) * 0.8 * 0.5)
return QWidget::mousePressEvent(e);
emit requestContextMenu();
}
void TrashWidget::updateIcon()
{
const Dock::DisplayMode displayMode = qApp->property(PROP_DISPLAY_MODE).value<Dock::DisplayMode>();
QString iconString = "user-trash";
if (!m_popupApplet->empty())
iconString.append("-full");
if (displayMode == Dock::Efficient)
iconString.append("-symbolic");
const int size = displayMode == Dock::Fashion ? std::min(width(), height()) * 0.8 : 16;
QIcon icon = QIcon::fromTheme(iconString);
m_icon = icon.pixmap(size, size);
update();
}
void TrashWidget::removeApp(const QString &appKey)
{
const QString cmd("dbus-send --print-reply --dest=com.deepin.dde.Launcher /com/deepin/dde/Launcher com.deepin.dde.Launcher.UninstallApp string:\"" + appKey + "\"");
QProcess *proc = new QProcess;
proc->start(cmd);
proc->waitForFinished();
proc->deleteLater();
}
void TrashWidget::moveToTrash(const QUrl &url)
{
const QFileInfo info = url.toLocalFile();
QDir trashDir(m_popupApplet->trashDir() + "/files");
if (!trashDir.exists())
trashDir.mkpath(".");
QDir().rename(info.absoluteFilePath(), trashDir.absoluteFilePath(info.fileName()));
}
|
b11cb143e08e721b10acb1c066359f5ff0eb877f
|
ee85bee36fac8052d49355e0ed40ae1dc72e53e5
|
/Course Assignment Solutions/University of California, San Diego (UCSD)/CSE 100 - Advanced Data Structures/PA2 - RST and benchtree/benchtree.cpp
|
54caae5a33a084bb07b463477d98525805bf3fb6
|
[] |
no_license
|
hak053/Algorithm-Problem-Solutions
|
c0a09dc2ed6397c75362b9d1dd050a2df2a4f0cf
|
79e248e9b1d824b95b7c000589ac9163861fcada
|
refs/heads/master
| 2021-01-23T02:29:44.427032
| 2015-05-17T21:36:09
| 2015-05-17T21:36:09
| 45,626,345
| 0
| 1
| null | 2015-11-05T17:07:06
| 2015-11-05T17:07:05
| null |
UTF-8
|
C++
| false
| false
| 5,850
|
cpp
|
benchtree.cpp
|
/**
* Alexander Niema Moshiri
* A09850737
* a1moshir@ucsd.edu
* PA2 (No Partner)
*/
#include <iostream>
#include "RST.hpp"
#include "countint.hpp"
#include <cmath>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
using namespace std;
int main(int argc, char* argv[]) {
/** Initialize Variables */
int maxSize = -1; /** initialize max size to -1 */
int numRuns = -1; /** initialize number of runs to -1 */
int structure = -1; /** 1 = bst, 2 = rst, 3 = set */
bool shuffle = false; /** initialize shuffle bool */
/******************** BEGIN ARGUMENT PARSE ********************/
/** Ensure 4 arguments */
if(argc != 5)
{
cout << "Invalid usage: must have 4 arguments." << endl;
exit(0);
}
else
{
cout << "# Benchmarking average number of comparisons for successful find";
cout << endl;
}
/** Create new strings for the arguments, for convenience */
string arg1 = argv[1];
string arg2 = argv[2];
string arg3 = argv[3];
string arg4 = argv[4];
/** Parse 1st argument as "bst", "rst", or "set" */
if(arg1 == "bst")
{
structure = 1;
}
else if(arg1 == "rst")
{
structure = 2;
}
else if(arg1 == "set")
{
structure = 3;
}
else
{
cout << "Invalid Argument 1. Options: bst, rst, set" << endl;
exit(0);
}
cout << "# Data structure: " << arg1 << endl;
/** Parse 2nd argument as "sorted" or "shuffled" */
if(arg2 == "sorted")
{
shuffle = false;
}
else if(arg2 == "shuffled")
{
shuffle = true;
}
else
{
cout << "Invalid Argument 2. Options: sorted, shuffled" << endl;
exit(0);
}
cout << "# Data: " << arg2 << endl;
/** Parse 3rd argument as the max size of the data structure */
for(unsigned i = 0; i < arg3.size(); i++)
{
if(!isdigit(arg3[i]))
{
cout << "Invalid Argument 3. Max size must be an integer." << endl;
exit(0);
}
}
maxSize = atoi(argv[3]); /** If it doesn't fail, valid capacity entered */
cout << "# N is powers of 2, minus 1, from 1 to " << arg3 << endl;
/** Parse 4th argument as the number of runs */
for(unsigned i = 0; i < arg4.size(); i++)
{
if(!isdigit(arg4[i]))
{
cout << "Invalid Argument 4. Number of Runs must be an integer." << endl;
exit(0);
}
}
numRuns = atoi(argv[4]); /** If it doesn't fail, valid num runs entered */
cout << "# Averaging over " << arg4 << " runs for each N " << endl;
/******************** END ARGUMENT PARSE ********************/
cout << "#" << endl;
cout.width(arg3.size()); cout << left << "# N\t";
cout.width(8); cout << right << "avgcomps\t";
cout.width(8); cout << right << "stdev" << endl;
/** Outer Loop, Each N */
for(int N = 1; N <= maxSize; N = 2*N + 1) /** Used mathematical pattern */
{
/** Initialize sum and sumSquare Variables */
double sum = 0;
double sumSquare = 0;
/** Inner Loop, Each Trial */
for(int run = 0; run < numRuns; run++)
{
/** Initialize the data structures */
std::set<countint> set; /** initialize set */
BST<countint> bst = BST<countint>(); /** initialize BST */
RST<countint> rst = RST<countint>(); /** initialize RST */
/** Create vector of N distinct key */
std::vector<countint> v;
v.clear();
for(int i = 0; i < N; i++)
{
v.push_back(i);
}
/** If in Shuffle Mode, shuffle the elements randomly */
if(shuffle)
{
std::random_shuffle(v.begin(),v.end());
}
/** Add elements into empty structure */
std::vector<countint>::iterator vit = v.begin();
std::vector<countint>::iterator ven = v.end();
for(vit = v.begin(); vit != ven; ++vit)
{
/** If Structure is BST, add into BST */
if(structure == 1)
{
bst.insert(*vit);
}
/** If Structure is RST, add into RST */
else if(structure == 2)
{
rst.insert(*vit);
}
/** If Structure is Set, add into Set */
else if(structure == 3)
{
set.insert(*vit);
}
/** If none of those, something's wrong */
else
{
cout << "Something went wrong: Data Structure is not set." << endl;
exit(0);
}
}
/** Find how many comparisons (on average) to find a key */
countint::clearcount();
for(vit = v.begin(); vit != ven; ++vit)
{
/** If Structure is BST, find from BST */
if(structure == 1)
{
bst.find(*vit);
}
/** If Structure is RST, find from RST */
else if(structure == 2)
{
rst.find(*vit);
}
/** If Structure is Set, find from Set */
else if(structure == 3)
{
set.find(*vit);
}
/** If none of those, something's wrong */
else
{
cout << "Something went wrong: Data Structure is not set." << endl;
exit(0);
}
}
double avgcomps = countint::getcount()/(double)N;
sum += avgcomps;
sumSquare += avgcomps*avgcomps;
/*cout << "AvgComps: " << avgcomps << "; Sum: " << sum << "; SumSquare: " << sumSquare << endl;*/
}
/** We now have sum and sumSquare of avgtime for all runs for this N */
double tHat = sum / (double)numRuns;
double sHat = sumSquare / (double)numRuns;
double stdev;
if(abs(sHat - (tHat*tHat)) < 1e-6) // If standard deviation is very tiny,
{
stdev = 0; // set it to 0
}
else
{
stdev = (double)sqrt(sHat - (tHat*tHat));
}
/** Now print the results! */
cout.width(arg3.size()); cout << N << "\t";
cout.width(8); cout << right << tHat << "\t";
cout.width(8); cout << right << stdev << endl;
}
}
|
b3ab3b941e561e7792788042fbfa3c58c0cc6415
|
d071e6156cf23ddee37a612f71d71a650c27fcfe
|
/hlg_pass/hlg1408_wo.cpp
|
762c2d0abb22029359dc7eec5d6d9aaf94917127
|
[] |
no_license
|
tsstss123/code
|
57f1f7d1a1bf68c47712897e2d8945a28e3e9862
|
e10795c35aac442345f84a58845ada9544a9c748
|
refs/heads/master
| 2021-01-24T23:00:08.749712
| 2013-04-30T12:33:24
| 2013-04-30T12:33:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,025
|
cpp
|
hlg1408_wo.cpp
|
#include <cstdio>
#include <cstring>
#include <climits>
#include <iostream>
using namespace std;
const int MAXN = 505;
int a[MAXN][MAXN];
int s[MAXN][MAXN];
int o[2][MAXN][MAXN];
/*
inline int BLOCK(int lx, int ly, int hx, int hy) {
return s[hx][hy] - s[lx-1][hy] - s[hx][ly-1] + s[lx-1][ly-1];
}
*/
#define BLOCK(lx, ly, hx, hy) (s[hx][hy] - s[lx-1][hy] - s[hx][ly-1] + s[lx-1][ly-1])
int main()
{
int n, m;
while (2 == scanf("%d %d", &n, &m)) {
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
scanf("%d", &a[i][j]);
o[1][i][j] = a[i][j];
s[i][j] = s[i-1][j] + s[i][j-1] - s[i-1][j-1] + a[i][j];
}
}
int l = min(n, m);
int ans = -INT_MAX;
int c = 0;
for (int k = 3; k <= l; k += 2) {
for (int i = 1; i+k-1 <= n; ++i) {
for (int j = 1; j+k-1 <= m; ++j) {
o[c][i][j] = BLOCK(i, j, i + k - 1, j + k - 1) - a[i+1][j] - o[1-c][i+1][j+1];
if (ans < o[c][i][j]) {
ans = o[c][i][j];
}
}
}
c = 1 - c;
}
printf("%d\n", ans);
}
return 0;
}
|
b6584f18876e72116ec23c95349200779fc72d5b
|
7412daba6b198687506ec73bad2786ac966963e6
|
/calibration_tool1/calibrate/cam_opencv_calib_extrinstic/readdata.cpp
|
b88e983b3b8083863669e4583978d72b46bcfdbd
|
[
"WTFPL"
] |
permissive
|
Zhangh2018/SLAMnDNN
|
ace6cf38bae8666f4d14a5ca36855deb9f8abec7
|
b96d5b35bf22ca4aaa5b9abf6ad73a3c274da5f2
|
refs/heads/master
| 2022-04-07T16:54:23.247971
| 2020-01-30T03:45:25
| 2020-01-30T03:45:25
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 15,730
|
cpp
|
readdata.cpp
|
#include <iostream>
#include <sstream>
#include <time.h>
#include <stdio.h>
#include <fstream>
#include <opencv2/core.hpp>
#include <opencv2/core/utility.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/calib3d.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/highgui.hpp>
using namespace std;
using namespace cv;
#define __DEBUG_MG__ 1
static double computeReprojectionErrors( const vector<vector<Point3f> >& objectPoints,
const vector<vector<Point2f> >& imagePoints,
const vector<Mat>& rvecs, const vector<Mat>& tvecs,
const Mat& cameraMatrix , const Mat& distCoeffs,
vector<float>& perViewErrors, bool fisheye)
{
vector<Point2f> imagePoints2;
size_t totalPoints = 0;
double totalErr = 0, err;
perViewErrors.resize(objectPoints.size());
for(size_t i = 0; i < objectPoints.size(); ++i )
{
if (fisheye)
{
fisheye::projectPoints(objectPoints[i], imagePoints2, rvecs[i], tvecs[i], cameraMatrix,
distCoeffs);
}
else
{
projectPoints(objectPoints[i], rvecs[i], tvecs[i], cameraMatrix, distCoeffs, imagePoints2);
}
err = norm(imagePoints[i], imagePoints2, NORM_L2);
size_t n = objectPoints[i].size();
perViewErrors[i] = (float) std::sqrt(err*err/n);
totalErr += err*err;
totalPoints += n;
}
return std::sqrt(totalErr/totalPoints);
}
int main()
{
//MG
#if __DEBUG_MG__
// string world_coordinate_file_x_path = "./MG_pic/MG_08_21/src_data/world_x_left.txt";
// string world_coordinate_file_y_path = "./MG_pic/MG_08_21/src_data/world_y_left.txt";
// string pixel_coordinate_file_x_path = "./MG_pic/MG_12_06/left/left_x.txt";
// string pixel_coordinate_file_y_path = "./MG_pic/MG_12_06/left/left_y.txt";
//
// string camera_instrinstic_path = "./MG_pic/MG_09_18/Intersic_Parameters/ocam_intrinsic_MG_left.txt";
// string distortiion_coefficients_path = "./MG_pic/MG_09_18/Intersic_Parameters/distortiion_coefficients_MG_left.txt";
string world_coordinate_file_x_path = "/home/caobei/calibration_tool/calibrate/cam_opencv_calib_extrinstic/RW_20190123/world/world_x_right.txt";
string world_coordinate_file_y_path = "/home/caobei/calibration_tool/calibrate/cam_opencv_calib_extrinstic/RW_20190123/world/world_y_right.txt";
string pixel_coordinate_file_x_path = "/home/caobei/calibration_tool/calibrate/cam_opencv_calib_extrinstic/RW_20190123/right/right_x.txt";
string pixel_coordinate_file_y_path = "/home/caobei/calibration_tool/calibrate/cam_opencv_calib_extrinstic/RW_20190123/right/right_y.txt";
string camera_instrinstic_path = "/home/caobei/calibration_tool/calibrate/cam_opencv_calib_extrinstic/RW_20190123/Intersic_Parameter/ocam_intrinsic_right.txt";
string distortiion_coefficients_path = "/home/caobei/calibration_tool/calibrate/cam_opencv_calib_extrinstic/RW_20190123/Intersic_Parameter/distortiion_coefficients_right.txt";
#else //GL8
string world_coordinate_file_x_path = "./GL8_6_26_installed/src_data/world_back_x.txt";
string world_coordinate_file_y_path = "./GL8_6_26_installed/src_data/world_back_y.txt";
string pixel_coordinate_file_x_path = "./GL8_6_26_installed/src_data/back_x.txt";
string pixel_coordinate_file_y_path = "./GL8_6_26_installed/src_data/back_y.txt";
string camera_instrinstic_path = "./GL8_6_26_installed/camera_matrix/camera_intrinsic_back.txt";
string distortiion_coefficients_path = "./GL8_6_26_installed/camera_matrix/camera_distortion_coefficients_back.txt";
#endif
// char output_file_trans[] = "./output/trans";
// char output_file_K_optimized[] = "./output/optimized_K";
// char output_file_D_optimized[] = "./output/optimized_D";
// char output_file_totalAvgErr[] = "./output/totalAvgErr";
// char output_file_result[] = "./output/result";
char output_file_trans[] = "/home/caobei/calibration_tool/calibrate/cam_opencv_calib_extrinstic/RW_20190123/right/output/trans";
char output_file_K_optimized[] = "/home/caobei/calibration_tool/calibrate/cam_opencv_calib_extrinstic/RW_20190123/right/output/optimized_K";
char output_file_D_optimized[] = "/home/caobei/calibration_tool/calibrate/cam_opencv_calib_extrinstic/RW_20190123/right/output/optimized_D";
char output_file_totalAvgErr[] = "/home/caobei/calibration_tool/calibrate/cam_opencv_calib_extrinstic/RW_20190123/right/output/totalAvgErr";
char output_file_result[] = "/home/caobei/calibration_tool/calibrate/cam_opencv_calib_extrinstic/RW_20190123/right/output/result";
vector<Point3f> object;
vector<vector<Point3f>> objectv;
vector<Point2f> imagepix;
vector<vector<Point2f>> imagev;
//数据文件相关输入流
ifstream infilex;
ifstream infiley;
ifstream infile_imagex;
ifstream infile_imagey;
ifstream camera_matrix;
ifstream distortiion_coefficients;
//文件指针,用于写入输出数据
FILE *fp_trans = fopen(output_file_trans,"w+");
FILE *fp_trans_camera_K = fopen(output_file_K_optimized,"w+");
FILE *fp_trans_camera_D = fopen(output_file_D_optimized,"w+");
FILE *fp_trans_totalAvgErr = fopen(output_file_totalAvgErr,"w+");
FILE *fp_trans_result = fopen(output_file_result,"w+");
//打开相关数据文件
infilex.open(world_coordinate_file_x_path,ios::in);
infiley.open(world_coordinate_file_y_path,ios::in);
infile_imagex.open(pixel_coordinate_file_x_path,ios::in);
infile_imagey.open(pixel_coordinate_file_y_path,ios::in);
camera_matrix.open(camera_instrinstic_path,ios::in);
distortiion_coefficients.open(distortiion_coefficients_path,ios::in);
if(!infilex)
{
cout<<"fail to open the file "<<world_coordinate_file_x_path<<endl;
exit(1);
}
if(!infiley)
{
cout<<"fail to open the file "<<world_coordinate_file_y_path<<endl;
exit(1);
}
if(!infile_imagex)
{
cout<<"fail to open the file "<<pixel_coordinate_file_x_path<<endl;
exit(1);
}
if(!infile_imagey)
{
cout<<"fail to open the file "<<pixel_coordinate_file_y_path<<endl;
exit(1);
}
if(!camera_matrix)
{
cout<<"fail to open the file "<<camera_instrinstic_path<<endl;
exit(1);
}
if(!distortiion_coefficients)
{
cout<<"fail to open the file "<<distortiion_coefficients_path<<endl;
exit(1);
}
//相机内参和畸变系数
Mat K(3,3,CV_64FC1);
Mat D(4,1,CV_64FC1);
//
// Mat raw_image = imread("./GL8/image/front.bmp");
// int raw_width = raw_image.cols;
// int raw_height = raw_image.rows;
// cout<<"raw_width : "<<raw_width<<endl;
// cout<<"raw_height : "<<raw_height<<endl;
//
int raw_width = 1280;
int raw_height = 720;
//读取相机内参数据写入K
double RR;
int rr_index = 0;
cout<<"camera_matrix : "<<endl;
while(camera_matrix>>RR) // 1、文本文件的读写: 用插入器(<<)向文件输出; 用析取器(>>)从文件输入。 //从camera_matrix文本中读取一个double值。
{
K.at<double>(rr_index, 0) = RR;
cout<<RR<< " ";
camera_matrix >> RR;
K.at<double>(rr_index, 1) = RR;
cout<<RR<<" ";
camera_matrix >> RR;
K.at<double>(rr_index, 2) = RR;
cout<<RR<<endl;
rr_index++;
}
if(rr_index >3 )
{
cout<<"camera_matrix.txt is illegal"<<endl;
exit(1);
}
//读取畸变系数,写入D
double coeff;
distortiion_coefficients >> coeff;
D.at<double>(0, 0) = coeff;
cout<<"coeff: "<<coeff<< " ";
distortiion_coefficients >> coeff;
D.at<double>(1, 0) = coeff;
cout<<coeff<< " ";
distortiion_coefficients >> coeff;
D.at<double>(2, 0) = coeff;
cout<<coeff<< " ";
distortiion_coefficients >> coeff;
D.at<double>(3, 0) = coeff;
cout<<coeff<<endl;
//读取位置坐标和像素坐标
double datax;
double datay;
double data_imagex;
double data_imagey;
int i = 0;
while(infilex>>datax)
{
infiley>>datay;
infile_imagex>>data_imagex;
infile_imagey>>data_imagey;
object.push_back(Point3f(datax,datay,0));
imagepix.push_back(Point2f(data_imagex,data_imagey));
cout<<"object coordinate and imagepixel coordinate : "<<i<<": "<<object[i]<<imagepix[i]<<endl;
i++;
}
objectv.push_back(object);
imagev.push_back(imagepix);
vector<Point3f> object2;
vector<Point2f> imagepix2;
infilex.close();
infiley.close();
infile_imagex.close();
infile_imagey.close();
Mat rvecsm;
Mat tvecsm;
int flags = 0;
flags += cv::fisheye::CALIB_USE_INTRINSIC_GUESS; //若指定此标签,必须保证cameraMatrix包含有效的fx、fy、cx、cy的初始值。否则(cx,cy)最初被设置为图像中心。焦距以最小二乘计算
flags += cv::fisheye::CALIB_RECOMPUTE_EXTRINSIC; //每次优化迭代内参后重新计算外参
//flags |= cv::fisheye::CALIB_CHECK_COND; //检查条件号的有效性
flags += cv::fisheye::CALIB_FIX_SKEW; //保持fx与fy相同
//flags |= cv::fisheye::CALIB_FIX_K1; //鱼眼畸变系数选择哪一个置为0并保持为0。即为某一系数固定为0
//flags |= cv::fisheye::CALIB_FIX_K2;
//flags |= cv::fisheye::CALIB_FIX_K3;
//flags |= cv::fisheye::CALIB_FIX_K4;
flags += cv::fisheye::CALIB_FIX_INTRINSIC; //固定内参
cv::Mat K_before = K.clone();
cv::Mat D_before = D.clone();
cout << "K_before_optimize: " << K_before << endl;
cout << "D_before_optimize: " << D_before << endl;
double rms = 0;
rms = cv::fisheye::calibrate(objectv, imagev, cv::Size(raw_width,raw_height), K, D, rvecsm, tvecsm, flags);
cout << "K_after_optimize: " << K << endl;
cout << "D_after_optimize: " << D << endl;
cout<<"rvecsm : "<<rvecsm<<endl;
cout<<"tvecsm : "<<tvecsm<<endl;
Mat row1 = rvecsm.rowRange(0,1).clone();
cout<<"row1 : "<<row1<<endl;
Mat rvecsm2rmatrix;
cv::Rodrigues(row1, rvecsm2rmatrix); //罗德李格斯公式将旋转向量转换成旋转矩阵
cout<<"rvecsm2rmatrix : "<<rvecsm2rmatrix<<endl;
#if 1
// 赋值。R直接赋值
Mat srcR(3,3,CV_32F);
srcR.at<float>(0,0) = float(rvecsm2rmatrix.at<double>(1,0));
srcR.at<float>(0,1) = float(rvecsm2rmatrix.at<double>(1,1));
srcR.at<float>(0,2) = float(rvecsm2rmatrix.at<double>(1,2));
srcR.at<float>(1,0) = float(rvecsm2rmatrix.at<double>(0,0));
srcR.at<float>(1,1) = float(rvecsm2rmatrix.at<double>(0,1));
srcR.at<float>(1,2) = float(rvecsm2rmatrix.at<double>(0,2));
srcR.at<float>(2,0) = float(rvecsm2rmatrix.at<double>(2,0));
srcR.at<float>(2,1) = float(rvecsm2rmatrix.at<double>(2,1));
srcR.at<float>(2,2) = float(rvecsm2rmatrix.at<double>(2,2));
//T由行向量变为列向量
Mat srcT(3,1,CV_32F);
srcT.at<float>(0,0) = float(tvecsm.at<double>(0,1));
srcT.at<float>(1,0) = float(tvecsm.at<double>(0,0));
srcT.at<float>(2,0) = float(tvecsm.at<double>(0,2));
std::cout<< "srcR:"<< srcR << endl;
std::cout<< "srcT:"<< srcT << endl;
Mat verification_result = -(srcR.inv())*srcT;
cout << "verification_result:" << verification_result<< endl;
#endif
//将结果rt写入文件,存为T矩阵,外参矩阵。
//调整相机坐标系,外参第一行和第二行互换 [liuli 2019/01/11]
// double R11 = rvecsm2rmatrix.at<double>(0,0);
// double R12 = rvecsm2rmatrix.at<double>(0,1);
// double R13 = rvecsm2rmatrix.at<double>(0,2);
// double R21 = rvecsm2rmatrix.at<double>(1,0);
// double R22 = rvecsm2rmatrix.at<double>(1,1);
// double R23 = rvecsm2rmatrix.at<double>(1,2);
double R11 = rvecsm2rmatrix.at<double>(1,0);
double R12 = rvecsm2rmatrix.at<double>(1,1);
double R13 = rvecsm2rmatrix.at<double>(1,2);
double R21 = rvecsm2rmatrix.at<double>(0,0);
double R22 = rvecsm2rmatrix.at<double>(0,1);
double R23 = rvecsm2rmatrix.at<double>(0,2);
double R31 = rvecsm2rmatrix.at<double>(2,0);
double R32 = rvecsm2rmatrix.at<double>(2,1);
double R33 = rvecsm2rmatrix.at<double>(2,2);
// double T1 = tvecsm.at<double>(0,0);
// double T2 = tvecsm.at<double>(0,1);
double T1 = tvecsm.at<double>(0,1);
double T2 = tvecsm.at<double>(0,0);
double T3 = tvecsm.at<double>(0,2);
fprintf(fp_trans,"%15.9f",R11);
fprintf(fp_trans,"%15.9f",R12);
fprintf(fp_trans,"%15.9f",R13);
fprintf(fp_trans,"%15.9f\n",T1);
fprintf(fp_trans,"%15.9f",R21);
fprintf(fp_trans,"%15.9f",R22);
fprintf(fp_trans,"%15.9f",R23);
fprintf(fp_trans,"%15.9f\n",T2);
fprintf(fp_trans,"%15.9f",R31);
fprintf(fp_trans,"%15.9f",R32);
fprintf(fp_trans,"%15.9f",R33);
fprintf(fp_trans,"%15.9f\n",T3);
//优化后的相机内参矩阵K存储
double K11 = K.at<double>(0,0);
double K12 = K.at<double>(0,1);
double K13 = K.at<double>(0,2);
double K21 = K.at<double>(1,0);
double K22 = K.at<double>(1,1);
double K23 = K.at<double>(1,2);
double K31 = K.at<double>(2,0);
double K32 = K.at<double>(2,1);
double K33 = K.at<double>(2,2);
fprintf(fp_trans_camera_K,"%15.9f",K11);
fprintf(fp_trans_camera_K,"%15.9f",K12);
fprintf(fp_trans_camera_K,"%15.9f\n",K13);
fprintf(fp_trans_camera_K,"%15.9f",K21);
fprintf(fp_trans_camera_K,"%15.9f",K22);
fprintf(fp_trans_camera_K,"%15.9f\n",K23);
fprintf(fp_trans_camera_K,"%15.9f",K31);
fprintf(fp_trans_camera_K,"%15.9f",K32);
fprintf(fp_trans_camera_K,"%15.9f",K33);
//优化后的畸变系数存储
double D1 = D.at<double>(0,0);
double D2 = D.at<double>(0,1);
double D3 = D.at<double>(0,2);
double D4 = D.at<double>(0,3);
fprintf(fp_trans_camera_D,"%15.9f\n",D1);
fprintf(fp_trans_camera_D,"%15.9f\n",D2);
fprintf(fp_trans_camera_D,"%15.9f\n",D3);
fprintf(fp_trans_camera_D,"%15.9f\n",D4);
//平均误差存储
fprintf(fp_trans_totalAvgErr,"%15.9f\n",rms);
//result存储
double result00 = verification_result.at<float>(0,0);
double result10 = verification_result.at<float>(1,0);
double result20 = verification_result.at<float>(2,0);
fprintf(fp_trans_result,"%15.9f\n",result00);
fprintf(fp_trans_result,"%15.9f\n",result10);
fprintf(fp_trans_result,"%15.9f\n",result20);
double totalAvgErr = 0;
vector<float> projectErrors;
vector<Mat> rvecs;
vector<Mat> tvecs;
double r11 = rvecsm.at<double>(0,0);
double r12 = rvecsm.at<double>(0,1);
double r13 = rvecsm.at<double>(0,2);
double r14 = rvecsm.at<double>(1,0);
double r15 = rvecsm.at<double>(1,1);
double r16 = rvecsm.at<double>(1,2);
rvecs.reserve(rvecsm.rows);
tvecs.reserve(tvecsm.rows);
for(int i = 0; i < int(objectv.size()); i++){
rvecs.push_back(rvecsm.row(i));
tvecs.push_back(tvecsm.row(i));
}
totalAvgErr = computeReprojectionErrors(objectv, imagev, rvecs, tvecs, K, D, projectErrors, 1);
cout<<"rms = "<<rms<<endl;
cout<<"totalAvgErr = "<<totalAvgErr<<endl;
vector<float>::iterator vector_it;
for(vector_it = projectErrors.begin(); vector_it != projectErrors.end(); vector_it++)
{
cout<<"projectErrors = "<< *vector_it << endl;
}
fclose(fp_trans);
fclose(fp_trans_camera_K);
fclose(fp_trans_camera_D);
fclose(fp_trans_totalAvgErr);
return 0;
}
|
ca7d3cdb8df4a20bf0be344b44661cad28019d41
|
82f04e0942b580299a3880df75db74c7e7cb3638
|
/Primatte/algorithmprimatte.cpp
|
98f895b96d322500fcd25167855b4dc801fe7403
|
[
"MIT"
] |
permissive
|
thuanvh/EstimateImageMatting
|
279c3b27e4d1ccbdc4ca3858151626243850dde4
|
2abbec761fce77ab256f82b1e2c618b29d99c131
|
refs/heads/master
| 2022-04-19T07:26:44.142108
| 2020-04-17T06:22:02
| 2020-04-17T06:22:02
| 255,775,824
| 0
| 0
|
MIT
| 2020-04-15T01:50:50
| 2020-04-15T01:50:49
| null |
UTF-8
|
C++
| false
| false
| 4,126
|
cpp
|
algorithmprimatte.cpp
|
#include "algorithmprimatte.h"
#include "ialphalocator.h"
#include "icoloursegmenter.h"
#include "ifittingalgorithm.h"
#include "inputassembler.h"
#include <stdexcept>
#include "io.h"
namespace anima
{
namespace alg
{
namespace primatte
{
AlgorithmPrimatte::AlgorithmPrimatte(AlgorithmPrimatteDesc desc)
: mAnalysed(false)
{
//Validate desc
if(!desc.segmenter)
throw std::runtime_error("Null segmenter");
if(!desc.alphaLocator)
throw std::runtime_error("Null alpha locator");
if(desc.innerPostShrinkingMultiplier < 0 ||
desc.innerShrinkingMinDistance < 0 ||
desc.innerShrinkingThreshold < 0 ||
desc.outerExpandDelta < 0 ||
desc.outerExpansionStartThreshold < 0 ||
desc.outerScaleParameter <0)
throw std::runtime_error("Algorithm parameter out of range");
//Try constructing a bounding polyhedron to validate its descriptor
BoundingPolyhedron(desc.boundingPolyhedronDesc);
//Set desc
mDesc = desc;
}
void AlgorithmPrimatte::analyse()
{
if(!mInput)
throw std::runtime_error("Using algorithm with null input.");
//Set up unit polyhedron
BoundingPolyhedron unitPoly (mDesc.boundingPolyhedronDesc);
mPolys[POLY_INNER] = unitPoly;
mPolys[POLY_OUTER] = unitPoly;
//Fit inner polyhedron around the background points
mPolys[POLY_INNER].fitter()->shrink(
mPolys[POLY_INNER],
mDesc.segmenter->segment(
mInput->backgroundPoints(),
mInput->background(),
mDesc.innerShrinkingThreshold).inner,
mInput->background(),
mDesc.innerShrinkingMinDistance);
//Scale the inner polyhedron
mPolys[POLY_INNER] = mPolys[POLY_INNER]*mDesc.innerPostShrinkingMultiplier;
//Ensure that it is greater than the inner polyhedron
float innerPolyhedronMaxSize = mPolys[POLY_INNER].findLargestRadius();
float startRadius = std::max(innerPolyhedronMaxSize, mDesc.outerExpansionStartThreshold);
//Expand the sphere from the starting radius towards startingRadius+expandDelta
mPolys[POLY_OUTER].fitter()->expand(mPolys[POLY_OUTER],
mInput->points(),
mDesc.segmenter,
mInput->background(),
startRadius,
startRadius+mDesc.outerExpandDelta);
//Scale outer if wanted
float maxInnerRadius = mPolys[POLY_INNER].findLargestRadius();
float scale = mPolys[POLY_OUTER].radius() +
(maxInnerRadius-mPolys[POLY_OUTER].radius())*
(1.f-mDesc.outerScaleParameter);
mPolys[POLY_OUTER] = mPolys[POLY_OUTER]*(scale/mPolys[POLY_OUTER].radius());
mAnalysed = true;
}
cv::Mat AlgorithmPrimatte::computeAlphas() const
{
if(!mAnalysed)
throw std::runtime_error("Trying to compute alphas with algorithm before input analysis.");
return mDesc.alphaLocator->findAlphas(mPolys, POLY_COUNT, *mInput);
}
void AlgorithmPrimatte::debugDraw() const
{
for(int i = 0; i < POLY_COUNT; ++i)
mPolys[i].debugDraw(math::vec3((float)((i+2)%4==0), (float)((i+2)%3==0), 0.f));
}
}
}
}
|
4226e4c68d913adca745efd201fdd532af588801
|
ac5520ac678b1e2759b9b99dce5f5a6b4269f77a
|
/ScanLineFill/ScanLineAlgorithm/Figure.h
|
73427c87b56b3ac69a9e93e7f045d4d362d596ad
|
[
"Apache-2.0"
] |
permissive
|
jinfeijie/ImageProcessingAlgorithm
|
d981e53ddd74a6530d44de346b9e0927bd7e920b
|
404308120dde95ef228b9f415def6a71d525c3ad
|
refs/heads/master
| 2021-06-29T04:28:31.097663
| 2018-04-07T14:05:15
| 2018-04-07T14:05:15
| 95,859,227
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 188
|
h
|
Figure.h
|
#include <QPainter>
#pragma once
class CFigure
{
public:
int start_point_x_, start_point_y_, end_point_x_, end_point_y_;
virtual void Draw(QPainter &paint){};
virtual ~CFigure(){}
};
|
338afb82d993c5067bc35e7d4c8fcab3572dd5e8
|
07c06570a624c0ed9558d4894c2df35cfe5f42b7
|
/textRenderer/TextRenderer.h
|
e7b95c41863efb67e505ccaba86565a4883b0b61
|
[
"BSD-3-Clause"
] |
permissive
|
shunte88/pico-ssd1306
|
5089382c2f35aea670bddaa3c4484886021a6583
|
ae8144e2350e2b831cd0709810b8120102d7588e
|
refs/heads/master
| 2023-08-14T01:55:53.733479
| 2021-09-29T16:19:17
| 2021-09-29T16:19:17
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,758
|
h
|
TextRenderer.h
|
#pragma once
#ifndef SSD1306_TEXTRENDERER_H
#define SSD1306_TEXTRENDERER_H
#include "../ssd1306.h"
#include "5x8_font.h"
#include "8x8_font.h"
#include "12x16_font.h"
#include "16x32_font.h"
namespace pico_ssd1306{
/// \enum pico_ssd1306::Rotation
enum class Rotation{
/// deg0 - means no rotation
deg0,
/// deg 90 - means 90 deg rotation
deg90,
};
/// \brief Draws a single glyph on the screen
/// \param ssd1306 - pointer to a SSD1306 object aka initialised display
/// \param font - pointer to a font data array
/// \param c - char to be drawn
/// \param anchor_x, anchor_y - coordinates setting where to put the glyph
/// \param mode - mode describes setting behavior. See WriteMode doc for more information
/// \param rotation - either rotates the char by 90 deg or leaves it unrotated
void drawChar(pico_ssd1306::SSD1306 *ssd1306, const unsigned char * font, char c, uint8_t anchor_x, uint8_t anchor_y, WriteMode mode = WriteMode::ADD, Rotation rotation = Rotation::deg0);
/// \brief Draws text on screen
/// \param ssd1306 - pointer to a SSD1306 object aka initialised display
/// \param font - pointer to a font data array
/// \param text - text to be drawn
/// \param anchor_x, anchor_y - coordinates setting where to put the text
/// \param mode - mode describes setting behavior. See WriteMode doc for more information
/// \param rotation - either rotates the text by 90 deg or leaves it unrotated
void drawText(pico_ssd1306::SSD1306 *ssd1306, const unsigned char * font, const char * text, uint8_t anchor_x, uint8_t anchor_y, WriteMode mode = WriteMode::ADD, Rotation rotation = Rotation::deg0);
}
#endif //SSD1306_TEXTRENDERER_H
|
b6a65dc020f921918a8c0c162f86040251007cdb
|
4fd262abf31af5e77699a845bf1ebfe047d1d24e
|
/tests/detail/constants.hpp
|
c7e26acb393cec8f577313c1429a18a206972b50
|
[
"MIT"
] |
permissive
|
N-A-D/libra
|
bd570abee210eb2a6f0b6e92cd8e0be69b3634c9
|
2c60242bf9094b2cd8cd40b616e6116a897b6e26
|
refs/heads/master
| 2022-02-09T13:54:01.084968
| 2019-07-06T01:08:43
| 2019-07-06T01:08:43
| 187,731,057
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 35
|
hpp
|
constants.hpp
|
#pragma once
constexpr int N = 50;
|
9d40eb7bceca0b8dcd96265e4dafca25982d019b
|
1b8b6b2d700cadbaa38ec8c9c814aaeaa16d5aed
|
/src/sprite.cpp
|
6387cde459d5d80e7d18d04f1b43a182134cc655
|
[
"MIT"
] |
permissive
|
t-mccawley/zerkola
|
fb5ff8f6d1d22771a668583ab7301864027f7960
|
e9b4607d059ea89c865410799a6eae0d3d75515d
|
refs/heads/master
| 2020-05-03T00:54:06.781921
| 2019-06-12T04:38:29
| 2019-06-12T04:38:29
| 178,322,488
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,205
|
cpp
|
sprite.cpp
|
#include <sprite.h>
#include <iostream>
#include <game_control.h>
#include <algorithm>
#include <geometry.h>
#include <iostream>
#include <assert.h>
namespace sprite {
Sprite::Sprite() {};
Sprite::~Sprite() {}
Sprite::Sprite(graphics::Graphics* graphics_ptr,
const std::string &filePath,
int sourceX,
int sourceY,
int width,
int height):
_graphics_ptr(graphics_ptr),
_upper_left_corner(0,0),
_dir(0,0),
_center_of_rotation(0,0)
{
#ifdef DEBUG_SPRITE
std::cout << "===== Sprite Constructor Called =====" << std::endl;
#endif
_sourceRect.x = sourceX;
_sourceRect.y = sourceY;
_sourceRect.w = width;
_sourceRect.h = height;
#ifdef DEBUG_SPRITE
std::cout << "_sourceRect.x: " << _sourceRect.x << std::endl;
std::cout << "_sourceRect.y: " << _sourceRect.y << std::endl;
std::cout << "_sourceRect.w: " << _sourceRect.w << std::endl;
std::cout << "_sourceRect.h: " << _sourceRect.h << std::endl;
#endif
_spriteSheet = SDL_CreateTextureFromSurface(graphics_ptr->getRenderer(), graphics_ptr->loadImage(filePath));
if (_spriteSheet == NULL) {
std::cout << std::endl << "Error: Unable to load image" << std::endl;
}
}
void Sprite::draw(bool verbose) const {
if (verbose) {
std::cout << "Sprite::draw()" << std::endl;
std::cout << "_upper_left_corner.x(): " << _upper_left_corner.x() << std::endl;
std::cout << "_upper_left_corner.y(): " << _upper_left_corner.y() << std::endl;
std::cout << "_dir.x(): " << _dir.x() << std::endl;
std::cout << "_dir.y(): " << _dir.y() << std::endl;
std::cout << "_center_of_rotation.x(): " << _center_of_rotation.x() << std::endl;
std::cout << "_center_of_rotation.y(): " << _center_of_rotation.y() << std::endl;
}
//Create destination rectangle on screen
//This is where double is converted to
int UL_x, UL_y, width, height;
width = static_cast<int>(_sourceRect.w*gc::SPRITE_SCALE);
height = static_cast<int>(_sourceRect.h*gc::SPRITE_SCALE);
UL_x = _upper_left_corner.x();
UL_y = _upper_left_corner.y();
if (verbose) {
std::cout << "width: " << width << std::endl;
std::cout << "height: " << height << std::endl;
std::cout << "UL_x: " << UL_x << std::endl;
std::cout << "UL_y: " << UL_y << std::endl;
}
//Assert on window limits
assert((UL_x + width) <= gc::WINDOW_WIDTH);
assert(UL_x >= 0);
assert(UL_y >= 0);
assert((UL_y + height) <= gc::WINDOW_HEIGHT);
SDL_Rect destinationRectangle = {UL_x, UL_y, width, height};
//Determine angle from global Y_2D (pointing up) to _dir CW
Eigen::Vector2d v1(gc::Y_2D_PHYS.cast<double>());
Eigen::Vector2d v2(_dir.cast<double>());
double theta = geo::AngBetweenVecs(v1, v2, gc::AngularDirection::CW)*geo::RAD_TO_DEG; //Note angle must be in degrees
if (verbose) {
std::cout << "theta: " << theta << std::endl;
}
SDL_Point center_point = {_center_of_rotation.x(), _center_of_rotation.y()};
//Render
_graphics_ptr->renderCopy(_spriteSheet, &_sourceRect, &destinationRectangle, theta, ¢er_point);
return;
}
}
|
80955c02ff05dffd3c6b24272bdfca3c06f956ee
|
6abfbf8d3c934bfb77ce989c46f7ee5c3e3c19a7
|
/476. Number Complement/Solution.cpp
|
d6e588569aea5331e0a7527efe114e2ed74016bf
|
[] |
no_license
|
AristoChen/LeetCode-AC-Solution
|
7be7d09d99f131e06529e4e34e12129729a12efa
|
d2f988257b1631e79cf13763bf87e826ee834c3b
|
refs/heads/master
| 2020-03-17T20:30:29.879961
| 2018-06-07T13:26:20
| 2018-06-07T13:26:20
| 133,913,472
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 732
|
cpp
|
Solution.cpp
|
/*
Submission Detail:{
Difficulty : Easy
Acceptance Rate : 61.19 %
Runtime : 8 ms
Testcase : 149 / 149 passed
Ranking : Your runtime beats 12.38 % of cpp submissions.
}
*/
class Solution {
public:
int findComplement(int num) {
vector<int> temp;
int answer = 0;
while(num != 0)
{
temp.push_back(num % 2);
num = num / 2;
}
for(int i = 0; i < temp.size(); i++)
{
if(temp[i] == 0)
temp[i] = 1;
else if(temp[i] == 1)
temp[i] = 0;
if(temp[i] == 1)
answer = answer + pow(2, i);
}
return answer;
}
};
|
c324611efcfc9412730667c1e4c2807b3d9a7de3
|
a2151ce6569c05bb3896f2d966030a713720af29
|
/Proiect/Autobuz.cpp
|
b2bd4ae86a268d018fbd857270f490e7de0f7595
|
[] |
no_license
|
JokerDBLue/ProiectCTP
|
3428b96cd9c215ed2c9513e14fe28256cd937d1d
|
40337da4e249d06b426ceb92ac2bd4dd88ff99cd
|
refs/heads/master
| 2022-04-10T07:46:55.328281
| 2020-03-15T14:28:04
| 2020-03-15T14:28:04
| 187,687,814
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,793
|
cpp
|
Autobuz.cpp
|
#include "Autobuz.h"
Autobuz::Autobuz()
{
this->zona = 1;
this->numar = "";
this->zi = "";
this->orar;
this->ruta;
}
Autobuz::Autobuz(int zona, string numar, string zi, vector<vector<string> > orar, vector<string> ruta)
{
this->zona = zona;
this->numar = numar;
this->zi = zi;
this->orar = orar;
this->ruta = ruta;
}
Autobuz::Autobuz(const Autobuz & a)
{
this->zona = a.zona;
this->numar = a.numar;
this->zi = a.zi;
this->orar = a.orar;
this->ruta = a.ruta;
}
int Autobuz::getZona()
{
return this->zona;
}
string Autobuz::getNumar()
{
return this->numar;
}
string Autobuz::getZi()
{
return this->zi;
}
vector<vector<string> > Autobuz::getOrar()
{
return this->orar;
}
vector<string> Autobuz::getRuta()
{
return this->ruta;
}
void Autobuz::setZona(int z)
{
this->zona = z;
}
void Autobuz::setNumar(string nr)
{
this->numar = nr;
}
void Autobuz::setZi(string z)
{
this->zi = z;
}
void Autobuz::setOrar(vector<vector<string> > o)
{
this->orar = o;
}
void Autobuz::setRuta(vector<string> r)
{
this->ruta = r;
}
bool Autobuz::oAnumitaRuta(string inceput, string sfarsit)
{
int k = 0;
for (size_t i = 0; i < ruta.size(); i++)
if (ruta[i] == inceput)
{
k = i;
}
for (size_t i = k; i < ruta.size(); i++)
if (ruta[i] == sfarsit)
return true;
return false;
}
bool Autobuz::operator==(const Autobuz & a)
{
return (a.numar == this->numar);
}
ostream & operator<<(ostream & os, const Autobuz a)
{
os << "Autobuzul " << a.numar << ": " << "Zona " << a.zona << endl;
os << "Orar: " << endl;
for (size_t i = 0; i < a.ruta.size(); i++)
{
os << a.ruta[i] << ": ";
for (size_t j = 0; j < a.orar.size(); j++)
os << a.orar[j][i] << " ";
cout << endl;
}
return os;
}
Autobuz::~Autobuz()
{
this->orar.clear();
this->ruta.clear();
}
|
1d1c4bcc74ffb086c3b5a6532040ef5ea6b9f1e0
|
9356d61555549ccb0b12b722c80c87695c1723e9
|
/Main.cpp
|
64da1a45cb66dd79ce81cfbd96ab27cea174fb6a
|
[] |
no_license
|
MonsieurVolt/testSfml
|
d1892a373f4388beebe3beaaa5c4bf06bf582803
|
3265ddd30e5b1d4070a6ec4da5195171756460e1
|
refs/heads/master
| 2023-07-16T05:28:44.865565
| 2021-09-01T22:05:23
| 2021-09-01T22:07:24
| 402,208,434
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 895
|
cpp
|
Main.cpp
|
#include <SFML/Graphics.hpp>
#include <cassert>
#include <iostream>
#include <map>
#include "RessourcesHolder.hpp"
using namespace std;
namespace Textures
{
enum struct ID
{
LandScape,
Airplane,
Missile
};
};
int main()
{
sf::RenderWindow window(sf::VideoMode(500, 500), "Ressources management");
ResourceHolder<sf::Texture, Textures::ID> textures;
textures.load(Textures::ID::Airplane, "Eagle.png");
textures.load(Textures::ID::LandScape, "Desert.png");
sf::Sprite plane(textures.get(Textures::ID::Airplane));
sf::Sprite desert(textures.get(Textures::ID::LandScape));
desert.setPosition(sf::Vector2f(300, 300));
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
window.close();
}
}
window.clear(sf::Color::Red);
window.draw(plane);
window.draw(desert);
window.display();
}
}
|
4c1ea44450c6396f527dc870185b23cf96034ab9
|
50312e055a8b9c29c6f56f4fd87f100cf698d700
|
/GameTemplate/Game/SkinModelRender.h
|
4290244ca7bb962dc2aecc0aa0b8e6d3a1011470
|
[] |
no_license
|
kawaharamiyauchi/Game_01
|
f20bfd48b163bd62d3bf906b2bf54efb8a6979b1
|
95da906aa6a445e3cdccec4b9a0922e5d1aa5bae
|
refs/heads/master
| 2020-06-27T12:43:56.213152
| 2020-06-25T00:32:37
| 2020-06-25T00:32:37
| 199,956,192
| 0
| 0
| null | null | null | null |
SHIFT_JIS
|
C++
| false
| false
| 2,414
|
h
|
SkinModelRender.h
|
#pragma once
#include "graphics/SkinModel.h"
#include"IGameObject.h"
class SkinModelRender:public IGameObject
{
public:
SkinModelRender();
~SkinModelRender();
void Init(const wchar_t*filePath);
/// <summary>
/// シャドウキャスターのフラグを設定
/// </summary>
/// <param name="flag">シャドウキャスターフラグ</param>
void SetShadowCasterFlag(bool flag)
{
m_isCasterFlag = flag;
m_skinModel.SetShadowCasterFlag(flag);
}
/// <summary>
/// シャドウレシーバーのフラグを設定
/// </summary>
/// <param name="flag">シャドウレシーバーフラグ</param>
void SetShadowRecieverFlag(bool flag)
{
m_isRecieverFlag = flag;
m_skinModel.SetShadowReciever(flag);
}
void SetShadowCasterUpdate();
void SetActiveFlag(bool flag)
{
m_skinModel.SetActiveFlag(flag);
}
/// <summary>
/// 座標を設定
/// </summary>
/// <param name="pos">座標</param>
void SetPosition(const CVector3& pos)
{
m_position = pos;
}
/// <summary>
/// 回転を設定
/// </summary>
/// <param name="rot">回転</param>
void SetRotation(const CQuaternion& rot)
{
m_rotation = rot;
}
/// <summary>
/// 拡大率を設定
/// </summary>
/// <param name="sca">拡大率</param>
void SetScale(const CVector3& sca)
{
m_scale = sca;
}
/// <summary>
/// スキンモデルを取得
/// </summary>
SkinModel* GetSkinModel()
{
return &m_skinModel;
}
/// <summary>
/// スケルトンを取得
/// </summary>
/// <returns></returns>
Skeleton* GetSkeleton()
{
return &m_skinModel.GetSkeleton();
}
CMatrix* GetWorldMatrix()
{
return &m_skinModel.GetWorldMatrix();
}
void Update();
void Render();
/// <summary>
/// 自己発光カラーを設定
/// </summary>
/// <param name="color">カラー</param>
void SetGlowColor(CVector3 color)
{
m_skinModel.SetGlowColor(color);
}
/// <summary>
/// 鏡面反射光を設定。
/// </summary>
/// <param name="spec">スペキュラの絞り</param>
void SetSpecPow(float spec)
{
m_skinModel.SetSpecPow(spec);
}
private:
SkinModel m_skinModel;
EnRenderMode m_renderMode = enRenderMode_Normal;
CVector3 m_position = CVector3::Zero();
CQuaternion m_rotation = CQuaternion::Identity();
CVector3 m_scale = CVector3::One();
EnFbxUpAxis m_enFbxUpAxis = enFbxUpAxisZ; // FBXの上方向。
bool m_isRecieverFlag = false;
bool m_isCasterFlag = false;
};
|
b287469d5219064efe68b6a41f358625977ec549
|
4ce3266d333a8c51f05745e30029747474ffa522
|
/tests/blktrlm.cpp
|
a9f9f676d6dd3cae9255b3961a7c5220b2d9758b
|
[
"BSD-3-Clause"
] |
permissive
|
cpviolator/VOATOL
|
471137e95017653729926328fffa117dd0185800
|
d90c5ce5753aae2f8f88f439bd24b54bc621c5a9
|
refs/heads/master
| 2023-04-04T15:17:59.789681
| 2021-04-13T06:21:43
| 2021-04-13T06:21:43
| 257,758,348
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 11,778
|
cpp
|
blktrlm.cpp
|
#include "voatol_internal.h"
#include "algorithm_utils.h"
#include "blas.h"
#include "sort.h"
bool verbose = false;
int mat_size = 128;
int main(int argc, char **argv) {
struct timeval start, end, total_start, total_end;
gettimeofday(&total_start, NULL);
// timing variables
double t_total = 0.0;
double t_init = 0;
double t_sort = 0;
double t_eigen = 0.0;
double t_compute = 0.0;
double t_EV = 0.0;
// START init
//---------------------------------------------------------
gettimeofday(&start, NULL);
if (argc < 15 || argc > 15) {
cout << "./block_trlm <mat_size> <nKr> <nEv> <nConv> <max-restarts> <diag> <tol> <amin> <amax> <polydeg> <spectrum: 0=LR, 1=SR> <block> <verbosity: 1=verbose, 0=quiet> <Eigen Check: 0=false, 1=true>" << endl;
exit(0);
}
mat_size = atoi(argv[1]);
int nKr = atoi(argv[2]);
int nEv = atoi(argv[3]);
int nConv = atoi(argv[4]);
int max_restarts = atoi(argv[5]);
double diag = atof(argv[6]);
double tol = atof(argv[7]);
double a_min = atof(argv[8]);
double a_max = atof(argv[9]);
double poly_deg = atof(argv[10]);
bool use_acc = (a_min == 0 || a_max == 0 || poly_deg == 0) ? false : true;
int spectrum = atoi(argv[11]);
bool reverse = spectrum == 1 ? true : false;
int block_size = atoi(argv[12]);
bool verbose = (atoi(argv[13]) == 1 ? true : false);
bool eigen_check = (atoi(argv[14]) == 1 ? true : false);
if (nKr != mat_size) {
if (!(nKr > nEv + 6)) {
printf("nKr=%d must be greater than nEv+6=%d\n", nKr, nEv + 6);
exit(0);
}
} else if (nKr == mat_size) {
printf("nKr=mat_size=%d Computing a complete Arnoldi factorisation\n", nKr);
} else if (nEv > mat_size || nKr > mat_size) {
printf("nKr=%d and nEv=%d must be less than mat_size=%d\n", nKr, nEv, mat_size);
exit(0);
}
if (nKr%block_size != 0 || nEv%block_size != 0) {
printf("block_size=%d must be a factor of both nKr=%d and nEv=%d\n", block_size, nKr, nEv);
exit(0);
}
printf("Mat size = %d\n", mat_size);
printf("nKr = %d\n", nKr);
printf("nEv = %d\n", nEv);
printf("block_size = %d\n", block_size);
printf("Restarts = %d\n", max_restarts);
printf("diag = %e\n", diag);
printf("tol = %e\n", tol);
printf("reverse = %s\n", reverse == true ? "true" : "false");
//Construct a matrix using Eigen.
//---------------------------------------------------------------------
MatrixXcd ref = MatrixXcd::Random(mat_size, mat_size);
MatrixXcd diagonal = MatrixXcd::Identity(mat_size, mat_size);
diagonal *= diag;
// Copy to mat
Complex **mat = (Complex**)malloc(mat_size*sizeof(Complex*));
for(int i=0; i<mat_size; i++) {
mat[i] = (Complex*)malloc(mat_size*sizeof(Complex));
for(int j=0; j<mat_size; j++) {
mat[i][j] = ref(i,j) + conj(ref(j,i));
if(i == j) mat[i][j] += diag;
}
}
//Construct objects for Lanczos.
//---------------------------------------------------------------------
//Eigenvalues and their residuals
std::vector<double> residua(nKr, 0.0);
std::vector<Complex> evals(nKr, 0.0);
std::vector<double> arrow_eigs(nKr, 0.0);
//Ritz vectors and Krylov Space. The eigenvectors will be stored here.
std::vector<Complex*> kSpace(nKr+block_size);
for(int i=0; i<nKr+block_size; i++) {
kSpace[i] = (Complex*)malloc(mat_size*sizeof(Complex));
zero(kSpace[i]);
}
//Symmetric block tridiagonal matrix
std::vector<Complex> alpha(nKr * block_size, 0.0);
std::vector<Complex> beta(nKr * block_size, 0.0);
//Residual vector. Also used as a temp vector
std::vector<Complex*> r(block_size);
for(int i=0; i<block_size; i++) {
r[i] = (Complex*)malloc(mat_size*sizeof(Complex));
zero(r[i]);
}
double epsilon = DBL_EPSILON;
double mat_norm = 0.0;
bool converged = false;
int iter = 0;
int restart_iter = 0;
int iter_converged = 0;
int iter_locked = 0;
int iter_keep = 0;
int num_converged = 0;
int num_locked = 0;
int num_keep = 0;
// END init
//---------------------------------------------------------
gettimeofday(&end, NULL);
t_init += ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6;
//Eigensolve the matrix using Eigen, use as a reference.
//---------------------------------------------------------------------
gettimeofday(&start, NULL);
Eigen::SelfAdjointEigenSolver<MatrixXcd> eigenSolver;
std::vector<Complex> eigen_evals(mat_size, 0.0);
if(eigen_check) {
printf("START EIGEN SOLUTION\n");
eigenSolver.compute(ref + ref.adjoint() + diagonal);
gettimeofday(&end, NULL);
t_eigen += ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6;
printf("END EIGEN SOLUTION\n");
printf("Time to solve problem using Eigen = %e\n", t_eigen);
for(int i=0; i<mat_size; i++) eigen_evals[i] = eigenSolver.eigenvalues()[i];
}
//-----------------------------------------------------------------------
// START compute
//---------------------------------------------------------
gettimeofday(&start, NULL);
// Populate source with randoms.
printf("Using random guess\n");
for(int b=0; b<block_size; b++) {
for(int i=0; i<mat_size; i++) {
r[b][i].real(drand48());
}
}
//Gram-Schmidt initial sources
gramSchmidt(r);
orthoCheck(r, block_size);
for(int b=0; b<block_size; b++) copy(kSpace[b], r[b]);
t_compute += ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6;
// START BLKTRLM
// Block Thick restarted Lanczos method for symmetric eigenvalue problems
printf("START BLOCK THICK RESTARTED LANCZOS SOLUTION\n");
//-----------------------------------------------------------------
// Loop over restart iterations.
while(restart_iter < max_restarts && !converged) {
gettimeofday(&start, NULL);
for (int step = num_keep; step < nKr; step += block_size) {
blockLanczosStep(mat, kSpace, beta, alpha, r, num_keep, step, block_size, a_min, a_max, poly_deg);
}
iter += (nKr - num_keep);
gettimeofday(&end, NULL);
t_compute += ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6;
gettimeofday(&start, NULL);
int arrow_pos = num_keep - num_locked;
// The eigenvalues are returned in the alpha_eigs array
eigensolveFromBlockArrowMat(num_locked, arrow_pos, nKr, block_size, restart_iter, alpha, beta, arrow_eigs, residua, reverse);
gettimeofday(&end, NULL);
t_EV += ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6;
gettimeofday(&start, NULL);
// mat_norm is updated.
for (int i = num_locked; i < nKr; i++) {
if (verbose) printf("abs(alpha[%d]) = %e : mat norm = %e\n", i, abs(alpha[i]), mat_norm);
if (abs(alpha[i]) > mat_norm) {
mat_norm = abs(alpha[i]);
}
}
// Locking check
iter_locked = 0;
for (int i = 1; i < (nKr - num_locked); i++) {
if (residua[i + num_locked] < epsilon * mat_norm) {
if(verbose) printf("**** Locking %d resid=%+.6e condition=%.6e ****\n", i, residua[i + num_locked], epsilon * mat_norm);
iter_locked = i;
} else {
// Unlikely to find new locked pairs
break;
}
}
// Convergence check
iter_converged = iter_locked;
for (int i = iter_locked + 1; i < nKr - num_locked; i++) {
if (residua[i + num_locked] < tol * mat_norm) {
if(verbose) printf("**** Converged %d resid=%+.6e condition=%.6e ****\n", i, residua[i + num_locked], tol * mat_norm);
iter_converged = i;
} else {
// Unlikely to find new converged pairs
break;
}
}
iter_keep = std::min(iter_converged + (nKr - num_converged) / 2, nKr - num_locked - 12);
iter_keep = (iter_keep/block_size) * block_size;
gettimeofday(&end, NULL);
t_sort += ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6;
gettimeofday(&start, NULL);
computeKeptRitzComplex(kSpace, nKr, num_locked, iter_keep, block_size, beta);
gettimeofday(&end, NULL);
t_compute += ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6;
num_converged = num_locked + iter_converged;
num_converged = (num_converged/block_size) * block_size;
num_keep = num_locked + iter_keep;
num_keep = (num_keep/block_size) * block_size;
num_locked += iter_locked;
num_locked = (num_locked/block_size) * block_size;
printf("%04d converged eigenvalues at restart iter %04d\n", num_converged, restart_iter + 1);
if(verbose) {
printf("iter Conv = %d\n", iter_converged);
printf("iter Keep = %d\n", iter_keep);
printf("iter Lock = %d\n", iter_locked);
printf("num_converged = %d\n", num_converged);
printf("num_keep = %d\n", num_keep);
printf("num_locked = %d\n", num_locked);
}
// Check for convergence
if (num_converged >= nConv) {
gettimeofday(&start, NULL);
for(int i=0; i<nKr; i++) evals[i].real(arrow_eigs[i]);
reorder(kSpace, evals, residua, nKr, spectrum);
computeEvals(mat, kSpace, residua, evals, nKr);
gettimeofday(&end, NULL);
t_compute += ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6;
converged = true;
}
restart_iter++;
}
gettimeofday(&total_end, NULL);
t_total = ((total_end.tv_sec - total_start.tv_sec) * 1000000u + total_end.tv_usec - total_start.tv_usec) / 1.e6;
// Post computation report
if (!converged) {
printf("BLOCK TRLM failed to compute the requested %d vectors with a %d search space and %d Krylov space and %d block size in %d restart steps and %d OPs"
"restart steps.\n",
nConv, nEv, nKr, block_size, max_restarts, iter);
} else {
printf("BLOCK TRLM computed the requested %d vectors with a %d search space and a %d Krylov space and %d block size in %d restart_steps and %d OPs in %e secs.\n", nConv, nEv, nKr, block_size, restart_iter, iter, (t_compute + t_sort + t_EV));
// Dump all Ritz values and residua
for (int i = 0; i < nConv && use_acc; i++) {
printf("RitzValue[%04d]: (%+.16e, %+.16e) residual %.16e\n", i, arrow_eigs[i], 0.0, residua[i]);
}
if(eigen_check) {
// sort the eigen eigenvalues by the requested spectrum. The wanted values
// will appear at the end of the array. We need a dummy residua array to use
// the sorting function.
std::vector<double> res_dummy(mat_size, 0.0);
zsortc(spectrum+2, mat_size, eigen_evals, res_dummy);
for (int i = 0; i < nConv; i++) {
//int idx_e = mat_size - 1 - i;
int idx_e = i;
printf("EigenComp[%04d]: [(%+.8e, %+.8e) - (%+.8e, %+.8e)]/(%+.8e, %+.8e) = "
"(%+.8e,%+.8e)\n", i,
evals[i].real(), evals[i].imag(),
eigen_evals[idx_e].real(), eigen_evals[idx_e].imag(),
eigen_evals[idx_e].real(), eigen_evals[idx_e].imag(),
(evals[i].real() - eigen_evals[idx_e].real())/eigen_evals[idx_e].real(),
0.0);
}
} else {
for (int i = 0; i < nConv; i++) {
printf("EigValue[%04d]: ||(%+.8e, %+.8e)|| = %+.8e residual %.8e\n", i, evals[i].real(), evals[i].imag(), abs(evals[i]), residua[i]);
}
}
}
cout << "Timings:" << endl;
if(eigen_check) cout << "Eigen = " << t_eigen << endl;
cout << "init = " << t_init << endl;
cout << "compute = " << t_compute << endl;
cout << "sort = " << t_sort << endl;
cout << "EV = " << t_EV << endl;
cout << "missing = " << (t_total) << " - " << (t_compute + t_init + t_sort + t_EV + t_eigen) << " = " << (t_total - (t_compute + t_init + t_sort + t_EV + t_eigen)) << " ("<<(100*((t_total - (t_compute + t_init + t_sort + t_EV + t_eigen))))/t_total<<"%)" << endl;
}
|
b82ba53630040a6c74350bf06cbd6516724efb51
|
860d80cac7fdb7a8534f7d118ea8a244af86f3ce
|
/insight_testSuite/temp/src/digitalWalletTestMain.cpp
|
a43f34245e7de9006252f4d53cff3fa51eebd91d
|
[] |
no_license
|
gzgzgz/digitalWallet
|
7e622cfc1a40735d9d20777f50a8f7f878b4575f
|
e7ca6d040b449ea207df8df0083b3474c66699a2
|
refs/heads/master
| 2020-12-24T07:52:03.132419
| 2017-07-01T04:32:38
| 2017-07-01T04:32:38
| 73,362,393
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,301
|
cpp
|
digitalWalletTestMain.cpp
|
// digitalWalletTestMain.cpp : Defines the entry point for the console application.
//
#include "DigitalWallet.h"
#include <iostream>
#include <string>
#include <ctime>
int main()
{
DigitalWallet* payMoWallet = new DigitalWallet();
std::cout << "Enter the path to a file containing authorized transactions from history: " << std::endl;
std::string inputFileName;
std::cin >> inputFileName;
payMoWallet->createUserDatabaseFromPastDataFastIO(inputFileName);
std::cout << "Enter the path and name of the output file for the verification results: " << std::endl;
std::string outputFileName;
std::cin >> outputFileName;
int alertLevel = -1;
while (! (alertLevel == 1 || alertLevel==2 || alertLevel==4) ) {
std::cout << "Enter intended alert Level (1 for direct contact, 2 for 2nd degree contact, 4 for 4th degree contact, others not allowed): " << std::endl;
std::cin >> alertLevel;
}
long long suffix = (alertLevel==4?3:alertLevel);
std::string outputPath = "./paymo_output/output" + std::to_string((long long)suffix) + ".txt";
std::clock_t beforeClock = std::clock();
payMoWallet->verifyPaymentTrans(outputFileName, outputPath, alertLevel);
std::clock_t afterClock = std::clock();
std::cout << "analysis done in " << (afterClock - beforeClock) << " ms" << std::endl;
return 0;
}
|
fd4255e97e9e4245059fc3e001091e7c9a9c9e33
|
b32e6bd41c08b7db696092b6dfd41a39ef8e0010
|
/tests/screenBufferTest.cpp
|
b5c1014f49591affc558810cee55eefeaae0ec14
|
[] |
no_license
|
voidThread/color_chart
|
89d571f81d1060bafb25244c6e5f1a59a5a60b3c
|
c78a4ff0ef43b8a04d1d903d44123222de9b0905
|
refs/heads/master
| 2023-03-21T14:17:14.646043
| 2021-03-16T00:01:06
| 2021-03-16T00:01:06
| 348,168,347
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,158
|
cpp
|
screenBufferTest.cpp
|
#include <gtest/gtest.h>
#include "ScreenBuffer.h"
class ScreenBufferTest : public ::testing::Test
{
protected:
color_chart::screen::ScreenBuffer screenBuffer{16,9};
};
TEST_F(ScreenBufferTest, ScreenBufferFiledWithOneLineGradient) {
//Arrange
using namespace color_chart;
screen::CornersColors twoCorners{0x0000, 0xffff};
screenBuffer.setCornerColors(twoCorners);
//Act
auto buffer = screenBuffer.getScreen();
//Assert
ASSERT_EQ(buffer.size(), 9);
ASSERT_EQ(buffer.front().size(), 16);
ASSERT_EQ(buffer.front().back(), buffer.back().back());
ASSERT_EQ(buffer.front().front(), buffer.back().front());
}
TEST_F(ScreenBufferTest, ScreenBufferFiledWithOneLineGradientInvertedColors) {
//Arrange
using namespace color_chart;
screen::CornersColors twoCorners{0xffff, 0x0000};
screenBuffer.setCornerColors(twoCorners);
//Act
auto buffer = screenBuffer.getScreen();
//Assert
ASSERT_EQ(buffer.size(), 9);
ASSERT_EQ(buffer.front().size(), 16);
ASSERT_EQ(buffer.front().back(), buffer.back().back());
ASSERT_EQ(buffer.front().front(), buffer.back().front());
}
|
813390af30810ad97cfa5753344fb0a0c49d2f43
|
6432b801507aa6226561614cf96d01e5813942ec
|
/1sem/lab_stack_queue_ect/queue_in_hospital.cpp
|
c9251868868cbf127c0fa4a8b63a8ecae8053c4a
|
[] |
no_license
|
aralbaevaanya/algosd
|
05e7e7757925d912508023926201abc264ef887e
|
48429bb1461115a895286291ff1e66475c87417e
|
refs/heads/master
| 2020-03-18T14:40:07.246414
| 2018-11-14T15:09:39
| 2018-11-14T15:09:39
| 134,860,059
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,273
|
cpp
|
queue_in_hospital.cpp
|
#include <iostream>
#include <fstream>
#include <deque>
using namespace std;
int main() {
ifstream in("hospital.in");
ofstream fout("hospital.out");
int n;
int a;
char c;
in >> n;
int cun1=0, cun2=0;
deque<int> half1, half2;
for (int i = 0; i < n; i++) {
in >> c;
if (c == '+') {
in >> a;
half2.push_back(a);
cun2++;
if (cun1 < (cun1 + cun2 + 1) / 2) {
half1.push_back(half2.front());
half2.pop_front();
cun2--;
cun1++;
}
}else
if (c == '*') {
in >> a;
if (cun1 <= cun2) {
half1.push_back(a);
cun1++;
}
else {
half2.push_front(a);
cun2++;
}
}
else {
fout << half1.front()<<'\n';
half1.pop_front();
cun1--;
if (cun1 < (cun1 + cun2 + 1) / 2) {
half1.push_back(half2.front());
half2.pop_front();
cun2--;
cun1++;
}
}
}
}
|
3b397ed10df136e7fa42385655ba684ecf78657f
|
f46464ddfeacd37148a678601c529d6a6b29a929
|
/templates/_generic/generic_class.cpp
|
d2263df7d23774dc99b24c3f7dab2004285db9c0
|
[] |
no_license
|
keegansalankey/cpp-boiler
|
3fc5c6fbcd16850834b9c3fb764b04c0a2284a16
|
ea2d168a9b29088367f37d00fe58d8c816cd2482
|
refs/heads/main
| 2023-08-18T10:00:52.255981
| 2021-10-15T01:20:15
| 2021-10-15T01:20:15
| 417,022,264
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 64
|
cpp
|
generic_class.cpp
|
#include "<<replace_me>>.h"
<<replace_me>>::<<replace_me>>(){}
|
a744d81e03e48890f746c26b342d3b0a632b28ef
|
cae38993c00d5a3a6781f672954b585258de5976
|
/engine/FileTimeSearcher.h
|
6dc41cfeba8b36d5f5eb4193d333a0d3d914aa14
|
[] |
no_license
|
HT509-net/SearchMonkeyClone
|
a567fb8600c52deb7684358942dc6a58734488de
|
034e35a1f3409b7339b9911b938cf9ed101a9d55
|
refs/heads/master
| 2021-01-17T13:17:11.127678
| 2017-01-06T01:45:50
| 2017-01-06T01:45:50
| 38,259,999
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 574
|
h
|
FileTimeSearcher.h
|
#ifndef FILETIMESEARCHER_H
#define FILETIMESEARCHER_H
#include <QDateTime>
#include "SearcherDecorator.h"
#include "../SearchResult.h"
#include "../Types.h"
class Searcher;
class PhaseOneParameter;
class FileTimeSearcher : public SearcherDecorator
{
public:
FileTimeSearcher(Searcher* searcher, const PhaseOneParameter& param);
private:
virtual void DoUpdate(const Result& result);
QDateTime GetTimeFrom(const Result& result, TimeType type);
QDateTime beginTime;
QDateTime endTime;
TimeType matchedTimeType;
};
#endif
|
161e298d64004d83f45c3bdb459150b066714431
|
bbc746f2090f746ad5d1da137a1b26d6ed9f8258
|
/slymacOS/src/macos/os/window.cpp
|
41f423f9880d724af9036597d506bbd43a08a6c8
|
[
"MIT"
] |
permissive
|
Gibbeon/sly
|
4393b1ad2fd89bd0d44df15e6295a7f5e118b606
|
9216cf04a78f1d41af01186489ba6680b9641229
|
refs/heads/master
| 2021-08-17T10:54:06.199042
| 2020-04-18T16:08:10
| 2020-04-18T16:08:10
| 163,452,205
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,528
|
cpp
|
window.cpp
|
#include "sly/macOS/os/window.h"
#include "mtlpp/mtlpp.hpp"
#include "mtlpp/examples/window.hpp"
#import <Cocoa/Cocoa.h>
#import <MetalKit/MetalKit.h>
#include <stdio.h>
class MtlView : public ns::Object
{
public:
MtlView() { }
MtlView(const ns::Handle& handle) : ns::Object(handle) { }
mtlpp::Drawable GetDrawable() const
{
return ns::Handle{ (__bridge void*)((__bridge MTKView*)this->GetPtr()).currentDrawable };
}
mtlpp::RenderPassDescriptor GetRenderPassDescriptor() const
{
return ns::Handle{ (__bridge void*)((__bridge MTKView*)this->GetPtr()).currentRenderPassDescriptor };
}
};
@interface WindowViewTask : NSViewTask<MTKViewDelegate> {
@public void (*m_render)(const sly::os::MacOSWindow&);
@public const sly::os::MacOSWindow* m_window;
}
@end
@implementation WindowViewTask
-(void)mtkView:(nonnull MTKView *)view drawableSizeWillChange:(CGSize)size
{
}
-(void)drawInMTKView:(nonnull MTKView *)view
{
(*m_render)(*m_window);
}
@end
using namespace sly::os;
mtlpp::Device g_device;
mtlpp::CommandQueue g_commandQueue;
mtlpp::Buffer g_vertexBuffer;
mtlpp::RenderPipelineState g_renderPipelineState;
mtlpp::Drawable g_Drawable;
mtlpp::RenderPassDescriptor g_RenderPassDescriptor;
MtlView m_view;
sly::retval<void> MacOSWindow::init(WindowDesc& desc)
{
m_width = desc.width;
m_height = desc.height;
m_title = desc.pszTitle;
NSRect frame = NSMakeRect(0, 0, m_width, m_height);
NSWindow* window = [[NSWindow alloc] initWithContentRect:frame
#if MTLPP_IS_AVAILABLE_MAC(10_12)
styleMask:(NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable)
#else
styleMask:(NSTitledWindowMask | NSClosableWindowMask | NSResizableWindowMask)
#endif
backing:NSBackingStoreBuffered
defer:NO];
window.title = [[NSProcessInfo processInfo] processName];
WindowViewTask* viewTask = [WindowViewTask new];
viewTask->m_render = onRender;
viewTask->m_window = this;
// IDevice
g_device = mtlpp::Device::CreateSystemDefaultDevice();
// Hooking Device into RenderContext
MTKView* view = [[MTKView alloc] initWithFrame:frame];
view.device = (__bridge id<MTLDevice>)g_device.GetPtr();
view.delegate = viewTask;
view.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
[window.contentView addSubview:view];
[window center];
[window orderFrontRegardless];
m_view = ns::Handle{ (__bridge void*)view };
// shader
const char shadersSrc[] = R"""(
#include <metal_stdlib>
using namespace metal;
vertex float4 vertFunc(
const device packed_float3* vertexArray [[buffer(0)]],
unsigned int vID[[vertex_id]])
{
return float4(vertexArray[vID], 1.0);
}
fragment half4 fragFunc()
{
return half4(1.0, 0.0, 0.0, 1.0);
}
)""";
// vertextbuffer
const float vertexData[] =
{
0.0f, 1.0f, 0.0f,
-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
};
// commandQueue
g_commandQueue = g_device.NewCommandQueue();
// shader file
mtlpp::Library library = g_device.NewLibrary(shadersSrc, mtlpp::CompileOptions(), nullptr);
// shader proram
mtlpp::Function vertFunc = library.NewFunction("vertFunc");
mtlpp::Function fragFunc = library.NewFunction("fragFunc");
// vertex buffer
g_vertexBuffer = g_device.NewBuffer(vertexData, sizeof(vertexData), mtlpp::ResourceOptions::CpuCacheModeDefaultCache);
// render state
mtlpp::RenderPipelineDescriptor renderPipelineDesc;
renderPipelineDesc.SetVertexFunction(vertFunc);
renderPipelineDesc.SetFragmentFunction(fragFunc);
renderPipelineDesc.GetColorAttachments()[0].SetPixelFormat(mtlpp::PixelFormat::BGRA8Unorm);
g_renderPipelineState = g_device.NewRenderPipelineState(renderPipelineDesc, nullptr);
// not sure what this is, set up allocation loop/settings?
NSApplication * application = [NSApplication sharedApplication];
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
[NSApp activateIgnoringOtherApps:YES];
return success();
}
bool_t MacOSWindow::processMessages()
{
// main event loop
NSEvent *event = [NSApp nextEventMatchingMask:NSEventMaskAny
untilDate:[NSDate distantFuture]
inMode:NSDefaultRunLoopMode
dequeue:YES];
[NSApp sendEvent:event];
return true;
}
void MacOSWindow::onRender(const sly::os::MacOSWindow& window)
{
//window.onRender();
}
void MacOSWindow::onRender() const
{
// main rendering loop
mtlpp::CommandBuffer commandBuffer = g_commandQueue.CommandBuffer();
mtlpp::RenderPassDescriptor renderPassDesc = m_view.GetRenderPassDescriptor();
if (renderPassDesc)
{
mtlpp::RenderCommandEncoder renderCommandEncoder = commandBuffer.RenderCommandEncoder(renderPassDesc);
renderCommandEncoder.SetRenderPipelineState(g_renderPipelineState);
renderCommandEncoder.SetVertexBuffer(g_vertexBuffer, 0, 0);
renderCommandEncoder.Draw(mtlpp::PrimitiveType::Triangle, 0, 3);
renderCommandEncoder.EndEncoding();
commandBuffer.Present(m_view.GetDrawable());
}
commandBuffer.Commit();
commandBuffer.WaitUntilCompleted();
}
|
a891dc0936faf26597cbcdb65337abb5654bbe7e
|
03caa9561f3f35b9f0851bc58073de1e714a2d07
|
/Car.h
|
6d1a4fb332edab395372bc54ce4fc087dda54d6a
|
[] |
no_license
|
u4bi-dev/cpp_workspace
|
8528c45af6893f8305edb8a63695e2d6f1dada34
|
2ea4d5401109335397b0580087967a4a2bd63cf7
|
refs/heads/master
| 2021-06-09T01:04:33.471515
| 2016-12-02T15:24:10
| 2016-12-02T15:24:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,916
|
h
|
Car.h
|
/*
클래스 Car를 대상으로 파일을 나눈다고 예를 들어보기.
Car.h 클래스의 선언을 담음.
Car.cpp 클래스의 정의(멤버함수 정의)를 담음
여기서 말하는 클래스 선언은 멤버변수의 선언과
멤버함수의 원형을 포함한다고함.
이는 클래스와 관련된 문장의 오류를 잡아내는데 필요한 최소한의 정보
클래스를 구성하는 외형적인 틀을 보여줌
------------------------------------------------
클래스의 정의(definition)에 해당하는 함수의 정의는
다른 문장의 컴파일에 필요한 정보를 가지고 있지 않음.
따라서 함수의 정의는 컴파일 된 이후에 링커에 의해
하나의 실행 파일로 묶이기만 하면 된다고 함.
*/
#ifndef __CAR_H__
#define __CAR_H__
namespace CAR_CONST{
enum{
ID_LEN=20,MAX_SPD=200,FUEL_STEP=2,
ACC_STEP=10,BRK_STEP=10
}; /* 이넘에 차의 정보를 담음*/
}
/* car클래스 선언*/
class Car{
private:
char gamerID[CAR_CONST::ID_LEN];
int fuelGauge;
int curSpeed;
public:
void initMembers(char *ID, int fuel);
void showCarState();
void Accel();
void Break();
};
#endif
/* 헤더 파일에는 앞서 언급한 것처럼 클래스와 관련된 문장의 오류를
잡는데 필요한 최소한의 정보만 들어있음.
각종 상수와 멤버 변수, 멤버 함수 원형이 있는걸 알수 있음.*/
/* 28행과 52행에 생소한 #ifndef와 #endif가 있음.
이건 말 그대로 __CAR_H__가 #define 으로 정의되어 있지 않다면
아래 라인부터 #endif까지 포함시키라는
전처리 지시어임 매크로
반대로 #ifdef도 존재한다고 함.
*/
/*ifndef 같은 경우 헤더 파일의 중복 포함 문제를 방지하기 위한 매크로 선언이라고 함.*/
|
efa6b76570c9c3f7e254f02c509e5d9ab1681df8
|
999fdf150a93dc69d920786641fc9cd8e83f2a75
|
/src/plastimatch/register/translation_mi.cxx
|
b6ac88bf77f06faa520e3cb88abcac5487adbe5c
|
[
"BSD-2-Clause",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
agravgaard/Plastimatch
|
f79294947a1d44dd0c56798277374222fa92df57
|
7b5b79bb1a258d69a653bc82849ed420e673de3d
|
refs/heads/master
| 2021-01-17T06:53:30.814597
| 2020-08-21T12:51:14
| 2020-08-21T12:51:14
| 52,898,082
| 11
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,109
|
cxx
|
translation_mi.cxx
|
/* -----------------------------------------------------------------------
See COPYRIGHT.TXT and LICENSE.TXT for copyright and license information
----------------------------------------------------------------------- */
#include "plmregister_config.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "interpolate.h"
#include "interpolate_macros.h"
#include "logfile.h"
#include "plm_image.h"
#include "plm_image_header.h"
#include "registration_data.h"
#include "joint_histogram.h"
#include "stage_parms.h"
#include "translation_mi.h"
#include "volume.h"
#include "volume_macros.h"
#include "volume_resample.h"
#include "xform.h"
float
translation_mi (
const Stage_parms *stage,
const Metric_state::Pointer& ssi,
const float dxyz[3])
{
Volume *fixed = ssi->fixed_ss.get();
Volume *moving = ssi->moving_ss.get();
Joint_histogram *mi_hist = new Joint_histogram (
stage->mi_hist_type,
stage->mi_hist_fixed_bins,
stage->mi_hist_moving_bins);
mi_hist->initialize (fixed, moving);
mi_hist->reset_histograms ();
plm_long fijk[3], fidx; /* Indices within fixed image (vox) */
float fxyz[3]; /* Position within fixed image (mm) */
float mijk[3]; /* Indices within moving image (vox) */
float mxyz[3]; /* Position within moving image (mm) */
plm_long mijk_f[3], midx_f; /* Floor */
plm_long mijk_r[3]; /* Round */
float li_1[3]; /* Fraction of interpolant in lower index */
float li_2[3]; /* Fraction of interpolant in upper index */
plm_long num_vox = 0;
/* PASS 1 - Accumulate histogram */
LOOP_Z (fijk, fxyz, fixed) {
LOOP_Y (fijk, fxyz, fixed) {
LOOP_X (fijk, fxyz, fixed) {
/* Compute moving image coordinate of fixed image voxel */
mxyz[2] = fxyz[2] + dxyz[2] - moving->origin[2];
mxyz[1] = fxyz[1] + dxyz[1] - moving->origin[1];
mxyz[0] = fxyz[0] + dxyz[0] - moving->origin[0];
mijk[2] = PROJECT_Z (mxyz, moving->proj);
mijk[1] = PROJECT_Y (mxyz, moving->proj);
mijk[0] = PROJECT_X (mxyz, moving->proj);
if (!moving->is_inside (mijk)) continue;
/* Get tri-linear interpolation fractions */
li_clamp_3d (mijk, mijk_f, mijk_r, li_1, li_2, moving);
/* Find the fixed image linear index */
fidx = volume_index (fixed->dim, fijk);
/* Find linear index the corner voxel used to identifiy the
* neighborhood of the moving image voxels corresponding
* to the current fixed image voxel */
midx_f = volume_index (moving->dim, mijk_f);
/* Add to histogram */
mi_hist->add_pvi_8 (fixed, moving, fidx, midx_f, li_1, li_2);
num_vox++;
}
}
}
/* Compute score */
return mi_hist->compute_score (num_vox);
}
|
09f10fe4d96d4c35054aac68bb311ea8e8148b74
|
4e83005d14a1c2d513af2a7c1731b8dab90f875f
|
/src/FileInputStream.h
|
a1ddcf48b4cdcd1d906a25f0e3b5d35c354ce2cb
|
[] |
no_license
|
chris1201/PDFParser
|
6bf3139ad4173bc0aa655b4c606214a4c9e7e3af
|
fd2a38353dc35dd8f3dff2bda229114b17db0751
|
refs/heads/master
| 2021-01-18T09:10:38.945350
| 2014-08-18T02:34:28
| 2014-08-18T02:34:28
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 285
|
h
|
FileInputStream.h
|
#ifndef _FILEINPUTSTREAM_H_
#define _FILEINPUTSTREAM_H_
#include "CompoundInputStream.h"
class CFileInputStream : public CCompoundInputStream
{
public:
CFileInputStream(const char *pFile);
~CFileInputStream();
private:
int m_fd;
unsigned char *m_pData;
int m_nSize;
};
#endif
|
68f652c3104f7c40bf360a5e1585917707d4da84
|
27b3c7fa81a61d9f600ec3010c1e82002ef79b80
|
/arm/mirrr/inc/crssink.h
|
fcf3b48070e45aee84f715e3953377f449a3b973
|
[] |
no_license
|
siemens-elfloader/elf
|
d9222a44481d3a6d2669446cd08c110a80f26225
|
878f7315e755a061967e6d8e0f59566829a9fbdf
|
refs/heads/master
| 2023-02-13T06:59:48.187208
| 2021-01-06T09:41:52
| 2021-01-06T09:41:52
| 327,263,185
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,915
|
h
|
crssink.h
|
#pragma option push -b -a8 -pc -A- /*P_O_Push*/
/* this ALWAYS GENERATED file contains the definitions for the interfaces */
/* File created by MIDL compiler version 3.01.75 */
/* at Thu Apr 23 13:48:22 1998
*/
/* Compiler settings for crssink.idl:
Os (OptLev=s), W1, Zp8, env=Win32, ms_ext, c_ext
error checks: none
*/
//@@MIDL_FILE_HEADING( )
#include "rpc.h"
#include "rpcndr.h"
#ifndef COM_NO_WINDOWS_H
#include "windows.h"
#include "ole2.h"
#endif /*COM_NO_WINDOWS_H*/
#ifndef __crssink_h__
#define __crssink_h__
#ifdef __cplusplus
extern "C"{
#endif
/* Forward Declarations */
#ifndef __IReplicationEventSink_FWD_DEFINED__
#define __IReplicationEventSink_FWD_DEFINED__
typedef interface IReplicationEventSink IReplicationEventSink;
#endif /* __IReplicationEventSink_FWD_DEFINED__ */
#ifndef __SiteServerEventSink_FWD_DEFINED__
#define __SiteServerEventSink_FWD_DEFINED__
#ifdef __cplusplus
typedef class SiteServerEventSink SiteServerEventSink;
#else
typedef struct SiteServerEventSink SiteServerEventSink;
#endif /* __cplusplus */
#endif /* __SiteServerEventSink_FWD_DEFINED__ */
/* header files for imported files */
#include "oaidl.h"
#include "ocidl.h"
void __RPC_FAR * __RPC_USER MIDL_user_allocate(size_t);
void __RPC_USER MIDL_user_free( void __RPC_FAR * );
#ifndef __IReplicationEventSink_INTERFACE_DEFINED__
#define __IReplicationEventSink_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IReplicationEventSink
* at Thu Apr 23 13:48:22 1998
* using MIDL 3.01.75
****************************************/
/* [unique][helpstring][dual][uuid][object] */
EXTERN_C const IID IID_IReplicationEventSink;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("8072C46F-C89A-11D0-BAF5-00C04FD7082F")
IReplicationEventSink : public IDispatch
{
public:
virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE Initialize(
/* [string][in] */ BSTR szName) = 0;
virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE Shutdown( void) = 0;
virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OnEvent(
/* [in] */ VARIANT __RPC_FAR *pvEvent) = 0;
virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE Clear( void) = 0;
};
#else /* C style interface */
typedef struct IReplicationEventSinkVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IReplicationEventSink __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IReplicationEventSink __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IReplicationEventSink __RPC_FAR * This);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetTypeInfoCount )(
IReplicationEventSink __RPC_FAR * This,
/* [out] */ UINT __RPC_FAR *pctinfo);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetTypeInfo )(
IReplicationEventSink __RPC_FAR * This,
/* [in] */ UINT iTInfo,
/* [in] */ LCID lcid,
/* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetIDsOfNames )(
IReplicationEventSink __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames,
/* [in] */ UINT cNames,
/* [in] */ LCID lcid,
/* [size_is][out] */ DISPID __RPC_FAR *rgDispId);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Invoke )(
IReplicationEventSink __RPC_FAR * This,
/* [in] */ DISPID dispIdMember,
/* [in] */ REFIID riid,
/* [in] */ LCID lcid,
/* [in] */ WORD wFlags,
/* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams,
/* [out] */ VARIANT __RPC_FAR *pVarResult,
/* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo,
/* [out] */ UINT __RPC_FAR *puArgErr);
/* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Initialize )(
IReplicationEventSink __RPC_FAR * This,
/* [string][in] */ BSTR szName);
/* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Shutdown )(
IReplicationEventSink __RPC_FAR * This);
/* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnEvent )(
IReplicationEventSink __RPC_FAR * This,
/* [in] */ VARIANT __RPC_FAR *pvEvent);
/* [helpstring] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Clear )(
IReplicationEventSink __RPC_FAR * This);
END_INTERFACE
} IReplicationEventSinkVtbl;
interface IReplicationEventSink
{
CONST_VTBL struct IReplicationEventSinkVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IReplicationEventSink_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IReplicationEventSink_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IReplicationEventSink_Release(This) \
(This)->lpVtbl -> Release(This)
#define IReplicationEventSink_GetTypeInfoCount(This,pctinfo) \
(This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)
#define IReplicationEventSink_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \
(This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)
#define IReplicationEventSink_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \
(This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)
#define IReplicationEventSink_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \
(This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)
#define IReplicationEventSink_Initialize(This,szName) \
(This)->lpVtbl -> Initialize(This,szName)
#define IReplicationEventSink_Shutdown(This) \
(This)->lpVtbl -> Shutdown(This)
#define IReplicationEventSink_OnEvent(This,pvEvent) \
(This)->lpVtbl -> OnEvent(This,pvEvent)
#define IReplicationEventSink_Clear(This) \
(This)->lpVtbl -> Clear(This)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [helpstring] */ HRESULT STDMETHODCALLTYPE IReplicationEventSink_Initialize_Proxy(
IReplicationEventSink __RPC_FAR * This,
/* [string][in] */ BSTR szName);
void __RPC_STUB IReplicationEventSink_Initialize_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring] */ HRESULT STDMETHODCALLTYPE IReplicationEventSink_Shutdown_Proxy(
IReplicationEventSink __RPC_FAR * This);
void __RPC_STUB IReplicationEventSink_Shutdown_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring] */ HRESULT STDMETHODCALLTYPE IReplicationEventSink_OnEvent_Proxy(
IReplicationEventSink __RPC_FAR * This,
/* [in] */ VARIANT __RPC_FAR *pvEvent);
void __RPC_STUB IReplicationEventSink_OnEvent_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring] */ HRESULT STDMETHODCALLTYPE IReplicationEventSink_Clear_Proxy(
IReplicationEventSink __RPC_FAR * This);
void __RPC_STUB IReplicationEventSink_Clear_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IReplicationEventSink_INTERFACE_DEFINED__ */
#ifndef __SiteServerEventSinkLib_LIBRARY_DEFINED__
#define __SiteServerEventSinkLib_LIBRARY_DEFINED__
/****************************************
* Generated header for library: SiteServerEventSinkLib
* at Thu Apr 23 13:48:22 1998
* using MIDL 3.01.75
****************************************/
/* [helpstring][version][uuid] */
EXTERN_C const IID LIBID_SiteServerEventSinkLib;
#ifdef __cplusplus
EXTERN_C const CLSID CLSID_SiteServerEventSink;
class DECLSPEC_UUID("F03E09B6-CCAC-11D0-BAF6-00C04FD7082F")
SiteServerEventSink;
#endif
#endif /* __SiteServerEventSinkLib_LIBRARY_DEFINED__ */
/* Additional Prototypes for ALL interfaces */
unsigned long __RPC_USER BSTR_UserSize( unsigned long __RPC_FAR *, unsigned long , BSTR __RPC_FAR * );
unsigned char __RPC_FAR * __RPC_USER BSTR_UserMarshal( unsigned long __RPC_FAR *, unsigned char __RPC_FAR *, BSTR __RPC_FAR * );
unsigned char __RPC_FAR * __RPC_USER BSTR_UserUnmarshal(unsigned long __RPC_FAR *, unsigned char __RPC_FAR *, BSTR __RPC_FAR * );
void __RPC_USER BSTR_UserFree( unsigned long __RPC_FAR *, BSTR __RPC_FAR * );
unsigned long __RPC_USER VARIANT_UserSize( unsigned long __RPC_FAR *, unsigned long , VARIANT __RPC_FAR * );
unsigned char __RPC_FAR * __RPC_USER VARIANT_UserMarshal( unsigned long __RPC_FAR *, unsigned char __RPC_FAR *, VARIANT __RPC_FAR * );
unsigned char __RPC_FAR * __RPC_USER VARIANT_UserUnmarshal(unsigned long __RPC_FAR *, unsigned char __RPC_FAR *, VARIANT __RPC_FAR * );
void __RPC_USER VARIANT_UserFree( unsigned long __RPC_FAR *, VARIANT __RPC_FAR * );
/* end of Additional Prototypes */
#ifdef __cplusplus
}
#endif
#endif
#pragma option pop /*P_O_Pop*/
|
65842ef1e9b7fa2e4ca47c03f9b918613d57bde8
|
acdb11611fb73caa5a6d145e1a25ef2b347befbf
|
/Day 4/day4.cpp
|
252af30ae6b38053d5a6a44126b7405a1614ba08
|
[] |
no_license
|
NKrChauhan/Data-Structures-and-Algorithms
|
9e48c0ec4afba8b58c9259fd4f7e70c717cd4c94
|
2a801ad0cd6ce8f660d97b74027534e97ec9ca62
|
refs/heads/main
| 2023-03-12T17:34:49.829052
| 2021-02-19T10:53:34
| 2021-02-19T10:53:34
| 313,650,975
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,262
|
cpp
|
day4.cpp
|
#include <iostream>
#include <queue>
#include <vector>
#include <map>
using namespace std;
// structure
struct node{
int data;
struct node *left;
struct node *right;
};
// previously made function reused decleration
struct node *makeBinarySearchTree(int a[],int l);
struct node *getNewNode(int data);
void printNodesInorder(struct node *head);
// previous definitions
struct node *getNewNode(int data){
struct node *head=(struct node*)malloc(sizeof(struct node));
head->data=data;
head->left=NULL;
head->right=NULL;
return head;
}
struct node *makeBinarySearchTree(int a[],int l){
struct node *head=getNewNode(a[0]);
for(int i=1;i<l;i++){
struct node *newN=getNewNode(a[i]);
struct node *point=head;
while(1){
if(point->data>=a[i]){
if(!point->left){
point->left=newN;
break;
}
else point=point->left;
}else{
if(!point->right){
point->right=newN;
break;
}
else point=point->right;
}
}
}
return head;
}
void printNodesInorder(struct node *temp){
if(!temp) return;
printNodesInorder(temp->left);
cout<<temp->data<<", ";
printNodesInorder(temp->right);
return;
}
// Function decleration
struct node *floorBST(struct node *head,struct node *prev,int data);
struct node *ceilBST(struct node *head,struct node *prev,int data);
void PrintRange(struct node *head,int i,int k);
// Function definition
struct node *floorBST(struct node *head,struct node *prev,int data){
if(!head) return prev;
struct node *temp=floorBST(head->left,prev,data);
if(head->data==data) return head;
if(head->data>data) return temp;
else{
prev=head;
return floorBST(head->right,prev,data);
}
}
struct node *ceilBST(struct node *head,struct node *prev,int data){
if(!head) return prev;
if(head->data == data) return head;
struct node *temp=ceilBST(head->right,prev,data);
if(head->data <data)return temp;
else{
prev=head;
return ceilBST(head->left,head,data);
}
}
void PrintRange(struct node *head,int i,int k){
if(!head) return;
if(head->data<=k && head->data>=i){
PrintRange(head->left,i,k);
cout<<head->data<<", ";
PrintRange(head->right,i,k);
}else if(head->data<k && head->data<i)PrintRange(head->right,i,k);
else PrintRange(head->left,i,k);
}
int main(int argc, char const *argv[]) {
int a[]={2,6,3,5,1,8,9};
struct node *head=makeBinarySearchTree(a,7);
cout<<"Inorder print: ";
printNodesInorder(head);
cout<<endl;
cout<<"Range Printing from i to j is : ";
PrintRange(head,4,7);
cout<<endl;
struct node *flr=floorBST(head,NULL,4);
if(flr)cout<<"The floor value of data passd in bst is : "<<flr->data<<endl;
else cout<<"The floor value of data passd in bst is : DoesNotExist"<<endl;
struct node *cl=ceilBST(head,NULL,10);
if(cl)cout<<"The floor value of data passd in bst is : "<<cl->data<<endl;
else cout<<"The ceil value of data passd in bst is : DoesNotExist"<<endl;
return 0;
}
|
37e571c10129a7d49154043d7296e65cec6f279a
|
a139a182d01c43b549b3a1955cefdae9c6db5c70
|
/src/kernel/testdata/repo/oopl/cpp/metax/test_test/TestCaseMetaTest.h
|
117c18faa0da85975a357044de867a5963960522
|
[] |
no_license
|
metaesque/meta
|
520aebf4fecf5450f6cb5f3f024e6c1181d45b85
|
80ca357cb86e8669c7302c2c9277d8b47a23cc48
|
refs/heads/master
| 2023-05-24T18:41:53.104613
| 2023-05-15T01:09:42
| 2023-05-15T01:09:42
| 98,564,975
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 507
|
h
|
TestCaseMetaTest.h
|
#ifndef metax_test_test_TestCaseMetaTest_h
#define metax_test_test_TestCaseMetaTest_h 1
#include "metax/test/TestCase.h"
#include "metax/test/TestCaseMeta.h"
namespace metax {
namespace test_test {
// Auto-generated test class for auto-generated meta class metax.test.TestCaseMeta.
class TestCaseMetaTest : public metax::test::TestCase {
using metax::test::TestCase::TestCase;
// No decl code needed for test_TestCaseMeta
};
} // test_test
} // metax
#endif // metax_test_test_TestCaseMetaTest_h
|
f9d2dfcb0cf4e4296d6e60ee87b217cd51718f81
|
afffc76c474fa0f489bfc266ac60410383895193
|
/Ly Thuyet/Thi Thu Cuoi Ky/bai4/Project1/main.cpp
|
42f5d31f9315d52a11f88ac577e6b8c5b70995c3
|
[] |
no_license
|
dvtrunggg/OOP
|
5113f895b6e8c563a34985e25eebc8a9d5fe4d0b
|
3209293cce74ae60a62241db13a2e8c1b7f2f50f
|
refs/heads/main
| 2023-02-25T17:37:40.000985
| 2021-02-02T16:08:02
| 2021-02-02T16:08:02
| 333,431,145
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 123
|
cpp
|
main.cpp
|
#include"CongTyBaoHiem.h"
int main()
{
CongTyBaoHiem ct;
ct.Nhap();
ct.Xuat();
cout<<ct.tienThuDuoc();
return 0;
}
|
e1d379c92827e0c074c4b3d4eee676e435fbe041
|
6686bf3fe706bd3ea414e9ab6a8cfdd345c81be6
|
/Analysis/bin/wBackground.cpp
|
c569b2105a540135fc794fbc9a615e0cb96dbc51
|
[] |
no_license
|
jimbrooke/InvisibleHiggs
|
1e15e4fd1a06151ab415a0ed69061260b02e38b3
|
95e2c792c7b75e1e0606b6e4c9bca83c9f763592
|
refs/heads/master
| 2021-01-02T08:13:51.445096
| 2014-04-01T17:53:10
| 2014-04-01T17:53:10
| 11,792,965
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 35,362
|
cpp
|
wBackground.cpp
|
#include "InvisibleHiggs/Analysis/interface/ProgramOptions.h"
#include "InvisibleHiggs/Analysis/interface/Cuts.h"
#include "InvisibleHiggs/Analysis/interface/Histogrammer.h"
#include "InvisibleHiggs/Analysis/interface/StackPlot.h"
#include "InvisibleHiggs/Analysis/interface/SumDatasets.h"
#include "InvisibleHiggs/Analysis/interface/Datasets.h"
#include "InvisibleHiggs/Analysis/interface/LeptonWeights.h"
#include "InvisibleHiggs/Analysis/interface/Constants.h"
#include "TTree.h"
#include "TMath.h"
#include "TH1D.h"
#include "TH2D.h"
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include <iostream>
#include <fstream>
int main(int argc, char* argv[]) {
TH1::SetDefaultSumw2();
ProgramOptions options(argc, argv);
double lumi = options.lumi;
std::cout << "Integrated luminosity : " << lumi << " pb-1" << std::endl;
Datasets datasets(options.iDir);
datasets.readFile(options.datasetFile);
// output file
TFile* ofile = TFile::Open( (options.oDir+std::string("/WBackground.root")).c_str(), "RECREATE");
// For control plots
std::string oDirPlots = options.oDir+std::string("/WControlPlots");
boost::filesystem::path opath(oDirPlots);
if (!exists(opath)) {
std::cout << "Creating output directory : " << oDirPlots << std::endl;
boost::filesystem::create_directory(opath);
}
else std::cout << "Writing plots results to " << oDirPlots << std::endl;
std::vector<std::string> hnames; // to hold hist names for control plots
if (options.doMCFMWeights) std::cout << "Going to apply MCFM weights" << std::endl;
// cuts
Cuts cuts;
unsigned nCutsWMu = cuts.nCutsWMu();
unsigned nCutsWEl = cuts.nCutsWEl();
TCut puWeight("puWeight");
TCut elWeight("");//el1Weight");
TCut muWeight("");//mu1Weight");
//TCut wWeight = cuts.wWeight();
TCut trigCorr( "(trigCorrWeight>0) ? trigCorrWeight : 1." );
TCut cutSignalNoMETNoDPhi = cuts.HLTandMETFilters() + cuts.leptonVeto() + cuts.vbf();
// For lepton weights
TCut lVetoWeight = cuts.elVetoWeight(options.leptCorr) * cuts.muVetoWeight(options.leptCorr);
TCut muTightWeight = cuts.muTightWeight(options.leptCorr);
TCut elTightWeight = cuts.elTightWeight(options.leptCorr);
// histograms
double dphiEdges[4] = { 0., 1.0, 2.6, TMath::Pi() };
double metEdges[13] = { 0., 10., 20., 30., 40., 50., 60., 70., 80., 90., 100., 110., 120. };
TH1D* hWMu_MCC_DPhi = new TH1D("hWMu_MCC_DPhi", "", 3, dphiEdges); // W+jets MC ctrl region
TH1D* hWMu_MCS_DPhi = new TH1D("hWMu_MCS_DPhi", "", 3, dphiEdges); // W+jets MC sgnl region
TH1D* hWMu_BGC_DPhi = new TH1D("hWMu_BGC_DPhi", "", 3, dphiEdges); // background MC ctrl region
TH1D* hWMu_DataC_DPhi = new TH1D("hWMu_DataC_DPhi", "", 3, dphiEdges); // Data ctrl region
TH1D* hWEl_MCC_DPhi = new TH1D("hWEl_MCC_DPhi", "", 3, dphiEdges); // W+jets MC ctrl region
TH1D* hWEl_MCS_DPhi = new TH1D("hWEl_MCS_DPhi", "", 3, dphiEdges); // W+jets MC sgnl region
TH1D* hWEl_BGC_DPhi = new TH1D("hWEl_BGC_DPhi", "", 3, dphiEdges); // background MC ctrl region
TH1D* hWEl_DataC_DPhi = new TH1D("hWEl_DataC_DPhi", "", 3, dphiEdges); // Data ctrl region
// cutflow histograms
TH1D* hDataWMu = new TH1D("hWMu_CutFlow_Data", "", nCutsWMu, 0., nCutsWMu);
TH1D* hWLNuWMu = new TH1D("hWMu_CutFlow_WToLNu", "", nCutsWMu, 0., nCutsWMu);
TH1D* hQCDWMu = new TH1D("hWMu_CutFlow_QCD", "", nCutsWMu, 0., nCutsWMu);
TH1D* hDYWMu = new TH1D("hWMu_CutFlow_DY", "", nCutsWMu, 0., nCutsWMu);
TH1D* hSingleTWMu = new TH1D("hWMu_CutFlow_SingleTSum", "", nCutsWMu, 0., nCutsWMu);
TH1D* hDibosonWMu = new TH1D("hWMu_CutFlow_Diboson", "", nCutsWMu, 0., nCutsWMu);
TH1D* hDataWEl = new TH1D("hWEl_CutFlow_Data", "", nCutsWEl, 0., nCutsWEl);
TH1D* hWLNuWEl = new TH1D("hWEl_CutFlow_WToLNu", "", nCutsWEl, 0., nCutsWEl);
TH1D* hQCDWEl = new TH1D("hWEl_CutFlow_QCD", "", nCutsWEl, 0., nCutsWEl);
TH1D* hDYWEl = new TH1D("hWEl_CutFlow_DY", "", nCutsWEl, 0., nCutsWEl);
TH1D* hSingleTWEl = new TH1D("hWEl_CutFlow_SingleTSum", "", nCutsWEl, 0., nCutsWEl);
TH1D* hDibosonWEl = new TH1D("hWEl_CutFlow_Diboson", "", nCutsWEl, 0., nCutsWEl);
// loop over MC datasets
for (unsigned i=0; i<datasets.size(); ++i) {
Dataset dataset = datasets.getDataset(i);
TFile* file = datasets.getTFile(dataset.name);
TTree* tree = (TTree*) file->Get("invHiggsInfo/InvHiggsInfo");
// std::string lwFile = options.iDir + std::string("/") + dataset.name + std::string("_LeptonWeights.root");
// lw.addFriend(tree, lwFile);
// setup cuts
TCut cutD = cuts.cutDataset(dataset.name);
TCut otherCuts = puWeight * trigCorr;
// special cut for QCD W+jets and DY
TCut wWeight("");
TCut yStarWeight("");
TCut mjjWeight("");
TCut cutWMu_C(""), cutWMu_S(""), cutWEl_C(""), cutWEl_S("");
TCut cutWMuControlPlot("");
TCut cutWElControlPlot("");
// tmp histograms
TH1D* hWMu_C_DPhi = new TH1D("hWMu_C_DPhi", "", 3, dphiEdges); // W+jets MC ctrl region
TH1D* hWMu_S_DPhi = new TH1D("hWMu_S_DPhi", "", 3, dphiEdges); // W+jets MC sgnl region
TH1D* hWEl_C_DPhi = new TH1D("hWEl_C_DPhi", "", 3, dphiEdges); // W+jets MC ctrl region
TH1D* hWEl_S_DPhi = new TH1D("hWEl_S_DPhi", "", 3, dphiEdges); // W+jets MC sgnl region
double weight = 1.;
// check it's W+Jets
bool isWJets = false;
bool isEwkW = false;
bool isQCD = false;
if (dataset.name == "WJets" ||
dataset.name == "W1Jets" ||
dataset.name == "W2Jets" ||
dataset.name == "W3Jets" ||
dataset.name == "W4Jets" ||
dataset.name == "EWK_Wp2Jets" ||
dataset.name == "EWK_Wm2Jets") {
std::cout << "Analysing W MC : " << dataset.name << std::endl;
if (dataset.name == "EWK_Wp2Jets" || dataset.name == "EWK_Wm2Jets") isEwkW = true;
else isWJets = true;
if(isWJets) {
if (options.doMCFMWeights) {
yStarWeight = TCut("8.49667e-01 + (1.49687e-01*abs((log((sqrt(wgenmass*wgenmass + wgenpt*wgenpt*cosh(wgeneta)*cosh(wgeneta)) + wgenpt*sinh(wgeneta))/(sqrt(wgenmass*wgenmass + wgenpt*wgenpt)))) - 0.5*(genJet1Eta + genJet2Eta)))");
mjjWeight = TCut("3.92568e-01 + (1.20734e-01*log(genVBFM)) - (2.55622e-04*genVBFM)");
wWeight = yStarWeight * mjjWeight * cuts.wWeight();
}
else {
wWeight = cuts.wWeight();
}
}
cutWMu_C = otherCuts * muTightWeight * wWeight * (cuts.wMuVBF() + cuts.cutWMu("MET"));
cutWMu_S = otherCuts * lVetoWeight * wWeight * (cuts.wMuGen() + cuts.allCutsNoDPhi());
cutWEl_C = otherCuts * elTightWeight * wWeight * (cuts.wElVBF() + cuts.cutWEl("MET"));
cutWEl_S = otherCuts * lVetoWeight * wWeight * (cuts.wElGen() + cuts.allCutsNoDPhi());
cutWMuControlPlot = otherCuts * muTightWeight * wWeight * (cuts.HLTandMETFilters() + cuts.vbfloose() + cuts.cutWMu("MET") + cuts.cutWMu("wMu") );
cutWElControlPlot = otherCuts * elTightWeight * wWeight * (cuts.HLTandMETFilters() + cuts.vbfloose() + cuts.cutWEl("MET") + cuts.cutWEl("wEl") );
// weight to lumi
weight = lumi * dataset.sigma / dataset.nEvents;
std::cout << " weight : " << weight << std::endl;
tree->Draw("vbfDPhi>>hWMu_C_DPhi", cutWMu_C);
tree->Draw("vbfDPhi>>hWMu_S_DPhi", cutWMu_S);
tree->Draw("vbfDPhi>>hWEl_C_DPhi", cutWEl_C);
tree->Draw("vbfDPhi>>hWEl_S_DPhi", cutWEl_S);
hWMu_C_DPhi->Scale(weight);
hWMu_S_DPhi->Scale(weight);
hWEl_C_DPhi->Scale(weight);
hWEl_S_DPhi->Scale(weight);
// add to final histogram
hWMu_MCC_DPhi->Add(hWMu_C_DPhi);
hWMu_MCS_DPhi->Add(hWMu_S_DPhi);
hWEl_MCC_DPhi->Add(hWEl_C_DPhi);
hWEl_MCS_DPhi->Add(hWEl_S_DPhi);
}
else if (dataset.isData) {
std::cout << "Analysing Data : " << dataset.name << std::endl;
cutWMu_C = (cuts.wMuVBF() + cuts.cutWMu("MET"));
cutWMu_S = cuts.allCutsNoDPhi();
cutWEl_C = (cuts.wElVBF() + cuts.cutWEl("MET"));
cutWEl_S = cuts.allCutsNoDPhi();
tree->Draw("vbfDPhi>>hWMu_C_DPhi", cutWMu_C);
tree->Draw("vbfDPhi>>hWMu_S_DPhi", cutWMu_S);
tree->Draw("vbfDPhi>>hWEl_C_DPhi", cutWEl_C);
tree->Draw("vbfDPhi>>hWEl_S_DPhi", cutWEl_S);
hWMu_DataC_DPhi->Add(hWMu_C_DPhi);
hWEl_DataC_DPhi->Add(hWEl_C_DPhi);
cutWMuControlPlot = (cuts.HLTandMETFilters() + cuts.vbfloose() + cuts.cutWMu("MET") + cuts.cutWMu("wMu") );
cutWElControlPlot = (cuts.HLTandMETFilters() + cuts.vbfloose() + cuts.cutWEl("MET") + cuts.cutWEl("wEl") );
}
else {
std::cout << "Analysing BG MC : " << dataset.name << std::endl;
if (dataset.name.compare(0,3,"QCD") == 0) isQCD = true;
if (dataset.name == "DYJetsToLL_PtZ-100" || dataset.name == "DYJetsToLL") {
if (options.doMCFMWeights) {
yStarWeight = TCut("8.49667e-01 + (1.49687e-01*abs((log((sqrt(zgenmass*zgenmass + zgenpt*zgenpt*cosh(zgeneta)*cosh(zgeneta)) + zgenpt*sinh(zgeneta))/(sqrt(zgenmass*zgenmass + zgenpt*zgenpt)))) - 0.5*(genJet1Eta + genJet2Eta)))");
mjjWeight = TCut("3.92568e-01 + (1.20734e-01*log(genVBFM)) - (2.55622e-04*genVBFM)");
}
}
otherCuts *= yStarWeight * mjjWeight;
cutWMu_C = otherCuts * muTightWeight * (cutD + cuts.wMuVBF() + cuts.cutWMu("MET"));
cutWMu_S = otherCuts * lVetoWeight * (cutD + cuts.allCutsNoDPhi());
cutWEl_C = otherCuts * elTightWeight * (cutD + cuts.wElVBF() + cuts.cutWEl("MET"));
cutWEl_S = otherCuts * lVetoWeight * (cutD + cuts.allCutsNoDPhi());
cutWMuControlPlot = otherCuts * muTightWeight * (cutD + cuts.HLTandMETFilters() + cuts.vbfloose() + cuts.cutWMu("MET") + cuts.cutWMu("wMu") );
cutWElControlPlot = otherCuts * elTightWeight * (cutD + cuts.HLTandMETFilters() + cuts.vbfloose() + cuts.cutWEl("MET") + cuts.cutWEl("wEl") );
// weight to lumi
weight = lumi * dataset.sigma / dataset.nEvents;
std::cout << " weight : " << weight << std::endl;
tree->Draw("vbfDPhi>>hWMu_C_DPhi", cutWMu_C);
tree->Draw("vbfDPhi>>hWEl_C_DPhi", cutWEl_C);
hWMu_C_DPhi->Scale(weight);
hWEl_C_DPhi->Scale(weight);
if (!isQCD) {
hWMu_BGC_DPhi->Add(hWMu_C_DPhi);
hWEl_BGC_DPhi->Add(hWEl_C_DPhi);
}
}
// debug output
std::cout << " N ctrl (mu, dphi<1) : " << hWMu_C_DPhi->GetBinContent(1) << " +/- " << hWMu_C_DPhi->GetBinError(1) << std::endl;
std::cout << " N sgnl (mu, dphi<1) : " << hWMu_S_DPhi->GetBinContent(1) << " +/- " << hWMu_S_DPhi->GetBinError(1) << std::endl;
std::cout << " N ctrl (el, dphi<1) : " << hWEl_C_DPhi->GetBinContent(1) << " +/- " << hWEl_C_DPhi->GetBinError(1) << std::endl;
std::cout << " N sgnl (el, dphi<1) : " << hWEl_S_DPhi->GetBinContent(1) << " +/- " << hWEl_S_DPhi->GetBinError(1) << std::endl;
delete hWMu_C_DPhi;
delete hWMu_S_DPhi;
delete hWEl_C_DPhi;
delete hWEl_S_DPhi;
// per-dataset control plots (just an example, add more later)
ofile->cd();
// per-dataset cutflow hists
std::string hnameWMu = std::string("hWMu_CutFlow_")+dataset.name;
std::string hnameWEl = std::string("hWEl_CutFlow_")+dataset.name;
TH1D* hCutFlowWMu = new TH1D(hnameWMu.c_str(), "", nCutsWMu, 0., nCutsWMu);
TH1D* hCutFlowWEl = new TH1D(hnameWEl.c_str(), "", nCutsWEl, 0., nCutsWEl);
for (unsigned c=0; c<nCutsWMu; ++c) {
TCut cut;
if(c == nCutsWMu-1) //apply trigger correction
{
cut = otherCuts * (cutD + cuts.cutflowWMu(c));
if(isWJets) cut = otherCuts * wWeight * (cuts.cutflowWMu(c));
if(!(dataset.isData)) cut *= muTightWeight;
}
else
{
cut = puWeight * yStarWeight * mjjWeight * (cutD + cuts.cutflowWMu(c));
if(isWJets) cut = puWeight * wWeight * (cuts.cutflowWMu(c));
if(!(dataset.isData)) cut *= muTightWeight;
}
TH1D* h = new TH1D("h","", 1, 0., 1.);
tree->Draw("0.5>>h", cut);
hCutFlowWMu->SetBinContent(c+1, h->GetBinContent(1));
hCutFlowWMu->SetBinError(c+1, h->GetBinError(1));
delete h;
}
for (unsigned c=0; c<nCutsWEl; ++c) {
TCut cut;
if(c == nCutsWEl-1) //apply trigger correction
{
cut = otherCuts * (cutD + cuts.cutflowWEl(c));
if(isWJets) cut = otherCuts * wWeight * (cuts.cutflowWEl(c));
if(!(dataset.isData)) cut *= elTightWeight;
}
else
{
cut = puWeight * yStarWeight * mjjWeight * (cuts.cutflowWEl(c));
if(isWJets) cut = puWeight * wWeight * (cuts.cutflowWEl(c));
if(!(dataset.isData)) cut *= elTightWeight;
}
TH1D* h = new TH1D("h","", 1, 0., 1.);
tree->Draw("0.5>>h", cut);
hCutFlowWEl->SetBinContent(c+1, h->GetBinContent(1));
hCutFlowWEl->SetBinError(c+1, h->GetBinError(1));
delete h;
}
hCutFlowWMu->Scale(weight);
hCutFlowWEl->Scale(weight);
// sum histograms
if (dataset.isData) {
hDataWMu->Add(hCutFlowWMu);
hDataWEl->Add(hCutFlowWEl);
}
if (isWJets || isEwkW) {
hWLNuWMu->Add(hCutFlowWMu);
hWLNuWEl->Add(hCutFlowWEl);
}
if (dataset.name.compare(0,3,"QCD")==0) {
hQCDWMu->Add(hCutFlowWMu);
hQCDWEl->Add(hCutFlowWEl);
}
if (dataset.name.compare(0,2,"DY")==0) {
hDYWMu->Add(hCutFlowWMu);
hDYWEl->Add(hCutFlowWEl);
}
if (dataset.name.compare(0,7,"SingleT")==0) {
hSingleTWMu->Add(hCutFlowWMu);
hSingleTWEl->Add(hCutFlowWEl);
}
if (dataset.name.compare(0,2,"WW")==0 ||
dataset.name.compare(0,2,"WZ")==0 ||
dataset.name.compare(0,2,"ZZ")==0 ||
dataset.name.compare(0,2,"WG")==0) {
hDibosonWMu->Add(hCutFlowWMu);
hDibosonWEl->Add(hCutFlowWEl);
}
hCutFlowWMu->Write("",TObject::kOverwrite);
hCutFlowWEl->Write("",TObject::kOverwrite);
delete hCutFlowWMu;
delete hCutFlowWEl;
// For electron and muon channels do control plots:
// jet1Pt, jet2Pt, jet1Eta, jet2Eta, Mjj, dEtajj, dPhijj, MET and W_mT, W_pT
TFile* ofilePlots = TFile::Open( (oDirPlots+std::string("/")+dataset.name+std::string(".root")).c_str(), "RECREATE");
std::string chan[] = {"Mu", "El"};
// weight = (dataset.isData) ? 1. : (lumi * dataset.sigma / dataset.nEvents);
// std::cout << " weight : " << weight << std::endl;
for (int c = 0; c < 2; c++){
TCut Wcut = (c) ? cutWElControlPlot : cutWMuControlPlot; //wWeight included above
std::string hname = "hW"+chan[c]+"_jet1Pt";
if (i==0) hnames.push_back(hname);
TH1D* hJet1Pt = new TH1D(hname.c_str(), "", 50, 0., 1000.);
std::string str = "jet1Pt>>"+hname;
tree->Draw(str.c_str(), Wcut);
hJet1Pt->Scale(weight);
hJet1Pt->Write("", TObject::kOverwrite);
hname = "hW"+chan[c]+"_jet2Pt";
if (i==0) hnames.push_back(hname);
TH1D* hJet2Pt = new TH1D(hname.c_str(), "", 50, 0., 1000.);
str = "jet2Pt>>"+hname;
tree->Draw(str.c_str(), Wcut);
hJet2Pt->Scale(weight);
hJet2Pt->Write("", TObject::kOverwrite);
hname = "hW"+chan[c]+"_jet1Eta";
if (i==0) hnames.push_back(hname);
TH1D* hJet1Eta = new TH1D(hname.c_str(), "", 50, -5., 5.);
str = "jet1Eta>>"+hname;
tree->Draw(str.c_str(), Wcut);
hJet1Eta->Scale(weight);
hJet1Eta->Write("", TObject::kOverwrite);
hname = "hW"+chan[c]+"_jet2Eta";
if (i==0) hnames.push_back(hname);
TH1D* hJet2Eta = new TH1D(hname.c_str(), "", 50, -5., 5.);
str = "jet2Eta>>"+hname;
tree->Draw(str.c_str(), Wcut);
hJet2Eta->Scale(weight);
hJet2Eta->Write("", TObject::kOverwrite);
hname = "hW"+chan[c]+"_Mjj";
if (i==0) hnames.push_back(hname);
TH1D* hMjj = new TH1D(hname.c_str(), "", 50, 0., 4000. );
str = "vbfM>>"+hname;
tree->Draw(str.c_str(), Wcut);
hMjj->Scale(weight);
hMjj->Write("", TObject::kOverwrite);
hname = "hW"+chan[c]+"_dEtaJJ";
if (i==0) hnames.push_back(hname);
TH1D* hDEtaJJ = new TH1D(hname.c_str(), "", 50, 0.,8.);
str = "vbfDEta>>"+hname;
tree->Draw(str.c_str(), Wcut);
hDEtaJJ->Scale(weight);
hDEtaJJ->Write("", TObject::kOverwrite);
hname = "hW"+chan[c]+"_dPhiJJ";
if (i==0) hnames.push_back(hname);
TH1D* hDPhiJJ = new TH1D(hname.c_str(), "", 50, 0., TMath::Pi());
str = "vbfDPhi>>"+hname;
tree->Draw(str.c_str(), Wcut);
hDPhiJJ->Scale(weight);
hDPhiJJ->Write("", TObject::kOverwrite);
hname = "hW"+chan[c]+"_MET";
if (i==0) hnames.push_back(hname);
TH1D* hMET = new TH1D(hname.c_str(), "", 50, 0., 500. );
if (c)
str = "met>>"+hname;
else
str = "metNoWLepton>>"+hname;
tree->Draw(str.c_str(), Wcut);
hMET->Scale(weight);
hMET->Write("", TObject::kOverwrite);
hname = "hW"+chan[c]+"_WmT";
if (i==0) hnames.push_back(hname);
TH1D* hWmT = new TH1D(hname.c_str(), "", 20, 0., 200.);
str = "wMt>>"+hname;
tree->Draw(str.c_str(), Wcut);
hWmT->Scale(weight);
hWmT->Write("", TObject::kOverwrite);
hname = "hW"+chan[c]+"_WpT";
if (i==0) hnames.push_back(hname);
TH1D* hWpT = new TH1D(hname.c_str(), "", 25, 0., 500. );
str = "wPt>>"+hname;
tree->Draw(str.c_str(), Wcut);
hWpT->Scale(weight);
hWpT->Write("", TObject::kOverwrite);
}
delete tree;
ofilePlots->Close();
file->Close();
}
// W->mu
// stat only histograms
TH1D* hWMu_R_DPhi = new TH1D("hWMu_R_DPhi", "", 3, dphiEdges); // ratio of sngl/ctrl
TH1D* hWMu_EstC_DPhi = new TH1D("hWMu_EstC_DPhi", "", 3, dphiEdges); // estimated W in ctrl region
TH1D* hWMu_EstS_DPhi = new TH1D("hWMu_EstS_DPhi", "", 3, dphiEdges); // estimated W in signal region
// syst only histograms
TH1D* hWMu_BGC_DPhi_Syst = new TH1D("hWMu_BGC_DPhi_Syst", "", 3, dphiEdges);
TH1D* hWMu_DataC_DPhi_Syst = new TH1D("hWMu_DataC_DPhi_Syst", "", 3, dphiEdges);
TH1D* hWMu_R_DPhi_Syst = new TH1D("hWMu_R_DPhi_Syst", "", 3, dphiEdges); // ratio of sngl/ctrl
TH1D* hWMu_EstC_DPhi_Syst = new TH1D("hWMu_EstC_DPhi_Syst", "", 3, dphiEdges); // estimated W in ctrl region
TH1D* hWMu_EstS_DPhi_Syst = new TH1D("hWMu_EstS_DPhi_Syst", "", 3, dphiEdges); // estimated W in signal region
// stat only calculation
hWMu_R_DPhi->Divide(hWMu_MCS_DPhi, hWMu_MCC_DPhi, 1., 1.);
for (int i=1; i<=hWMu_R_DPhi->GetNbinsX(); ++i) hWMu_R_DPhi->SetBinError(i,0.); // ignore MC stats
hWMu_BGC_DPhi_Syst->Add(hWMu_BGC_DPhi, 1.); // take a copy for the syst only
for (int i=1; i<=hWMu_BGC_DPhi->GetNbinsX(); ++i) hWMu_BGC_DPhi->SetBinError(i,0.); // ignore MC stats
hWMu_EstC_DPhi->Add(hWMu_DataC_DPhi, hWMu_BGC_DPhi, 1., -1.);
hWMu_EstS_DPhi->Multiply(hWMu_EstC_DPhi, hWMu_R_DPhi, 1., 1.);
// syst only calculation
hWMu_DataC_DPhi_Syst->Add(hWMu_DataC_DPhi, 1.);
for (int i=1; i<=hWMu_DataC_DPhi_Syst->GetNbinsX(); ++i) hWMu_DataC_DPhi_Syst->SetBinError(i,0.); // ignore data stats
hWMu_R_DPhi_Syst->Divide(hWMu_MCS_DPhi, hWMu_MCC_DPhi, 1., 1.);
hWMu_EstC_DPhi_Syst->Add(hWMu_DataC_DPhi_Syst, hWMu_BGC_DPhi_Syst, 1., -1.);
hWMu_EstS_DPhi_Syst->Multiply(hWMu_EstC_DPhi_Syst, hWMu_R_DPhi_Syst, 1., 1.);
// W->e
// stat only histograms
TH1D* hWEl_R_DPhi = new TH1D("hWEl_R_DPhi", "", 3, dphiEdges);
TH1D* hWEl_EstC_DPhi = new TH1D("hWEl_EstC_DPhi", "", 3, dphiEdges);
TH1D* hWEl_EstS_DPhi = new TH1D("hWEl_EstS_DPhi", "", 3, dphiEdges);
// syst only histograms
TH1D* hWEl_BGC_DPhi_Syst = new TH1D("hWEl_BGC_DPhi_Syst", "", 3, dphiEdges);
TH1D* hWEl_DataC_DPhi_Syst = new TH1D("hWEl_DataC_DPhi_Syst", "", 3, dphiEdges);
TH1D* hWEl_R_DPhi_Syst = new TH1D("hWEl_R_DPhi_Syst", "", 3, dphiEdges);
TH1D* hWEl_EstC_DPhi_Syst = new TH1D("hWEl_EstC_DPhi_Syst", "", 3, dphiEdges);
TH1D* hWEl_EstS_DPhi_Syst = new TH1D("hWEl_EstS_DPhi_Syst", "", 3, dphiEdges);
// stat only calculation
hWEl_R_DPhi->Divide(hWEl_MCS_DPhi, hWEl_MCC_DPhi, 1., 1.);
for (int i=1; i<=hWEl_R_DPhi->GetNbinsX(); ++i) hWEl_R_DPhi->SetBinError(i,0.);
hWEl_BGC_DPhi_Syst->Add(hWEl_BGC_DPhi, 1.); // take a copy for the syst only
for (int i=1; i<=hWEl_BGC_DPhi->GetNbinsX(); ++i) hWEl_BGC_DPhi->SetBinError(i,0.); // ignore MC BG uncertainty
hWEl_EstC_DPhi->Add(hWEl_DataC_DPhi, hWEl_BGC_DPhi, 1., -1.);
hWEl_EstS_DPhi->Multiply(hWEl_EstC_DPhi, hWEl_R_DPhi, 1., 1.);
// syst only calculation
hWEl_DataC_DPhi_Syst->Add(hWEl_DataC_DPhi, 1.);
for (int i=1; i<=hWEl_DataC_DPhi_Syst->GetNbinsX(); ++i) hWEl_DataC_DPhi_Syst->SetBinError(i,0.); // ignore data stats
hWEl_R_DPhi_Syst->Divide(hWEl_MCS_DPhi, hWEl_MCC_DPhi, 1., 1.);
hWEl_EstC_DPhi_Syst->Add(hWEl_DataC_DPhi_Syst, hWEl_BGC_DPhi_Syst, 1., -1.);
hWEl_EstS_DPhi_Syst->Multiply(hWEl_EstC_DPhi_Syst, hWEl_R_DPhi_Syst, 1., 1.);
std::cout << std::endl;
/*
std::cout << "W->mu channel (dphi>2.6)" << std::endl;
std::cout << " W+jets MC ctrl region : " << hWMu_MCC_DPhi->GetBinContent(3) << " +/- " << hWMu_MCC_DPhi->GetBinError(3) << std::endl;
std::cout << " W+jets MC sgnl region : " << hWMu_MCS_DPhi->GetBinContent(3) << " +/- " << hWMu_MCS_DPhi->GetBinError(3) << std::endl;
std::cout << " Background ctrl region : " << hWMu_BGC_DPhi->GetBinContent(3) << " +/- " << hWMu_BGC_DPhi->GetBinError(3) << std::endl;
// std::cout << " Background sgnl region : " << hWMu_BGS_DPhi->GetBinContent(3) << " +/- " << hWMu_BGS_DPhi->GetBinError(3) << std::endl;
std::cout << " Data ctrl region : " << hWMu_DataC_DPhi->GetBinContent(3) << " +/- " << hWMu_DataC_DPhi->GetBinError(3) << std::endl;
std::cout << std::endl;
std::cout << " W in ctrl region : " << hWMu_EstC_DPhi->GetBinContent(3) << " +/- " << hWMu_EstC_DPhi->GetBinError(3) << std::endl;
std::cout << " N_S(MC)/N_C(MC) : " << hWMu_R_DPhi->GetBinContent(3) << " +/- " << hWMu_R_DPhi->GetBinError(3) << std::endl;
std::cout << " W in sgnl region : " << hWMu_EstS_DPhi->GetBinContent(3) << " +/- " << hWMu_EstS_DPhi->GetBinError(3) << std::endl;
std::cout << std::endl << std::endl;
std::cout << "W->el channel (dphi>2.6)" << std::endl;
std::cout << " W+jets MC ctrl region : " << hWEl_MCC_DPhi->GetBinContent(3) << " +/- " << hWEl_MCC_DPhi->GetBinError(3) << std::endl;
std::cout << " W+jets MC sgnl region : " << hWEl_MCS_DPhi->GetBinContent(3) << " +/- " << hWEl_MCS_DPhi->GetBinError(3) << std::endl;
std::cout << " Background ctrl region : " << hWEl_BGC_DPhi->GetBinContent(3) << " +/- " << hWEl_BGC_DPhi->GetBinError(3) << std::endl;
// std::cout << " Background sgnl region : " << hWEl_BGS_DPhi->GetBinContent(3) << std::endl;
std::cout << " Data ctrl region : " << hWEl_DataC_DPhi->GetBinContent(3) << " +/- " << hWEl_DataC_DPhi->GetBinError(3) << std::endl;
std::cout << std::endl;
std::cout << " W in ctrl region : " << hWEl_EstC_DPhi->GetBinContent(3) << " +/- " << hWEl_EstC_DPhi->GetBinError(3) << std::endl;
std::cout << " N_S(MC)/N_C(MC) : " << hWEl_R_DPhi->GetBinContent(3) << " +/- " << hWEl_R_DPhi->GetBinError(3) << std::endl;
std::cout << " W in sgnl region : " << hWEl_EstS_DPhi->GetBinContent(3) << " +/- " << hWEl_EstS_DPhi->GetBinError(3) << std::endl;
std::cout << std::endl << std::endl;
*/
std::cout << "W->mu channel (dphi<1.0)" << std::endl;
std::cout << " W+jets MC ctrl region : " << hWMu_MCC_DPhi->GetBinContent(1) << " +/- 0 (stat) +/- " << hWMu_MCC_DPhi->GetBinError(1) << " (syst)" << std::endl;
std::cout << " W+jets MC sgnl region : " << hWMu_MCS_DPhi->GetBinContent(1) << " +/- 0 (stat) +/- " << hWMu_MCS_DPhi->GetBinError(1) << " (syst)" << std::endl;
std::cout << " Background ctrl region : " << hWMu_BGC_DPhi->GetBinContent(1) << " +/- " << hWMu_BGC_DPhi->GetBinError(1) << " (stat) +/- " << hWMu_BGC_DPhi_Syst->GetBinError(1) << " (syst)" << std::endl;
// std::cout << " Background sgnl region : " << hWMu_BGS_DPhi->GetBinContent(1) << std::endl;
std::cout << " Data ctrl region : " << hWMu_DataC_DPhi->GetBinContent(1) << " +/- " << hWMu_DataC_DPhi->GetBinError(1) << " (stat) +/- " << hWMu_DataC_DPhi_Syst->GetBinError(1) << " (syst)" << std::endl;
std::cout << std::endl;
std::cout << " W in ctrl region : " << hWMu_EstC_DPhi->GetBinContent(1) << " +/- " << hWMu_EstC_DPhi->GetBinError(1) << " (stat) +/- " << hWMu_EstC_DPhi_Syst->GetBinError(1) << " (syst)" << std::endl;
std::cout << " N_S(MC)/N_C(MC) : " << hWMu_R_DPhi->GetBinContent(1) << " +/- " << hWMu_R_DPhi->GetBinError(1) << " (stat) +/- " << hWMu_R_DPhi_Syst->GetBinError(1) << " (syst)" << std::endl;
std::cout << " W in sgnl region : " << hWMu_EstS_DPhi->GetBinContent(1) << " +/- " << hWMu_EstS_DPhi->GetBinError(1) << " (stat) +/- " << hWMu_EstS_DPhi_Syst->GetBinError(1) << " (syst)" << std::endl;
std::cout << std::endl << std::endl;
std::cout << "W->el channel (dphi<1.0)" << std::endl;
std::cout << " W+jets MC ctrl region : " << hWEl_MCC_DPhi->GetBinContent(1) << " +/- 0 (stat) +/- " << hWEl_MCC_DPhi->GetBinError(1) << " (syst)" << std::endl;
std::cout << " W+jets MC sgnl region : " << hWEl_MCS_DPhi->GetBinContent(1) << " +/- 0 (stat) +/- " << hWEl_MCS_DPhi->GetBinError(1) << " (syst)" << std::endl;
std::cout << " Background ctrl region : " << hWEl_BGC_DPhi->GetBinContent(1) << " +/- " << hWEl_BGC_DPhi->GetBinError(1) << " (stat) +/- " << hWEl_BGC_DPhi_Syst->GetBinError(1) << " (syst)" << std::endl;
// std::cout << " Background sgnl region : " << hWEl_BGS_DPhi->GetBinContent(1) << std::endl;
std::cout << " Data ctrl region : " << hWEl_DataC_DPhi->GetBinContent(1) << " +/- " << hWEl_DataC_DPhi->GetBinError(1) << " (stat) +/- " << hWEl_DataC_DPhi_Syst->GetBinError(1) << " (syst)" << std::endl;
std::cout << std::endl;
std::cout << " W in ctrl region : " << hWEl_EstC_DPhi->GetBinContent(1) << " +/- " << hWEl_EstC_DPhi->GetBinError(1) << " (stat) +/- " << hWEl_EstC_DPhi_Syst->GetBinError(1) << " (syst)" << std::endl;
std::cout << " N_S(MC)/N_C(MC) : " << hWEl_R_DPhi->GetBinContent(1) << " +/- " << hWEl_R_DPhi->GetBinError(1) << " (stat) +/- " << hWEl_R_DPhi_Syst->GetBinError(1) << " (syst)" << std::endl;
std::cout << " W in sgnl region : " << hWEl_EstS_DPhi->GetBinContent(1) << " +/- " << hWEl_EstS_DPhi->GetBinError(1) << " (stat) +/- " << hWEl_EstS_DPhi_Syst->GetBinError(1) << " (syst)" << std::endl;
std::cout << std::endl << std::endl;
// write the cutflow table
std::cout << "Writing cut flow TeX file" << std::endl;
ofstream effFile;
effFile.open(options.oDir+std::string("/cutflowWMu.tex"));
effFile << "Cut & N(data) & N($W\\rightarrow l\\nu$) & N(DY) & N(QCD) & N($t\\bar{t}$) & N(single $t$) & N(diboson) \\\\" << std::endl;
TH1D* hTTbarWMu = (TH1D*) ofile->Get("hWMu_CutFlow_TTBar");
// cutflow table
for (unsigned i=0; i<nCutsWMu; ++i) {
effFile << cuts.cutNameWMu(i) << " & ";
effFile << "$" << hDataWMu->GetBinContent(i+1) << " \\pm " << hDataWMu->GetBinError(i+1) << "$ & ";
effFile << "$" << hWLNuWMu->GetBinContent(i+1) << " \\pm " << hWLNuWMu->GetBinError(i+1) << "$ & ";
effFile << "$" << hDYWMu->GetBinContent(i+1) << " \\pm " << hDYWMu->GetBinError(i+1) << "$ & ";
effFile << "$" << hQCDWMu->GetBinContent(i+1) << " \\pm " << hQCDWMu->GetBinError(i+1) << "$ & ";
effFile << "$" << hTTbarWMu->GetBinContent(i+1) << " \\pm " << hTTbarWMu->GetBinError(i+1) << "$ & ";
effFile << "$" << hSingleTWMu->GetBinContent(i+1) << " \\pm " << hSingleTWMu->GetBinError(i+1) << "$ & ";
effFile << "$" << hDibosonWMu->GetBinContent(i+1) << " \\pm " << hDibosonWMu->GetBinError(i+1) << "$ \\\\ ";
effFile << std::endl;
}
effFile << std::endl << std::endl;
effFile.close();
//WEl cutflow
effFile.open(options.oDir+std::string("/cutflowWEl.tex"));
effFile << "Cut & N(data) & N($W\\rightarrow l\\nu$) & N(DY) & N(QCD) & N($t\\bar{t}$) & N(single $t$) & N(diboson) \\\\" << std::endl;
TH1D* hTTbarWEl = (TH1D*) ofile->Get("hWEl_CutFlow_TTBar");
// cutflow table
for (unsigned i=0; i<nCutsWEl; ++i) {
effFile << cuts.cutNameWEl(i) << " & ";
effFile << "$" << hDataWEl->GetBinContent(i+1) << " \\pm " << hDataWEl->GetBinError(i+1) << "$ & ";
effFile << "$" << hWLNuWEl->GetBinContent(i+1) << " \\pm " << hWLNuWEl->GetBinError(i+1) << "$ & ";
effFile << "$" << hDYWEl->GetBinContent(i+1) << " \\pm " << hDYWEl->GetBinError(i+1) << "$ & ";
effFile << "$" << hQCDWEl->GetBinContent(i+1) << " \\pm " << hQCDWEl->GetBinError(i+1) << "$ & ";
effFile << "$" << hTTbarWEl->GetBinContent(i+1) << " \\pm " << hTTbarWEl->GetBinError(i+1) << "$ & ";
effFile << "$" << hSingleTWEl->GetBinContent(i+1) << " \\pm " << hSingleTWEl->GetBinError(i+1) << "$ & ";
effFile << "$" << hDibosonWEl->GetBinContent(i+1) << " \\pm " << hDibosonWEl->GetBinError(i+1) << "$ \\\\ ";
effFile << std::endl;
}
effFile << std::endl << std::endl;
effFile.close();
for (unsigned n = 0; n < hnames.size(); n++)
std::cout << hnames[n] <<std::endl;
// Do control plots
std::vector<std::string> wjetsDatasets;
wjetsDatasets.push_back(std::string("WJets"));
wjetsDatasets.push_back(std::string("W1Jets"));
wjetsDatasets.push_back(std::string("W2Jets"));
wjetsDatasets.push_back(std::string("W3Jets"));
wjetsDatasets.push_back(std::string("W4Jets"));
wjetsDatasets.push_back(std::string("EWK_Wp2Jets"));
wjetsDatasets.push_back(std::string("EWK_Wm2Jets"));
SumDatasets(oDirPlots, wjetsDatasets, hnames, "WNJets+EWK");
std::vector<std::string> topDatasets;
topDatasets.push_back(std::string("SingleT_t"));
topDatasets.push_back(std::string("SingleTbar_t"));
topDatasets.push_back(std::string("SingleT_s"));
topDatasets.push_back(std::string("SingleTbar_s"));
topDatasets.push_back(std::string("SingleT_tW"));
topDatasets.push_back(std::string("SingleTbar_tW"));
topDatasets.push_back(std::string("TTBar"));
SumDatasets(oDirPlots, topDatasets, hnames, "SingleT+TTBar");
// sum DY contributions
std::vector<std::string> dyjets;
dyjets.push_back("DYJetsToLL");
dyjets.push_back("DYJetsToLL_PtZ-100");
dyjets.push_back("DYJetsToLL_EWK");
SumDatasets(oDirPlots,dyjets,hnames,"DYJets+EWK");
// sum single top datasets
std::vector<std::string> dibDatasets;
dibDatasets.push_back(std::string("WW"));
dibDatasets.push_back(std::string("WZ"));
dibDatasets.push_back(std::string("ZZ"));
dibDatasets.push_back(std::string("WG"));
SumDatasets(oDirPlots, dibDatasets, hnames, "DiBoson");
// sum QCD histograms
std::vector<std::string> qcdDatasets;
qcdDatasets.push_back(std::string("QCD_Pt30to50"));
qcdDatasets.push_back(std::string("QCD_Pt50to80"));
qcdDatasets.push_back(std::string("QCD_Pt80to120"));
qcdDatasets.push_back(std::string("QCD_Pt120to170"));
qcdDatasets.push_back(std::string("QCD_Pt170to300"));
qcdDatasets.push_back(std::string("QCD_Pt300to470"));
qcdDatasets.push_back(std::string("QCD_Pt470to600"));
qcdDatasets.push_back(std::string("QCD_Pt600to800"));
qcdDatasets.push_back(std::string("QCD_Pt800to1000"));
qcdDatasets.push_back(std::string("QCD_Pt1000to1400"));
qcdDatasets.push_back(std::string("QCD_Pt1400to1800"));
qcdDatasets.push_back(std::string("QCD_Pt1800"));
SumDatasets(oDirPlots, qcdDatasets, hnames, "QCD");
// make plots
std::cout << "Making plots" << std::endl;
StackPlot plots(oDirPlots);
plots.setLegPos(0.70,0.60,0.93,0.89);
plots.addDataset("DiBoson", kViolet-6, 0);
plots.addDataset("QCD", kGreen+3, 0);
plots.addDataset("DYJets+EWK", kPink-4,0);
plots.addDataset("SingleT+TTBar", kAzure-2, 0);
plots.addDataset("WNJets+EWK", kGreen-3, 0);
plots.addDataset("METABCD", kBlack, 1);
std::string chan[] = {"Mu", "El"};
for (int c = 0; c < 2; c++){
std::string label = (c) ? "e channel" : "#mu channel";
plots.setLabel(label.c_str());
std::string hname = "hW"+chan[c]+"_jet1Pt";
plots.draw(hname.c_str(), "Leading jet p_{T} [GeV]", "N_{events}", true,"RATIO");
hname = "hW"+chan[c]+"_jet2Pt";
plots.draw(hname.c_str(), "Sub-leading jet p_{T} [GeV]", "N_{events}",true,"RATIO");
hname = "hW"+chan[c]+"_jet1Eta";
if (c == 0) plots.setYMax(1E5);
plots.draw(hname.c_str(), "Leading jet #eta", "N_{events}",true,"RATIO");
// if (c == 0) plots.setYMax(-1);
if (c == 0) plots.setYMax(1E5); else plots.setYMax(3E4);
hname = "hW"+chan[c]+"_jet2Eta";
plots.draw(hname.c_str(), "Sub-leading jet #eta", "N_{events}",true,"RATIO");
// plots.setYMax(-1);
hname = "hW"+chan[c]+"_Mjj";
plots.draw(hname.c_str(), "M_{jj} [GeV]", "N_{events}",true,"RATIO");
hname = "hW"+chan[c]+"_dEtaJJ";
plots.draw(hname.c_str(), "#Delta #eta_{jj}", "N_{events}",true,"RATIO");
hname = "hW"+chan[c]+"_dPhiJJ";
if (c == 1) plots.setYMax(2E4);
plots.draw(hname.c_str(), "#Delta #phi_{jj}", "N_{events}",true,"RATIO");
// plots.setYMax(-1);
hname = "hW"+chan[c]+"_MET";
plots.draw(hname.c_str(), "E_{T}^{miss} [GeV]", "N_{events}",true,"RATIO");
hname = "hW"+chan[c]+"_WmT";
plots.draw(hname.c_str(), "M^{W}_{T} [GeV]", "N_{events}",true,"RATIO");
hname = "hW"+chan[c]+"_WpT";
plots.draw(hname.c_str(), "p^{W}_{T} [GeV]", "N_{events}",true,"RATIO");
}
// store histograms
ofile->cd();
hWMu_MCC_DPhi->Write("",TObject::kOverwrite);
hWMu_MCS_DPhi->Write("",TObject::kOverwrite);
hWMu_BGC_DPhi->Write("",TObject::kOverwrite);
// hWMu_BGS_DPhi->Write("",TObject::kOverwrite);
hWMu_DataC_DPhi->Write("",TObject::kOverwrite);
hWMu_R_DPhi->Write("",TObject::kOverwrite);
hWMu_R_DPhi_Syst->Write("",TObject::kOverwrite);
hWMu_EstC_DPhi->Write("",TObject::kOverwrite);
hWMu_EstC_DPhi_Syst->Write("",TObject::kOverwrite);
hWMu_EstS_DPhi->Write("",TObject::kOverwrite);
hWMu_EstS_DPhi_Syst->Write("",TObject::kOverwrite);
hWEl_MCC_DPhi->Write("",TObject::kOverwrite);
hWEl_MCS_DPhi->Write("",TObject::kOverwrite);
hWEl_BGC_DPhi->Write("",TObject::kOverwrite);
// hWEl_BGS_DPhi->Write("",TObject::kOverwrite);
hWEl_DataC_DPhi->Write("",TObject::kOverwrite);
hWEl_R_DPhi->Write("",TObject::kOverwrite);
hWEl_R_DPhi_Syst->Write("",TObject::kOverwrite);
hWEl_EstC_DPhi->Write("",TObject::kOverwrite);
hWEl_EstC_DPhi_Syst->Write("",TObject::kOverwrite);
hWEl_EstS_DPhi->Write("",TObject::kOverwrite);
hWEl_EstS_DPhi_Syst->Write("",TObject::kOverwrite);
// write out summed cutflow histograms
hDataWMu->Write("",TObject::kOverwrite);
hWLNuWMu->Write("",TObject::kOverwrite);
hQCDWMu->Write("",TObject::kOverwrite);
hDYWMu->Write("",TObject::kOverwrite);
hSingleTWMu->Write("",TObject::kOverwrite);
hDibosonWMu->Write("",TObject::kOverwrite);
hDataWEl->Write("",TObject::kOverwrite);
hWLNuWEl->Write("",TObject::kOverwrite);
hQCDWEl->Write("",TObject::kOverwrite);
hDYWEl->Write("",TObject::kOverwrite);
hSingleTWEl->Write("",TObject::kOverwrite);
hDibosonWEl->Write("",TObject::kOverwrite);
ofile->Close();
}
|
5292e353362913107965b6e636143561ac5c0795
|
a664d3114183d35c7375a7466f93408573bf37a6
|
/AdaEngine/utils/head/CommandQueue.h
|
29e504b85380a35e72a87b12be5fe9879e06e1a2
|
[
"MIT"
] |
permissive
|
CookieYang/AdaEngine
|
6dbfde834e2495b372446053116d0829a37f5867
|
e027a44113f58bd145880b42e1910487ebd5317f
|
refs/heads/master
| 2020-05-15T21:53:39.561618
| 2019-06-14T12:03:39
| 2019-06-14T12:03:39
| 182,510,930
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,643
|
h
|
CommandQueue.h
|
#pragma once
#include <thread>
#include <mutex>
#include <condition_variable>
#include <cassert>
#include "SimpleType.h"
#include "Engine.h"
#define COMMA(N) _COMMA_##N
#define _COMMA_0
#define _COMMA_1 ,
#define _COMMA_2 ,
#define _COMMA_3 ,
#define _COMMA_4 ,
#define _COMMA_5 ,
#define _COMMA_6 ,
#define _COMMA_7 ,
#define _COMMA_8 ,
#define _COMMA_9 ,
#define _COMMA_10 ,
#define COMMA_SEP_LIST(ITEM, LENGTH) _COMMA_SEP_LIST_##LENGTH(ITEM)
#define _COMMA_SEP_LIST_10(ITEM) \
_COMMA_SEP_LIST_9(ITEM) \
, ITEM(10)
#define _COMMA_SEP_LIST_9(ITEM) \
_COMMA_SEP_LIST_8(ITEM) \
, ITEM(9)
#define _COMMA_SEP_LIST_8(ITEM) \
_COMMA_SEP_LIST_7(ITEM) \
, ITEM(8)
#define _COMMA_SEP_LIST_7(ITEM) \
_COMMA_SEP_LIST_6(ITEM) \
, ITEM(7)
#define _COMMA_SEP_LIST_6(ITEM) \
_COMMA_SEP_LIST_5(ITEM) \
, ITEM(6)
#define _COMMA_SEP_LIST_5(ITEM) \
_COMMA_SEP_LIST_4(ITEM) \
, ITEM(5)
#define _COMMA_SEP_LIST_4(ITEM) \
_COMMA_SEP_LIST_3(ITEM) \
, ITEM(4)
#define _COMMA_SEP_LIST_3(ITEM) \
_COMMA_SEP_LIST_2(ITEM) \
, ITEM(3)
#define _COMMA_SEP_LIST_2(ITEM) \
_COMMA_SEP_LIST_1(ITEM) \
, ITEM(2)
#define _COMMA_SEP_LIST_1(ITEM) \
_COMMA_SEP_LIST_0(ITEM) \
ITEM(1)
#define _COMMA_SEP_LIST_0(ITEM)
#define SEMIC_SEP_LIST(ITEM, LENGTH) _SEMIC_SEP_LIST_##LENGTH(ITEM)
#define _SEMIC_SEP_LIST_10(ITEM) \
_SEMIC_SEP_LIST_9(ITEM);\
ITEM(10)
#define _SEMIC_SEP_LIST_9(ITEM) \
_SEMIC_SEP_LIST_8(ITEM); \
ITEM(9)
#define _SEMIC_SEP_LIST_8(ITEM) \
_SEMIC_SEP_LIST_7(ITEM); \
ITEM(8)
#define _SEMIC_SEP_LIST_7(ITEM) \
_SEMIC_SEP_LIST_6(ITEM); \
ITEM(7)
#define _SEMIC_SEP_LIST_6(ITEM) \
_SEMIC_SEP_LIST_5(ITEM); \
ITEM(6)
#define _SEMIC_SEP_LIST_5(ITEM) \
_SEMIC_SEP_LIST_4(ITEM); \
ITEM(5)
#define _SEMIC_SEP_LIST_4(ITEM) \
_SEMIC_SEP_LIST_3(ITEM); \
ITEM(4)
#define _SEMIC_SEP_LIST_3(ITEM) \
_SEMIC_SEP_LIST_2(ITEM); \
ITEM(3)
#define _SEMIC_SEP_LIST_2(ITEM) \
_SEMIC_SEP_LIST_1(ITEM); \
ITEM(2)
#define _SEMIC_SEP_LIST_1(ITEM) \
_SEMIC_SEP_LIST_0(ITEM) \
ITEM(1)
#define _SEMIC_SEP_LIST_0(ITEM)
#define SPACE_SEP_LIST(ITEM, LENGTH) _SPACE_SEP_LIST_##LENGTH(ITEM)
#define _SPACE_SEP_LIST_10(ITEM) \
_SPACE_SEP_LIST_9(ITEM) \
ITEM(10)
#define _SPACE_SEP_LIST_9(ITEM) \
_SPACE_SEP_LIST_8(ITEM) \
ITEM(9)
#define _SPACE_SEP_LIST_8(ITEM) \
_SPACE_SEP_LIST_7(ITEM) \
ITEM(8)
#define _SPACE_SEP_LIST_7(ITEM) \
_SPACE_SEP_LIST_6(ITEM) \
ITEM(7)
#define _SPACE_SEP_LIST_6(ITEM) \
_SPACE_SEP_LIST_5(ITEM) \
ITEM(6)
#define _SPACE_SEP_LIST_5(ITEM) \
_SPACE_SEP_LIST_4(ITEM) \
ITEM(5)
#define _SPACE_SEP_LIST_4(ITEM) \
_SPACE_SEP_LIST_3(ITEM) \
ITEM(4)
#define _SPACE_SEP_LIST_3(ITEM) \
_SPACE_SEP_LIST_2(ITEM) \
ITEM(3)
#define _SPACE_SEP_LIST_2(ITEM) \
_SPACE_SEP_LIST_1(ITEM) \
ITEM(2)
#define _SPACE_SEP_LIST_1(ITEM) \
_SPACE_SEP_LIST_0(ITEM) \
ITEM(1)
#define _SPACE_SEP_LIST_0(ITEM)
#define ARG(N) p##N
#define PARAM(N) P##N p##N
#define TYPE_PARAM(N) class P##N
#define PARAM_DECL(N) typename GetSimpleTypeT<P##N>::type_t p##N // I don't know the means and "#define PARAM_DECL(N) P##N p##N" also works
#define DECL_CMD(N)\
template <class T, class M COMMA(N) COMMA_SEP_LIST(TYPE_PARAM, N)> \
struct Command##N : public CommandBase { \
T* instance; \
M method; \
SEMIC_SEP_LIST(PARAM_DECL, N); \
virtual void call() { \
(instance->*method)(COMMA_SEP_LIST(ARG, N)); \
} \
};
#define DECL_CMD_RET(N) \
template <class T, class M, COMMA_SEP_LIST(TYPE_PARAM, N) COMMA(N) class R> \
struct CommandRet##N : public SyncCommand { \
R* ret; \
T* instance; \
M method; \
SEMIC_SEP_LIST(PARAM_DECL, N); \
virtual void call(){ \
*ret = (instance->*method)(COMMA_SEP_LIST(ARG, N)); \
} \
};
#define DECL_CMD_SYNC(N) \
template <class T, class M COMMA(N) COMMA_SEP_LIST(TYPE_PARAM, N)> \
struct CommandSync##N: public SyncCommand{ \
T* instance; \
M method; \
SEMIC_SEP_LIST(PARAM_DECL, N); \
virtual void call(){ \
(instance->*method)(COMMA_SEP_LIST(ARG, N)); \
} \
};
#define TYPE_ARG(N) P##N
#define CMD_TYPE(N) Command##N<T, M COMMA(N) COMMA_SEP_LIST(TYPE_ARG, N)>
#define CMD_ASSIGN_PARAM(N) cmd->p##N = p##N
#define DECL_PUSH(N) \
template <class T, class M COMMA(N) COMMA_SEP_LIST(TYPE_PARAM, N)> \
void push(T* p_instance, M p_method COMMA(N) COMMA_SEP_LIST(PARAM, N)){ \
CMD_TYPE(N)* cmd = allocateAndLock<CMD_TYPE(N)>(); \
cmd->instance = p_instance; \
cmd->method = p_method; \
SEMIC_SEP_LIST(CMD_ASSIGN_PARAM, N); \
unlock(); \
if(sync) sync->signal(); \
};
#define CMD_RET_TYPE(N) CommandRet##N<T, M, COMMA_SEP_LIST(TYPE_ARG, N) COMMA(N) R>
#define DECL_PUSH_AND_RET(N) \
template <class T, class M, COMMA_SEP_LIST(TYPE_PARAM, N) COMMA(N) class R> \
void pushAndRet(T* p_instance, M p_method, COMMA_SEP_LIST(PARAM, N) COMMA(N) R* r_ret){ \
SyncSemaphore *ss = allocSyncSem(); \
CMD_RET_TYPE(N)* cmd = allocateAndLock<CMD_RET_TYPE(N)>(); \
cmd->instance = p_instance; \
cmd->method = p_method; \
SEMIC_SEP_LIST(CMD_ASSIGN_PARAM, N); \
cmd->ret = r_ret; \
cmd->syncSem = ss; \
unlock(); \
if(sync) sync->signal(); \
ss->sem->wait(); \
ss->inUse = false; \
};
#define CMD_SYNC_TYPE(N) CommandSync##N<T, M COMMA(N) COMMA_SEP_LIST(TYPE_ARG, N)>
#define DECL_PUSH_AND_SYNC(N) \
template <class T, class M COMMA(N) COMMA_SEP_LIST(TYPE_PARAM, N)> \
void pushAndSync(T* p_instance, M p_method COMMA(N) COMMA_SEP_LIST(PARAM, N)){ \
SyncSemaphore* ss = allocSyncSem(); \
CMD_SYNC_TYPE(N)* cmd = allocateAndLock<CMD_SYNC_TYPE(N)>(); \
cmd->instance = p_instance; \
cmd->method = p_method; \
SEMIC_SEP_LIST(CMD_ASSIGN_PARAM, N); \
cmd->syncSem = ss; \
unlock(); \
if(sync) sync->signal(); \
ss->sem->wait(); \
ss->inUse = false; \
};
class Semaphore {
public:
Semaphore(int value) :count{ value } {};
void wait();
void signal();
private:
int count;
std::mutex innerMutex;
std::condition_variable conditionVariable;
};
class CommandQueue {
struct SyncSemaphore
{
Semaphore* sem;
bool inUse;
};
struct CommandBase
{
virtual void call() = 0;
virtual void signal() {};
virtual ~CommandBase() {};
};
struct SyncCommand: public CommandBase
{
SyncSemaphore* syncSem;
virtual void signal() override {
syncSem->sem->signal();
}
};
DECL_CMD(0)
SPACE_SEP_LIST(DECL_CMD, 10)
DECL_CMD_RET(0)
SPACE_SEP_LIST(DECL_CMD_RET, 10)
DECL_CMD_SYNC(0)
SPACE_SEP_LIST(DECL_CMD_SYNC, 10)
enum
{
COMMAND_MEM_SIZE_KB = 256,
COMMAND_MEN_SIZE = COMMAND_MEM_SIZE_KB * 1024,
SYNC_SEMAPHORES = 8
};
uint8_t* command_mem;
uint32_t readPtr;
uint32_t writePtr;
uint32_t deallocPtr;
SyncSemaphore sync_sems[SYNC_SEMAPHORES];
std::mutex* mutex;
Semaphore* sync;
template <class T>
T* allocate() {
uint32_t alloc_size = ((sizeof(T) + 8 - 1) & ~(8 - 1)) + 8;
tryagain:
if (writePtr < deallocPtr) {
if ((deallocPtr - writePtr) <= alloc_size) {
// no more space for new alloc
if (dealloc_one()) {
goto tryagain;
}
return NULL;
}
}
else if (writePtr >= deallocPtr) {
// muse larger than one alloc and end flag(uint32_t)
if ((COMMAND_MEN_SIZE - writePtr) < alloc_size + sizeof(uint32_t)) {
if (deallocPtr == 0) {
if (dealloc_one()) {
goto tryagain;
}
return NULL;
}
assert(((COMMAND_MEN_SIZE - writePtr) >= 8));
// there is some space at head, move write prt to head
uint32_t* p = (uint32_t*)&command_mem[writePtr];
*p = 0; // tell us where is the end (for read)[end flag]
writePtr = 0;
goto tryagain;
}
}
uint32_t size = (sizeof(T) + 8 - 1)&~(8 - 1);
uint32_t *p = (uint32_t*)&command_mem[writePtr];
*p = (size << 1) | 1;
writePtr += 8;
T* cmd = new(&command_mem[writePtr]) T;
writePtr += size;
return cmd;
}
template <class T>
T* allocateAndLock() {
lock();
T* ret;
while ((ret = allocate<T>()) == NULL) {
unlock();
// unlock and sleep a little while
waitForFlush(); // no space to push cmd , wait
// try again
lock();
}
return ret;
}
void lock();
void unlock();
void waitForFlush();
bool flushOne(bool bLock = true);
SyncSemaphore* allocSyncSem();
bool dealloc_one();
public:
/* NORMAL PUSH COMMANDS */
DECL_PUSH(0)
SPACE_SEP_LIST(DECL_PUSH, 10)
/* PUSH AND RET COMMANDS */
DECL_PUSH_AND_RET(0)
SPACE_SEP_LIST(DECL_PUSH_AND_RET, 10)
/* PUSH AND RET SYNC COMMANDS*/
DECL_PUSH_AND_SYNC(0)
SPACE_SEP_LIST(DECL_PUSH_AND_SYNC, 10)
void waitAndFlushOne() {
assert(sync != nullptr);
sync->wait(); // wait for cmd
flushOne();
}
void flushAll() {
lock();
while (flushOne(false)) {
}
unlock();
}
CommandQueue(bool p_sync);
~CommandQueue();
};
#undef ARG
#undef PARAM
#undef TYPE_PARAM
#undef PARAM_DECL
#undef DECL_CMD
#undef DECL_CMD_RET
#undef DECL_CMD_SYNC
#undef TYPE_ARG
#undef CMD_TYPE
#undef CMD_ASSIGN_PARAM
#undef DECL_PUSH
#undef CMD_RET_TYPE
#undef DECL_PUSH_AND_RET
#undef CMD_SYNC_TYPE
#undef DECL_CMD_SYNC
|
1fa7bef2ccdda954b59c75b632226109adbf9ad0
|
afe758963925562f3c0ee578f87e8d6255ad9507
|
/src/particle_filter.cpp
|
794b99db5b2f834473cc7845ba24bf668a406b33
|
[] |
no_license
|
sonofram/CarND-Kidnapped-Vehicle-Project
|
c62c01a618cf18d9df056ebca22421a676b01ccb
|
828043fa237eda7bc2921e35ec89d44444045cce
|
refs/heads/master
| 2021-01-02T09:17:46.242598
| 2017-08-06T22:50:15
| 2017-08-06T22:50:15
| 99,185,879
| 0
| 0
| null | 2017-08-03T03:19:54
| 2017-08-03T03:19:54
| null |
UTF-8
|
C++
| false
| false
| 11,941
|
cpp
|
particle_filter.cpp
|
/*
* particle_filter.cpp
*
* Created on: Dec 12, 2016
* Author: Tiffany Huang
*/
#include <random>
#include <algorithm>
#include <iostream>
#include <numeric>
#include <math.h>
#include <iostream>
#include <sstream>
#include <string>
#include <iterator>
#include "particle_filter.h"
using namespace std;
void ParticleFilter::init(double x, double y, double theta, double std[]) {
// TODO: Set the number of particles. Initialize all particles to first position (based on estimates of
// x, y, theta and their uncertainties from GPS) and all weights to 1.
// Add random Gaussian noise to each particle.
// NOTE: Consult particle_filter.h for more information about this method (and others in this file).
num_particles = 100;
double std_x, std_y, std_theta; // Standard deviations for x, y, and psi
// TODO: Set standard deviations for x, y, and psi.
std_x = std[0];
std_y = std[1];
std_theta=std[2];
// This line creates a normal (Gaussian) distribution for x.
normal_distribution<double> dist_x(x, std_x);
normal_distribution<double> dist_y(y, std_y);
normal_distribution<double> dist_theta(theta, std_theta);
for (int i = 0; i < num_particles; ++i) {
double sample_x, sample_y, sample_theta,sample_weight;
Particle sample_particle;
// TODO: Sample and from these normal distrubtions like this:
// sample_x = dist_x(gen);
// where "gen" is the random engine initialized earlier (line 18).
sample_x = dist_x(gen);
sample_y = dist_y(gen);
sample_theta = dist_theta(gen);
sample_particle.id = i+1;
sample_particle.x = sample_x;
sample_particle.y = sample_y;
sample_particle.theta = sample_theta;
sample_particle.weight = 1.0;
particles.push_back(sample_particle);
// Print your samples to the terminal.
//cout << "Sample " << i + 1 << " " << sample_x << " " << sample_y << " " << sample_theta << endl;
}
is_initialized = true;
}//end of init function
void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) {
// TODO: Add measurements to each particle and add random Gaussian noise.
// NOTE: When adding noise you may find std::normal_distribution and
// std::default_random_engine useful.
// http://en.cppreference.com/w/cpp/numeric/random/normal_distribution
// http://www.cplusplus.com/reference/random/default_random_engine/
double x_init,y_init,theta_init;
double x_pred,y_pred,theta_pred;
double std_x,std_y,std_theta;
std_x = std_pos[0];
std_y = std_pos[1];
std_theta = std_pos[2];
//normal_distribution<double> dist_x(0, std_x);
//normal_distribution<double> dist_y(0, std_y);
//normal_distribution<double> dist_theta(0, std_theta);
for (int i = 0; i < num_particles; ++i) {
x_init = particles[i].x;
y_init = particles[i].y;
theta_init =particles[i].theta;
if (fabs(yaw_rate) < 0.00001) {
x_pred = x_init + velocity * delta_t * cos(particles[i].theta);
y_pred = y_init + velocity * delta_t * sin(particles[i].theta);
theta_pred = theta_init;
}else{
x_pred = x_init + (velocity/yaw_rate)*(sin(theta_init + yaw_rate*delta_t)-sin(theta_init));
y_pred = y_init + (velocity/yaw_rate)*(cos(theta_init)- cos(theta_init + yaw_rate*delta_t));
theta_pred = theta_init + yaw_rate*delta_t;
}
normal_distribution<double> dist_x(x_pred, std_x);
normal_distribution<double> dist_y(y_pred, std_y);
normal_distribution<double> dist_theta(theta_pred, std_theta);
x_pred = dist_x(gen);
y_pred = dist_y(gen);
theta_pred = dist_theta(gen);
//x_pred = x_pred + dist_x(gen);
//y_pred = y_pred + dist_y(gen);
//theta_pred = theta_pred + dist_theta(gen);
particles[i].x = x_pred;
particles[i].y = y_pred;
particles[i].theta = theta_pred;
// Print your samples to the terminal.
//cout << "Init " << i + 1 << " " << x_init << " " << y_init << " " << theta_init << endl;
//cout << "Predicted " << i + 1 << " " << x_pred << " " << y_pred << " " << theta_pred << endl;
}
}
void ParticleFilter::dataAssociation(std::vector<LandmarkObs> predicted, std::vector<LandmarkObs>& observations){//,std::vector<LandmarkObs_MapId>& data_map ) {
// TODO: Find the predicted measurement that is closest
//to each observed measurement and assign the
// observed measurement to this particular landmark.
// NOTE: this method will NOT be called by the grading code.
//But you will probably find it useful to
// implement this method and use it as a helper during the
//updateWeights phase.
for (int i = 0; i < observations.size(); i++) {
LandmarkObs o = observations[i];
//cout << "dataAssociate i: " << o.id << std::endl;
// init minimum distance
double min_dist = INFINITY;
// storing min distance map_id
int map_id = -1;
for (int j = 0; j < predicted.size(); j++) {
LandmarkObs p = predicted[j];
//get distance
double cur_dist = dist(o.x, o.y, p.x, p.y);
// find the predicted landmark nearest the current observed landmark
if (cur_dist < min_dist) {
min_dist = cur_dist;
map_id = p.id;
}
} //end of j loop
//store results of map cordinate observations with closes map_id;
observations[i].id = map_id;
//LandmarkObs_MapId out_obs_map;
//out_obs_map.id = observations[i].id;
//out_obs_map.x = observations[i].x;
//out_obs_map.y = observations[i].y;
//out_obs_map.map_id = map_id;
//data_map.push_back(out_obs_map);
//cout << "data_map[i].id: "<< data_map[i].id << std::endl;
//cout << "data_map[i].map_id: "<< data_map[i].map_id << std::endl;
}//end of i loop
}
void ParticleFilter::updateWeights(double sensor_range, double std_landmark[],
std::vector<LandmarkObs> observations, Map map_landmarks) {
// TODO: Update the weights of each particle using a
// mult-variate Gaussian distribution. You can read
// more about this distribution here:
// https://en.wikipedia.org/wiki/Multivariate_normal_distribution
// NOTE:The observations are given in the VEHICLE'S coordinate system.
// Your particles are located according to the MAP'S coordinate system.
// You will need to transform between the two systems.
// Keep in mind that this transformation requires both rotation
// AND translation (but no scaling).
// The following is a good resource for the theory:
// https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm
// and the following is a good resource for the actual equation to
// implement (look at equation
// 3.33 http://planning.cs.uiuc.edu/node99.html
for (int i = 0; i < num_particles; i++) {
// get the particle x, y coordinates
double p_x = particles[i].x;
double p_y = particles[i].y;
double p_theta = particles[i].theta;
vector<LandmarkObs> predicted;
// for each map landmark...
for (int j = 0; j < map_landmarks.landmark_list.size(); j++) {
// get id and x,y coordinates
float map_lm_x = map_landmarks.landmark_list[j].x_f;
float map_lm_y = map_landmarks.landmark_list[j].y_f;
int map_lm_id = map_landmarks.landmark_list[j].id_i;
// only consider landmarks within sensor range of the particle
double dx = map_lm_x - p_x;
double dy = map_lm_y - p_y;
if(dx*dx + dy*dy <= sensor_range*sensor_range){
predicted.push_back(LandmarkObs{ map_lm_id, map_lm_x, map_lm_y });
}
}//end of predicted loop
std::vector<LandmarkObs> map_coord_observations;
for (int j = 0; j < observations.size(); j++) {
double x = cos(p_theta)*observations[j].x - sin(p_theta)*observations[j].y + p_x;
double y = sin(p_theta)*observations[j].x + cos(p_theta)*observations[j].y + p_y;
map_coord_observations.push_back(LandmarkObs{ observations[j].id, x, y });
}
//std::vector<LandmarkObs_MapId> data_map;
dataAssociation(predicted,map_coord_observations);//,data_map);
particles[i].weight = 1.0;
for (int j = 0; j < map_coord_observations.size(); j++) {
// placeholders for observation and associated prediction coordinates
double observed_x, observed_y;
double predicted_x, predicted_y;
observed_x = map_coord_observations[j].x;
observed_y = map_coord_observations[j].y;
int associated_prediction = map_coord_observations[j].id;//.map_id;
// get the x,y coordinates of the prediction associated
//with the current observation
for (int k = 0; k < predicted.size(); k++) {
if (predicted[k].id == associated_prediction) {
predicted_x = predicted[k].x;
predicted_y = predicted[k].y;
}
}
// calculate weight for this observation with multivariate Gaussian
double std_x = std_landmark[0];
double std_y = std_landmark[1];
double denom = ( 1/(2*M_PI*std_x*std_y));
double v_x = pow(predicted_x-observed_x,2)/(2*pow(std_x, 2));
double v_y = pow(predicted_y-observed_y,2)/(2*pow(std_y, 2));
double obs_w = denom * exp(-(v_x + v_y));
//cout << "obs_w: " << obs_w << std::endl;
//total weight for particle
particles[i].weight *= obs_w;
}
//cout << "i[" << i <<"] particle weight: " << particles[i].weight << std::endl;
}//end of particles loop
}
void ParticleFilter::resample() {
// TODO: Resample particles with replacement with probability proportional to their weight.
// NOTE: You may find std::discrete_distribution helpful here.
// http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution
vector<Particle> sample_particles;
// get max weight
vector<double> weights;
for (int i = 0; i < num_particles; i++) {
weights.push_back(particles[i].weight);
}
double max_weight = *max_element(weights.begin(), weights.end());
// generate random starting index for resampling wheel
std::discrete_distribution<int> dist(0, num_particles-1);
int index = dist(gen);
// uniform random distribution [0.0, max_weight)
double beta = 0.0;
for (int i = 0; i < num_particles; i++) {
beta += max_weight * 2.0;
while (beta > weights[index]) {
beta -= weights[index];
index = (index + 1) % num_particles;
}
sample_particles.push_back(particles[index]);
}
//Surviving particle will be passed on to next stage.
particles = sample_particles;
}
Particle ParticleFilter::SetAssociations(Particle particle, std::vector<int> associations, std::vector<double> sense_x, std::vector<double> sense_y)
{
//particle: the particle to assign each listed association, and association's (x,y)
//world coordinates mapping to
// associations: The landmark id that goes along with each listed association
// sense_x: the associations x mapping already converted to world coordinates
// sense_y: the associations y mapping already converted to world coordinates
//Clear the previous associations
particle.associations.clear();
particle.sense_x.clear();
particle.sense_y.clear();
particle.associations= associations;
particle.sense_x = sense_x;
particle.sense_y = sense_y;
return particle;
}
string ParticleFilter::getAssociations(Particle best)
{
vector<int> v = best.associations;
stringstream ss;
copy( v.begin(), v.end(), ostream_iterator<int>(ss, " "));
string s = ss.str();
s = s.substr(0, s.length()-1); // get rid of the trailing space
return s;
}
string ParticleFilter::getSenseX(Particle best)
{
vector<double> v = best.sense_x;
stringstream ss;
copy( v.begin(), v.end(), ostream_iterator<float>(ss, " "));
string s = ss.str();
s = s.substr(0, s.length()-1); // get rid of the trailing space
return s;
}
string ParticleFilter::getSenseY(Particle best)
{
vector<double> v = best.sense_y;
stringstream ss;
copy( v.begin(), v.end(), ostream_iterator<float>(ss, " "));
string s = ss.str();
s = s.substr(0, s.length()-1); // get rid of the trailing space
return s;
}
|
386378ec64308b586474b694391f1b00646dda2a
|
a52a5c89f7be672464695fddd59e70ca3cc0b5ff
|
/automationstate.cc
|
9f4faef7d58ef35c97b849e7876443addf3c8fec
|
[
"Apache-2.0"
] |
permissive
|
google/rct-automation
|
f41113e761c1e9860e67bc3e76dfcdd2fc436bb5
|
623362573fe030840183228acf722469c2cf9c64
|
refs/heads/master
| 2023-04-02T01:25:26.057062
| 2014-08-22T20:42:38
| 2014-08-22T20:42:38
| 23,001,786
| 21
| 13
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,339
|
cc
|
automationstate.cc
|
/*
* Copyright 2012-2014 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "automationstate.h"
#include "playlist.h"
#include <glog/logging.h>
#include <stdio.h>
#include <unistd.h>
#include <gflags/gflags.h>
#include "requirementengine.h"
#include "mplayersession.h"
DEFINE_bool(defaulthuman, false, "If true, when automation starts a human is in control.");
DEFINE_int32(bumpercutoff, 200, "If we have <= bumpercutoff seconds remaining after we have "
"exhausted our options with mainshow and override playlists, use the bumpers playlist "
"for passing time. Otherwise, a new mainshow will be selected.");
DEFINE_int32(sleepcutoff, 4, "If we have <= sleepcutoff seconds remaining after we have "
"exhausted our options with mainshow, override, and bumperlist [assuming sleepcutoff < bumpercutoff]"
" playlists, we can sleep for the remainder of time. This value => max amount of dead air "
"we'll intentionally generate.");
DECLARE_string(bumpers);
AutomationState *AutomationState::state_;
__thread MplayerSession *AutomationState::player_;
AutomationState::AutomationState(sqlite3* db, MplayerSession* player) :
db_(db),
re_(boost::shared_ptr<RequirementEngine>(new RequirementEngine(db))),
main_player_(player),
override_(FLAGS_defaulthuman),
override_playlist_(new Playlist(db)),
mainshow_(new Playlist(db)),
bumperlist_(new Playlist(db)) {
player_ = main_player_;
bumperlist_->NeverSave();
mainshow_->NeverSave();
override_playlist_->NeverSave();
SetMainshow();
state_ = this;
}
bool AutomationState::RunOnce() {
time_t deadline, gap;
// Attempt to yield to a human
if (ManualOverride()) {
// If we did anything in manual override, skip any requirements that happened
// before we returned.
re_->set_time(time(NULL));
}
if (bumperlist_->Size() == 0) {
ResetBumpers();
} else {
VLOG(5) << "Bumperlist of size " << bumperlist_->Size();
}
automation::Schedule next_requirements;
re_->FillNext(&next_requirements, &deadline, &gap);
VLOG(10) << "Deadline set to " << deadline << "after which we play " << next_requirements.DebugString();
if (time(NULL) >= deadline) {
re_->RunBlock(deadline, &next_requirements);
// We're doing this needlessly most of the time. We only need to do this if we
// played bumpers...
ResetBumpers();
return true;
}
PlayableItem next_track(db_);
GetMainshow()->PopWithTimelimit(deadline - time(NULL) + gap, &next_track);
MplayerSession &mp = *CHECK_NOTNULL(get_player());
if (next_track.data().has_filename()) {
// We found something in our mainshow_ that fits in the alloted time; play it.
mp.Play(next_track);
return true;
} else {
// OK, we weren't able to find something to play in our mainshow_.
PlayableItem next_bumper(db_);
if((deadline - time(NULL)) >= FLAGS_bumpercutoff && !GetMainshow()->Size()) {
// We have more than 200 seconds left before our requirement is due,
// or the mainshow_ is empty. Instead of falling back to bumpers,
// let's just get a new mainshow_.
LOG(ERROR) << "Abandoning mainshow (" << mainshow_->Name() << ") due to too much remaining time.";
SetMainshow();
return false;
} else {
bumperlist_->PopWithTimelimit(deadline - time(NULL) + gap, &next_bumper);
if (next_bumper.data().has_filename()) {
// We found a bumper to play. Play it.
mp.Play(next_bumper);
return true;
}
// We have no bumpers left. Let's check one time to see if we still
// have time to kill...
int time_left = deadline - time(NULL);
if(time_left <= 0) {
return true;
}
// Well, shoot, we do have time to kill. If it's under sleepcutoff,
// sleep it off
if(time_left <= FLAGS_sleepcutoff) {
sleep(time_left);
return true; // we "played" silence, so return true here
} else {
LOG(ERROR) << "Too much time left to sleep post-bumpers.";
return false;
}
}
}
CHECK(false); // Not reached
return false;
}
extern int shutdown_requested;
bool AutomationState::ManualOverride() {
bool did_anything = false;
PlaylistPtr op = AutomationState::get_state()->get_override_playlist();
while (AutomationState::get_state()->get_manual_override() || op->Size()) {
did_anything = true;
PlayableItem next(db_);
op->PopFront(&next);
if (next.data().has_filename()) {
AutomationState::get_state()->get_player()->Play(next);
} else {
// The value of override_ might have changed by now as we didn't hold
// a lock on this, which means we'll sleep (and possibly return
// true here, although typically we'd be doing that anyway if in this
// codepath) perhaps incorrectly here. I don't think this is a concern.
usleep(500);
if (shutdown_requested) {
exit(0);
}
}
}
return did_anything;
}
void AutomationState::SetMainshow() {
mainshow_->Fetch();
LOG(INFO) << "Randomly selected playlist \"" << mainshow_->Name() << "\" as mainshow.";
return;
}
void AutomationState::SetMainshow(std::string playlist) {
if (playlist.empty()) {
return SetMainshow();
}
if (mainshow_->FetchShuffled(playlist)) {
LOG(INFO) << "Selected \"" << mainshow_->Name() << "\" as mainshow, per request.";
} else {
LOG(WARNING) << "Requested playlist \"" << playlist << "\" not found.";
SetMainshow();
}
}
PlaylistPtr AutomationState::GetMainshow() {
return mainshow_;
}
void AutomationState::ResetBumpers() {
VLOG(5) << "Reloading bumpers";
if (FLAGS_bumpers.empty()) {
bumperlist_->FetchSuperlist(LLONG_MAX, 0);
} else {
Playlist::LockByName(db_, FLAGS_bumpers);
bumperlist_->Fetch(FLAGS_bumpers);
}
}
|
e490f1a2439d487122216de459ea1bcaa0a0c536
|
4ad7ee2b92bfc5d3a26b4318a62e4bdff5a80a01
|
/Chapter_3_Libraries_Interfaces/3_3_Strings/Exercise_3_8.cpp
|
ac0cabfe5a6aae922c9ab352a871f9f23c988531
|
[] |
no_license
|
oya163/DataStructure_Cpp
|
9669e1f018b2efaf701232cdcdcecf08bf9aab5a
|
3d4462751a245f57446a780e68b72ce0a7c22409
|
refs/heads/master
| 2021-01-13T03:10:47.293467
| 2017-03-22T15:27:39
| 2017-03-22T15:27:39
| 77,426,506
| 0
| 1
| null | null | null | null |
WINDOWS-1252
|
C++
| false
| false
| 988
|
cpp
|
Exercise_3_8.cpp
|
/*
Without using the string method substr, implement your own function
SubString(s, pos, len), which returns the substring of s, beginning at position
pos and including at most len characters. Make sure that your function correctly
applies the following rules:
a. If pos is negative, it is set to 0 so that it indicates the first character in the string.
b. If len is greater than s.length()– pos, it is set to strlen(s) – pos so that it
stops at last character.
c. If pos is greater than s.length() - 1, SubString returns the empty string.
*/
#include <iostream>
#include "HeaderFiles\strutils.h"
using namespace std;
int main() {
cout << "This program returns the substring as substr does" << endl;
string inputWord = "";
int pos = 0, len = 0;
cout << "Enter the word "; cin >> inputWord;
cout << "Enter the position to start splitting "; cin >> pos;
cout << "Enter the length of substring "; cin >> len;
cout << "SubString = " << SubString(inputWord, pos, len) << endl;
}
|
34a04347234ec6ff6b0f33ffd7a5f286d1b6252b
|
cb44f695e3f62b2b6d726c4da8f6b21adb444e2d
|
/IslandMainProject/Source/IslandMainProject/Public/Damageable.h
|
8519b0e7d0a7d4ccbd6bfc6a8b6b1b0edae4ff69
|
[] |
no_license
|
plutoshe/MeshTool
|
462597c1b2737228c1ff266f25e9150301ce67f6
|
cde50b1507ef7fc71b7082f4d9bee6a8ea643bea
|
refs/heads/master
| 2020-09-02T03:52:19.982797
| 2019-11-02T08:18:01
| 2019-11-02T08:21:24
| 219,126,348
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 664
|
h
|
Damageable.h
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "UObject/Interface.h"
#include "Damageable.generated.h"
// This class does not need to be modified.
UINTERFACE(BlueprintType)
class UDamageable : public UInterface
{
GENERATED_BODY()
};
/**
*
*/
class ISLANDMAINPROJECT_API IDamageable
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = Damageable)
void GetDamage(float damage);
UFUNCTION(BlueprintImplementableEvent, Category = Damageable)
void BPOnGetdamage();
void Die();
protected:
int m_currentHealth;
int m_maxHealth;
};
|
22a92b353b212847927f2bee177cc921db810ae0
|
63d41dba70f1c27bc128cecd390b4dcb80a7e0b5
|
/SimulationCore/sckeyboardcontrolledobj.h
|
80a266882bc6fc8f11e317462e816a5057edceae
|
[] |
no_license
|
null0000/MOV
|
8f77c8021cd3ffe5fa36671859a791bac34dfa25
|
7689362ed0a82c8d740c6bd1eb596ed8586e8fcd
|
refs/heads/master
| 2016-09-06T00:40:33.947153
| 2015-03-04T21:06:30
| 2015-03-04T21:06:30
| 14,441,879
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,097
|
h
|
sckeyboardcontrolledobj.h
|
#ifndef SCKEYBOARDCONTROLLEDOBJ_H
#define SCKEYBOARDCONTROLLEDOBJ_H
#include <QVector2D>
#include <QSharedPointer>
#include "simulationcore_ie.h"
#include "scKeyboardInput.h"
class scKeyboardState;
class scObjDesc;
class scMovementDesc;
class scWorldDesc;
class SIM_IE scKeyboardControlledObj {
public:
scKeyboardControlledObj(scKeyboardState_p keyboardObj, scKeyboardMap_ccp km);
scKeyboardControlledObj(scKeyboardState_p keyboardObj, scKeyboardMap_ccp km, QVector2D scaleFactor);
scMovementDesc getMovement(const scObjDesc &objDesc) const;
bool isUsing() const;
void updateStrategy(const scObjDesc &objDesc, const scWorldDesc &worldState) const;
private:
class keyboardListener;
friend class keyboardListener;
void registerKeyboardListener();
QVector2D deltaScale;
scKeyboardState_p ks;
scKeyboardMap_ccp kMap;
float udScale() const {return (ks->keyScale(kMap->Down()) - ks->keyScale(kMap->Up())); }
float lrScale() const {return (ks->keyScale(kMap->Right()) - ks->keyScale(kMap->Left()));}
};
#endif // SCKEYBOARDCONTROLLEDOBJ_H
|
f847ffa03637f2c47484d68b48d695b9cf44ca47
|
408d8348d7698a2d92bef73c68d277b6206e4225
|
/src/C4Network2IO.h
|
339012078ec58f1a404a6751ad4def183c791441
|
[
"ISC"
] |
permissive
|
legacyclonk/LegacyClonk
|
b8cad7fa8b3634c79a3c03b3f25e622d74bb2250
|
6281c878e42026b6b10d39819243af8f6673aabd
|
refs/heads/master
| 2023-08-17T03:27:30.561982
| 2023-08-13T16:37:08
| 2023-08-13T16:37:08
| 194,545,617
| 62
| 16
|
NOASSERTION
| 2022-10-29T15:31:12
| 2019-06-30T17:58:19
|
C++
|
UTF-8
|
C++
| false
| false
| 14,048
|
h
|
C4Network2IO.h
|
/*
* LegacyClonk
*
* Copyright (c) RedWolf Design
* Copyright (c) 2013-2018, The OpenClonk Team and contributors
* Copyright (c) 2017-2021, The LegacyClonk Team and contributors
*
* Distributed under the terms of the ISC license; see accompanying file
* "COPYING" for details.
*
* "Clonk" is a registered trademark of Matthes Bender, used with permission.
* See accompanying file "TRADEMARK" for details.
*
* To redistribute this file separately, substitute the full license texts
* for the above references.
*/
#pragma once
#include "C4NetIO.h"
#include "C4Client.h"
#include "C4InteractiveThread.h"
#include "C4PuncherPacket.h"
#include <atomic>
#include <cstdint>
class C4Network2IOConnection;
// enums & constants
enum C4Network2IOProtocol
{
P_UDP, P_TCP, P_NONE = -1
};
const int C4NetTimer = 500, // ms
C4NetPingFreq = 1000, // ms
C4NetStatisticsFreq = 1000, // ms
C4NetAcceptTimeout = 10, // s
C4NetPingTimeout = 30000; // ms
// client count
const int C4NetMaxClients = 256;
class C4Network2IO
: protected C4InteractiveThread::Callback,
protected C4NetIO::CBClass,
protected StdSchedulerProc
{
public:
C4Network2IO();
virtual ~C4Network2IO();
protected:
// main traffic net i/o classes
C4NetIO *pNetIO_TCP, *pNetIO_UDP;
// discovery net i/o
class C4Network2IODiscover *pNetIODiscover;
// reference server
class C4Network2RefServer *pRefServer;
// local client core
C4ClientCore LCCore;
CStdCSec LCCoreCSec;
// connection list
C4Network2IOConnection *pConnList;
CStdCSec ConnListCSec, BroadcastCSec;
// next connection ID to use
uint32_t iNextConnID;
// allow incoming connections?
bool fAllowConnect;
// connection acceptance
struct AutoAccept
{
C4ClientCore CCore;
AutoAccept *Next;
}
*pAutoAcceptList;
CStdCSec AutoAcceptCSec;
// make sure only one connection is established?
bool fExclusiveConn;
// timer & ping
unsigned long iLastExecute, iLastPing;
// statistics
unsigned long iLastStatistic;
int iTCPIRate, iTCPORate, iTCPBCRate,
iUDPIRate, iUDPORate, iUDPBCRate;
// punching
C4NetIO::addr_t PuncherAddrIPv4, PuncherAddrIPv6;
bool IsPuncherAddr(const C4NetIO::addr_t &addr) const;
public:
bool hasTCP() const { return !!pNetIO_TCP; }
bool hasUDP() const { return !!pNetIO_UDP; }
// initialization
bool Init(std::uint16_t iPortTCP, std::uint16_t iPortUDP, std::uint16_t iPortDiscovery = 0, std::uint16_t iPortRefServer = 0); // by main thread
void Clear(); // by main thread
void SetLocalCCore(const C4ClientCore &CCore); // by main thread
// i/o types
C4NetIO *MsgIO(); // by both
C4NetIO *DataIO(); // by both
// connections
bool Connect(const C4NetIO::addr_t &addr, C4Network2IOProtocol prot, const C4ClientCore &ccore, const char *password = nullptr); // by main thread
bool ConnectWithSocket(const C4NetIO::addr_t &addr, C4Network2IOProtocol eProt, const C4ClientCore &nCCore, std::unique_ptr<C4NetIOTCP::Socket> socket, const char *szPassword = nullptr); // by main thread
void SetAcceptMode(bool fAcceptAll); // by main thread
void SetExclusiveConnMode(bool fExclusiveConn); // by main thread
int getConnectionCount(); // by main thread
void ClearAutoAccept(); // by main thread
void AddAutoAccept(const C4ClientCore &CCore); // by main thread
void RemoveAutoAccept(const C4ClientCore &CCore); // by main thread
C4Network2IOConnection *GetMsgConnection(int iClientID); // by both (returns referenced connection!)
C4Network2IOConnection *GetDataConnection(int iClientID); // by both (returns referenced connection!)
// broadcasting
void BeginBroadcast(bool fSelectAll = false); // by both
void EndBroadcast(); // by both
bool Broadcast(const C4NetIOPacket &rPkt); // by both
// sending helpers
bool BroadcastMsg(const C4NetIOPacket &rPkt); // by both
// punch
bool InitPuncher(C4NetIO::addr_t puncherAddr); // by main thread
void SendPuncherPacket(const C4NetpuncherPacket &, C4NetIO::HostAddress::AddressFamily family);
void Punch(const C4NetIO::addr_t &); // Sends a ping packet
// stuff
C4NetIO *getNetIO(C4Network2IOProtocol eProt); // by both
const char *getNetIOName(C4NetIO *pNetIO);
C4Network2IOProtocol getNetIOProt(C4NetIO *pNetIO);
// statistics
int getProtIRate (C4Network2IOProtocol eProt) const { return eProt == P_TCP ? iTCPIRate : iUDPIRate; }
int getProtORate (C4Network2IOProtocol eProt) const { return eProt == P_TCP ? iTCPORate : iUDPORate; }
int getProtBCRate(C4Network2IOProtocol eProt) const { return eProt == P_TCP ? iTCPBCRate : iUDPBCRate; }
// reference
void SetReference(class C4Network2Reference *pReference);
bool IsReferenceNeeded();
protected:
// *** callbacks
// C4NetIO-Callbacks
virtual bool OnConn(const C4NetIO::addr_t &addr, const C4NetIO::addr_t &AddrConnect, const C4NetIO::addr_t *pOwnAddr, C4NetIO *pNetIO) override;
virtual void OnDisconn(const C4NetIO::addr_t &addr, C4NetIO *pNetIO, const char *szReason) override;
virtual void OnPacket(const C4NetIOPacket &rPacket, C4NetIO *pNetIO) override;
// C4NetIOMan
virtual void OnError(const char *strError, C4NetIO *pNetIO);
// StdSchedulerProc
virtual bool Execute(int iTimeout) override;
virtual int GetTimeout() override;
// Event callback by C4InteractiveThread
void OnThreadEvent(C4InteractiveEventType eEvent, const std::any &eventData) override; // by main thread
// connections list
void AddConnection(C4Network2IOConnection *pConn); // by both
void RemoveConnection(C4Network2IOConnection *pConn); // by both
C4Network2IOConnection *GetConnection(const C4NetIO::addr_t &addr, C4NetIO *pNetIO); // by both
C4Network2IOConnection *GetConnectionByConnAddr(const C4NetIO::addr_t &addr, C4NetIO *pNetIO); // by both
C4Network2IOConnection *GetConnectionByID(uint32_t iConnID); // by thread
// network events (signals to main thread)
struct NetEvPacketData;
// connection acceptance
bool doAutoAccept(const C4ClientCore &CCore, const C4Network2IOConnection &Conn);
// general packet handling (= forward in most cases)
bool HandlePacket(const C4NetIOPacket &rPacket, C4Network2IOConnection *pConn, bool fThread); // by both
void CallHandlers(int iHandlers, const class C4IDPacket *pPacket, C4Network2IOConnection *pConn, bool fThread); // by both
// packet handling (some are really handled here)
void HandlePacket(char cStatus, const C4PacketBase *pPacket, C4Network2IOConnection *pConn);
void HandleFwdReq(const class C4PacketFwd &rFwd, C4Network2IOConnection *pBy);
void HandlePuncherPacket(const C4NetIOPacket &packet);
// misc
bool Ping();
void CheckTimeout();
void GenerateStatistics(int iInterval);
void SendConnPackets();
};
enum C4Network2IOConnStatus
{
CS_Connect, // waiting for connection
CS_Connected, // waiting for Conn
CS_HalfAccepted, // got Conn (peer identified, client class created if neccessary)
CS_Accepted, // got ConnRe (peer did accept)
CS_Closed,
CS_ConnectFail, // got closed before HalfAccepted was reached
};
class C4Network2IOConnection // shared
{
friend class C4Network2IO;
public:
C4Network2IOConnection();
~C4Network2IOConnection();
protected:
// connection data
class C4NetIO *pNetClass;
C4Network2IOProtocol eProt;
C4NetIO::addr_t PeerAddr, ConnectAddr;
std::unique_ptr<C4NetIOTCP::Socket> tcpSimOpenSocket;
// status data
C4Network2IOConnStatus Status;
uint32_t iID, iRemoteID; // connection ID for this and the remote client
bool fAutoAccept; // auto accepted by thread?
bool fBroadcastTarget; // broadcast target?
time_t iTimestamp; // timestamp of last status change
int iPingTime; // ping
unsigned long iLastPing; // if > iLastPong, it's the first ping that hasn't been answered yet
unsigned long iLastPong; // last pong received
C4ClientCore CCore; // client core (>= CS_HalfAccepted)
CStdCSec CCoreCSec;
int iIRate, iORate; // input/output rates (by C4NetIO, in b/s)
int iPacketLoss; // lost packets (in the last seconds)
StdStrBuf Password; // password to use for connect
bool fConnSent; // initial connection packet send
bool fPostMortemSent; // post mortem send
// packet backlog
uint32_t iOutPacketCounter, iInPacketCounter;
struct PacketLogEntry
{
uint32_t Number;
C4NetIOPacket Pkt;
PacketLogEntry *Next;
};
PacketLogEntry *pPacketLog;
CStdCSec PacketLogCSec;
// list (C4Network2IO)
C4Network2IOConnection *pNext;
// reference counter
std::atomic<long> iRefCnt;
public:
C4NetIO *getNetClass() const { return pNetClass; }
C4Network2IOProtocol getProtocol() const { return eProt; }
const C4NetIO::addr_t &getPeerAddr() const { return PeerAddr.GetPort() ? PeerAddr : ConnectAddr; }
const C4NetIO::addr_t &getConnectAddr() const { return ConnectAddr; }
uint32_t getID() const { return iID; }
time_t getTimestamp() const { return iTimestamp; }
const C4ClientCore &getCCore() const { return CCore; }
int getClientID() const { return CCore.getID(); }
bool isHost() const { return CCore.isHost(); }
int getPingTime() const { return iPingTime; }
int getLag() const;
int getPacketLoss() const { return iPacketLoss; }
const char *getPassword() const { return Password.getData(); }
bool isConnSent() const { return fConnSent; }
uint32_t getInPacketCounter() const { return iInPacketCounter; }
uint32_t getOutPacketCounter() const { return iOutPacketCounter; }
bool isConnecting() const { return Status == CS_Connect; }
bool isOpen() const { return Status != CS_Connect && Status != CS_Closed && Status != CS_ConnectFail; }
bool isHalfAccepted() const { return Status == CS_HalfAccepted || Status == CS_Accepted; }
bool isAccepted() const { return Status == CS_Accepted; }
bool isClosed() const { return Status == CS_Closed || Status == CS_ConnectFail; }
bool isAutoAccepted() const { return fAutoAccept; }
bool isBroadcastTarget() const { return fBroadcastTarget; }
bool isFailed() const { return Status == CS_ConnectFail; }
protected:
// called by C4Network2IO only
void Set(C4NetIO *pnNetClass, C4Network2IOProtocol eProt, const C4NetIO::addr_t &nPeerAddr, const C4NetIO::addr_t &nConnectAddr, C4Network2IOConnStatus nStatus, const char *szPassword, uint32_t iID);
void SetSocket(std::unique_ptr<C4NetIOTCP::Socket> socket);
void SetRemoteID(uint32_t iRemoteID);
void SetPeerAddr(const C4NetIO::addr_t &nPeerAddr);
void OnPing();
void SetPingTime(int iPingTime);
void SetStatus(C4Network2IOConnStatus nStatus);
void SetAutoAccepted();
void OnPacketReceived(uint8_t iPacketType);
void ClearPacketLog(uint32_t iStartNumber = ~0);
public:
// status changing
void SetHalfAccepted() { SetStatus(CS_HalfAccepted); }
void SetAccepted() { SetStatus(CS_Accepted); }
void SetCCore(const C4ClientCore &nCCore);
void ResetAutoAccepted() { fAutoAccept = false; }
void SetConnSent() { fConnSent = true; }
// connection operations
bool Connect();
void Close();
bool Send(const C4NetIOPacket &rPkt);
void SetBroadcastTarget(bool fSet); // (only call after C4Network2IO::BeginBroadcast!)
// statistics
void DoStatistics(int iInterval, int *pIRateSum, int *pORateSum);
// reference counting
void AddRef(); void DelRef();
// post mortem
bool CreatePostMortem(class C4PacketPostMortem *pPkt);
};
// Packets
class C4PacketPing : public C4PacketBase
{
public:
C4PacketPing(uint32_t iPacketCounter = 0);
protected:
uint32_t iTime;
uint32_t iPacketCounter;
public:
uint32_t getTravelTime() const;
uint32_t getPacketCounter() const { return iPacketCounter; }
virtual void CompileFunc(StdCompiler *pComp) override;
};
class C4PacketConn : public C4PacketBase
{
public:
C4PacketConn();
C4PacketConn(const class C4ClientCore &nCCore, uint32_t iConnID, const char *szPassword = nullptr);
protected:
int32_t iVer;
uint32_t iConnID;
C4ClientCore CCore;
StdStrBuf Password;
public:
int32_t getVer() const { return iVer; }
uint32_t getConnID() const { return iConnID; }
const C4ClientCore &getCCore() const { return CCore; }
const char *getPassword() const { return Password.getData(); }
virtual void CompileFunc(StdCompiler *pComp) override;
};
class C4PacketConnRe : public C4PacketBase
{
public:
C4PacketConnRe();
C4PacketConnRe(bool fOK, bool fWrongPassword, const char *szMsg = nullptr);
protected:
bool fOK, fWrongPassword;
StdStrBuf szMsg;
public:
bool isOK() const { return fOK; }
bool isPasswordWrong() const { return fWrongPassword; }
const char *getMsg() const { return szMsg.getData(); }
virtual void CompileFunc(StdCompiler *pComp) override;
};
class C4PacketFwd : public C4PacketBase
{
public:
C4PacketFwd();
protected:
bool fNegativeList;
int32_t iClients[C4NetMaxClients];
int32_t iClientCnt;
C4NetIOPacket Data;
public:
const C4NetIOPacket &getData() const { return Data; }
int32_t getClient(int32_t i) const { return iClients[i]; }
int32_t getClientCnt() const { return iClientCnt; }
bool DoFwdTo(int32_t iClient) const;
void SetData(const C4NetIOPacket &Pkt);
void SetListType(bool fnNegativeList);
void AddClient(int32_t iClient);
virtual void CompileFunc(StdCompiler *pComp) override;
};
class C4PacketPostMortem : public C4PacketBase
{
public:
C4PacketPostMortem();
~C4PacketPostMortem();
private:
uint32_t iConnID;
uint32_t iPacketCounter; // last packet counter of dead connection
uint32_t iPacketCount;
struct PacketLink
{
C4NetIOPacket Pkt;
PacketLink *Next;
};
PacketLink *pPackets;
public:
const uint32_t getConnID() const { return iConnID; }
const uint32_t getPacketCount() const { return iPacketCount; }
void SetConnID(uint32_t inConnID) { iConnID = inConnID; }
const C4NetIOPacket *getPacket(uint32_t iNumber) const;
void SetPacketCounter(uint32_t iPacketCounter);
void Add(const C4NetIOPacket &rPkt);
virtual void CompileFunc(StdCompiler *pComp) override;
};
|
38cdf919c5c474032f3224214ec37ff7a7fa6d59
|
682fff6346995f264f5a7cb139227d1beb6c9192
|
/taller/server/GestorEscenario.cpp
|
e4096d98b91419e217b4be4a3e96d0467860399f
|
[] |
no_license
|
demianLopez/taller
|
7cb02200360d3f9ca9188bd41b3121ac63c0da76
|
5b38e6e7a3060870d9a7a1db649fc7ad2ec4b5ca
|
refs/heads/master
| 2020-05-17T11:22:53.761643
| 2014-12-09T23:21:59
| 2014-12-09T23:21:59
| 23,194,531
| 0
| 1
| null | 2014-10-29T23:32:13
| 2014-08-21T16:28:59
|
C++
|
UTF-8
|
C++
| false
| false
| 11,126
|
cpp
|
GestorEscenario.cpp
|
/*
* GestorEscenario.cpp
*
* Created on: 17/9/2014
* Author: FireHorse
*/
#include "GestorEscenario.h"
#include <Box2D/Box2D.h>
#include "polygons/PolygonFactory.h"
#include "../common/Logger.h"
GestorEscenario::GestorEscenario() {
}
GestorEscenario::~GestorEscenario() {
}
escenario* GestorEscenario::getEscenario() {
return &elEscenario;
}
void GestorEscenario::configurarEscenerio(int altopx, int anchopx, int altoun,
int anchoun, string imagen_fondo, int personajeX, int personajeY,
int cantidadJugadores, string nombreMapa, string sigNivel, int minJug
, double * posiciones) {
this->elEscenario.altopx = altopx;
this->elEscenario.anchopx = anchopx;
this->elEscenario.altoun = altoun;
this->elEscenario.anchoun = anchoun;
this->elEscenario.imagen_fondo = imagen_fondo;
this->elEscenario.personajeX = personajeX;
this->elEscenario.personajeY = personajeY;
this->elEscenario.cantidadJugadores = cantidadJugadores;
this->elEscenario.nombreMapa = nombreMapa;
this->elEscenario.sigNivel = sigNivel;
this->elEscenario.minJug = minJug;
this->elEscenario.pos = posiciones;
}
escenario GestorEscenario::datos() {
return elEscenario;
}
void GestorEscenario::agregarObjeto(string tipo, double posX, double posY,
string color, double rot, double masa, double escala, bool estado,
double alto, double ancho, int lados, double radio, double baseParal,
double angulo, double base_superior, double base_inferior) {
objeto nuevoObjeto;
nuevoObjeto.tipo = tipo;
nuevoObjeto.posX = posX;
nuevoObjeto.posY = posY;
nuevoObjeto.color = color;
nuevoObjeto.colRGB = this->obtenerRGB(color);
nuevoObjeto.rot = rot;
nuevoObjeto.masa = masa;
nuevoObjeto.escala = escala;
nuevoObjeto.estatico = estado;
nuevoObjeto.alto = alto;
nuevoObjeto.ancho = ancho;
nuevoObjeto.lados = lados;
nuevoObjeto.radio = radio;
nuevoObjeto.baseParal = baseParal;
nuevoObjeto.angulo = angulo;
nuevoObjeto.base_superior = base_superior;
nuevoObjeto.base_inferior = base_inferior;
this->objetos.push_back(nuevoObjeto);
}
void GestorEscenario::setActual(const char* actual){
this->escenarioActual = (char*)actual;
}
char * GestorEscenario::getActual(){
return escenarioActual ;
}
void GestorEscenario::agregarEnemigo(int tipo,double posx,double posy){
enemy nuevoEnemigo;
nuevoEnemigo.tipo = tipo;
nuevoEnemigo.posx = posx;
nuevoEnemigo.posy = posy;
this-> enemigos.push_back(nuevoEnemigo);
}
void GestorEscenario::imprimirXConsola() {
cout << "Descripcion escenario:" << endl;
cout << "altopx = " << elEscenario.altopx << endl;
cout << "anchopx = " << elEscenario.anchopx << endl;
cout << "altoun = " << elEscenario.altoun << endl;
cout << "anchoun = " << elEscenario.anchoun << endl;
cout << "Dir Image: " << elEscenario.imagen_fondo << endl;
cout << "Descripcion personaje:" << endl;
cout << "x = " << elEscenario.personajeX << endl;
cout << "y = " << elEscenario.personajeY << endl;
this->obtenerObjetos();
}
void GestorEscenario::obtenerObjetos() {
for (unsigned int i = 0; i < objetos.size(); i++) {
string tipo = objetos[i].tipo;
if (tipo == "rect") {
this->colocarRect(objetos[i]);
} else if (tipo == "poli") {
this->colocarPoli(objetos[i]);
} else if (tipo == "circ") {
this->colocarCirc(objetos[i]);
} else if (tipo == "paral") {
this->colocarParal(objetos[i]);
} else if (tipo == "trap") {
this->colocarTrap(objetos[i]);
} else {
return;
}
}
}
void imprimirRGB(objeto figura) {
cout << "Color en RGB:" << endl;
cout << "Rojo:" << figura.colRGB.red << endl;
cout << "Verde:" << figura.colRGB.green << endl;
cout << "Azul:" << figura.colRGB.blue << endl;
}
World * GestorEscenario::obtenerMundo() {
world = new World(new b2Vec2(0, -20));
world->setUnits(elEscenario.anchoun, elEscenario.altoun);
world->setMapData(new string(elEscenario.nombreMapa),
elEscenario.cantidadJugadores);
b2Vec2 SDLCharPos = b2Vec2(elEscenario.personajeX, elEscenario.personajeY);
world->setNextLevelName((char *)elEscenario.sigNivel.c_str());
world->setCurrentLevelName(escenarioActual);
//Water HARDCODEADO
//char mapWithWater[] = "Maps/nivel2.json";
if(escenarioActual[10] == '2'){
world->setWater();
}
world->setMinPlayers(elEscenario.minJug);
world->addPlayerPos(elEscenario.pos[0], elEscenario.pos[1]);
world->addPlayerPos(elEscenario.pos[2], elEscenario.pos[3]);
world->addPlayerPos(elEscenario.pos[4], elEscenario.pos[5]);
world->addPlayerPos(elEscenario.pos[6], elEscenario.pos[7]);
delete[] elEscenario.pos;
for(auto enemigo : enemigos){
Enemigo * enemy = new Enemigo();
enemy->colocar(enemigo.tipo,enemigo.posx,enemigo.posy);
world->addEnemy(enemy);
}
for (auto objeto : objetos) {
string tipo = objeto.tipo;
Polygon * nuevoPoligono;
if (tipo == "rect") {
nuevoPoligono = this->colocarRect(objeto);
} else if (tipo == "poli") {
nuevoPoligono = this->colocarPoli(objeto);
} else if (tipo == "circ") {
nuevoPoligono = this->colocarCirc(objeto);
} else if (tipo == "paral") {
nuevoPoligono = this->colocarParal(objeto);
} else if (tipo == "trap") {
nuevoPoligono = this->colocarTrap(objeto);
}
bool todoOk = true;
for (auto * alreadyAddedPolygon : world->getPolygonList()) {
b2Shape * shapeNew =
(b2Shape*) nuevoPoligono->getBody()->GetFixtureList()->GetShape();
b2Shape * shapeAlreadyAdded =
(b2Shape*) alreadyAddedPolygon->getBody()->GetFixtureList()->GetShape();
if (!bothStatic(alreadyAddedPolygon, nuevoPoligono)
&& b2TestOverlap(shapeNew, 0, shapeAlreadyAdded, 0,
nuevoPoligono->getBody()->GetTransform(),
alreadyAddedPolygon->getBody()->GetTransform())) {
todoOk = false;
}
}
if (nuevoPoligono && todoOk) {
world->addPolygon(nuevoPoligono);
} else {
world->getBox2DWorld()->DestroyBody(nuevoPoligono->getBody());
delete nuevoPoligono;
Logger::customLog("GestorEscenario.cpp", Logger::WARNING,
"Objetos superpuestos, se elimina el segundo");
}
}
return world;
}
Polygon * GestorEscenario::colocarRect(objeto figura) {
if (figura.estatico) {
return PolygonFactory::get_static_rectangle(figura.alto, figura.ancho,
figura.posX, figura.posY, figura.masa, figura.rot / 57, world);
}
return PolygonFactory::get_dynamic_rectangle(figura.alto, figura.ancho,
figura.posX, figura.posY, figura.masa, figura.rot / 57, world);
/*cout << "\n Datos Rectangulo" << endl;
cout <<"PosX: " << figura.posX << endl;
cout <<"PosY: " << figura.posY << endl;
cout <<"Color: " << figura.color << endl;
imprimirRGB(figura);
cout <<"Rotacion: " << figura.rot << endl;
cout <<"Masa: " << figura.masa << endl;
cout <<"Escala: " << figura.escala << endl;
cout <<"Estatico: " << figura.estatico << endl;
cout <<"Alto: " << figura.alto << endl;
cout <<"Ancho: " << figura.ancho << endl;
*/
}
Polygon * GestorEscenario::colocarPoli(objeto figura) {
if (figura.estatico) {
return PolygonFactory::get_static_regular_polygon(figura.lados,
figura.escala, figura.posX, figura.posY, figura.masa,
figura.rot / 57, world);
}
return PolygonFactory::get_dynamic_regular_polygon(figura.lados,
figura.escala, figura.posX, figura.posY, figura.masa,
figura.rot / 57, world);
/*
cout << "\n Datos Poligono" << endl;
cout <<"PosX: " << figura.posX << endl;
cout <<"PosY: " << figura.posY << endl;
cout <<"Color: " << figura.color << endl;
imprimirRGB(figura);
cout <<"Rotacion: " << figura.rot << endl;
cout <<"Masa: " << figura.masa << endl;
cout <<"Escala: " << figura.escala << endl;
cout <<"Estatico: " << figura.estatico << endl;
cout << "Lados: " << figura.lados << endl;
*/
}
Polygon * GestorEscenario::colocarCirc(objeto figura) {
if (figura.estatico) {
return PolygonFactory::get_static_circle(figura.radio * 2, figura.posX,
figura.posY, figura.masa, figura.rot / 57, world);
}
return PolygonFactory::get_dynamic_circle(figura.radio * 2, figura.posX,
figura.posY, figura.masa, figura.rot / 57, world);
/*
cout << "\n Datos Circulo" << endl;
cout <<"PosX: " << figura.posX << endl;
cout <<"PosY: " << figura.posY << endl;
cout <<"Color: " << figura.color << endl;
imprimirRGB(figura);
cout <<"Rotacion: " << figura.rot << endl;
cout <<"Masa: " << figura.masa << endl;
cout <<"Escala: " << figura.escala << endl;
cout <<"Estatico: " << figura.estatico << endl;
cout << "Radio: " << figura.radio << endl;
*/
}
Polygon * GestorEscenario::colocarParal(objeto figura) {
if (figura.estatico) {
return PolygonFactory::get_static_paralelogram(figura.baseParal,
figura.alto, figura.angulo, figura.posX, figura.posY,
figura.masa, figura.rot / 57, world);
}
return PolygonFactory::get_dynamic_paralelogram(figura.baseParal,
figura.alto, figura.angulo, figura.posX, figura.posY, figura.masa,
figura.rot / 57, world);
/*
cout << "\n Datos Paralelogramo" << endl;
cout <<"PosX: " << figura.posX << endl;
cout <<"PosY: " << figura.posY << endl;
cout <<"Color: " << figura.color << endl;
imprimirRGB(figura);
cout <<"Rotacion: " << figura.rot << endl;
cout <<"Masa: " << figura.masa << endl;
cout <<"Escala: " << figura.escala << endl;
cout <<"Estatico: " << figura.estatico << endl;
cout << "Base: " << figura.baseParal << endl;
cout << "Angulo: " << figura.angulo << endl;
cout << "Alto: " << figura.alto << endl;
*/
}
Polygon * GestorEscenario::colocarTrap(objeto figura) {
if (figura.estatico) {
return PolygonFactory::get_static_trapezoid(figura.alto,
figura.base_inferior, figura.base_superior, figura.angulo,
figura.posX, figura.posY, figura.masa, figura.rot / 57, world);
}
return PolygonFactory::get_dynamic_trapezoid(figura.alto,
figura.base_inferior, figura.base_superior, figura.angulo,
figura.posX, figura.posY, figura.masa, figura.rot / 57, world);
/*
cout << "\n Datos Trapecio" << endl;
cout <<"PosX: " << figura.posX << endl;
cout <<"PosY: " << figura.posY << endl;
cout <<"Color: " << figura.color << endl;
imprimirRGB(figura);
cout <<"Rotacion: " << figura.rot << endl;
cout <<"Masa: " << figura.masa << endl;
cout <<"Escala: " << figura.escala << endl;
cout <<"Estatico: " << figura.estatico << endl;
cout << "Base Mayor: " << figura.base_superior << endl;
cout << "Base Menor: " << figura.base_inferior << endl;
cout << "Angulo: " << figura.angulo << endl;
*/
}
int GestorEscenario::calcularColor(char col1, char col2) {
int color = 0;
if ((int(col2) >= 48) && (int(col2) <= 57))
color = color + (int(col2) - 48);
else
color = color + (int(col2) - 55);
if ((int(col1) >= 48) && (int(col1) <= 57))
color = color + ((int(col1) - 48) * 16);
else
color = color + ((int(col1) - 55) * 16);
return color;
}
rgb GestorEscenario::obtenerRGB(string color) {
rgb colores;
colores.red = this->calcularColor(color[1], color[2]);
colores.green = this->calcularColor(color[3], color[4]);
colores.blue = this->calcularColor(color[5], color[6]);
return colores;
}
bool GestorEscenario::bothStatic(Polygon * aPolygon, Polygon * anotherPolygon) {
return aPolygon->isStatic() && anotherPolygon->isStatic();
}
|
14832862673ac26a0de7441ff0df14f415a11c03
|
cb42f051ad3183f4e0d6408deeb7bda6bc507ff5
|
/ex07_simple_line_follower/nr.inc
|
64b645553852e1e7b5cfde79cf7124faaf5f2948
|
[] |
no_license
|
elecrom/el_mega16_sample_codes
|
5d6f0e4d14160c5742bddbafd8c8cee544280298
|
2bcf524ae0ce36259957a8bb1972095301d01a34
|
refs/heads/master
| 2021-01-12T07:33:44.137510
| 2016-12-20T17:23:36
| 2016-12-20T17:23:36
| 76,977,462
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 79
|
inc
|
nr.inc
|
.DEF _adcch=R4
.DEF _tmp=R5
.DEF _dir=R6
__GLOBAL_INI_TBL:
.DW 0
_0x24:
|
95a9b03e6cc5d14e433eaa4863f1ebdeebb7c4e3
|
087f98db3fe1ee6bdc5625f3d1888dfb5c0070f5
|
/Q_learnig_by_STVIAN004/Q_learning/CDiscCollisionObject.cpp
|
9359e9dee77e3da91b1752477653bd832b56545c
|
[] |
no_license
|
IanStevens1/Q-Learning
|
56bb5bbaa21df9476b247d8238e7c9711a842cb7
|
f0082677e8236a6ac0e6db14a48a53d1baf52e02
|
refs/heads/master
| 2021-01-23T05:45:27.041872
| 2014-10-01T17:38:57
| 2014-10-01T17:38:57
| 24,688,225
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 648
|
cpp
|
CDiscCollisionObject.cpp
|
#include "CDiscCollisionObject.h"
#include "SVector2D.h"
CDiscCollisionObject::CDiscCollisionObject(): CCollisionObject(ObjectType::Mine)
{
m_vPosition = new SVector2D<int>(0,0);
}
CDiscCollisionObject::CDiscCollisionObject(ObjectType objectType, SVector2D<int> position):CCollisionObject(objectType)
{
m_vPosition = new SVector2D<int>(position.x,position.y);
}
CDiscCollisionObject::~CDiscCollisionObject()
{
delete m_vPosition;
}
void CDiscCollisionObject::setPosition(SVector2D<int> position)
{
m_vPosition->x = position.x;
m_vPosition->y = position.y;
}
SVector2D<int> CDiscCollisionObject::getPosition() const
{
return *m_vPosition;
}
|
77669816909c32675ffc4725999af94eb7207ed6
|
880557ea1db4b385e7dca82afb82818e7e47f5dd
|
/src/diagnostic/loggerDevice.h
|
d3a522bf89f393740c9f868c5c6afbf3d7c72faa
|
[] |
no_license
|
fscur/phi
|
45db0903463add36108be948381511a7f74f4c8d
|
4b147bbd589b0bec89f59fa3ed843b927b6b0004
|
refs/heads/master
| 2021-01-20T11:44:18.781654
| 2017-02-22T13:53:22
| 2017-02-22T13:53:22
| 82,651,381
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 314
|
h
|
loggerDevice.h
|
#pragma once
#include <phi.h>
namespace phi
{
class loggerDevice
{
public:
loggerDevice() {};
virtual ~loggerDevice() {};
virtual void logError(string message) = 0;
virtual void logWarning(string message) = 0;
virtual void logInfo(string message) = 0;
};
}
|
f423d5f00aad43a8f65dac0611c8659322dc8dcc
|
0379dd91363f38d8637ff242c1ce5d3595c9b549
|
/windows_10_shared_source_kit/windows_10_shared_source_kit/unknown_version/Source/Audio/Test/uaatest/HdHitPlugin.cpp
|
4265835385c5cfcaf53670ddd63af56f85de49aa
|
[] |
no_license
|
zhanglGitHub/windows_10_shared_source_kit
|
14f25e6fff898733892d0b5cc23b2b88b04458d9
|
6784379b0023185027894efe6b97afee24ca77e0
|
refs/heads/master
| 2023-03-21T05:04:08.653859
| 2020-09-28T16:44:54
| 2020-09-28T16:44:54
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,221
|
cpp
|
HdHitPlugin.cpp
|
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
*/
#include <nt.h>
#include <ntrtl.h>
#include <nturtl.h>
#include <windows.h>
#include <tchar.h>
#include <atlstr.h>
#include <shell98.h>
#include <module98.h>
#include <dvmodule.h>
#include <cfgmgr32.h>
#include <setupapi.h>
#include <hitframework.h>
#define USERMODE // or azcodec.h includes wdm.h (kernel mode version of windows.h)
#include <azcodec.h>
#include <privioct.h>
#include <controller-interface.h>
#include "install.h"
#include "uaatest.h"
#include "HdRegTest.h"
#include "HdHitLog.h"
#include "HdHitPlugin.h"
#include "hdaudiomemoryspace.h"
#include "controller.h"
extern Hit::ILog *Log;
HRESULT ResetController(HANDLE hController, double* pdEnterResetTime, double* pdExitResetTime)
{
DWORD BytesReturned;
HRESULT hResult = STATUS_SUCCESS;
double times[] = { 0.0, 0.0 };
BOOL b = DeviceIoControl(hController, IOCTL_HDCNTTEST_RESET, NULL , 0, times, sizeof(times), &BytesReturned,0);//HdCntRead.pRWBuffer, HdCntRead.RWBytes, &BytesReturned, 0);
if (!b) {
hResult = GetLastError();
} else {
*pdEnterResetTime = times[0];
*pdExitResetTime = times[1];
}
return hResult;
}
HRESULT TestRead(HANDLE hController, HDCNT_ReadWrite& HdCntRead)
{
DWORD BytesReturned;
HRESULT hResult = STATUS_SUCCESS;
BOOL b = DeviceIoControl(hController, IOCTL_HDCNTTEST_READ, &HdCntRead, sizeof (HDCNT_ReadWrite), HdCntRead.RWBuffer, HdCntRead.RWBytes, &BytesReturned,0);//HdCntRead.pRWBuffer, HdCntRead.RWBytes, &BytesReturned, 0);
if (!b) {
hResult = GetLastError();
}
return hResult;
}
HRESULT TestWrite(HANDLE hController, HDCNT_ReadWrite HdCntWrite)
{
DWORD BytesReturned;
HRESULT hResult = STATUS_SUCCESS;
BOOL b = DeviceIoControl(hController, IOCTL_HDCNTTEST_WRITE, &HdCntWrite, sizeof (HDCNT_ReadWrite), NULL, 0, &BytesReturned, 0);
if (!b) {
hResult = GetLastError();
}
return hResult;
}
namespace Hit {
HRESULT HdCntRead (
IN ULONG Offset,
IN ULONG Length,
__bcount(Length) IN PVOID Buffer,
IN OUT PVOID Context
)
{
HDCNT_ReadWrite HdRead;
HRESULT hResult;
HdRead.RWBytes = Length;
HdRead.RWOffset = Offset;
// HdRead.RWBuffer = Buffer;
HANDLE hController = *(HANDLE*)Context;
hResult = TestRead(hController , HdRead);
memcpy_s(Buffer, Length, (PVOID)HdRead.RWBuffer, HdRead.RWBytes);
return hResult;
}
HRESULT HdCntWrite (
IN ULONG Offset,
IN ULONG Length,
__bcount(Length) IN PVOID Buffer,
IN OUT PVOID Context
)
{
HDCNT_ReadWrite HdWrite;
HdWrite.RWBytes = Length;
HdWrite.RWOffset = Offset;
memcpy_s( HdWrite.RWBuffer, sizeof(HdWrite.RWBuffer), Buffer, Length);
HANDLE hController = *(HANDLE*)Context;
return TestWrite(hController , HdWrite);
}
}
|
7ff48e263d3cec9140b1bc247d365606621308ea
|
924763dfaa833a898a120c411a5ed3b2d9b2f8c7
|
/compiled/cpp_stl_11/debug_0.cpp
|
74c5434dda10188c2c94913157a870c81af151a3
|
[
"MIT"
] |
permissive
|
kaitai-io/ci_targets
|
31257dfdf77044d32a659ab7b8ec7da083f12d25
|
2f06d144c5789ae909225583df32e2ceb41483a3
|
refs/heads/master
| 2023-08-25T02:27:30.233334
| 2023-08-04T18:54:45
| 2023-08-04T18:54:45
| 87,530,818
| 4
| 6
|
MIT
| 2023-07-28T22:12:01
| 2017-04-07T09:44:44
|
C++
|
UTF-8
|
C++
| false
| false
| 740
|
cpp
|
debug_0.cpp
|
// This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild
#include "debug_0.h"
debug_0_t::debug_0_t(kaitai::kstream* p__io, kaitai::kstruct* p__parent, debug_0_t* p__root) : kaitai::kstruct(p__io) {
m__parent = p__parent;
m__root = this;
m_array_of_ints = nullptr;
}
void debug_0_t::_read() {
m_one = m__io->read_u1();
m_array_of_ints = std::unique_ptr<std::vector<uint8_t>>(new std::vector<uint8_t>());
const int l_array_of_ints = 3;
for (int i = 0; i < l_array_of_ints; i++) {
m_array_of_ints->push_back(std::move(m__io->read_u1()));
}
m__unnamed2 = m__io->read_u1();
}
debug_0_t::~debug_0_t() {
_clean_up();
}
void debug_0_t::_clean_up() {
}
|
e958e9a27847766734e058abe5b5af2cbe6d8af4
|
b0177018417e035e34e6eaf7a3d4eaa2e93e2308
|
/ext/ml4r/MachineLearning/GBM/GBMEstimator.h
|
90aeee89aa1be376738565443d770100a801f131
|
[] |
no_license
|
vlc/ml4r
|
5fb91be3e6fc89052d977a3947d439f8dbe534aa
|
0b95465ff215cf70ff82b4ee69adb7bf5b531c27
|
refs/heads/master
| 2020-12-25T00:28:18.094054
| 2014-03-30T08:03:34
| 2014-03-30T08:03:34
| 4,769,047
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,088
|
h
|
GBMEstimator.h
|
#ifndef GBMEstimator_h__
#define GBMEstimator_h__
#include "MachineLearning/DecisionTree/FeatureInteraction.h"
#include "MachineLearning/MLEstimator.h"
#include <boost/shared_ptr.hpp>
#include <vector>
#include <map>
#include <set>
#include <utility>
using std::pair;
using std::set;
using std::map;
using std::vector;
using boost::shared_ptr;
class GBMParameters;
class GBMOutput;
class DecisionTreeExperiment;
class DecisionTreeNode;
class SplitDefinition;
class MLData;
class GBMCalculator;
class MLExperiment;
class GBMEstimator : public MLEstimator
{
public:
GBMEstimator(MLData* data, vector<shared_ptr<MLExperiment> > experiments, shared_ptr<GBMParameters> parameters);
~GBMEstimator();
shared_ptr<MLOutput> estimate();
void estimateMore(int numTrees);
vector<FeatureInteraction> findInteractions(int howMany);
protected:
void initializeEstimator();
void performIteration();
void constructFeatureIndices();
void initialiseGBMExperimentData();
void populateInitialF();
void updateZ(vector<shared_ptr<DecisionTreeExperiment> >& experiments);
void updatePredictions(vector<shared_ptr<DecisionTreeExperiment> >& experiments);
void sortTrainingExperiments();
void constructDecisionTree(vector<shared_ptr<DecisionTreeExperiment> >& experiments);
void constructGenerousDecisionTree(vector<shared_ptr<DecisionTreeExperiment> >& experiments, int rfToLevel);
// map<int, vector<shared_ptr<DecisionTreeExperiment> > > partitionSortedExperiments(shared_ptr<SplitDefinition> splitDefinition, Partition partition);
map<int, vector<shared_ptr<DecisionTreeExperiment> > > bagSortedExperiments(vector<shared_ptr<DecisionTreeExperiment> >& baggedExperiments);
vector<int> getRandomFeatureList();
void calculateFIncrementPerDecisionTreeNode();
void applyFIncrementToInBagExperiments();
pair<vector<shared_ptr<DecisionTreeExperiment> >, vector<shared_ptr<DecisionTreeExperiment> > > bagExperiments();
void applyFIncrementToExperiments(vector<shared_ptr<DecisionTreeExperiment> >& outOfBagExperiments);
void reportDeviance(vector<shared_ptr<DecisionTreeExperiment> >& experiments);
void deleteRedundantData();
shared_ptr<GBMOutput> m_output;
vector<shared_ptr<DecisionTreeExperiment> > m_decisionTreeExperiments;
shared_ptr<GBMParameters> m_parameters;
vector<int> m_featureIndices;
shared_ptr<DecisionTreeNode> m_decisionTreeHead;
set<shared_ptr<DecisionTreeNode> > m_terminalNodes;
map<shared_ptr<DecisionTreeNode>, double> m_FIncrements;
shared_ptr<GBMCalculator> m_gbmCalculator;
bool m_missingValueDefined;
double m_missingValue;
private:
};
#endif // GBMEstimator_h__
|
bc0c7d3f9b6fc1e8ba3ba959eb002f28933c8144
|
d89004697363eb29005e74021bdf00b13e6cce4c
|
/snake.h
|
d81f84b0a1b76fc21f6b698b82dead948cfda19e
|
[] |
no_license
|
Aisson/Snake
|
97ab494fe21db70dea7a58837b8fde2b2f332d9f
|
3beab2a8f90f2b8db78beda32eda65f0f91b7aa0
|
refs/heads/master
| 2023-03-16T23:40:00.607148
| 2021-03-01T08:46:03
| 2021-03-01T08:46:03
| 343,343,685
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 651
|
h
|
snake.h
|
#pragma once
#include <conio.h>
#include <vector>
#include "unit.h"
#include"food.h"
#include"control.h"
typedef enum Dir
{
KUP,KDOWN,KLEFT,KRIGHT,STOP
};
class snake
{
public:
int m_HeadX;
int m_HeadY;
int m_Len;
int m_Speed;
static int speed;
//static int score;
//static int level;
int m_iScore;
int m_iLevel;
Dir m_Dir;
vector<unit> m_Body;
public:
snake(int x=40,int y=10,int len=8,int speed=250, Dir dir= KRIGHT, char pic='#');
~snake();
void showSnake();
void eraseSnake();
void listen_key_borad();
void move();
bool eatFood(food& Food);
bool ifDeath();
bool ifDeathself();
void changeInfo();
bool checkLevel();
};
|
fb4c79638320f0ac8c77784248080187678fb2c8
|
f00e82e62d21b96ec8fc9938159eb5e57c98c301
|
/v2.5/GEAR Studio/Project.cpp
|
ecfd0334ef73fa70ef9436177c03a39c9b567292
|
[] |
no_license
|
andyreimann/gear
|
b1aca01ccd5fb9ecda8cd63190b8d9c87e142a72
|
d58ce2ea4e284b9f6e5c82c88742f2cfdbfb89d9
|
refs/heads/master
| 2020-05-18T06:46:03.385546
| 2015-02-02T23:04:06
| 2015-02-02T23:04:06
| 17,493,522
| 5
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,426
|
cpp
|
Project.cpp
|
#include "Project.h"
#include "GEARStudioEvents.h"
#include <G2/StringTools.h>
#include <fstream>
#include <QProgressDialog>
Project::Project(std::string const& projectDirectory) :
JsonDeserializer(projectDirectory + "/project.json"),
JsonSerializer(projectDirectory + "/project.json"),
mProjectDirectory(projectDirectory)
{
}
Project::~Project()
{
// unload existing scene and replace with new scene
if (mCurrentScene.get() != nullptr)
{
G2S::onSceneUnloaded(mCurrentScene.get());
}
}
void
Project::loadLastScene(QProgressDialog* progress)
{
if (!error())
{
std::string lastSceneName;
if (mResource.isMember("last_opened_scene") && G2::Tools::String::trim(mResource["last_opened_scene"].asString()).size() > 0)
{
lastSceneName = mResource["last_opened_scene"].asString();
}
else if (mResource.isMember("scenes"))
{
Json::Value const& scenes = mResource["scenes"];
if (scenes.isArray() && scenes.isValidIndex(0))
{
lastSceneName = scenes[0].asString();
}
}
lastSceneName = G2::Tools::String::trim(lastSceneName);
if (lastSceneName.size() > 0)
{
loadScene(mProjectDirectory + lastSceneName, progress);
}
}
}
void
Project::loadScene(std::string const& sceneFile, QProgressDialog* progress)
{
std::shared_ptr<Scene> scene(new Scene(mProjectDirectory, sceneFile));
if (scene->error())
{
}
else
{
// unload existing scene and replace with new scene
if (mCurrentScene.get() != nullptr)
{
G2S::onSceneUnloaded(mCurrentScene.get());
}
mCurrentScene = scene;
mCurrentScene->load(progress);
if (mCurrentScene.get() != nullptr)
{
G2S::onSceneLoaded(mCurrentScene.get());
}
}
}
void Project::exportProject(QProgressDialog* progress)
{
progress->setLabelText("Generating C++ Code");
G2S::onLog(INFO, "Generate and compile project");
std::ofstream out(mProjectDirectory + "/generated-src/Game_generated.cpp");
// set some global settings
out.setf(std::ios::fixed, std::ios::floatfield);
out.precision(6);
out << "#include <Game.h>" << std::endl;
out << "#include <glm/ext.hpp>" << std::endl;
out << "using namespace G2;" << std::endl;
out << "void Game::_auto_generated_loadCurrentScene()" << std::endl;
out << "{" << std::endl;
out << " if(mCurrentScene == \"" << mCurrentScene->getName() << "\")" << std::endl;
out << " {" << std::endl;
// export scene
mCurrentScene->generateEntityInitializationCode(out, progress);
out << " }" << std::endl;
out << "}" << std::endl;
out.close();
progress->setLabelText("Generating Visual Studio Solution");
progress->setValue(progress->value());
progress->setMaximum(progress->maximum() + 1);
// call premake
std::string premakeCmd = mProjectDirectory.substr(0, 2) + " && cd " + mProjectDirectory + " && " + "premake5.exe --file=premake.lua vs2013";
system(premakeCmd.c_str());
progress->setLabelText("Compiling Visual Studio Solution");
progress->setValue(progress->value() + 1);
progress->setMaximum(progress->maximum() + 10);
std::string compileCmd = "\"" + mProjectDirectory.substr(0, 2) + " && cd " + mProjectDirectory + " && \"C:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\Common7\\IDE\\devenv.exe\" \"GEAR Studio Sample.sln\" /Build \"Debug|x64\" /Out gear.out /Log gear.log\"";
int status = system(compileCmd.c_str());
progress->setValue(progress->value() + 10);
G2S::onLog(INFO, "Compilation has exited with code " + std::to_string(status));
}
|
653349cece3364bab65334fb5f21132ac8f108da
|
2f535dbc215dc2b01738617311015c4647154936
|
/spellcorrector/在线部分/src/Thread.cc
|
50421769f3bb2fa50157a86f2a2f887cad144fb4
|
[] |
no_license
|
zlmone/2020
|
759e56a7611dadcb675792367457d35097a3be62
|
1d5594545cbd8389a0f05724ceb1e34107017621
|
refs/heads/master
| 2022-04-08T10:39:02.332613
| 2020-03-13T09:47:17
| 2020-03-13T09:47:17
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,359
|
cc
|
Thread.cc
|
#include "../include/Thread.h"
#include<iostream>
using std::cout;
using std::endl;
namespace wd{
namespace current_thread{
__thread const char *threadName="wd thread";
//extern表示“外来的”意思
}
using ThreadCallback=std::function<void()>;
struct ThreadData//大概是用于存储每个线程特有的属性
{
ThreadData(const string name,ThreadCallback && cb)
:_name(name)
,_cb(cb)
{}
//子线程真正执行的函数
//个人理解:给全局变量赋值一个局部值
void runInThread(){
cout<<"void runInThread()"<<endl;
current_thread::threadName=(_name==string()?"wd thread":_name.c_str());
if(_cb){
cout<<"_cb()"<<endl;
_cb();
}
}
string _name;
ThreadCallback _cb;
};
Thread::~Thread()
{
if (_isRunning) {
pthread_detach(_pthid);
}
cout << "~Thread()" << endl;
}
void Thread::start() {
cout<<"thread::start"<<endl;
ThreadData *pdata=new ThreadData(_name,std::move(_cb));
pthread_create(&_pthid,nullptr,threadFunc,pdata);
//最后那个参数,为什么不能传this,也是个问题
_isRunning = true;
}
void Thread::join() {
if (_isRunning) {
pthread_join(_pthid, nullptr);
_isRunning = false;
}
}
void * Thread::threadFunc(void * arg)
{
ThreadData * pData = static_cast<ThreadData *>(arg);
if(pData)
pData->runInThread();//执行任务
delete pData;
return nullptr;
}
}
|
6ddbfc8b6ee773746ccf582acfb5a47d89c5b14d
|
fe69e4e586f3017571684517e5e74592d2af9731
|
/09375/9375.cpp11.cpp
|
288305bebafb7e1c4efad3e65e5bf0f3c56d1d2a
|
[] |
no_license
|
computerphilosopher/BOJ
|
f8fc0b8deb462cb29ac842a85a194cbf098856ec
|
ad4bba6aca97bfe3bb98845867402ee491380e47
|
refs/heads/master
| 2020-05-03T18:11:12.155118
| 2019-04-01T00:28:42
| 2019-04-01T00:28:42
| 178,757,808
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 976
|
cpp
|
9375.cpp11.cpp
|
#include <string>
#include <iostream>
#include <map>
#include <vector>
using namespace std;
int solution(vector<vector<string>> &clothes) {
int answer = 0;
map<string, int> hash;
for(auto v : clothes){
hash[v[1]] += 1;
}
answer = 1;
for(auto m : hash){
answer *= (m.second+1);
}
answer--;
return answer;
}
int main(){
int t = 0;
cin.sync_with_stdio(false);
cin >> t;
for(int tc = 0; tc<t; tc++){
int n = 0;
cin >> n;
vector<vector <string> > clothes(n);
for(int i=0; i<n; i++){
string cloth;
string category;
cin >> cloth >> category;
clothes[i].push_back(cloth);
clothes[i].push_back(category);
}
const int s = solution(clothes);
cout << s << "\n";
}
return 0;
}
|
5c0ceef3dac19a72d8a1f8b8426671ed43503228
|
339261bea4044688f85d49eb7c7fc344ff8ac773
|
/app/log_server/app_writer.h
|
98519b524b3273d83d4e60afc0a0d15369030cfe
|
[] |
no_license
|
jiangyong27/tnf
|
64392e9c65cfd0e796c9adb027887daf93b87219
|
7e045b651f3256226e8813b145835855aeefd036
|
refs/heads/master
| 2021-01-18T18:30:38.877214
| 2016-08-01T15:38:49
| 2016-08-01T15:38:49
| 64,679,518
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 807
|
h
|
app_writer.h
|
#ifndef _DATA_JASONYJIANG_COMMON_PROJ_TOOLS_TNF_APP_LOG_SERVER_APP_WRITER_H
#define _DATA_JASONYJIANG_COMMON_PROJ_TOOLS_TNF_APP_LOG_SERVER_APP_WRITER_H
#pragma once
#include "net/net_queue.h"
#include "net/net_thread.h"
#include "net/net_logger.h"
#include "net/net_epoll.h"
class CAppWriter : public Thread
{
public:
CAppWriter();
~CAppWriter();
void SetQueue(CNetQueue *queue) {m_queue = queue;}
void Run();
void OnQueue();
private:
int SwitchToNextFile();
bool IsSwitchFile();
bool Write(const char* data, size_t len);
private:
int m_fd;
std::string m_path_prefix;
time_t m_pre_time;
CNetQueue *m_queue;
CEpoll *m_epoll;
char *m_buffer;
uint32_t m_buffer_size;
};
#endif // _DATA_JASONYJIANG_COMMON_PROJ_TOOLS_TNF_APP_LOG_SERVER_APP_WRITER_H
|
348aee7dd92476f2205e0e29255cb438a33d1331
|
37860b1135d21e1af386ad414ce1ed192f23717b
|
/GCJ2009/Round1B/A.cpp
|
0aa0f54a27b80cb006bb8a20bea8cb429c694075
|
[] |
no_license
|
bnuzhanyu/GCJ
|
d9e42882ef45908efd17b168c5c451f55524b872
|
db6a156be737349c8c35445bad8f3d8ff0ddc81e
|
refs/heads/master
| 2022-07-01T05:16:00.920563
| 2022-05-16T05:53:11
| 2022-05-16T05:53:11
| 83,320,956
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,818
|
cpp
|
A.cpp
|
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <string.h>
#include <set>
#include <string>
#include <map>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
#define FOR(i,n) for(int i=0; i<n; i++)
typedef unsigned long long ull;
typedef long long ll;
void usefile(const string& a){
if(a!="std" && a!="s"){
freopen( (a + ".in").c_str(), "r", stdin);
freopen( (a + ".out").c_str(), "w", stdout);
}
}
const int MAXN = 1000;
struct TreeNode{
int l, r;
string feature;
double w;
}tree[MAXN];
void skip(const string& str, int& st){
while(st < str.size() && str[st] == ' ') st++;
}
string parse_feature(const string& str, int& st){
string ans;
while(st<str.size() && (isalpha(str[st]) || isdigit(str[st]) || str[st] == '.') ) ans.push_back(str[st++]);
return ans;
}
double parse_double(const string& str, int& st){
double ans;
stringstream ss (parse_feature(str, st));
ss >> ans;
return ans;
}
int parse_tree_node(const string& str, int &st, int & id){
int x = id;
skip(str, st);
st++;
skip(str, st);
tree[x].w = parse_double(str, st);
skip(str, st);
if(str[st] == ')') {
tree[x].feature = "";
//cout << "(" << x << ":" << tree[x].w << ")";
st++;
}else{
tree[x].feature = parse_feature(str, st);
//cout << "(" << x << ": " << tree[x].feature << " " << tree[x].w ;
id++;
tree[x].l = parse_tree_node(str, st, id);
id++;
tree[x].r = parse_tree_node(str, st, id);
//cout << ")" ;
skip(str, st);
st++;
}
return x;
}
double prob(set<string>& st){
int id = 0;
double ret = 1;
while(1){
ret *= tree[id].w;
if(tree[id].feature == "") break;
if(st.count(tree[id].feature)) id = tree[id].l;
else id = tree[id].r;
}
return ret;
}
int main(){
usefile("A2");
int T, A, Q;
cin >> T;
for(int ca=1; ca<=T; ca++)
{
string str_tree;
string str;
cin >> A;
getline(cin, str);
for(int i=0; i<A; i++){
getline(cin, str);
str_tree.push_back(' ');
str_tree.append(str);
}
int id = 0, st = 0;
parse_tree_node(str_tree, st, id);
cin >> Q;
cout << "Case #" << ca << ":" << endl;
for(int i=0; i<Q; i++){
int n;
cin >> str >> n;
set<string> st;
for(int j=0; j<n; j++){
cin >> str;
st.insert(str);
}
cout << fixed << prob(st) << endl;
}
}
}
|
1a366c23f1d1af88b3d509702ea177efc2ddd246
|
f95ca67a47039410eeec30b64a8e6ce58a3dcce6
|
/src/msg/DataMsg.hpp
|
c8fe34bd0333f84ba62f8f4838af59dc1bd0564e
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
phamtec/skweltch
|
782a9413d10c4a8005acfedc7263e086c9d20577
|
9bd4f828e4ca30cd7058cf30be82329c5e3af637
|
refs/heads/master
| 2020-05-26T23:16:54.108880
| 2015-03-17T07:43:49
| 2015-03-17T07:43:49
| 10,887,437
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 759
|
hpp
|
DataMsg.hpp
|
#ifndef __DATAMSG_HPP_INCLUDED__
#define __DATAMSG_HPP_INCLUDED__
#include "Msg.hpp"
#include "IDataMsg.hpp"
/**
Message that contains data.
*/
template <typename DataType>
class DataMsg : public Msg<msgpack::type::tuple<int, clock_t, DataType> >, public IDataMsg {
public:
DataMsg(const zmq::message_t &message) : Msg<msgpack::type::tuple<int, clock_t, DataType> >(message) {}
DataMsg(int id, clock_t t, DataType n) : Msg<msgpack::type::tuple<int, clock_t, DataType> >(
msgpack::type::tuple<int, clock_t, DataType>(id, t, n)) {}
// getters.
virtual int getId() {
return this->data.a0;
}
virtual clock_t getTime() {
return this->data.a1;
}
DataType getPayload() {
return this->data.a2;
}
};
#endif // __DATAMSG_HPP_INCLUDED__
|
cd6fb72a7cd419ec3d87e7a5d9297e3457755023
|
c3e6a7fca5e47d6d6094d4a589b7f31506d4387a
|
/AudioReflectorDriver/ARStereoPanControl.cpp
|
6a0de453a744192209d820fe17d3ddaf4af66673
|
[] |
no_license
|
fruitsamples/HAL
|
d5731f67ff6373fae4aaf3d334443f7c934c6a8f
|
b9d11a4b1d955bf509361e1bbb9b13139a8f7334
|
refs/heads/master
| 2021-01-10T11:07:21.408727
| 2015-11-04T03:20:32
| 2015-11-04T03:20:32
| 45,437,461
| 0
| 1
| null | null | null | null |
WINDOWS-1252
|
C++
| false
| false
| 7,354
|
cpp
|
ARStereoPanControl.cpp
|
/* Copyright © 2007 Apple Inc. All Rights Reserved.
Disclaimer: IMPORTANT: This Apple software is supplied to you by
Apple Inc. ("Apple") in consideration of your agreement to the
following terms, and your use, installation, modification or
redistribution of this Apple software constitutes acceptance of these
terms. If you do not agree with these terms, please do not use,
install, modify or redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and
subject to these terms, Apple grants you a personal, non-exclusive
license, under Apple's copyrights in this original Apple software (the
"Apple Software"), to use, reproduce, modify and redistribute the Apple
Software, with or without modifications, in source and/or binary forms;
provided that if you redistribute the Apple Software in its entirety and
without modifications, you must retain this notice and the following
text and disclaimers in all such redistributions of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc.
may be used to endorse or promote products derived from the Apple
Software without specific prior written permission from Apple. Except
as expressly stated in this notice, no other rights or licenses, express
or implied, are granted by Apple herein, including but not limited to
any patent rights that may be infringed by your derivative works or by
other works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/*==================================================================================================
ARStereoPanControl.cpp
==================================================================================================*/
//==================================================================================================
// Includes
//==================================================================================================
// Self Include
#include "ARStereoPanControl.h"
//==================================================================================================
// ARStereoPanControl
//==================================================================================================
OSDefineMetaClassAndStructors(ARStereoPanControl, IOAudioControl)
bool ARStereoPanControl::init(SInt32 inCurrentValue, SInt32 inFullLeftValue, SInt32 inCenterValue, SInt32 inFullRightValue, UInt32 inLeftChannelNumber, UInt32 inRightChannelNumber, UInt32 inChannelID, const char* inChannelName, UInt32 inControlID, UInt32 inSubType, UInt32 inUsage, OSDictionary* inProperties)
{
bool theAnswer = false;
// allocate an OSNumber to hold the current value
OSNumber* theCurrentValue = OSNumber::withNumber(inCurrentValue, sizeof(SInt32)*8);
if(theCurrentValue != NULL)
{
// initialize the super class
theAnswer = IOAudioControl::init(kIOAudioControlTypeStereoPan, theCurrentValue, inChannelID, inChannelName, inControlID, inSubType, inUsage, inProperties);
// release the number since we're done with it
theCurrentValue->release();
// initialize the rest of the control
if(theAnswer)
{
setFullLeftValue(inFullLeftValue);
setCenterValue(inCenterValue);
setFullRightValue(inFullRightValue);
setLeftChannelNumber(inLeftChannelNumber);
setRightChannelNumber(inRightChannelNumber);
}
}
return theAnswer;
}
void ARStereoPanControl::free()
{
IOAudioControl::free();
}
ARStereoPanControl* ARStereoPanControl::create(SInt32 inCurrentValue, SInt32 inFullLeftValue, SInt32 inCenterValue, SInt32 inFullRightValue, UInt32 inLeftChannelNumber, UInt32 inRightChannelNumber, UInt32 inChannelID, const char* inChannelName, UInt32 inControlID, UInt32 inSubType, UInt32 inUsage)
{
ARStereoPanControl* theAnswer = new ARStereoPanControl;
if(theAnswer != NULL)
{
if(!theAnswer->init(inCurrentValue, inFullLeftValue, inCenterValue, inFullRightValue, inLeftChannelNumber, inRightChannelNumber, inChannelID, inChannelName, inControlID, inSubType, inUsage, NULL))
{
theAnswer->release();
theAnswer = NULL;
}
}
return theAnswer;
}
SInt32 ARStereoPanControl::getFullLeftValue()
{
return mFullLeftValue;
}
void ARStereoPanControl::setFullLeftValue(SInt32 inFullLeftValue)
{
mFullLeftValue = inFullLeftValue;
setProperty(kIOAudioStereoPanControlFullLeftValueKey, inFullLeftValue, sizeof(SInt32)*8);
sendChangeNotification(kIOAudioControlRangeChangeNotification);
}
SInt32 ARStereoPanControl::getCenterValue()
{
return mCenterValue;
}
void ARStereoPanControl::setCenterValue(SInt32 inCenterValue)
{
mCenterValue = inCenterValue;
setProperty(kIOAudioStereoPanControlCenterValueKey, inCenterValue, sizeof(SInt32)*8);
sendChangeNotification(kIOAudioControlRangeChangeNotification);
}
SInt32 ARStereoPanControl::getFullRightValue()
{
return mFullRightValue;
}
void ARStereoPanControl::setFullRightValue(SInt32 inFullRightValue)
{
mFullRightValue = inFullRightValue;
setProperty(kIOAudioStereoPanControlFullRightValueKey, inFullRightValue, sizeof(SInt32)*8);
sendChangeNotification(kIOAudioControlRangeChangeNotification);
}
UInt32 ARStereoPanControl::getLeftChannelNumber()
{
return mLeftChannelNumber;
}
void ARStereoPanControl::setLeftChannelNumber(UInt32 inLeftChannelNumber)
{
mLeftChannelNumber = inLeftChannelNumber;
setProperty(kIOAudioStereoPanControlLeftChannelKey, inLeftChannelNumber, sizeof(UInt32)*8);
sendChangeNotification(kIOAudioControlRangeChangeNotification);
}
UInt32 ARStereoPanControl::getRightChannelNumber()
{
return mRightChannelNumber;
}
void ARStereoPanControl::setRightChannelNumber(UInt32 inRightChannelNumber)
{
mRightChannelNumber = inRightChannelNumber;
setProperty(kIOAudioStereoPanControlRightChannelKey, inRightChannelNumber, sizeof(SInt32)*8);
sendChangeNotification(kIOAudioControlRangeChangeNotification);
}
IOReturn ARStereoPanControl::validateValue(OSObject* inNewValue)
{
IOReturn theAnswer = kIOReturnBadArgument;
// cast the value to a number
OSNumber* theNumber = OSDynamicCast(OSNumber, inNewValue);
if(theNumber != NULL)
{
// convert the number into an integer
SInt32 theNewValue = (SInt32)theNumber->unsigned32BitValue();
// make sure the new value is within the proper range
if((theNewValue >= mFullLeftValue) && (theNewValue <= mFullRightValue))
{
theAnswer = kIOReturnSuccess;
}
else
{
theAnswer = kIOReturnError;
}
}
return theAnswer;
}
|
c6bf9a0230b8bcd007117e5c2e1895614bf18e08
|
648eafe3a182d6753bdc65cdb50add2a2826930d
|
/2 - Árvore Binária de Busca/main.cpp
|
f2305d626c5f009b1cc31b80097d642cc68a0470
|
[] |
no_license
|
filipedwan/Estrutura-de-Dados-II
|
eb5a2060449a2d36ebdd319210a221e729402e9e
|
a38bced9f75208c2a56fe918f8bef68324ac8c53
|
refs/heads/master
| 2021-09-11T18:21:32.195773
| 2018-04-11T00:36:40
| 2018-04-11T00:36:40
| 125,720,606
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 382
|
cpp
|
main.cpp
|
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include "arvbb.h"
int main() {
Arv_bin* arv = abb_cria();
abb_insere(arv, 'g');
abb_insere(arv, 'c');
abb_insere(arv, 'p');
abb_insere(arv, 'b');
abb_insere(arv, 'd');
abb_insere(arv, 'h');
abb_insere(arv, 'r');
abb_remove(arv, 'g');
abb_remove(arv, 'c');
arv_imprime(arv);
arv_libera(arv);
return 0;
}
|
3e0a528433d9d1682a4d71dfcba071c8b80c1850
|
4780fa2ddbb72ed082efa3c35e8427e53161dd7a
|
/behavioralStateMachine/CRecollect.h
|
53b66fd526c133627f421002fe8abf3d5c7ddb2e
|
[] |
no_license
|
luricardorod/createWorlds
|
0834c21cf9e804cd6806375aa81a02e1bfce72c0
|
c5a43b6952d48ce365ed99f1a7dfaaee67d4209b
|
refs/heads/master
| 2021-01-21T20:34:42.807890
| 2017-08-17T00:39:21
| 2017-08-17T00:39:21
| 92,255,293
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 215
|
h
|
CRecollect.h
|
#pragma once
#include "CStates.h"
class CRecollect :
public CStates
{
public:
int Update(CUnits* unit, float deltaTime);
void OnEnter(CUnits *unit);
void OnExit(CUnits *unit);
CRecollect();
~CRecollect();
};
|
ab864662bf2f66084b85ad234a0a8ade09204946
|
f3e0b57dbb25b189ebf547050eed02be896652c8
|
/b844.cpp
|
5e94daed8c4d954da727bbd8ec250405d7aec229
|
[] |
no_license
|
txya900619/zerojudge
|
60d0a129cdb797bc772ac67c73210bb97294dbb9
|
9a403a72b8b617a4f7a81266b881ef13bcab71a8
|
refs/heads/master
| 2021-07-10T18:46:27.806157
| 2020-10-26T06:33:36
| 2020-10-26T06:33:36
| 211,144,941
| 1
| 2
| null | 2020-10-26T06:33:37
| 2019-09-26T17:27:47
|
C++
|
UTF-8
|
C++
| false
| false
| 777
|
cpp
|
b844.cpp
|
#include <bits/stdc++.h>
#include <algorithm>
using namespace std;
int main(int argc, char *argv[])
{
ios::sync_with_stdio(0), cin.tie(0);
long n = 0, q = 0, m = 0, ask = 0;
cin >> n >> q;
long datas[n];
for (long i = 0; i < n; i++)
{
cin >> datas[i];
}
sort(datas,datas+n);
while (q--)
{
long l = 1, r = n;
m = (r + l) / 2;
cin >> ask;
while (r - l<=0)
{
if(ask>=datas[m-1]){
l = m+1;
}else{
r = m-1;
}
m =(r+l)/2;
}
if (datas[l-1]>ask){
l-=1;
}
if(l%2){
cout<<1<<endl;
}else{
cout<<0<<endl;
}
}
return 0;
}
|
e570754cdae7a6f15007dd766cf0694031760ed5
|
3b13eedb87e6545f832e1c62b8cb05b8428a897b
|
/src/main/avikodak/sites/codechef/easy/spoon.h
|
030b28144f1896ff7b8cc2c39aab9435bbab5892
|
[] |
no_license
|
avikodak/algos_v2
|
a9c66b2f2b862318f12feb216240a9a66249aa2b
|
e1c77f1064c83599d0e57f426319ab536a6eeb29
|
refs/heads/master
| 2021-01-19T20:43:29.366352
| 2017-03-25T17:15:22
| 2017-03-25T17:15:22
| 24,980,353
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,140
|
h
|
spoon.h
|
/****************************************************************************************************************************************************
* File Name : spoon.h
* File Location : /home/avikodak/Desktop/projects/algos_v2/src/main/avikodak/sites/codechef/easy/spoon.h
* Created on : 11-Sep-2015 :: 7:32:01 pm
* Author : avikodak
* Testing Status : Tested
* URL : https://www.codechef.com/problems/SPOON
****************************************************************************************************************************************************/
/****************************************************************************************************************************************************/
/* NAMESPACE DECLARATION AND IMPORTS */
/****************************************************************************************************************************************************/
using namespace std;
using namespace __gnu_cxx;
/****************************************************************************************************************************************************/
/* INCLUDES */
/****************************************************************************************************************************************************/
#include <string>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <ctime>
#include <list>
#include <map>
#include <set>
#include <bitset>
#include <functional>
#include <numeric>
#include <utility>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string.h>
#include <hash_map>
#include <stack>
#include <queue>
#include <limits.h>
#include <stdint.h>
#include <lib/constants/constants.h>
#include <lib/ds/commonds.h>
#include <lib/ds/linkedlistds.h>
#include <lib/ds/graphds.h>
#include <lib/ds/mathds.h>
#include <lib/ds/treeds.h>
#include <lib/utils/arrayutil.h>
#include <lib/utils/avltreeutil.h>
#include <lib/utils/bplustreeutil.h>
#include <lib/utils/btreeutil.h>
#include <lib/utils/commonutil.h>
#include <lib/utils/dillutil.h>
#include <lib/utils/graphutil.h>
#include <lib/utils/mathutil.h>
#include <lib/utils/redblacktreeutil.h>
#include <lib/utils/sillutil.h>
#include <lib/utils/treeutil.h>
#include <lib/utils/twofourtreeutil.h>
/****************************************************************************************************************************************************/
/* USER DEFINED CONSTANTS */
/****************************************************************************************************************************************************/
/****************************************************************************************************************************************************/
/* MAIN CODE START */
/****************************************************************************************************************************************************/
#ifndef SPOON_H_
#define SPOON_H_
//Tested
void isSpoonPresent(vector<string> userInput) {
for(int rowCounter = 0; rowCounter < userInput.size(); rowCounter++) {
for(int columnCounter = 0; columnCounter < userInput[0].length(); columnCounter++) {
if(columnCounter+4 < userInput[0].length()) {
if(userInput[rowCounter][columnCounter] == 's' &&
userInput[rowCounter][columnCounter+1] == 'p' &&
userInput[rowCounter][columnCounter+2] == 'o' &&
userInput[rowCounter][columnCounter+3] == 'o' &&
userInput[rowCounter][columnCounter+4] == 'n') {
printf("There is a spoon!\n");
return;
}
} else {
break;
}
}
}
for(int columnCounter = 0; columnCounter < userInput[0].length(); columnCounter++) {
for(int rowCounter = 0; rowCounter < userInput.size(); rowCounter++) {
if(rowCounter+4 < userInput.size()) {
if(userInput[rowCounter][columnCounter] == 's' &&
userInput[rowCounter+1][columnCounter] == 'p' &&
userInput[rowCounter+2][columnCounter] == 'o' &&
userInput[rowCounter+3][columnCounter] == 'o' &&
userInput[rowCounter+4][columnCounter] == 'n') {
printf("There is a spoon!\n");
return;
}
} else {
break;
}
}
}
printf("There is indeed no spoon!\n");
}
//Tested
void printResults() {
unsigned int testCases,rows,columns;
string input;
vector<string> userInput;
scanf("%u",&testCases);
while(testCases--) {
scanf("%u %u",&rows,&columns);
userInput.clear();
while(rows--) {
cin >> input;
transform(input.begin(),input.end(),input.begin(),::tolower);
userInput.push_back(input);
}
isSpoonPresent(userInput);
}
}
#endif /* SPOON_H_ */
/****************************************************************************************************************************************************/
/* MAIN CODE END */
/****************************************************************************************************************************************************/
|
5b35e1838962ad331e7d43d221e3b4a447c54102
|
d6ab12f806552b4a754edfba40e29ce6b1aec786
|
/pausewidget.h
|
f5a87215647184f71485bc53200ad4f7e40f5f17
|
[] |
no_license
|
tecton/HexGame
|
998e4373001d93fb1bafb671bb60a60b6452f5b5
|
3fe9d7b8e0ca6abd1f9eb84eb08fb931a5a86171
|
refs/heads/master
| 2021-01-20T05:08:33.789717
| 2011-11-01T03:57:44
| 2011-11-01T03:57:44
| 2,028,141
| 1
| 4
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,453
|
h
|
pausewidget.h
|
#ifndef PAUSEWIDGET_H
#define PAUSEWIDGET_H
// File must include
#include "abstractpixmapwidget.h"
#include <QVector>
// Forward declaration
class AbstractItem;
class StringItem;
/**
* @brief A class to show the pause widget.
*/
class PauseWidget : public AbstractPixmapWidget
{
Q_OBJECT
public:
/**
* @brief Constructor.
*/
PauseWidget();
/**
* @brief Destructor.
*/
~PauseWidget();
virtual void makePixmap(
#ifdef USE_PIXMAP
QPixmap& pixmap,
#else
QPainter* painter,
#endif
int width,
int height);
virtual void makeBasicPixmap(
#ifdef USE_PIXMAP
QPixmap& pixmap,
#else
QPainter* painter,
#endif
int width,
int height);
virtual void addEffect(
#ifdef USE_PIXMAP
QPixmap& pixmap,
#else
QPainter* painter,
#endif
int width,
int height);
virtual QPointF toScene(double xRate, double yRate);
virtual void dealPressed(QPointF mousePos, Qt::MouseButton button);
virtual void dealMoved(QPointF mousePos, Qt::MouseButton button);
virtual void dealReleased(QPointF mousePos, Qt::MouseButton button);
virtual void getForcus(){}
virtual void loseForcus(){}
private:
// Items of the game
StringItem *pauseHint;
// A vector stores the items,
// used to paint and release the space
QVector<AbstractItem *> myItems;
signals:
/**
* @brief A signal to tell other widget to resume.
*/
void resume();
};
#endif // PAUSEWIDGET_H
|
a7768410d5bb5f482cb413cbdf653efb9d0eab7a
|
787b915243a8d1658f339152c05f80d14db69226
|
/cacl/widget.cpp
|
cb9bf2cdd5dea87642718b4af52801a5bbcfd423
|
[] |
no_license
|
Justicewa/QT
|
ab1a81b6baeb3e5b4adcbad20e6d78516a2baba8
|
082e69de6ed7b9e9c69237d9854f43c4fcd96c78
|
refs/heads/master
| 2020-05-17T13:52:11.396018
| 2019-05-04T14:44:38
| 2019-05-04T14:44:38
| 183,747,860
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,000
|
cpp
|
widget.cpp
|
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pushButton_clicked()
{
char string1[20]={0};
char string2[20]={0};
char fu[2]={0};
int sum = 0;
strcpy(string1, ui->lineEdit1->text().toLatin1().data()); //文本转char
strcpy(string2, ui->lineEdit3->text().toLatin1().data());
strcpy(fu,ui->lineEdit2->text().toLatin1().data());
switch (fu[0]) {
case '+':
sum = atoi(string1) + atoi(string2);
break;
case '-':
sum = atoi(string1) - atoi(string2);
break;
case '*':
sum = atoi(string1) * atoi(string2);
break;
case '/':
sum = atoi(string1) / atoi(string2);
break;
default:
break;
}
char buf[20] = {0};
sprintf(buf,"%d",sum);
ui->lineEdit4->setText(buf);
}
void Widget::on_pushButton_13_clicked()
{
}
|
625da7cdd2702ea64a33c3461914c2b8a7486144
|
7d1e67fa845aa3c0ab57b484a3d6167c15af4927
|
/EspOledSelect/setTemp.ino
|
64c3b0797593374ce6153440441768e5a1fea64a
|
[] |
no_license
|
bavensky/ESP8266-OLED-SettingMode
|
784341070267959a389714aeea7b37f24c1609ee
|
8dff226b30f2114b44b5ec8a7bf7b5907a9b9242
|
refs/heads/master
| 2021-08-14T18:32:12.068323
| 2017-11-16T13:45:43
| 2017-11-16T13:45:43
| 110,099,294
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 775
|
ino
|
setTemp.ino
|
void mode2() {
Serial.println("set Temp avarible");
delay(200);
if (digitalRead(BT0) == 0) {
tmpCount += 1;
}
if (tmpCount > 30) {
tmpCount = 20;
}
display.clear();
display.setTextAlignment(TEXT_ALIGN_LEFT);
display.setFont(ArialMT_Plain_16);
display.drawString(0, 0, "Smart Farm");
display.setFont(ArialMT_Plain_10);
display.drawString(0, 16, "Temp");
display.drawString(35, 16, String(tmpCount));
display.drawString(50, 16, "C");
display.display();
delay(200);
if (digitalRead(BT13) == 0) {
previousMillis = millis();
}
while (digitalRead(BT13) == 0) {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= 1500) {
previousMillis = currentMillis;
modeRun = 0;
}
}
}
|
e699ff33b9cba3b58689306d9b8b0723ea0d178b
|
435be38e1fec093c3a38ef328216b2ec04bd37e0
|
/1017.Packets.cpp
|
5e5c271e27a40a4008569a3158599309fbe00d99
|
[] |
no_license
|
renardbebe/myPOJ
|
54197da713d9fdcb85a0f7fbe2d565f6cfd8640c
|
68f603993b7b1fa105043e22337a031a8eef9e64
|
refs/heads/master
| 2018-12-08T18:19:53.966837
| 2018-09-17T08:11:32
| 2018-09-17T08:11:32
| 117,306,446
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,147
|
cpp
|
1017.Packets.cpp
|
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
int main () {
int N, a, b, c, d, e, f, y, x; // N用来存储需要的箱子数目,y用来存储 2*2 的空位数目
int u[4] = {0, 5, 3, 1};
/* 数组u 表示3*3 的产品数目分别是 4的倍数,4 的倍数+1, 4 的倍数+2, 4 的倍数+3
时,为3*3的产品打开的新箱子中剩余的 2*2的空位的个数 */
while(1) {
scanf("%d%d%d%d%d%d", &a, &b, &c, &d, &e, &f);
if(a == 0 && b == 0 && c == 0 && d == 0 && e == 0 && f == 0)
break;
N = f + e + d + (c + 3) / 4; // (c+3)/4 正好等于c除以4向上取整的结果
y = 5 * d + u[c % 4]; // 每一个4*4的箱子装过后还可以再装5个2*2的箱子
/* 还有3*3的箱子如果没填满6*6的箱子的话,也可以用来装2*2的箱子
5*5的箱子则只能装1*1的情况了 */
if(b > y)
N += (b - y + 8 ) / 9; // 如果要装的2*2的箱子的数目比提供的空间要多, 那么多的部分要新开一些箱子
x = 36 * N - 36 * f - 25 * e - 16 * d - 9 * c - 4 * b;
if(a > x)
N += ( a - x + 35 ) / 36;
printf("%d\n", N);
}
}
|
457cc0513d17b118ce2ad9bf7544e0d144bd928b
|
77e27b77795159808583ca3a4e4d16249d4bab1b
|
/Chapter 4/Chapter4Number8.cpp
|
98045e110b27ea0e4f953f8eff4aac8d10d50a35
|
[] |
no_license
|
doodayev/GaddisChallenges
|
8c7debda40f8fb70377dbb066f828ec3da75b751
|
a60717d95f1db389dba6c377034589d2fc621a6d
|
refs/heads/master
| 2022-12-04T14:19:47.734570
| 2020-07-10T09:25:01
| 2020-07-10T09:25:01
| 265,373,565
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,994
|
cpp
|
Chapter4Number8.cpp
|
#include <iostream>
#include <string>
using namespace std;
int main()
{
string choice1;
string choice2;
cout << "Enter a color that's red, yellow, or blue \n";
cin >> choice1;
cout << "Enter another color that's red, yellow, or blue \n";
cin >> choice2;
if ((choice1=="blue" || choice1=="Blue" || choice1=="BLUE") && (choice2=="blue" || choice2=="Blue" || choice2=="BLUE"))
{
cout << "When you mix these two together you get blue! \n";
}
if ((choice1=="blue" || choice1=="Blue" || choice1=="BLUE") && (choice2=="red" || choice2=="Red" || choice2=="RED"))
{
cout << "When you mix these two together you get purple! \n";
}
if ((choice2=="blue" || choice2=="Blue" || choice2=="BLUE") && (choice1=="red" || choice1=="Red" || choice1=="RED"))
{
cout << "When you mix these two together you get purple! \n";
}
if ((choice1=="blue" || choice1=="Blue" || choice1=="BLUE") && (choice2=="yellow" || choice2=="Yellow" || choice2=="YELLOW"))
{
cout << "When you mix these two together you get green! \n";
}
if ((choice2=="blue" || choice2=="Blue" || choice2=="BLUE") && (choice1=="yellow" || choice1=="Yellow" || choice1=="YELLOW"))
{
cout << "When you mix these two together you get green! \n";
}
if ((choice1=="Red" || choice1=="red" || choice1=="RED") && (choice2=="yellow" || choice2=="Yellow" || choice2=="YELLOW"))
{
cout << "When you mix these two together you get orange! \n";
}
if ((choice2=="Red" || choice2=="red" || choice2=="RED") && (choice1=="yellow" || choice1=="Yellow" || choice1=="YELLOW"))
{
cout << "When you mix these two together you get orange! \n";
}
if ((choice1=="Red" || choice1=="red" || choice1=="RED") && (choice2=="Red" || choice2=="red" || choice2=="RED"))
{
cout << "When you mix these two together you get red! \n";
}
if ((choice1=="yellow" || choice1=="Yellow" || choice1=="YELLOW") && (choice2=="yellow" || choice2=="Yellow" || choice2=="YELLOW"))
{
cout << "When you mix these two together you get yellow! \n";
}
}
|
333955787810d0630c4aeb556c4f2117a326e361
|
48044db9c9b4b40767dc707bb0efc15f368017b7
|
/Ptr_Swap.cpp
|
3cf28ace2fe04be5318de0f77a7580b447a93c29
|
[] |
no_license
|
Wade-Benoit/Udemy_Cpp_Section_12
|
c0fd7428057e8aa94b3518f1d0838c3568581f3d
|
7f984532a56cc719861755d5c9f10ab7e6ce3c35
|
refs/heads/main
| 2023-03-23T18:43:54.353005
| 2021-03-17T06:37:25
| 2021-03-17T06:37:25
| 348,602,840
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 698
|
cpp
|
Ptr_Swap.cpp
|
// PASSING POINTERS TO FUNCTIONS 2, WITH SWAP
#include <iostream>
using namespace std;
void swap(int *a, int *b); //function that accepts two pointers to integers
int main() {
int x {10};
int y {20};
cout << "\nx: " << x << " and y: " << y << endl;
swap(&x, &y);
cout << "After swapping: " << endl;
cout << "\nx: " << x << " and y: " << y << endl;
return 0;
}
void swap(int *a, int *b) { //Function takes the values of the pointed-to variables and swaps them
int temp; //placeholder
temp = *a; //dereferencing and changing the pointer values by reference to them
*a = *b;
*b = temp;
}
|
402c6168b3a634f459ade5489ebd8569439b4b48
|
4f3fdea3a0dc75a4f4ea9ba1aded3e1f75b19d64
|
/1. Graf nieskierowany/src/Graph.cpp
|
d17172ed54a609d6f57e64c0b11702db5f2a9d40
|
[] |
no_license
|
matelko123/Projekty-cpp
|
48f09639dbb7f282c286676bbf0c541a8111c7a1
|
8658b4289cad440394be8698df92785c224afa54
|
refs/heads/main
| 2023-05-14T01:56:29.563033
| 2021-06-06T21:17:53
| 2021-06-06T21:17:53
| 358,951,482
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,536
|
cpp
|
Graph.cpp
|
#include "Graph.hpp"
Graph::Graph() {}
Graph::Graph(std::string filename)
{
loadData(filename);
}
Graph::~Graph()
{
clear();
}
void Graph::clear()
{
for (auto node : graf)
node.clear();
}
void Graph::loadData(std::string filename)
{
// File stream
std::fstream fin;
fin.open(filename, std::ios::in);
if (fin.good() == false)
{
std::cout << "Something went wrong with read file." << std::endl;
exit(1);
}
std::string line, word;
int i = 0;
std::list<int> tmp;
while (fin.eof() == false)
{
i = 0;
tmp.clear();
// Get data from file in line
getline(fin, line);
std::stringstream s(line);
while (getline(s, word, ';'))
{
int val = std::stoi(word);
if (val == 1)
tmp.push_back(i);
i++;
}
graf.push_back(tmp);
}
fin.close();
}
void Graph::printList(std::list<int> node, int i)
{
std::cout << i << ": ";
for (auto const n : node)
std::cout << " <-> " << n;
std::cout << std::endl;
}
void Graph::print()
{
int i = 0;
for (std::list<int> node : graf)
{
printList(node, i++);
}
}
bool Graph::isCyclic()
{
const int n = graf.size();
int w, v, z, i;
std::list<int> S;
bool *visited = new bool[n];
for (int j = 0; j < n; j++)
visited[j] = false;
S.push_back(0);
S.push_back(-1);
visited[0] = true;
while (!S.empty())
{
w = S.front();
S.pop_back();
v = S.front();
S.pop_back();
for (auto it = graf[v].begin(); it != graf[v].end(); it++)
{
z = *it;
if (!visited[z])
{
S.push_back(z);
S.push_back(v);
visited[z] = true;
}
else if (z != w)
{
delete[] visited;
return true;
}
}
}
delete[] visited;
return false;
}
bool Graph::isConsistent()
{
int vc = 0, v, u;
const int n = graf.size();
std::list<int> S;
bool *visited = new bool[n];
for (int i = 0; i < n; i++, visited[i] = false);
S.push_back(0);
visited[0] = true;
while (!S.empty())
{
S.pop_back();
v = S.front();
for (auto it = graf[v].begin(); it != graf[v].end(); it++)
{
if (!visited[*it])
{
S.push_back(*it);
visited[*it] = true;
}
}
vc++;
}
if (vc == n)
return true;
return false;
}
bool Graph::isBipartite()
{
int vc = 0, v, u;
const int n = graf.size();
std::list<int> S, Q;
int *C = new int[n];
for (int i = 0; i < n; i++, C[i] = 0);
for (int i = 0; i < n; i++)
if (!C[i])
{
C[i] = 1;
Q.push_back(i);
while (!Q.empty())
{
v = Q.front();
Q.pop_back();
for (auto it = graf[v].begin(); it != graf[v].end(); it++)
{
if (C[*it] == C[v])
{
delete[] C;
return false;
}
if (!C[*it])
{
C[*it] = -C[v];
Q.push_back(*it);
}
}
}
}
delete[] C;
return true;
}
|
bbfcc2454f34c4b9621c5f442f9cb16cfd7fd901
|
7495529047d2f5ce25e7bfd696b88c44c42a926d
|
/new_code/rule.h
|
e8c7e5b323d42f83cab313a3da5c2800f2c1148d
|
[] |
no_license
|
hitaitengteng/honors
|
a768b3d3455bbd2a408d281ab77de4f75cd54713
|
a13a6091e09b8837366c22c640421feca9261c23
|
refs/heads/master
| 2021-09-26T22:31:43.244030
| 2018-11-03T21:10:59
| 2018-11-03T21:10:59
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,076
|
h
|
rule.h
|
#ifndef RULE_H
#define RULE_H
#include "attribute.h"
/****************************************************************************
* File: rule.h
* Author: Will Gantt
* Description: Defines the Rule class and declares related functions
*
* A rule is the basic evolutionary unit in a Michigan-style
* learning classifier system (like this one), and it has
* two fundamental components: a condition and a predicted class.
*
* The condition specifies the features an example (input vector)
* must have in order for the rule to match it. These 'features'
* are just ranges of values for particular attributes. Thus,
* the data structure here used to represent a condition is
* a vector of Attribute objects.
*
* The rule's class determines how examples matching the rule
* will be classified. A given rule has just a single class.
* In its current iteration, this program tries to describe the
* features of just one class at a time. Therefore, all of the
* rules in a Population have the same class. This could easily
* be changed in future experiments.
*
* The Rule class also has several other member variables. The
* ID (id_) is an integer value that uniquely identifies a rule.
* 'num_dont_care_' indicates the number of attributes in the
* rule's condition that have their 'dont_care_' variables set
* to true.
*
* Additionally, rules keep track of the number of true positive,
* false positive, true negative, and false negative examples.
* The meanings of these terms are explained in the comments
* below.
*
* Finally, rules have two fitness values. The first is computed
* from the number of true and false positives and negatives and
* is used to establish a preliminary ranking of all the rules
* in the Population. The second fitness is also computed from
* the number of true and false positives and negatives, but
* takes into account the ranking established by the first
* fitness. The fitness sytem is explained in greater detail
* below.
****************************************************************************/
class Rule {
public:
// MEMBER VARIABLES
// A vector of attributes that determine the features of
// the examples that the rule will match. Ideally, this
// would be a private member variable, but writing wrappers
// for all the relevant functions in the vector class is
// a pain.
std::vector<Attribute> condition_;
// FUNCTIONS
// first constructor (default)
Rule() {
id_ = NO_ID;
classification_ = 0;
num_dont_care_ = 0;
true_positives_ = 0.5;
false_positives_ = 0.5;
true_negatives_ = 0.5;
false_negatives_ = 0.5;
}
// second constructor (initializes the condition vector)
Rule(int num_attributes) {
id_ = NO_ID;
classification_ = 0;
num_dont_care_ = 0;
true_positives_ = 0.5;
false_positives_ = 0.5;
true_negatives_ = 0.5;
false_negatives_ = 0.5;
// initialize the condition vector
Attribute a;
for (int i=0; i<num_attributes; i++)
condition_.push_back(a);
}
// equality operator
bool operator==(const Rule &rule) const;
// computes fitness1 using odds ratio. Odds ratio is
// just the product of the number of true positives and
// true negatives divided by the product of the number
// of the false positives and false negatives:
//
// (|TP| x |TN|) / (|FP| x |FN|)
//
void updateFitness1() {
fitness1_ = (true_positives_ * true_negatives_) /
(false_positives_ * false_negatives_);
// for each "don't care" value that the rule has,
// it receives a slight fitness boost
fitness1_ += num_dont_care_ * FITNESS_BOOST;
}
// computes fitness2 using odds ratio
void updateFitness2() {
fitness2_ = log((true_positives_ * true_negatives_) /
(false_positives_ * false_negatives_));
// if the fitness is negative (which is possible, since
// we're taking the log of the odds ratio), adjust it to
// a very low positive value
if (fitness2_ <= 0)
fitness2_ = FITNESS_BOOST;
// for each "don't care" value that the rule has,
// it receives a slight fitness boost
fitness2_ += num_dont_care_ * FITNESS_BOOST;
}
// resets the counts of true positives, false positives,
// true negatives, and false negatives
void resetCounts() {
true_positives_ = 0.5;
false_positives_ = 0.5;
true_negatives_ = 0.5;
false_negatives_ = 0.5;
}
// determines whether a given input should count as a true positive,
// true negative, false positive, or false negative for the rule
int processInput(std::vector<double> &input);
// mutates the class and attribute ranges in the condition with
// some probability
void mutate(double p_mutate,
double p_dont_care,
std::vector< std::vector<double> > quantiles);
// checks whether this rule matches an example
bool matches(std::vector<double> input);
// generate a random rule, supposing you already have some
// information about the dataset that you're working with
static Rule random(int num_classes,
std::vector<std::vector<double> > quantiles,
double dont_care_prob);
// prints out some information about a rule
void print();
// prints out complete information about a rule
void printVerbose();
//
// getters
//
int id() const {return id_;}
int classification() const {return classification_;}
double true_positives() const {return true_positives_;}
double false_positives() const {return false_positives_;}
double true_negatives() const {return true_negatives_;}
double false_negatives() const {return false_negatives_;}
int num_dont_care() const {return num_dont_care_;}
double fitness1() const {return fitness1_;}
double fitness2() const {return fitness2_;}
//
// setters
//
void setID(int id) {
id_ = id;
}
void setClass(int classification) {
classification_ = classification;
}
void setTruePositives(double true_positives) {
true_positives_ = true_positives;
}
void setFalsePositives(double false_positives) {
false_positives_ = false_positives;
}
void setTrueNegatives(double true_negatives) {
true_negatives_ = true_negatives;
}
void setFalseNegatives(double false_negatives) {
false_negatives_ = false_negatives;
}
void setNumDontCare(int num_dont_care) {
num_dont_care_ = num_dont_care;
}
void setFitness1(double fitness1) {
fitness1_ = fitness1;
}
void setFitness2(double fitness2)
{fitness2_ = fitness2;
}
private:
/*
* Note that the variable type for the number of TPs,
* TNs, FPs, and FNs is double. This is so that they
* may be initialized with a value of 0.5, which is a
* way to avoid having to check for division by 0 when
* computing the odds ratio.
*/
// a number that uniquely identifies the rule
int id_;
// the class into which any input matching the condition is
// to be categorized, according to the rule
int classification_;
// the number of examples correctly classified by the rule
double true_positives_;
// the number of examples that the rule matches but does
// not correctly classify
double false_positives_;
// the number of examples that the rule neither matches
// nor correctly classifies
double true_negatives_;
// the number of examples that the rule does not match,
// but that have the same class as the rule
double false_negatives_;
// the number of attributes in the condition of this rule
// whose dont_care_ variable is set to true
int num_dont_care_;
// the first fitness is used to establish a preliminary
// ranking of the rules used to compute the 2nd fitness,
// which drives the GA. This first fitness is calculated
// using odds ratio
double fitness1_;
// the second fitness is also calculated using odds ratio,
// but in computing the 2nd fitness, we count an example
// as a true positive only for the fittest rule that covers
// it
double fitness2_;
};
#endif
|
b84807ec4f9bf5c8c44edee92a962b1f436589c9
|
68e3dbe1bf28683d34446a6d4eb6b18d5ad6abcb
|
/TopicWise Problems/Recurrsion/last index where an element is present.cpp
|
44f90c0b2e8270e2a8f6c488399b9e83b839c111
|
[] |
no_license
|
VyankteshVyas/Competitve-Coding
|
6d7188308eb522caa34ce9e713241a1039557bff
|
da6e79b899b06677599144ed0bd85c9cc7305484
|
refs/heads/master
| 2022-12-29T08:03:02.404891
| 2020-10-20T15:58:51
| 2020-10-20T15:58:51
| 266,714,617
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 391
|
cpp
|
last index where an element is present.cpp
|
#include<bits/stdc++.h>
using namespace std;
int lastindex(int arr[],int currindex,int val){
if(currindex==-1){
return -1;
}
if(arr[currindex]==val) return currindex;
else return lastindex(arr,currindex-1,val);
}
int main(){
int arr[]={5,9,23,9,2};
int res=lastindex(arr,sizeof(arr)/sizeof(int)-1,9);
res!=-1 ? cout<<"present at "<<res : cout<<"not present";
return 0;
}
|
385342cde436213186d24b491a66d661c37f79d3
|
76e7a6908ca1058fad5ca7ed0916721884546242
|
/source/Erwin/core/application.cpp
|
c40b8e073795211193ed03b878d75e110979e362
|
[
"MIT"
] |
permissive
|
ndoxx/erwin
|
9bbb1a0b330d990a1d8a26b9338b8a026c4aa317
|
505884805391feb54e484fbb46277a492a2e65e0
|
refs/heads/master
| 2022-10-29T01:03:42.214948
| 2020-09-24T05:28:48
| 2020-09-24T05:28:48
| 206,838,293
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,936
|
cpp
|
application.cpp
|
#include "core/application.h"
#include "core/clock.hpp"
#include "core/intern_string.h"
#include "core/config.h"
#include "imgui/imgui_layer.h"
#include "input/input.h"
#include "filesystem/filesystem.h"
#include "render/common_geometry.h"
#include "render/renderer.h"
#include "render/renderer_2d.h"
#include "render/renderer_3d.h"
#include "render/renderer_pp.h"
#include "asset/asset_manager.h"
#include "event/window_events.h"
#include "memory/arena.h"
#include "level/scene_manager.h"
#include "level/scene.h"
#include "entity/init.h"
#include "debug/logger.h"
#include "kibble/logger/logger_thread.h"
#include <iostream>
using namespace kb;
namespace erwin
{
Application* Application::pinstance_ = nullptr;
static ImGuiLayer* IMGUI_LAYER = nullptr;
static struct ApplicationStorage
{
std::vector<WPath> configuration_files;
memory::HeapArea client_area;
memory::HeapArea system_area;
memory::HeapArea render_area;
} s_storage;
Application::Application():
vsync_enabled_(false),
is_running_(true),
minimized_(false)
{
// Create application singleton
W_ASSERT(!Application::pinstance_, "Application already exists!");
Application::pinstance_ = this;
KLOGGER_START();
// Initialize file system
wfs::init();
}
void Application::add_configuration(const WPath& filepath)
{
if(filepath.exists())
s_storage.configuration_files.push_back(filepath);
else
{
DLOGW("application") << "Unable to find configuration file:" << std::endl;
DLOGI << "client configuration directory: " << WCC('p') << wfs::get_client_config_dir() << std::endl;
DLOGI << "file path: " << WCC('p') << filepath << std::endl;
}
}
void Application::add_configuration(const WPath& user_path, const WPath& default_path)
{
if(wfs::ensure_user_config(user_path, default_path))
s_storage.configuration_files.push_back(user_path);
else
{
DLOGW("application") << "Unable to find configuration file:" << std::endl;
DLOGI << "file path: " << WCC('p') << user_path << std::endl;
}
}
memory::HeapArea& Application::get_client_area()
{
return s_storage.client_area;
}
const memory::HeapArea& Application::get_system_area()
{
return s_storage.system_area;
}
const memory::HeapArea& Application::get_render_area()
{
return s_storage.render_area;
}
bool Application::init()
{
{
W_PROFILE_SCOPE("Application config")
// Initialize config
cfg::load("syscfg://erwin.xml"_wp);
KLOGGER(set_single_threaded(cfg::get<bool>("erwin.logger.single_threaded"_h, true)));
KLOGGER(set_backtrace_on_error(cfg::get<bool>("erwin.logger.backtrace_on_error"_h, true)));
// Spawn logger thread
KLOGGER(spawn());
KLOGGER(sync());
// Log basic info
DLOGN("config") << "[Paths]" << std::endl;
DLOGI << "Executable path: " << WCC('p') << wfs::get_self_dir() << WCC(0) << std::endl;
DLOGI << "Root dir: " << WCC('p') << wfs::get_root_dir() << WCC(0) << std::endl;
DLOGI << "Config dir: " << WCC('p') << wfs::get_config_dir() << WCC(0) << std::endl;
// Parse intern strings
istr::init();
Input::init();
}
// Initialize system memory
{
W_PROFILE_SCOPE("System memory init")
DLOGN("application") << "Initializing system memory" << std::endl;
size_t system_mem_size = cfg::get<size_t>("erwin.memory.system_area"_h, 10_MB);
if(!s_storage.system_area.init(system_mem_size))
{
DLOGF("application") << "Cannot allocate system memory." << std::endl;
return false;
}
}
// Initialize renderer memory
{
W_PROFILE_SCOPE("Renderer memory init")
DLOGN("application") << "Initializing renderer memory" << std::endl;
size_t renderer_mem_size = cfg::get<size_t>("erwin.memory.renderer_area"_h, 20_MB);
if(!s_storage.render_area.init(renderer_mem_size))
{
DLOGF("application") << "Cannot allocate renderer memory." << std::endl;
return false;
}
}
// Configure client
{
W_PROFILE_SCOPE("Client configuration parsing")
DLOGN("config") << "Parsing client configuration" << std::endl;
on_client_init();
for(auto&& cfg_file: s_storage.configuration_files)
cfg::load(cfg_file);
}
// Initialize client memory
{
W_PROFILE_SCOPE("Client memory init")
DLOGN("application") << "Initializing client memory" << std::endl;
size_t client_mem_size = cfg::get<size_t>("client.memory.area"_h, 1_MB);
if(!s_storage.client_area.init(client_mem_size))
{
DLOGF("application") << "Cannot allocate client memory." << std::endl;
return false;
}
}
// Reflect components
{
W_PROFILE_SCOPE("Components reflection")
entity::init_components();
}
// Create window
{
W_PROFILE_SCOPE("Window creation")
WindowProps props
{
cfg::get<std::string>("client.display.title"_h, "ErwinEngine"),
cfg::get<uint32_t>("client.display.width"_h, 1280),
cfg::get<uint32_t>("client.display.height"_h, 1024),
cfg::get<bool>("client.display.full"_h, false),
cfg::get<bool>("client.display.topmost"_h, false),
cfg::get<bool>("client.display.vsync"_h, true),
cfg::get<bool>("client.display.host"_h, true)
};
#ifdef W_DEBUG
props.title += " [DEBUG]";
#endif
window_ = Window::create(props);
vsync_enabled_ = props.vsync;
}
{
W_PROFILE_SCOPE("Renderer startup")
FramebufferPool::init(window_->get_width(), window_->get_height());
Renderer::init(s_storage.render_area);
AssetManager::create_asset_registry(); // Create engine asset registry (index 0)
CommonGeometry::init();
Renderer2D::init();
Renderer3D::init();
PostProcessingRenderer::init();
}
{
W_PROFILE_SCOPE("ImGui overlay creation")
// Generate ImGui overlay
IMGUI_LAYER = new ImGuiLayer();
IMGUI_LAYER->on_attach();
}
// React to window close events (and shutdown application)
EventBus::subscribe(this, &Application::on_window_close_event);
{
W_PROFILE_SCOPE("Application load")
on_load();
layer_stack_.commit();
}
// Show memory content
#ifdef W_DEBUG
DLOG("memory",1) << WCC(204,153,0) << "--- System memory area ---" << std::endl;
s_storage.system_area.debug_show_content();
DLOG("memory",1) << WCC(204,153,0) << "--- Render memory area ---" << std::endl;
s_storage.render_area.debug_show_content();
DLOG("memory",1) << WCC(204,153,0) << "--- Client memory area ---" << std::endl;
s_storage.client_area.debug_show_content();
#endif
DLOG("application",1) << WCC(0,153,153) << "--- Application base initialized ---" << std::endl;
return true;
}
void Application::shutdown()
{
{
W_PROFILE_SCOPE("Layer stack shutdown")
layer_stack_.clear();
IMGUI_LAYER->on_detach();
}
{
W_PROFILE_SCOPE("Application unloading")
on_unload();
}
{
W_PROFILE_SCOPE("Renderer shutdown")
FramebufferPool::shutdown();
PostProcessingRenderer::shutdown();
Renderer2D::shutdown();
Renderer3D::shutdown();
CommonGeometry::shutdown();
Renderer::shutdown();
}
{
W_PROFILE_SCOPE("Low level systems shutdown")
Input::shutdown();
KLOGGER(kill());
}
}
void Application::enable_vsync(bool value)
{
window_->set_vsync(value);
vsync_enabled_ = value;
}
size_t Application::push_layer(Layer* layer, bool enabled)
{
W_PROFILE_FUNCTION()
size_t index = layer_stack_.push_layer(layer);
layer->set_enabled(enabled);
return index;
}
size_t Application::push_overlay(Layer* layer, bool enabled)
{
W_PROFILE_FUNCTION()
size_t index = layer_stack_.push_overlay(layer);
layer->set_enabled(enabled);
return index;
}
void Application::toggle_imgui_layer()
{
if(IMGUI_LAYER)
IMGUI_LAYER->toggle();
}
void Application::run()
{
DLOG("application",1) << WCC(0,153,153) << "--- Application started ---" << std::endl;
// Display layer stack composition
DLOG("application",1) << WCC(204,0,204) << "Layer stack composition:" << std::endl;
DLOG("application",1) << WCC(204,0,204) << layer_stack_ << std::endl;
// Profiling options
W_PROFILE_ENABLE_SESSION(cfg::get<bool>("erwin.profiling.runtime_session_enabled"_h, false));
nanoClock frame_clock;
frame_clock.restart();
std::chrono::nanoseconds frame_d(16666666);
while(is_running_)
{
// --- EVENT PHASE ---
game_clock_.update(frame_d);
EventBus::enqueue(BeginFrameEvent());
// Dispatch queued events
EventBus::dispatch();
// --- UPDATE PHASE ---
// For each layer, update
{
W_PROFILE_SCOPE("Layer updates")
for(auto* layer: layer_stack_)
layer->update(game_clock_);
}
// Frame config
Renderer::set_host_window_size(window_->get_width(), window_->get_height());
// Asset manager sync work
AssetManager::update();
// --- RENDER PHASE ---
// For each layer, render
if(!minimized_)
{
W_PROFILE_SCOPE("Layer render")
for(auto* layer: layer_stack_)
layer->render();
}
{
#ifndef W_PROFILE_RENDER
W_PROFILE_SCOPE("Renderer flush")
#endif
Renderer::flush();
}
// TODO: move this to renderer
{
W_PROFILE_SCOPE("ImGui render")
if(IMGUI_LAYER->is_enabled())
{
IMGUI_LAYER->begin();
on_imgui_new_frame_();
this->on_imgui_render();
for(auto* layer: layer_stack_)
layer->on_imgui_render();
IMGUI_LAYER->end();
}
}
// --- CLEANUP PHASE ---
if(SceneManager::has_current())
SceneManager::get_current().cleanup();
// Update window
window_->update();
{
W_PROFILE_SCOPE("Logger flush")
KLOGGER(flush());
}
frame_d = frame_clock.restart();
}
// Save all client configuration files
for(auto&& cfg_file: s_storage.configuration_files)
{
DLOGN("application") << "Saving config file:" << std::endl;
DLOGI << WCC('p') << cfg_file << std::endl;
cfg::save(cfg_file);
}
DLOG("application",1) << WCC(0,153,153) << "--- Application stopped ---" << std::endl;
}
bool Application::on_window_close_event(const WindowCloseEvent&)
{
is_running_ = false;
return false;
}
} // namespace erwin
|
807971cb12b6c398778fce39a11b6a3620f7d1b9
|
43704e0722995cb5d94f04c6772ea315734c853e
|
/C++Primer_vs2017/9.26.cpp
|
f47518e69843e29a4746a0e0794e77113caf8c07
|
[] |
no_license
|
lirui233/C-Primer_vs2017
|
fb52e61baeefa25ba9bbb6dda82dd0946633b686
|
88eacaa75e2166e2e38f95be1a6658222997a599
|
refs/heads/master
| 2020-03-18T18:41:16.560775
| 2018-06-19T05:56:00
| 2018-06-19T05:56:00
| 135,107,384
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 610
|
cpp
|
9.26.cpp
|
#include <iostream>
#include <vector>
#include <list>
using namespace std;
int main(void)
{
int a[] = { 0,1,1,2,3,5,8,13,21,55,89 };
vector<int> vec(a, a+11);
list<int> l(a, a+11);
auto iter = vec.begin();
for (;iter != vec.end();)
{
if (0 == (*iter) % 2)
{
iter = vec.erase(iter);
}
else
{
++iter;
}
}
for (auto &x : vec)
{
cout << x << endl;
}
cout << endl;
auto iter2 = l.begin();
for (; iter2 != l.end();)
{
if (*iter2 % 2)
{
iter2 = l.erase(iter2);
}
else
{
iter2++;
}
}
for (auto &x : l)
{
cout << x << endl;
}
system("pause");
return 0;
}
|
3157fa770fa737297c4fe5680583690a4689825d
|
03b5b626962b6c62fc3215154b44bbc663a44cf6
|
/src/instruction/VPERMW.cpp
|
294dfe247e96a5e52f0cbd2d84a824e80accec1e
|
[] |
no_license
|
haochenprophet/iwant
|
8b1f9df8ee428148549253ce1c5d821ece0a4b4c
|
1c9bd95280216ee8cd7892a10a7355f03d77d340
|
refs/heads/master
| 2023-06-09T11:10:27.232304
| 2023-05-31T02:41:18
| 2023-05-31T02:41:18
| 67,756,957
| 17
| 5
| null | 2018-08-11T16:37:37
| 2016-09-09T02:08:46
|
C++
|
UTF-8
|
C++
| false
| false
| 183
|
cpp
|
VPERMW.cpp
|
#include "VPERMW.h"
int CVPERMW::my_init(void *p)
{
this->name = "CVPERMW";
this->alias = "VPERMW";
return 0;
}
CVPERMW::CVPERMW()
{
this->my_init();
}
CVPERMW::~CVPERMW()
{
}
|
33434551c9610d9eef436d85afa9b2acd276b6bc
|
db5664467043ecdf04304ad6e285251c137a803c
|
/codility/NumberOfDiscIntersections/src/utests.cpp
|
561eaa8e7353df3215fa8b497948ec1b1a71629f
|
[] |
no_license
|
sifaserdarozen/CodeTrain
|
0cea53ca59bd0583f878f81680b816681c06a5af
|
1e7aba7383cfba5e3aa55eceab25edf9bfed3499
|
refs/heads/master
| 2023-04-07T01:30:20.505660
| 2023-04-03T18:02:06
| 2023-04-03T18:02:06
| 61,748,291
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,124
|
cpp
|
utests.cpp
|
/** @file utests.cpp
*
* Unit tests are performed with Catch v1.3.5
* More information about catch may be seen at their site https://github.com/philsquared/Catch
*/
#include <vector>
// 3rd party libraries
#define CATCH_CONFIG_MAIN // provides creation of executable, should be above catch.hpp
#include "catch.hpp"
extern int solution(std::vector<int> &A);
TEST_CASE( "Codility tests case", "[solution]" )
{
SECTION( "codility test" )
{
std::vector<int> A = {1, 5, 2, 1, 4, 0};
REQUIRE( 11 == solution(A));
}
}
TEST_CASE( "Extra tests cases", "[solution]" )
{
SECTION( "three same element set" )
{
std::vector<int> A = {1, 1, 1};
REQUIRE( 3 == solution(A));
}
SECTION( "alternating small set" )
{
std::vector<int> A = {1, 0, 1, 0, 1};
REQUIRE( 6 == solution(A));
}
SECTION( "extreme radius set" )
{
std::vector<int> A = {1, 2147483647, 0};
REQUIRE( 2 == solution(A));
}
SECTION( "non intersecting set" )
{
std::vector<int> A = {0, 0, 0};
REQUIRE( 0 == solution(A));
}
}
|
f3c4b05f0da7e5246bf605fd1d36289da590b064
|
00d712168ab09a7be4d77b0c2e0639df13fa2854
|
/CapsEngine/CAPS/Source/Rendering/Devices/PhysicalDevices.cpp
|
c27db41b0dd628e5bdd3eb4448d41a3b5f0436f0
|
[] |
no_license
|
Aladin-Saleh/Moteur-Graphique-Physique
|
4db381ce18b50aa65de4b05a7c1b72a7c1de513b
|
dcbc3e69b056c4d5deeff80575dc6cc811627416
|
refs/heads/main
| 2023-03-16T06:17:54.235711
| 2021-03-16T11:30:37
| 2021-03-16T11:30:37
| 348,312,327
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,843
|
cpp
|
PhysicalDevices.cpp
|
#include "PhysicalDevices.hpp"
#include "SwapChain.hpp"
namespace Ge
{
std::vector<const char*> PhysicalDevices::deviceExtensions =
{
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
bool PhysicalDevices::Initialize(VulkanDeviceMisc * vDM)
{
uint32_t deviceCount = 0;
vkEnumeratePhysicalDevices(vDM->str_instance, &deviceCount, nullptr);//On recupere le nombre de cartes graphique de l'appareil
if (deviceCount == 0)
{
Debug::Error("Vulkan n'a pas r�ussi � trouver de carte graphique qui support l'api Vulkan");
return false;
}
std::vector<VkPhysicalDevice> devices(deviceCount);// creation d'un vector de la taille du nombre de carte graphique
vkEnumeratePhysicalDevices(vDM->str_instance, &deviceCount, devices.data());//recupere toutes les cartes graphiques
m_physicalDevice = VK_NULL_HANDLE;
for (int i = 0; i < devices.size() && m_physicalDevice == VK_NULL_HANDLE; i++)// iteration de toutes les cartes graphiques en selectionnant la meilleur
{
if (isDeviceSuitable(devices[i], vDM))// verification des conditions d'utilisation de la carte graphique
{
m_physicalDevice = devices[i];
vDM->str_physicalDevice = m_physicalDevice;
m_msaaSamples = getMaxUsableSampleCount(vDM);// recuperation du nombre maximal de sample par pixel (anti aliasing)
vDM->str_msaaSamples = m_msaaSamples;
}
}
if (m_physicalDevice == VK_NULL_HANDLE)
{
Debug::Error("Vulkan n'a pas reussi a trouver une carte graphique");
return false;
}
Debug::Info("Initialisation du PhysicalDevices");
vkGetPhysicalDeviceProperties(m_physicalDevice, &m_physicalDeviceProperties);
vDM->str_physicalDeviceProperties = m_physicalDeviceProperties;
Debug::Info("Nom de l'appareil: %s",m_physicalDeviceProperties.deviceName);
return true;
}
void PhysicalDevices::Release()
{
Debug::Info("Liberation du PhysicalDevices");
}
VkSampleCountFlagBits PhysicalDevices::getMaxUsableSampleCount(VulkanDeviceMisc * vDM)
{
VkPhysicalDeviceProperties physicalDeviceProperties;// propri�t� de la carte Graphique
vkGetPhysicalDeviceProperties(vDM->str_physicalDevice, &physicalDeviceProperties);// On recupere les propri�t� de la carte Graphique
VkSampleCountFlags counts = physicalDeviceProperties.limits.framebufferColorSampleCounts & physicalDeviceProperties.limits.framebufferDepthSampleCounts;// on recupere sont �chantillonage maximal valeur recommander par le constructeur de la carte graphique
if (counts & VK_SAMPLE_COUNT_64_BIT) { return VK_SAMPLE_COUNT_64_BIT; }
if (counts & VK_SAMPLE_COUNT_32_BIT) { return VK_SAMPLE_COUNT_32_BIT; }
if (counts & VK_SAMPLE_COUNT_16_BIT) { return VK_SAMPLE_COUNT_16_BIT; }
if (counts & VK_SAMPLE_COUNT_8_BIT) { return VK_SAMPLE_COUNT_8_BIT; }
if (counts & VK_SAMPLE_COUNT_4_BIT) { return VK_SAMPLE_COUNT_4_BIT; }
if (counts & VK_SAMPLE_COUNT_2_BIT) { return VK_SAMPLE_COUNT_2_BIT; }
return VK_SAMPLE_COUNT_1_BIT;//si aucune valeur n'est trouver alors l'echantillonage vaut 1
}
bool PhysicalDevices::isDeviceSuitable(VkPhysicalDevice device, VulkanDeviceMisc * vDM)
{
QueueFamilyIndices indices = PhysicalDevices::findQueueFamilies(device,vDM);//On recupere la famille de queue de la carte graphique Prensent,graphique
bool extensionsSupported = checkDeviceExtensionSupport(device, vDM);//on regarde si l'extention vulkan est supporter par la carte graphique
bool swapChainAdequate = false;
if (extensionsSupported)
{
SwapChainSupportDetails swapChainSupport = SwapChain::querySwapChainSupport(device, vDM);//On regarde si la carte graphique possede
swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();//Si les vecteurs sont vides c'est que la carte graphique na pas une configuration adequate pour faire un rendu
}
VkPhysicalDeviceFeatures supportedFeatures;
vkGetPhysicalDeviceFeatures(device, &supportedFeatures);
return indices.isComplete() && extensionsSupported && swapChainAdequate && supportedFeatures.samplerAnisotropy;
}
bool PhysicalDevices::checkDeviceExtensionSupport(VkPhysicalDevice device, VulkanDeviceMisc * vDM)
{
uint32_t extensionCount;// nombre d'extension suporter
vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr);// on recupere le nombre d'extention
std::vector<VkExtensionProperties> availableExtensions(extensionCount);// on cree un vector pour le nombre d'extention
vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, availableExtensions.data());
std::vector<const char *> deviceExtensions = PhysicalDevices::deviceExtensions;
std::set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end());
for (const auto& extension : availableExtensions)
{
requiredExtensions.erase(extension.extensionName);
}
return requiredExtensions.empty();
}
QueueFamilyIndices PhysicalDevices::findQueueFamilies(VkPhysicalDevice device, VulkanDeviceMisc * vDM)
{
QueueFamilyIndices indices; // structure du physical device
uint32_t queueFamilyCount = 0;//nombre de queue disponible
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr);//recupere le nombre de queue
std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data());
for (int i = 0; i < queueFamilies.size() && !indices.isComplete(); i++)
{
if (queueFamilies[i].queueFlags & VK_QUEUE_GRAPHICS_BIT)
{
indices.graphicsFamily = i;
}
VkBool32 presentSupport = false;
vkGetPhysicalDeviceSurfaceSupportKHR(device, i, vDM->str_surface, &presentSupport);
if (presentSupport)
{
indices.presentFamily = i;
}
}
return indices;
}
uint32_t PhysicalDevices::getGraphiqueIndexFamily(VkPhysicalDevice device)
{
QueueFamilyIndices indices;
uint32_t queueFamilyCount = 0;//nombre de queue disponible
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr);//recupere le nombre de queue
std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data());
for (int i = 0; i < queueFamilies.size() && !indices.isComplete(); i++)
{
if (queueFamilies[i].queueFlags & VK_QUEUE_GRAPHICS_BIT)
{
return i;
}
}
return -1;
}
std::vector<const char*> PhysicalDevices::getDeviceExtensions()
{
return PhysicalDevices::deviceExtensions;
}
uint32_t PhysicalDevices::getCountQueueFamily(VkPhysicalDevice device)
{
QueueFamilyIndices indices; // structure du physical device
uint32_t queueFamilyCount = 0;//nombre de queue disponible
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr);//recupere le nombre de queue
return queueFamilyCount;
}
}
|
6a235a45ab9c94a310d8a6faedbde67b1435cfc7
|
06ed93d4541a1531e75a9a3906f7da540ec0ecc6
|
/softbankRobotics/choregraphe-suite-2.5.5.5-linux64/share/doc/dev/cpp/examples/sensors/fastgetsetdcm/fastgetsetdcm.cpp
|
ee0b958d0d0479c952125035834dbd59da2b770c
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
Cmathou/S8-Simulated-Pepper-Project
|
8dc38c64dcf1f9d22acd2cd4dff501cd4cda95c6
|
a4fb90f1c59c50354c689a37c3977f7d89f699d1
|
refs/heads/master
| 2020-05-27T21:04:22.050455
| 2019-06-11T13:22:52
| 2019-06-11T13:22:52
| 188,784,416
| 0
| 1
|
MIT
| 2019-05-27T06:31:23
| 2019-05-27T06:31:22
| null |
UTF-8
|
C++
| false
| false
| 17,628
|
cpp
|
fastgetsetdcm.cpp
|
/// <summary>
/// Example module to use fast method to get/set joints every 10ms with minimum delays.
/// </summary>
#include "fastgetsetdcm.h"
#include <boost/shared_ptr.hpp>
#include <alcommon/alproxy.h>
#include <alcommon/albroker.h>
#include <alcommon/almodule.h>
#include <alerror/alerror.h>
// Use DCM proxy
#include <alproxies/dcmproxy.h>
// Used to read values of ALMemory directly in RAM
#include <almemoryfastaccess/almemoryfastaccess.h>
#include <boost/bind.hpp>
/// <summary>
/// Example module to use fast method to get/set joints every 10ms with minimum delays.
/// </summary>
/// <param name="broker"> A smart pointer to the broker.</param>
/// <param name="name"> The name of the module. </param>
FastGetSetDCM::FastGetSetDCM(boost::shared_ptr<AL::ALBroker> broker,
const std::string &name )
: AL::ALModule(broker, name )
, fMemoryFastAccess(boost::shared_ptr<AL::ALMemoryFastAccess>(new AL::ALMemoryFastAccess()))
{
setModuleDescription( "Example module to use fast method to get/set joints every 10ms with minimum delays." );
functionName("startLoop", getName() , "start");
BIND_METHOD(FastGetSetDCM::startLoop);
functionName("stopLoop", getName() , "stop");
BIND_METHOD(FastGetSetDCM::stopLoop);
functionName("setStiffness" , getName(),
"change stiffness of all joint");
addParam("value", "new stiffness value from 0.0 to 1.0");
BIND_METHOD(FastGetSetDCM::setStiffness);
// start the example.
// You can remove it and call FastGetSetDCM.startLoop() to start instead.
startLoop();
}
FastGetSetDCM::~FastGetSetDCM()
{
stopLoop();
}
// Start the example
void FastGetSetDCM::startLoop()
{
signed long isDCMRunning;
try
{
// Get the DCM proxy
dcmProxy = getParentBroker()->getDcmProxy();
}
catch (AL::ALError& e)
{
throw ALERROR(getName(), "startLoop()", "Impossible to create DCM Proxy : " + e.toString());
}
// Is the DCM running ?
try
{
isDCMRunning = getParentBroker()->getProxy("ALLauncher")->call<bool>("isModulePresent", std::string("DCM"));
}
catch (AL::ALError& e)
{
throw ALERROR(getName(), "startLoop()", "Error when connecting to DCM : " + e.toString());
}
if (!isDCMRunning)
{
throw ALERROR(getName(), "startLoop()", "Error no DCM running ");
}
init();
connectToDCMloop();
}
// Stop the example
void FastGetSetDCM::stopLoop()
{
setStiffness(0.0f);
// Remove the postProcess call back connection
fDCMPostProcessConnection.disconnect();
}
// Initialisation of ALmemory fast access, DCM commands, Alias, stiffness, ...
void FastGetSetDCM::init()
{
initFastAccess();
createPositionActuatorAlias();
createHardnessActuatorAlias();
setStiffness(0.2f); // Set to 1.0 for maximum stiffness, but only after a test
preparePositionActuatorCommand();
}
// ALMemory fast access
void FastGetSetDCM::initFastAccess()
{
fSensorKeys.clear();
// Here as an example inertial + joints + FSR are read
fSensorKeys.resize(7 + 25 + 6);
// Joints Sensor list
fSensorKeys[HEAD_PITCH] = std::string("Device/SubDeviceList/HeadPitch/Position/Sensor/Value");
fSensorKeys[HEAD_YAW] = std::string("Device/SubDeviceList/HeadYaw/Position/Sensor/Value");
fSensorKeys[L_ANKLE_PITCH] = std::string("Device/SubDeviceList/LAnklePitch/Position/Sensor/Value");
fSensorKeys[L_ANKLE_ROLL] = std::string("Device/SubDeviceList/LAnkleRoll/Position/Sensor/Value");
fSensorKeys[L_ELBOW_ROLL] = std::string("Device/SubDeviceList/LElbowRoll/Position/Sensor/Value");
fSensorKeys[L_ELBOW_YAW] = std::string("Device/SubDeviceList/LElbowYaw/Position/Sensor/Value");
fSensorKeys[L_HAND] = std::string("Device/SubDeviceList/LHand/Position/Sensor/Value");
fSensorKeys[L_HIP_PITCH] = std::string("Device/SubDeviceList/LHipPitch/Position/Sensor/Value");
fSensorKeys[L_HIP_ROLL] = std::string("Device/SubDeviceList/LHipRoll/Position/Sensor/Value");
fSensorKeys[L_HIP_YAW_PITCH] = std::string("Device/SubDeviceList/LHipYawPitch/Position/Sensor/Value");
fSensorKeys[L_KNEE_PITCH] = std::string("Device/SubDeviceList/LKneePitch/Position/Sensor/Value");
fSensorKeys[L_SHOULDER_PITCH] = std::string("Device/SubDeviceList/LShoulderPitch/Position/Sensor/Value");
fSensorKeys[L_SHOULDER_ROLL] = std::string("Device/SubDeviceList/LShoulderRoll/Position/Sensor/Value");
fSensorKeys[L_WRIST_YAW] = std::string("Device/SubDeviceList/LWristYaw/Position/Sensor/Value");
fSensorKeys[R_ANKLE_PITCH] = std::string("Device/SubDeviceList/RAnklePitch/Position/Sensor/Value");
fSensorKeys[R_ANKLE_ROLL] = std::string("Device/SubDeviceList/RAnkleRoll/Position/Sensor/Value");
fSensorKeys[R_ELBOW_ROLL] = std::string("Device/SubDeviceList/RElbowRoll/Position/Sensor/Value");
fSensorKeys[R_ELBOW_YAW] = std::string("Device/SubDeviceList/RElbowYaw/Position/Sensor/Value");
fSensorKeys[R_HAND] = std::string("Device/SubDeviceList/RHand/Position/Sensor/Value");
fSensorKeys[R_HIP_PITCH] = std::string("Device/SubDeviceList/RHipPitch/Position/Sensor/Value");
fSensorKeys[R_HIP_ROLL] = std::string("Device/SubDeviceList/RHipRoll/Position/Sensor/Value");
fSensorKeys[R_KNEE_PITCH] = std::string("Device/SubDeviceList/RKneePitch/Position/Sensor/Value");
fSensorKeys[R_SHOULDER_PITCH] = std::string("Device/SubDeviceList/RShoulderPitch/Position/Sensor/Value");
fSensorKeys[R_SHOULDER_ROLL] = std::string("Device/SubDeviceList/RShoulderRoll/Position/Sensor/Value");
fSensorKeys[R_WRIST_YAW] = std::string("Device/SubDeviceList/RWristYaw/Position/Sensor/Value");
// Inertial sensors
fSensorKeys[ACC_X] = std::string("Device/SubDeviceList/InertialSensor/AccX/Sensor/Value");
fSensorKeys[ACC_Y] = std::string("Device/SubDeviceList/InertialSensor/AccY/Sensor/Value");
fSensorKeys[ACC_Z] = std::string("Device/SubDeviceList/InertialSensor/AccZ/Sensor/Value");
fSensorKeys[GYR_X] = std::string("Device/SubDeviceList/InertialSensor/GyrX/Sensor/Value");
fSensorKeys[GYR_Y] = std::string("Device/SubDeviceList/InertialSensor/GyrY/Sensor/Value");
fSensorKeys[ANGLE_X] = std::string("Device/SubDeviceList/InertialSensor/AngleX/Sensor/Value");
fSensorKeys[ANGLE_Y] = std::string("Device/SubDeviceList/InertialSensor/AngleY/Sensor/Value");
// Some FSR sensors
fSensorKeys[L_COP_X] = std::string("Device/SubDeviceList/LFoot/FSR/CenterOfPressure/X/Sensor/Value");
fSensorKeys[L_COP_Y] = std::string("Device/SubDeviceList/LFoot/FSR/CenterOfPressure/Y/Sensor/Value");
fSensorKeys[L_TOTAL_WEIGHT] = std::string("Device/SubDeviceList/LFoot/FSR/TotalWeight/Sensor/Value");
fSensorKeys[R_COP_X] = std::string("Device/SubDeviceList/RFoot/FSR/CenterOfPressure/X/Sensor/Value");
fSensorKeys[R_COP_Y] = std::string("Device/SubDeviceList/RFoot/FSR/CenterOfPressure/Y/Sensor/Value");
fSensorKeys[R_TOTAL_WEIGHT] = std::string("Device/SubDeviceList/RFoot/FSR/TotalWeight/Sensor/Value");
// Create the fast memory access
fMemoryFastAccess->ConnectToVariables(getParentBroker(), fSensorKeys, false);
}
void FastGetSetDCM::createPositionActuatorAlias()
{
AL::ALValue jointAliasses;
jointAliasses.arraySetSize(2);
jointAliasses[0] = std::string("jointActuator"); // Alias for all 25 joint actuators
jointAliasses[1].arraySetSize(25);
// Joints actuator list
jointAliasses[1][HEAD_PITCH] = std::string("Device/SubDeviceList/HeadPitch/Position/Actuator/Value");
jointAliasses[1][HEAD_YAW] = std::string("Device/SubDeviceList/HeadYaw/Position/Actuator/Value");
jointAliasses[1][L_ANKLE_PITCH] = std::string("Device/SubDeviceList/LAnklePitch/Position/Actuator/Value");
jointAliasses[1][L_ANKLE_ROLL] = std::string("Device/SubDeviceList/LAnkleRoll/Position/Actuator/Value");
jointAliasses[1][L_ELBOW_ROLL] = std::string("Device/SubDeviceList/LElbowRoll/Position/Actuator/Value");
jointAliasses[1][L_ELBOW_YAW] = std::string("Device/SubDeviceList/LElbowYaw/Position/Actuator/Value");
jointAliasses[1][L_HAND] = std::string("Device/SubDeviceList/LHand/Position/Actuator/Value");
jointAliasses[1][L_HIP_PITCH] = std::string("Device/SubDeviceList/LHipPitch/Position/Actuator/Value");
jointAliasses[1][L_HIP_ROLL] = std::string("Device/SubDeviceList/LHipRoll/Position/Actuator/Value");
jointAliasses[1][L_HIP_YAW_PITCH] = std::string("Device/SubDeviceList/LHipYawPitch/Position/Actuator/Value");
jointAliasses[1][L_KNEE_PITCH] = std::string("Device/SubDeviceList/LKneePitch/Position/Actuator/Value");
jointAliasses[1][L_SHOULDER_PITCH] = std::string("Device/SubDeviceList/LShoulderPitch/Position/Actuator/Value");
jointAliasses[1][L_SHOULDER_ROLL] = std::string("Device/SubDeviceList/LShoulderRoll/Position/Actuator/Value");
jointAliasses[1][L_WRIST_YAW] = std::string("Device/SubDeviceList/LWristYaw/Position/Actuator/Value");
jointAliasses[1][R_ANKLE_PITCH] = std::string("Device/SubDeviceList/RAnklePitch/Position/Actuator/Value");
jointAliasses[1][R_ANKLE_ROLL] = std::string("Device/SubDeviceList/RAnkleRoll/Position/Actuator/Value");
jointAliasses[1][R_ELBOW_ROLL] = std::string("Device/SubDeviceList/RElbowRoll/Position/Actuator/Value");
jointAliasses[1][R_ELBOW_YAW] = std::string("Device/SubDeviceList/RElbowYaw/Position/Actuator/Value");
jointAliasses[1][R_HAND] = std::string("Device/SubDeviceList/RHand/Position/Actuator/Value");
jointAliasses[1][R_HIP_PITCH] = std::string("Device/SubDeviceList/RHipPitch/Position/Actuator/Value");
jointAliasses[1][R_HIP_ROLL] = std::string("Device/SubDeviceList/RHipRoll/Position/Actuator/Value");
jointAliasses[1][R_KNEE_PITCH] = std::string("Device/SubDeviceList/RKneePitch/Position/Actuator/Value");
jointAliasses[1][R_SHOULDER_PITCH] = std::string("Device/SubDeviceList/RShoulderPitch/Position/Actuator/Value");
jointAliasses[1][R_SHOULDER_ROLL] = std::string("Device/SubDeviceList/RShoulderRoll/Position/Actuator/Value");
jointAliasses[1][R_WRIST_YAW] = std::string("Device/SubDeviceList/RWristYaw/Position/Actuator/Value");
// Create alias
try
{
dcmProxy->createAlias(jointAliasses);
}
catch (const AL::ALError &e)
{
throw ALERROR(getName(), "createPositionActuatorAlias()", "Error when creating Alias : " + e.toString());
}
}
void FastGetSetDCM::createHardnessActuatorAlias()
{
AL::ALValue jointAliasses;
// Alias for all joint stiffness
jointAliasses.clear();
jointAliasses.arraySetSize(2);
jointAliasses[0] = std::string("jointStiffness"); // Alias for all 25 actuators
jointAliasses[1].arraySetSize(25);
// stiffness list
jointAliasses[1][HEAD_PITCH] = std::string("Device/SubDeviceList/HeadPitch/Hardness/Actuator/Value");
jointAliasses[1][HEAD_YAW] = std::string("Device/SubDeviceList/HeadYaw/Hardness/Actuator/Value");
jointAliasses[1][L_ANKLE_PITCH] = std::string("Device/SubDeviceList/LAnklePitch/Hardness/Actuator/Value");
jointAliasses[1][L_ANKLE_ROLL] = std::string("Device/SubDeviceList/LAnkleRoll/Hardness/Actuator/Value");
jointAliasses[1][L_ELBOW_ROLL] = std::string("Device/SubDeviceList/LElbowRoll/Hardness/Actuator/Value");
jointAliasses[1][L_ELBOW_YAW] = std::string("Device/SubDeviceList/LElbowYaw/Hardness/Actuator/Value");
jointAliasses[1][L_HAND] = std::string("Device/SubDeviceList/LHand/Hardness/Actuator/Value");
jointAliasses[1][L_HIP_PITCH] = std::string("Device/SubDeviceList/LHipPitch/Hardness/Actuator/Value");
jointAliasses[1][L_HIP_ROLL] = std::string("Device/SubDeviceList/LHipRoll/Hardness/Actuator/Value");
jointAliasses[1][L_HIP_YAW_PITCH] = std::string("Device/SubDeviceList/LHipYawPitch/Hardness/Actuator/Value");
jointAliasses[1][L_KNEE_PITCH] = std::string("Device/SubDeviceList/LKneePitch/Hardness/Actuator/Value");
jointAliasses[1][L_SHOULDER_PITCH] = std::string("Device/SubDeviceList/LShoulderPitch/Hardness/Actuator/Value");
jointAliasses[1][L_SHOULDER_ROLL] = std::string("Device/SubDeviceList/LShoulderRoll/Hardness/Actuator/Value");
jointAliasses[1][L_WRIST_YAW] = std::string("Device/SubDeviceList/LWristYaw/Hardness/Actuator/Value");
jointAliasses[1][R_ANKLE_PITCH] = std::string("Device/SubDeviceList/RAnklePitch/Hardness/Actuator/Value");
jointAliasses[1][R_ANKLE_ROLL] = std::string("Device/SubDeviceList/RAnkleRoll/Hardness/Actuator/Value");
jointAliasses[1][R_ELBOW_ROLL] = std::string("Device/SubDeviceList/RElbowRoll/Hardness/Actuator/Value");
jointAliasses[1][R_ELBOW_YAW] = std::string("Device/SubDeviceList/RElbowYaw/Hardness/Actuator/Value");
jointAliasses[1][R_HAND] = std::string("Device/SubDeviceList/RHand/Hardness/Actuator/Value");
jointAliasses[1][R_HIP_PITCH] = std::string("Device/SubDeviceList/RHipPitch/Hardness/Actuator/Value");
jointAliasses[1][R_HIP_ROLL] = std::string("Device/SubDeviceList/RHipRoll/Hardness/Actuator/Value");
jointAliasses[1][R_KNEE_PITCH] = std::string("Device/SubDeviceList/RKneePitch/Hardness/Actuator/Value");
jointAliasses[1][R_SHOULDER_PITCH] = std::string("Device/SubDeviceList/RShoulderPitch/Hardness/Actuator/Value");
jointAliasses[1][R_SHOULDER_ROLL] = std::string("Device/SubDeviceList/RShoulderRoll/Hardness/Actuator/Value");
jointAliasses[1][R_WRIST_YAW] = std::string("Device/SubDeviceList/RWristYaw/Hardness/Actuator/Value");
// Create alias
try
{
dcmProxy->createAlias(jointAliasses);
}
catch (const AL::ALError &e)
{
throw ALERROR(getName(), "createHardnessActuatorAlias()", "Error when creating Alias : " + e.toString());
}
}
void FastGetSetDCM::preparePositionActuatorCommand()
{
commands.arraySetSize(6);
commands[0] = std::string("jointActuator");
commands[1] = std::string("ClearAll"); // Erase all previous commands
commands[2] = std::string("time-separate");
commands[3] = 0;
commands[4].arraySetSize(1);
//commands[4][0] Will be the new time
commands[5].arraySetSize(25); // For all joints
for (int i=0; i<25; i++)
{
commands[5][i].arraySetSize(1);
//commands[5][i][0] will be the new angle
}
}
void FastGetSetDCM::setStiffness(const float &stiffnessValue)
{
AL::ALValue stiffnessCommands;
int DCMtime;
// increase stiffness with the "jointStiffness" Alias created at initialisation
try
{
// Get time : return the time in 1 seconde
DCMtime = dcmProxy->getTime(1000);
}
catch (const AL::ALError &e)
{
throw ALERROR(getName(), "setStiffness()", "Error on DCM getTime : " + e.toString());
}
// Prepare one dcm command:
// it will linearly "Merge" all joint stiffness
// from last value to "stiffnessValue" in 1 seconde
stiffnessCommands.arraySetSize(3);
stiffnessCommands[0] = std::string("jointStiffness");
stiffnessCommands[1] = std::string("Merge");
stiffnessCommands[2].arraySetSize(1);
stiffnessCommands[2][0].arraySetSize(2);
stiffnessCommands[2][0][0] = stiffnessValue;
stiffnessCommands[2][0][1] = DCMtime;
try
{
dcmProxy->set(stiffnessCommands);
}
catch (const AL::ALError &e)
{
throw ALERROR(getName(), "setStiffness()", "Error when sending stiffness to DCM : " + e.toString());
}
}
void FastGetSetDCM::connectToDCMloop()
{
// Get all values from ALMemory using fastaccess
fMemoryFastAccess->GetValues(sensorValues);
// Save all sensor position for the sensor=actuator test
for (int i=0; i<25; i++)
{
initialJointSensorValues.push_back(sensorValues[i]);
}
// Connect callback to the DCM post proccess
try
{
fDCMPostProcessConnection =
getParentBroker()->getProxy("DCM")->getModule()->atPostProcess(boost::bind(&FastGetSetDCM::synchronisedDCMcallback, this));
}
catch (const AL::ALError &e)
{
throw ALERROR(getName(), "connectToDCMloop()", "Error when connecting to DCM postProccess: " + e.toString());
}
}
/**
* WARNING
*
* Once this method is connected to DCM postprocess
* it will be called in Real Time every 10 milliseconds from DCM thread
* Dynamic allocation and system call are strictly forbidden in this method
* Computation time in this section must remain as short as possible to prevent
* erratic move or joint getting loose.
*
*/
// Send the new values of all joints to the DCM.
// Note : a joint could be ignore unsing a NAN value.
// Note : do not forget to set stiffness
void FastGetSetDCM::synchronisedDCMcallback()
{
int DCMtime;
try
{
// Get absolute time, at 0 ms in the future ( i.e. now )
DCMtime = dcmProxy->getTime(0);
}
catch (const AL::ALError &e)
{
throw ALERROR(getName(), "synchronisedDCMcallback()", "Error on DCM getTime : " + e.toString());
}
commands[4][0] = DCMtime; // To be used in the next cycle
for (int i=0; i<25; i++)
{
// new actuator value = first Sensor value
commands[5][i][0] = initialJointSensorValues[i];
}
// Uncomment this to activate
// Left Arm mirror Right Arm
// Get all values from ALMemory using fastaccess
fMemoryFastAccess->GetValues(sensorValues);
commands[5][L_SHOULDER_PITCH][0] = sensorValues[R_SHOULDER_PITCH];
commands[5][L_SHOULDER_ROLL][0] = - sensorValues[R_SHOULDER_ROLL];
commands[5][L_ELBOW_YAW][0] = - sensorValues[R_ELBOW_YAW];
commands[5][L_ELBOW_ROLL][0] = - sensorValues[R_ELBOW_ROLL];
try
{
dcmProxy->setAlias(commands);
}
catch (const AL::ALError &e)
{
throw ALERROR(getName(), "synchronisedDCMcallback()", "Error when sending command to DCM : " + e.toString());
}
}
|
3889c91301199c4282c16e2eccc66fec7f267008
|
35c836ed4b443a8f2a5076edf25e8a00b1b93203
|
/WebKit2-7606.2.104.1.1/WebKit2-7606.2.104.1.1/UIProcess/Plugins/PluginInfoStore.cpp
|
b9463150e08542b6784b6bf6fed71f74ce32b8a1
|
[
"MIT"
] |
permissive
|
mlcldh/appleWebKit2
|
e3260c49e7bf82bf70617841868af81fc32c5d9f
|
39cc42a4710c9319c8da269621844493ab2ccdd6
|
refs/heads/master
| 2021-06-12T05:52:05.942098
| 2021-05-27T07:27:38
| 2021-05-27T07:27:38
| 190,697,531
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,726
|
cpp
|
PluginInfoStore.cpp
|
/*
* Copyright (C) 2010, 2012 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "PluginInfoStore.h"
#if ENABLE(NETSCAPE_PLUGIN_API)
#include "PluginModuleInfo.h"
#include <WebCore/MIMETypeRegistry.h>
#include <WebCore/SecurityOrigin.h>
#include <WebCore/URL.h>
#include <algorithm>
#include <wtf/ListHashSet.h>
#include <wtf/StdLibExtras.h>
using namespace WebCore;
namespace WebKit {
PluginInfoStore::PluginInfoStore()
: m_pluginListIsUpToDate(false)
{
}
void PluginInfoStore::setAdditionalPluginsDirectories(const Vector<String>& directories)
{
m_additionalPluginsDirectories = directories;
refresh();
}
void PluginInfoStore::refresh()
{
m_pluginListIsUpToDate = false;
}
template <typename T, typename U>
static void addFromVector(T& hashSet, const U& vector)
{
for (size_t i = 0; i < vector.size(); ++i)
hashSet.add(vector[i]);
}
void PluginInfoStore::loadPluginsIfNecessary()
{
if (m_pluginListIsUpToDate)
return;
ListHashSet<String> uniquePluginPaths;
// First, load plug-ins from the additional plug-ins directories specified.
for (size_t i = 0; i < m_additionalPluginsDirectories.size(); ++i)
addFromVector(uniquePluginPaths, pluginPathsInDirectory(m_additionalPluginsDirectories[i]));
// Then load plug-ins from the standard plug-ins directories.
Vector<String> directories = pluginsDirectories();
for (size_t i = 0; i < directories.size(); ++i)
addFromVector(uniquePluginPaths, pluginPathsInDirectory(directories[i]));
// Then load plug-ins that are not in the standard plug-ins directories.
addFromVector(uniquePluginPaths, individualPluginPaths());
m_plugins.clear();
for (const auto& pluginPath : uniquePluginPaths)
loadPlugin(m_plugins, pluginPath);
m_pluginListIsUpToDate = true;
}
void PluginInfoStore::loadPlugin(Vector<PluginModuleInfo>& plugins, const String& pluginPath)
{
PluginModuleInfo plugin;
if (!getPluginInfo(pluginPath, plugin))
return;
if (!shouldUsePlugin(plugins, plugin))
return;
plugins.append(plugin);
}
Vector<PluginModuleInfo> PluginInfoStore::plugins()
{
loadPluginsIfNecessary();
return m_plugins;
}
PluginModuleInfo PluginInfoStore::findPluginForMIMEType(const String& mimeType, PluginData::AllowedPluginTypes allowedPluginTypes) const
{
ASSERT(!mimeType.isNull());
for (const auto& plugin : m_plugins) {
if (allowedPluginTypes == PluginData::OnlyApplicationPlugins && !plugin.info.isApplicationPlugin)
continue;
for (const auto& mimeClassInfo : plugin.info.mimes) {
if (mimeClassInfo.type == mimeType)
return plugin;
}
}
return PluginModuleInfo();
}
PluginModuleInfo PluginInfoStore::findPluginForExtension(const String& extension, String& mimeType, PluginData::AllowedPluginTypes allowedPluginTypes) const
{
ASSERT(!extension.isNull());
for (const auto& plugin : m_plugins) {
if (allowedPluginTypes == PluginData::OnlyApplicationPlugins && !plugin.info.isApplicationPlugin)
continue;
for (const auto& mimeClassInfo : plugin.info.mimes) {
if (mimeClassInfo.extensions.contains(extension)) {
// We found a supported extension, set the correct MIME type.
mimeType = mimeClassInfo.type;
return plugin;
}
}
}
return PluginModuleInfo();
}
static inline String pathExtension(const URL& url)
{
String extension;
String filename = url.lastPathComponent();
if (!filename.endsWith('/')) {
size_t extensionPos = filename.reverseFind('.');
if (extensionPos != notFound)
extension = filename.substring(extensionPos + 1);
}
return extension.convertToASCIILowercase();
}
#if !PLATFORM(COCOA)
bool PluginInfoStore::shouldAllowPluginToRunUnsandboxed(const String& pluginBundleIdentifier)
{
UNUSED_PARAM(pluginBundleIdentifier);
return false;
}
PluginModuleLoadPolicy PluginInfoStore::defaultLoadPolicyForPlugin(const PluginModuleInfo&)
{
return PluginModuleLoadNormally;
}
PluginModuleInfo PluginInfoStore::findPluginWithBundleIdentifier(const String&)
{
ASSERT_NOT_REACHED();
return PluginModuleInfo();
}
#endif
PluginModuleInfo PluginInfoStore::findPlugin(String& mimeType, const URL& url, PluginData::AllowedPluginTypes allowedPluginTypes)
{
loadPluginsIfNecessary();
// First, check if we can get the plug-in based on its MIME type.
if (!mimeType.isNull()) {
PluginModuleInfo plugin = findPluginForMIMEType(mimeType, allowedPluginTypes);
if (!plugin.path.isNull())
return plugin;
}
// Next, check if any plug-ins claim to support the URL extension.
String extension = pathExtension(url);
if (!extension.isNull() && mimeType.isEmpty()) {
PluginModuleInfo plugin = findPluginForExtension(extension, mimeType, allowedPluginTypes);
if (!plugin.path.isNull())
return plugin;
// Finally, try to get the MIME type from the extension in a platform specific manner and use that.
String extensionMimeType = MIMETypeRegistry::getMIMETypeForExtension(extension);
if (!extensionMimeType.isNull()) {
PluginModuleInfo plugin = findPluginForMIMEType(extensionMimeType, allowedPluginTypes);
if (!plugin.path.isNull()) {
mimeType = extensionMimeType;
return plugin;
}
}
}
return PluginModuleInfo();
}
bool PluginInfoStore::isSupportedPlugin(const PluginInfoStore::SupportedPlugin& plugin, const String& mimeType, const URL& pluginURL)
{
if (!mimeType.isEmpty() && plugin.mimeTypes.contains(mimeType))
return true;
auto extension = pathExtension(pluginURL);
return extension.isEmpty() ? false : plugin.extensions.contains(extension);
}
bool PluginInfoStore::isSupportedPlugin(const String& mimeType, const URL& pluginURL, const String&, const URL& pageURL)
{
// We check only pageURL for consistency with WebProcess visible plugins.
if (!m_supportedPlugins)
return true;
return m_supportedPlugins->findMatching([&] (auto&& plugin) {
return pageURL.isMatchingDomain(plugin.matchingDomain) && isSupportedPlugin(plugin, mimeType, pluginURL);
}) != notFound;
}
std::optional<Vector<SupportedPluginIdentifier>> PluginInfoStore::supportedPluginIdentifiers()
{
if (!m_supportedPlugins)
return std::nullopt;
return WTF::map(*m_supportedPlugins, [] (auto&& item) {
return SupportedPluginIdentifier { item.matchingDomain, item.identifier };
});
}
void PluginInfoStore::addSupportedPlugin(String&& domainName, String&& identifier, HashSet<String>&& mimeTypes, HashSet<String> extensions)
{
if (!m_supportedPlugins)
m_supportedPlugins = Vector<SupportedPlugin> { };
m_supportedPlugins->append(SupportedPlugin { WTFMove(domainName), WTFMove(identifier), WTFMove(mimeTypes), WTFMove(extensions) });
}
PluginModuleInfo PluginInfoStore::infoForPluginWithPath(const String& pluginPath) const
{
for (const auto& plugin : m_plugins) {
if (plugin.path == pluginPath)
return plugin;
}
ASSERT_NOT_REACHED();
return PluginModuleInfo();
}
} // namespace WebKit
#endif // ENABLE(NETSCAPE_PLUGIN_API)
|
fa4e86349f258334341b3f21407217aeee85cd1b
|
82dc3cc4c97c05e384812cc9aa07938e2dbfe24b
|
/toolbox/src/C1functions/SF2.h
|
bb358ccc9bd9528d7e4dd8f2ffa37b111e687fd6
|
[
"BSD-3-Clause"
] |
permissive
|
samanseifi/Tahoe
|
ab40da0f8d952491943924034fa73ee5ecb2fecd
|
542de50ba43645f19ce4b106ac8118c4333a3f25
|
refs/heads/master
| 2020-04-05T20:24:36.487197
| 2017-12-02T17:09:11
| 2017-12-02T17:24:23
| 38,074,546
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,577
|
h
|
SF2.h
|
/* $Id: SF2.h,v 1.3 2004/06/19 23:27:18 paklein Exp $ */
#ifndef _SF2_H_
#define _SF2_H_
/* base class */
#include "C1FunctionT.h"
namespace Tahoe{
/** cohesive force law
* The force is given by
\f[
F(dr) = A dr \exp \left[ -\frac{dr^2}{B} \right]
\f]
* where \f$ dr = l - l_0 \f$. */
class SF2: public C1FunctionT
{
public:
/* constructor */
SF2(double A, double B, double l_0 = 1.0);
SF2(void);
/* I/O */
virtual void Print(ostream& out) const;
virtual void PrintName(ostream& out) const;
/* returning values */
virtual double Function(double x) const;
virtual double DFunction(double x) const;
virtual double DDFunction(double x) const;
/** returning values in groups - derived classes should define
* their own non-virtual function called within this functon
* which maps in to out w/o requiring a virtual function call
* everytime. Default behavior is just to map the virtual functions
* above.
*/
virtual dArrayT& MapFunction(const dArrayT& in, dArrayT& out) const;
virtual dArrayT& MapDFunction(const dArrayT& in, dArrayT& out) const;
virtual dArrayT& MapDDFunction(const dArrayT& in, dArrayT& out) const;
/** \name implementation of the ParameterInterfaceT interface */
/*@{*/
/** describe the parameters needed by the interface */
virtual void DefineParameters(ParameterListT& list) const;
/** accept parameter list */
virtual void TakeParameterList(const ParameterListT& list);
/*@{*/
private:
/* potential parameters */
double fA;
double fB;
double fl_0; //equilibrium length
};
}
#endif /* _SMITH_FERRANTE_H_ */
|
ab7576efcb20e67aa33c127faa88dc6ca6c2feb7
|
e85b32d0d4824f6733506bd041f8dd3102c56fa3
|
/imebra/library/base/include/baseStream.h
|
f4310283e1649e77d6158b6680d29da9ad695c14
|
[] |
no_license
|
miyako/4d-plugin-imebra
|
75a10aa8801fe5a3bddd61a8d80da5ea8b8455c5
|
fc0172da34db28bad8521a667e4c7cdc5641e9c9
|
refs/heads/master
| 2021-01-10T18:30:29.231868
| 2017-11-13T02:38:31
| 2017-11-13T02:38:31
| 18,977,094
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,516
|
h
|
baseStream.h
|
/*
Imebra 2011 build 2011-09-18_22-24-41
Imebra: a C++ Dicom library
Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 by Paolo Brandoli
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE FREEBSD PROJECT ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FREEBSD PROJECT OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those of the authors
and should not be interpreted as representing official policies, either expressed or implied,
of the Imebra Project.
Imebra is available at http://imebra.com
*/
/*! \file baseStream.h
\brief Declaration of the the base class for the streams (memory, file, ...)
used by the puntoexe library.
*/
#if !defined(imebraBaseStream_3146DA5A_5276_4804_B9AB_A3D54C6B123A__INCLUDED_)
#define imebraBaseStream_3146DA5A_5276_4804_B9AB_A3D54C6B123A__INCLUDED_
#include "baseObject.h"
#include "../include/exception.h"
#include <vector>
#include <map>
#include <stdexcept>
///////////////////////////////////////////////////////////
//
// Everything is in the namespace puntoexe
//
///////////////////////////////////////////////////////////
namespace puntoexe
{
/// \addtogroup group_baseclasses
///
/// @{
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
/// \brief This class represents a stream.
///
/// Specialized classes derived from this class can
/// read/write from/to files stored on the computer's
/// disks, on the network or in memory.
///
/// The application can read or write into the stream
/// by using the streamReader or the streamWriter.
///
/// While this class can be used across several threads,
/// the streamReader and the streamWriter can be used in
/// one thread only. This is not a big deal, since one
/// stream can be connected to several streamReaders and
/// streamWriters.
///
/// The library supplies two specialized streams derived
/// from this class:
/// - puntoexe::stream (used to read or write into physical
/// files)
/// - puntoexe::memoryStream (used to read or write into
/// puntoexe::memory objects)
///
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
class baseStream : public baseObject
{
public:
/// \brief Writes raw data into the stream.
///
/// The function is multithreading-safe and is called by
/// the streamWriter class when its buffer has to be
/// flushed.
///
/// @param startPosition the position in the file where
/// the data has to be written
/// @param pBuffer pointer to the data that has to
/// be written
/// @param bufferLength number of bytes in the data
/// buffer that has to be written
///
///////////////////////////////////////////////////////////
virtual void write(imbxUint32 startPosition, const imbxUint8* pBuffer, imbxUint32 bufferLength) = 0;
/// \brief Read raw data from the stream.
///
/// The function is multithreading-safe and is called by
/// the streamReader class when its buffer has to be
/// refilled.
///
/// @param startPosition the position in the file from
/// which the data has to be read
/// @param pBuffer a pointer to the memory where the
/// read data has to be placed
/// @param bufferLength the number of bytes to read from
/// the file
/// @return the number of bytes read from the file. When
/// it is 0 then the end of the file has been
/// reached
///
///////////////////////////////////////////////////////////
virtual imbxUint32 read(imbxUint32 startPosition, imbxUint8* pBuffer, imbxUint32 bufferLength) = 0;
};
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
/// \brief The base exception for all the exceptions
/// thrown by the function in baseStream.
///
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
class streamException: public std::runtime_error
{
public:
streamException(const std::string& message): std::runtime_error(message){}
};
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
/// \brief Exception thrown when the stream cannot be
/// open.
///
///////////////////////////////////////////////////////////
class streamExceptionOpen : public streamException
{
public:
streamExceptionOpen(const std::string& message): streamException(message){}
};
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
/// \brief Exception thrown when there is an error during
/// the read phase.
///
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
class streamExceptionRead : public streamException
{
public:
streamExceptionRead(const std::string& message): streamException(message){}
};
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
/// \brief Exception thrown when there is an error during
/// the write phase.
///
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
class streamExceptionWrite : public streamException
{
public:
streamExceptionWrite(const std::string& message): streamException(message){}
};
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
/// \brief Exception thrown when there are problems during
/// the closure of the stream.
///
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
class streamExceptionClose : public streamException
{
public:
streamExceptionClose(const std::string& message): streamException(message){}
};
///@}
} // namespace puntoexe
#endif // !defined(imebraBaseStream_3146DA5A_5276_4804_B9AB_A3D54C6B123A__INCLUDED_)
|
60f0c84c898ba94ab818926827b067b388b58946
|
bf1ae57ea948ae78634dde98c973640a0a5d539d
|
/lineEditor/Editor.cpp
|
0a24093d7e516d3c4dbae6271f762bfb0f84ce1b
|
[
"Unlicense"
] |
permissive
|
mansasha21/OOP
|
99e080922208c2d74e7d76373c78ee3f6e1c8912
|
f30fffa08c0be978fb27a06f33748ddcbfeb2420
|
refs/heads/master
| 2020-05-02T13:05:45.997465
| 2019-12-26T05:16:12
| 2019-12-26T05:16:12
| 177,975,272
| 2
| 1
|
Unlicense
| 2019-04-12T15:15:08
| 2019-03-27T10:55:58
|
C++
|
UTF-8
|
C++
| false
| false
| 648
|
cpp
|
Editor.cpp
|
#include "Editor.h"
Editor::Editor(std::string& line):line(line){}
void Editor::addAndExecuteCommand(std::unique_ptr<Command> cmd)
{
(*cmd).redo();
commands_.push_back(std::move(cmd));
}
void Editor::undo()
{
if (commands_.empty())
return;
canceledCommands.push_back(std::move(commands_.back()));
commands_.pop_back();
(*canceledCommands.back()).undo();
}
void Editor::redo()
{
if (canceledCommands.empty())
return;
(*canceledCommands.back()).redo();
commands_.push_back(std::move(canceledCommands.back()));
canceledCommands.pop_back();
}
std::string Editor::showLine() const
{
return line;
}
|
5e1b5e819cf06a42ce2443d04e801719e9247f33
|
3e03813dd3f76db341b51957c24801b8c0252994
|
/test.cpp
|
02a736cfc7ac5d7c02583b7071d0360cc945e2a3
|
[
"BSL-1.0"
] |
permissive
|
sergegers/optional_utility
|
f5045078ab33ffac1aed301f2a9e80338f0ec797
|
1d5f1924e0679701a1d553112035677debefc99b
|
refs/heads/master
| 2021-06-21T17:19:16.432327
| 2017-08-07T13:45:25
| 2017-08-07T13:45:25
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,023
|
cpp
|
test.cpp
|
//#define OPTIONAL_UTILITY_NO_CXX14_RETURN_TYPE_DEDUCTION
#include "optional_utility.hpp"
#include <cassert>
#include <iostream>
#include <string>
namespace
{
struct _
{
template <typename F>
_(F f)
{
try {
f();
} catch (std::exception const& e) {
std::cerr << e.what() << std::endl;
assert(false && "unexpected exception");
} catch (...) {
assert(false && "unexpected exception");
}
}
};
}
#define TEST(name) _ name##__LINE__ = []
TEST(value)
{
using optional_utility::value;
{
boost::optional<int> op = 42;
assert(value(op) == 42);
}
{
boost::optional<int> op = boost::none;
try {
value(op);
assert(false && "not thrown");
} catch (boost::bad_optional_access const&) {
}
}
};
TEST(value_or)
{
using optional_utility::value_or;
{
boost::optional<int> op = 42;
assert(value_or(op, 84) == 42);
}
{
boost::optional<int> op = boost::none;
assert(value_or(op, 84) == 84);
}
};
TEST(map)
{
using optional_utility::map;
{
boost::optional<int> op = 42;
boost::optional<int> op2 = op
| map([](int i) { return i * 2; });
assert(op2.get() == 84);
}
{
boost::optional<int> op = 42;
boost::optional<int> op2 = op
| map([](int i) { return i * 2; })
| map([](int i) { return i + 1; });
assert(op2.get() == 85);
}
{
boost::optional<int> op = 42;
boost::optional<std::string> op2 = op
| map([](int i) { return std::to_string(i); });
assert(op2.get() == "42");
}
};
TEST(to_optional)
{
using optional_utility::map;
using optional_utility::to_optional;
{
boost::optional<int> op = 42;
auto op2 = op
| map([](int i) { return i * 2; })
| to_optional;
static_assert(std::is_same<decltype(op2), boost::optional<int>>::value, "");
assert(op2 == 84);
}
{
boost::optional<int> op = 42;
auto temp = op
| map([](int i) { return i * 2; });
static_assert(!std::is_same<decltype(temp), boost::optional<int>>::value, "");
auto op2 = temp
| to_optional;
assert(op2 == 84);
}
};
TEST(member_function)
{
using optional_utility::map;
using namespace std::string_literals;
{
boost::optional<std::string> op = "hello"s;
boost::optional<std::string::size_type> op2 = op
| map(&std::string::length);
assert(op2.get() == 5);
}
{
boost::optional<std::string> op = "hello"s;
boost::optional<std::string> op2 = op
| map(&std::string::substr, 1, 3);
assert(op2.get() == "ell");
}
};
#include <iostream>
int main() {
std::cout << "tests finished" << std::endl;
}
|
ca697c172e3b31a67e5d038e9b82c86cdeaabadc
|
2f1ea09dd203982ad928ffddbcbb92943938c36a
|
/webinfo/webinfo.h
|
55e288e934b03688abd6993f64e5e46e2c2bfb3e
|
[] |
no_license
|
peterlacko/school-projects
|
8688455bb3ecf76ad047ac8094e44294500f84e1
|
f3cfecb68efd77eafe68a04542d9501ccb8fe0aa
|
refs/heads/master
| 2021-01-20T17:21:07.283586
| 2016-07-17T11:54:19
| 2016-07-17T11:59:36
| 63,529,439
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,639
|
h
|
webinfo.h
|
/*
* =====================================================================================
*
* Filename: webinifo.h
*
* Description: hlavickovy subor k webinfo.cpp
*
* Version: 1.0
* Created: 26.02.2012 23:40:26
* Revision: none
* Compiler: gcc
*
* Author: Peter Lacko (xlacko06), xlacko06@stud.fit.vutbr.cz
*
* =====================================================================================
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <regex.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
// struktura uchovava informacie o parametroch
struct paramsInfo {
int lSize;
int sId;
int mModified;
int tType;
};
// struktura uriInfo obsahuje rozparsovanu adresu
struct uriInfo {
std::string domain;
std::string path;
std::string port;
};
// velkost buffru pre nacitanu spravu
const int BUFFER_SIZE = 1000;
// maximalny povoleny pocet presmerovani
const int MaxRedirections = 5;
// navratove kody funkce spracujucej odpoved servra
enum httpReturnValues {
HTTP_OK,
HTTP_REDIRECT,
HTTP_ERROR
};
// navratove kony programu
enum ReturnValues {
WRONG_PARAMS=11,
WRONG_ADDRESS,
SOCKET_ERROR,
CONNECTION_ERROR,
INTERNAL_ERROR
};
int connectAndWrite (std::string & reply, const uriInfo uri, int & sockNumber);
int handleReply (std::string & reply, std::string & codeOrAddress, int & crlf);
int parseUri (const char * uriStr_c, uriInfo & uri);
int GetArg (int argc, char *argv[], paramsInfo & params);
|
4fe413c58068ee6c36a1cdc4778fc87b074eee5c
|
5f4a4e8109562ba88ab60e19429ce1084f14f9b2
|
/VideoShaderLiveCoding/src/main.cpp
|
10b9b96fe4cdef589f1cb63828615177480782bb
|
[] |
no_license
|
andreasmuller/RaspberryPiWorkshop
|
53f91fbe3d65183a982fe93e07e9e97aa538bf63
|
d403dbbec3417092b6113b729b8bb96bae90a6bd
|
refs/heads/master
| 2016-09-16T07:22:26.231952
| 2013-08-12T16:02:36
| 2013-08-12T16:02:36
| 7,204,213
| 35
| 10
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 599
|
cpp
|
main.cpp
|
#include "ofMain.h"
//#define USE_DEVELOP_APP
#ifdef USE_DEVELOP_APP
#include "developApp.h"
#warning "!!!!!!! YOU ARE USING THE developApp WHEN YOU PROBABLY WANT THE testApp !!!!!!!!"
#else
#include "testApp.h"
#endif
#include "ofGLProgrammableRenderer.h"
//========================================================================
int main( ){
ofSetLogLevel(OF_LOG_VERBOSE);
ofSetCurrentRenderer(ofPtr<ofBaseRenderer>(new ofGLProgrammableRenderer()));
ofSetupOpenGL(1280,720, OF_WINDOW);
#ifdef USE_DEVELOP_APP
ofRunApp( new developApp());
#else
ofRunApp( new testApp());
#endif
}
|
d1cbc2ed04a43f631a92f48478c720e88b98fa0b
|
b4396cf30845c5ec00ca8160264e06a25808d35b
|
/Classes/BgLayer.cpp
|
b6cdaa46d9ca769b4c0aac084a8614d044db02c7
|
[] |
no_license
|
VincentPeng/SaveHostage
|
6d47f56929ec6e9f042b29ecb4500cbac8069a3d
|
785205b1e9e0e3356966e07cf4a6fa0ffd127049
|
refs/heads/master
| 2021-01-15T10:13:33.967931
| 2016-08-25T06:13:36
| 2016-08-25T06:13:36
| 16,710,436
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 592
|
cpp
|
BgLayer.cpp
|
//
// BgLayer.cpp
// SaveHostage
//
// Created by Ke Peng on 4/9/14.
//
//
#include "BgLayer.h"
USING_NS_CC;
USING_NS_CC_EXT;
BgLayer::BgLayer() {}
BgLayer::~BgLayer() {}
bool BgLayer::init() {
bool ret = false;
do {
CC_BREAK_IF(!Layer::init());
cocos2d::Node* node =
cocostudio::SceneReader::getInstance()->createNodeWithSceneFile(
"RPGGame.json");
this->addChild(node);
ret = true;
} while (0);
return ret;
}
|
7e0fd26c2b2b3e959faef7cdc447544c06afb9ad
|
aa9dbd084e29f78754901549a41fd1f573f83b79
|
/RayTracer/raytracer.h
|
1a4095dec7c83f8d69cc6d7e52f33a1b11035740
|
[] |
no_license
|
THTBSE/GeometricTools
|
939509819c431cf5bc303a11a500a83001960b65
|
6001f43b2a49e4c7eff4eb9f74a48c36745f1cb4
|
refs/heads/master
| 2019-01-19T13:33:26.935251
| 2014-12-30T13:23:47
| 2014-12-30T13:23:47
| 25,525,477
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 590
|
h
|
raytracer.h
|
#ifndef _RAYTRACER_H_
#define _RAYTRACER_H_
#include "include\GLFW\glfw3.h"
#include "basicGeometry.h"
#include "material.h"
#include <vector>
using namespace std;
typedef shared_ptr<geometry> GPtr;
void GenerateObjects(vector<GPtr> &objects);
class rayTracer
{
public:
rayTracer(int w, int h, const Vector3 &e);
void renderScene();
void rayTrace(const vector<GPtr> &objects, int maxReflect = 5);
int width, height, lw, rw, lh, rh;
Vector3 eye;
vector<Color> colors;
private:
Color rayTraceRecursive(const vector<GPtr> &objects, const Ray3 &ray, int maxReflcet);
};
#endif
|
ed2ab240d725ed86fcc9f7279322791521da3817
|
4bfc3c184e736bb68dccbb6d5657f11c950df002
|
/src/pass/merge_loops.cc
|
478473f44e3e813dffd64a983df011adfb3b568f
|
[
"Apache-2.0",
"Zlib",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense",
"BSD-2-Clause"
] |
permissive
|
laekov/akg
|
159aa64ef6135222b5af784c408731275dfa9bdb
|
5316b8cb2340bbf71bdc724dc9d81513a67b3104
|
refs/heads/master
| 2022-12-01T04:09:03.548063
| 2020-08-19T08:38:57
| 2020-08-19T08:41:28
| 288,678,192
| 0
| 0
|
Apache-2.0
| 2020-08-19T08:41:30
| 2020-08-19T08:36:53
|
Python
|
UTF-8
|
C++
| false
| false
| 4,817
|
cc
|
merge_loops.cc
|
/**
* Copyright 2019 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tvm/ir.h>
#include <tvm/ir_mutator.h>
#include <tvm/ir_pass.h>
#include <ir_pass.h>
#include <pass/ir_util.h>
#include <emit_insn/insn_info.h>
#include "pass/analyze_align.h"
namespace akg {
namespace ir {
namespace {
int HasNode(const Array<NodeRef> &array, const NodeRef &node) {
int index = 0;
for (const auto &item : array) {
if (item.same_as(node)) {
return index;
}
index++;
}
return -1;
}
class LoopsCompacter : public IRMutator {
public:
explicit LoopsCompacter(bool is_dynamic) : is_dynamic_(is_dynamic) {}
~LoopsCompacter() override = default;
Stmt Mutate_(const AttrStmt *op, const Stmt &s) final {
if (op->attr_key == "pragma_ub_gm" || (op->attr_key == "pragma_emit_insn" && op->value->IsInstance<StringImm>() &&
!exclude_align_analyze_list.count(op->value.as<StringImm>()->value))) {
stores_ = Array<NodeRef>();
loads_ = Array<NodeRef>();
GetStoreAndLoads(op->body, stores_, loads_);
StmtInfo if_info;
StmtInfo for_info;
GetIfForInfo(op->body, if_info, for_info);
dst_info_list_ = GetComputationInfo(stores_, for_info);
src_info_list_ = GetComputationInfo(loads_, for_info);
CompactComputationInfoList(dst_info_list_, src_info_list_, if_info, for_info);
for_vars_ = Map<Var, Expr>();
in_insn_ = true;
auto ret = IRMutator::Mutate_(op, s);
in_insn_ = false;
auto opn = ret.as<AttrStmt>();
CHECK(opn);
if (ForVarIsClean(opn->body, for_info)) {
auto body = PackForLoop(opn->body, for_info);
return AttrStmt::make(opn->node, opn->attr_key, opn->value, body);
}
return s;
} else if (op->attr_key == "pragma_emit_insn") {
return s;
}
return IRMutator::Mutate_(op, s);
}
Expr Mutate_(const Load *op, const Expr &e) final {
auto load = IRMutator::Mutate_(op, e);
if (in_insn_) {
auto idx = HasNode(loads_, e);
if (idx != -1) {
CHECK_GT(src_info_list_.size(), idx);
auto index = GenerateIndex(src_info_list_[idx]);
auto opn = load.as<Load>();
CHECK(opn);
return Load::make(opn->type, opn->buffer_var, index, opn->predicate);
}
}
return load;
}
Stmt Mutate_(const Store *op, const Stmt &s) final {
auto store = IRMutator::Mutate_(op, s);
if (in_insn_) {
auto idx = HasNode(stores_, s);
if (idx != -1) {
CHECK_GT(dst_info_list_.size(), idx);
auto index = GenerateIndex(dst_info_list_[idx]);
auto opn = store.as<Store>();
CHECK(opn);
return Store::make(opn->buffer_var, opn->value, index, opn->predicate);
}
}
return store;
}
Stmt Mutate_(const For *op, const Stmt &s) final {
if (in_insn_) {
for_vars_.Set(op->loop_var, Expr(0));
return this->Mutate(op->body);
}
return IRMutator::Mutate_(op, s);
}
private:
Expr GenerateIndex(const StmtStoreInfo &info) {
Expr expr = info->elem_offset_;
for (size_t i = 0; i != info->var_.size(); ++i) {
CHECK_GT(info->strides_.size(), i);
expr += info->var_[i] * info->strides_[i];
}
return expr;
}
Stmt PackForLoop(Stmt s, const StmtInfo &for_info) {
for (size_t i = 0; i != for_info.vars_.size(); ++i) {
auto op = for_info.ops_[i].as<For>();
CHECK(op);
s = For::make(for_info.vars_[i], op->min, op->extent, op->for_type, op->device_api, s);
}
return s;
}
bool ForVarIsClean(const Stmt &s, const StmtInfo &for_info) {
Map<Var, Expr> map;
for (const auto &e : for_vars_) {
if (!IsInArray(for_info.vars_, e.first)) {
map.Set(e.first, Expr(0));
}
}
for (const auto &e : map) {
if (air::ir::StmtUseVar(s, e.first)) {
return false;
}
}
return true;
}
Map<Var, Expr> for_vars_;
Array<NodeRef> stores_;
Array<NodeRef> loads_;
StmtInfoList dst_info_list_;
StmtInfoList src_info_list_;
bool in_insn_{false};
bool is_dynamic_{false};
};
} // namespace
Stmt MergeLoops(const Stmt &stmt, bool is_dynamic) { return LoopsCompacter(is_dynamic).Mutate(stmt); }
} // namespace ir
} // namespace akg
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.