hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bd4ad8dd12486df8755c5e838cff0515b5743778
| 471
|
cpp
|
C++
|
1877/main.cpp
|
exaw/timustasks
|
d0c4cb797e6063d35f25842712a8417fdfd8f4d4
|
[
"MIT"
] | null | null | null |
1877/main.cpp
|
exaw/timustasks
|
d0c4cb797e6063d35f25842712a8417fdfd8f4d4
|
[
"MIT"
] | null | null | null |
1877/main.cpp
|
exaw/timustasks
|
d0c4cb797e6063d35f25842712a8417fdfd8f4d4
|
[
"MIT"
] | null | null | null |
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <map>
#include <numeric>
#include <set>
#include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
using namespace std;
int main ()
{
ios_base::sync_with_stdio (false);
int k1 = 0, k2 = 0;
cin>>k1>>k2;
if ( k1 % 2 == 0 || k2 % 2 == 1 )
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
return 0;
}
| 13.083333
| 38
| 0.592357
|
exaw
|
bd4c88fc07fc54030e8fdb491e4e92333d27d6db
| 5,124
|
cc
|
C++
|
src/test/test-mysql.cc
|
lujingwei002/coord
|
cb5e5723293d8529663ca89e0c1d6b8c348fffff
|
[
"MIT"
] | null | null | null |
src/test/test-mysql.cc
|
lujingwei002/coord
|
cb5e5723293d8529663ca89e0c1d6b8c348fffff
|
[
"MIT"
] | null | null | null |
src/test/test-mysql.cc
|
lujingwei002/coord
|
cb5e5723293d8529663ca89e0c1d6b8c348fffff
|
[
"MIT"
] | null | null | null |
#include "coord/coord.h"
#include "gtest/gtest.h"
#include "coord/builtin/slice.h"
#include "coord/sql/init.h"
#include "coord/sql/mysql/init.h"
#include "coord/config/config.h"
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <cstdlib>
class TestMySQL : public testing::Test {
public:
static void SetUpTestCase() {
}
static void TearDownTestCase() {
}
void SetUp() {
auto coord = coord::NewCoord();
int err = coord->beforeTest("test/test.ini");
ASSERT_EQ(err, 0);
this->sqlMgr = coord::sql::newSQLMgr(coord);
this->coord = coord;
}
void TearDown() {
int err = this->coord->afterTest();
ASSERT_EQ(err, 0);
delete this->coord;
}
public:
coord::Coord* coord;
coord::sql::sql_mgr* sqlMgr;
};
class Test1 {
public:
Test1(const char* name) {
this->name = name;
}
void hello1(const char* w) {
printf("aaa %s %s\n", this->name.c_str(), w);
}
void hello2(const char* w) {
printf("aaa %s %s\n", this->name.c_str(), w);
}
public:
std::string name;
};
typedef std::function<void (const char* w)> TestFunction;
TEST_F(TestMySQL, TestSetGet) {
Test1* t1 = new Test1("t1");
Test1* t2 = new Test1("t2");
TestFunction f1 = std::bind(&Test1::hello1, t1, std::placeholders::_1);
TestFunction f2 = std::bind(&Test1::hello2, t2, std::placeholders::_1);
if (f1.target<void(*)(const char*)>() == f2.target<void(*)(const char*)>()) {
printf("ffffffffffffffffffffffffffffffffff1\n");
} else {
printf("ffffffffffffffffffffffffffffffffff2\n");
}
int err = this->coord->Proto->ImportDir(this->coord->config->Basic.Proto.c_str());
ASSERT_EQ(err, 0);
auto client = this->sqlMgr->getClient("DB");
ASSERT_NE(client, nullptr);
err = client->Ping();
ASSERT_EQ(err, 0);
ASSERT_STREQ(client->Format("aa ?, ?", 1, "你好"), "aa 1, '你好'");
ASSERT_STREQ(client->Format("aa ?, ?", 1, (char*)"你好"), "aa 1, '你好'");
ASSERT_STREQ(client->Format("aa ?, ?,?", 1, "你好"), "aa 1, '你好',?");
ASSERT_STREQ(client->Format("aa ?, ?", 1, "你好", "2"), "aa 1, '你好'");
auto result = client->Execute("DROP TABLE `testcoord`");
//ASSERT_NE(result, nullptr);
result = client->Execute("CREATE TABLE `testcoord` (\
`userid` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '用户id',\
`openid` varchar(64) NOT NULL DEFAULT '' COMMENT 'openid',\
`nickname` varchar(128) NOT NULL DEFAULT '' COMMENT '昵称',\
`avatar` varchar(128) NOT NULL DEFAULT '' COMMENT '头像',\
`diamond` bigint(11) NOT NULL DEFAULT '0' COMMENT '钻石',\
`score` decimal(11, 2) NOT NULL DEFAULT '0' COMMENT '分类',\
`rank` enum('one', 'two', 'three') NOT NULL DEFAULT 'two' COMMENT '排名',\
`catalog` set('c1', 'c2', 'c3') NOT NULL DEFAULT 'c1,c3' COMMENT '分类',\
`coin` bigint(11) NOT NULL DEFAULT '0' COMMENT '金币',\
`createtime` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间',\
`updatetime` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间',\
PRIMARY KEY (`userid`)\
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户表';\
");
ASSERT_NE(result, nullptr);
result = client->Execute("INSERT INTO testcoord(userid, nickname, score, rank, catalog) VALUES (1, '你好a', 3.123, 'three', 'c2,c3')");
ASSERT_NE(result, nullptr);
ASSERT_EQ(result.RowsAffected(), (uint64_t)1);
result = client->Execute("INSERT INTO testcoord(userid, nickname) VALUES (?, ?)", 2, "你好b", 4);
ASSERT_NE(result, nullptr);
ASSERT_EQ(result.RowsAffected(), (uint64_t)1);
auto rows = client->Query("SELECT userid, nickname, avatar, score, rank, catalog, createtime FROM testcoord ORDER BY userid asc LIMIT 10");
while (rows.Next()) {
if (rows.Index() == 0){
ASSERT_STREQ(rows.String("nickname"), "你好a");
ASSERT_EQ(rows.Number("score"), 3.12);
ASSERT_STREQ(rows.String("rank"), "three");
ASSERT_STREQ(rows.String("catalog"), "c2,c3");
} else if(rows.Index() == 1){
ASSERT_STREQ(rows.String("nickname"), "你好b");
}
}
auto user = this->coord->Proto->NewReflect("test.User");
ASSERT_NE(user, nullptr);
err = client->Get(user, "SELECT * FROM testcoord WHERE userid=?", 1);
ASSERT_EQ(err, 0);
//printf("ppppppp %s\n", user.DebugString());
//coord::slice<coord::protobuf::Reflect> userArr;
//err = client->Query(userArr, "SELECT * FROM testcoord");
//ASSERT_EQ(err, 0);
rows = client->Query("SELECT userid1, nickname, avatar, createtime FROM testcoord LIMIT 10");
ASSERT_EQ(rows, nullptr);
result = client->Execute("UPDATE testcoord SET nickname=? WHERE userid=2", "你好c");
ASSERT_NE(result, nullptr);
ASSERT_EQ(result.RowsAffected(), (uint64_t)1);
result = client->Execute("UPDATE testcoord SET nickname=?", "你好");
ASSERT_NE(result, nullptr);
ASSERT_EQ(result.RowsAffected(), (uint64_t)2);
result = client->Execute("DROP TABLE `testcoord`");
ASSERT_NE(result, nullptr);
}
| 37.40146
| 143
| 0.607143
|
lujingwei002
|
bd4ff33907f456a6d566c8012e96165c2566cbae
| 1,402
|
cpp
|
C++
|
instanceedr.cpp
|
slist/cbapi-qt-demo
|
b44e31824a5b9973aa0ccff39c15ff7805902b8b
|
[
"MIT"
] | 3
|
2020-09-14T19:39:53.000Z
|
2021-01-19T11:58:27.000Z
|
instanceedr.cpp
|
slist/cbapi-qt-demo
|
b44e31824a5b9973aa0ccff39c15ff7805902b8b
|
[
"MIT"
] | null | null | null |
instanceedr.cpp
|
slist/cbapi-qt-demo
|
b44e31824a5b9973aa0ccff39c15ff7805902b8b
|
[
"MIT"
] | null | null | null |
// Copyright 2020 VMware, Inc.
// SPDX-License-Identifier: MIT
#include "instanceedr.h"
#include "ui_instanceedr.h"
InstanceEdr::InstanceEdr(QWidget *parent) :
QWidget(parent),
ui(new Ui::InstanceEdr)
{
ui->setupUi(this);
}
InstanceEdr::~InstanceEdr()
{
delete ui;
}
void InstanceEdr::set_name(const QString & name)
{
ui->lineEdit_name->setText(name);
}
void InstanceEdr::set_api(const QString & api)
{
ui->lineEdit_api->setText(api);
}
void InstanceEdr::set_url(const QString & url)
{
ui->lineEdit_url->setText(url);
check_validity();
}
QString InstanceEdr::get_name()
{
return ui->lineEdit_name->text();
}
QString InstanceEdr::get_api()
{
return ui->lineEdit_api->text();
}
QString InstanceEdr::get_url()
{
return ui->lineEdit_url->text();
}
bool InstanceEdr::isValid()
{
if (get_name().isEmpty() || get_api().isEmpty() || get_url().isEmpty())
return false;
return true;
}
void InstanceEdr::check_validity()
{
if (!isValid()) {
ui->label_invalid->show();
} else {
ui->label_invalid->hide();
}
}
void InstanceEdr::on_lineEdit_name_textChanged(const QString & /* arg1 */)
{
check_validity();
}
void InstanceEdr::on_lineEdit_url_textChanged(const QString & /* arg1 */)
{
check_validity();
}
void InstanceEdr::on_lineEdit_api_textChanged(const QString & /* arg1 */)
{
check_validity();
}
| 17.308642
| 75
| 0.664051
|
slist
|
bd54b467c25f3b14a6178edd3ef1d5130470ef69
| 703
|
cc
|
C++
|
test/Airflow/readfile.cc
|
fstudio/Phoenix
|
28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d
|
[
"MIT"
] | 8
|
2015-01-23T05:41:46.000Z
|
2019-11-20T05:10:27.000Z
|
test/Airflow/readfile.cc
|
fstudio/Phoenix
|
28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d
|
[
"MIT"
] | null | null | null |
test/Airflow/readfile.cc
|
fstudio/Phoenix
|
28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d
|
[
"MIT"
] | 4
|
2015-05-05T05:15:43.000Z
|
2020-03-07T11:10:56.000Z
|
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char **argv)
{
char buffer[20]={0};
FILE *fp=nullptr;
if(fopen_s(&fp,argv[1],"rb")!=0)
return -1;
if(fread_s(buffer,20,1,20,fp)<0)
{
fclose(fp);
return -2;
}
fclose(fp);
printf("%02X-%02X-%02X-%02X-%02X-%02X-%02X-%02X-%02X-%02X",
(unsigned char)buffer[0],
(unsigned char)buffer[1],
(unsigned char)buffer[2],
(unsigned char)buffer[3],
(unsigned char)buffer[4],
(unsigned char)buffer[5],
(unsigned char)buffer[6],
(unsigned char)buffer[7],
(unsigned char)buffer[8],
(unsigned char)buffer[9]);
return 0;
}
| 22.677419
| 63
| 0.540541
|
fstudio
|
32e3cc4e727858a1b23d68c676147a1712e8d336
| 392
|
cpp
|
C++
|
C++/if/01 Password .cpp
|
Noob-coder-07/DeepAlgo
|
b7f5f8eacefff561648b476946d80948b3f69f51
|
[
"Apache-2.0"
] | null | null | null |
C++/if/01 Password .cpp
|
Noob-coder-07/DeepAlgo
|
b7f5f8eacefff561648b476946d80948b3f69f51
|
[
"Apache-2.0"
] | null | null | null |
C++/if/01 Password .cpp
|
Noob-coder-07/DeepAlgo
|
b7f5f8eacefff561648b476946d80948b3f69f51
|
[
"Apache-2.0"
] | 1
|
2021-09-07T03:12:49.000Z
|
2021-09-07T03:12:49.000Z
|
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
string Password = "Hello";
cout << "Enter a Password => " << flush;
string input;
cin >> input;
if(Password == input)
{
cout << "Password Accepted....." << endl;
}
if(Password != input)
{
cout << "Access Denied....." << endl;
}
getch();
return 0;
}
| 13.517241
| 49
| 0.507653
|
Noob-coder-07
|
32e9035bece31b37ed27ed859bd066a1d7ae64f2
| 1,768
|
cpp
|
C++
|
mvp_tips/CPUID/CPUID/ExtendedCPU0.cpp
|
allen7575/The-CPUID-Explorer
|
77d0feef70482b2e36cff300ea24271384329f60
|
[
"Naumen",
"Condor-1.1",
"MS-PL"
] | 9
|
2017-08-31T06:03:18.000Z
|
2019-01-06T05:07:26.000Z
|
mvp_tips/CPUID/CPUID/ExtendedCPU0.cpp
|
allen7575/The-CPUID-Explorer
|
77d0feef70482b2e36cff300ea24271384329f60
|
[
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null |
mvp_tips/CPUID/CPUID/ExtendedCPU0.cpp
|
allen7575/The-CPUID-Explorer
|
77d0feef70482b2e36cff300ea24271384329f60
|
[
"Naumen",
"Condor-1.1",
"MS-PL"
] | 8
|
2017-08-31T06:23:22.000Z
|
2022-01-24T06:47:19.000Z
|
// ExtendedCPU0.cpp : implementation file
//
#include "stdafx.h"
#include "resource.h"
#include "ExtendedCPU0.h"
#include "CPUIDx86.h"
#include "ReportRegs.h"
#include "CurrentProcessor.h"
// CExtendedCPU0 dialog
IMPLEMENT_DYNCREATE(CExtendedCPU0, CLeaves)
CExtendedCPU0::CExtendedCPU0()
: CLeaves(CExtendedCPU0::IDD)
{
}
CExtendedCPU0::~CExtendedCPU0()
{
}
void CExtendedCPU0::DoDataExchange(CDataExchange* pDX)
{
CLeaves::DoDataExchange(pDX);
DDX_Control(pDX, IDC_EAX, c_EAX);
DDX_Control(pDX, IDC_EBX, c_EBX);
DDX_Control(pDX, IDC_ECX, c_ECX);
DDX_Control(pDX, IDC_EDX, c_EDX);
}
BEGIN_MESSAGE_MAP(CExtendedCPU0, CLeaves)
END_MESSAGE_MAP()
// CExtendedCPU0 message handlers
/****************************************************************************
* CExtendedCPU0::OnSetActive
* Result: BOOL
*
* Effect:
* Reports the registers
****************************************************************************/
BOOL CExtendedCPU0::OnSetActive()
{
CPUregs regs;
GetAndReport(0x80000000, regs);
CString s;
s.Format(_T("%08x"), regs.EAX);
c_EAX.SetWindowText(s);
return CLeaves::OnSetActive();
}
/****************************************************************************
* CExtendedCPU0::OnInitDialog
* Result: BOOL
* TRUE, always
* Effect:
* Initializes the dialog
****************************************************************************/
BOOL CExtendedCPU0::OnInitDialog()
{
CLeaves::OnInitDialog();
SetFixedFont(c_EBX);
SetFixedFont(c_ECX);
SetFixedFont(c_EDX);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
| 22.961039
| 77
| 0.557127
|
allen7575
|
32f91bccb96b86a022267acb0fa41e009dc08275
| 8,913
|
hpp
|
C++
|
jdu_source_collection/jsc/bioinfo/psl.hpp
|
gersteinlab/LESSeq
|
bfc0a9aae081682a176e26d9804b980999595f16
|
[
"MIT"
] | 7
|
2016-06-19T21:14:55.000Z
|
2020-09-15T03:04:41.000Z
|
jdu_source_collection/jsc/bioinfo/psl.hpp
|
gersteinlab/LESSeq
|
bfc0a9aae081682a176e26d9804b980999595f16
|
[
"MIT"
] | 3
|
2015-02-12T21:17:00.000Z
|
2020-03-20T13:50:38.000Z
|
jdu_source_collection/jsc/bioinfo/psl.hpp
|
gersteinlab/LESSeq
|
bfc0a9aae081682a176e26d9804b980999595f16
|
[
"MIT"
] | null | null | null |
#ifndef _jsc_bioinfo_psl_hpp_included_
#define _jsc_bioinfo_psl_hpp_included_
#include <boost/config.hpp>
#include <math.h>
#include <iostream>
#include <map>
#include <set>
#include <sstream>
#include <vector>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/tokenizer.hpp>
#include "jsc/util/interval_list.hpp"
using namespace std;
using namespace boost;
using namespace boost::lambda;
using namespace jsc::util;
namespace jsc
{
namespace bioinfo
{
/*!
* the format of a psl_entry.
* according to the description at:
* http://genome.ucsc.edu/FAQ/FAQformat
*/
class psl_entry
{
public:
double identity; // identity score
double score; // psl score
long matches; /* 1 */
long misMatches; /* 2 */
long repMatches; /* 3 */
long nCount; /* 4 */
long qNumInsert; /* 5 */
long qBaseInsert; /* 6 */
long tNumInsert; /* 7 */
long tBaseInsert; /* 8 */
string strand; /* 9 */
string qName; /* 10 */
long qSize; /* 11 */
long qStart; /* 12 */
long qEnd; /* 13 */
string tName; /* 14 */
long tSize; /* 15 */
long tStart; /* 16 */
long tEnd; /* 17 */
unsigned long blockCount; /* 18 */
vector<long> blockSizes; /* 19 */
vector<long> qStarts; /* 20 */
vector<long> tStarts; /* 21 */
};
typedef shared_ptr<psl_entry> psl_ptr;
typedef vector<psl_ptr> vec_pslp;
typedef map<psl_ptr, double> map_pslp_fitness;
typedef multimap<string, psl_ptr> map_qname_pslp;
typedef set<string> set_qname;
/*!
* print a psl entry
*/
void print_pslp(psl_ptr const & pslp, ostream & os)
{
os << pslp->matches /* 1 */
<< "\t" << pslp->misMatches /* 2 */
<< "\t" << pslp->repMatches /* 3 */
<< "\t" << pslp->nCount /* 4 */
<< "\t" << pslp->qNumInsert /* 5 */
<< "\t" << pslp->qBaseInsert /* 6 */
<< "\t" << pslp->tNumInsert /* 7 */
<< "\t" << pslp->tBaseInsert /* 8 */
<< "\t" << pslp->strand /* 9 */
<< "\t" << pslp->qName /* 10 */
<< "\t" << pslp->qSize /* 11 */
<< "\t" << pslp->qStart /* 12 */
<< "\t" << pslp->qEnd /* 13 */
<< "\t" << pslp->tName /* 14 */
<< "\t" << pslp->tSize /* 15 */
<< "\t" << pslp->tStart /* 16 */
<< "\t" << pslp->tEnd /* 17 */
<< "\t" << pslp->blockCount /* 18 */
<< "\t";
// blockSizes /* 19 */
for (unsigned int i = 0; i < pslp->blockCount; ++i)
{
os << pslp->blockSizes[i] << ",";
}
os << "\t";
// qStarts /* 20 */
for (unsigned int i = 0; i < pslp->blockCount; ++i)
{
os << pslp->qStarts[i] << ",";
}
os << "\t";
// tStarts /* 21 */
for (unsigned int i = 0; i < pslp->blockCount; ++i)
{
os << pslp->tStarts[i] << ",";
}
os << endl;
}
/*!
* convert a psl line to psl_entry
*/
psl_ptr str2pslp(string const & line)
{
psl_ptr pslp(new psl_entry());
istringstream iss(line);
string strBlockSizes, strQStarts, strTStarts;
iss >> pslp->matches /* 1 */
>> pslp->misMatches /* 2 */
>> pslp->repMatches /* 3 */
>> pslp->nCount /* 4 */
>> pslp->qNumInsert /* 5 */
>> pslp->qBaseInsert /* 6 */
>> pslp->tNumInsert /* 7 */
>> pslp->tBaseInsert /* 8 */
>> pslp->strand /* 9 */
>> pslp->qName /* 10 */
>> pslp->qSize /* 11 */
>> pslp->qStart /* 12 */
>> pslp->qEnd /* 13 */
>> pslp->tName /* 14 */
>> pslp->tSize /* 15 */
>> pslp->tStart /* 16 */
>> pslp->tEnd /* 17 */
>> pslp->blockCount /* 18 */
>> strBlockSizes /* 19 */
>> strQStarts /* 20 */
>> strTStarts; /* 21 */
/* deal with blockSizes, qStarts, and TStarts */
typedef tokenizer<char_separator<char> > tok;
char_separator<char> sep(",");
tok tBlockSizes(strBlockSizes, sep);
tok tQStarts(strQStarts, sep);
tok tTStarts(strTStarts, sep);
for_each(tBlockSizes.begin(), tBlockSizes.end(),
bind(&vector<long>::push_back,
ref(pslp->blockSizes),
bind(atol,
bind(&string::c_str, _1))));
for_each(tQStarts.begin(), tQStarts.end(),
bind(&vector<long>::push_back,
ref(pslp->qStarts),
bind(atol,
bind(&string::c_str, _1))));
for_each(tTStarts.begin(), tTStarts.end(),
bind(&vector<long>::push_back,
ref(pslp->tStarts),
bind(atol,
bind(&string::c_str, _1))));
assert(pslp->qSize >= pslp->qEnd - pslp->qStart);
assert(pslp->blockCount == pslp->blockSizes.size()
&& pslp->blockCount == pslp->qStarts.size()
&& pslp->blockCount == pslp->tStarts.size());
return pslp;
}
/*!
* load a vector of psl_ptrs from an istream (w/o the psl header)
*/
vec_pslp load_pslps_noheader(istream & is)
{
string line;
/* read content */
vec_pslp pslps;
while (getline(is, line) && !is.eof())
{
pslps.push_back(str2pslp(line));
}
return pslps;
}
/*!
* a fitness score simulating the percent identity score defined at:
* http://genome.ucsc.edu/FAQ/FAQblat.html
*
* here we assume that the psl_entry is a dna vs. dna blat result,
* and we focus on the fitness of the query sequence.
*/
double psl_q_fitness_ucsc(psl_ptr const & pslp, bool const & consider_ins_factor = true)
{
double badness = 0;
double qAliSize = pslp->qEnd - pslp->qStart;
double tAliSize = pslp->tEnd - pslp->tStart;
double aliSize = min(qAliSize, tAliSize);
if (aliSize <= 0) {
return 0;
}
double sizeDif = qAliSize - tAliSize;
if (sizeDif < 0) {
sizeDif = 0;
}
double insertFactor = pslp->qNumInsert;
if (!consider_ins_factor) {
insertFactor = 0;
}
long total = pslp->matches + pslp->repMatches + pslp->misMatches;
assert(total != 0);
badness = (1000 * ((double)pslp->misMatches + insertFactor + round(3 * log(1 + sizeDif)))) / (double)total;
return (100.0 - (long)badness * 0.1);
}
double psl_score_ucsc(psl_ptr const & pslp) {
return pslp->matches +
(pslp->repMatches >> 1) -
pslp->misMatches -
pslp->qNumInsert -
pslp->tNumInsert;
}
double psl_identity(psl_ptr const & pslp) {
return (double)(pslp->matches + pslp->repMatches) / (double)(pslp->matches + pslp->repMatches + pslp->misMatches);
}
/*!
* a fitness score that is similar to the percent identity score
* defined at:
* http://genome.ucsc.edu/FAQ/FAQblat.html
*
* here we assume that the psl_entry is a dna vs. dna blat result,
* and we focus on the fitness of the query sequence.
*/
double psl_q_fitness(psl_ptr const & pslp)
{
double badness = 0;
double sizeDif = abs((pslp->tEnd - pslp->tStart) - (pslp->qEnd - pslp->qStart))
+ abs(pslp->qSize - (pslp->qEnd - pslp->qStart));
double insertFactor = pslp->qNumInsert + pslp->tNumInsert;
long total = pslp->matches + pslp->repMatches + pslp->misMatches;
assert(total != 0);
badness = (1000 * ((double)pslp->misMatches + (double)insertFactor + 3 * log(1 + sizeDif))) / (double)total;
return (100 - badness * 0.1);
}
/*!
* Note that the returned psl_entry may not be fully filled:
* only strand, tName, tStart, tEnd, blockCount, blockSizes, tStarts
* will be filled.
*/
psl_ptr combine_forward_reverse_reads(psl_ptr const & forward_pslp, psl_ptr const & reverse_pslp, bool & combined)
{
assert(forward_pslp->strand != reverse_pslp->strand);
psl_ptr combined_pslp(new psl_entry());
combined_pslp->qName = forward_pslp->qName + "::" + reverse_pslp->qName;
combined_pslp->strand = forward_pslp->strand;
combined_pslp->tName = forward_pslp->tName;
combined = true;
interval_list<long> il_f, il_r;
il_f.add_starts_sizes(forward_pslp->tStarts, forward_pslp->blockSizes);
il_r.add_starts_sizes(reverse_pslp->tStarts, reverse_pslp->blockSizes);
if (!il_f.coverage_overlap(il_r))
{
combined = false;
}
interval_list<long> il;
il.add_interval_list(il_f);
il.add_interval_list(il_r);
unsigned long n = il.get_starts().size();
assert(n > 0);
combined_pslp->tStart = il.get_starts()[0];
combined_pslp->tEnd = il.get_ends()[n - 1];
combined_pslp->blockCount = n;
for (unsigned long i = 0; i < n; i++)
{
combined_pslp->tStarts.push_back(il.get_starts()[i]);
combined_pslp->blockSizes.push_back(il.get_ends()[i] - il.get_starts()[i]);
}
return combined_pslp;
}
/*!
* Note that the returned psl_entry may not be fully filled:
* only qName, strand, tName, tStart, tEnd, blockCount, blockSizes, tStarts
* will be filled.
*/
psl_ptr fill_in_gaps(psl_ptr const & pslp, double const & threshold)
{
psl_ptr processed_pslp(new psl_entry());
processed_pslp->qName = pslp->qName;
processed_pslp->strand = pslp->strand;
processed_pslp->tName = pslp->tName;
interval_list<long> il;
il.add_starts_sizes(pslp->tStarts, pslp->blockSizes);
il.fill_in_gaps(threshold);
unsigned long n = il.get_starts().size();
assert(n > 0);
processed_pslp->tStart = il.get_starts()[0];
processed_pslp->tEnd = il.get_ends()[n - 1];
processed_pslp->blockCount = n;
for (unsigned long i = 0; i < n; i++)
{
processed_pslp->tStarts.push_back(il.get_starts()[i]);
processed_pslp->blockSizes.push_back(il.get_ends()[i] - il.get_starts()[i]);
}
return processed_pslp;
}
} /* end of bioinfo */
} /* end of jsc */
#endif
| 26.292035
| 115
| 0.638393
|
gersteinlab
|
32fe586ac7e10e7d2ffd43b1d75d5faa54be0fdf
| 13,241
|
cpp
|
C++
|
src/prompt.cpp
|
aparks5/synthcastle
|
ebb542d014c87a11a83b9e212668eca75a333fbf
|
[
"MIT"
] | 2
|
2021-12-20T03:20:05.000Z
|
2021-12-28T16:15:20.000Z
|
src/prompt.cpp
|
aparks5/synthcastle
|
ebb542d014c87a11a83b9e212668eca75a333fbf
|
[
"MIT"
] | 69
|
2021-08-30T13:09:01.000Z
|
2022-01-15T17:41:40.000Z
|
src/prompt.cpp
|
aparks5/synthcastle
|
ebb542d014c87a11a83b9e212668eca75a333fbf
|
[
"MIT"
] | null | null | null |
#include "prompt.h"
#include "util.h"
#include "windows.h"
#include <deque>
#include "spdlog/spdlog.h"
#include "spdlog/sinks/stdout_color_sinks.h"
#include "spdlog/sinks/rotating_file_sink.h"
static void logVoiceParams(VoiceParams params) {
spdlog::info("voice params updated");
spdlog::info("bpm: {}", params.bpm);
spdlog::info("filter cutoff (Hz): {}", params.filtFreq);
spdlog::info("osc2-enable: {}", params.bEnableOsc2);
}
static void logFxParams(FxParams fxparams) {
spdlog::info("fx params updated");
spdlog::info("delay1-enable: {}", fxparams.bEnableDelay1);
spdlog::info("delay2-enable: {}", fxparams.bEnableDelay2);
spdlog::info("chorus-enable: {}", fxparams.bEnableChorus);
}
Prompt::Prompt(std::shared_ptr<MixerStream> s)
: stream(s)
{
}
void Prompt::open()
{
std::string prompt;
VoiceParams params;
FxParams fxparams;
params.envParams = { 1,250,0,0 };
stream->update(params);
std::deque<NoteEvent> notes;
NoteGenerator gen;
bool bParamChanged = false;
bool bFxParamChanged = false;
std::cout << ">>> type 'help' to list commands" << std::endl;
std::vector<spdlog::sink_ptr> sinks;
sinks.push_back(std::make_shared<spdlog::sinks::stdout_color_sink_st>());
sinks.push_back(std::make_shared<spdlog::sinks::rotating_file_sink_mt>("history.log",1024*1024,5,false));
auto logger = std::make_shared<spdlog::logger>("logger", begin(sinks), end(sinks));
//register it if you need to access it globally
spdlog::register_logger(logger);
spdlog::set_default_logger(logger);
spdlog::flush_on(spdlog::level::info);
spdlog::info("opening history log...");
while (true) {
std::cout << ">>> ";
std::cin >> prompt;
if (prompt == "help") {
spdlog::info(">>> commands: stop, tracks, mix, osc, freq, filt-freq, filt-q, filt-lfo-freq, pitch/filt-lfo-on/off, ");
spdlog::info(">>> pitch-lfo-freq, pitch-lfo-depth, reverb-on/off, chorus-on/off, delay-on/off");
spdlog::info(">>> delay-time, delay-feedback, delay-mix");
spdlog::info(">>> osc2-enable, osc2-coarse, osc2-fine, env [attackMs decayMs susdB]");
spdlog::info(">>> play [note] [note-note2-note3:duration,note4:duration2...], loop loopNumTimes");
}
if (prompt == "stop") {
stream->stopLoop();
}
if (prompt == "start") {
stream->start();
}
if (prompt == "midilog-on") {
stream->enableMidiLogging();
}
if (prompt == "midilog-off") {
stream->disableMidiLogging();
}
if (prompt == "tracks") {
spdlog::info(">> list of tracks");
size_t trackCount = 0;
std::vector<std::string> trackList = stream->getTrackList();
for (auto track : trackList) {
std::cout << trackCount << ": " << track << std::endl;
trackCount++;
}
}
if (prompt == "bpm") {
std::cout << ">> enter bpm (20-200 beats per minute)" << std::endl;
std::cin >> prompt;
auto bpm = std::stof(prompt);
bpm = clamp(bpm, 20.f, 200.f);
params.bpm = bpm;
bParamChanged = true;
}
if (prompt == "exit") {
break;
}
if (prompt == "freq") {
std::cout << ">> enter frequency in Hz" << std::endl;
std::cin >> prompt;
auto freq = std::stof(prompt);
freq = clamp(freq, 0.f, 10000.f);
params.freq = freq;
bParamChanged = true;
}
if (prompt == "filt-freq") {
std::cout << ">> enter filter cutoff frequency in Hz" << std::endl;
std::cin >> prompt;
auto freq = std::stof(prompt);
freq = clamp(freq, 0.f, 10000.f);
params.filtFreq = freq;
bParamChanged = true;
}
if (prompt == "filt-q") {
std::cout << ">> enter filter resonance (0 - 10)" << std::endl;
std::cin >> prompt;
auto q = std::stof(prompt);
q = clamp(q, 0.f, 10.f);
params.filtQ = q;
bParamChanged = true;
}
if (prompt == "filt-lfo-freq") {
std::cout << ">> enter filter LFO frequency (0 - 40)" << std::endl;
std::cin >> prompt;
auto freq = std::stof(prompt);
freq = clamp(freq, 0.f, 40.f);
params.filtLFOFreq = freq;
bParamChanged = true;
}
if (prompt == "pitch-lfo-freq") {
std::cout << ">> enter pitch LFO frequency (0 - 40)" << std::endl;
std::cin >> prompt;
auto freq = std::stof(prompt);
freq = clamp(freq, 0.f, 40.f);
params.pitchLFOFreq = freq;
bParamChanged = true;
}
if (prompt == "track") {
auto trackCount = 0;
std::vector<std::string> trackList = stream->getTrackList();
spdlog::info(">> list of tracks");
for (auto track : trackList) {
spdlog::info("{}: {}", trackCount, track);
trackCount++;
}
std::cin >> prompt;
auto trackNum = 0;
bool bErr = false;
try {
trackNum = std::stoi(prompt);
}
// Catch stoi errors
catch (const std::invalid_argument& e) {
spdlog::error("invalid argument");
bErr = true;
}
catch (const std::out_of_range& e) {
spdlog::error("input out of range");
bErr = true;
}
trackNum = clamp(trackNum, 0, trackCount);
std::string trackName;
trackCount = 0;
for (auto track : trackList) {
if (trackNum == trackCount) {
stream->setActiveTrackName(track);
spdlog::info("setting active track name to: {}", track);
break;
}
else {
trackCount++;
}
}
}
if (prompt == "pitch-lfo-depth") {
std::cout << ">> enter pitch LFO depth (0. - 1.)" << std::endl;
std::cin >> prompt;
auto depth = std::stof(prompt);
depth = clamp(depth, 0.f, 1.f);
params.pitchLFOdepth = depth;
bParamChanged = true;
}
if (prompt == "filt-lfo-on") {
params.bEnableFiltLFO = true;
bParamChanged = true;
}
if (prompt == "filt-lfo-off") {
params.bEnableFiltLFO = false;
bParamChanged = true;
}
if (prompt == "pitch-lfo-on") {
params.bEnablePitchLFO = true;
bParamChanged = true;
}
if (prompt == "pitch-lfo-off") {
params.bEnablePitchLFO = false;
bParamChanged = true;
}
if (prompt == "chorus-on") {
fxparams.bEnableChorus = true;
bFxParamChanged = true;
}
if (prompt == "chorus-off") {
fxparams.bEnableChorus = false;
bFxParamChanged = true;
}
if (prompt == "delay-on") {
fxparams.bEnableDelay1 = true;
bFxParamChanged = true;
}
if (prompt == "delay-off") {
fxparams.bEnableDelay1 = false;
bFxParamChanged = true;
}
if (prompt == "delay-time") {
std::cout << ">> enter delay time in milliseconds (0. - 1000.)" << std::endl;
std::cin >> prompt;
auto delayTimeMs = std::stof(prompt);
delayTimeMs = clamp(delayTimeMs, 0.f, 1000.f);
fxparams.delay1time = delayTimeMs;
bFxParamChanged = true;
}
if (prompt == "delay-feedback") {
std::cout << ">> enter delay feedback as a ratio (0. - 1.)" << std::endl;
std::cin >> prompt;
auto delayFeedbackRatio = std::stof(prompt);
delayFeedbackRatio = clamp(delayFeedbackRatio, 0.f, 1.f);
fxparams.delay1feedback = delayFeedbackRatio;
bFxParamChanged = true;
}
if (prompt == "delay-mix") {
std::cout << ">> enter delay wet/dry mix as a ratio (0. - 1.)" << std::endl;
std::cin >> prompt;
auto delayMix = std::stof(prompt);
delayMix = clamp(delayMix, 0.f, 1.f);
fxparams.delay1level = delayMix;
bParamChanged = true;
}
if (prompt == "reverb-on") {
fxparams.bEnableReverb = true;
bFxParamChanged = true;
}
if (prompt == "reverb-off") {
fxparams.bEnableReverb = false;
bFxParamChanged = true;
}
if (prompt == "record-start") {
stream->record(true);
}
if (prompt == "record-stop") {
stream->record(false);
}
if (prompt == "bitcrusher-on") {
fxparams.bEnableBitcrusher = true;
bFxParamChanged = true;
}
if (prompt == "bitcrusher-off") {
fxparams.bEnableBitcrusher = false;
bFxParamChanged = true;
}
if (prompt == "bitcrusher-bits") {
std::cout << ">> enter bit depth (1-32)" << std::endl;
std::cin >> prompt;
auto depth = std::stoi(prompt);
depth = clamp(depth, 0, 32);
fxparams.bitCrusherNBits = depth;
bFxParamChanged = true;
}
if (prompt == "osc") {
std::cout << ">> enter sine, saw, tri, square" << std::endl;
std::cin >> prompt;
OscillatorType osc = OscillatorType::SINE;
if (prompt == "sine") {
osc = OscillatorType::SINE;
}
if (prompt == "saw") {
osc = OscillatorType::SAW;
}
if (prompt == "tri") {
osc = OscillatorType::TRIANGLE;
}
if (prompt == "square") {
osc = OscillatorType::SQUARE;
}
params.osc = osc;
bParamChanged = true;
}
if (prompt == "osc2-enable") {
params.bEnableOsc2 = true;
bParamChanged = true;
}
if (prompt == "osc2-disable") {
params.bEnableOsc2 = false;
bParamChanged = true;
}
if (prompt == "osc2") {
std::cout << ">> enter sine, saw, tri, square" << std::endl;
std::cin >> prompt;
OscillatorType osc = OscillatorType::SINE;
if (prompt == "sine") {
osc = OscillatorType::SINE;
}
if (prompt == "saw") {
osc = OscillatorType::SAW;
}
if (prompt == "tri") {
osc = OscillatorType::TRIANGLE;
}
if (prompt == "square") {
osc = OscillatorType::SQUARE;
}
params.osc2 = osc;
bParamChanged = true;
}
if (prompt == "osc2-coarse") {
std::cin >> prompt;
auto coarse = std::stof(prompt);
coarse = clamp(coarse, -24.f, 24.f);
params.osc2coarse = coarse;
bParamChanged = true;
}
if (prompt == "osc2-fine") {
std::cin >> prompt;
auto fine = std::stof(prompt);
fine = clamp(fine, -1.f, 1.f);
params.osc2fine = fine;
bParamChanged = true;
}
if (prompt == "env") {
std::cout << ">> enter adsr envelope parameters (attack ms, decay ms, sustain dB (< 0), release ms) (e.g. 250 10 -10 500) " << std::endl;
std::vector<std::string> param;
size_t paramCount = 0;
std::string envP;
while (paramCount < 4 && std::cin >> envP) {
param.push_back(envP);
paramCount++;
}
size_t attMs = 0;
size_t decMs = 0;
int susdB = 0;
size_t relMs = 0;
std::sscanf(param[0].c_str(), "%zu", &attMs);
std::sscanf(param[1].c_str(), "%zu", &decMs);
std::sscanf(param[2].c_str(), "%d", &susdB);
std::sscanf(param[3].c_str(), "%zu", &relMs);
attMs = (attMs > 5000) ? 500 : attMs;
decMs = (decMs > 5000) ? 500 : decMs;
susdB = (susdB > 0) ? 0 : susdB;
relMs = (relMs > 5000) ? 500 : relMs;
EnvelopeParams env(attMs, decMs, susdB, relMs);
params.envParams = env;
bParamChanged = true;
}
if (prompt == "play") {
std::string pattern;
std::cin >> pattern;
std::vector<std::string> trackList = stream->getTrackList();
NoteGenerator gen;
spdlog::info("play " + pattern);
auto temp = gen.makeSequence(pattern, trackList);
while (!temp.empty()) {
notes.push_back(temp.front());
temp.pop_front();
}
}
if (prompt == "randompattern") {
std::cout << "usage: randompattern <scale>. generated random pattern N times. play with 'pattern' command" << std::endl;
NoteGenerator gen;
std::string keyStr, patStr, modeStr;
std::cin >> keyStr >> patStr >> modeStr;
// TODO: combine these to method. populate key, pattern, mode
Key key = Scale::strToKey(keyStr);
ScalePattern pattern = Scale::strToScalePattern(patStr);
ScaleMode mode = Scale::strToScaleMode(modeStr);
Scale scale = Scale(key, pattern, mode);
auto temp = gen.randomPattern("synth1", 8, scale);
notes = temp;
std::cout << "generated random pattern, play with 'pattern' command" << std::endl;
}
if (prompt == "scale") {
std::cout << "usage: scale <key pattern mode>. e.g. scale C# maj lydian" << std::endl;
NoteGenerator gen;
std::string keyStr, patStr, modeStr;
std::cin >> keyStr >> patStr >> modeStr;
// populate key, pattern, mode
Key key = Scale::strToKey(keyStr);
ScalePattern pattern = Scale::strToScalePattern(patStr);
ScaleMode mode = Scale::strToScaleMode(modeStr);
auto temp = gen.scalePattern(key, pattern, mode);
stream->queueLoop(1, temp, params.bpm);
std::cout << "now playing scale" << std::endl;
}
if (prompt == "loop") {
std::cin >> prompt;
int loopCount = std::stod(prompt);
if (notes.size() == 0) {
std::cout << "nothing to loop, use play to declare a sequence..." << std::endl;
}
else {
stream->queueLoop(loopCount, notes, params.bpm);
}
}
if (prompt == "pattern") {
auto temp = NoteGenerator::sortTimeVal(notes);
spdlog::info("(notes in pattern sorted by timestamp)");
if (temp.size() > 0) {
for (auto note : temp) {
spdlog::info("{}", note);
}
stream->queueLoop(1, notes, params.bpm);
}
else {
std::cout << "no notes to play!" << std::endl;
}
}
if (prompt == "clear") {
notes = {};
}
if (prompt == "mix") {
std::cout << ">> mix <trackname> <dB (-60...0)>" << std::endl;
std::vector<std::string> param;
size_t paramCount = 0;
std::string gainParams;
while (paramCount < 2 && std::cin >> gainParams) {
param.push_back(gainParams);
paramCount++;
}
std::string track;
track = param[0];
float fGainDB = 0.f;
std::sscanf(param[1].c_str(), "%f", &fGainDB);
fGainDB = clamp(fGainDB, -60.f, 0.f);
stream->updateTrackGainDB(track, fGainDB);
bParamChanged = true;
}
if (bParamChanged) {
logVoiceParams(params);
stream->update(params);
bParamChanged = false;
}
if (bFxParamChanged) {
logFxParams(fxparams);
stream->update(fxparams);
bFxParamChanged = false;
}
}
}
| 27.357438
| 140
| 0.61083
|
aparks5
|
32fe5c733afef97b59aa68bebecf411d6038ac13
| 13,835
|
cc
|
C++
|
Source/Plugins/GraphicsPlugins/BladeImageFI/source/ETC2EAC.cc
|
OscarGame/blade
|
6987708cb011813eb38e5c262c7a83888635f002
|
[
"MIT"
] | 146
|
2018-12-03T08:08:17.000Z
|
2022-03-21T06:04:06.000Z
|
Source/Plugins/GraphicsPlugins/BladeImageFI/source/ETC2EAC.cc
|
huangx916/blade
|
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
|
[
"MIT"
] | 1
|
2019-01-18T03:35:49.000Z
|
2019-01-18T03:36:08.000Z
|
Source/Plugins/GraphicsPlugins/BladeImageFI/source/ETC2EAC.cc
|
huangx916/blade
|
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
|
[
"MIT"
] | 31
|
2018-12-03T10:32:43.000Z
|
2021-10-04T06:31:44.000Z
|
/********************************************************************
created: 2015/01/28
filename: ETC2EAC.cc
author: Crazii
purpose: ETC2/EAC block compression
reference:
*********************************************************************/
#include <BladePCH.h>
#include "ETC2EAC.h"
#include "ETC2EACCommon.h"
namespace Blade
{
namespace ETC2EAC
{
/************************************************************************/
/* compression */
/************************************************************************/
/** @brief compress input 4x4 colors in given format, to ETC2 - RGB */
void compressBlockETC2(uint8 *outBlock, const uint8* colors, PixelFormat format)
{
Color::RGBA BLADE_ALIGNED(64) decodeBuffer[4*4];
Color::RGB BLADE_ALIGNED(64) colorBuffer[4*4];
extractBlockRGB(colorBuffer, colors, format, 4);
uint32 c[2];
compressBlockETC2RGB(colorBuffer, decodeBuffer, 4, 4, 0, 0, (uint8*)&c[0]);
std::memcpy(outBlock, c, sizeof(c) );
}
/** @brief compress input 4x4 colors in given format, to ETC2 - RGBA */
void compressBlockETC2EAC(uint8 *outBlock, const uint8* colors, PixelFormat format)
{
Color::RGBA BLADE_ALIGNED(64) decodeBuffer[4*4];
Color::RGB BLADE_ALIGNED(64) colorBuffer[4*4];
uint8 BLADE_ALIGNED(64) alphaBuffer[4*4];
extractBlockRGBA(colorBuffer, alphaBuffer, colors, format, 4);
uint32 c[4];
compressBlockAlphaFast(alphaBuffer, 0, 0, 4, 4, (uint8*)&c[0]);
compressBlockETC2RGB(colorBuffer, decodeBuffer, 4, 4, 0, 0, (uint8*)&c[2]);
std::memcpy(outBlock, c, sizeof(c) );
}
/** @brief compress input 4x4 colors in given format, to EAC, using only the R channel */
void compressBlockR11EAC(uint8 *outBlock, const uint8* colors, PixelFormat format)
{
uint8 BLADE_ALIGNED(64) redBuffer[4*4];
extractBlockR(redBuffer, colors, format, 4);
uint32 c[2];
compressBlockAlphaFast(redBuffer, 0, 0, 4, 4, (uint8*)&c[0]);
std::memcpy(outBlock, c, sizeof(c) );
}
/** @brief compress input 4x4 colors in given format, to EAC, using only the R,G channel */
void compressBlockRG11EAC(uint8 *outBlock, const uint8* colors, PixelFormat format, bool normalize)
{
uint8 BLADE_ALIGNED(64) redBuffer[4*4];
uint8 BLADE_ALIGNED(64) greenBuffer[4*4];
if( normalize )
extractBlockRGNormalize(redBuffer, greenBuffer, colors, format, 4);
else
extractBlockRG(redBuffer, greenBuffer, colors, format, 4);
uint32 c[4];
compressBlockAlphaFast(redBuffer, 0, 0, 4, 4, (uint8*)&c[0]);
compressBlockAlphaFast(greenBuffer, 0, 0, 4, 4, (uint8*)&c[2]);
std::memcpy(outBlock, c, sizeof(c) );
}
/** @brief */
size_t compressImageETC2(uint8 *outBuffer, const uint8* colors, int width, int height, PixelFormat format)
{
assert( width % 4 == 0 );
assert( height % 4 == 0 );
uint8 BLADE_ALIGNED(64) *outData = outBuffer;
Color::RGBA BLADE_ALIGNED(64) decodeBuffer[4*4];
Color::RGB BLADE_ALIGNED(64) colorBuffer[4*4];
uint32 c[2];
size_t pixelBytes = format.getSizeBytes();
assert( PixelFormat(PF_RGB_ETC2).getSizeBytes() == sizeof(c) );
for (int j = 0; j < height; j += 4)
{
for (int i = 0; i < width; i += 4)
{
IPlatformManager::prefetch<PM_READ>(colors + pixelBytes*4);
IPlatformManager::prefetch<PM_WRITE>(outData + sizeof(c));
extractBlockRGB(colorBuffer, colors, format, width);
compressBlockETC2RGB(colorBuffer, decodeBuffer, 4, 4, 0, 0, (uint8*)&c[0]);
std::memcpy(outData, c, sizeof(c) );
colors += pixelBytes*4;
outData += sizeof(c);
}
colors += pixelBytes*width*3;
}
return (size_t)(outData - outBuffer);
}
/** @brief */
size_t compressImageETC2EAC(uint8 *outBuffer, const uint8* colors, int width, int height, PixelFormat format)
{
assert( width % 4 == 0 );
assert( height % 4 == 0 );
uint8 BLADE_ALIGNED(64) *outData = outBuffer;
Color::RGBA BLADE_ALIGNED(64) decodeBuffer[4*4];
Color::RGB BLADE_ALIGNED(64) colorBuffer[4*4];
uint8 BLADE_ALIGNED(64) alphaBuffer[4*4];
uint32 c[4];
size_t pixelBytes = format.getSizeBytes();
assert( PixelFormat(PF_RGBA_ETC2EAC).getSizeBytes() == sizeof(c) );
for (int j = 0; j < height; j += 4)
{
for (int i = 0; i < width; i += 4)
{
IPlatformManager::prefetch<PM_READ>(colors + pixelBytes*4);
IPlatformManager::prefetch<PM_WRITE>(outData + sizeof(c));
extractBlockRGBA(colorBuffer, alphaBuffer, colors, format, width);
compressBlockAlphaFast(alphaBuffer, 0, 0, 4, 4, (uint8*)&c[0]);
compressBlockETC2RGB(colorBuffer, decodeBuffer, 4, 4, 0, 0, (uint8*)&c[2]);
std::memcpy(outData, c, sizeof(c) );
colors += pixelBytes*4;
outData += sizeof(c);
}
colors += pixelBytes*width*3;
}
return (size_t)(outData - outBuffer);
}
/** @brief */
size_t compressImageR11EAC(uint8 *outBuffer, const uint8* colors, int width, int height, PixelFormat format)
{
assert( width % 4 == 0 );
assert( height % 4 == 0 );
uint8 BLADE_ALIGNED(64) *outData = outBuffer;
uint8 BLADE_ALIGNED(64) redBuffer[4*4];
uint32 c[2];
size_t pixelBytes = format.getSizeBytes();
assert( PixelFormat(PF_R_EAC).getSizeBytes() == sizeof(c) );
for (int j = 0; j < height; j += 4)
{
for (int i = 0; i < width; i += 4)
{
IPlatformManager::prefetch<PM_READ>(colors + 4*pixelBytes);
IPlatformManager::prefetch<PM_WRITE>(outData + sizeof(c));
extractBlockR(redBuffer, colors, format, width);
compressBlockAlphaFast(redBuffer, 0, 0, 4, 4, (uint8*)&c[0]);
std::memcpy(outData, c, sizeof(c) );
colors += pixelBytes*4;
outData += sizeof(c);
}
colors += pixelBytes*width*3;
}
return (size_t)(outData - outBuffer);
}
/** @brief */
size_t compressImageRG11EAC(uint8 *outBuffer, const uint8* colors, int width, int height, PixelFormat format, bool normalize)
{
assert( width % 4 == 0 );
assert( height % 4 == 0 );
uint8 BLADE_ALIGNED(64) *outData = outBuffer;
uint8 BLADE_ALIGNED(64) redBuffer[4*4];
uint8 BLADE_ALIGNED(64) greenBuffer[4*4];
uint32 c[4];
size_t pixelBytes = format.getSizeBytes();
assert( PixelFormat(PF_RG_EAC).getSizeBytes() == sizeof(c) );
for (int j = 0; j < height; j += 4)
{
for (int i = 0; i < width; i += 4)
{
IPlatformManager::prefetch<PM_READ>(colors + 4*pixelBytes);
IPlatformManager::prefetch<PM_WRITE>(outData + sizeof(c));
if( normalize )
extractBlockRGNormalize(redBuffer, greenBuffer, colors, format, width);
else
extractBlockRG(redBuffer, greenBuffer, colors, format, width);
compressBlockAlphaFast(redBuffer, 0, 0, 4, 4, (uint8*)&c[0]);
compressBlockAlphaFast(greenBuffer, 0, 0, 4, 4, (uint8*)&c[2]);
std::memcpy(outData, c, sizeof(c) );
colors += pixelBytes*4;
outData += sizeof(c);
}
colors += pixelBytes*width*3;
}
return (size_t)(outData - outBuffer);
}
/************************************************************************/
/* decompression */
/************************************************************************/
/** @brief */
void decompressBlockETC2(uint8* outColors, const uint8 *block, PixelFormat format)
{
Color::RGBA BLADE_ALIGNED(64) colorBuffer[4*4];
std::memset(colorBuffer, 0, sizeof(colorBuffer) );
uint32 c[2];
std::memcpy(c, block, sizeof(c));
decompressBlockETC2RGB((uint8*)&c[0], (uint8*)colorBuffer, 4, 4, 0, 0, 4);
insertBlock(outColors, colorBuffer, format, 4);
}
/** @brief */
void decompressBlockETC2EAC(uint8* outColors, const uint8 *block, PixelFormat format)
{
Color::RGBA BLADE_ALIGNED(64) colorBuffer[4*4];
std::memset(colorBuffer, 0, sizeof(colorBuffer) );
uint32 c[4];
std::memcpy(c, block, sizeof(c));
decompressBlockAlphaC((uint8*)&c[0], (uint8*)&colorBuffer[0].a, 4, 4, 0, 0, 4);
decompressBlockETC2RGB((uint8*)&c[2], (uint8*)colorBuffer, 4, 4, 0, 0, 4);
insertBlock(outColors, colorBuffer, format, 4);
}
/** @brief */
void decompressBlockR11EAC(uint8* outColors, const uint8 *block, PixelFormat format)
{
Color::RGBA BLADE_ALIGNED(64) colorBuffer[4*4];
std::memset(colorBuffer, 0, sizeof(colorBuffer) );
uint32 c[2];
std::memcpy(c, block, sizeof(c));
decompressBlockAlphaC((uint8*)&c[0], (uint8*)&(colorBuffer[0].r), 4, 4, 0, 0, 4);
insertBlock(outColors, colorBuffer, format, 4);
}
/** @brief */
void decompressBlockRG11EAC(uint8* outColors, const uint8 *block, PixelFormat format)
{
Color::RGBA BLADE_ALIGNED(64) colorBuffer[4*4];
std::memset(colorBuffer, 0, sizeof(colorBuffer) );
uint32 c[4];
std::memcpy(c, block, sizeof(c));
decompressBlockAlphaC((uint8*)&c[0], (uint8*)&(colorBuffer[0].r), 4, 4, 0, 0, 4);
decompressBlockAlphaC((uint8*)&c[2], (uint8*)&(colorBuffer[0].g), 4, 4, 0, 0, 4);
insertBlock(outColors, colorBuffer, format, 4);
}
/** @brief return output bytes */
/* @note width & height are in original source image dimensions */
size_t decompressImageETC2(uint8 *outBuffer, const uint8* blocks, int width, int height, PixelFormat format)
{
assert(width % 4 == 0);
assert(height % 4 == 0);
Color::RGBA BLADE_ALIGNED(64) colorBuffer[4*4];
std::memset(colorBuffer, 0, sizeof(colorBuffer) );
uint32 c[2];
BLADE_ALIGNED(64) uint8* buffer = outBuffer;
size_t pixelBytes = format.getSizeBytes();
assert( PixelFormat(PF_RGB_ETC2).getSizeBytes() == sizeof(c));
size_t blockWidth = size_t((width+3)/4);
size_t blockHeight = size_t((height+3)/4);
for (size_t j = 0; j < blockHeight; ++j)
{
for (size_t i = 0; i < blockWidth; ++i)
{
IPlatformManager::prefetch<PM_READ>(blocks + sizeof(c));
IPlatformManager::prefetch<PM_WRITE>(buffer + 4*pixelBytes);
std::memcpy(c, blocks, sizeof(c));
decompressBlockETC2RGB((uint8*)&c[0], (uint8*)colorBuffer, 4, 4, 0, 0, 4);
insertBlock(buffer, colorBuffer, format, width);
blocks += sizeof(c);
buffer += 4*pixelBytes;
}
buffer += width*pixelBytes*3;
}
return (size_t)(buffer - outBuffer);
}
/** @brief */
size_t decompressImageETC2EAC(uint8 *outBuffer, const uint8* blocks, int width, int height, PixelFormat format)
{
assert(width % 4 == 0);
assert(height % 4 == 0);
Color::RGBA BLADE_ALIGNED(64) colorBuffer[4*4];
std::memset(colorBuffer, 0, sizeof(colorBuffer) );
uint32 c[4];
BLADE_ALIGNED(64) uint8* buffer = outBuffer;
size_t pixelBytes = format.getSizeBytes();
assert( PixelFormat(PF_RGBA_ETC2EAC).getSizeBytes() == sizeof(c));
size_t blockWidth = (size_t)((width+3)/4);
size_t blockHeight = (size_t)((height+3)/4);
for (size_t j = 0; j < blockHeight; ++j)
{
for (size_t i = 0; i < blockWidth; ++i)
{
IPlatformManager::prefetch<PM_READ>(blocks + sizeof(c));
IPlatformManager::prefetch<PM_WRITE>(buffer + 4*pixelBytes);
std::memcpy(c, blocks, sizeof(c));
decompressBlockAlphaC((uint8*)&c[0], (uint8*)&colorBuffer[0].a, 4, 4, 0, 0, 4);
decompressBlockETC2RGB((uint8*)&c[2], (uint8*)colorBuffer, 4, 4, 0, 0, 4);
insertBlock(buffer, colorBuffer, format, width);
blocks += sizeof(c);
buffer += 4*pixelBytes;
}
buffer += width*pixelBytes*3;
}
return (size_t)(buffer - outBuffer);
}
/** @brief */
size_t decompressImageR11EAC(uint8 *outBuffer, const uint8* blocks, int width, int height, PixelFormat format)
{
assert(width % 4 == 0);
assert(height % 4 == 0);
Color::RGBA BLADE_ALIGNED(64) colorBuffer[4*4];
std::memset(colorBuffer, 0, sizeof(colorBuffer) );
uint32 c[2];
BLADE_ALIGNED(64) uint8* buffer = outBuffer;
size_t pixelBytes = format.getSizeBytes();
assert( PixelFormat(PF_R_EAC).getSizeBytes() == sizeof(c));
size_t blockWidth = (size_t)((width+3)/4);
size_t blockHeight = (size_t)((height+3)/4);
for (size_t j = 0; j < blockHeight; ++j)
{
for (size_t i = 0; i < blockWidth; ++i)
{
IPlatformManager::prefetch<PM_READ>(blocks + sizeof(c));
IPlatformManager::prefetch<PM_WRITE>(buffer + 4*pixelBytes);
std::memcpy(c, blocks, sizeof(c));
decompressBlockAlphaC((uint8*)&c[0], (uint8*)&(colorBuffer[0].r), 4, 4, 0, 0, 4);
insertBlock(buffer, colorBuffer, format, width);
blocks += sizeof(c);
buffer += 4*pixelBytes;
}
buffer += width*pixelBytes*3;
}
return (size_t)(buffer - outBuffer);
}
/** @brief */
size_t decompressImageRG11EAC(uint8 *outBuffer, const uint8* blocks, int width, int height, PixelFormat format)
{
assert(width % 4 == 0);
assert(height % 4 == 0);
Color::RGBA BLADE_ALIGNED(64) colorBuffer[4*4];
std::memset(colorBuffer, 0, sizeof(colorBuffer) );
uint32 c[4];
BLADE_ALIGNED(64) uint8* buffer = outBuffer;
size_t pixelBytes = format.getSizeBytes();
assert( PixelFormat(PF_RG_EAC).getSizeBytes() == sizeof(c));
size_t blockWidth = (size_t)((width+3)/4);
size_t blockHeight = (size_t)((height+3)/4);
for (size_t j = 0; j < blockHeight; ++j)
{
for (size_t i = 0; i < blockWidth; ++i)
{
IPlatformManager::prefetch<PM_READ>(blocks + sizeof(c));
IPlatformManager::prefetch<PM_WRITE>(buffer + 4*pixelBytes);
std::memcpy(c, blocks, sizeof(c));
decompressBlockAlphaC((uint8*)&c[0], (uint8*)&(colorBuffer[0].r), 4, 4, 0, 0, 4);
decompressBlockAlphaC((uint8*)&c[2], (uint8*)&(colorBuffer[0].g), 4, 4, 0, 0, 4);
insertBlock(buffer, colorBuffer, format, width);
blocks += sizeof(c);
buffer += 4*pixelBytes;
}
buffer += width*pixelBytes*3;
}
return (size_t)(buffer - outBuffer);
}
}//namespace ETC2EAC
}//namespace Blade
| 32.78436
| 127
| 0.622551
|
OscarGame
|
32ff64c1d17f46a71a1c44627d62f6b5911a16f4
| 618
|
hpp
|
C++
|
src/widgets/PlayerFrame.hpp
|
filipdjordjevic/music_player
|
a0d66005a2fe0b8f277662a37d8d1c2912196536
|
[
"MIT"
] | null | null | null |
src/widgets/PlayerFrame.hpp
|
filipdjordjevic/music_player
|
a0d66005a2fe0b8f277662a37d8d1c2912196536
|
[
"MIT"
] | null | null | null |
src/widgets/PlayerFrame.hpp
|
filipdjordjevic/music_player
|
a0d66005a2fe0b8f277662a37d8d1c2912196536
|
[
"MIT"
] | null | null | null |
#pragma once
#include <QtWidgets>
#include "VolumeSlider.hpp"
#include "SeekBar.hpp"
#include "LcdLabel.hpp"
#include "CircleButton.hpp"
namespace ui
{
class PlayerFrame : public QFrame
{
Q_OBJECT
private:
CircleButton *playBtn_;
CircleButton *soundBtn_;
VolumeSlider *volumeSlider_;
SeekBar *seekBar_;
LcdLabel *durationLbl_;
LcdLabel *songLbl_;
bool playing_;
QTimer *timer_;
void connectWidgetsToActions();
public:
PlayerFrame(QWidget *parent = NULL);
void loadSongData();
};
} // namespace ui
| 19.3125
| 44
| 0.627832
|
filipdjordjevic
|
fd065cb4c52b896a29c94642cf6a8389f0e88c7b
| 1,663
|
cpp
|
C++
|
src/uMOOSArduinoLib/NetClientComm.cpp
|
mandad/moos-ivp-manda
|
6bc81d14aba7c537b7932d6135eed7a5b39c3c52
|
[
"MIT"
] | 9
|
2016-02-25T03:25:53.000Z
|
2022-03-27T09:47:50.000Z
|
src/uMOOSArduinoLib/NetClientComm.cpp
|
mandad/moos-ivp-manda
|
6bc81d14aba7c537b7932d6135eed7a5b39c3c52
|
[
"MIT"
] | null | null | null |
src/uMOOSArduinoLib/NetClientComm.cpp
|
mandad/moos-ivp-manda
|
6bc81d14aba7c537b7932d6135eed7a5b39c3c52
|
[
"MIT"
] | 4
|
2016-06-02T17:42:42.000Z
|
2021-12-15T09:37:55.000Z
|
/************************************************************/
/* NAME: Mike Bogochow, Jeff Masucci, Cody Noel */
/* ORGN: UNH */
/* FILE: NetClientComm.cpp */
/* DATE: April 2014 */
/************************************************************/
/* This is an implementation of IMOOSComm for communicating */
/* over a network as a client. */
/************************************************************/
#include "NetClientComm.h"
#include "NetUtil/tcpblockio.h"
#include "NetUtil/no_sigpipe.h"
#ifdef WIN32
#else
#include <unistd.h>
#endif
#include <fcntl.h>
#include <sys/stat.h>
#include <sstream>
#include <string.h>
using namespace std;
/**
* Create a new client communications object.
*
* @param serverPort
* the port number the server is running on
* @param serverNode
* either an IPv4 address or a DNS name for the server
* @param delimiter
* the delimiter character for messages between client and server
*/
NetClientComm::NetClientComm(char *serverPort, char *serverNode,
const char *delimiter)
//: delim(delimiter)
{
this->delim = delimiter;
this->serverPort = serverPort;
this->serverNode = serverNode;
socketFD = -1;
}
NetClientComm::~NetClientComm()
{
if (socketFD > -1)
close(socketFD);
}
/**
* Open socket.
*
* @return true on successful open of socket
* false otherwise
*/
bool NetClientComm::openComm()
{
no_sigpipe();
socketFD = openclient(serverPort, serverNode, serverIP, clientIP);
return socketFD >= 0;
}
| 24.820896
| 70
| 0.542995
|
mandad
|
fd0a820283e8bfe74856d5e202860089b96f9e70
| 1,984
|
cpp
|
C++
|
std-regex/id-scanners/AdvancedIdScanner.cpp
|
PS-Group/compiler-theory-samples
|
c916af50eb42020024257ecd17f9be1580db7bf0
|
[
"MIT"
] | null | null | null |
std-regex/id-scanners/AdvancedIdScanner.cpp
|
PS-Group/compiler-theory-samples
|
c916af50eb42020024257ecd17f9be1580db7bf0
|
[
"MIT"
] | null | null | null |
std-regex/id-scanners/AdvancedIdScanner.cpp
|
PS-Group/compiler-theory-samples
|
c916af50eb42020024257ecd17f9be1580db7bf0
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "AdvancedIdScanner.h"
CAdvancedIdScanner::CAdvancedIdScanner()
: m_pattern("[a-zA-Z_][a-zA-Z0-9_]*")
, m_commentBegin("/\\*")
, m_commentEnd("\\*/")
{
}
void CAdvancedIdScanner::ScanLine(std::string const& text)
{
// У функции regex_search есть вариант, принимающий 2 итератора вместо строки,
// то есть можно использовать итераторы для последовательного движения по строке.
auto from = text.cbegin();
auto to = text.cend();
if (m_isInComment)
{
AdvanceInComment(from, to);
}
else
{
AdvanceNormal(from, to);
}
}
std::vector<std::string> CAdvancedIdScanner::GetIds()const
{
std::vector<std::string> result;
result.reserve(m_ids.size());
for (std::string const& id : m_ids)
{
result.emplace_back(id);
}
return result;
}
void CAdvancedIdScanner::AdvanceInComment(string_iterator from, string_iterator to)
{
std::smatch match;
if (std::regex_search(from, to, match, m_commentEnd))
{
m_isInComment = false;
from += match.prefix().length() + match.length(0);
AdvanceNormal(from, to);
}
}
void CAdvancedIdScanner::AdvanceNormal(string_iterator from, string_iterator to)
{
std::smatch match;
if (std::regex_search(from, to, match, m_commentBegin))
{
auto commentStart = from + match.prefix().length();
AdvanceNoComment(from, commentStart);
m_isInComment = true;
AdvanceInComment(commentStart + match.length(0), to);
}
else
{
AdvanceNoComment(from, to);
}
}
void CAdvancedIdScanner::AdvanceNoComment(string_iterator from, string_iterator to)
{
std::smatch match;
while (std::regex_search(from, to, match, m_pattern))
{
// Сохраняем сопоставленный ID в std::set.
m_ids.insert(match[0]);
// Перемещаем позицию начала поиска за конец найденного ID.
from += match.prefix().length() + match.length(0);
}
}
| 25.766234
| 85
| 0.645161
|
PS-Group
|
fd0f037b8fb5ccdf8bf6d7801765eefd56de0437
| 664
|
cpp
|
C++
|
src/system/Logger.cpp
|
hugomarquez/cpp-toolkit
|
83797f34313b04a4dad931ee1648dcb37b50f64c
|
[
"MIT"
] | null | null | null |
src/system/Logger.cpp
|
hugomarquez/cpp-toolkit
|
83797f34313b04a4dad931ee1648dcb37b50f64c
|
[
"MIT"
] | null | null | null |
src/system/Logger.cpp
|
hugomarquez/cpp-toolkit
|
83797f34313b04a4dad931ee1648dcb37b50f64c
|
[
"MIT"
] | null | null | null |
#include "include/hm/system/Logger.h"
#include <spdlog/spdlog.h>
#include "spdlog/sinks/stdout_color_sinks.h"
namespace hm {
Logger* Logger::instance = 0;
void Logger::setLevel(int level)
{
switch (level) {
case 1: spdlog::set_level(spdlog::level::debug); break;
default: spdlog::set_level(spdlog::level::debug); break;
}
}
void Logger::debug(std::string msg) { spdlog::debug(msg);}
void Logger::info(std::string msg) { spdlog::info(msg);}
void Logger::warn(std::string msg) { spdlog::warn(msg);}
void Logger::error(std::string msg) { spdlog::error(msg);}
void Logger::critical(std::string msg) { spdlog::critical(msg);}
}
| 30.181818
| 66
| 0.671687
|
hugomarquez
|
fd145a50b7e69bfd7dd569504eddd393c15c56b7
| 130
|
hpp
|
C++
|
include/chasm/chasm.hpp
|
Ostoic/chasm
|
9ffab5686cac79158699d704368c67ec29551327
|
[
"MIT"
] | null | null | null |
include/chasm/chasm.hpp
|
Ostoic/chasm
|
9ffab5686cac79158699d704368c67ec29551327
|
[
"MIT"
] | null | null | null |
include/chasm/chasm.hpp
|
Ostoic/chasm
|
9ffab5686cac79158699d704368c67ec29551327
|
[
"MIT"
] | null | null | null |
#pragma once
#include "lex/split.hpp"
#include "parser/parser.hpp"
namespace chasm
{
using lex::split;
using parse::parser;
}
| 11.818182
| 28
| 0.715385
|
Ostoic
|
fd1983cc538893f22cd20591540994a3599c69de
| 399
|
cpp
|
C++
|
Dummy_device/create_Dummy_device.cpp
|
dekieras/GLEANApp
|
3cae6aa53f90f0c950f3097edcda5193b6b89fe8
|
[
"MIT"
] | 3
|
2017-04-06T21:37:22.000Z
|
2020-10-05T12:46:50.000Z
|
Dummy_device/create_Dummy_device.cpp
|
dekieras/GLEANApp
|
3cae6aa53f90f0c950f3097edcda5193b6b89fe8
|
[
"MIT"
] | null | null | null |
Dummy_device/create_Dummy_device.cpp
|
dekieras/GLEANApp
|
3cae6aa53f90f0c950f3097edcda5193b6b89fe8
|
[
"MIT"
] | null | null | null |
#include "GLEANKernel/Output_tee_globals.h"
#include "Dummy_device.h"
// for use in non-dynamically loaded models
Device_base * create_Dummy_device()
{
return new Dummy_device(Normal_out);
}
// the class factory functions to be accessed with dlsym
extern "C" Device_base * create_device()
{
return create_Dummy_device();
}
extern "C" void destroy_device(Device_base * p)
{
delete p;
}
| 19.95
| 56
| 0.744361
|
dekieras
|
fd1a68499337a52e0a2e7a47af158b2f45aa6ffe
| 604
|
hpp
|
C++
|
library/ATF/CPtrList.hpp
|
lemkova/Yorozuya
|
f445d800078d9aba5de28f122cedfa03f26a38e4
|
[
"MIT"
] | 29
|
2017-07-01T23:08:31.000Z
|
2022-02-19T10:22:45.000Z
|
library/ATF/CPtrList.hpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 90
|
2017-10-18T21:24:51.000Z
|
2019-06-06T02:30:33.000Z
|
library/ATF/CPtrList.hpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 44
|
2017-12-19T08:02:59.000Z
|
2022-02-24T23:15:01.000Z
|
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <CObject.hpp>
#include <CPlex.hpp>
START_ATF_NAMESPACE
struct CPtrList : CObject
{
struct CNode
{
struct CNode *pNext;
struct CNode *pPrev;
void *data;
};
struct CNode *m_pNodeHead;
struct CNode *m_pNodeTail;
__int64 m_nCount;
struct CNode *m_pNodeFree;
struct CPlex *m_pBlocks;
__int64 m_nBlockSize;
};
END_ATF_NAMESPACE
| 23.230769
| 108
| 0.620861
|
lemkova
|
fd1ea221aea7ee6bfe58b94a66dbb17d3877794c
| 5,201
|
cpp
|
C++
|
FDRV/src/DFXML_creator.cpp
|
AlexXandreE/Autopsy-Plugin-2017
|
a3027e7c431b23b3e9a5144a6e2cc89d0da331ce
|
[
"BSL-1.0"
] | 2
|
2018-05-01T14:09:21.000Z
|
2018-06-27T11:49:41.000Z
|
FDRV/src/DFXML_creator.cpp
|
AlexXandreE/Autopsy-Plugin-2017
|
a3027e7c431b23b3e9a5144a6e2cc89d0da331ce
|
[
"BSL-1.0"
] | 1
|
2020-04-18T00:11:54.000Z
|
2020-04-18T00:11:54.000Z
|
FDRV/src/DFXML_creator.cpp
|
AlexXandreE/Autopsy-Plugin-2017-FaceDetection
|
a3027e7c431b23b3e9a5144a6e2cc89d0da331ce
|
[
"BSL-1.0"
] | null | null | null |
#include <chrono>
#include <ctime>
#include <Lmcons.h>
#include <boost/filesystem.hpp>
#include <boost/version.hpp>
#include <boost/format.hpp>
#include <dlib/image_processing.h>
#include <dlib/gui_widgets.h>
#include <dlib/string.h>
#include <dlib/image_io.h>
#include <openssl/sha.h>
#include <FDRV/DFXML_creator.hpp>
using namespace std;
using namespace boost;
using namespace dlib;
using std::ofstream;
// PRIVATE FUNCTION
int DFXMLCreator::openssl_sha1(char *name, unsigned char *out)
{
FILE *f;
unsigned char buf[8192];
SHA_CTX sc;
int err;
f = fopen(name, "rb");
if (f == NULL)
{
cout << "Couldn't open file" << endl;
return -1;
}
SHA1_Init(&sc);
for (;;)
{
size_t len;
len = fread(buf, 1, sizeof buf, f);
if (len == 0)
break;
SHA1_Update(&sc, buf, len);
}
err = ferror(f);
fclose(f);
if (err)
{
cout << "Error hashing file" << endl;
return -1;
}
SHA1_Final(out, &sc);
return 0;
}
// CONSTRUCTOR
// NONE
pugi::xml_document DFXMLCreator::create_document()
{
pugi::xml_document doc;
doc.load_string("<?xml version='1.0' encoding='UTF-8'?>\n");
pugi::xml_node dfxml_node = doc.append_child("dfxml");
dfxml_node.append_attribute("xmlns") = "http://www.forensicswiki.org/wiki/Category:Digital_Forensics_XML";
dfxml_node.append_attribute("xmlns:dc") = "http://purl.org/dc/elements/1.1/";
dfxml_node.append_attribute("xmlns:xsi") = "http://www.w3.org/2001/XMLSchema-instance";
dfxml_node.append_attribute("version") = "1.1.1";
return doc;
}
void DFXMLCreator::add_DFXML_creator(pugi::xml_node &parent,
const char *program_name,
const char *program_version)
{
pugi::xml_node creator_node = parent.append_child("creator");
creator_node.append_attribute("version") = "1.0";
creator_node.append_child("program").text().set(program_name);
creator_node.append_child("version").text().set(program_version);
pugi::xml_node build_node = creator_node.append_child("build_environment");
#ifdef BOOST_VERSION
{
char buf[64];
snprintf(buf, sizeof(buf), "%d", BOOST_VERSION);
pugi::xml_node lib_node = build_node.append_child("library");
lib_node.append_attribute("name") = "boost";
lib_node.append_attribute("version") = buf;
}
#endif
pugi::xml_node lib_node = build_node.append_child("library");
lib_node.append_attribute("name") = "pugixml";
lib_node.append_attribute("version") = "1.9";
lib_node = build_node.append_child("library");
lib_node.append_attribute("name") = "dlib";
lib_node.append_attribute("version") = "19.10";
pugi::xml_node exe_node = creator_node.append_child("execution_environment");
chrono::system_clock::time_point p = chrono::system_clock::now();
time_t t = chrono::system_clock::to_time_t(p);
exe_node.append_child("start_date").text().set(ctime(&t));
char username[UNLEN + 1];
DWORD username_len = UNLEN + 1;
GetUserName(username, &username_len);
exe_node.append_child("username").text().set(username);
}
void DFXMLCreator::add_fileobject(pugi::xml_node &parent,
const char *file_path,
const int number_faces,
const long original_width,
const long original_height,
const long working_width,
const long working_height,
const std::vector<dlib::mmod_rect, std::allocator<dlib::mmod_rect>> detected_faces)
{
// TODO: Check why is this giving error
filesystem::path p(file_path);
uintmax_t f_size = filesystem::file_size(p);
pugi::xml_node file_obj = parent.append_child("fileobject");
file_obj.append_child("filesize").text().set(f_size);
string delimiter = "__id__";
string aux_name(p.filename().string());
string img_n = aux_name.substr(0, aux_name.find(delimiter));
file_obj.append_child("filename").text().set(img_n.c_str());
// incluir as hashs
unsigned char hash_buff[SHA_DIGEST_LENGTH];
if (openssl_sha1((char *)file_path, hash_buff))
{
cout << "Error getting file hash" << endl;//dlog << LWARN << "Error getting file hash";
}
else
{
pugi::xml_node hash_nodeMD5 = file_obj.append_child("hashdigest");
hash_nodeMD5.append_attribute("type") = "sha1";
char tmphash[SHA_DIGEST_LENGTH];
for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++)
{
sprintf((char *)&(tmphash[i * 2]), "%02x", hash_buff[i]);
}
hash_nodeMD5.text().set(tmphash);
}
pugi::xml_node detection_node = file_obj.append_child("facialdetection");
detection_node.append_child("number_faces").text().set(number_faces);
std::stringstream ss;
ss << original_width << "x" << original_height;
detection_node.append_child("original_size").text().set(ss.str().c_str());
ss.clear();
ss.str("");
ss << working_width << "x" << working_height;
detection_node.append_child("working_size").text().set(ss.str().c_str());
for (int i = 1; i <= detected_faces.size(); i++)
{
std::stringstream ss;
rectangle rec = detected_faces[i - 1];
ss << rec.left() << " "
<< rec.top() << " "
<< rec.right() << " "
<< rec.bottom();
pugi::xml_node face_node = detection_node.append_child("face");
face_node.text().set(ss.str().c_str());
pugi::xml_node score = face_node.append_child("confidence_score");
// TODO:: Converter / arredondar
score.text().set(detected_faces[i].detection_confidence);
}
}
| 27.812834
| 107
| 0.698135
|
AlexXandreE
|
fd2410d646360c792463ce53d98290865390a08b
| 9,868
|
cc
|
C++
|
src/delay_escape.cc
|
DouglasRMiles/QuProlog
|
798d86f87fb4372b8918ef582ef2f0fc0181af2d
|
[
"Apache-2.0"
] | 5
|
2019-11-20T02:05:31.000Z
|
2022-01-06T18:59:16.000Z
|
src/delay_escape.cc
|
logicmoo/QuProlog
|
798d86f87fb4372b8918ef582ef2f0fc0181af2d
|
[
"Apache-2.0"
] | null | null | null |
src/delay_escape.cc
|
logicmoo/QuProlog
|
798d86f87fb4372b8918ef582ef2f0fc0181af2d
|
[
"Apache-2.0"
] | 2
|
2022-01-08T13:52:24.000Z
|
2022-03-07T17:41:37.000Z
|
// delay_escape.cc - General delay mechanism.
//
// ##Copyright##
//
// Copyright 2000-2016 Peter Robinson (pjr@itee.uq.edu.au)
//
// 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.00
//
// 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.
//
// ##Copyright##
//
// $Id: delay_escape.cc,v 1.7 2006/01/31 23:17:49 qp Exp $
//#include "atom_table.h"
#include "global.h"
#include "thread_qp.h"
//
// psi_delay(variable, term)
// Delay the call to term and associate the problem with variable.
// mode(in,in)
//
Thread::ReturnValue
Thread::psi_delay(Object *& object1, Object *& object2)
{
assert(object1->variableDereference()->hasLegalSub());
assert(object2->variableDereference()->hasLegalSub());
Object* val1 = heap.dereference(object1);
Object* val2 = heap.dereference(object2);
assert(val1->isAnyVariable());
//
// Delay the problem.
//
delayProblem(val2, val1);
//
// Complete operation.
//
return(RV_SUCCESS);
}
//
// psi_delayed_problems_for_var(variable, term)
// Return the list of delayed problems associated with the given variable.
// mode(in,out)
//
Thread::ReturnValue
Thread::psi_delayed_problems_for_var(Object *& object1, Object *& object2)
{
Object* o = object1;
Object* delays = AtomTable::nil;
assert(o != NULL);
while (o->isAnyVariable())
{
delays = OBJECT_CAST(Reference*, o)->getDelays();
Object* n = OBJECT_CAST(Reference*, o)->getReference();
if ((n == o) || !delays->isNil())
{
object2 = delays;
return(RV_SUCCESS);
}
o = n;
}
object2 = delays;
return(RV_SUCCESS);
}
//
// psi_get_bound_structure(variable, variable)
// Return the dereferenced variable as the argument of a "bound" structure.
// mode(in,out)
//
Thread::ReturnValue
Thread::psi_get_bound_structure(Object *& object1, Object *& object2)
{
assert(object1->variableDereference()->hasLegalSub());
Object* val1 = heap.dereference(object1);
assert(val1->isAnyVariable());
if (val1->isVariable())
{
val1 = addExtraInfo(OBJECT_CAST(Variable*, val1));
}
Structure* newstruct = heap.newStructure(1);
newstruct->setFunctor(atoms->add("bound"));
newstruct->setArgument(1,val1);
Structure* boundstruct = heap.newStructure(1);
boundstruct->setFunctor(atoms->add("$bound"));
boundstruct->setArgument(1,newstruct);
object2 = boundstruct;
return(RV_SUCCESS);
}
//
// psi_psidelay_resume
// Restore the thread state after a retry delay from a pseudo instruction
// mode()
//
Thread::ReturnValue
Thread::psi_psidelay_resume(void)
{
assert(false);
status.resetNeckCutRetry();
RestoreXRegisters();
programCounter = savedPC;
return(RV_SUCCESS);
}
//
// psi_get_delays(delays,type,avoid)
// Return the list of delayed problems of given type
// type is 'all' or 'unify' other than those in avoid.
// mode(out,in,in)
//
Thread::ReturnValue
Thread::psi_get_delays(Object *& delaylist, Object*& type, Object*& avoid)
{
bool unify_only = (type->variableDereference() == atoms->add("unify"));
Object *delays = AtomTable::nil;
Object *avoid_list = avoid->variableDereference();
for (Object *global_delays =
ipTable.getImplicitPara(AtomTable::delays)->variableDereference();
global_delays->isCons();
global_delays = OBJECT_CAST(Cons *, global_delays)->getTail()->variableDereference())
{
assert(OBJECT_CAST(Cons *, global_delays)->getHead()->variableDereference()->isStructure());
Structure *delay
= OBJECT_CAST(Structure*, OBJECT_CAST(Cons *, global_delays)->getHead()->variableDereference());
assert(delay->getArity() == 2);
Object* status = delay->getArgument(1)->variableDereference();
if (!status->isVariable() || !OBJECT_CAST(Variable*,status)->isFrozen())
{
continue;
}
Object* var = delay->getArgument(2);
Object* vdelays;
(void)psi_delayed_problems_for_var(var, vdelays);
for (; vdelays->isCons();
vdelays = OBJECT_CAST(Cons*,
vdelays)->getTail()->variableDereference())
{
Object* vd =
OBJECT_CAST(Cons*, vdelays)->getHead()->variableDereference();
assert(vd->isStructure());
Structure* vdstruct = OBJECT_CAST(Structure *, vd);
assert(vdstruct->getArity() == 2);
Object* vdstatus = vdstruct->getArgument(1)->variableDereference();
assert(vdstatus->isVariable());
if (!OBJECT_CAST(Variable*,vdstatus)->isFrozen())
{
continue;
}
Object* problem = vdstruct->getArgument(2)->variableDereference();
if (avoid_list->inList(problem))
{
continue;
}
if (unify_only)
{
if (!problem->isStructure())
{
continue;
}
Structure* pstruct = OBJECT_CAST(Structure*, problem);
if (pstruct->getArity() == 2 &&
pstruct->getFunctor() == AtomTable::equal)
{
delays = heap.newCons(problem, delays);
}
}
else
{
if (!problem->isStructure())
{
delays = heap.newCons(problem, delays);
}
else
{
Structure* pstruct = OBJECT_CAST(Structure*, problem);
if (pstruct->getArity() == 2 &&
pstruct->getFunctor() == atoms->add("delay_until") &&
pstruct->getArgument(1)->variableDereference()->isStructure())
{
Structure* arg1struct = OBJECT_CAST(Structure*, pstruct->getArgument(1)->variableDereference());
if (arg1struct->getArity() == 1 &&
arg1struct->getFunctor() == atoms->add("$bound"))
{
Structure* newpstruct = heap.newStructure(2);
newpstruct->setFunctor(pstruct->getFunctor());
newpstruct->setArgument(1,arg1struct->getArgument(1));
newpstruct->setArgument(2,pstruct->getArgument(2));
delays = heap.newCons(newpstruct, delays);
continue;
}
}
delays = heap.newCons(problem, delays);
}
}
}
}
delaylist = delays;
return RV_SUCCESS;
}
//
// psi_bound(term)
// test if term is bound to something
// mode(in)
//
Thread::ReturnValue
Thread::psi_bound(Object *& object1)
{
Object* deref = object1->variableDereference();
return BOOL_TO_RV(deref != object1);
}
//
// Remove any solved problems associated with any variables.
//
Thread::ReturnValue
Thread::psi_compress_var_delays()
{
for (Object *global_delays =
ipTable.getImplicitPara(AtomTable::delays)->variableDereference();
global_delays->isCons();
global_delays = OBJECT_CAST(Cons *, global_delays)->getTail()->variableDereference())
{
assert(OBJECT_CAST(Cons *, global_delays)->getHead()->variableDereference()->isStructure());
Structure *delay = OBJECT_CAST(Structure*, OBJECT_CAST(Cons *, global_delays)->getHead()->variableDereference());
assert(delay->getArity() == 2);
Object* status = delay->getArgument(1)->variableDereference();
if (!status->isVariable() || !OBJECT_CAST(Variable*,status)->isFrozen())
{
continue;
}
// Get the variable with delays
Reference* var = OBJECT_CAST(Reference*, delay->getArgument(2)->variableDereference());
bool solved_found = false;
Object* var_delays = var->getDelays();
if (!var_delays->isNil())
{
// Compress delay list
// Find the first delay to keep
for ( ; var_delays->isCons();
var_delays = OBJECT_CAST(Cons *, var_delays)->getTail())
{
Structure *delay =
OBJECT_CAST(Structure *,
OBJECT_CAST(Cons *, var_delays)->getHead());
Variable *delay_status = OBJECT_CAST(Variable*,
delay->getArgument(1));
if (delay_status->isThawed())
{
// Solved problem
solved_found = true;
}
else
{
break;
}
}
if (solved_found)
{
updateAndTrailObject(reinterpret_cast<heapobject*>(var),
var_delays,
Reference::DelaysOffset);
}
// Scan the rest of the delay list
if (var_delays->isNil())
{
if (solved_found)
{
updateAndTrailObject(reinterpret_cast<heapobject*>(var),
var_delays,
Reference::DelaysOffset);
}
// Nothing to do
continue;
}
solved_found = false;
Object* look_ahead = OBJECT_CAST(Cons *, var_delays)->getTail();
for ( ; look_ahead->isCons();
look_ahead = OBJECT_CAST(Cons *, look_ahead)->getTail())
{
Structure *delay =
OBJECT_CAST(Structure *,
OBJECT_CAST(Cons *, look_ahead)->getHead());
Variable *delay_status = OBJECT_CAST(Variable*,
delay->getArgument(1));
if (delay_status->isThawed())
{
solved_found = true;
}
else
{
if (solved_found)
{
solved_found = false;
// point var_delays at next unsolved problem
updateAndTrailObject(reinterpret_cast<heapobject*>(var_delays), look_ahead, Cons::TailOffset);
}
var_delays = look_ahead;
}
}
if (solved_found)
{
solved_found = false;
// point var_delays at next unsolved problem
updateAndTrailObject(reinterpret_cast<heapobject*>(var_delays), look_ahead, Cons::TailOffset);
}
}
}
return RV_SUCCESS;
}
//
// Retry the delayed nfi problems.
//
Thread::ReturnValue
Thread::psi_retry_ov_delays(void)
{
return BOOL_TO_RV(retry_delays(NFI));
}
//
// Retry the delayed nfi and = problems.
//
Thread::ReturnValue
Thread::psi_retry_ov_eq_delays(void)
{
bool result = retry_delays(BOTH);
if (result)
{
(void)psi_compress_var_delays();
return RV_SUCCESS;
}
else
{
return RV_FAIL;
}
}
| 26.67027
| 119
| 0.654439
|
DouglasRMiles
|
fd2800700bc7399c059178e0cf7a11648c28c198
| 6,819
|
hpp
|
C++
|
mainframe/simd.hpp
|
tedmiddleton/mainframe
|
0d0537e8936d60c30573f08506f92bd6e8455fcf
|
[
"BSL-1.0"
] | null | null | null |
mainframe/simd.hpp
|
tedmiddleton/mainframe
|
0d0537e8936d60c30573f08506f92bd6e8455fcf
|
[
"BSL-1.0"
] | null | null | null |
mainframe/simd.hpp
|
tedmiddleton/mainframe
|
0d0537e8936d60c30573f08506f92bd6e8455fcf
|
[
"BSL-1.0"
] | null | null | null |
// Copyright Ted Middleton 2022.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)
#ifndef INCLUDED_mainframe_simd_h
#define INCLUDED_mainframe_simd_h
#include <iostream>
#if __AVX__
#include <immintrin.h>
#endif
#include "mainframe/base.hpp"
namespace mf { namespace detail
{
template< typename T >
T
mean( const T* t, size_t num )
{
const T* e = t + num;
T m = static_cast<T>(0);
for ( const T* c = t ; c != e; c++ ) {
m += *c;
}
return static_cast<T>(m / num);
}
#ifdef __AVX__
float
mean( const float* t, size_t num )
{
size_t i = 0;
__m256 accum = _mm256_setzero_ps();
for ( ; i+8 < num; i += 8 ) {
__m256 vals = _mm256_loadu_ps( t + i );
accum = _mm256_add_ps( accum, vals );
}
float ms[8];
_mm256_storeu_ps( ms, accum );
float m = ms[0] + ms[1] + ms[2] + ms[3] + ms[4] + ms[5] + ms[6] + ms[7];
for ( ; i < num; i += 1 ) {
m += t[ i ];
}
return m / num;
}
double
mean( const double* t, size_t num )
{
size_t i = 0;
__m256d accum = _mm256_setzero_pd();
for ( ; i+4 < num; i += 4 ) {
__m256d vals = _mm256_loadu_pd( t + i );
accum = _mm256_add_pd( accum, vals );
}
double ms[4];
_mm256_storeu_pd( ms, accum );
double m = ms[0] + ms[1] + ms[2] + ms[3];
for ( ; i < num; i += 1 ) {
m += t[ i ];
}
return m / num;
}
#endif
template< typename A, typename B >
auto
correlate_pearson( const A* a, const B* b, size_t num ) -> decltype( a[0] * b[0] )
{
using T = decltype(a[0] * b[0]);
A amean = mean( a, num );
B bmean = mean( b, num );
const A* aend = a + num;
const A* acurr = a;
const B* bcurr = b;
A aaccum = static_cast<A>( 0 );
B baccum = static_cast<B>( 0 );
double cov = 0.0;
for ( ; acurr != aend; ++acurr, ++bcurr ) {
A xa = *acurr;
B xb = *bcurr;
A adiff = xa - amean;
B bdiff = xb - bmean;
A adiffsq = adiff * adiff;
B bdiffsq = bdiff * bdiff;
T abdiff = adiff * bdiff;
aaccum += adiffsq;
baccum += bdiffsq;
cov += abdiff;
}
T corr = static_cast<T>(cov / std::sqrt( aaccum * baccum ));
return corr;
}
#ifdef __AVX__
double
correlate_pearson( const double* a, const double* b, size_t num )
{
double samean = mean( a, num );
double sbmean = mean( b, num );
__m256d amean = _mm256_set1_pd( samean );
__m256d bmean = _mm256_set1_pd( sbmean );
__m256d aaccum = _mm256_setzero_pd();
__m256d baccum = _mm256_setzero_pd();
__m256d cov = _mm256_setzero_pd();
size_t k = 0;
for ( ; k + 4 < num; k += 4 ) {
__m256d xa, xb, adiff, bdiff, adiffsq, bdiffsq, abdiff;
xa = _mm256_loadu_pd( a + k );
xb = _mm256_loadu_pd( b + k );
adiff = _mm256_sub_pd( xa, amean );
bdiff = _mm256_sub_pd( xb, bmean );
adiffsq = _mm256_mul_pd( adiff, adiff );
bdiffsq = _mm256_mul_pd( bdiff, bdiff );
abdiff = _mm256_mul_pd( adiff, bdiff );
aaccum = _mm256_add_pd( aaccum, adiffsq );
baccum = _mm256_add_pd( baccum, bdiffsq );
cov = _mm256_add_pd( cov, abdiff );
}
double mcov[4];
_mm256_storeu_pd( mcov, cov );
double fcov = mcov[0] + mcov[1] + mcov[2] + mcov[3];
double maaccum[4];
_mm256_storeu_pd( maaccum, aaccum );
double faaccum = maaccum[0] + maaccum[1] + maaccum[2] + maaccum[3];
double mbaccum[4];
_mm256_storeu_pd( mbaccum, baccum );
double fbaccum = mbaccum[0] + mbaccum[1] + mbaccum[2] + mbaccum[3];
for ( ; k < num; k+=1 ) {
double xa = a[k];
double xb = b[k];
double adiff = xa - samean;
double bdiff = xb - sbmean;
double adiffsq = adiff * adiff;
double bdiffsq = bdiff * bdiff;
double abdiff = adiff * bdiff;
faaccum += adiffsq;
fbaccum += bdiffsq;
fcov += abdiff;
}
double corr = fcov / std::sqrt( faaccum * fbaccum );
return corr;
}
float
correlate_pearson( const float* a, const float* b, size_t num )
{
float samean = mean( a, num );
float sbmean = mean( b, num );
__m256 amean = _mm256_set1_ps( samean );
__m256 bmean = _mm256_set1_ps( sbmean );
__m256 aaccum = _mm256_setzero_ps();
__m256 baccum = _mm256_setzero_ps();
__m256 cov = _mm256_setzero_ps();
size_t k = 0;
for ( ; k + 8 < num; k += 8 ) {
__m256 xa, xb, adiff, bdiff, adiffsq, bdiffsq, abdiff;
xa = _mm256_loadu_ps( a + k );
xb = _mm256_loadu_ps( b + k );
adiff = _mm256_sub_ps( xa, amean );
bdiff = _mm256_sub_ps( xb, bmean );
adiffsq = _mm256_mul_ps( adiff, adiff );
bdiffsq = _mm256_mul_ps( bdiff, bdiff );
abdiff = _mm256_mul_ps( adiff, bdiff );
aaccum = _mm256_add_ps( aaccum, adiffsq );
baccum = _mm256_add_ps( baccum, bdiffsq );
cov = _mm256_add_ps( cov, abdiff );
}
float mcov[8];
_mm256_storeu_ps( mcov, cov );
float fcov = mcov[0] + mcov[1] + mcov[2] + mcov[3]
+ mcov[4] + mcov[5] + mcov[6] + mcov[7];
float maaccum[8];
_mm256_storeu_ps( maaccum, aaccum );
float faaccum = maaccum[0] + maaccum[1] + maaccum[2] + maaccum[3]
+ maaccum[4] + maaccum[5] + maaccum[6] + maaccum[7];
float mbaccum[8];
_mm256_storeu_ps( mbaccum, baccum );
float fbaccum = mbaccum[0] + mbaccum[1] + mbaccum[2] + mbaccum[3]
+ mbaccum[4] + mbaccum[5] + mbaccum[6] + mbaccum[7];
for ( ; k < num; k+=1 ) {
float xa = a[k];
float xb = b[k];
float adiff = xa - samean;
float bdiff = xb - sbmean;
float adiffsq = adiff * adiff;
float bdiffsq = bdiff * bdiff;
float abdiff = adiff * bdiff;
faaccum += adiffsq;
fbaccum += bdiffsq;
fcov += abdiff;
}
float corr = fcov / std::sqrt( faaccum * fbaccum );
return corr;
}
#endif
}} // namespace mf::detail
#endif // INCLUDED_mainframe_simd_h
| 32.317536
| 86
| 0.504326
|
tedmiddleton
|
fd2c00958ee0c29a9372d7d291a87f62e06360d7
| 608
|
cpp
|
C++
|
programa25.cpp
|
sclip/sis110-02-2020
|
a4ef1ece3e9ed08058c829e421a54d38e210cdba
|
[
"MIT"
] | null | null | null |
programa25.cpp
|
sclip/sis110-02-2020
|
a4ef1ece3e9ed08058c829e421a54d38e210cdba
|
[
"MIT"
] | null | null | null |
programa25.cpp
|
sclip/sis110-02-2020
|
a4ef1ece3e9ed08058c829e421a54d38e210cdba
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <iomanip>
using namespace std;
/**
Escribir un programa para leer un numero entero por teclado
y mostrar por pantalla la siguiente figura:
*
**
***
Ej. Entrada
3
4
Salida
*
**
***
*
**
***
****
*/
int main()
{
int n;
cin>>n;
/*for(int i=0;i<n;i++)
{
for(int j=0;j<i+1;j++)
cout<<"*";
cout<<endl;
}*/
/*for(int i=0;i<n;i++)
{
string puntos(i+1,'*');
cout<<puntos<<endl;
//cout<<string(i+1,'*')<<endl;
}*/
for(int i=0;i<n;i++)
cout<<setfill('*')<<setw(i+1)<<""<<endl;
return 0;
}
| 14.139535
| 59
| 0.481908
|
sclip
|
fd2cda45ca6cffd6827ca5976551252252ded072
| 836
|
hpp
|
C++
|
src/gpu/metal.hpp
|
DveloperY0115/FirstRayTracer
|
9487bbf4a3c7ac0ad2343fdaca6b5d8548f1e332
|
[
"MIT"
] | 1
|
2021-02-18T08:38:21.000Z
|
2021-02-18T08:38:21.000Z
|
src/gpu/metal.hpp
|
DveloperY0115/RTFoundation
|
9487bbf4a3c7ac0ad2343fdaca6b5d8548f1e332
|
[
"MIT"
] | 1
|
2020-05-15T16:42:33.000Z
|
2020-05-17T07:23:43.000Z
|
src/gpu/metal.hpp
|
DveloperY0115/ray-tracing-in-one-weekend-cpp
|
4a293f8db7eefd1d62e6be46a53d65ff348eaa52
|
[
"MIT"
] | null | null | null |
//
// Created by dveloperY0115 on 1/28/2021.
//
#ifndef RAY_TRACING_IN_CPP_METAL_H
#define RAY_TRACING_IN_CPP_METAL_H
#include "material.hpp"
class metal : public material {
public:
__device__ metal(const vector3& a, float f) : albedo(a) { if (f < 1) fuzz = f; else fuzz = 1; }
__device__ virtual bool scatter(const ray& r_in, const hit_record& rec, vector3& attenuation,
ray& scattered, curandState *local_rand_state) const {
vector3 reflected = reflect(unit_vector(r_in.direction()), rec.normal);
scattered = ray(rec.p, reflected + fuzz * random_in_unit_sphere(local_rand_state), r_in.time());
attenuation = albedo;
return (dot(scattered.direction(), rec.normal) > 0.0f);
}
vector3 albedo;
float fuzz;
};
#endif //RAY_TRACING_IN_CPP_METAL_H
| 33.44
| 104
| 0.671053
|
DveloperY0115
|
fd2d436eb0a749e2aff868b3752eb523aeca493c
| 127
|
cpp
|
C++
|
AtCoder/ABC053/A/abc053_a.cpp
|
object-oriented-human/competitive
|
9e761020e887d8980a39a64eeaeaa39af0ecd777
|
[
"MIT"
] | 2
|
2021-07-27T10:46:47.000Z
|
2021-07-27T10:47:57.000Z
|
AtCoder/ABC053/A/abc053_a.cpp
|
foooop/competitive
|
9e761020e887d8980a39a64eeaeaa39af0ecd777
|
[
"MIT"
] | null | null | null |
AtCoder/ABC053/A/abc053_a.cpp
|
foooop/competitive
|
9e761020e887d8980a39a64eeaeaa39af0ecd777
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int main() {
int x; cin >> x;
x < 1200 ? cout << "ABC" : cout << "ARC";
}
| 21.166667
| 45
| 0.527559
|
object-oriented-human
|
fd2fca42ac4233c6c7f31c5f4b012afe20f3aa79
| 10,173
|
cpp
|
C++
|
Source/AllProjects/Tests2/TestCIDMData/TestCIDMData_AttrData.cpp
|
MarkStega/CIDLib
|
82014e064eef51cad998bf2c694ed9c1c8cceac6
|
[
"MIT"
] | 216
|
2019-03-09T06:41:28.000Z
|
2022-02-25T16:27:19.000Z
|
Source/AllProjects/Tests2/TestCIDMData/TestCIDMData_AttrData.cpp
|
MarkStega/CIDLib
|
82014e064eef51cad998bf2c694ed9c1c8cceac6
|
[
"MIT"
] | 9
|
2020-09-27T08:00:52.000Z
|
2021-07-02T14:27:31.000Z
|
Source/AllProjects/Tests2/TestCIDMData/TestCIDMData_AttrData.cpp
|
MarkStega/CIDLib
|
82014e064eef51cad998bf2c694ed9c1c8cceac6
|
[
"MIT"
] | 29
|
2019-03-09T10:12:24.000Z
|
2021-03-03T22:25:29.000Z
|
//
// FILE NAME: TestMData_AttrData.cpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 08/07/2018
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2019
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// These are tests of the attribute data classes.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $_CIDLib_Log_$
//
// ---------------------------------------------------------------------------
// Include our public header and our own specific header
// ---------------------------------------------------------------------------
#include "TestCIDMData.hpp"
#include "TestCIDMData_AttrData.hpp"
// ---------------------------------------------------------------------------
// Magic macros
// ---------------------------------------------------------------------------
RTTIDecls(TTest_AttrDataBasic, TTestFWTest)
// ---------------------------------------------------------------------------
// CLASS: TTest_AttrDataBasic
// PREFIX: tfwt
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TTest_AttrDataBasic: Constructor and Destructor
// ---------------------------------------------------------------------------
TTest_AttrDataBasic::TTest_AttrDataBasic() :
TTestFWTest
(
L"Attr Data 1", L"Basic tests of the attribute data class", 4
)
{
}
TTest_AttrDataBasic::~TTest_AttrDataBasic()
{
}
// ---------------------------------------------------------------------------
// TTest_AttrDataBasic: Public, inherited methods
// ---------------------------------------------------------------------------
tTestFWLib::ETestRes
TTest_AttrDataBasic::eRunTest(TTextStringOutStream& strmOut, tCIDLib::TBoolean& bWarning)
{
tTestFWLib::ETestRes eRes = tTestFWLib::ETestRes::Success;
tCIDLib::TBoolean bRes;
// Test a default constructed one for initial state
{
TAttrData adatDef;
bRes = bTestState3
(
strmOut
, L"def ctor"
, CID_LINE
, adatDef
, TString::strEmpty()
, TString::strEmpty()
, TString::strEmpty()
, tCIDMData::EAttrTypes::String
, tCIDMData::EAttrEdTypes::None
, TString::strEmpty()
, 0
, TString::strEmpty()
);
if (!bRes)
eRes = tTestFWLib::ETestRes::Failed;
}
// Test setting and reading back each value type
{
TAttrData adatType;
//
// Do boolean type
//
adatType.Set
(
L"Bool Test"
, L"/Test/Boolean"
, TString::strEmpty()
, tCIDMData::EAttrTypes::Bool
);
bRes = bTestState
(
strmOut
, L"Bool Test"
, CID_LINE
, adatType
, TString::strEmpty()
, tCIDMData::EAttrTypes::Bool
, L"False"
);
if (!bRes)
eRes = tTestFWLib::ETestRes::Failed;
adatType.SetBool(kCIDLib::True);
if (adatType.bVal() != kCIDLib::True)
{
strmOut << TFWCurLn << L"Did not get back set true value" << kCIDLib::NewLn;
eRes = tTestFWLib::ETestRes::Failed;
}
//
// Do Card type
//
adatType.Set
(
L"Card Test"
, L"/Test/Card"
, TString::strEmpty()
, tCIDMData::EAttrTypes::Card
);
bRes = bTestState
(
strmOut
, L"Card Test"
, CID_LINE
, adatType
, TString::strEmpty()
, tCIDMData::EAttrTypes::Card
, L"0"
);
if (!bRes)
eRes = tTestFWLib::ETestRes::Failed;
adatType.SetCard(11);
if (adatType.c4Val() != 11)
{
strmOut << TFWCurLn << L"Did not get back set 11 value" << kCIDLib::NewLn;
eRes = tTestFWLib::ETestRes::Failed;
}
}
return eRes;
}
// ---------------------------------------------------------------------------
// TTest_AttrDataBasic: Private, non-virtual methods
// ---------------------------------------------------------------------------
// Avoid some redundancy by providing a test for basic state of an attribute
tCIDLib::TBoolean
TTest_AttrDataBasic::bTestState( TTextOutStream& strmOut
, const TString& strTestName
, const tCIDLib::TCard4 c4Line
, const TAttrData& adatTest
, const TString& strLimits
, const tCIDMData::EAttrTypes eType
, const TString& strFmtValue)
{
tCIDLib::TBoolean bRet = kCIDLib::True;
if (eType != adatTest.eType())
{
strmOut << TTFWCurLn(CID_FILE, c4Line)
<< strTestName << L" should have type "
<< tCIDMData::strXlatEAttrTypes(eType)
<< L" but has "
<< tCIDMData::strXlatEAttrTypes(adatTest.eType())
<< kCIDLib::NewLn;
bRet = kCIDLib::False;
}
if (strLimits != adatTest.strLimits())
{
strmOut << TTFWCurLn(CID_FILE, c4Line)
<< strTestName << L" should have limit '"
<< strLimits
<< L"' but has '"
<< adatTest.strLimits()
<< L"'\n";
bRet = kCIDLib::False;
}
// Format the value to test
TString strTestVal;
adatTest.FormatToText(strTestVal);
if (strTestVal != strFmtValue)
{
strmOut << TTFWCurLn(CID_FILE, c4Line)
<< strTestName << L" should have value '"
<< strFmtValue
<< L"' but has '"
<< strTestVal
<< L"'\n";
bRet = kCIDLib::False;
}
return bRet;
}
tCIDLib::TBoolean
TTest_AttrDataBasic::bTestState2( TTextOutStream& strmOut
, const TString& strTestName
, const tCIDLib::TCard4 c4Line
, const TAttrData& adatTest
, const TString& strAttrId
, const TString& strSpecType
, const TString& strLimits
, const tCIDMData::EAttrTypes eType
, const tCIDMData::EAttrEdTypes eEditType
, const TString& strFmtValue)
{
// Call the other version first
tCIDLib::TBoolean bRet = bTestState
(
strmOut
, strTestName
, c4Line
, adatTest
, strLimits
, eType
, strFmtValue
);
if (strAttrId != adatTest.strId())
{
strmOut << TTFWCurLn(CID_FILE, c4Line)
<< strTestName << L" should have id '"
<< strAttrId
<< L"' but has '"
<< adatTest.strId()
<< L"'\n";
bRet = kCIDLib::False;
}
if (strSpecType != adatTest.strSpecType())
{
strmOut << TTFWCurLn(CID_FILE, c4Line)
<< strTestName << L" should have special type '"
<< strSpecType
<< L"' but has '"
<< adatTest.strSpecType()
<< L"'\n";
bRet = kCIDLib::False;
}
if (eEditType != adatTest.eEditType())
{
strmOut << TTFWCurLn(CID_FILE, c4Line)
<< strTestName << L" should have edit type "
<< tCIDMData::strXlatEAttrEdTypes(eEditType)
<< L" but has "
<< tCIDMData::strXlatEAttrEdTypes(adatTest.eEditType())
<< kCIDLib::NewLn;
bRet = kCIDLib::False;
}
return bRet;
}
tCIDLib::TBoolean
TTest_AttrDataBasic::bTestState3( TTextOutStream& strmOut
, const TString& strTestName
, const tCIDLib::TCard4 c4Line
, const TAttrData& adatTest
, const TString& strAttrId
, const TString& strSpecType
, const TString& strLimits
, const tCIDMData::EAttrTypes eType
, const tCIDMData::EAttrEdTypes eEditType
, const TString& strFmtValue
, const tCIDLib::TCard8 c8UserData
, const TString& strUserData)
{
// Call the other version first
tCIDLib::TBoolean bRet = bTestState2
(
strmOut
, strTestName
, c4Line
, adatTest
, strAttrId
, strSpecType
, strLimits
, eType
, eEditType
, strFmtValue
);
// And do our extra bits
if (c8UserData != adatTest.c8User())
{
strmOut << TTFWCurLn(CID_FILE, c4Line)
<< strTestName << L" should have TCard8 user data "
<< c8UserData
<< L" but has "
<< adatTest.c8User()
<< kCIDLib::NewLn;
bRet = kCIDLib::False;
}
if (strUserData != adatTest.strUserData())
{
strmOut << TTFWCurLn(CID_FILE, c4Line)
<< strTestName << L" should have string user data '"
<< strUserData
<< L"' but has '"
<< adatTest.strUserData()
<< L"'\n";
bRet = kCIDLib::False;
}
return bRet;
}
| 30.276786
| 89
| 0.433009
|
MarkStega
|
fd308e43d5783a3a00f7b1922d8f468429a6f363
| 5,015
|
cpp
|
C++
|
City/City/Testing/CCityTest.cpp
|
NicholsTyler/cse_335
|
b8a46522c15a9881cb681ae94b4a5f737817b05e
|
[
"MIT"
] | null | null | null |
City/City/Testing/CCityTest.cpp
|
NicholsTyler/cse_335
|
b8a46522c15a9881cb681ae94b4a5f737817b05e
|
[
"MIT"
] | null | null | null |
City/City/Testing/CCityTest.cpp
|
NicholsTyler/cse_335
|
b8a46522c15a9881cb681ae94b4a5f737817b05e
|
[
"MIT"
] | null | null | null |
#include "pch.h"
#include "CppUnitTest.h"
#include "City.h"
#include "TileRoad.h"
#include "TileLandscape.h"
#include "TileCoalmine.h"
#include "TileBuilding.h"
using namespace std;
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace Testing
{
class CTestVisitor : public CTileVisitor
{
public:
virtual void VisitRoad(CTileRoad* road) override { mNumRoads++; }
virtual void VisitLandscape(CTileLandscape* landScape) override { mNumLandScapes++; }
virtual void VisitCoalmine(CTileCoalmine* coalMine) override { mNumCoalMines++; }
virtual void VisitBuilding(CTileBuilding* building) override { mNumBuildings++; }
int mNumRoads = 0;
int mNumLandScapes = 0;
int mNumCoalMines = 0;
int mNumBuildings = 0;
};
TEST_CLASS(CCityTest)
{
public:
TEST_METHOD_INITIALIZE(methodName)
{
extern wchar_t g_dir[];
::SetCurrentDirectory(g_dir);
}
TEST_METHOD(TestCCityConstructor)
{
CCity city;
}
/** Tests for the GetAdjacent function
*/
TEST_METHOD(TestCCityAdjacent)
{
CCity city;
int grid = CCity::GridSpacing;
// Add a center tile to test
auto center = make_shared<CTileRoad>(&city);
center->SetLocation(grid * 10, grid * 17);
city.Add(center);
// Upper left
auto ul = make_shared<CTileRoad>(&city);
ul->SetLocation(grid * 8, grid * 16);
city.Add(ul);
city.SortTiles();
Assert::IsTrue(city.GetAdjacent(center, -1, -1) == ul, L"Upper left test");
Assert::IsTrue(city.GetAdjacent(center, 1, -1) == nullptr, L"Upper right null test");
// Upper right
auto ur = make_shared<CTileRoad>(&city);
ur->SetLocation(grid * 12, grid * 16);
city.Add(ur);
// Lower left
auto ll = make_shared<CTileRoad>(&city);
ll->SetLocation(grid * 8, grid * 18);
city.Add(ll);
// Lower right
auto lr = make_shared<CTileRoad>(&city);
lr->SetLocation(grid * 12, grid * 18);
city.Add(lr);
city.SortTiles();
Assert::IsTrue(city.GetAdjacent(center, 1, -1) == ur, L"Upper right test");
Assert::IsTrue(city.GetAdjacent(center, -1, 1) == ll, L"Lower left test");
Assert::IsTrue(city.GetAdjacent(center, 1, 1) == lr, L"Lower right test");
}
TEST_METHOD(TestCCityIterator)
{
// Construct a city object
CCity city;
// Add some tiles
auto tile1 = make_shared<CTileRoad>(&city);
auto tile2 = make_shared<CTileRoad>(&city);
auto tile3 = make_shared<CTileRoad>(&city);
city.Add(tile1);
city.Add(tile2);
city.Add(tile3);
// Does begin point to the first tile?
auto iter1 = city.begin();
auto iter2 = city.end();
Assert::IsTrue(tile1 == *iter1, L"First item correct");
++iter1;
Assert::IsTrue(tile2 == *iter1, L"Second item correct");
++iter1;
Assert::IsTrue(tile3 == *iter1, L"Third item correct");
++iter1;
Assert::IsFalse(iter1 != iter2);
}
TEST_METHOD(TestCCityVisitor)
{
// Construct a city object
CCity city;
// Add some tiles of each time
auto tile1 = make_shared<CTileRoad>(&city);
auto tile2 = make_shared<CTileBuilding>(&city);
auto tile3 = make_shared<CTileLandscape>(&city);
auto tile4 = make_shared<CTileCoalmine>(&city);
city.Add(tile1);
city.Add(tile2);
city.Add(tile3);
city.Add(tile4);
CTestVisitor visitor;
city.Accept(&visitor);
Assert::AreEqual(1, visitor.mNumRoads,
L"Visitor number of roads");
Assert::AreEqual(1, visitor.mNumLandScapes,
L"Visitor number of landscapes");
Assert::AreEqual(1, visitor.mNumCoalMines,
L"Visitor number of coalmines");
Assert::AreEqual(1, visitor.mNumBuildings,
L"Visitor number of buildings");
// Construct an empty city object
CCity emptyCity;
CTestVisitor emptyVisitor;
emptyCity.Accept(&emptyVisitor);
Assert::AreEqual(0, emptyVisitor.mNumRoads,
L"Visitor number of roads");
Assert::AreEqual(0, emptyVisitor.mNumLandScapes,
L"Visitor number of landscapes");
Assert::AreEqual(0, emptyVisitor.mNumCoalMines,
L"Visitor number of coalmines");
Assert::AreEqual(0, emptyVisitor.mNumBuildings,
L"Visitor number of buildings");
}
};
}
| 31.740506
| 97
| 0.554935
|
NicholsTyler
|
fd38913ee6929ff670690ff8689318fe63932139
| 1,315
|
cpp
|
C++
|
cpp/301-310/Minimum Height Trees.cpp
|
KaiyuWei/leetcode
|
fd61f5df60cfc7086f7e85774704bacacb4aaa5c
|
[
"MIT"
] | 150
|
2015-04-04T06:53:49.000Z
|
2022-03-21T13:32:08.000Z
|
cpp/301-310/Minimum Height Trees.cpp
|
yizhu1012/leetcode
|
d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7
|
[
"MIT"
] | 1
|
2015-04-13T15:15:40.000Z
|
2015-04-21T20:23:16.000Z
|
cpp/301-310/Minimum Height Trees.cpp
|
yizhu1012/leetcode
|
d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7
|
[
"MIT"
] | 64
|
2015-06-30T08:00:07.000Z
|
2022-01-01T16:44:14.000Z
|
class Solution {
public:
vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
vector<int> res;
if(n <= 2) {
for(int i = 0;i < n;i++)
res.push_back(i);
return res;
}
int k = 0;
vector<set<int>> myvec(n, set<int>());
queue<int> myqueue;
for(auto e : edges) {
myvec[e.first].insert(e.second);
myvec[e.second].insert(e.first);
}
for(int i = 0;i < n;i++) {
if(myvec[i].size() == 1) {
myqueue.push(i);
k++;
}
}
while(1) {
int j = myqueue.size();
for(int i = 0;i < j;i++) {
int v = myqueue.front();
myqueue.pop();
for(auto e : myvec[v]) {
myvec[e].erase(v);
if(myvec[e].size() == 1) {
myqueue.push(e);
k++;
}
}
}
if(n == k) break;
}
while(!myqueue.empty()) {
res.push_back(myqueue.front());
myqueue.pop();
}
sort(res.begin(), res.end());
return res;
}
};
| 25.784314
| 74
| 0.349049
|
KaiyuWei
|
fd3de0284634f25e8345852b89225993adb5fd8c
| 21,395
|
cpp
|
C++
|
SpockLib/c_view.cpp
|
zachmakesgames/Spock
|
bb5a6a9b4ce2c86fe49c08b7aa1ae633b95443e4
|
[
"MIT"
] | null | null | null |
SpockLib/c_view.cpp
|
zachmakesgames/Spock
|
bb5a6a9b4ce2c86fe49c08b7aa1ae633b95443e4
|
[
"MIT"
] | null | null | null |
SpockLib/c_view.cpp
|
zachmakesgames/Spock
|
bb5a6a9b4ce2c86fe49c08b7aa1ae633b95443e4
|
[
"MIT"
] | null | null | null |
#include "c_view.h"
c_view::c_view(c_instance *instance, c_device *device, int x, int y) :
m_instance(instance), m_device(device), m_closing_callback(nullptr), m_resize_callback(nullptr),
m_extent_2D({})
{
VkResult result;
//Set up the window
this->m_extent_2D.height= y;
this->m_extent_2D.width= x;
this->m_window= glfwCreateWindow(x, y, m_instance->get_instance_name().c_str(), NULL, NULL);
result= glfwCreateWindowSurface(*this->m_instance->get_instance(), this->m_window, NULL, &this->m_window_surface);
if (result != VK_SUCCESS) {
#ifdef DEBUG
std::cout << "Vulkan encountered an error with glfwCreateWindowSurface: " << result << std::endl;
#endif
throw std::exception("Could not create GLFW window surface");
}
//Check for surface support, vulkan will complain if we dont
VkBool32 supported_surface= false;
result= vkGetPhysicalDeviceSurfaceSupportKHR(*this->m_device->get_physical_device(), this->m_device->get_graphics_queue_family_index(), this->m_window_surface, &supported_surface);
if (result != VK_SUCCESS) {
#ifdef DEBUG
std::cout << "Vulkan could not determine if surface is supported: " << result << std::endl;
#endif
throw std::exception("Could not create GLFW window surface");
}
if (!supported_surface) {
#ifdef DEBUG
std::cout << "SURFACE IS NOT SUPPORTED!!!!" << std::endl;
#endif
throw std::exception("GLFW surface is not supported by this device");
}
//Check which formats are available
//First find out how many there are
uint32_t format_count= -1;
vkGetPhysicalDeviceSurfaceFormatsKHR(*this->m_device->get_physical_device(), this->m_window_surface, &format_count, nullptr);
VkSurfaceFormatKHR *supported_formats= new VkSurfaceFormatKHR[format_count];
//Then populate the formats
vkGetPhysicalDeviceSurfaceFormatsKHR(*this->m_device->get_physical_device(), this->m_window_surface, &format_count, supported_formats);
#ifdef DEBUG
std::cout << "Found " << format_count << " supported formats" << std::endl;
for (int i= 0; i < format_count; i++) {
switch (supported_formats[i].format) {
case VK_FORMAT_R8G8B8A8_UNORM: std::cout << "Format: VK_FORMAT_R8G8B8A8_UNORM" << std::endl;
break;
case VK_FORMAT_R8G8B8A8_SNORM: std::cout << "Format: VK_FORMAT_R8G8B8A8_SNORM" << std::endl;
break;
case VK_FORMAT_R8G8B8A8_USCALED: std::cout << "Format: VK_FORMAT_R8G8B8A8_USCALED" << std::endl;
break;
case VK_FORMAT_R8G8B8A8_SSCALED: std::cout << "Format: VK_FORMAT_R8G8B8A8_SSCALED" << std::endl;
break;
case VK_FORMAT_R8G8B8A8_UINT: std::cout << "Format: VK_FORMAT_R8G8B8A8_UINT" << std::endl;
break;
case VK_FORMAT_R8G8B8A8_SINT: std::cout << "Format: VK_FORMAT_R8G8B8A8_SINT" << std::endl;
break;
case VK_FORMAT_R8G8B8A8_SRGB: std::cout << "Format: VK_FORMAT_R8G8B8A8_SRGB" << std::endl;
break;
case VK_FORMAT_B8G8R8A8_UNORM: std::cout << "Format: VK_FORMAT_B8G8R8A8_UNORM" << std::endl;
break;
case VK_FORMAT_B8G8R8A8_SNORM: std::cout << "Format: VK_FORMAT_B8G8R8A8_SNORM" << std::endl;
break;
case VK_FORMAT_B8G8R8A8_USCALED: std::cout << "Format: VK_FORMAT_B8G8R8A8_USCALED" << std::endl;
break;
case VK_FORMAT_B8G8R8A8_SSCALED: std::cout << "Format: VK_FORMAT_B8G8R8A8_SSCALED" << std::endl;
break;
case VK_FORMAT_B8G8R8A8_UINT: std::cout << "Format: VK_FORMAT_B8G8R8A8_UINT" << std::endl;
break;
case VK_FORMAT_B8G8R8A8_SINT: std::cout << "Format: VK_FORMAT_B8G8R8A8_SINT" << std::endl;
break;
case VK_FORMAT_B8G8R8A8_SRGB: std::cout << "Format: VK_FORMAT_B8G8R8A8_SRGB" << std::endl;
break;
}
switch (supported_formats[i].colorSpace) {
case VK_COLOR_SPACE_SRGB_NONLINEAR_KHR: std::cout << "Colorspace: VK_COLOR_SPACE_SRGB_NONLINEAR_KHR" << std::endl;
break;
case VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT: std::cout << "Colorspace: VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT" << std::endl;
break;
case VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT: std::cout << "Colorspace: VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT" << std::endl;
break;
case VK_COLOR_SPACE_DCI_P3_LINEAR_EXT: std::cout << "Colorspace: VK_COLOR_SPACE_DCI_P3_LINEAR_EXT" << std::endl;
break;
case VK_COLOR_SPACE_DCI_P3_NONLINEAR_EXT: std::cout << "Colorspace: VK_COLOR_SPACE_DCI_P3_NONLINEAR_EXT" << std::endl;
break;
case VK_COLOR_SPACE_BT709_LINEAR_EXT: std::cout << "Colorspace: VK_COLOR_SPACE_BT709_LINEAR_EXT" << std::endl;
break;
case VK_COLOR_SPACE_BT709_NONLINEAR_EXT: std::cout << "Colorspace: VK_COLOR_SPACE_BT709_NONLINEAR_EXT" << std::endl;
break;
case VK_COLOR_SPACE_BT2020_LINEAR_EXT: std::cout << "Colorspace: VK_COLOR_SPACE_BT2020_LINEAR_EXT" << std::endl;
break;
case VK_COLOR_SPACE_HDR10_ST2084_EXT: std::cout << "Colorspace: VK_COLOR_SPACE_HDR10_ST2084_EXT" << std::endl;
break;
case VK_COLOR_SPACE_DOLBYVISION_EXT: std::cout << "Colorspace: VK_COLOR_SPACE_DOLBYVISION_EXT" << std::endl;
break;
case VK_COLOR_SPACE_HDR10_HLG_EXT: std::cout << "Colorspace: VK_COLOR_SPACE_HDR10_HLG_EXT" << std::endl;
break;
}
}
#endif
//Check which present modes are available
uint32_t present_mode_count= -1;
vkGetPhysicalDeviceSurfacePresentModesKHR(*this->m_device->get_physical_device(), this->m_window_surface, &present_mode_count, nullptr);
VkPresentModeKHR *present_modes= new VkPresentModeKHR[present_mode_count];
//Then populate the present modes
vkGetPhysicalDeviceSurfacePresentModesKHR(*this->m_device->get_physical_device(), this->m_window_surface, &present_mode_count, present_modes);
#ifdef DEBUG
std::cout << "Found " << present_mode_count << " presentation modes" << std::endl;
for (int i= 0; i < present_mode_count; i++) {
switch (present_modes[i]) {
case VK_PRESENT_MODE_IMMEDIATE_KHR: std::cout << "VK_PRESENT_MODE_IMMEDIATE_KHR" << std::endl;
break;
case VK_PRESENT_MODE_MAILBOX_KHR: std::cout << "VK_PRESENT_MODE_MAILBOX_KHR" << std::endl;
break;
case VK_PRESENT_MODE_FIFO_KHR: std::cout << "VK_PRESENT_MODE_FIFO_KHR" << std::endl;
break;
case VK_PRESENT_MODE_FIFO_RELAXED_KHR: std::cout << "VK_PRESENT_MODE_FIFO_RELAXED_KHR" << std::endl;
break;
case VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR: std::cout << "VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR" << std::endl;
break;
case VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR: std::cout << "VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR" << std::endl;
break;
}
}
#endif
//Set up the swap chain creation info
///TODO: set this up more dynamically
this->m_swapchain_create_info.sType= VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
this->m_swapchain_create_info.pNext= nullptr;
this->m_swapchain_create_info.flags= 0;
this->m_swapchain_create_info.surface= this->m_window_surface;
this->m_swapchain_create_info.minImageCount= this->m_swapchain_image_count;
//VkFormat selectedFormat= this->GetImageFormat();
this->m_swapchain_create_info.imageFormat= VK_FORMAT_B8G8R8A8_SRGB;
this->m_swapchain_create_info.imageColorSpace= VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;// this->GetColorSpaceFromFormat(selectedFormat);
this->m_swapchain_create_info.presentMode= VK_PRESENT_MODE_IMMEDIATE_KHR; ///TODO: Add method to use different present modes
this->m_swapchain_create_info.imageExtent= this->m_extent_2D;
this->m_swapchain_create_info.imageArrayLayers= 1;
this->m_swapchain_create_info.imageUsage= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
this->m_swapchain_create_info.preTransform= VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
this->m_swapchain_create_info.compositeAlpha= VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
this->m_swapchain_create_info.imageSharingMode= VK_SHARING_MODE_EXCLUSIVE;
this->m_swapchain_create_info.queueFamilyIndexCount= this->m_device->get_graphics_queue_family_index();
this->m_swapchain_create_info.pQueueFamilyIndices= nullptr;
this->m_swapchain_create_info.oldSwapchain= VK_NULL_HANDLE;
this->m_swapchain_create_info.clipped= VK_TRUE;
result= vkCreateSwapchainKHR(*this->m_device->get_logical_device(), &this->m_swapchain_create_info, nullptr, &this->m_swapchain);
if (result != VK_SUCCESS) {
#ifdef DEBUG
std::cout << "Vulkan encountered an error creating the swapchain: " << result << std::endl;
#endif
throw std::exception("Could not create swapchain");
}
//Next get the swapchain images
result= vkGetSwapchainImagesKHR(*this->m_device->get_logical_device(), this->m_swapchain, &this->m_swapchain_image_count, nullptr);
if (result != VK_SUCCESS) {
#ifdef DEBUG
std::cout << "Vulkan encountered an error getting the present image count: " << result << std::endl;
#endif
throw std::exception("Could not get swapchain images");
}
if (this->m_present_image_count < this->m_swapchain_image_count) {
#ifdef DEBUG
std::cout << "Did not get the number of requested swap chain images!" << std::endl;
#endif
throw std::exception("Swapchain/present image count mismatch");
}
this->m_present_images= new VkImage[this->m_present_image_count];
result= vkGetSwapchainImagesKHR(*this->m_device->get_logical_device(), this->m_swapchain, &this->m_present_image_count, this->m_present_images);
if (result != VK_SUCCESS) {
#ifdef DEBUG
std::cout << "Vulkan encountered an error getting the present images: " << result << std::endl;
#endif
throw std::exception("Error creating swapchain images");
}
//Set up Present Views
this->m_present_image_views= new VkImageView[this->m_present_image_count];
this->m_present_image_view_create_info= new VkImageViewCreateInfo[this->m_present_image_count];
for (int i= 0; i < this->m_present_image_count; i++) {
this->m_present_image_view_create_info[i].sType= VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
this->m_present_image_view_create_info[i].pNext= nullptr;
this->m_present_image_view_create_info[i].flags= 0;
this->m_present_image_view_create_info[i].viewType= VK_IMAGE_VIEW_TYPE_2D;
this->m_present_image_view_create_info[i].format= VK_FORMAT_B8G8R8A8_SRGB; //need to correlate this to the available formats above?
//this->m_present_image_view_create_info[i].format= this->GetImageFormat(); //There, now its linked to the available formats
this->m_present_image_view_create_info[i].components.r= VK_COMPONENT_SWIZZLE_R;
this->m_present_image_view_create_info[i].components.g= VK_COMPONENT_SWIZZLE_G;
this->m_present_image_view_create_info[i].components.b= VK_COMPONENT_SWIZZLE_B;
this->m_present_image_view_create_info[i].components.a= VK_COMPONENT_SWIZZLE_A;
this->m_present_image_view_create_info[i].subresourceRange.aspectMask= VK_IMAGE_ASPECT_COLOR_BIT;
this->m_present_image_view_create_info[i].subresourceRange.baseMipLevel= 0;
this->m_present_image_view_create_info[i].subresourceRange.levelCount= 1;
this->m_present_image_view_create_info[i].subresourceRange.baseArrayLayer= 0;
this->m_present_image_view_create_info[i].subresourceRange.layerCount= 1;
this->m_present_image_view_create_info[i].image= this->m_present_images[i];
result= vkCreateImageView(*this->m_device->get_logical_device(), &this->m_present_image_view_create_info[i], nullptr, &this->m_present_image_views[i]);
if (result != VK_SUCCESS) {
#ifdef DEBUG
std::cout << "Vulkan encountered an error creating image view " << i << ": " << result << std::endl;
#endif
throw std::exception("Could not create image view");
}
}
//Set up the depth stencil
this->m_extent_3D= { this->m_extent_2D.width, this->m_extent_2D.height, 1 };
this->m_image_create_info.sType= VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
this->m_image_create_info.pNext= nullptr;
this->m_image_create_info.flags= 0;
this->m_image_create_info.imageType= VK_IMAGE_TYPE_2D;
this->m_image_create_info.format= VK_FORMAT_D32_SFLOAT_S8_UINT;
this->m_image_create_info.extent= this->m_extent_3D;
this->m_image_create_info.mipLevels= 1;
this->m_image_create_info.arrayLayers= 1;
this->m_image_create_info.samples= VK_SAMPLE_COUNT_1_BIT;
this->m_image_create_info.tiling= VK_IMAGE_TILING_OPTIMAL;
this->m_image_create_info.usage= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
this->m_image_create_info.sharingMode= VK_SHARING_MODE_EXCLUSIVE;
this->m_image_create_info.queueFamilyIndexCount= 0;
this->m_image_create_info.pQueueFamilyIndices= nullptr;
this->m_image_create_info.initialLayout= VK_IMAGE_LAYOUT_UNDEFINED;
this->m_depth_stencil_image= {};
result= vkCreateImage(*this->m_device->get_logical_device(), &this->m_image_create_info, nullptr, &this->m_depth_stencil_image);
if (result != VK_SUCCESS) {
#ifdef DEBUG
std::cout << "Vulkan encountered an error creating the depth stencil: " << result << std::endl;
#endif
throw std::exception("Could not create depth stencil image");
}
//Get information about what memory requirements the depth stencil needs
vkGetImageMemoryRequirements(*this->m_device->get_logical_device(), this->m_depth_stencil_image, &this->m_stencil_requirements);
VkPhysicalDeviceMemoryProperties memProperties= {}; ///TODO: Do this in the Device class earlier and save for later use
vkGetPhysicalDeviceMemoryProperties(*this->m_device->get_physical_device(), &memProperties);
//Find memory that is device local
uint32_t memoryIndex= -1;
for (unsigned int i= 0; i < memProperties.memoryTypeCount; i++) {
VkMemoryType memType= memProperties.memoryTypes[i];
VkMemoryPropertyFlags memFlags= memType.propertyFlags;
if ((this->m_stencil_requirements.memoryTypeBits & (1 << i)) != 0) {
if ((memFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0) {
memoryIndex= i;
break;
}
}
}
if (memoryIndex < 0) {
throw std::exception("No device memory??!!");
}
//Set up the memory allocation info struct
this->m_stencil_memory_alloc_info.sType= VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
this->m_stencil_memory_alloc_info.pNext= nullptr;
this->m_stencil_memory_alloc_info.allocationSize= this->m_stencil_requirements.size;
this->m_stencil_memory_alloc_info.memoryTypeIndex= memoryIndex;
//Then allocate the memory
this->m_stencil_memory= new VkDeviceMemory();
result= vkAllocateMemory(*this->m_device->get_logical_device(), &this->m_stencil_memory_alloc_info, nullptr, this->m_stencil_memory);
if (result != VK_SUCCESS) {
#ifdef DEBUG
std::cout << "Vulkan encountered an error allocating memory for the depth stencil: " << result << std::endl;
#endif
throw std::exception("Could not allocate memory for depth stencil");
}
//And bind the memory
result= vkBindImageMemory(*this->m_device->get_logical_device(), this->m_depth_stencil_image, *this->m_stencil_memory, 0);
if (result != VK_SUCCESS) {
#ifdef DEBUG
std::cout << "Vulkan encountered an error binding the depth stencil image memory: " << result << std::endl;
#endif
throw std::exception("Could not bind stnecil image memory");
}
//
//Then set up the image view
this->m_image_view_create_info.sType= VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
this->m_image_view_create_info.pNext= nullptr;
this->m_image_view_create_info.flags= 0;
this->m_image_view_create_info.image= this->m_depth_stencil_image;
this->m_image_view_create_info.viewType= VK_IMAGE_VIEW_TYPE_2D;
this->m_image_view_create_info.format= this->m_image_create_info.format;
this->m_image_view_create_info.components.r= VK_COMPONENT_SWIZZLE_IDENTITY;
this->m_image_view_create_info.components.g= VK_COMPONENT_SWIZZLE_IDENTITY;
this->m_image_view_create_info.components.b= VK_COMPONENT_SWIZZLE_IDENTITY;
this->m_image_view_create_info.components.a= VK_COMPONENT_SWIZZLE_IDENTITY;
this->m_image_view_create_info.subresourceRange.aspectMask= VK_IMAGE_ASPECT_DEPTH_BIT;
this->m_image_view_create_info.subresourceRange.baseMipLevel= 0;
this->m_image_view_create_info.subresourceRange.levelCount= 1;
this->m_image_view_create_info.subresourceRange.baseArrayLayer= 0;
this->m_image_view_create_info.subresourceRange.layerCount= 1;
this->m_image_view= new VkImageView();
result= vkCreateImageView(*this->m_device->get_logical_device(), &this->m_image_view_create_info, nullptr, this->m_image_view);
if (result != VK_SUCCESS) {
#ifdef DEBUG
std::cout << "Vulkan encountered an error creating the image view: " << result << std::endl;
#endif
throw std::exception("Could not create image view");
}
//
//Then set up render passes
//copied this from sample code developed by Dr. Mike Bailey at Oregon State University
//Doesn't really need to be changed yet so I'm attributing the original author because reasons
// need 2 - one for the color and one for the depth/stencil
VkAttachmentDescription vad[2];
//vad[0].format= VK_FORMAT_B8G8R8A8_UNORM;
vad[0].format= VK_FORMAT_B8G8R8A8_SRGB;
//vad[0].format= this->GetImageFormat();
vad[0].samples= VK_SAMPLE_COUNT_1_BIT;
vad[0].loadOp= VK_ATTACHMENT_LOAD_OP_CLEAR;
vad[0].storeOp= VK_ATTACHMENT_STORE_OP_STORE;
vad[0].stencilLoadOp= VK_ATTACHMENT_LOAD_OP_DONT_CARE;
vad[0].stencilStoreOp= VK_ATTACHMENT_STORE_OP_DONT_CARE;
vad[0].initialLayout= VK_IMAGE_LAYOUT_UNDEFINED;
vad[0].finalLayout= VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
vad[0].flags= 0;
//vad[0].flags= VK_ATTACHMENT_DESCRIPTION_MAT_ALIAS_BIT;
vad[1].format= VK_FORMAT_D32_SFLOAT_S8_UINT; //Note this is not using GetImageFormat because the depth format is different
vad[1].samples= VK_SAMPLE_COUNT_1_BIT;
vad[1].loadOp= VK_ATTACHMENT_LOAD_OP_CLEAR;
vad[1].storeOp= VK_ATTACHMENT_STORE_OP_DONT_CARE;
vad[1].stencilLoadOp= VK_ATTACHMENT_LOAD_OP_DONT_CARE;
vad[1].stencilStoreOp= VK_ATTACHMENT_STORE_OP_DONT_CARE;
vad[1].initialLayout= VK_IMAGE_LAYOUT_UNDEFINED;
vad[1].finalLayout= VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
vad[1].flags= 0;
VkAttachmentReference colorReference;
colorReference.attachment= 0;
colorReference.layout= VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkAttachmentReference depthReference;
depthReference.attachment= 1;
depthReference.layout= VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkSubpassDescription vsd;
vsd.flags= 0;
vsd.pipelineBindPoint= VK_PIPELINE_BIND_POINT_GRAPHICS;
vsd.inputAttachmentCount= 0;
vsd.pInputAttachments= (VkAttachmentReference*)nullptr;
vsd.colorAttachmentCount= 1;
vsd.pColorAttachments= &colorReference;
vsd.pResolveAttachments= (VkAttachmentReference*)nullptr;
vsd.pDepthStencilAttachment= &depthReference;
vsd.preserveAttachmentCount= 0;
vsd.pPreserveAttachments= (uint32_t*)nullptr;
this->m_render_pass_create_info.sType= VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
this->m_render_pass_create_info.pNext= nullptr;
this->m_render_pass_create_info.flags= 0;
this->m_render_pass_create_info.attachmentCount= 2;
this->m_render_pass_create_info.pAttachments= vad;
this->m_render_pass_create_info.subpassCount= 1;
this->m_render_pass_create_info.pSubpasses= &vsd;
this->m_render_pass_create_info.dependencyCount= 0;
this->m_render_pass_create_info.pDependencies= nullptr;
this->m_render_passes= new VkRenderPass();
result= vkCreateRenderPass(*this->m_device->get_logical_device(), &this->m_render_pass_create_info, nullptr, this->m_render_passes);
if (result != VK_SUCCESS) {
#ifdef DEBUG
std::cout << "Vulkan encountered an error creating the render pass: " << result << std::endl;
#endif
throw std::exception("Could not create render passes");
}
//
//Finally set up the frame buffer
this->m_framebuffers= new VkFramebuffer[this->m_framebuffer_count];
this->m_framebuffer_create_info.sType= VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
this->m_framebuffer_create_info.pNext= nullptr;
this->m_framebuffer_create_info.flags= 0;
this->m_framebuffer_create_info.renderPass= *this->m_render_passes;
this->m_framebuffer_create_info.attachmentCount= 2;
this->m_framebuffer_create_info.pAttachments= this->m_framebuffer_attachments;
this->m_framebuffer_create_info.width= this->m_extent_2D.width;
this->m_framebuffer_create_info.height= this->m_extent_2D.height;
this->m_framebuffer_create_info.layers= 1;
this->m_framebuffer_attachments[0]= this->m_present_image_views[0];
this->m_framebuffer_attachments[1]= *this->m_image_view;
result= vkCreateFramebuffer(*this->m_device->get_logical_device(), &this->m_framebuffer_create_info, nullptr, &this->m_framebuffers[0]);
if (result != VK_SUCCESS) {
#ifdef DEBUG
std::cout << "Vulkan encountered an error creating the first frame buffer: " << result << std::endl;
#endif
throw std::exception("Could not create first frame buffer");
}
this->m_framebuffer_attachments[0]= this->m_present_image_views[1];
this->m_framebuffer_attachments[1]= *this->m_image_view;
result= vkCreateFramebuffer(*this->m_device->get_logical_device(), &this->m_framebuffer_create_info, nullptr, &this->m_framebuffers[1]);
if (result != VK_SUCCESS) {
#ifdef DEBUG
std::cout << "Vulkan encountered an error creating the second frame buffer: " << result << std::endl;
#endif
throw std::exception("Could not create second frame buffer");
}
}
VkSwapchainKHR *c_view::get_swapchain() {
return &this->m_swapchain;
}
VkExtent2D c_view::get_extent_2D() {
return this->m_extent_2D;
}
VkRenderPass *c_view::get_render_pass() {
return this->m_render_passes;
}
VkFramebuffer *c_view::get_frame_buffers(int *out_count) {
if (out_count != nullptr) {
*out_count= this->m_framebuffer_count;
}
return this->m_framebuffers;
}
void c_view::set_closing_callback(std::function<void()> new_callback) {
this->m_closing_callback= new_callback;
}
void c_view::set_resize_callback(std::function<void(int, int)> new_callback) {
this->m_resize_callback= new_callback;
}
void c_view::resize(int x, int y) {
///TODO: implement this
}
| 43.222222
| 181
| 0.783454
|
zachmakesgames
|
fd475727ae2c507e53318e34ee7a5ba5fe66d3e7
| 4,400
|
cpp
|
C++
|
dwarf/SB/Game/zCamMarker.cpp
|
stravant/bfbbdecomp
|
2126be355a6bb8171b850f829c1f2731c8b5de08
|
[
"OLDAP-2.7"
] | 1
|
2021-01-05T11:28:55.000Z
|
2021-01-05T11:28:55.000Z
|
dwarf/SB/Game/zCamMarker.cpp
|
sonich2401/bfbbdecomp
|
5f58b62505f8929a72ccf2aa118a1539eb3a5bd6
|
[
"OLDAP-2.7"
] | null | null | null |
dwarf/SB/Game/zCamMarker.cpp
|
sonich2401/bfbbdecomp
|
5f58b62505f8929a72ccf2aa118a1539eb3a5bd6
|
[
"OLDAP-2.7"
] | 1
|
2022-03-30T15:15:08.000Z
|
2022-03-30T15:15:08.000Z
|
typedef struct xCamAsset;
typedef struct zCamMarker;
typedef struct xSerial;
typedef struct _tagxCamFollowAsset;
typedef struct xBase;
typedef struct xVec3;
typedef struct _tagxCamShoulderAsset;
typedef struct xLinkAsset;
typedef struct xBaseAsset;
typedef struct _tagp2CamStaticAsset;
typedef struct _tagp2CamStaticFollowAsset;
typedef enum _tagTransType;
typedef struct _tagxCamPathAsset;
typedef int32(*type_1)(xBase*, xBase*, uint32, float32*, xBase*);
typedef int32(*type_4)(xBase*, xBase*, uint32, float32*, xBase*);
typedef float32 type_0[4];
typedef uint32 type_2[2];
typedef uint8 type_3[3];
struct xCamAsset : xBaseAsset
{
xVec3 pos;
xVec3 at;
xVec3 up;
xVec3 right;
xVec3 view_offset;
int16 offset_start_frames;
int16 offset_end_frames;
float32 fov;
float32 trans_time;
_tagTransType trans_type;
uint32 flags;
float32 fade_up;
float32 fade_down;
union
{
_tagxCamFollowAsset cam_follow;
_tagxCamShoulderAsset cam_shoulder;
_tagp2CamStaticAsset cam_static;
_tagxCamPathAsset cam_path;
_tagp2CamStaticFollowAsset cam_staticFollow;
};
uint32 valid_flags;
uint32 markerid[2];
uint8 cam_type;
uint8 pad[3];
};
struct zCamMarker : xBase
{
xCamAsset* asset;
};
struct xSerial
{
};
struct _tagxCamFollowAsset
{
float32 rotation;
float32 distance;
float32 height;
float32 rubber_band;
float32 start_speed;
float32 end_speed;
};
struct xBase
{
uint32 id;
uint8 baseType;
uint8 linkCount;
uint16 baseFlags;
xLinkAsset* link;
int32(*eventFunc)(xBase*, xBase*, uint32, float32*, xBase*);
};
struct xVec3
{
float32 x;
float32 y;
float32 z;
};
struct _tagxCamShoulderAsset
{
float32 distance;
float32 height;
float32 realign_speed;
float32 realign_delay;
};
struct xLinkAsset
{
uint16 srcEvent;
uint16 dstEvent;
uint32 dstAssetID;
float32 param[4];
uint32 paramWidgetAssetID;
uint32 chkAssetID;
};
struct xBaseAsset
{
uint32 id;
uint8 baseType;
uint8 linkCount;
uint16 baseFlags;
};
struct _tagp2CamStaticAsset
{
uint32 unused;
};
struct _tagp2CamStaticFollowAsset
{
float32 rubber_band;
};
enum _tagTransType
{
eTransType_None,
eTransType_Interp1,
eTransType_Interp2,
eTransType_Interp3,
eTransType_Interp4,
eTransType_Linear,
eTransType_Interp1Rev,
eTransType_Interp2Rev,
eTransType_Interp3Rev,
eTransType_Interp4Rev,
eTransType_Total
};
struct _tagxCamPathAsset
{
uint32 assetID;
float32 time_end;
float32 time_delay;
};
int32(*zCamMarkerEventCB)(xBase*, xBase*, uint32, float32*, xBase*);
int32 zCamMarkerEventCB(xBase* to, uint32 toEvent, float32* toParam);
void zCamMarkerLoad(zCamMarker* m, xSerial* s);
void zCamMarkerSave(zCamMarker* m, xSerial* s);
void zCamMarkerInit(xBase* b, xCamAsset* asset);
// zCamMarkerEventCB__FP5xBaseP5xBaseUiPCfP5xBase
// Start address: 0x310910
int32 zCamMarkerEventCB(xBase* to, uint32 toEvent, float32* toParam)
{
// Line 47, Address: 0x310910, Func Offset: 0
// Line 51, Address: 0x310914, Func Offset: 0x4
// Line 59, Address: 0x310948, Func Offset: 0x38
// Line 60, Address: 0x310954, Func Offset: 0x44
// Line 62, Address: 0x31095c, Func Offset: 0x4c
// Line 63, Address: 0x310960, Func Offset: 0x50
// Line 64, Address: 0x310968, Func Offset: 0x58
// Line 67, Address: 0x310970, Func Offset: 0x60
// Line 72, Address: 0x310978, Func Offset: 0x68
// Line 71, Address: 0x31097c, Func Offset: 0x6c
// Line 72, Address: 0x310980, Func Offset: 0x70
// Func End, Address: 0x310988, Func Offset: 0x78
}
// zCamMarkerLoad__FP10zCamMarkerP7xSerial
// Start address: 0x310990
void zCamMarkerLoad(zCamMarker* m, xSerial* s)
{
// Line 38, Address: 0x310990, Func Offset: 0
// Func End, Address: 0x310998, Func Offset: 0x8
}
// zCamMarkerSave__FP10zCamMarkerP7xSerial
// Start address: 0x3109a0
void zCamMarkerSave(zCamMarker* m, xSerial* s)
{
// Line 29, Address: 0x3109a0, Func Offset: 0
// Func End, Address: 0x3109a8, Func Offset: 0x8
}
// zCamMarkerInit__FP5xBaseP9xCamAsset
// Start address: 0x3109b0
void zCamMarkerInit(xBase* b, xCamAsset* asset)
{
// Line 10, Address: 0x3109b0, Func Offset: 0
// Line 12, Address: 0x3109c4, Func Offset: 0x14
// Line 17, Address: 0x3109cc, Func Offset: 0x1c
// Line 18, Address: 0x3109d8, Func Offset: 0x28
// Line 21, Address: 0x3109e0, Func Offset: 0x30
// Line 23, Address: 0x3109ec, Func Offset: 0x3c
// Line 24, Address: 0x3109f0, Func Offset: 0x40
// Func End, Address: 0x310a04, Func Offset: 0x54
}
| 22
| 69
| 0.76
|
stravant
|
fd47afe859506578fb0db6362b231e20b435202e
| 2,634
|
cpp
|
C++
|
src/services/pcn-k8sfilter/src/serializer/K8sfilterJsonObject.cpp
|
francescomessina/polycube
|
38f2fb4ffa13cf51313b3cab9994be738ba367be
|
[
"ECL-2.0",
"Apache-2.0"
] | 337
|
2018-12-12T11:50:15.000Z
|
2022-03-15T00:24:35.000Z
|
src/services/pcn-k8sfilter/src/serializer/K8sfilterJsonObject.cpp
|
l1b0k/polycube
|
7af919245c131fa9fe24c5d39d10039cbb81e825
|
[
"ECL-2.0",
"Apache-2.0"
] | 253
|
2018-12-17T21:36:15.000Z
|
2022-01-17T09:30:42.000Z
|
src/services/pcn-k8sfilter/src/serializer/K8sfilterJsonObject.cpp
|
l1b0k/polycube
|
7af919245c131fa9fe24c5d39d10039cbb81e825
|
[
"ECL-2.0",
"Apache-2.0"
] | 90
|
2018-12-19T15:49:38.000Z
|
2022-03-27T03:56:07.000Z
|
/**
* k8sfilter API
* k8sfilter API generated from k8sfilter.yang
*
* OpenAPI spec version: 1.0.0
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/polycube-network/swagger-codegen.git
* branch polycube
*/
/* Do not edit this file manually */
#include "K8sfilterJsonObject.h"
#include <regex>
namespace io {
namespace swagger {
namespace server {
namespace model {
K8sfilterJsonObject::K8sfilterJsonObject() {
m_nameIsSet = false;
m_portsIsSet = false;
m_nodeportRange = "30000-32767";
m_nodeportRangeIsSet = true;
}
K8sfilterJsonObject::K8sfilterJsonObject(const nlohmann::json &val) :
JsonObjectBase(val) {
m_nameIsSet = false;
m_portsIsSet = false;
m_nodeportRangeIsSet = false;
if (val.count("name")) {
setName(val.at("name").get<std::string>());
}
if (val.count("ports")) {
for (auto& item : val["ports"]) {
PortsJsonObject newItem{ item };
m_ports.push_back(newItem);
}
m_portsIsSet = true;
}
if (val.count("nodeport-range")) {
setNodeportRange(val.at("nodeport-range").get<std::string>());
}
}
nlohmann::json K8sfilterJsonObject::toJson() const {
nlohmann::json val = nlohmann::json::object();
if (!getBase().is_null()) {
val.update(getBase());
}
if (m_nameIsSet) {
val["name"] = m_name;
}
{
nlohmann::json jsonArray;
for (auto& item : m_ports) {
jsonArray.push_back(JsonObjectBase::toJson(item));
}
if (jsonArray.size() > 0) {
val["ports"] = jsonArray;
}
}
if (m_nodeportRangeIsSet) {
val["nodeport-range"] = m_nodeportRange;
}
return val;
}
std::string K8sfilterJsonObject::getName() const {
return m_name;
}
void K8sfilterJsonObject::setName(std::string value) {
m_name = value;
m_nameIsSet = true;
}
bool K8sfilterJsonObject::nameIsSet() const {
return m_nameIsSet;
}
const std::vector<PortsJsonObject>& K8sfilterJsonObject::getPorts() const{
return m_ports;
}
void K8sfilterJsonObject::addPorts(PortsJsonObject value) {
m_ports.push_back(value);
m_portsIsSet = true;
}
bool K8sfilterJsonObject::portsIsSet() const {
return m_portsIsSet;
}
void K8sfilterJsonObject::unsetPorts() {
m_portsIsSet = false;
}
std::string K8sfilterJsonObject::getNodeportRange() const {
return m_nodeportRange;
}
void K8sfilterJsonObject::setNodeportRange(std::string value) {
m_nodeportRange = value;
m_nodeportRangeIsSet = true;
}
bool K8sfilterJsonObject::nodeportRangeIsSet() const {
return m_nodeportRangeIsSet;
}
void K8sfilterJsonObject::unsetNodeportRange() {
m_nodeportRangeIsSet = false;
}
}
}
}
}
| 18.680851
| 75
| 0.69552
|
francescomessina
|
fd4f885e8e2a92839403ee05655e3fa61ab11c12
| 1,952
|
cpp
|
C++
|
staff/samples/optional/component/src/TasksImpl.cpp
|
gale320/staff
|
c90e65a984e9931d803fc88243971639fe3876b7
|
[
"Apache-2.0"
] | 14
|
2015-04-04T17:42:53.000Z
|
2021-03-09T11:09:51.000Z
|
staff/samples/optional/component/src/TasksImpl.cpp
|
gale320/staff
|
c90e65a984e9931d803fc88243971639fe3876b7
|
[
"Apache-2.0"
] | 3
|
2015-07-30T13:22:42.000Z
|
2017-06-06T15:13:28.000Z
|
staff/samples/optional/component/src/TasksImpl.cpp
|
gale320/staff
|
c90e65a984e9931d803fc88243971639fe3876b7
|
[
"Apache-2.0"
] | 13
|
2015-04-25T20:43:45.000Z
|
2021-12-29T07:55:47.000Z
|
// This file generated by staff_codegen
// For more information please visit: http://code.google.com/p/staff/
// Service Implementation
#include "TasksImpl.h"
namespace samples
{
namespace optional
{
TasksImpl::TasksImpl()
{
}
TasksImpl::~TasksImpl()
{
}
void TasksImpl::OnCreate()
{
// this function is called when service instance is created and registered
}
void TasksImpl::OnDestroy()
{
// this function is called immediately before service instance destruction
}
int TasksImpl::Add(const Task& rstTask)
{
Task& rstAddedTask = *m_lsTasks.insert(m_lsTasks.end(), rstTask);
rstAddedTask.nId = m_lsTasks.size();
return *rstAddedTask.nId;
}
void TasksImpl::UpdateOwner(int nTaskId, const staff::Optional< int >& rtnOwnerId)
{
for (TasksList::iterator itTask = m_lsTasks.begin();
itTask != m_lsTasks.end(); ++itTask)
{
if (itTask->nId == nTaskId)
{
itTask->tnOwnerId = rtnOwnerId;
break;
}
}
}
void TasksImpl::UpdateAttachInfo(int nTaskId, const staff::Optional< AttachInfo >& rtnAttachInfo)
{
for (TasksList::iterator itTask = m_lsTasks.begin();
itTask != m_lsTasks.end(); ++itTask)
{
if (itTask->nId == nTaskId)
{
itTask->tstAttachInfo = rtnAttachInfo;
break;
}
}
}
staff::Optional< AttachInfo > samples::optional::TasksImpl::GetAttachInfo(int nTaskId)
{
for (TasksList::iterator itTask = m_lsTasks.begin();
itTask != m_lsTasks.end(); ++itTask)
{
if (itTask->nId == nTaskId)
{
return itTask->tstAttachInfo;
}
}
return staff::Optional< AttachInfo >();
}
::samples::optional::TasksList TasksImpl::GetAllTasks() const
{
return m_lsTasks;
}
staff::Optional< std::list<std::string> > TasksImpl::EchoOpt(
const staff::Optional< std::list<std::string> >& opt)
{
return opt;
}
std::list< staff::Optional<std::string> > TasksImpl::EchoOpt2(
const std::list< staff::Optional<std::string> >& opt)
{
return opt;
}
}
}
| 19.717172
| 97
| 0.674693
|
gale320
|
fd5134bdb38c6445f558d74504981cf0649ff898
| 45,308
|
cc
|
C++
|
src/main/cpp/controller/controller.cc
|
rdfostrich/cobra
|
b65ec1aa7b10e990a3b40d86636050377ff2d2d6
|
[
"MIT"
] | 4
|
2020-07-02T12:11:41.000Z
|
2021-11-03T13:44:57.000Z
|
src/main/cpp/controller/controller.cc
|
rdfostrich/cobra
|
b65ec1aa7b10e990a3b40d86636050377ff2d2d6
|
[
"MIT"
] | 6
|
2021-06-14T11:34:39.000Z
|
2021-06-29T15:10:16.000Z
|
src/main/cpp/controller/controller.cc
|
rdfostrich/cobra
|
b65ec1aa7b10e990a3b40d86636050377ff2d2d6
|
[
"MIT"
] | 1
|
2021-05-20T14:16:24.000Z
|
2021-05-20T14:16:24.000Z
|
#include <util/StopWatch.hpp>
#include "controller.h"
#include "snapshot_patch_iterator_triple_id.h"
#include "patch_builder_streaming.h"
#include "../snapshot/combined_triple_iterator.h"
#include "../simpleprogresslistener.h"
#include <sys/stat.h>
#include <boost/filesystem.hpp>
Controller::Controller(string basePath, int8_t kc_opts, bool readonly) : patchTreeManager(new PatchTreeManager(basePath, kc_opts, readonly)), snapshotManager(new SnapshotManager(basePath, readonly)) {
struct stat sb;
if (!(stat(basePath.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode))) {
throw std::invalid_argument("The provided path '" + basePath + "' is not a valid directory.");
}
}
Controller::~Controller() {
delete patchTreeManager;
delete snapshotManager;
}
size_t Controller::get_version_materialized_count_estimated(const Triple& triple_pattern, int patch_id) const {
return get_version_materialized_count(triple_pattern, patch_id, true).first;
}
std::pair<size_t, ResultEstimationType> Controller::get_version_materialized_count(const Triple& triple_pattern, int patch_id, bool allowEstimates) const {
int snapshot_id = get_corresponding_snapshot_id(patch_id);
if(snapshot_id < 0) {
return std::make_pair(0, EXACT);
}
HDT* snapshot = get_snapshot_manager()->get_snapshot(snapshot_id);
IteratorTripleID* snapshot_it = SnapshotManager::search_with_offset(snapshot, triple_pattern, 0);
size_t snapshot_count = snapshot_it->estimatedNumResults();
if (!allowEstimates && snapshot_it->numResultEstimation() != EXACT) {
snapshot_count = 0;
while (snapshot_it->hasNext()) {
snapshot_it->next();
snapshot_count++;
}
}
if(snapshot_id == patch_id) {
return std::make_pair(snapshot_count, snapshot_it->numResultEstimation());
}
DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id);
int patch_tree_id = get_patch_tree_id(patch_id);
PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id, dict);
if(patchTree == NULL) {
return std::make_pair(snapshot_count, snapshot_it->numResultEstimation());
}
std::pair<PatchPosition, Triple> deletion_count_data = patchTree->deletion_count(triple_pattern, patch_id);
size_t addition_count = patchTree->addition_count(patch_id, triple_pattern);
return std::make_pair(snapshot_count - deletion_count_data.first + addition_count, snapshot_it->numResultEstimation());
}
TripleIterator* Controller::get_version_materialized(const Triple &triple_pattern, int offset, int patch_id) const {
// Find the snapshot
int snapshot_id = get_corresponding_snapshot_id(patch_id);
if(snapshot_id < 0) {
//throw std::invalid_argument("No snapshot was found for version " + std::to_string(patch_id));
return new EmptyTripleIterator();
}
HDT* snapshot = get_snapshot_manager()->get_snapshot(snapshot_id);
// Simple case: We are requesting a snapshot, delegate lookup to that snapshot.
IteratorTripleID* snapshot_it = SnapshotManager::search_with_offset(snapshot, triple_pattern, offset);
if(snapshot_id == patch_id) {
return new SnapshotTripleIterator(snapshot_it);
}
DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id);
// Otherwise, we have to prepare an iterator for a certain patch
int patch_tree_id = get_patch_tree_id(patch_id);
PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id, dict);
if(patchTree == NULL) {
return new SnapshotTripleIterator(snapshot_it);
}
PositionedTripleIterator* deletion_it = NULL;
long added_offset = 0;
bool check_offseted_deletions = true;
// Limit the patch id to the latest available patch id
// int max_patch_id = patchTree->get_max_patch_id();
// if (patch_id > max_patch_id) {
// patch_id = max_patch_id;
// }
std::pair<PatchPosition, Triple> deletion_count_data = patchTree->deletion_count(triple_pattern, patch_id);
// This loop continuously determines new snapshot iterators until it finds one that contains
// no new deletions with respect to the snapshot iterator from last iteration.
// This loop is required to handle special cases like the one in the ControllerTest::EdgeCase1.
// As worst-case, this loop will take O(n) (n:dataset size), as an optimization we can look
// into storing long consecutive chains of deletions more efficiently.
while(check_offseted_deletions) {
if (snapshot_it->hasNext()) { // We have elements left in the snapshot we should apply deletions to
// Determine the first triple in the original snapshot and use it as offset for the deletion iterator
TripleID *tripleId = snapshot_it->next();
Triple firstTriple(tripleId->getSubject(), tripleId->getPredicate(), tripleId->getObject());
deletion_it = patchTree->deletion_iterator_from(firstTriple, patch_id, triple_pattern);
deletion_it->getPatchTreeIterator()->set_early_break(true);
// Calculate a new offset, taking into account deletions.
PositionedTriple first_deletion_triple;
long snapshot_offset = 0;
if (deletion_it->next(&first_deletion_triple, true)) {
snapshot_offset = first_deletion_triple.position;
} else {
// The exact snapshot triple could not be found as a deletion
if (patchTree->get_spo_comparator()->compare(firstTriple, deletion_count_data.second) < 0) {
// If the snapshot triple is smaller than the largest deletion,
// set the offset to zero, as all deletions will come *after* this triple.
// Note that it should impossible that there would exist a deletion *before* this snapshot triple,
// otherwise we would already have found this triple as a snapshot triple before.
// If we would run into issues because of this after all, we could do a backwards step with
// deletion_it and see if we find a triple matching the pattern, and use its position.
snapshot_offset = 0;
} else {
// If the snapshot triple is larger than the largest deletion,
// set the offset to the total number of deletions.
snapshot_offset = deletion_count_data.first;
}
}
long previous_added_offset = added_offset;
added_offset = snapshot_offset;
// Make a new snapshot iterator for the new offset
// TODO: look into reusing the snapshot iterator and applying a relative offset (NOTE: I tried it before, it's trickier than it seems...)
delete snapshot_it;
snapshot_it = SnapshotManager::search_with_offset(snapshot, triple_pattern, offset + added_offset);
// Check if we need to loop again
check_offseted_deletions = previous_added_offset < added_offset;
if(check_offseted_deletions) {
delete deletion_it;
deletion_it = NULL;
}
} else {
check_offseted_deletions = false;
}
}
return new SnapshotPatchIteratorTripleID(snapshot_it, deletion_it, patchTree->get_spo_comparator(), snapshot, triple_pattern, patchTree, patch_id, offset, deletion_count_data.first);
}
std::pair<size_t, ResultEstimationType> Controller::get_delta_materialized_count(const Triple &triple_pattern, int patch_id_start, int patch_id_end, bool allowEstimates) const {
int snapshot_id_start = get_corresponding_snapshot_id(patch_id_start);
int snapshot_id_end = get_corresponding_snapshot_id(patch_id_end);
int patch_tree_id_end = get_patch_tree_id(patch_id_end);
int patch_tree_id_start = get_patch_tree_id(patch_id_start);
// S_start <- P <- P_end
if(snapshot_id_start == patch_id_start){
DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id_start);
PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id_end, dict);
size_t count = patchTree->deletion_count(triple_pattern, patch_id_end).first + patchTree->addition_count(patch_id_end, triple_pattern);
return std::make_pair(count, EXACT);
}
//P_start -> P -> S_end
else if(snapshot_id_end == patch_id_end){
DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id_end);
PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id_start, dict);
size_t count = patchTree->deletion_count(triple_pattern, patch_id_start).first + patchTree->addition_count(patch_id_start, triple_pattern);
return std::make_pair(count, EXACT);
}
// reverse tree and forward tree case P_start -> S <- P_end
else if(snapshot_id_start > patch_id_start && snapshot_id_end < patch_id_end) {
DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id_end);
PatchTree* patchTreeForward = get_patch_tree_manager()->get_patch_tree(patch_tree_id_end, dict);
PatchTree* patchTreeReverse = get_patch_tree_manager()->get_patch_tree(patch_tree_id_start, dict);
size_t count = patchTreeForward->deletion_count(triple_pattern, patch_id_end).first + patchTreeForward->addition_count(patch_id_end, triple_pattern) + patchTreeReverse->deletion_count(triple_pattern, patch_id_start).first + patchTreeReverse->addition_count(patch_id_start, triple_pattern);
return std::make_pair(count, UP_TO);
}
else{
if (allowEstimates) {
DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id_start);
PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id_start, dict);
size_t count_start = patchTree->deletion_count(triple_pattern, patch_id_start).first + patchTree->addition_count(patch_id_start, triple_pattern);
size_t count_end = patchTree->deletion_count(triple_pattern, patch_id_end).first + patchTree->addition_count(patch_id_end, triple_pattern);
// There may be an overlap between the delta-triples from start and end.
// This overlap is not easy to determine, so we ignore it when possible.
// The real count will never be higher this value, because we should subtract the overlap count.
return std::make_pair(count_start + count_end, UP_TO);
} else {
return std::make_pair(get_delta_materialized(triple_pattern, 0, patch_id_start, patch_id_end)->get_count(), EXACT);
}
}
}
size_t Controller::get_delta_materialized_count_estimated(const Triple &triple_pattern, int patch_id_start, int patch_id_end) const {
return get_delta_materialized_count(triple_pattern, patch_id_start, patch_id_end, true).second;
}
TripleDeltaIterator* Controller::get_delta_materialized(const Triple &triple_pattern, int offset, int patch_id_start,
int patch_id_end) const {
if (patch_id_end <= patch_id_start) {
return new EmptyTripleDeltaIterator();
}
// Find the snapshot
int snapshot_id_start = get_corresponding_snapshot_id(patch_id_start);
int snapshot_id_end = get_corresponding_snapshot_id(patch_id_end);
if (snapshot_id_start < 0 || snapshot_id_end < 0) {
return new EmptyTripleDeltaIterator();
}
// start = snapshot, end = snapshot
if(snapshot_id_start == patch_id_start && snapshot_id_end == patch_id_end) {
// TODO: implement this when multiple snapshots are supported
throw std::invalid_argument("Multiple snapshots are not supported.");
}
// start = snapshot, end = patch
if(snapshot_id_start == patch_id_start && snapshot_id_end != patch_id_end) {
DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id_end);
if (snapshot_id_start == snapshot_id_end) {
// Return iterator for the end patch relative to the start snapshot
int patch_tree_id = get_patch_tree_id(patch_id_end);
PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id, dict);
if(patchTree == NULL) {
throw std::invalid_argument("Could not find the given end patch id");
}
if (TripleStore::is_default_tree(triple_pattern)) {
return (new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValue>(patchTree, triple_pattern, patch_id_end))->offset(offset);
} else {
return (new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValueReduced>(patchTree, triple_pattern, patch_id_end))->offset(offset);
}
} else {
// TODO: implement this when multiple snapshots are supported
throw std::invalid_argument("Multiple snapshots are not supported.");
}
}
// start = patch, end = snapshot
if(snapshot_id_start != patch_id_start && snapshot_id_end == patch_id_end) {
DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id_end);
if (snapshot_id_start == snapshot_id_end) {
// Return iterator for the end patch relative to the start snapshot
int patch_tree_id = get_patch_tree_id(patch_id_start);
PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id, dict);
if(patchTree == NULL) {
throw std::invalid_argument("Could not find the given end patch id");
}
if (TripleStore::is_default_tree(triple_pattern)) {
return (new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValue>(patchTree, triple_pattern, patch_id_start))->offset(offset);
} else {
return (new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValueReduced>(patchTree, triple_pattern, patch_id_start))->offset(offset);
}
} else {
// TODO: implement this when multiple snapshots are supported
throw std::invalid_argument("Multiple snapshots are not supported.");
}
// // TODO: implement this when multiple snapshots are supported
// throw std::invalid_argument("Multiple snapshots are not supported.");
}
// start = patch, end = patch
if(snapshot_id_start != patch_id_start && snapshot_id_end != patch_id_end) {
DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id_end);
if (snapshot_id_start == snapshot_id_end) {
// Return diff between two patches relative to the same snapshot
int patch_tree_id_end = get_patch_tree_id(patch_id_end);
int patch_tree_id_start = get_patch_tree_id(patch_id_start);
// forward patch tree (same tree) S <- P_start <- P_end
if(snapshot_id_start < patch_tree_id_start && patch_tree_id_end == patch_tree_id_start){
PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id_end, dict);
if(patchTree == NULL) {
throw std::invalid_argument("Could not find the given end patch id");
}
if (TripleStore::is_default_tree(triple_pattern)) {
return (new ForwardDiffPatchTripleDeltaIterator<PatchTreeDeletionValue>(patchTree, triple_pattern, patch_id_start, patch_id_end))->offset(offset);
} else {
return (new ForwardDiffPatchTripleDeltaIterator<PatchTreeDeletionValueReduced>(patchTree, triple_pattern, patch_id_start, patch_id_end))->offset(offset);
}
}
//reverse patch tree (same tree) P_start -> P_end -> S
else if(snapshot_id_start > patch_tree_id_start && patch_tree_id_end == patch_tree_id_start){
PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id_end, dict);
if(patchTree == NULL) {
throw std::invalid_argument("Could not find the given end patch id");
}
if (TripleStore::is_default_tree(triple_pattern)) {
return (new ForwardDiffPatchTripleDeltaIterator<PatchTreeDeletionValue>(patchTree, triple_pattern, patch_id_start, patch_id_end, true))->offset(offset);
} else {
return (new ForwardDiffPatchTripleDeltaIterator<PatchTreeDeletionValueReduced>(patchTree, triple_pattern, patch_id_start, patch_id_end, true))->offset(offset);
}
}
// reverse tree and forward tree case P_start -> S <- P_end
else{
// int patch_tree_id = get_patch_tree_id(patch_id_start);
// PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id, dict);
// if(patchTree == NULL) {
// throw std::invalid_argument("Could not find the given end patch id");
// }
// if (TripleStore::is_default_tree(triple_pattern)) {
// return (new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValue>(patchTree, triple_pattern, patch_id_start))->offset(offset);
// } else {
// return (new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValueReduced>(patchTree, triple_pattern, patch_id_start))->offset(offset);
// }
//
// int patch_tree_id = get_patch_tree_id(patch_id_end);
// PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id, dict);
// if(patchTree == NULL) {
// throw std::invalid_argument("Could not find the given end patch id");
// }
// if (TripleStore::is_default_tree(triple_pattern)) {
// return (new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValue>(patchTree, triple_pattern, patch_id_end))->offset(offset);
// } else {
// return (new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValueReduced>(patchTree, triple_pattern, patch_id_end))->offset(offset);
// }
PatchTree* patchTreeReverse = get_patch_tree_manager()->get_patch_tree(patch_tree_id_start, dict);
PatchTree* patchTreeForward = get_patch_tree_manager()->get_patch_tree(patch_tree_id_end, dict);
if(patchTreeReverse == NULL || patchTreeForward == NULL) {
throw std::invalid_argument("Could not find the given patch id");
}
if (TripleStore::is_default_tree(triple_pattern)) {
return (new BiDiffPatchTripleDeltaIterator<PatchTreeDeletionValue>(
new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValue>(patchTreeReverse,
triple_pattern,
patch_id_start
),
new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValue>(patchTreeForward,
triple_pattern,
patch_id_end),
patchTreeForward->get_spo_comparator()))->offset(offset);
} else {
return (new BiDiffPatchTripleDeltaIterator<PatchTreeDeletionValueReduced>(
new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValueReduced>(patchTreeReverse,
triple_pattern,
patch_id_start),
new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValueReduced>(patchTreeForward,
triple_pattern,
patch_id_end),
patchTreeForward->get_spo_comparator()))->offset(offset);
}
}
} else {
// TODO: implement this when multiple snapshots are supported
throw std::invalid_argument("Multiple snapshots are not supported.");
}
}
return nullptr;
}
std::pair<size_t, ResultEstimationType> Controller::get_version_count(const Triple &triple_pattern, bool allowEstimates) const {
// TODO: this will require some changes when we support multiple snapshots.
// Find the snapshot an count its elements
HDT* snapshot = get_snapshot_manager()->get_snapshot(0);
IteratorTripleID* snapshot_it = SnapshotManager::search_with_offset(snapshot, triple_pattern, 0);
size_t count = snapshot_it->estimatedNumResults();
if (!allowEstimates && snapshot_it->numResultEstimation() != EXACT) {
count = 0;
while (snapshot_it->hasNext()) {
snapshot_it->next();
count++;
}
}
// Count the additions for all versions
DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(0);
PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(0, dict);
if (patchTree != NULL) {
count += patchTree->addition_count(0, triple_pattern);
}
return std::make_pair(count, allowEstimates ? snapshot_it->numResultEstimation() : EXACT);
}
std::pair<size_t, ResultEstimationType> Controller::get_partial_version_count(const Triple &triple_pattern, bool allowEstimates) const {
// TODO: this will require some changes when we support multiple snapshots.
int snapshot_id = snapshotManager->get_snapshots().begin()->first;
int reverse_patch_tree_id = snapshot_id - 1;
int forward_patch_tree_id = snapshot_id + 1;
// Find the snapshot an count its elements
HDT* snapshot = get_snapshot_manager()->get_snapshot(snapshot_id);
DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id);
IteratorTripleID* snapshot_it = SnapshotManager::search_with_offset(snapshot, triple_pattern, 0);
PatchTree* reverse_patch_tree = get_patch_tree_manager()->get_patch_tree(reverse_patch_tree_id, dict); // Can be null
PatchTree* forward_patch_tree = get_patch_tree_manager()->get_patch_tree(forward_patch_tree_id, dict); // Can be null
size_t count = snapshot_it->estimatedNumResults();
if (!allowEstimates && snapshot_it->numResultEstimation() != EXACT) {
count = 0;
while (snapshot_it->hasNext()) {
snapshot_it->next();
count++;
}
}
// Count the additions for all versions
if (reverse_patch_tree != NULL) {
count += reverse_patch_tree->addition_count(-1, triple_pattern);
}
if (forward_patch_tree != NULL) {
count += forward_patch_tree->addition_count(-1, triple_pattern);
}
return std::make_pair(count, UP_TO);
}
size_t Controller::get_version_count_estimated(const Triple &triple_pattern) const {
return get_version_count(triple_pattern, true).first;
}
TripleVersionsIterator* Controller::get_partial_version(const Triple &triple_pattern, int offset) const {
int snapshot_id = snapshotManager->get_snapshots().begin()->first;
int reverse_patch_tree_id = snapshot_id - 1;
int forward_patch_tree_id = snapshot_id + 1;
HDT* snapshot = get_snapshot_manager()->get_snapshot(snapshot_id);
IteratorTripleID* snapshot_it = SnapshotManager::search_with_offset(snapshot, triple_pattern, offset);
DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id);
PatchTree* reverse_patch_tree = get_patch_tree_manager()->get_patch_tree(reverse_patch_tree_id, dict); // Can be null
PatchTree* forward_patch_tree = get_patch_tree_manager()->get_patch_tree(forward_patch_tree_id, dict); // Can be null
// Snapshots have already been offsetted, calculate the remaining offset.
// After this, offset will only be >0 if we are past the snapshot elements and at the additions.
if (snapshot_it->numResultEstimation() == EXACT) {
offset -= snapshot_it->estimatedNumResults();
if (offset <= 0) {
offset = 0;
} else {
delete snapshot_it;
snapshot_it = NULL;
}
} else {
IteratorTripleID *tmp_it = SnapshotManager::search_with_offset(snapshot, triple_pattern, 0);
while (tmp_it->hasNext() && offset > 0) {
tmp_it->next();
offset--;
}
delete tmp_it;
}
return (new TripleVersionsIterator(triple_pattern, snapshot_it, reverse_patch_tree, forward_patch_tree, snapshot_id))->offset(offset);
}
TripleVersionsIterator* Controller::get_version(const Triple &triple_pattern, int offset) const {
// // TODO: this will require some changes when we support multiple snapshots. (probably just a simple merge for all snapshots with what is already here)
// // Find the snapshot
// int snapshot_id = 0;
// HDT* snapshot = get_snapshot_manager()->get_snapshot(snapshot_id);
// IteratorTripleID* snapshot_it = SnapshotManager::search_with_offset(snapshot, triple_pattern, offset);
// DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id);
// PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(snapshot_id, dict); // Can be null, if only snapshot is available
//
// // Snapshots have already been offsetted, calculate the remaining offset.
// // After this, offset will only be >0 if we are past the snapshot elements and at the additions.
// if (snapshot_it->numResultEstimation() == EXACT) {
// offset -= snapshot_it->estimatedNumResults();
// if (offset <= 0) {
// offset = 0;
// } else {
// delete snapshot_it;
// snapshot_it = NULL;
// }
// } else {
// IteratorTripleID *tmp_it = SnapshotManager::search_with_offset(snapshot, triple_pattern, 0);
// while (tmp_it->hasNext() && offset > 0) {
// tmp_it->next();
// offset--;
// }
// delete tmp_it;
// }
//
// return (new TripleVersionsIterator(triple_pattern, snapshot_it, patchTree, 0))->offset(offset);
return NULL;
}
bool Controller::append(PatchElementIterator* patch_it, int patch_id, DictionaryManager* dict, bool check_uniqueness, ProgressListener* progressListener) {
//find largest key smaller or equal to patch_id, this is the patch_tree_id
auto it = patchTreeManager->get_patch_trees().lower_bound(patch_id); //gives elements equal to or greater than patch_id
if(it == patchTreeManager->get_patch_trees().end() || it->first > patch_id) {
if(it == patchTreeManager->get_patch_trees().begin()) {
// todo error no smaller element found
return -1;
}
it--;
}
int patch_tree_id = it->first;
return get_patch_tree_manager()->append(patch_it, patch_id, patch_tree_id, check_uniqueness, progressListener, dict);
}
bool Controller::reverse_append(PatchElementIterator* patch_it, int patch_id, DictionaryManager* dict, bool check_uniqueness, ProgressListener* progressListener) {
//find smallest element larger than or equal to patch_id, this is the patch_tree_id
int patch_tree_id;
if(patchTreeManager->get_patch_trees().find(patch_id) == patchTreeManager->get_patch_trees().end()){
auto iterator = patchTreeManager->get_patch_trees().upper_bound(patch_id); //returns first element bigger than patch_id
patch_tree_id = iterator->first;
}
else{
patch_tree_id = patch_id;
}
return get_patch_tree_manager()->reverse_append(patch_it, patch_id, patch_tree_id, dict, check_uniqueness, progressListener);
}
PatchTreeManager* Controller::get_patch_tree_manager() const {
return patchTreeManager;
}
SnapshotManager* Controller::get_snapshot_manager() const {
return snapshotManager;
}
DictionaryManager *Controller::get_dictionary_manager(int patch_id) const {
int snapshot_id = get_corresponding_snapshot_id(patch_id);
if(snapshot_id < 0) {
throw std::invalid_argument("No snapshot has been created yet.");
}
get_snapshot_manager()->get_snapshot(snapshot_id); // Force a snapshot load
return get_snapshot_manager()->get_dictionary_manager(snapshot_id);
}
int Controller::get_max_patch_id() {
get_snapshot_manager()->get_snapshot(0); // Make sure our first snapshot is loaded, otherwise KC might get intro trouble while reorganising since it needs the dict for that.
int max_patch_id = get_patch_tree_manager()->get_max_patch_id(get_snapshot_manager()->get_dictionary_manager(0));
if (max_patch_id < 0) {
return get_corresponding_snapshot_id(0);
}
return max_patch_id;
}
void Controller::cleanup(string basePath, Controller* controller) {
// Delete patch files
std::map<int, PatchTree*> patches = controller->get_patch_tree_manager()->get_patch_trees();
std::map<int, PatchTree*>::iterator itP = patches.begin();
std::list<int> patchMetadataToDelete;
while(itP != patches.end()) {
int id = itP->first;
std::remove((basePath + PATCHTREE_FILENAME(id, "spo_deletions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(id, "pos_deletions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(id, "pso_deletions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(id, "sop_deletions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(id, "osp_deletions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(id, "spo_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(id, "pos_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(id, "pso_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(id, "sop_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(id, "osp_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(id, "count_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(id, "count_additions.tmp")).c_str());
patchMetadataToDelete.push_back(id);
itP++;
}
// Delete snapshot files
std::map<int, HDT*> snapshots = controller->get_snapshot_manager()->get_snapshots();
std::map<int, HDT*>::iterator itS = snapshots.begin();
std::list<int> patchDictsToDelete;
while(itS != snapshots.end()) {
int id = itS->first;
std::remove((basePath + SNAPSHOT_FILENAME_BASE(id)).c_str());
std::remove((basePath + SNAPSHOT_FILENAME_BASE(id) + ".index").c_str());
patchDictsToDelete.push_back(id);
itS++;
}
delete controller;
// Delete dictionaries
std::list<int>::iterator it1;
for(it1=patchDictsToDelete.begin(); it1!=patchDictsToDelete.end(); ++it1) {
DictionaryManager::cleanup(basePath, *it1);
}
// Delete metadata files
std::list<int>::iterator it2;
for(it2=patchMetadataToDelete.begin(); it2!=patchMetadataToDelete.end(); ++it2) {
std::remove((basePath + METADATA_FILENAME_BASE(*it2)).c_str());
}
}
PatchBuilder* Controller::new_patch_bulk() {
return new PatchBuilder(this);
}
PatchBuilderStreaming *Controller::new_patch_stream() {
return new PatchBuilderStreaming(this);
}
bool Controller::replace_patch_tree(string basePath, int patch_tree_id) {
// remove old files
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "spo_deletions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "pos_deletions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "pso_deletions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "sop_deletions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "osp_deletions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "spo_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "pos_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "pso_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "sop_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "osp_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "count_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "count_additions.tmp")).c_str());
std::remove((basePath + METADATA_FILENAME_BASE(patch_tree_id)).c_str());
//rename temp files
std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "spo_deletions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "spo_deletions")).c_str());
std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "pos_deletions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "pos_deletions")).c_str());
std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "pso_deletions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "pso_deletions")).c_str());
std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "sop_deletions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "sop_deletions")).c_str());
std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "osp_deletions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "osp_deletions")).c_str());
std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "spo_additions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "spo_additions")).c_str());
std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "pos_additions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "pos_additions")).c_str());
std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "pso_additions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "pso_additions")).c_str());
std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "sop_additions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "sop_additions")).c_str());
std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "osp_additions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "osp_additions")).c_str());
std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "count_additions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "count_additions")).c_str());
std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "count_additions.tmp")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "count_additions.tmp")).c_str());
std::rename((basePath + TEMP_METADATA_FILENAME_BASE(patch_tree_id)).c_str(), (basePath + METADATA_FILENAME_BASE(patch_tree_id)).c_str());
return true;
}
int Controller::get_patch_tree_id(int patch_id)const {
// case 1: S <- P <- P
// case 2: S <- P <- P S <- P
// case 3: S <- P <- P P -> P -> S <- P
// case 4: P -> P -> S <- P <- P
// return lower tree if reverse tree does not exists
// return upper tree if reverse tree does exists
std::map<int, HDT*> loaded_snapshots = get_snapshot_manager()->get_snapshots();
std::map<int, HDT*>::iterator low, prev;
low = loaded_snapshots.lower_bound(patch_id);
int low_snapshot_id = -1;
int high_snapshot_id = -1;
if(low == loaded_snapshots.begin() && low == loaded_snapshots.end()) {
// empty map
return -1;
}
if (low == loaded_snapshots.end()) {
low--;
low_snapshot_id = low->first;
} else if (low == loaded_snapshots.begin()) {
low_snapshot_id = low->first;
} else {
prev = std::prev(low);
high_snapshot_id = low->first;
low_snapshot_id = prev->first;
}
// case 4
if(low_snapshot_id > patch_id){
return low_snapshot_id - 1;
}
std::map<int, PatchTree*> patches = get_patch_tree_manager()->get_patch_trees();
int low_patch_tree_id = low_snapshot_id + 1 ; // todo make function of forward patch_tree_id
if(high_snapshot_id >= 0){ // if high snapshot exists
auto it = patches.find(high_snapshot_id - 1); // todo make function of reverse patch_tree_id
if(it != patches.end()){ // if reverse patch tree exists
int dist_to_low = patch_id - low_snapshot_id;
int dist_to_high = high_snapshot_id - patch_id;
if(dist_to_high < dist_to_low){ // closer to reverse patch tree
return high_snapshot_id - 1; // todo make function of reverse patch_tree_id
}
}
}
// check if forward chain exists
auto it = patches.find(low_patch_tree_id); // todo make function of reverse patch_tree_id
if(it == patches.end()){
return -1;
}
return low_patch_tree_id;
}
int Controller::get_corresponding_snapshot_id(int patch_id) const {
// get snapshot before patch_id
// get snapshot after patch_id
// if snapshot after patch_id does not exist or snapshot_after does not have reverse tree, return snapshot before patch_id
// if reverse does exist, return snapshot id closest to patch_id (in case of tie, return lowest snapshot_id
std::map<int, HDT*> loaded_snapshots = get_snapshot_manager()->get_snapshots();
std::map<int, HDT*>::iterator low, prev;
low = loaded_snapshots.lower_bound(patch_id);
int low_snapshot_id = -1;
int high_snapshot_id = -1;
if(low == loaded_snapshots.begin() && low == loaded_snapshots.end()) {
// empty map
return -1;
}
if (low == loaded_snapshots.end()) {
low--;
low_snapshot_id = low->first;
} else if (low == loaded_snapshots.begin()) {
low_snapshot_id = low->first;
} else {
prev = std::prev(low);
high_snapshot_id = low->first;
low_snapshot_id = prev->first;
}
if(high_snapshot_id == patch_id)
return high_snapshot_id;
else if(low_snapshot_id == patch_id)
return low_snapshot_id;
else{
std::map<int, PatchTree*> loaded_patches = get_patch_tree_manager()->get_patch_trees();
int low_patch_tree_id = low_snapshot_id + 1 ; // todo make function of forward patch_tree_id
if(high_snapshot_id >= 0){ // if high snapshot exists
auto it = loaded_patches.find(high_snapshot_id - 1); // todo make function of reverse patch_tree_id
if(it != loaded_patches.end()){ // if reverse patch tree exists
int dist_to_low = patch_id - low_snapshot_id;
int dist_to_high = high_snapshot_id - patch_id;
if(dist_to_high < dist_to_low){ // closer to reverse patch tree
return high_snapshot_id;
}
}
}
return low_snapshot_id;}
}
bool Controller::copy_patch_tree_files(string basePath, int patch_tree_id) {
try {
boost::filesystem::path source, target;
source = basePath + PATCHTREE_FILENAME(patch_tree_id, "spo_deletions");
target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "spo_deletions");
if (boost::filesystem::exists(source))
boost::filesystem::copy_file(source, target);
source = basePath + PATCHTREE_FILENAME(patch_tree_id, "pos_deletions");
target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "pos_deletions");
if (boost::filesystem::exists(source))
boost::filesystem::copy_file(source, target);
source = basePath + PATCHTREE_FILENAME(patch_tree_id, "pso_deletions");
target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "pso_deletions");
if (boost::filesystem::exists(source))
boost::filesystem::copy_file(source, target);
source = basePath + PATCHTREE_FILENAME(patch_tree_id, "sop_deletions");
target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "sop_deletions");
if (boost::filesystem::exists(source))
boost::filesystem::copy_file(source, target);
source = basePath + PATCHTREE_FILENAME(patch_tree_id, "osp_deletions");
target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "osp_deletions");
if (boost::filesystem::exists(source))
boost::filesystem::copy_file(source, target);
source = basePath + PATCHTREE_FILENAME(patch_tree_id, "spo_additions");
target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "spo_additions");
if (boost::filesystem::exists(source))
boost::filesystem::copy_file(source, target);
source = basePath + PATCHTREE_FILENAME(patch_tree_id, "pos_additions");
target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "pos_additions");
if (boost::filesystem::exists(source))
boost::filesystem::copy_file(source, target);
source = basePath + PATCHTREE_FILENAME(patch_tree_id, "pso_additions");
target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "pso_additions");
if (boost::filesystem::exists(source))
boost::filesystem::copy_file(source, target);
source = basePath + PATCHTREE_FILENAME(patch_tree_id, "sop_additions");
target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "sop_additions");
if (boost::filesystem::exists(source))
boost::filesystem::copy_file(source, target);
source = basePath + PATCHTREE_FILENAME(patch_tree_id, "osp_additions");
target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "osp_additions");
if (boost::filesystem::exists(source))
boost::filesystem::copy_file(source, target);
source = basePath + PATCHTREE_FILENAME(patch_tree_id, "count_additions");
target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "count_additions");
if (boost::filesystem::exists(source))
boost::filesystem::copy_file(source, target);
// source = basePath + PATCHTREE_FILENAME(patch_tree_id, "count_additions.tmp");
// target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "count_additions.tmp");
// if (boost::filesystem::exists(source))
// boost::filesystem::copy_file(source, target);
source = basePath + METADATA_FILENAME_BASE(patch_tree_id);
target = basePath + TEMP_METADATA_FILENAME_BASE(patch_tree_id);
if (boost::filesystem::exists(source))
boost::filesystem::copy_file(source, target);
} catch (const boost::filesystem::filesystem_error& e){
return false;
}
return true;
}
void Controller::remove_forward_chain(std::string basePath, int temp_snapshot_id){
int patch_tree_id = temp_snapshot_id + 1;
get_patch_tree_manager()->remove_patch_tree(patch_tree_id);
get_snapshot_manager()->remove_snapshot(temp_snapshot_id);
std::remove((basePath + PATCHDICT_FILENAME_BASE(temp_snapshot_id)).c_str());
std::remove((basePath + METADATA_FILENAME_BASE(patch_tree_id)).c_str());
std::remove((basePath + SNAPSHOT_FILENAME_BASE(temp_snapshot_id)).c_str());
std::remove((basePath + SNAPSHOT_FILENAME_BASE(temp_snapshot_id) + ".index").c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "spo_deletions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "pos_deletions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "pso_deletions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "sop_deletions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "osp_deletions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "spo_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "pos_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "pso_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "sop_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "osp_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "count_additions")).c_str());
std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "count_additions.tmp")).c_str());
}
void Controller::extract_changeset(int patch_tree_id, std::string path_to_files) {
patchTreeManager->get_patch_tree(patch_tree_id, get_dictionary_manager(patch_tree_id))->getTripleStore()->extract_additions(get_dictionary_manager(patch_tree_id), path_to_files);
patchTreeManager->get_patch_tree(patch_tree_id, get_dictionary_manager(patch_tree_id))->getTripleStore()->extract_deletions(get_dictionary_manager(patch_tree_id), path_to_files);
}
| 55.119221
| 297
| 0.677916
|
rdfostrich
|
fd541295ab267af73a7a4def844271f4430b93ad
| 6,306
|
cpp
|
C++
|
src/cpp/constraints.cpp
|
laudv/veritas
|
ba1761cc333b08b4381afa720b24ace065a9f106
|
[
"Apache-2.0"
] | 6
|
2020-10-29T10:20:48.000Z
|
2022-03-31T13:39:47.000Z
|
src/cpp/constraints.cpp
|
laudv/veritas
|
ba1761cc333b08b4381afa720b24ace065a9f106
|
[
"Apache-2.0"
] | 1
|
2021-11-25T13:15:11.000Z
|
2021-12-08T09:23:24.000Z
|
src/cpp/constraints.cpp
|
laudv/veritas
|
ba1761cc333b08b4381afa720b24ace065a9f106
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2020 DTAI Research Group - KU Leuven.
* License: Apache License 2.0
* Author: Laurens Devos
*/
#include "constraints.hpp"
namespace veritas {
UpdateResult
Add::update(Domain& self, Domain& ldom, Domain& rdom)
{
std::cout << "ADD0 "
<< "self: " << self
<< ", l: " << ldom
<< ", r: " << rdom
<< std::endl;
// self = ldom + rdom
FloatT new_self_lo, new_self_hi;
FloatT new_ldom_lo, new_ldom_hi;
FloatT new_rdom_lo, new_rdom_hi;
new_self_lo = std::max(self.lo, ldom.lo+rdom.lo);
new_self_hi = std::min(self.hi, ldom.hi+rdom.hi);
new_ldom_lo = std::max(ldom.lo, self.lo-rdom.hi);
new_ldom_hi = std::min(ldom.hi, self.hi-rdom.lo);
new_rdom_lo = std::max(rdom.lo, self.lo-ldom.hi),
new_rdom_hi = std::min(rdom.hi, self.hi-ldom.lo);
if (new_self_lo > new_self_hi
|| new_ldom_lo > new_ldom_hi
|| new_rdom_lo > new_rdom_hi)
return INVALID;
UpdateResult res = static_cast<UpdateResult>(
!(self.lo == new_self_lo && self.hi == new_self_hi
&& ldom.lo == new_ldom_lo && ldom.hi == new_ldom_hi
&& rdom.lo == new_rdom_lo && rdom.hi == new_rdom_hi));
self = {new_self_lo, new_self_hi};
ldom = {new_ldom_lo, new_ldom_hi};
rdom = {new_rdom_lo, new_rdom_hi};
std::cout << "ADD1 "
<< "self: " << self
<< ", l: " << ldom
<< ", r: " << rdom
<< " res=" << res
<< std::endl;
return res;
}
UpdateResult
Eq::update(Domain& ldom, Domain& rdom)
{
// L == R -> share the same domain
FloatT new_lo = std::max(ldom.lo, rdom.lo);
FloatT new_hi = std::min(ldom.hi, rdom.hi);
//std::cout << "EQ ldom " << ldom << ", rdom " << rdom << std::endl;
if (new_lo > new_hi)
return INVALID;
UpdateResult res = static_cast<UpdateResult>(
(ldom.lo != new_lo || ldom.hi != new_hi)
|| (rdom.lo != new_lo || rdom.hi != new_hi));
ldom.lo = new_lo;
rdom.lo = new_lo;
ldom.hi = new_hi;
rdom.hi = new_hi;
//std::cout << "-- ldom " << ldom << ", rdom " << rdom << std::endl;
return res;
}
UpdateResult
LtEq::update(Domain& ldom, Domain& rdom)
{
// LEFT <= RIGHT
FloatT new_lo = std::max(ldom.lo, rdom.lo);
FloatT new_hi = std::min(ldom.hi, rdom.hi);
//std::cout << "LTEQ ldom " << ldom << ", rdom " << rdom << std::endl;
if (ldom.lo > new_hi || new_lo > rdom.hi)
return INVALID;
UpdateResult res = static_cast<UpdateResult>(
(ldom.lo != new_lo || ldom.hi != new_hi)
|| (rdom.lo != new_lo || rdom.hi != new_hi));
ldom = {ldom.lo, new_hi};
rdom = {new_lo, rdom.hi};
//std::cout << "---- ldom " << ldom << ", rdom " << rdom << std::endl;
return res;
}
ConstraintPropagator::ConstraintPropagator(int num_features)
: num_features_(num_features)
{
for (int i = 0; i < num_features_; ++i)
{
AnyExpr e;
e.tag = AnyExpr::VAR;
e.parent = -1;
exprs_.push_back(e);
}
}
void
ConstraintPropagator::copy_from_box(const Box& box)
{
size_t j = 0;
for (int i = 0; i < num_features_; ++i) // box is sorted by item.feat_id
{
AnyExpr& e = exprs_[i];
e.tag = AnyExpr::VAR;
e.dom = {};
if (j < box.size() && box[j].feat_id == i)
{
e.dom = box[j].domain;
++j;
}
}
for (size_t i = num_features_; i < exprs_.size(); ++i)
{
AnyExpr& expr = exprs_[i];
if (expr.tag == AnyExpr::CONST)
expr.dom = {expr.constant.value, expr.constant.value};
else
expr.dom = {}; // reset domain of non-consts
}
}
void
ConstraintPropagator::copy_to_box(Box& box) const
{
size_t j = 0;
size_t sz = box.size();
for (int i = 0; i < num_features_; ++i)
{
if (j < sz && box[j].feat_id == i)
{
box[j].domain = exprs_[i].dom;
++j;
}
else if (!exprs_[i].dom.is_everything())
{
box.push_back({i, exprs_[i].dom}); // add new domain to box
}
}
// sort newly added domain ids, if any
if (sz < box.size())
{
std::sort(box.begin(), box.end(),
[](const DomainPair& a, const DomainPair& b) {
return a.feat_id < b.feat_id;
});
}
}
UpdateResult
ConstraintPropagator::aggregate_update_result(std::initializer_list<UpdateResult> l)
{
UpdateResult res = UNCHANGED;
for (auto r : l)
{
if (r == INVALID)
return INVALID;
if (r == UPDATED)
res = UPDATED;
};
return res;
}
void
ConstraintPropagator::eq(int left, int right)
{
AnyComp c;
c.left = left;
c.right = right;
c.comp.eq = {};
c.tag = AnyComp::EQ;
comps_.push_back(c);
}
void
ConstraintPropagator::lteq(int left, int right)
{
AnyComp c;
c.left = left;
c.right = right;
c.comp.lteq = {};
c.tag = AnyComp::LTEQ;
comps_.push_back(c);
}
int
ConstraintPropagator::constant(FloatT value)
{
AnyExpr e;
e.tag = AnyExpr::CONST;
e.constant = {value};
e.parent = -1;
exprs_.push_back(e);
return exprs_.size() - 1;
}
int
ConstraintPropagator::add(int left, int right)
{
AnyExpr e;
e.tag = AnyExpr::ADD;
e.add = {left, right};
e.parent = -1;
int id = exprs_.size();
exprs_.push_back(e);
exprs_.at(left).parent = id;
exprs_.at(right).parent = id;
return id;
}
} // namespace veritas
| 27.417391
| 88
| 0.479385
|
laudv
|
fd56b6f69cb56a982b035873e8b501012f623a25
| 29,721
|
cpp
|
C++
|
Common/src/song.cpp
|
danfrz/PLEBTracker
|
f6aa7078c3f39e9c8b025e70e7dbeab19119e213
|
[
"MIT"
] | 86
|
2016-04-13T16:39:02.000Z
|
2022-03-20T17:35:09.000Z
|
Common/src/song.cpp
|
danfrz/PLEBTracker
|
f6aa7078c3f39e9c8b025e70e7dbeab19119e213
|
[
"MIT"
] | 19
|
2016-04-14T07:38:19.000Z
|
2021-04-12T21:58:08.000Z
|
Common/src/song.cpp
|
danfrz/PLEBTracker
|
f6aa7078c3f39e9c8b025e70e7dbeab19119e213
|
[
"MIT"
] | 8
|
2018-06-04T22:02:06.000Z
|
2022-01-19T05:34:19.000Z
|
#include "song.h"
#include <iostream>
Song::Song(bool fill_defaults)
{
bytes_per_row = 0x1CB0;
interrow_resolution = 0x18;
for(int i = 9; i < SONGNAME_LENGTH+1; i++)
songname[i] = 0;
songname[0]='s';
songname[1]='o';
songname[2]='n';
songname[3]='g';
songname[4]=' ';
songname[5]='n';
songname[6]='a';
songname[7]='m';
songname[8]='e';
instruments = new Instrument*[256];
num_instruments = 0;
tracks = 4;
patterns = new Pattern*[256];
num_patterns = 0;
//Either 1 or 0; will be same as num_instruments. either work.
for(int i = num_patterns; i < 256; i++)
{
instruments[i] = NULL;
patterns[i] = NULL;
}
orders = new unsigned char[256];
num_orders=0;
waveEntries = 0;
waveTable = new unsigned short[512];
for(int i = 0; i < 512; i++)
waveTable[i] = 0;
pulseEntries = 0;
pulseTable = new unsigned short[512];
for(int i = 0; i < 512; i++)
pulseTable[i] = 0;
filterEntries = 0;
filterTable = new unsigned short[512];
for(int i = 0; i < 512; i++)
filterTable[i] = 0;
if(fill_defaults)
{
num_instruments = 1;
Instrument *defaultInst = new Instrument();
instruments[0] = defaultInst;
Pattern *defaultPat = new Pattern(tracks, 64);
patterns[0] = defaultPat;
num_patterns = 1;
num_orders = 1;
orders[0] = 0;
waveEntries = 1;
waveTable[0] = 0x0100;
pulseEntries = 2;
pulseTable[0] = 0x0000;
pulseTable[1] = 0xFF00;
filterEntries = 3;
filterTable[0] = 0xF000;
filterTable[1] = 0x0000;
filterTable[2] = 0xFF01;
}
}
Song::Song(std::istream &in)
{
patterns = NULL;
instruments = NULL;
orders = new unsigned char[256];
waveTable = new unsigned short[512];
pulseTable = new unsigned short[512];
filterTable = new unsigned short[512];
input(in);
}
Song::~Song()
{
for(int i = 0; i < num_instruments; i++)
delete instruments[i];
for(int i = 0; i < num_patterns; i++)
delete patterns[i];
delete [] instruments;
delete [] patterns;
delete [] orders;
delete [] waveTable;
delete [] pulseTable;
delete [] filterTable;
}
std::ostream &Song::output(std::ostream &out) const
{
out.write(songname, SONGNAME_LENGTH+1);
out.write((char*)&bytes_per_row, sizeof(short));
out.write((char*)&interrow_resolution, sizeof(char));
out.write((char*)&tracks, sizeof(char));
out.write((char*)&num_orders, sizeof(char));
out.write((char*)orders, num_orders);
out.write((char*)&waveEntries, sizeof(short));
out.write((char*)waveTable, waveEntries*sizeof(short));
out.write((char*)&pulseEntries, sizeof(short));
out.write((char*)pulseTable, pulseEntries*sizeof(short));
out.write((char*)&filterEntries, sizeof(short));
out.write((char*)filterTable, filterEntries*sizeof(short));
out.write((char*)&num_instruments, sizeof(char));
for(int i = 0; i < num_instruments; i++)
(instruments[i])->output(out);
out.write((char*)&num_patterns, sizeof(char));
for(int i = 0; i < num_patterns; i++)
(patterns[i])->output(out);
return out;
}
std::istream &Song::input(std::istream &in)
{
if(instruments)
delete [] instruments;
if(patterns)
delete [] patterns;
in.read(songname, SONGNAME_LENGTH+1);
in.read((char*)&bytes_per_row, sizeof(short));
in.read((char*)&interrow_resolution, sizeof(char));
in.read((char*)&tracks, sizeof(char));
in.read((char*)&num_orders, sizeof(char));
in.read((char*)orders, num_orders);
in.read((char*)&waveEntries, sizeof(short));
in.read((char*)waveTable, waveEntries*sizeof(short));
for(int i = waveEntries; i < 512; i++)
waveTable[i] = 0;
in.read((char*)&pulseEntries, sizeof(short));
in.read((char*)pulseTable, pulseEntries*sizeof(short));
for(int i = pulseEntries; i < 512; i++)
pulseTable[i] = 0;
in.read((char*)&filterEntries, sizeof(short));
in.read((char*)filterTable, filterEntries*sizeof(short));
for(int i = filterEntries; i < 512; i++)
filterTable[i] = 0;
instruments = new Instrument*[256];
in.read((char*)&num_instruments, sizeof(char));
for(int i = 0; i < num_instruments; i++)
instruments[i] = new Instrument(in);
for(int i = num_instruments; i < 256; i++)
instruments[i] = NULL;
patterns = new Pattern*[256];
in.read((char*)&num_patterns, sizeof(char));
for(int i = 0; i < num_patterns; i++)
patterns[i] = new Pattern(in);
for(int i = num_patterns; i < 256; i++)
patterns[i] = NULL;
return in;
}
void Song::copyCommutable(Song *other)
{
//Copy things that are necessary for any of the objects of the song to operate
//Instruments, Wavetable, Pulsetable, metadata
//Copy the wave table from this song into the other song
unsigned short *otrwavebl = other->getWaveTable();
for(int i = 0; i < waveEntries; i++)
other->setWaveEntry(i,waveTable[i]);
other->waveEntries = waveEntries;
//Copy the pulse table from this song into the other song
unsigned short *otrpulsebl = other->getPulseTable();
for(int i = 0; i < pulseEntries; i++)
other->setPulseEntry(i,pulseTable[i]);
other->pulseEntries = pulseEntries;
unsigned short *otrfilterbl = other->getFilterTable();
for(int i = 0; i < filterEntries; i++)
other->setFilterEntry(i,filterTable[i]);
other->filterEntries = filterEntries;
//Copy important song data to the other song
other->setInterRowResolution(interrow_resolution);
other->setBytesPerRow(bytes_per_row);
other->setTrackNum(tracks);
//Copy instruments
for(int i = 0; i < num_instruments; i++)
other->addInstrument(new Instrument(*instruments[i]));
}
Song *Song::makeExcerpt(unsigned char orderstart, unsigned char orderend, unsigned char rowstart, unsigned char rowend)
{
unsigned int len = 0;
for(int orderi = orderstart; orderi <= orderend; orderi++)
len += getPatternByOrder(orderi)->numRows();
len -= rowstart;
len -= getPatternByOrder(orderend)->numRows() - orderend+1;
Song *out = new Song(false);
copyCommutable(out);
Pattern *first, *last;
if(orderstart == orderend) //play only one order
{
first = new Pattern(*getPatternByOrder(orderstart));
first->chop(rowstart, rowend);
out->addPattern(first);
out->insertOrder(0,0);
}
else //play multiple orders
{
//Copy over the first and last patterns
first = new Pattern(*getPatternByOrder(orderstart));
last = new Pattern(*getPatternByOrder(orderend));
//Chop them to specification
first->chop(rowstart, first->numRows()-1);
last->chop(0,rowend);
//Add the first pattern
out->addPattern(first);
out->insertOrder(0,0);
//Add the final pattern at the end
out->addPattern(last);
out->insertOrder(1,1);
//The last order will continue to be pushed back by the insertion of other orders on it's location
for(int orderi = orderstart+1, i = 1; orderi < orderend; orderi++, i++)
{
//Have to create new patterns because Song will
//run destructor: the patters would be double-freed
out->addPattern(new Pattern(*getPatternByOrder(orderi)));
out->insertOrder(i,i+1);
}
}
return out;
}
Song *Song::makeExcerpt(unsigned int length, unsigned char orderstart, unsigned char rowstart)
{
//Acc is used to accumulate how many rows have been added already until length has been reached
unsigned char rowend, orderend;
unsigned int acc = getPatternByOrder(orderstart)->numRows() - rowstart;
unsigned char orderi = orderstart;
//Loop through following orders until acc >= length
while (acc < length && ++orderi < num_orders)
{
acc += getPatternByOrder(orderi)->numRows();
}
//Make the ending order the last order that filled acc to length
if(orderi >= num_orders)
orderend = num_orders-1;
else
orderend = orderi;
if(orderstart == orderend) //If there is only one order in this excerpt
{
//cut off rowend at wherever makes the length
rowend = rowstart + length;
if(rowend >= getPatternByOrder(orderstart)->numRows())
rowend = getPatternByOrder(orderstart)->numRows()-1;
}
else
{
//cut off rowend at the max row of the last order's pattern plus (length - acc)
rowend = length - (acc - getPatternByOrder(orderend)->numRows());
}
return makeExcerpt(orderstart, orderend, rowstart, rowend);
}
void Song::setName(const char *name, int length)
{
if(length > SONGNAME_LENGTH)
length = SONGNAME_LENGTH;
for(int i = 0; i < length; i++)
songname[i] = name[i];
}
bool Song::insertOrder(unsigned char dest, unsigned char pattern)
{
if(pattern >= num_patterns)
return false;
if(dest >num_orders)
return false;
for(int i=(num_orders++)-1; i >= dest; i--)
orders[i+1] = orders[i];
orders[dest] = pattern;
return true;
}
bool Song::removeOrder(unsigned char ordr)
{
if(ordr >= num_orders || num_orders == 1)
return false;
num_orders--;
for(int i=ordr; i < num_orders; i++)
orders[i] = orders[i+1];
return true;
}
void Song::setTrackNum(const unsigned newtracks)
{
tracks = newtracks;
//loop through every pattern and change tracks
for(int i = 0; i < num_patterns; i++)
patterns[i]->setTrackNum(newtracks);
}
bool Song::newPattern(unsigned int tracks, unsigned int rows)
{
if(num_patterns == 255)
return false;
Pattern *newPat = new Pattern(tracks,rows);
patterns[num_patterns++] = newPat;
return true;
}
bool Song::clonePattern(unsigned char src)
{
if(num_patterns == 255)
return false;
Pattern *source = patterns[src];
Pattern *newPat = new Pattern(*source);
patterns[num_patterns++] = newPat;
return true;
}
bool Song::clearPattern(unsigned char ptrn)
{
patterns[ptrn]->clear();
}
bool Song::removePattern(unsigned char ptrn)
{
if(ptrn >= num_patterns || num_patterns == 1)
return false;
delete patterns[ptrn];
for(int i = ptrn+1; i < num_patterns; i++)
patterns[i-1] = patterns[i];
num_patterns--;
patterns[num_patterns] = NULL;
//then update orders to the new pattern indicies!
//Set to the first pattern
//so that it stands out and it would stand out looking through order list
for(int i = 0; i < num_orders; i++)
if(orders[i] > ptrn)
orders[i]--;
return true;
}
void Song::addPattern(Pattern *ptrn)
{
if(num_patterns == 0xFF)
return;
patterns[num_patterns] = ptrn;
num_patterns++;
}
bool Song::newInstrument()
{
if(num_instruments == 255)
return false;
Instrument *defaultInst = new Instrument();
instruments[num_instruments++] = defaultInst;
return true;
}
bool Song::cloneInstrument(unsigned char inst)
{
if(num_instruments == 255)
return false;
Instrument *srcInst = instruments[inst];
Instrument *newInst = new Instrument(*srcInst);
instruments[num_instruments++] = newInst;
return true;
}
bool Song::removeInstrument(unsigned char inst)
{
if(inst >= num_instruments || num_instruments == 1)
return false;
delete instruments[inst];
inst+=1;
while(inst < num_instruments)
instruments[inst-1] = instruments[inst++];
num_instruments--;
//then update patterns with new instrument indicies
for(int i = 0; i < num_patterns; i++)
patterns[i]->purgeInstrument(inst);
return true;
}
void Song::addInstrument(Instrument *inst)
{
instruments[num_instruments++]=inst;
}
bool Song::insertWaveEntry(unsigned short index, unsigned short entry)
{
if(waveEntries == 0xFFFF)
return false;
for(unsigned short last = ++waveEntries; last > index; last--)
waveTable[last] = waveTable[last-1];
fixWaveJumps(index, 1);
waveTable[index] = entry;
return true;
}
//The entry is a jump function whose value might be changed
//by the insertion or deletion of other entries.
bool isJumpFunc_Volatile(const unsigned short &wave)
{
unsigned char func = (wave & 0xFF00) >> 8;
switch(func)
{
case 0xFF:
case 0xFC:
case 0xFD:
return true;
}
return false;
}
void Song::fixWaveJumps(const unsigned short &index, short difference)
{
if(difference == 0) return;
//FIX WAVE INDEXES FOR INSTRUMENTS
unsigned char instwav;
if(difference > 0)
{
for(unsigned char i = 0; i < num_instruments; i++)
{
instwav = instruments[i]->getWaveIndex();
// > 0 because the first instrument's wave pointer shouldn't
// realistically change due to insertions at index 0
if(instwav > 0 && instwav > index && instwav < 0xFFFF-difference)
{
instruments[i]->setWaveIndex(instwav+difference);
}
}
}
else
{
for(unsigned char i = 0; i < num_instruments; i++)
{
instwav = instruments[i]->getWaveIndex();
if(instwav > index)
{
if(instwav >= -difference)
instruments[i]->setWaveIndex(instwav +difference);
else
instruments[i]->setWaveIndex(0);
}
}
}
//FIX WAVE JUMPS IN WAVE TABLE
unsigned short jumptype;
unsigned short dest;
if(difference > 0)
{
for(unsigned short i = 0; i < waveEntries; i++)
{
if( isJumpFunc_Volatile(waveTable[i]))//is jump, correct it
{
jumptype = waveTable[i] & 0xFF00;
if( (i < waveEntries-1) && ((waveTable[i+1]&0xFF00) == jumptype))//Long jump
{
dest = ((waveTable[i] & 0xFF) << 8) | (waveTable[i+1] & 0xFF);
if(dest > index && dest < 0xFFFF-difference)
{
dest += difference;
waveTable[i] = jumptype | ((dest & 0xFF00) >> 8);
waveTable[i+1] = jumptype | (dest & 0xFF);
}
i++;
}
else
{
dest = waveTable[i] & 0xFF;
if(dest > index)
{
if(dest >= 0xFF - difference)
{
if(waveEntries < 0xFFFF)
{
dest += difference;
waveTable[i] &= 0xFF00;
waveTable[i] |= ((dest & 0xFF00) >> 8);
insertWaveEntry(i+1,jumptype | (dest & 0xFF));
}
}
else
waveTable[i]+=difference;
}
}
}
}
}
else //difference negative
{
for(unsigned short i = 0; i < waveEntries; i++)
{
if( isJumpFunc_Volatile(waveTable[i]))//is jump, correct it
{
jumptype = waveTable[i] & 0xFF00;
if( (i < waveEntries-1) && ((waveTable[i+1] & 0xFF00) == jumptype) )//Long jump
{
dest = ((waveTable[i] & 0xFF) << 8) | (waveTable[i+1] & 0xFF);
if(dest > index && dest >= -difference)
{
dest += difference;
waveTable[i] = jumptype | ((dest & 0xFF00) >> 8);
waveTable[i+1] = jumptype | (dest & 0xFF);
}
i++;
}
else
{
dest = waveTable[i] & 0xFF;
if(dest > index)
{
if(dest >= -difference)
waveTable[i]+= difference;
else
waveTable[i] &= 0xFF00;
}
}
}
}
}
//FIX WAVE JUMPS IN PATTERNS: 7XX
Pattern *p;
for(int i = 0; i < num_patterns; i++)
{
p = patterns[i];
for(int trk = 0; trk < p->numTracks(); trk++)
{
for(int row = 0; row < p->numRows(); row++)
{
unsigned int entry = p->at(trk,row);
if((entry & 0xF00) == 0x700)
{
unsigned char wavejump = entry & 0xFF;
if(difference > 0)
{
if(wavejump > 0 &&wavejump >= index && wavejump < 0xFF-difference)
{
wavejump +=difference;
}
}
else
{
if(wavejump > index)
{
if(wavejump >= -difference)
wavejump +=difference;
else
wavejump = 0;
}
}
entry &= ~0xFF;
entry |= wavejump;
p->setAt(trk,row,entry);
}
}
}
}
}
bool Song::removeWaveEntry(unsigned short index)
{
if(waveEntries == 0)
return false;
for(unsigned short i = index+1; i < waveEntries; i++)
waveTable[i-1] = waveTable[i];
waveTable[--waveEntries] = 0;
fixWaveJumps(index, -1);
return true;
}
bool Song::insertPulseEntry(unsigned short index, unsigned short entry)
{
if(pulseEntries == 0xFFFF)
return false;
for(unsigned short last = ++pulseEntries; last > index; last--)
pulseTable[last] = pulseTable[last-1];
fixPulseJumps(index, 1);
pulseTable[index] = entry;
return true;
}
void Song::fixPulseJumps(const unsigned short &index, short difference)
{
if(difference == 0) return;
//Fix instrument pulse index references
unsigned short instpls;
if(difference > 0)
{
for(unsigned char i = 0; i < num_instruments; i++)
{
instpls = instruments[i]->getPulseIndex();
// > 0 because the first instrument's wave pointer shouldn't
// realistically change due to insertions at index 0
if(instpls > 0 && instpls > index && instpls < 0xFFFF-difference && instpls != 0xFFFF)
{
instruments[i]->setPulseIndex(instpls+difference);
}
}
}
else
{
for(unsigned char i = 0; i < num_instruments; i++)
{
instpls = instruments[i]->getPulseIndex();
if(instpls > index && instpls != 0xFFFF)
{
if(instpls >= -difference)
instruments[i]->setPulseIndex(instpls +difference);
else
instruments[i]->setPulseIndex(0);
}
}
}
//Fix Pulse jumps
unsigned short jumptype;
unsigned short dest;
if(difference > 0)
{
for(unsigned short i = 0; i < pulseEntries; i++)
{
if( isJumpFunc_Volatile(pulseTable[i]))//is jump, correct it
{
jumptype = pulseTable[i] & 0xFF00;
if( (i < pulseEntries-1) && ((pulseTable[i+1]&0xFF00) == jumptype))//Long jump
{
dest = ((pulseTable[i] & 0xFF) << 8) | (pulseTable[i+1] & 0xFF);
if(dest > index && dest < 0xFFFF-difference)
{
dest += difference;
pulseTable[i] = jumptype | ((dest & 0xFF00) >> 8);
pulseTable[i+1] = jumptype | (dest & 0xFF);
}
i++;
}
else
{
dest = pulseTable[i] & 0xFF;
if(dest > index)
{
if(dest >= 0xFF - difference)
{
if(waveEntries < 0xFFFF)
{
dest += difference;
pulseTable[i] &= 0xFF00;
pulseTable[i] |= ((dest & 0xFF00) >> 8);
insertPulseEntry(i+1,jumptype | (dest & 0xFF));
}
}
else
pulseTable[i]+=difference;
}
}
}
}
}
else //difference negative
{
for(unsigned short i = 0; i < pulseEntries; i++)
{
if( isJumpFunc_Volatile(pulseTable[i]))//is jump, correct it
{
jumptype = pulseTable[i] & 0xFF00;
if( (i < pulseEntries-1) && ((pulseTable[i+1] & 0xFF00) == jumptype) )//Long jump
{
dest = ((pulseTable[i] & 0xFF) << 8) | (pulseTable[i+1] & 0xFF);
if(dest > index && dest >= -difference)
{
dest += difference;
pulseTable[i] = jumptype | ((dest & 0xFF00) >> 8);
pulseTable[i+1] = jumptype | (dest & 0xFF);
}
i++;
}
else
{
dest = pulseTable[i] & 0xFF;
if(dest > index)
{
if(dest >= -difference)
pulseTable[i]+= difference;
else
pulseTable[i] &= 0xFF00;
}
}
}
}
}
Pattern *p;
for(int i = 0; i < num_patterns; i++)
{
p = patterns[i];
for(int trk = 0; trk < p->numTracks(); trk++)
{
for(int row = 0; row < p->numRows(); row++)
{
unsigned int entry = p->at(trk,row);
if((entry & 0xF00) == 0x900)
{
unsigned char plsjump = entry & 0xFF;
if(difference > 0)
{
if(plsjump > 0 && plsjump > index && plsjump < 0xFF-difference)
{
plsjump +=difference;
}
}
else
{
if(plsjump > index)
{
if(plsjump >= -difference)
plsjump +=difference;
else
plsjump = 0;
}
}
entry &= ~0xFF;
entry |= plsjump;
p->setAt(trk,row,entry);
}
}
}
}
}
bool Song::removePulseEntry(unsigned short index)
{
if(pulseEntries == 0)
return false;
for(unsigned short i = index+1; i < pulseEntries; i++)
pulseTable[i-1] = pulseTable[i];
pulseTable[--pulseEntries] = 0;
fixPulseJumps(index, -1);
return true;
}
bool Song::insertFilterEntry(unsigned short index, unsigned short entry)
{
if(filterEntries == 0xFFFF)
return false;
for(unsigned short last = ++filterEntries; last > index; last--)
filterTable[last] = filterTable[last-1];
fixFilterJumps(index, 1);
filterTable[index] = entry;
return true;
}
void Song::fixFilterJumps(const unsigned short &index, short difference)
{
if(difference == 0) return;
//Fix instrument pulse index references
unsigned short instflt;
if(difference > 0)
{
for(unsigned char i = 0; i < num_instruments; i++)
{
instflt = instruments[i]->getFilterIndex();
// > 0 because the first instrument's wave pointer shouldn't
// realistically change due to insertions at index 0
if(instflt > 0 && instflt > index && instflt < 0xFFFF-difference && instflt != 0xFFFF)
{
instruments[i]->setFilterIndex(instflt+difference);
}
}
}
else
{
for(unsigned char i = 0; i < num_instruments; i++)
{
instflt = instruments[i]->getFilterIndex();
if(instflt > index && instflt != 0xFFFF)
{
if(instflt >= -difference)
instruments[i]->setFilterIndex(instflt +difference);
else
instruments[i]->setFilterIndex(0);
}
}
}
//Fix Pulse jumps
unsigned short jumptype;
unsigned short dest;
if(difference > 0)
{
for(unsigned short i = 0; i < filterEntries; i++)
{
if( isJumpFunc_Volatile(filterTable[i]))//is jump, correct it
{
jumptype = filterTable[i] & 0xFF00;
if( (i < filterEntries-1) && ((filterTable[i+1]&0xFF00) == jumptype))//Long jump
{
dest = ((filterTable[i] & 0xFF) << 8) | (filterTable[i+1] & 0xFF);
if(dest > index && dest < 0xFFFF-difference)
{
dest += difference;
filterTable[i] = jumptype | ((dest & 0xFF00) >> 8);
filterTable[i+1] = jumptype | (dest & 0xFF);
}
i++;
}
else
{
dest = filterTable[i] & 0xFF;
if(dest > index)
{
if(dest >= 0xFF - difference)
{
if(waveEntries < 0xFFFF)
{
dest += difference;
filterTable[i] &= 0xFF00;
filterTable[i] |= ((dest & 0xFF00) >> 8);
insertFilterEntry(i+1,jumptype | (dest & 0xFF));
}
}
else
filterTable[i]+=difference;
}
}
}
}
}
else //difference negative
{
for(unsigned short i = 0; i < filterEntries; i++)
{
if( isJumpFunc_Volatile(filterTable[i]))//is jump, correct it
{
jumptype = filterTable[i] & 0xFF00;
if( (i < filterEntries-1) && ((filterTable[i+1] & 0xFF00) == jumptype) )//Long jump
{
dest = ((filterTable[i] & 0xFF) << 8) | (filterTable[i+1] & 0xFF);
if(dest > index && dest >= -difference)
{
dest += difference;
filterTable[i] = jumptype | ((dest & 0xFF00) >> 8);
filterTable[i+1] = jumptype | (dest & 0xFF);
}
i++;
}
else
{
dest = filterTable[i] & 0xFF;
if(dest > index)
{
if(dest >= -difference)
filterTable[i]+= difference;
else
filterTable[i] &= 0xFF00;
}
}
}
}
}
Pattern *p;
for(int i = 0; i < num_patterns; i++)
{
p = patterns[i];
for(int trk = 0; trk < p->numTracks(); trk++)
{
for(int row = 0; row < p->numRows(); row++)
{
unsigned int entry = p->at(trk,row);
if((entry & 0xF00) == 0xC00)
{
unsigned char fltjump = entry & 0xFF;
if(difference > 0)
{
if(fltjump > 0 &&fltjump > index && fltjump < 0xFF-difference)
{
fltjump +=difference;
}
}
else
{
if(fltjump > index)
{
if(fltjump >= -difference)
fltjump +=difference;
else
fltjump = 0;
}
}
entry &= ~0xFF;
entry |= fltjump;
p->setAt(trk,row,entry);
}
}
}
}
}
bool Song::removeFilterEntry(unsigned short index)
{
if(filterEntries == 0)
return false;
for(unsigned short i = index+1; i < filterEntries; i++)
filterTable[i-1] = filterTable[i];
filterTable[--filterEntries] = 0;
fixFilterJumps(index, -1);
return true;
}
| 28.359733
| 119
| 0.488611
|
danfrz
|
fd57609a87c44fed9c4340ddf05369168e5621cc
| 15,285
|
cpp
|
C++
|
cppVersion/map.cpp
|
maxgoren/codealong2020
|
b8ef380900544c3daabd549f89f196e133622b10
|
[
"MIT"
] | 5
|
2020-06-17T06:27:45.000Z
|
2021-01-17T19:59:41.000Z
|
cppVersion/map.cpp
|
maxgoren/codealong2020
|
b8ef380900544c3daabd549f89f196e133622b10
|
[
"MIT"
] | null | null | null |
cppVersion/map.cpp
|
maxgoren/codealong2020
|
b8ef380900544c3daabd549f89f196e133622b10
|
[
"MIT"
] | 1
|
2022-03-07T15:22:17.000Z
|
2022-03-07T15:22:17.000Z
|
/****************************************************************
* MIT License
*
* Copyright (c) 2020 Max Goren
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
***************************************************/
Rect::Rect(int x, int y, int w, int h)
{
this->uL.x = x;
this->uL.y = y;
this->lR.x = x + w;
this->lR.y = y + h;
}
Rect::Rect()
{
}
Map::Map(int w, int h)
{
int x, y;
this->width = w;
this->height = h;
//initialize tile grid
for (x = 1; x < w - 1; x++)
{
for (y = 1; y < h - 1; y++)
{
layout[x][y].blocks = true;
layout[x][y].pos.x = x;
layout[x][y].pos.y = y;
}
}
}
bool Rect::collision(Rect other)
{
if ((uL.x < other.lR.x) && (lR.x > other.uL.x) &&
(uL.y < other.lR.y) && (lR.y > other.uL.y)) {
return true; //collision
} else {
return false;
}
}
double Map::isInFov(int x, int y, int px, int py)
{
double alpha = (px - x) * (px - x);
double beta = (py - y) * (py - y);
return sqrt((alpha+beta)*1.0);
}
void Map::digRect(Rect room)
{
int x, y;
for (x = room.uL.x; x < room.lR.x; x++)
{
for (y = room.uL.y; y < room.lR.y; y++)
{
this->layout[x][y].blocks = false;
this->layout[x][y].isinRoom = room.idNum;
this->layout[x][y].value = 10;
}
}
std::cout<<"Dug room "<<room.idNum<<"from x"<<room.uL.x<<" to x "<<room.lR.x<<" and y"<<room.uL.y<<" to "<<room.lR.y<<".\n";
}
void Map::genRect(int numRoom, int maxSize)
{
int i;
int posx, posy, possize;
int roomsMade = 0;
int collisions = 0;
Rect* posroom;
//screensections;
Rect scrSec1(1,1,width/2, height/2 - 1);
scrSec1.numItems = 0;
scrSec1.numEnts = 0;
scrSect.push_back(scrSec1);
Rect scrSec2(width/2, 1, width/2 - 1, height/2 - 1);
scrSec2.numItems = 0;
scrSec2.numEnts = 0;
scrSect.push_back(scrSec2);
Rect scrSec3(1, height/2, width/2, height/2);
scrSec3.numItems = 0;
scrSec3.numEnts = 0;
scrSect.push_back(scrSec3);
Rect scrSec4(width/2, height/2, width/2 - 1, height/2 - 1);
scrSec4.numItems = 0;
scrSec4.numEnts = 0;
scrSect.push_back(scrSec4);
std::cout<<"Screen partition complete.\n";
while (roomsMade < numRoom)
{
possize = getrand(5, maxSize);
switch (getrand(1,4))
{
case 1:
posx = getrand(scrSect[0].uL.x + 1, scrSect[0].lR.x - (possize + 1));
posy = getrand(scrSect[0].uL.y + 1, scrSect[0].lR.y - (possize + 1));
std::cout<<"Room: "<<roomsMade<<" section one selected\n";
break;
case 2:
posx = getrand(scrSect[1].uL.x + 1, scrSect[1].lR.x - (possize + 1));
posy = getrand(scrSect[1].uL.y + 1, scrSect[1].lR.y - (possize + 1));
std::cout<<"Room: "<<roomsMade<<" section two selected\n";
break;
case 3:
posx = getrand(scrSect[2].uL.x + 1, scrSect[2].lR.x - (possize + 1));
posy = getrand(scrSect[2].uL.y + 1, scrSect[2].lR.y - (possize + 1));
std::cout<<"Room: "<<roomsMade<<" section three selected\n";
break;
case 4:
posx = getrand(scrSect[3].uL.x + 1, scrSect[3].lR.x - (possize + 1));
posy = getrand(scrSect[3].uL.y + 1, scrSect[3].lR.y - (possize + 1));
std::cout<<"Room: "<<roomsMade<<" section four selected\n";
break;
}
std::cout<<"Room: "<<roomsMade<<" posx/posy: "<<posx<<"/"<<posy<<"\n";
posroom = new Rect(posx, posy, possize + (possize/2) , possize);
posroom->idNum = roomsMade;
std::cout<<"Room: "<<roomsMade<<" object created\n";
posroom->cent.x = (posroom->uL.x + posroom->lR.x) / 2;
posroom->cent.y = (posroom->uL.y + posroom->lR.y) / 2;
std::cout<<"Room: "<<roomsMade<<" centx/y set: "<<posroom->cent.x<<"/"<<posroom->cent.y<<"\n";
if (roomsMade > 0)
{
for (auto R = rooms.begin() ; R != rooms.end(); R++)
{ if (posroom->collision(*R)) { collisions++; } }
if (collisions == 0)
{
digRect(*posroom);
rooms.push_back(*posroom);
roomsMade++;
collisions = 0;
std::cout<<"Room "<<posroom->idNum<<"made. x/y: "<<posroom->uL.x<<"/"<<posroom->uL.y<<" x2/y2:"<<posroom->lR.x<<"/"<<posroom->lR.y<<std::endl;
} else {
std::cout<<collisions<<"Collisions Detected.\n";
collisions = 0;
}
} else {
digRect(*posroom);
rooms.push_back(*posroom);
roomsMade++;
}
if (roomsMade == 2)
{
spy = rooms.at(0).cent.y;
spx = rooms.at(0).cent.x;
}
}
if (getrand(1,100) > 50)
{
connectRooms(rooms);
} else {
connectRooms2(rooms);
}
//placePortal();
outline();
}
void Map::connectRooms(std::vector<Rect> rooms)
{
int ax,bx;
int ay,by;
Rect* start;
Rect* fin;
int i = 0;
int r;
for ( r = 0; r < rooms.size() - 1; r++)
{
start = &rooms[i];
fin = &rooms[i+1];
std::cout<<"Connecting: "<<start->idNum<<" to "<<fin->idNum<<"\n";
if (start->cent.x <= fin->cent.x)
{
std::cout<<"if one, condition A\n";
for (ax = start->cent.x; ax <= (fin->cent.x + start->cent.x) / 2; ax++)
{
layout[ax][start->cent.y].blocks = false;
layout[ax][start->cent.y].isinRoom = 77;
}
for (bx = fin->cent.x; bx >= (fin->cent.x + start->cent.x) / 2; bx--)
{
layout[bx][fin->cent.y].blocks = false;
layout[bx][fin->cent.y].isinRoom = 77;
}
std::cout<<"From: X"<<start->cent.x<<" and "<<fin->cent.x<<" to "<<(start->cent.x + fin->cent.x)/2<<"\n";
} else {
std::cout<<"If one condition B\n";
for (ax = start->cent.x; ax >= (fin->cent.x + start->cent.x) / 2; ax--)
{
layout[ax][start->cent.y].blocks = false;
layout[ax][start->cent.y].isinRoom = 77;
}
for (bx = fin->cent.x; bx <= (fin->cent.x + start->cent.x) / 2; bx++)
{
layout[bx][fin->cent.y].blocks = false;
layout[bx][fin->cent.y].isinRoom = 77;
}
std::cout<<"From: X"<<start->cent.x<<" and "<<fin->cent.x<<" to "<<(start->cent.x + fin->cent.x)/2<<"\n";
}
if (start->cent.y <= fin->cent.y)
{
std::cout<<"if two condition A\n";
for (ay = start->cent.y; ay < fin->cent.y; ay++)
{
layout[ax][ay].blocks = false;
layout[ax+1][ay].blocks = false;
layout[ax][ay].isinRoom = 77; //77 =pathway
}
std::cout<<"From: Y"<<start->cent.y<<" to "<<fin->cent.y<<"\n";
} else {
std::cout<<"if two, codition B\n";
for (by = fin->cent.y; by <= start->cent.y; by++)
{
layout[bx][by].blocks = false;
layout[bx-1][by].blocks = false;
layout[bx][by].isinRoom = 77;
}
std::cout<<"From: Y"<<fin->cent.y<<" to "<<start->cent.y<<"\n";
}
std::cout<<"Connected.\n";
i++;
}
}
void Map::connectRooms2(std::vector<Rect> rooms)
{
int ax, ay;
int bx, by;
Rect* start;
Rect* fin;
int r, i=0;
for (r = 0; r < rooms.size() - 1; r++)
{
start = &rooms[i];
fin = &rooms[i] + 1;
std::cout<<"Connecting: "<<start->idNum<<" to "<<fin->idNum<<"\n";
if (start->cent.y <= fin->cent.y)
{
std::cout<<"If one, condition A\n";
for (ay = start->cent.y; ay <= (start->cent.y + fin->cent.y) / 2; ay++)
{
layout[start->cent.x][ay].blocks = false;
layout[start->cent.x][ay].isinRoom = 77;
/***********************************/
layout[start->cent.x+1][ay].blocks=false;
}
for (by = fin->cent.y; by >= (start->cent.y + fin->cent.y) / 2; by--)
{
layout[fin->cent.x][by].blocks = false;
layout[fin->cent.x][by].isinRoom = 77;
/**************************************/
layout[fin->cent.x-1][by].blocks=false;
}
} else {
std::cout<<"If one, condition B\n";
for (ay = start->cent.y; ay >= (start->cent.y + fin->cent.y) / 2; ay--)
{
layout[start->cent.x][ay].blocks = false;
layout[start->cent.x][ay].isinRoom = 77;
/***************************************/
layout[start->cent.x-1][ay].blocks = false;
}
for (by = fin->cent.y; by <= (start->cent.y + fin->cent.y) / 2; by++)
{
layout[fin->cent.x][by].blocks = false;
layout[fin->cent.x][by].isinRoom = 77;
/***************************************/
layout[fin->cent.x+1][by].blocks=false;
}
}
if (start->cent.x <= fin->cent.x)
{
std::cout<<"If two, condition A\n";
for (ax = start->cent.x; ax <= fin->cent.x; ax++)
{
layout[ax][ay].blocks = false;
layout[ax][ay].isinRoom = 77;
}
} else {
std::cout<<"If two, condition B\n";
for (bx = fin->cent.x; bx <= start->cent.x; bx++)
{
layout[bx][by].blocks = false;
layout[bx][by].isinRoom = 77;
}
}
std::cout<<"Connection complete.\n";
i++;
}
}
void Map::connectR2R(Rect st, Rect fi)
{
int ax, ay;
int bx, by;
Rect* start = &st;
Rect* fin = &fi;
int r, i=0;
std::cout<<"Connecting: "<<start->idNum<<" to "<<fin->idNum<<"\n";
if (start->cent.y <= fin->cent.y)
{
std::cout<<"If one, condition A\n";
for (ay = start->cent.y; ay <= (start->cent.y + fin->cent.y) / 2; ay++)
{
layout[start->cent.x][ay].blocks = false;
layout[start->cent.x][ay].isinRoom = 77;
/***********************************/
layout[start->cent.x+1][ay].blocks=false;
}
for (by = fin->cent.y; by >= (start->cent.y + fin->cent.y) / 2; by--)
{
layout[fin->cent.x][by].blocks = false;
layout[fin->cent.x][by].isinRoom = 77;
/**************************************/
layout[fin->cent.x-1][by].blocks=false;
}
} else {
std::cout<<"If one, condition B\n";
for (ay = start->cent.y; ay >= (start->cent.y + fin->cent.y) / 2; ay--)
{
layout[start->cent.x][ay].blocks = false;
layout[start->cent.x][ay].isinRoom = 77;
/***************************************/
layout[start->cent.x-1][ay].blocks = false;
}
for (by = fin->cent.y; by <= (start->cent.y + fin->cent.y) / 2; by++)
{
layout[fin->cent.x][by].blocks = false;
layout[fin->cent.x][by].isinRoom = 77;
/***************************************/
layout[fin->cent.x+1][by].blocks=false;
}
}
if (start->cent.x <= fin->cent.x)
{
std::cout<<"If two, condition A\n";
for (ax = start->cent.x; ax <= fin->cent.x; ax++)
{
layout[ax][ay].blocks = false;
layout[ax][ay].isinRoom = 77;
}
} else {
std::cout<<"If two, condition B\n";
for (bx = fin->cent.x; bx <= start->cent.x; bx++)
{
layout[bx][by].blocks = false;
layout[bx][by].isinRoom = 77;
}
}
std::cout<<"Connection complete.\n";
}
void Map::outline()
{
int x, y;
for (x = 0; x < width; x++)
{
for (y = 0; y < height; y++)
{
if (layout[x][y].blocks == false && layout[x+1][y].blocks == true)
{
layout[x+1][y].border = true;
}
if (layout[x][y].blocks == false && layout[x][y+1].blocks == true)
{
layout[x][y+1].border = true;
}
if (layout[x][y].blocks == false && layout[x-1][y].blocks == true)
{
layout[x-1][y].border = true;
}
if (layout[x][y].blocks == false && layout[x][y-1].blocks == true)
{
layout[x][y-1].border = true;
}
if (layout[x][y].blocks == false && layout[x-1][y].border == true && layout[x][y+1].border==true)
{
layout[x-1][y+1].border=true;
}
if (layout[x][y].blocks == false && layout[x-1][y].border == true && layout[x][y-1].border==true)
{
layout[x-1][y-1].border=true;
}
if (layout[x][y].blocks == false && layout[x+1][y].border == true && layout[x][y-1].border==true)
{
layout[x+1][y-1].border=true;
}
if (layout[x][y].blocks == false && layout[x+1][y].border == true && layout[x][y+1].border==true)
{
layout[x+1][y+1].border=true;
}
}
}
}
void Map::spawnMonsters(int numBads)
{
ent *badGuy;
int numMonst = 0;
int i, randRm, x, y;
while (numMonst < 13)
{
randRm = getrand(0, rooms.size() - 1);
if (rooms.at(randRm).numEnts <= 2)
{
x = getrand(rooms[randRm].uL.x+1, rooms[randRm].lR.x-1);
y = getrand(rooms[randRm].uL.y+1, rooms[randRm].lR.y-1);
if (layout[x][y].populated == false && layout[x][y].blocks==false)
{
if (getrand(0,50) < 35)
{
badGuy = new ent(x, y, "Goblin", 'G', color_from_name("green"));
} else {
badGuy = new ent(x, y, "Vampire", 'V', color_from_name("flame"));
}
badGuys.push_back(badGuy);
rooms[randRm].numEnts++;
layout[x][y].populated = true;
layout[x][y].blocks = true;
numMonst++;
}
}
}
}
void Map::placeItems(int numItems)
{
int sect;
int rit;
float rp, rh;
int itemsMade = 0;
Point randPos;
Items* item;
struct stuff things;
while (itemsMade < numItems)
{
rp = getrandfloat(0.10, 2.25);
rh = getrandfloat(4.35, 9.33);
rit = getrand(0,22);
sect = getrand(0, 3);
if (scrSect[sect].numItems < numItems)
{
randPos.x = getrand(this->scrSect.at(sect).uL.x, this->scrSect.at(sect).lR.x);
randPos.y = getrand(this->scrSect.at(sect).uL.y, this->scrSect.at(sect).lR.y);
if (this->layout[randPos.x][randPos.y].blocks == false && this->layout[randPos.x][randPos.y].populated == false)
{
item = new Items(randPos.x,randPos.y, things.things[rit], rh, rp);
this->itemList.push_back(item);
this->layout[randPos.x][randPos.y].populated = true;
itemsMade++;
scrSect[sect].numItems++;
}
}
}
}
void Map::placePortal()
{
int dx, dy;
int dx2, dy2;
int distance;
int distance2;
float dist;
std::pair<Rect*,Rect*> closest;
Rect far = rooms.back();
Rect* start = &rooms.front();
Rect* next;
for (auto r = rooms.begin() + 1; r != rooms.end(); r++)
{
dx = r->cent.x - start->cent.x;
dy = r->cent.y - start->cent.y;
dx2 = r->cent.x - far.cent.x;
dy2 = r->cent.y - far.cent.y;
dist = sqrtf(dx*dx+dy*dy);
distance = (int)round(dist);
dist = sqrtf(dx2*dx2+dy2*dy2);
distance2 = (int)round(dist);
std::cout<<r->idNum<<" & "<<start->idNum<<"\n";
std::cout<<"r -> start "<<distance<<"\n";
std::cout<<r->idNum<<" & "<<far.idNum<<"\n";
std::cout<<"r -> finnish "<<distance2<<"\n";
if (distance < distance2)
{
next = start;
} else {
next = &far;
far = *r;
}
std::cout<<"winner: "<<r->idNum<<" & "<<next->idNum<<"\n";
}
connectR2R(*start,*next);
start = next;
}
| 28.948864
| 149
| 0.53366
|
maxgoren
|
fd5b5642bd20ebde3431ec8c7689553cadf9ad85
| 4,483
|
cpp
|
C++
|
eiam/src/v20210420/model/UserGroupInformation.cpp
|
suluner/tencentcloud-sdk-cpp
|
a56c73cc3f488c4d1e10755704107bb15c5e000d
|
[
"Apache-2.0"
] | 43
|
2019-08-14T08:14:12.000Z
|
2022-03-30T12:35:09.000Z
|
eiam/src/v20210420/model/UserGroupInformation.cpp
|
suluner/tencentcloud-sdk-cpp
|
a56c73cc3f488c4d1e10755704107bb15c5e000d
|
[
"Apache-2.0"
] | 12
|
2019-07-15T10:44:59.000Z
|
2021-11-02T12:35:00.000Z
|
eiam/src/v20210420/model/UserGroupInformation.cpp
|
suluner/tencentcloud-sdk-cpp
|
a56c73cc3f488c4d1e10755704107bb15c5e000d
|
[
"Apache-2.0"
] | 28
|
2019-07-12T09:06:22.000Z
|
2022-03-30T08:04:18.000Z
|
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/eiam/v20210420/model/UserGroupInformation.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Eiam::V20210420::Model;
using namespace std;
UserGroupInformation::UserGroupInformation() :
m_userGroupIdHasBeenSet(false),
m_userGroupNameHasBeenSet(false),
m_lastModifiedDateHasBeenSet(false)
{
}
CoreInternalOutcome UserGroupInformation::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("UserGroupId") && !value["UserGroupId"].IsNull())
{
if (!value["UserGroupId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `UserGroupInformation.UserGroupId` IsString=false incorrectly").SetRequestId(requestId));
}
m_userGroupId = string(value["UserGroupId"].GetString());
m_userGroupIdHasBeenSet = true;
}
if (value.HasMember("UserGroupName") && !value["UserGroupName"].IsNull())
{
if (!value["UserGroupName"].IsString())
{
return CoreInternalOutcome(Core::Error("response `UserGroupInformation.UserGroupName` IsString=false incorrectly").SetRequestId(requestId));
}
m_userGroupName = string(value["UserGroupName"].GetString());
m_userGroupNameHasBeenSet = true;
}
if (value.HasMember("LastModifiedDate") && !value["LastModifiedDate"].IsNull())
{
if (!value["LastModifiedDate"].IsString())
{
return CoreInternalOutcome(Core::Error("response `UserGroupInformation.LastModifiedDate` IsString=false incorrectly").SetRequestId(requestId));
}
m_lastModifiedDate = string(value["LastModifiedDate"].GetString());
m_lastModifiedDateHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void UserGroupInformation::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_userGroupIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "UserGroupId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_userGroupId.c_str(), allocator).Move(), allocator);
}
if (m_userGroupNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "UserGroupName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_userGroupName.c_str(), allocator).Move(), allocator);
}
if (m_lastModifiedDateHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "LastModifiedDate";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_lastModifiedDate.c_str(), allocator).Move(), allocator);
}
}
string UserGroupInformation::GetUserGroupId() const
{
return m_userGroupId;
}
void UserGroupInformation::SetUserGroupId(const string& _userGroupId)
{
m_userGroupId = _userGroupId;
m_userGroupIdHasBeenSet = true;
}
bool UserGroupInformation::UserGroupIdHasBeenSet() const
{
return m_userGroupIdHasBeenSet;
}
string UserGroupInformation::GetUserGroupName() const
{
return m_userGroupName;
}
void UserGroupInformation::SetUserGroupName(const string& _userGroupName)
{
m_userGroupName = _userGroupName;
m_userGroupNameHasBeenSet = true;
}
bool UserGroupInformation::UserGroupNameHasBeenSet() const
{
return m_userGroupNameHasBeenSet;
}
string UserGroupInformation::GetLastModifiedDate() const
{
return m_lastModifiedDate;
}
void UserGroupInformation::SetLastModifiedDate(const string& _lastModifiedDate)
{
m_lastModifiedDate = _lastModifiedDate;
m_lastModifiedDateHasBeenSet = true;
}
bool UserGroupInformation::LastModifiedDateHasBeenSet() const
{
return m_lastModifiedDateHasBeenSet;
}
| 30.496599
| 155
| 0.7205
|
suluner
|
fd5c167fe2de69e059d08716f61869c19ccce090
| 2,360
|
cc
|
C++
|
src/mnn/kernel/cpu/fully_connected_op_cpu.cc
|
horance-liu/mnn
|
d53216e5f3fb60ea1da6f44e72fc0d949974931d
|
[
"Apache-2.0"
] | 4
|
2021-05-17T02:49:36.000Z
|
2021-05-18T13:31:33.000Z
|
src/mnn/kernel/cpu/fully_connected_op_cpu.cc
|
horance-liu/mnn
|
d53216e5f3fb60ea1da6f44e72fc0d949974931d
|
[
"Apache-2.0"
] | 1
|
2021-06-02T03:01:05.000Z
|
2021-06-02T03:01:05.000Z
|
src/mnn/kernel/cpu/fully_connected_op_cpu.cc
|
horance-liu/mnn
|
d53216e5f3fb60ea1da6f44e72fc0d949974931d
|
[
"Apache-2.0"
] | 4
|
2021-05-19T01:43:07.000Z
|
2021-12-09T07:29:34.000Z
|
/*
* Copyright (c) 2021, Horance Liu and the respective contributors
* All rights reserved.
*
* Use of this source code is governed by a Apache 2.0 license that can be found
* in the LICENSE file.
*/
#include "mnn/kernel/cpu/fully_connected_op_cpu.h"
namespace mnn {
namespace kernels {
void fully_connected_op_internal(const Matrix &in_data, const Vector &W,
const Vector &bias, Matrix &out_data, const FullyParams ¶ms,
const bool layer_parallelize)
{
for_i(layer_parallelize, in_data.size(), [&](size_t sample) {
const Vector &in = in_data[sample];
Vector &out = out_data[sample];
for (size_t i = 0; i < params.out_size_; i++) {
out[i] = Float {0};
for (size_t c = 0; c < params.in_size_; c++) {
out[i] += W[c * params.out_size_ + i] * in[c];
}
if (params.has_bias_) {
out[i] += bias[i];
}
}
});
}
void fully_connected_op_internal(const Matrix &prev_out, const Vector &W,
Matrix &dW, Matrix &db, Matrix &curr_delta, Matrix &prev_delta,
const FullyParams ¶ms, const bool layer_parallelize)
{
for (size_t sample = 0; sample < prev_out.size(); sample++) {
for (size_t c = 0; c < params.in_size_; c++) {
// propagate delta to previous layer
// prev_delta[c] += current_delta[r] * W_[c * out_size_ + r]
prev_delta[sample][c] += vectorize::dot(&curr_delta[sample][0],
&W[c * params.out_size_], params.out_size_);
}
for_(layer_parallelize, 0, params.out_size_, [&](const BlockedRange &r) {
// accumulate weight-step using delta
// dW[c * out_size + i] += current_delta[i] * prev_out[c]
for (size_t c = 0; c < params.in_size_; c++) {
vectorize::muladd(&curr_delta[sample][r.begin()], prev_out[sample][c],
r.end() - r.begin(),
&dW[sample][c * params.out_size_ + r.begin()]);
}
if (params.has_bias_) {
// Vector& db = *in_grad[2];
for (size_t i = r.begin(); i < r.end(); i++) {
db[sample][i] += curr_delta[sample][i];
}
}
});
}
}
} // namespace kernels
} // namespace mnn
| 35.223881
| 86
| 0.54322
|
horance-liu
|
fd5d55923e68b941e8e033abfac025a43107741c
| 1,881
|
cpp
|
C++
|
source/computation-derivatives-gt2s_ga1s.cpp
|
p-maybank/bayesian-uq
|
5e3b34aaf33512d94fd417238df5582b3a89170b
|
[
"BSD-3-Clause"
] | 1
|
2021-07-03T22:53:53.000Z
|
2021-07-03T22:53:53.000Z
|
source/computation-derivatives-gt2s_ga1s.cpp
|
p-maybank/bayesian-uq
|
5e3b34aaf33512d94fd417238df5582b3a89170b
|
[
"BSD-3-Clause"
] | null | null | null |
source/computation-derivatives-gt2s_ga1s.cpp
|
p-maybank/bayesian-uq
|
5e3b34aaf33512d94fd417238df5582b3a89170b
|
[
"BSD-3-Clause"
] | 2
|
2021-07-03T22:57:22.000Z
|
2021-10-10T13:29:54.000Z
|
#include <vector>
#include "Eigen/Dense"
#include "scalar-typedef.hpp"
#include "stable-sde.hpp"
#include "data-vector.hpp"
#include "vector-io.hpp"
#include "computation.hpp"
using namespace std;
using namespace Eigen;
#ifdef USE_DCO_TYPES
template<>
void Computation<gt2s_ga1s_scalar>::derivatives(Matrix<gt2s_ga1s_scalar, Dynamic, 1>& theta,
const Eigen::Matrix<gt2s_ga1s_scalar, Eigen::Dynamic, 1>& x_star,
Matrix<double,Dynamic,1> & grad,
Matrix<double,Dynamic,Dynamic> & hess,
unsigned int & ifail){
const int theta_size = theta.size();
grad.resize(theta_size);
hess.resize(theta_size,theta_size);
// Create tape
if( DCO_GA1S_MODE::global_tape==nullptr) {
DCO_GT2S_GA1S_MODE::global_tape = DCO_GT2S_GA1S_MODE::tape_t::create();
}
auto pos = DCO_GT2S_GA1S_MODE::global_tape->get_position();
for(int i=0; i<theta_size; i++) {
// Register inputs
for(int j=0; j<theta_size; j++) {
DCO_GT2S_GA1S_MODE::global_tape->register_variable(theta(j));
}
dco::derivative(dco::value(theta(i))) = 1.0;
// Actual computation to be differentiated
gt2s_ga1s_scalar ll = eval(theta, x_star, ifail);
DCO_GT2S_GA1S_MODE::global_tape->register_output_variable(ll);
dco::derivative(ll) = 1.0;
DCO_GT2S_GA1S_MODE::global_tape->interpret_adjoint();
// Fill Jacobian
grad(i) = dco::value(dco::derivative(theta(i)));
// Fill Hessian
for(int j=0; j<theta_size; j++) hess(j, i) = dco::derivative(dco::derivative(theta(j)));
dco::derivative(dco::value(theta(i))) = 0.0;
DCO_GT2S_GA1S_MODE::global_tape->reset();
}
DCO_GT2S_GA1S_MODE::global_tape->reset_to( pos );
DCO_GT2S_GA1S_MODE::tape_t::remove(DCO_GT2S_GA1S_MODE::global_tape);
return;
}
#endif
| 32.431034
| 103
| 0.653907
|
p-maybank
|
5b746ac7d9bb646e6168d6c081e3f442cb2d1b9f
| 366
|
cpp
|
C++
|
src/en/WorldManager.cpp
|
kochol/ari2
|
ca185191531acc1954cd4acfec2137e32fdb5c2d
|
[
"MIT"
] | 81
|
2018-12-11T20:48:41.000Z
|
2022-03-18T22:24:11.000Z
|
src/en/WorldManager.cpp
|
kochol/ari2
|
ca185191531acc1954cd4acfec2137e32fdb5c2d
|
[
"MIT"
] | 7
|
2020-04-19T11:50:39.000Z
|
2021-11-12T16:08:53.000Z
|
src/en/WorldManager.cpp
|
kochol/ari2
|
ca185191531acc1954cd4acfec2137e32fdb5c2d
|
[
"MIT"
] | 4
|
2019-04-24T11:51:29.000Z
|
2021-03-10T05:26:33.000Z
|
#include "WorldManager.hpp"
#include "World.hpp"
#include <core/memory/Memory.hpp>
namespace ari
{
namespace en
{
//! Create a new World
World* WorldManager::CreateWorld()
{
return core::Memory::New<World>();
}
//! Destroy a world
void WorldManager::DestroyWorld(World* _world)
{
core::Memory::Delete<World>(_world);
}
} // en
} // ari
| 15.25
| 48
| 0.647541
|
kochol
|
5b786104818f2dded7183adeed4c73af5a677cb4
| 2,561
|
cpp
|
C++
|
648-replace-words/648-replace-words.cpp
|
shreydevep/DSA
|
688af414c1fada1b82a4b4e9506747352007c894
|
[
"MIT"
] | null | null | null |
648-replace-words/648-replace-words.cpp
|
shreydevep/DSA
|
688af414c1fada1b82a4b4e9506747352007c894
|
[
"MIT"
] | null | null | null |
648-replace-words/648-replace-words.cpp
|
shreydevep/DSA
|
688af414c1fada1b82a4b4e9506747352007c894
|
[
"MIT"
] | null | null | null |
class Solution {
public:
class Trie{
public:
class Node{
public:
Node* links[26] = {NULL};
string str = "";
bool containsKey(char ch){
return (links[ch-'a'] != NULL);
}
void put(char ch, Node* node){
links[ch-'a'] = node;
}
Node* get(char ch){
return links[ch-'a'];
}
void setEnd(string word){
str = word;
}
};
Node* root;
Trie(){
root = new Node();
}
void insert(string word){
Node* node = root;
for(auto ch : word){
if(!node->containsKey(ch)){
node->put(ch,new Node);
}
node = node->get(ch);
}
node->setEnd(word);
}
string replaceWithPrefix(string word){
Node* node = root;
for(auto ch : word){
if(!node->containsKey(ch)){
return word;
}
node = node->get(ch);
//cout << ch <<" "<< node->str <<" "<< word <<"\n";
if(node->str != ""){
return node->str;
}
}
if(node->str != "") return node->str;
return word;
}
};
vector<string> removeDupWord(string str)
{
// Used to split string around spaces.
vector <string> fin;
istringstream ss(str);
string word; // for storing each word
// Traverse through all words
// while loop till we get
// strings to store in string word
while (ss >> word)
{
// print the read word
fin.push_back(word);
}
return fin;
}
string replaceWords(vector<string>& dictionary, string sentence) {
Trie obj;
vector <string> fin = removeDupWord(sentence);
for(auto word : dictionary){
obj.insert(word);
}
for(int i=0;i<fin.size();++i){
fin[i] = obj.replaceWithPrefix(fin[i]);
}
sentence = "";
for(int i=0;i<fin.size();++i){
sentence += (fin[i] + " ");
}
sentence.pop_back();
return sentence;
}
};
| 25.868687
| 70
| 0.385396
|
shreydevep
|
5b7a233f651cf3fd113d95f0df596b982066c3b6
| 4,813
|
hpp
|
C++
|
hpx/util/detail/empty_vtable.hpp
|
andreasbuhr/hpx
|
4366a90aacbd3e95428a94ab24a1646a67459cc2
|
[
"BSL-1.0"
] | null | null | null |
hpx/util/detail/empty_vtable.hpp
|
andreasbuhr/hpx
|
4366a90aacbd3e95428a94ab24a1646a67459cc2
|
[
"BSL-1.0"
] | null | null | null |
hpx/util/detail/empty_vtable.hpp
|
andreasbuhr/hpx
|
4366a90aacbd3e95428a94ab24a1646a67459cc2
|
[
"BSL-1.0"
] | null | null | null |
// Copyright (c) 2011 Thomas Heller
// Copyright (c) 2013 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#if !BOOST_PP_IS_ITERATING
#ifndef HPX_FUNCTION_DETAIL_EMPTY_VTABLE_HPP
#define HPX_FUNCTION_DETAIL_EMPTY_VTABLE_HPP
#include <hpx/config/forceinline.hpp>
#include <hpx/util/add_rvalue_reference.hpp>
#include <boost/ref.hpp>
#include <boost/preprocessor/iteration/iterate.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/repetition/enum_trailing_params.hpp>
#include <typeinfo>
namespace hpx { namespace util { namespace detail
{
struct empty_vtable_base
{
enum { empty = true };
static std::type_info const& get_type()
{
return typeid(void);
}
static void static_delete(void ** f) {}
static void destruct(void ** f) {}
static void clone(void *const* f, void ** dest) {}
static void copy(void *const* f, void ** dest) {}
// we can safely return an int here as those function will never
// be called.
static int& construct(void ** f)
{
hpx::throw_exception(bad_function_call,
"empty function object should not be used",
"empty_vtable_base::construct", __FILE__, __LINE__);
static int t = 0;
return t;
}
static int& get(void **f)
{
hpx::throw_exception(bad_function_call,
"empty function object should not be used",
"empty_vtable_base::get", __FILE__, __LINE__);
static int t = 0;
return t;
}
static int& get(void *const*f)
{
hpx::throw_exception(bad_function_call,
"empty function object should not be used",
"empty_vtable_base::get", __FILE__, __LINE__);
static int t = 0;
return t;
}
};
template <typename Sig, typename IArchive, typename OArchive>
struct empty_vtable;
}}}
#define BOOST_UTIL_DETAIL_EMPTY_VTABLE_ADD_RVALUE_REF(Z, N, D) \
typename util::add_rvalue_reference<BOOST_PP_CAT(D, N)>::type \
BOOST_PP_CAT(a, N) \
/**/
#if !defined(HPX_USE_PREPROCESSOR_LIMIT_EXPANSION)
# include <hpx/util/detail/preprocessed/empty_vtable.hpp>
#else
#if defined(__WAVE__) && defined(HPX_CREATE_PREPROCESSED_FILES)
# pragma wave option(preserve: 1, line: 0, output: "preprocessed/empty_vtable_" HPX_LIMIT_STR ".hpp")
#endif
#define BOOST_PP_ITERATION_PARAMS_1 \
( \
3 \
, ( \
0 \
, HPX_FUNCTION_ARGUMENT_LIMIT \
, <hpx/util/detail/empty_vtable.hpp> \
) \
) \
/**/
#include BOOST_PP_ITERATE()
#if defined(__WAVE__) && defined (HPX_CREATE_PREPROCESSED_FILES)
# pragma wave option(output: null)
#endif
#endif // !defined(HPX_USE_PREPROCESSOR_LIMIT_EXPANSION)
#undef BOOST_UTIL_DETAIL_EMPTY_VTABLE_ADD_RVALUE_REF
#endif
#else
#define N BOOST_PP_ITERATION()
namespace hpx { namespace util { namespace detail
{
template <
typename R
BOOST_PP_ENUM_TRAILING_PARAMS(N, typename A)
, typename IArchive
, typename OArchive
>
struct empty_vtable<
R(BOOST_PP_ENUM_PARAMS(N, A))
, IArchive
, OArchive
>
: empty_vtable_base
{
typedef R (*functor_type)(BOOST_PP_ENUM_PARAMS(N, A));
static vtable_ptr_base<
R(BOOST_PP_ENUM_PARAMS(N, A))
, IArchive
, OArchive
> *get_ptr()
{
return
get_empty_table<
R(BOOST_PP_ENUM_PARAMS(N, A))
>::template get<IArchive, OArchive>();
}
BOOST_ATTRIBUTE_NORETURN static R
invoke(void ** f
BOOST_PP_ENUM_TRAILING(N, BOOST_UTIL_DETAIL_EMPTY_VTABLE_ADD_RVALUE_REF, A))
{
hpx::throw_exception(bad_function_call,
"empty function object should not be used",
"empty_vtable::operator()");
}
};
}}}
#undef N
#endif
| 31.051613
| 102
| 0.540204
|
andreasbuhr
|
5b7babe6958aa7327c1581dc0a7afa00fc9aab33
| 1,960
|
cpp
|
C++
|
khr2/controllers/khr2/KHR2_Data.cpp
|
llessieux/KHR2Webot
|
f1d7207c12b2a666b023c4a16082601b29ae54bb
|
[
"MIT"
] | null | null | null |
khr2/controllers/khr2/KHR2_Data.cpp
|
llessieux/KHR2Webot
|
f1d7207c12b2a666b023c4a16082601b29ae54bb
|
[
"MIT"
] | null | null | null |
khr2/controllers/khr2/KHR2_Data.cpp
|
llessieux/KHR2Webot
|
f1d7207c12b2a666b023c4a16082601b29ae54bb
|
[
"MIT"
] | null | null | null |
#include "KHR2_Data.h"
bool RCBMotion::SaveToFile(RCBMotion *m,char *filename)
{
FILE *f = fopen(filename,"wt");
if ( f == NULL )
return false;
fprintf(f,"[GraphicalEdit]\n");
fprintf(f,"Type=%d\n",m->m_type);
fprintf(f,"Width=500\n");
fprintf(f,"Height=%d\n",30*((m->m_item_count/8) + 1));
fprintf(f,"Items=%d\n",m->m_item_count);
fprintf(f,"Links=%d\n",m->m_link_count);
fprintf(f,"Start=%d\n",m->m_start);
fprintf(f,"Name=%s\n",m->m_name);
fprintf(f,"Port=0\n");
fprintf(f,"Ctrl=%d\n",m->m_control);
fprintf(f,"\n");
for(int i=0;i<m->m_item_count;i++)
{
const RCBMotionItem &item = m->m_items[i];
fprintf(f,"[Item%d]\n",i);
fprintf(f,"Name=%s\n",item.m_name);
fprintf(f,"Width=%d\n",item.m_width);
fprintf(f,"Height=%d\n",item.m_height);
fprintf(f,"Left=%d\n",item.m_left);
fprintf(f,"Top=%d\n",item.m_top);
fprintf(f,"Color=%d\n",item.m_color);
fprintf(f,"Type=%d\n",item.m_type);
fprintf(f,"Prm=");
std::list<int>::const_iterator it = item.m_params.begin();
for(int j=0;j<24;j++,it++)
{
fprintf(f,"%d",*it);
if ( j != 23 )
fprintf(f,",");
else
fprintf(f,"\n");
}
fprintf(f,"\n");
}
for(int i=0;i<m->m_link_count;i++)
{
const RCBMotionLink &item = m->m_links[i];
fprintf(f,"[Link%d]\n",i);
fprintf(f,"Main=%d\n",item.m_main);
fprintf(f,"Origin=%d\n",item.m_origin);
fprintf(f,"Final=%d\n",item.m_final);
fprintf(f,"Point=");
for(unsigned int j=0;j<item.m_points.size();j++)
{
fprintf(f,"%d",item.m_points[j]);
if ( j != item.m_points.size()-1 )
fprintf(f,",");
}
fprintf(f,"\n");
fprintf(f,"\n");
}
fclose(f);
return true;
}
| 28.823529
| 66
| 0.497959
|
llessieux
|
5b829bdb1b036b5ea700ffa3692ecbcf1da3b1ca
| 674
|
hpp
|
C++
|
ILogger.hpp
|
kit-cpp-course/yushkov-ia
|
f08795754beec39a5b0801a0e4bad8f87c9838b4
|
[
"MIT"
] | null | null | null |
ILogger.hpp
|
kit-cpp-course/yushkov-ia
|
f08795754beec39a5b0801a0e4bad8f87c9838b4
|
[
"MIT"
] | null | null | null |
ILogger.hpp
|
kit-cpp-course/yushkov-ia
|
f08795754beec39a5b0801a0e4bad8f87c9838b4
|
[
"MIT"
] | null | null | null |
#pragma once
#include <string>
namespace wv
{
class OperationLogger;
/*
* Интерфейс для логирования действий
*/
class ILogger
{
public:
virtual ~ILogger() = default;
/*
* Записывает строку в лог
*/
virtual void Log(const std::string& message) const = 0;
/*
* Записывает строку в лог, добавляя в конец символ конца строки
*/
virtual void LogLine(const std::string& message) const = 0;
/*
* Записывает целое число в лог
*/
virtual void Log(int value) const = 0;
/*
* Логирует длительность операции
*/
virtual OperationLogger LogOperation(const std::string& message) const = 0;
};
}
| 18.216216
| 78
| 0.626113
|
kit-cpp-course
|
5b876d3da54dbd8e01a2d50acf5895694f48e76a
| 489
|
hpp
|
C++
|
include/boost/hana/group/minus_mcd.hpp
|
rbock/hana
|
2b76377f91a5ebe037dea444e4eaabba6498d3a8
|
[
"BSL-1.0"
] | 2
|
2015-05-07T14:29:13.000Z
|
2015-07-04T10:59:46.000Z
|
include/boost/hana/group/minus_mcd.hpp
|
rbock/hana
|
2b76377f91a5ebe037dea444e4eaabba6498d3a8
|
[
"BSL-1.0"
] | null | null | null |
include/boost/hana/group/minus_mcd.hpp
|
rbock/hana
|
2b76377f91a5ebe037dea444e4eaabba6498d3a8
|
[
"BSL-1.0"
] | null | null | null |
/*!
@file
Defines `boost::hana::Group::minus_mcd`.
@copyright Louis Dionne 2014
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_HANA_GROUP_MINUS_MCD_HPP
#define BOOST_HANA_GROUP_MINUS_MCD_HPP
// minus_mcd is in the forward declaration header because it is required by
// the instance for builtins
#include <boost/hana/group/group.hpp>
#endif // !BOOST_HANA_GROUP_MINUS_MCD_HPP
| 27.166667
| 78
| 0.791411
|
rbock
|
5b88b9108869ce09833464ed746880ef99723f20
| 1,039
|
cpp
|
C++
|
20.Valid_Parentheses/solution_1.cpp
|
bngit/leetcode-practices
|
5324aceac708d9b214a7d98d489b8d5dc55c89e9
|
[
"MIT"
] | null | null | null |
20.Valid_Parentheses/solution_1.cpp
|
bngit/leetcode-practices
|
5324aceac708d9b214a7d98d489b8d5dc55c89e9
|
[
"MIT"
] | null | null | null |
20.Valid_Parentheses/solution_1.cpp
|
bngit/leetcode-practices
|
5324aceac708d9b214a7d98d489b8d5dc55c89e9
|
[
"MIT"
] | null | null | null |
#include <cstdlib>
#include <vector>
#include <string>
#include <cassert>
#include <algorithm>
#include <sstream>
#include <map>
#include <typeinfo>
#include <iostream>
#include <stack>
using namespace std;
class Solution {
public:
bool isValid(string s) {
stack<char> bracket;
for (auto &c : s) {
if (!bracket.empty()) {
if ((bracket.top() == '(' && c == ')') // 这里写成and也是可以的
|| (bracket.top() == '[' && c == ']')
|| (bracket.top() == '{' && c == '}')) {
bracket.pop();
}
else {
if (c == ')' || c == ']' || c == '}') {
return false;
}
else {
bracket.push(c);
}
}
}
else {
bracket.push(c);
}
}
if (!bracket.empty()) {
return false;
}
return true;
}
};
| 23.613636
| 71
| 0.358999
|
bngit
|
5b8e0ad8c2a72e7b0c96728367d7311d9dd0297c
| 325
|
cpp
|
C++
|
test/StaircaseSimulator_main.cpp
|
leiz86/staircase_code_simulator
|
bba297c1c1fbb4921855b0e4f43afb505c1235fa
|
[
"Apache-2.0"
] | null | null | null |
test/StaircaseSimulator_main.cpp
|
leiz86/staircase_code_simulator
|
bba297c1c1fbb4921855b0e4f43afb505c1235fa
|
[
"Apache-2.0"
] | null | null | null |
test/StaircaseSimulator_main.cpp
|
leiz86/staircase_code_simulator
|
bba297c1c1fbb4921855b0e4f43afb505c1235fa
|
[
"Apache-2.0"
] | null | null | null |
/*
* StaircaseSimulator_main.cpp
*
* Created on: Dec 10, 2017
* Author: leizhang
*/
#include "StaircaseSimulator.h"
int main(int argc, char **argv) {
StaircaseSimulator & scs = StaircaseSimulator::GetInstance();
const char testOpts[] = "test";
scs.init(testOpts);
scs.run(0);
scs.report(1);
return 0;
}
| 15.47619
| 62
| 0.664615
|
leiz86
|
5b901cc7a7352094517dae80b4131606c50d23d6
| 674
|
hpp
|
C++
|
src/ResolvedResource.hpp
|
abelsensors/esp32_https_server
|
e568d8321764cce26ab76976f6489065b3744c7a
|
[
"MIT"
] | 221
|
2018-06-11T07:47:54.000Z
|
2022-03-28T17:56:06.000Z
|
src/ResolvedResource.hpp
|
abelsensors/esp32_https_server
|
e568d8321764cce26ab76976f6489065b3744c7a
|
[
"MIT"
] | 128
|
2017-12-19T18:18:58.000Z
|
2022-03-22T01:15:26.000Z
|
src/ResolvedResource.hpp
|
abelsensors/esp32_https_server
|
e568d8321764cce26ab76976f6489065b3744c7a
|
[
"MIT"
] | 82
|
2018-04-29T01:14:47.000Z
|
2022-03-21T11:32:02.000Z
|
#ifndef SRC_RESOLVEDRESOURCE_HPP_
#define SRC_RESOLVEDRESOURCE_HPP_
#include "ResourceNode.hpp"
#include "ResourceParameters.hpp"
namespace httpsserver {
/**
* \brief This class represents a resolved resource, meaning the result of mapping a string URL to an HTTPNode
*/
class ResolvedResource {
public:
ResolvedResource();
~ResolvedResource();
void setMatchingNode(HTTPNode * node);
HTTPNode * getMatchingNode();
bool didMatch();
ResourceParameters * getParams();
void setParams(ResourceParameters * params);
private:
HTTPNode * _matchingNode;
ResourceParameters * _params;
};
} /* namespace httpsserver */
#endif /* SRC_RESOLVEDRESOURCE_HPP_ */
| 21.741935
| 110
| 0.759644
|
abelsensors
|
5b9d03e9935b8a3135870fceae961f323becc7a0
| 20,861
|
hpp
|
C++
|
main.hpp
|
mehmetoguzderin/cpp-2021-vulkan
|
07e3eba40e9df66ddd3bce8ea266300dc735a3f0
|
[
"CC0-1.0"
] | null | null | null |
main.hpp
|
mehmetoguzderin/cpp-2021-vulkan
|
07e3eba40e9df66ddd3bce8ea266300dc735a3f0
|
[
"CC0-1.0"
] | null | null | null |
main.hpp
|
mehmetoguzderin/cpp-2021-vulkan
|
07e3eba40e9df66ddd3bce8ea266300dc735a3f0
|
[
"CC0-1.0"
] | null | null | null |
/* Inspired by
* https://github.com/KhronosGroup/Vulkan-Hpp/tree/master/RAII_Samples
* https://github.com/KhronosGroup/Vulkan-Tools/tree/master/cube
* https://github.com/KhronosGroup/Vulkan-Samples/tree/master/samples/extensions/raytracing_basic
* https://github.com/glfw/glfw/blob/master/tests/triangle-vulkan.c
* https://github.com/charles-lunarg/vk-bootstrap/tree/master/example
* https://github.com/ocornut/imgui/blob/master/examples/example_glfw_vulkan/main.cpp
* https://github.com/nvpro-samples/vk_raytracing_tutorial_KHR
*/
#include <algorithm>
#include <cassert>
#include <chrono>
#include <cinttypes>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <limits>
#include <memory>
#include <numeric>
#include <optional>
#include <sstream>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#define VK_NO_PROTOTYPES
#define VULKAN_HPP_TYPESAFE_CONVERSION
#define VULKAN_HPP_DISPATCH_LOADER_DYNAMIC 1
#include "vulkan/vulkan.hpp"
#include "vulkan/vulkan_raii.hpp"
VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE
#define VMA_VULKAN_VERSION 1002000
#define VMA_STATIC_VULKAN_FUNCTIONS 0
#define VMA_DYNAMIC_VULKAN_FUNCTIONS 0
#define VMA_IMPLEMENTATION
#include "vk_mem_alloc.h"
#define GLFW_INCLUDE_NONE
#include "GLFW/glfw3.h"
#define IMGUI_IMPL_VULKAN_NO_PROTOTYPES
#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_vulkan.h"
#include "glm/ext.hpp"
#include "glm/glm.hpp"
using namespace glm;
#include "glslang/SPIRV/GlslangToSpv.h"
#include "CLI/App.hpp"
#include "CLI/Config.hpp"
#include "CLI/Formatter.hpp"
#include "main.h"
struct Main {
std::string applicationName{"cpp-2021-vulkan"};
double applicationDuration = 0.0;
uint64_t frameCount = 0;
double frameDuration = 0.0;
UniformConstants uniformConstants{{0, 0, 0}};
std::unique_ptr<vk::raii::Context> context;
std::unique_ptr<vk::raii::Instance> instance;
std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice;
uint32_t queueFamilyIndex;
std::unique_ptr<vk::raii::Device> device;
std::unique_ptr<vk::raii::Queue> queue;
std::unique_ptr<vk::raii::CommandPool> commandPool;
void commandPoolSubmit(const std::function<void(const vk::raii::CommandBuffer& commandBuffer)> encoder,
vk::Fence waitFence = {},
const vk::ArrayProxyNoTemporaries<const vk::PipelineStageFlags>& waitStageMask = {},
const vk::ArrayProxyNoTemporaries<const vk::Semaphore>& waitSemaphores = {}) {
vk::CommandBufferAllocateInfo commandBufferAllocateInfo(**commandPool, vk::CommandBufferLevel::ePrimary, 1);
auto commandBuffer = std::move(vk::raii::CommandBuffers(*device, commandBufferAllocateInfo).front());
commandBuffer.begin(vk::CommandBufferBeginInfo(vk::CommandBufferUsageFlagBits::eOneTimeSubmit));
encoder(commandBuffer);
commandBuffer.end();
vk::SubmitInfo submitInfo(waitSemaphores, waitStageMask, *commandBuffer);
queue->submit(submitInfo, waitFence);
queue->waitIdle();
}
std::unique_ptr<vk::raii::DescriptorPool> descriptorPool;
VmaAllocator allocator;
void allocatorCreate() {
VmaVulkanFunctions allocatorVulkanFunctions{};
#define VMA_VULKAN_FUNCTIONS_RAII_INSTANCE(functionName) allocatorVulkanFunctions.functionName = instance->getDispatcher()->functionName
#define VMA_VULKAN_FUNCTIONS_RAII_DEVICE(functionName) allocatorVulkanFunctions.functionName = device->getDispatcher()->functionName;
#define VMA_VULKAN_KHR_FUNCTIONS_RAII_INSTANCE(functionName) \
if (instance->getDispatcher()->functionName##KHR == nullptr) \
allocatorVulkanFunctions.functionName##KHR = instance->getDispatcher()->functionName; \
else \
allocatorVulkanFunctions.functionName##KHR = instance->getDispatcher()->functionName##KHR;
#define VMA_VULKAN_KHR_FUNCTIONS_RAII_DEVICE(functionName) \
if (device->getDispatcher()->functionName##KHR == nullptr) \
allocatorVulkanFunctions.functionName##KHR = device->getDispatcher()->functionName; \
else \
allocatorVulkanFunctions.functionName##KHR = device->getDispatcher()->functionName##KHR;
VMA_VULKAN_FUNCTIONS_RAII_INSTANCE(vkGetPhysicalDeviceProperties);
VMA_VULKAN_FUNCTIONS_RAII_INSTANCE(vkGetPhysicalDeviceMemoryProperties);
VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkAllocateMemory);
VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkFreeMemory);
VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkMapMemory);
VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkUnmapMemory);
VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkFlushMappedMemoryRanges);
VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkInvalidateMappedMemoryRanges);
VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkBindBufferMemory);
VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkBindImageMemory);
VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkGetBufferMemoryRequirements);
VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkGetImageMemoryRequirements);
VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkCreateBuffer);
VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkDestroyBuffer);
VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkCreateImage);
VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkDestroyImage);
VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkCmdCopyBuffer);
VMA_VULKAN_KHR_FUNCTIONS_RAII_DEVICE(vkGetBufferMemoryRequirements2);
VMA_VULKAN_KHR_FUNCTIONS_RAII_DEVICE(vkGetImageMemoryRequirements2);
VMA_VULKAN_KHR_FUNCTIONS_RAII_DEVICE(vkBindBufferMemory2);
VMA_VULKAN_KHR_FUNCTIONS_RAII_DEVICE(vkBindImageMemory2);
VMA_VULKAN_KHR_FUNCTIONS_RAII_INSTANCE(vkGetPhysicalDeviceMemoryProperties2);
#undef VMA_VULKAN_KHR_FUNCTIONS_RAII_DEVICE
#undef VMA_VULKAN_KHR_FUNCTIONS_RAII_INSTANCE
#undef VMA_VULKAN_FUNCTIONS_RAII_DEVICE
#undef VMA_VULKAN_FUNCTIONS_RAII_INSTANCE
VmaAllocatorCreateInfo allocatorCreateInfo{
.flags = 0,
.physicalDevice = static_cast<VkPhysicalDevice>(**physicalDevice),
.device = static_cast<VkDevice>(**device),
.pVulkanFunctions = &allocatorVulkanFunctions,
.instance = static_cast<VkInstance>(**instance),
.vulkanApiVersion = VK_API_VERSION_1_2,
};
if (vmaCreateAllocator(&allocatorCreateInfo, &allocator) != VK_SUCCESS) {
throw std::runtime_error("vmaCreateAllocator(&allocatorCreateInfo, &allocator) != VK_SUCCESS");
};
}
void allocatorDestroy() { vmaDestroyAllocator(allocator); }
struct Buffer {
vk::Buffer buffer;
vk::DescriptorBufferInfo descriptor;
VmaAllocation allocation;
VmaAllocationInfo info;
};
Buffer bufferCreate(const vk::BufferCreateInfo bufferCreateInfo, const VmaAllocationCreateInfo allocationCreateInfo) {
VkBufferCreateInfo vkBufferCreateInfo = static_cast<VkBufferCreateInfo>(bufferCreateInfo);
VkBuffer vkBuffer;
VmaAllocation vmaAllocation;
VmaAllocationInfo vmaInfo;
if (vmaCreateBuffer(allocator, &vkBufferCreateInfo, &allocationCreateInfo, &vkBuffer, &vmaAllocation, &vmaInfo) != VK_SUCCESS) {
throw std::runtime_error(
"vmaCreateBuffer(allocator, &vkBufferCreateInfo, &allocationCreateInfo, &vkBuffer, &vmaAllocation, &vmaInfo) != VK_SUCCESS");
}
return Buffer{
.buffer = static_cast<vk::Buffer>(vkBuffer),
.descriptor = vk::DescriptorBufferInfo(vkBuffer, 0, bufferCreateInfo.size),
.allocation = vmaAllocation,
.info = vmaInfo,
};
}
template <typename T>
void bufferUse(const Buffer buffer, const std::function<void(T* data)> user) {
void* data;
if (vmaMapMemory(allocator, buffer.allocation, &data) != VK_SUCCESS)
throw std::runtime_error("vmaMapMemory(allocator, buffer.allocation, &data) != VK_SUCCESS");
vmaInvalidateAllocation(allocator, buffer.allocation, 0, buffer.descriptor.range);
user(reinterpret_cast<T*>(data));
vmaFlushAllocation(allocator, buffer.allocation, 0, buffer.descriptor.range);
vmaUnmapMemory(allocator, buffer.allocation);
}
void bufferDestroy(Buffer& buffer) { vmaDestroyBuffer(allocator, buffer.buffer, buffer.allocation); }
struct Image {
vk::Image image;
std::unique_ptr<vk::raii::ImageView> view;
VmaAllocation allocation;
VmaAllocationInfo info;
};
Image imageCreate(const vk::ImageCreateInfo imageCreateInfo,
vk::ImageViewCreateInfo viewCreateInfo,
const VmaAllocationCreateInfo allocationCreateInfo) {
auto vkImageCreateInfo = static_cast<VkImageCreateInfo>(imageCreateInfo);
VkImage vkImage;
VmaAllocation allocation;
VmaAllocationInfo allocationInfo;
if (vmaCreateImage(allocator, &vkImageCreateInfo, &allocationCreateInfo, &vkImage, &allocation, &allocationInfo) != VK_SUCCESS)
throw std::runtime_error(
"vmaCreateImage(allocator, &vkImageCreateInfo, &allocationCreateInfo, &vkImage, &allocation, &allocationInfo) != "
"VK_SUCCESS");
vk::Image image(vkImage);
viewCreateInfo.image = image;
return Image{
.image = static_cast<vk::Image>(vkImage),
.view = std::make_unique<vk::raii::ImageView>(*device, viewCreateInfo),
.allocation = allocation,
.info = allocationInfo,
};
}
void imageDestroy(Image& image) {
image.view.reset();
vmaDestroyImage(allocator, image.image, image.allocation);
}
vk::raii::ShaderModule shaderModuleCreateFromGlslFile(vk::ShaderStageFlagBits shaderStage, std::filesystem::path shaderGlsl) {
std::ifstream shaderModuleMainCompInput(shaderGlsl, std::ios::binary);
if (shaderModuleMainCompInput.fail()) {
throw std::runtime_error("shaderModuleMainCompInput.fail()");
}
std::stringstream shaderModuleMainCompStream;
shaderModuleMainCompStream << shaderModuleMainCompInput.rdbuf();
std::string shaderSource = shaderModuleMainCompStream.str();
std::vector<unsigned int> shaderSpirv;
EShLanguage stage;
switch (shaderStage) {
case vk::ShaderStageFlagBits::eVertex:
stage = EShLangVertex;
break;
case vk::ShaderStageFlagBits::eTessellationControl:
stage = EShLangTessControl;
break;
case vk::ShaderStageFlagBits::eTessellationEvaluation:
stage = EShLangTessEvaluation;
break;
case vk::ShaderStageFlagBits::eGeometry:
stage = EShLangGeometry;
break;
case vk::ShaderStageFlagBits::eFragment:
stage = EShLangFragment;
break;
case vk::ShaderStageFlagBits::eCompute:
stage = EShLangCompute;
break;
case vk::ShaderStageFlagBits::eRaygenKHR:
stage = EShLangRayGen;
break;
case vk::ShaderStageFlagBits::eAnyHitKHR:
stage = EShLangAnyHit;
break;
case vk::ShaderStageFlagBits::eClosestHitKHR:
stage = EShLangClosestHit;
break;
case vk::ShaderStageFlagBits::eMissKHR:
stage = EShLangMiss;
break;
case vk::ShaderStageFlagBits::eIntersectionKHR:
stage = EShLangIntersect;
break;
case vk::ShaderStageFlagBits::eCallableKHR:
stage = EShLangCallable;
break;
default:
throw std::runtime_error("shaderStage");
}
const char* shaderStrings[1]{shaderSource.data()};
glslang::TShader shader(stage);
shader.setStrings(shaderStrings, 1);
EShMessages messages = (EShMessages)(EShMsgSpvRules | EShMsgVulkanRules);
TBuiltInResource buildInResources{.maxLights = 32,
.maxClipPlanes = 6,
.maxTextureUnits = 32,
.maxTextureCoords = 32,
.maxVertexAttribs = 64,
.maxVertexUniformComponents = 4096,
.maxVaryingFloats = 64,
.maxVertexTextureImageUnits = 32,
.maxCombinedTextureImageUnits = 80,
.maxTextureImageUnits = 32,
.maxFragmentUniformComponents = 4096,
.maxDrawBuffers = 32,
.maxVertexUniformVectors = 128,
.maxVaryingVectors = 8,
.maxFragmentUniformVectors = 16,
.maxVertexOutputVectors = 16,
.maxFragmentInputVectors = 15,
.minProgramTexelOffset = -8,
.maxProgramTexelOffset = 7,
.maxClipDistances = 8,
.maxComputeWorkGroupCountX = 65535,
.maxComputeWorkGroupCountY = 65535,
.maxComputeWorkGroupCountZ = 65535,
.maxComputeWorkGroupSizeX = 1024,
.maxComputeWorkGroupSizeY = 1024,
.maxComputeWorkGroupSizeZ = 64,
.maxComputeUniformComponents = 1024,
.maxComputeTextureImageUnits = 16,
.maxComputeImageUniforms = 8,
.maxComputeAtomicCounters = 8,
.maxComputeAtomicCounterBuffers = 1,
.maxVaryingComponents = 60,
.maxVertexOutputComponents = 64,
.maxGeometryInputComponents = 64,
.maxGeometryOutputComponents = 128,
.maxFragmentInputComponents = 128,
.maxImageUnits = 8,
.maxCombinedImageUnitsAndFragmentOutputs = 8,
.maxCombinedShaderOutputResources = 8,
.maxImageSamples = 0,
.maxVertexImageUniforms = 0,
.maxTessControlImageUniforms = 0,
.maxTessEvaluationImageUniforms = 0,
.maxGeometryImageUniforms = 0,
.maxFragmentImageUniforms = 8,
.maxCombinedImageUniforms = 8,
.maxGeometryTextureImageUnits = 16,
.maxGeometryOutputVertices = 256,
.maxGeometryTotalOutputComponents = 1024,
.maxGeometryUniformComponents = 1024,
.maxGeometryVaryingComponents = 64,
.maxTessControlInputComponents = 128,
.maxTessControlOutputComponents = 128,
.maxTessControlTextureImageUnits = 16,
.maxTessControlUniformComponents = 1024,
.maxTessControlTotalOutputComponents = 4096,
.maxTessEvaluationInputComponents = 128,
.maxTessEvaluationOutputComponents = 128,
.maxTessEvaluationTextureImageUnits = 16,
.maxTessEvaluationUniformComponents = 1024,
.maxTessPatchComponents = 120,
.maxPatchVertices = 32,
.maxTessGenLevel = 64,
.maxViewports = 16,
.maxVertexAtomicCounters = 0,
.maxTessControlAtomicCounters = 0,
.maxTessEvaluationAtomicCounters = 0,
.maxGeometryAtomicCounters = 0,
.maxFragmentAtomicCounters = 8,
.maxCombinedAtomicCounters = 8,
.maxAtomicCounterBindings = 1,
.maxVertexAtomicCounterBuffers = 0,
.maxTessControlAtomicCounterBuffers = 0,
.maxTessEvaluationAtomicCounterBuffers = 0,
.maxGeometryAtomicCounterBuffers = 0,
.maxFragmentAtomicCounterBuffers = 1,
.maxCombinedAtomicCounterBuffers = 1,
.maxAtomicCounterBufferSize = 16384,
.maxTransformFeedbackBuffers = 4,
.maxTransformFeedbackInterleavedComponents = 64,
.maxCullDistances = 8,
.maxCombinedClipAndCullDistances = 8,
.maxSamples = 4,
.maxMeshOutputVerticesNV = 256,
.maxMeshOutputPrimitivesNV = 512,
.maxMeshWorkGroupSizeX_NV = 32,
.maxMeshWorkGroupSizeY_NV = 1,
.maxMeshWorkGroupSizeZ_NV = 1,
.maxTaskWorkGroupSizeX_NV = 32,
.maxTaskWorkGroupSizeY_NV = 1,
.maxTaskWorkGroupSizeZ_NV = 1,
.maxMeshViewCountNV = 4,
.maxDualSourceDrawBuffersEXT = 1,
.limits = {
.nonInductiveForLoops = 1,
.whileLoops = 1,
.doWhileLoops = 1,
.generalUniformIndexing = 1,
.generalAttributeMatrixVectorIndexing = 1,
.generalVaryingIndexing = 1,
.generalSamplerIndexing = 1,
.generalVariableIndexing = 1,
.generalConstantMatrixVectorIndexing = 1,
}};
if (!shader.parse(&buildInResources, 100, false, messages)) {
throw std::runtime_error(std::string("!shader.parse(&buildInResources, 100, false, messages): getInfoLog:\n") +
std::string(shader.getInfoLog()) + std::string("\ngetInfoDebugLog:\n") + std::string(shader.getInfoDebugLog()));
}
glslang::TProgram program;
program.addShader(&shader);
if (!program.link(messages)) {
throw std::runtime_error(std::string("!program.link(messages): getInfoLog:\n") + std::string(shader.getInfoLog()) +
std::string("\ngetInfoDebugLog:\n") + std::string(shader.getInfoDebugLog()));
}
glslang::GlslangToSpv(*program.getIntermediate(stage), shaderSpirv);
return vk::raii::ShaderModule(*device, vk::ShaderModuleCreateInfo(vk::ShaderModuleCreateFlags(), shaderSpirv));
}
vk::raii::ShaderModule shaderModuleCreateFromSpirvFile(std::filesystem::path shaderSpirvFile) {
std::ifstream shaderModuleMainCompInput(shaderSpirvFile, std::ios::ate | std::ios::binary);
if (shaderModuleMainCompInput.fail()) {
throw std::runtime_error("shaderModuleMainCompInput.fail()");
}
size_t shaderModuleMainCompInputSize = (size_t)shaderModuleMainCompInput.tellg();
std::vector<char> shaderModuleMainCompSpirv(shaderModuleMainCompInputSize);
shaderModuleMainCompInput.seekg(0);
shaderModuleMainCompInput.read(shaderModuleMainCompSpirv.data(), static_cast<std::streamsize>(shaderModuleMainCompInputSize));
return vk::raii::ShaderModule(*device, vk::ShaderModuleCreateInfo({}, shaderModuleMainCompInputSize,
reinterpret_cast<const uint32_t*>(shaderModuleMainCompSpirv.data())));
}
Main() = delete;
Main(const Main&) = delete;
Main& operator=(const Main&) = delete;
Main(int argc, char** argv);
};
| 52.1525
| 143
| 0.602656
|
mehmetoguzderin
|
5b9f95a8c24e74fea5aa9c4adaa61c6ecec9b7d0
| 329
|
cpp
|
C++
|
SelectionAlgorithm.cpp
|
LegatAbyssWalker/SortingAlgorithms
|
ab902e8c7fe1489899263bd2a7f22553d3ed0ede
|
[
"MIT"
] | null | null | null |
SelectionAlgorithm.cpp
|
LegatAbyssWalker/SortingAlgorithms
|
ab902e8c7fe1489899263bd2a7f22553d3ed0ede
|
[
"MIT"
] | null | null | null |
SelectionAlgorithm.cpp
|
LegatAbyssWalker/SortingAlgorithms
|
ab902e8c7fe1489899263bd2a7f22553d3ed0ede
|
[
"MIT"
] | null | null | null |
#include "SelectionAlgorithm.h"
void SelectionAlgorithm::sort() {
// Selective sorts the vector
// Sorts through every single element in the vector
for (int i = 0; i < numbers.size() - 1; i++) {
for (int j = i + 1; j < numbers.size(); j++) {
if (numbers[i] > numbers[j]) { std::swap(numbers[i], numbers[j]); }
}
}
}
| 25.307692
| 70
| 0.610942
|
LegatAbyssWalker
|
5ba2f21372bc93827fa628f632175b0545dc71f5
| 2,892
|
cpp
|
C++
|
src/Platform/PlatformVideoUtilsCommon.cpp
|
mushware/adanaxis-core-app
|
679ac3e8a122e059bb208e84c73efc19753e87dd
|
[
"MIT"
] | 9
|
2020-11-02T17:20:40.000Z
|
2021-12-25T15:35:36.000Z
|
src/Platform/PlatformVideoUtilsCommon.cpp
|
mushware/adanaxis-core-app
|
679ac3e8a122e059bb208e84c73efc19753e87dd
|
[
"MIT"
] | 2
|
2020-06-27T23:14:13.000Z
|
2020-11-02T17:28:32.000Z
|
src/Platform/PlatformVideoUtilsCommon.cpp
|
mushware/adanaxis-core-app
|
679ac3e8a122e059bb208e84c73efc19753e87dd
|
[
"MIT"
] | 1
|
2021-05-12T23:05:42.000Z
|
2021-05-12T23:05:42.000Z
|
//%Header {
/*****************************************************************************
*
* File: src/Platform/PlatformVideoUtilsCommon.cpp
*
* Copyright: Andy Southgate 2002-2007, 2020
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
****************************************************************************/
//%Header } 8CRf6CzmJsi8HkHmspv+DQ
/*
* $Id$
* $Log$
*/
#include "PlatformVideoUtils.h"
#include "mushGL.h"
#include "mushMedia.h"
#include "mushPlatform.h"
using namespace Mushware;
using namespace std;
const GLModeDef&
PlatformVideoUtils::DefaultModeDef(void) const
{
U32 modeNum = 0;
for (U32 i=2; i < m_modeDefs.size(); ++i)
{
if (m_modeDefs[i].Width() == 1024 &&
m_modeDefs[i].Height() == 768)
{
modeNum = i;
}
}
return m_modeDefs[modeNum];
}
Mushware::U32
PlatformVideoUtils::ModeDefFind(const GLModeDef& inModeDef) const
{
U32 retVal = 0;
for (U32 i=1; i<m_modeDefs.size(); ++i)
{
if (inModeDef == m_modeDefs[i])
{
retVal = i;
}
}
return retVal;
}
const GLModeDef&
PlatformVideoUtils::PreviousModeDef(const GLModeDef& inModeDef) const
{
U32 modeNum = ModeDefFind(inModeDef);
if (modeNum == 0)
{
modeNum = m_modeDefs.size() - 1;
}
else
{
--modeNum;
}
return m_modeDefs[modeNum];
}
const GLModeDef&
PlatformVideoUtils::NextModeDef(const GLModeDef& inModeDef) const
{
U32 modeNum = ModeDefFind(inModeDef);
++modeNum;
if (modeNum >= m_modeDefs.size())
{
modeNum = 0;
}
return m_modeDefs[modeNum];
}
U32
PlatformVideoUtils::NumModesGet(void) const
{
return m_modeDefs.size();
}
void
PlatformVideoUtils::RenderModeInfo(U32 inNum) const
{
throw MushcoreLogicFail("RenderModeInfo deprecated");
}
| 25.59292
| 78
| 0.640041
|
mushware
|
5baa6188461759460a685d8ba329c33d962bcbe3
| 800
|
hpp
|
C++
|
include/threepp/materials/ShadowMaterial.hpp
|
maidamai0/threepp
|
9b50e2c0f2a7bb3ebfd3ffeef61dbefcd54c7071
|
[
"MIT"
] | null | null | null |
include/threepp/materials/ShadowMaterial.hpp
|
maidamai0/threepp
|
9b50e2c0f2a7bb3ebfd3ffeef61dbefcd54c7071
|
[
"MIT"
] | null | null | null |
include/threepp/materials/ShadowMaterial.hpp
|
maidamai0/threepp
|
9b50e2c0f2a7bb3ebfd3ffeef61dbefcd54c7071
|
[
"MIT"
] | null | null | null |
// https://github.com/mrdoob/three.js/blob/r129/src/materials/ShadowMaterial.js
#ifndef THREEPP_SHADOWMATERIAL_HPP
#define THREEPP_SHADOWMATERIAL_HPP
#include "interfaces.hpp"
#include "threepp/materials/Material.hpp"
namespace threepp {
class ShadowMaterial : public virtual Material,
public MaterialWithColor {
public:
[[nodiscard]] std::string type() const override {
return "ShadowMaterial";
}
static std::shared_ptr<ShadowMaterial> create() {
return std::shared_ptr<ShadowMaterial>(new ShadowMaterial());
}
protected:
ShadowMaterial() : MaterialWithColor(0x000000) {
this->transparent = true;
};
};
}// namespace threepp
#endif//THREEPP_SHADOWMATERIAL_HPP
| 22.857143
| 79
| 0.655
|
maidamai0
|
5baae439c5d71695f8feea2e6d6b6e5df206df47
| 2,020
|
cc
|
C++
|
src/topo/Tree.cc
|
rkowalewski/fmpi
|
39a5e9add0d0354c4a2cceeb0a91518bd9f41796
|
[
"BSD-3-Clause"
] | null | null | null |
src/topo/Tree.cc
|
rkowalewski/fmpi
|
39a5e9add0d0354c4a2cceeb0a91518bd9f41796
|
[
"BSD-3-Clause"
] | null | null | null |
src/topo/Tree.cc
|
rkowalewski/fmpi
|
39a5e9add0d0354c4a2cceeb0a91518bd9f41796
|
[
"BSD-3-Clause"
] | null | null | null |
#include <fmpi/topo/Tree.hpp>
#include <fmpi/util/Math.hpp>
#include <fmpi/util/NumericRange.hpp>
// TLX
#include <tlx/math/ffs.hpp>
#include <tlx/math/integer_log2.hpp>
#include <tlx/math/round_to_power_of_two.hpp>
namespace fmpi {
static void knomial_tree_aux(Tree* tree, mpi::Rank me, uint32_t size) {
/* Receive from parent */
auto const vr = (me - tree->root + size) % size;
auto const radix = static_cast<int>(tree->radix);
auto const nr = static_cast<int>(size);
int mask = 0x1;
while (mask < nr) {
if ((vr % (radix * mask)) != 0) {
int parent = vr / (radix * mask) * (radix * mask);
parent = (parent + tree->root) % nr;
tree->src = mpi::Rank{parent};
break;
}
mask *= radix;
}
mask /= radix;
/* Send data to all children */
while (mask > 0) {
for (int r = 1; r < radix; r++) {
int child = vr + mask * r;
if (child < nr) {
child = (child + tree->root) % nr;
tree->destinations.push_back(mpi::Rank{child});
}
}
mask /= radix;
}
}
static void binomial_tree_aux(Tree* tree, mpi::Rank me, uint32_t size) {
// cyclically shifted rank
int32_t const vr = (me - tree->root + size) % size;
auto const nr = static_cast<int>(size);
int d = 1; // distance
int r = 0; // round
if (vr > 0) {
r = tlx::ffs(vr) - 1;
d <<= r;
auto const from = ((vr ^ d) + tree->root) % nr;
tree->src = mpi::Rank{from};
} else {
d = tlx::round_up_to_power_of_two(nr);
}
for (d >>= 1; d > 0; d >>= 1, ++r) {
if (vr + d < nr) {
auto to = (vr + d + tree->root) % nr;
tree->destinations.push_back(mpi::Rank{to});
}
}
}
std::unique_ptr<Tree> knomial(
mpi::Rank me, mpi::Rank root, uint32_t size, uint32_t radix) {
std::unique_ptr<Tree> tree = std::make_unique<Tree>(root, radix);
if (radix == 2) {
binomial_tree_aux(tree.get(), me, size);
} else {
knomial_tree_aux(tree.get(), me, size);
}
return tree;
}
} // namespace fmpi
| 25.56962
| 72
| 0.567327
|
rkowalewski
|
5bacbd5c8ea68a83f1c1dc754f283ab8e189ec98
| 2,429
|
hpp
|
C++
|
addons/vehicles_land/configs/vehicles/taki_malitia.hpp
|
SOCOMD/SOCOMD-MODS-2021
|
834cd5f99831bd456179a1f55f5a91398c29bf57
|
[
"MIT"
] | null | null | null |
addons/vehicles_land/configs/vehicles/taki_malitia.hpp
|
SOCOMD/SOCOMD-MODS-2021
|
834cd5f99831bd456179a1f55f5a91398c29bf57
|
[
"MIT"
] | null | null | null |
addons/vehicles_land/configs/vehicles/taki_malitia.hpp
|
SOCOMD/SOCOMD-MODS-2021
|
834cd5f99831bd456179a1f55f5a91398c29bf57
|
[
"MIT"
] | null | null | null |
// mortar man
/*
class CUP_O_2b14_82mm_TK_INS : CUP_2b14_82mm_Base {
class Turrets : Turrets {
class MainTurret : MainTurret {
magazines[] = {
"8Rnd_82mm_Mo_shells",
"8Rnd_82mm_Mo_shells",
"8Rnd_82mm_Mo_shells",
"8Rnd_82mm_Mo_shells",
"8Rnd_82mm_Mo_shells",
"8Rnd_82mm_Mo_shells",
"8Rnd_82mm_Mo_shells",
"8Rnd_82mm_Mo_shells",
"8Rnd_82mm_Mo_Flare_white",
"8Rnd_82mm_Mo_Smoke_white"
};
weapons[] = {"mortar_82mm"};
};
};
};
*/
// m2 BTR milita
class CUP_O_BTR40_MG_TKM : CUP_BTR40_MG_Base {
class Turrets : Turrets {
class MainTurret : MainTurret {
magazines[] = {
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M",
"CUP_200Rnd_TE1_Red_Tracer_127x99_M"
};
weapons[] = {"CUP_Vhmg_M2_veh"};
};
};
};
// APC MT-LB-LV
class CUP_O_MTLB_pk_TK_MILITIA : CUP_MTLB_Base {
class Turrets : Turrets {
class MainTurret : MainTurret {
magazines[] = {
"CUP_2000Rnd_TE1_Green_Tracer_762x54_PKT_M",
"CUP_2000Rnd_TE1_Green_Tracer_762x54_PKT_M",
"CUP_2000Rnd_TE1_Green_Tracer_762x54_PKT_M",
"CUP_2000Rnd_TE1_Green_Tracer_762x54_PKT_M"
};
// default: weapons[] = {"CUP_Vhmg_PKT_veh_Noeject"};
weapons[] = {"CUP_Vhmg_PKT_veh"}; // squirty :)
};
};
};
| 36.80303
| 65
| 0.575957
|
SOCOMD
|
5bb3bbef1b8d4a974b85de8a136d083579370cf0
| 1,662
|
cpp
|
C++
|
source/Entity.cpp
|
thejsa/rhythm-run
|
ab11f97e7552c217bfa4a8392ec96aadf0f9f6b1
|
[
"CC-BY-3.0"
] | 1
|
2022-02-01T19:33:21.000Z
|
2022-02-01T19:33:21.000Z
|
source/Entity.cpp
|
thejsa/rhythm-run
|
ab11f97e7552c217bfa4a8392ec96aadf0f9f6b1
|
[
"CC-BY-3.0"
] | null | null | null |
source/Entity.cpp
|
thejsa/rhythm-run
|
ab11f97e7552c217bfa4a8392ec96aadf0f9f6b1
|
[
"CC-BY-3.0"
] | null | null | null |
/*
* Rhythm Run for Nintendo 3DS
* Lauren Kelly, 2020, 2021
*/
#include <3ds.h>
#include <citro2d.h>
#include <stdint.h>
// Most getters/setters are defined in the header file to enhance performance optimisations
#include "Entity.hpp"
Entity::Entity(float a_x, float a_y, C2D_SpriteSheet a_spriteSheet,
size_t a_spriteIndex = 0, float a_centerX = 0.5f, float a_centerY = 0.5f,
float a_scaleX = 1.0f, float a_scaleY = 1.0f, float a_rotation = 0.0f)
: spriteSheet(a_spriteSheet)
, spriteIndex(a_spriteIndex)
{
// Load specified sprite from specified spriteSheet
C2D_SpriteFromSheet(&sprite, spriteSheet, spriteIndex);
// Set position, scale
C2D_SpriteSetCenter(&sprite, a_centerX, a_centerY);
C2D_SpriteSetPos(&sprite, a_x, a_y);
C2D_SpriteSetScale(&sprite, a_scaleX, a_scaleY);
C2D_SpriteSetRotation(&sprite, a_rotation);
};
void Entity::setSprite(size_t a_index, C2D_SpriteSheet a_spriteSheet = NULL)
{
spriteIndex = a_index;
// If the caller passed a (valid) spritesheet param, use it
if (a_spriteSheet != NULL) {
spriteSheet = a_spriteSheet;
}
sprite.image = C2D_SpriteSheetGetImage(spriteSheet, spriteIndex);
}
Rectangle Entity::getRect()
{
float xOffset = getCenterXRaw();
float yOffset = getCenterYRaw();
return Rectangle(
// top left corner
{
sprite.params.pos.x - xOffset,
sprite.params.pos.y - yOffset },
// lower right corner
{
sprite.params.pos.x - xOffset + getWidth(),
sprite.params.pos.y - yOffset + getHeight() });
}
AABB Entity::getAABB()
{
return AABB(getRect());
}
| 27.7
| 91
| 0.673887
|
thejsa
|
5bb7858ca6daee4250c6e31ec816b851e9d6549e
| 8,804
|
hpp
|
C++
|
source/timemory/components/skeletons.hpp
|
jrmadsen/TiMEmory
|
8df2055e68da56e2fe57f716ca9b6d27f7eb4407
|
[
"MIT"
] | 5
|
2018-01-19T06:18:00.000Z
|
2019-07-19T16:08:46.000Z
|
source/timemory/components/skeletons.hpp
|
jrmadsen/TiMEmory
|
8df2055e68da56e2fe57f716ca9b6d27f7eb4407
|
[
"MIT"
] | 1
|
2018-02-09T21:33:08.000Z
|
2018-02-11T23:39:47.000Z
|
source/timemory/components/skeletons.hpp
|
jrmadsen/TiMEmory
|
8df2055e68da56e2fe57f716ca9b6d27f7eb4407
|
[
"MIT"
] | 2
|
2019-06-30T00:46:54.000Z
|
2019-07-09T18:35:45.000Z
|
// MIT License
//
// Copyright (c) 2020, The Regents of the University of California,
// through Lawrence Berkeley National Laboratory (subject to receipt of any
// required approvals from the U.S. Dept. of Energy). All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
/** \file components/skeletons.hpp
* \headerfile components/skeletons.hpp "timemory/components/skeletons.hpp"
*
* These provide fake types for heavyweight types w.r.t. templates. In general,
* if a component is templated or contains a lot of code, create a skeleton
* and in \ref timemory/components/types.hpp use an #ifdef to provide the skeleton
* instead. Also, make sure the component file is not directly included.
* If the type uses callbacks, emulate the callbacks here.
*
*/
#pragma once
#include <cstdint>
#include <functional>
#include <iostream>
#include <string>
#include <tuple>
#include <type_traits>
#include <vector>
#include "timemory/ert/types.hpp"
// clang-format off
namespace tim { namespace device { struct cpu; struct gpu; } }
// clang-format on
//======================================================================================//
//
namespace tim
{
namespace component
{
namespace skeleton
{
//--------------------------------------------------------------------------------------//
struct base
{};
//--------------------------------------------------------------------------------------//
template <typename... _Types>
struct cuda
{};
//--------------------------------------------------------------------------------------//
template <typename... _Types>
struct nvtx
{};
//--------------------------------------------------------------------------------------//
template <typename _Kind>
struct cupti_activity
{
using activity_kind_t = _Kind;
using kind_vector_type = std::vector<activity_kind_t>;
using get_initializer_t = std::function<kind_vector_type()>;
static get_initializer_t& get_initializer()
{
static auto _lambda = []() { return kind_vector_type{}; };
static get_initializer_t _instance = _lambda;
return _instance;
}
};
//--------------------------------------------------------------------------------------//
template <typename... _Types>
struct cupti_counters
{
// short-hand for vectors
using string_t = std::string;
using strvec_t = std::vector<string_t>;
/// a tuple of the <devices, events, metrics>
using tuple_type = std::tuple<int, strvec_t, strvec_t>;
/// function for setting all of device, metrics, and events
using get_initializer_t = std::function<tuple_type()>;
static get_initializer_t& get_initializer()
{
static auto _lambda = []() -> tuple_type { return tuple_type{}; };
static get_initializer_t _instance = _lambda;
return _instance;
}
};
//--------------------------------------------------------------------------------------//
template <typename... _Types>
struct gpu_roofline
{
using device_t = device::cpu;
using clock_type = wall_clock;
using ert_data_t = ert::exec_data<clock_type>;
using ert_data_ptr_t = std::shared_ptr<ert_data_t>;
// short-hand for variadic expansion
template <typename _Tp>
using ert_config_type = ert::configuration<device_t, _Tp, clock_type>;
template <typename _Tp>
using ert_counter_type = ert::counter<device_t, _Tp, clock_type>;
template <typename _Tp>
using ert_executor_type = ert::executor<device_t, _Tp, clock_type>;
template <typename _Tp>
using ert_callback_type = ert::callback<ert_executor_type<_Tp>>;
// variadic expansion for ERT types
using ert_config_t = std::tuple<ert_config_type<_Types>...>;
using ert_counter_t = std::tuple<ert_counter_type<_Types>...>;
using ert_executor_t = std::tuple<ert_executor_type<_Types>...>;
using ert_callback_t = std::tuple<ert_callback_type<_Types>...>;
static ert_config_t& get_finalizer()
{
static ert_config_t _instance;
return _instance;
}
};
//--------------------------------------------------------------------------------------//
template <size_t N>
struct papi_array
{
using event_list = std::vector<int>;
using get_initializer_t = std::function<event_list()>;
static get_initializer_t& get_initializer()
{
static get_initializer_t _instance = []() { return event_list{}; };
return _instance;
}
};
//--------------------------------------------------------------------------------------//
template <int... _Types>
struct papi_tuple
{};
//--------------------------------------------------------------------------------------//
template <typename... _Types>
struct cpu_roofline
{
using device_t = device::cpu;
using clock_type = wall_clock;
using ert_data_t = ert::exec_data<clock_type>;
using ert_data_ptr_t = std::shared_ptr<ert_data_t>;
// short-hand for variadic expansion
template <typename _Tp>
using ert_config_type = ert::configuration<device_t, _Tp, clock_type>;
template <typename _Tp>
using ert_counter_type = ert::counter<device_t, _Tp, clock_type>;
template <typename _Tp>
using ert_executor_type = ert::executor<device_t, _Tp, clock_type>;
template <typename _Tp>
using ert_callback_type = ert::callback<ert_executor_type<_Tp>>;
// variadic expansion for ERT types
using ert_config_t = std::tuple<ert_config_type<_Types>...>;
using ert_counter_t = std::tuple<ert_counter_type<_Types>...>;
using ert_executor_t = std::tuple<ert_executor_type<_Types>...>;
using ert_callback_t = std::tuple<ert_callback_type<_Types>...>;
static ert_config_t& get_finalizer()
{
static ert_config_t _instance;
return _instance;
}
};
//--------------------------------------------------------------------------------------//
template <size_t _N, typename... _Types>
struct gotcha
{
using config_t = void;
using get_initializer_t = std::function<config_t()>;
static get_initializer_t& get_initializer()
{
static get_initializer_t _instance = []() {};
return _instance;
}
};
//--------------------------------------------------------------------------------------//
template <typename... _Types>
struct caliper
{};
//--------------------------------------------------------------------------------------//
} // namespace skeleton
//--------------------------------------------------------------------------------------//
template <typename _Tp, typename _Vp>
struct base;
//--------------------------------------------------------------------------------------//
template <typename _Tp>
struct base<_Tp, skeleton::base>
{
static constexpr bool implements_storage_v = false;
using Type = _Tp;
using value_type = void;
using base_type = base<_Tp, skeleton::base>;
};
//--------------------------------------------------------------------------------------//
} // namespace component
} // namespace tim
#if !defined(TIMEMORY_USE_GOTCHA)
# if !defined(TIMEMORY_C_GOTCHA)
# define TIMEMORY_C_GOTCHA(...)
# endif
# if !defined(TIMEMORY_DERIVED_GOTCHA)
# define TIMEMORY_DERIVED_GOTCHA(...)
# endif
# if !defined(TIMEMORY_CXX_GOTCHA)
# define TIMEMORY_CXX_GOTCHA(...)
# endif
# if !defined(TIMEMORY_CXX_MEMFUN_GOTCHA)
# define TIMEMORY_CXX_MEMFUN_GOTCHA(...)
# endif
# if !defined(TIMEMORY_C_GOTCHA_TOOL)
# define TIMEMORY_C_GOTCHA_TOOL(...)
# endif
# if !defined(TIMEMORY_CXX_GOTCHA_TOOL)
# define TIMEMORY_CXX_GOTCHA_TOOL(...)
# endif
#endif
| 32.249084
| 90
| 0.57701
|
jrmadsen
|
5bc0536983148928798ae84baf6880e890bcda6c
| 423
|
hpp
|
C++
|
include/geometry/segment.hpp
|
not522/Competitive-Programming
|
be4a7d25caf5acbb70783b12899474a56c34dedb
|
[
"Unlicense"
] | 7
|
2018-04-14T14:55:51.000Z
|
2022-01-31T10:49:49.000Z
|
include/geometry/segment.hpp
|
not522/Competitive-Programming
|
be4a7d25caf5acbb70783b12899474a56c34dedb
|
[
"Unlicense"
] | 5
|
2018-04-14T14:28:49.000Z
|
2019-05-11T02:22:10.000Z
|
include/geometry/segment.hpp
|
not522/Competitive-Programming
|
be4a7d25caf5acbb70783b12899474a56c34dedb
|
[
"Unlicense"
] | null | null | null |
#pragma once
#include "geometry/line.hpp"
class Segment : public Line, public Ordered<Segment> {
public:
Segment() {}
Segment(const Point &a, const Point &b) : Line(a, b) {}
Segment(Input &in) : Line(in) {}
bool operator<(const Segment &segment) const {
return a == segment.a ? b < segment.b : a < segment.a;
}
Real area() const {
return (this->a.x * this->b.y - this->a.y * this->b.x) / 2;
}
};
| 21.15
| 63
| 0.602837
|
not522
|
5bc0960b3dc3a2099c06255085cb44c962ad84b4
| 1,447
|
cpp
|
C++
|
ex02/Base.cpp
|
Igors78/cpp06
|
d50929edcaef218d68ab04b41d4a6693032f83bb
|
[
"Unlicense"
] | 1
|
2021-11-28T14:16:09.000Z
|
2021-11-28T14:16:09.000Z
|
ex02/Base.cpp
|
Igors78/cpp06
|
d50929edcaef218d68ab04b41d4a6693032f83bb
|
[
"Unlicense"
] | null | null | null |
ex02/Base.cpp
|
Igors78/cpp06
|
d50929edcaef218d68ab04b41d4a6693032f83bb
|
[
"Unlicense"
] | null | null | null |
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Base.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ioleinik <ioleinik@student.42wolfsburg.de> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/28 15:47:22 by ioleinik #+# #+# */
/* Updated: 2021/11/28 15:47:43 by ioleinik ### ########.fr */
/* */
/* ************************************************************************** */
#include "Base.hpp"
/*
** ------------------------------- CONSTRUCTOR --------------------------------
*/
/*
** -------------------------------- DESTRUCTOR --------------------------------
*/
Base::~Base()
{
}
/*
** --------------------------------- OVERLOAD ---------------------------------
*/
/*
** --------------------------------- METHODS ----------------------------------
*/
/*
** --------------------------------- ACCESSOR ---------------------------------
*/
/* ************************************************************************** */
| 37.102564
| 80
| 0.12094
|
Igors78
|
5bc41a641535e7d8eed059d8775775b59ce17c70
| 3,943
|
cpp
|
C++
|
src/xray/render/engine/sources/effect_deffer_aref.cpp
|
ixray-team/ixray-2.0
|
85c3a544175842323fc82f42efd96c66f0fc5abb
|
[
"Linux-OpenIB"
] | 3
|
2021-10-30T09:36:14.000Z
|
2022-03-26T17:00:06.000Z
|
src/xray/render/engine/sources/effect_deffer_aref.cpp
|
acidicMercury8/ixray-2.0
|
85c3a544175842323fc82f42efd96c66f0fc5abb
|
[
"Linux-OpenIB"
] | null | null | null |
src/xray/render/engine/sources/effect_deffer_aref.cpp
|
acidicMercury8/ixray-2.0
|
85c3a544175842323fc82f42efd96c66f0fc5abb
|
[
"Linux-OpenIB"
] | 1
|
2022-03-26T17:00:08.000Z
|
2022-03-26T17:00:08.000Z
|
////////////////////////////////////////////////////////////////////////////
// Created : 20.02.2009
// Author : Mykhailo Parfeniuk
// Copyright ( C) GSC Game World - 2009
////////////////////////////////////////////////////////////////////////////
#include "pch.h"
#include <xray/render/engine/effect_deffer_aref.h>
#include <xray/render/core/effect_compiler.h>
namespace xray {
namespace render_dx10 {
effect_deffer_aref::effect_deffer_aref( bool is_lmapped):
effect_deffer_base( false, false, false)
{
m_blend = FALSE;
m_desc.m_version = 1;
m_is_lmapped = is_lmapped;
}
void effect_deffer_aref::compile_blended( effect_compiler& compiler, const effect_compilation_options& options)
{
shader_defines_list defines;
make_defines( defines);
if ( m_is_lmapped)
{
compiler.begin_pass( "lmapE", "lmapE", defines)
//.set_depth( TRUE)
.set_alpha_blend ( true, D3D_BLEND_SRC_ALPHA, D3D_BLEND_INV_SRC_ALPHA)
.bind_constant ( "alpha_ref", &m_aref_val)
.set_texture ( "t_base", options.tex_list[0])
.def_sampler ( "s_lmap")
.set_texture ( "t_lmap", options.tex_list[1])
.def_sampler ( "s_hemi", D3D_TEXTURE_ADDRESS_CLAMP, D3D_FILTER_MIN_MAG_LINEAR_MIP_POINT)
.set_texture ( "t_hemi", options.tex_list[2])
.def_sampler ( "s_env", D3D_TEXTURE_ADDRESS_CLAMP)
.set_texture ( "t_env", r2_t_envs0)
.end_pass();
//C.r_Pass ( "lmapE","lmapE",TRUE,TRUE,FALSE,TRUE,D3D_BLEND_SRC_ALPHA, D3D_BLEND_INV_SRC_ALPHA, TRUE, oAREF.value);
//C.r_Sampler ( "s_base", C.L_textures[0] );
//C.r_Sampler ( "s_lmap", C.L_textures[1] );
//C.r_Sampler_clf ( "s_hemi", *C.L_textures[2]);
//C.r_Sampler ( "s_env", r2_T_envs0, false,D3DTADDRESS_CLAMP);
//C.r_End ();
}
else
{
compiler.begin_pass( "vert", "vert", defines)
.set_alpha_blend( true, D3D_BLEND_SRC_ALPHA, D3D_BLEND_INV_SRC_ALPHA)
.bind_constant ( "alpha_ref", &m_aref_val)
.set_texture ( "t_base", options.tex_list[0])
.end_pass();
//C.r_Pass ( "vert", "vert", TRUE,TRUE,FALSE,TRUE,D3D_BLEND_SRC_ALPHA, D3D_BLEND_INV_SRC_ALPHA, TRUE, oAREF.value);
//C.r_Sampler ( "s_base", C.L_textures[0] );
//C.r_End ();
}
}
void effect_deffer_aref::compile( effect_compiler& compiler, const effect_compilation_options& options)
{
if ( m_blend)
{
compiler.begin_technique( /*SE_R2_NORMAL_HQ*/);
compile_blended( compiler, options);
compiler.end_technique();
compiler.begin_technique( /*SE_R2_NORMAL_LQ*/);
compile_blended( compiler, options);
compiler.end_technique();
}
else
{
shader_defines_list defines;
make_defines( defines);
//C.SetParams ( 1,false); //.
// codepath is the same, only the shaders differ
// ***only pixel shaders differ***
compiler.begin_technique( /*SE_R2_NORMAL_HQ*/);
uber_deffer( compiler, "base", "base", true, true, options);
compiler.end_technique();
compiler.begin_technique( /*SE_R2_NORMAL_LQ*/);
uber_deffer( compiler, "base", "base", false, true, options);
compiler.end_technique();
compiler.begin_technique( /*SE_R2_SHADOW*/);
//if ( RImplementation.o.HW_smap)
// compiler.begin_pass( "shadow_direct_base_aref","shadow_direct_base_aref");
//else
compiler.begin_pass ( "shadow_direct_base_aref", "shadow_direct_base_aref", defines)
.set_depth ( true, true)
.set_alpha_blend( FALSE)
.bind_constant ( "alpha_ref", &m_aref_val220)
.set_texture ( "t_base", options.tex_list[0])
.end_pass()
.end_technique();
}
}
void effect_deffer_aref::load( memory::reader& mem_reader)
{
effect::load( mem_reader);
if ( 1==m_desc.m_version)
{
xrP_Integer aref_val;
xrPREAD_PROP( mem_reader, xrPID_INTEGER, aref_val);
//m_aref_val = aref_val.value;
xrP_BOOL blend;
xrPREAD_PROP( mem_reader, xrPID_BOOL, blend);
m_blend = blend.value != 0;
}
}
} // namespace render
} // namespace xray
| 32.319672
| 120
| 0.660918
|
ixray-team
|
5bc45115070be632ff4387809bd1a9b96c905e7b
| 1,281
|
hpp
|
C++
|
src/third.hpp
|
hobby-dev/sirius
|
8bfdef75f225ba50bde16b3f75c8b6ac09cebb86
|
[
"MIT"
] | null | null | null |
src/third.hpp
|
hobby-dev/sirius
|
8bfdef75f225ba50bde16b3f75c8b6ac09cebb86
|
[
"MIT"
] | null | null | null |
src/third.hpp
|
hobby-dev/sirius
|
8bfdef75f225ba50bde16b3f75c8b6ac09cebb86
|
[
"MIT"
] | null | null | null |
#pragma once
#include <string>
#include <vector>
namespace sirius {
// Problem 3:
// Implement Serialize and Deserialize methods of List class. Serialize into binary
// file. Note: all relationships between elements of the list must be preserved.
// Definitions of struct ListNode and class List are provided:
//struct ListNode {
// ListNode *prev;
// ListNode *next;
// ListNode *rand; // points to a random element of the list or is NULL
// std::string data;
//};
//
//class List {
//
// public:
// void Serialize(FILE *file);
// void Deserialize(FILE *file);
//
// private:
// ListNode *head;
// ListNode *tail;
// int count;
//};
struct ListNode {
ListNode *prev{nullptr};
ListNode *next{nullptr};
ListNode *rand{nullptr}; // points to a random element of the list or is NULL
std::string data{};
};
class List {
public:
~List();
void PushBack(std::string &&value);
ListNode *accessNode(uint64_t index);
uint64_t Size() { return count; }
/**
* @param file must be opened with fopen(path, "wb"))
*/
void Serialize(FILE *file);
/**
* @param file must be opened with fopen(path, "rb"))
*/
void Deserialize(FILE *file);
private:
void cleanup();
ListNode *head{nullptr};
ListNode *tail{nullptr};
uint64_t count{0};
};
}
| 20.66129
| 83
| 0.662763
|
hobby-dev
|
5bc5e1a9b900718c300882d1eed2067f504bb910
| 4,287
|
cpp
|
C++
|
vehicle/OVMS.V3/components/can/src/candump_crtd.cpp
|
goev/Open-Vehicle-Monitoring-System-3
|
f2efd1898ec1df19eb730c1eda9a1999a00b36b4
|
[
"MIT"
] | null | null | null |
vehicle/OVMS.V3/components/can/src/candump_crtd.cpp
|
goev/Open-Vehicle-Monitoring-System-3
|
f2efd1898ec1df19eb730c1eda9a1999a00b36b4
|
[
"MIT"
] | null | null | null |
vehicle/OVMS.V3/components/can/src/candump_crtd.cpp
|
goev/Open-Vehicle-Monitoring-System-3
|
f2efd1898ec1df19eb730c1eda9a1999a00b36b4
|
[
"MIT"
] | null | null | null |
/*
; Project: Open Vehicle Monitor System
; Module: CAN dump framework
; Date: 18th January 2018
;
; (C) 2018 Mark Webb-Johnson
;
; Permission is hereby granted, free of charge, to any person obtaining a copy
; of this software and associated documentation files (the "Software"), to deal
; in the Software without restriction, including without limitation the rights
; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
; copies of the Software, and to permit persons to whom the Software is
; furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in
; all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
; THE SOFTWARE.
*/
#include "ovms_log.h"
//static const char *TAG = "candump-crtd";
#include <errno.h>
#include "pcp.h"
#include "candump_crtd.h"
candump_crtd::candump_crtd()
{
m_bufpos = 0;
}
candump_crtd::~candump_crtd()
{
}
const char* candump_crtd::formatname()
{
return "crtd";
}
std::string candump_crtd::get(struct timeval *time, CAN_frame_t *frame)
{
m_bufpos = 0;
char busnumber[2]; busnumber[0]=0; busnumber[1]=0;
if (frame->origin)
{
const char* name = frame->origin->GetName();
if (*name != 0)
{
while (name[1] != 0) name++;
busnumber[0] = *name;
}
}
sprintf(m_buf,"%ld.%06ld %sR%s %0*X",
time->tv_sec, time->tv_usec,
busnumber,
(frame->FIR.B.FF == CAN_frame_std) ? "11":"29",
(frame->FIR.B.FF == CAN_frame_std) ? 3 : 8,
frame->MsgID);
for (int k=0; k<frame->FIR.B.DLC; k++)
sprintf(m_buf+strlen(m_buf)," %02x", frame->data.u8[k]);
strcat(m_buf,"\n");
return std::string(m_buf);
}
std::string candump_crtd::getheader(struct timeval *time)
{
m_bufpos = 0;
sprintf(m_buf,"%ld.%06ld CXX OVMS\n",
time->tv_sec, time->tv_usec);
return std::string(m_buf);
}
size_t candump_crtd::put(CAN_frame_t *frame, uint8_t *buffer, size_t len)
{
size_t k;
char *b = (char*)buffer;
memset(frame,0,sizeof(CAN_frame_t));
for (k=0;k<len;k++)
{
if ((b[k]=='\r')||(b[k]=='\n'))
{
//ESP_EARLY_LOGI(TAG,"CRTD GOT CR/LF %02x",b[k]);
if (m_bufpos == 0)
continue;
else
break;
}
m_buf[m_bufpos] = b[k];
if (m_bufpos < CANDUMP_CRTD_MAXLEN) m_bufpos++;
}
//ESP_EARLY_LOGI(TAG,"CRTD PUT bufpos=%d inlen=%d now=%d",m_bufpos,len,k);
if (k>=len) return len;
// OK. We have a buffer ready for decoding...
// buffer[Start .. k-1]
m_buf[m_bufpos] = 0;
//ESP_EARLY_LOGI(TAG,"CRTD message buffer is %d bytes",m_bufpos);
m_bufpos = 0; // Prepare for next message
b = m_buf;
// We look for something like
// 1524311386.811100 1R11 100 01 02 03
if (!isdigit(b[0])) return k+1;
for (;((*b != 0)&&(*b != ' '));b++) {}
if (*b == 0) return k+1;
b++;
char bus = '1';
if (isdigit(*b))
{
bus = *b;
b++;
}
if ((b[0]=='R')&&(b[1]=='1')&&(b[2]=='1'))
{
// R11 incoming CAN frame
frame->FIR.B.FF = CAN_frame_std;
}
else if ((b[0]=='R')&&(b[1]=='2')&&(b[2]=='9'))
{
// R29 incoming CAN frame
frame->FIR.B.FF = CAN_frame_ext;
}
else
return k+1;
if (b[3] != ' ') return k+1;
b += 4;
char *p;
errno = 0;
frame->MsgID = (uint32_t)strtol(b,&p,16);
if ((frame->MsgID == 0)&&(errno != 0)) return k+1;
b = p;
for (int k=0;k<8;k++)
{
if (*b==0) break;
b++;
errno = 0;
long d = strtol(b,&p,16);
if ((d==0)&&(errno != 0)) break;
frame->data.u8[k] = (uint8_t)d;
frame->FIR.B.DLC++;
b = p;
}
char cbus[5] = "can";
cbus[3] = bus;
cbus[4] = 0;
frame->origin = (canbus*)MyPcpApp.FindDeviceByName(cbus);
//ESP_EARLY_LOGI(TAG,"CRTD done return=%d",k+1);
return k+1;
}
| 24.924419
| 79
| 0.605318
|
goev
|
5bcacfe1a4fe9b010dae211b326b9cca39bbf3d2
| 10,990
|
cpp
|
C++
|
src/demeter-win/vs/simple/work.cpp
|
pcdeadeasy/NetworkDirect
|
4c2ee56604c3493f87313dbb7bc8b1630dceaf39
|
[
"MIT"
] | 1
|
2019-06-18T23:31:10.000Z
|
2019-06-18T23:31:10.000Z
|
src/demeter-win/vs/simple/work.cpp
|
pcdeadeasy/NetworkDirect
|
4c2ee56604c3493f87313dbb7bc8b1630dceaf39
|
[
"MIT"
] | null | null | null |
src/demeter-win/vs/simple/work.cpp
|
pcdeadeasy/NetworkDirect
|
4c2ee56604c3493f87313dbb7bc8b1630dceaf39
|
[
"MIT"
] | 1
|
2019-06-18T21:43:29.000Z
|
2019-06-18T21:43:29.000Z
|
#include <libraries/logger/Logger.h>
#include <libraries/Winshim/Winshim.h>
#include <libraries/ndutil/ndutil.h>
#include <libraries/ndutil/ndtestutil.h>
#include "params.h"
#include "ndscope.h"
#include "errors.h"
#include "work.h"
static void stage8(
params_t* const params,
work_t work,
const struct sockaddr* pAddress,
IND2Adapter* const pAdapter,
HANDLE const hOverlappedFile,
IND2MemoryRegion* const pMemoryRegion,
ND2_ADAPTER_INFO const* const pInfo,
IND2CompletionQueue* const pSendCompletionQueue,
IND2CompletionQueue* const pRecvCompletionQueue,
IND2QueuePair* const pQueuePair
)
{
LOG_ENTER();
IND2Connector* pConnector = 0;
HRESULT hr =
pAdapter->CreateConnector(IID_IND2Connector, hOverlappedFile, (void**)&pConnector);
LOG("IND2Adapter::CreateConnector -> %08X", hr);
if (ND_SUCCESS != hr)
throw EX_CREATE_CONNECTOR;
try
{
(*work)(
params,
pAddress,
pAdapter,
hOverlappedFile,
pMemoryRegion,
pInfo,
pSendCompletionQueue,
pRecvCompletionQueue,
pQueuePair,
pConnector
);
}
catch (...)
{
ULONG ul = pConnector->Release();
LOG("IND2QueuePair::Release -> %u", ul);
throw;
}
ULONG ul = pConnector->Release();
LOG("IND2Connector::Release -> %u", ul);
LOG_VOID_RETURN();
}
static void stage7(
params_t* const params,
work_t work,
const struct sockaddr* pAddress,
IND2Adapter* const pAdapter,
HANDLE const hOverlappedFile,
IND2MemoryRegion* const pMemoryRegion,
ND2_ADAPTER_INFO const* const pInfo,
IND2CompletionQueue* const pSendCompletionQueue,
IND2CompletionQueue* const pRecvCompletionQueue
)
{
LOG_ENTER();
static void* const context = (void*)"CreateQueuePair context";
ULONG const recvQueueDepth = 3;
ULONG const sendQueueDepth = 3;
ULONG const maxRecvRequestSge = 3;
ULONG const maxSendRequestSge = 3;
ULONG const inlineDataSize = pInfo->MaxInlineDataSize;
IND2QueuePair* pQueuePair = 0;
HRESULT const hr =
pAdapter->CreateQueuePair(
IID_IND2QueuePair,
pSendCompletionQueue,
pRecvCompletionQueue,
context,
recvQueueDepth,
sendQueueDepth,
maxRecvRequestSge,
maxSendRequestSge,
inlineDataSize,
(void**)&pQueuePair
);
LOG("IND2Adapter::CreateQueuePair -> %08X", hr);
if (ND_SUCCESS != hr)
throw EX_CREATE_QUEUE_PAIR;
try
{
stage8(
params,
work,
pAddress,
pAdapter,
hOverlappedFile,
pMemoryRegion,
pInfo,
pSendCompletionQueue,
pRecvCompletionQueue,
pQueuePair
);
}
catch (...)
{
ULONG ul = pQueuePair->Release();
LOG("IND2QueuePair::Release -> %u", ul);
throw;
}
ULONG ul = pQueuePair->Release();
LOG("IND2QueuePair::Release -> %u", ul);
LOG_VOID_RETURN();
}
static void stage6(
params_t* const params,
work_t work,
const struct sockaddr* pAddress,
IND2Adapter* const pAdapter,
HANDLE const hOverlappedFile,
IND2MemoryRegion* const pMemoryRegion,
ND2_ADAPTER_INFO const* const pInfo,
IND2CompletionQueue* const pSendCompletionQueue
)
{
LOG_ENTER();
IND2CompletionQueue* pRecvCompletionQueue = 0;
HRESULT hr =
pAdapter->CreateCompletionQueue(
IID_IND2CompletionQueue,
hOverlappedFile,
pInfo->MaxCompletionQueueDepth,
0,
0,
(void**)(&pRecvCompletionQueue)
);
LOG("IND2Adapter::CreateCompletionQueue -> %08X", hr);
if (ND_SUCCESS != hr)
throw EX_CREATE_COMPLETION_QUEUE;
try
{
stage7(
params,
work,
pAddress,
pAdapter,
hOverlappedFile,
pMemoryRegion,
pInfo,
pSendCompletionQueue,
pRecvCompletionQueue
);
}
catch (...)
{
ULONG ul = pRecvCompletionQueue->Release();
LOG("IND2CompletionQueue::Release -> %u", ul);
throw;
}
ULONG ul = pRecvCompletionQueue->Release();
LOG("IND2CompletionQueue::Release -> %u", ul);
LOG_VOID_RETURN();
}
static void stage5(
params_t* const params,
work_t work,
const struct sockaddr* pAddress,
IND2Adapter* const pAdapter,
HANDLE const hOverlappedFile,
IND2MemoryRegion* const pMemoryRegion,
ND2_ADAPTER_INFO const* const pInfo
)
{
LOG_ENTER();
IND2CompletionQueue* pSendCompletionQueue = 0;
HRESULT hr =
pAdapter->CreateCompletionQueue(
IID_IND2CompletionQueue,
hOverlappedFile,
pInfo->MaxCompletionQueueDepth,
0,
0,
(void**)(&pSendCompletionQueue)
);
LOG("IND2Adapter::CreateCompletionQueue -> %08X", hr);
if (ND_SUCCESS != hr)
throw EX_CREATE_COMPLETION_QUEUE;
try
{
stage6(
params,
work,
pAddress,
pAdapter,
hOverlappedFile,
pMemoryRegion,
pInfo,
pSendCompletionQueue
);
}
catch (...)
{
ULONG ul = pSendCompletionQueue->Release();
LOG("IND2CompletionQueue::Release -> %u", ul);
throw;
}
ULONG ul = pSendCompletionQueue->Release();
LOG("IND2CompletionQueue::Release -> %u", ul);
LOG_VOID_RETURN();
}
static void stage4(
params_t* const params,
work_t work,
const struct sockaddr* pAddress,
IND2Adapter* const pAdapter,
HANDLE const hOverlappedFile,
IND2MemoryRegion* const pMemoryRegion
)
{
LOG_ENTER();
LOG("pMemoryRegion: %p", pMemoryRegion);
ND2_ADAPTER_INFO info = { 0 };
info.InfoVersion = ND_VERSION_2;
ULONG cbInfo = sizeof(info);
HRESULT hr =
pAdapter->Query(
&info,
&cbInfo
);
LOG("IND2Adapter::Query -> %08X", hr);
if (ND_SUCCESS != hr)
throw EX_QUERY;
stage5(
params,
work,
pAddress,
pAdapter,
hOverlappedFile,
pMemoryRegion,
&info
);
LOG_VOID_RETURN();
}
static void stage3(
params_t* const params,
work_t work,
const struct sockaddr* pAddress,
IND2Adapter* const pAdapter,
HANDLE const hOverlappedFile
)
{
LOG_ENTER();
IND2MemoryRegion* pMemoryRegion = 0;
HRESULT hr =
pAdapter->CreateMemoryRegion(
IID_IND2MemoryRegion,
hOverlappedFile,
(void**)&pMemoryRegion
);
LOG("IND2Adapter::CreateMemoryRegion -> %08X", hr);
if (hr != ND_SUCCESS)
throw EX_CREATE_MEMORY_REGION;
try
{
stage4(
params,
work,
pAddress,
pAdapter,
hOverlappedFile,
pMemoryRegion
);
}
catch (...)
{
ULONG ul = pMemoryRegion->Release();
LOG("IND2MemoryRegion::Release -> %u", ul);
throw;
}
ULONG ul = pMemoryRegion->Release();
LOG("IND2MemoryRegion::Release -> %u", ul);
LOG_VOID_RETURN();
}
static void stage2(
params_t* const params,
work_t work,
const struct sockaddr* pAddress,
IND2Adapter* const pAdapter
)
{
LOG_ENTER();
HANDLE hOverlappedFile = 0;
HRESULT hr =
pAdapter->CreateOverlappedFile(
&hOverlappedFile
);
LOG("IND2Adapter::CreateOverlappedFile -> %08X", hr);
if (hr != ND_SUCCESS)
throw EX_CREATE_OVERLAPPED_FILE;
try
{
stage3(params, work, pAddress, pAdapter, hOverlappedFile);
}
catch (...)
{
BOOL b = CloseHandle(hOverlappedFile);
LOG("CloseHandle -> %d", b);
throw;
}
BOOL b = CloseHandle(hOverlappedFile);
LOG("CloseHandle -> %d", b);
LOG_VOID_RETURN();
}
void work(
params_t* const params,
work_t work,
get_local_address_t get_local_address
)
{
LOG_ENTER();
struct sockaddr LocalAddress = (*get_local_address)(
(LPSTR)params->ip.c_str(),
params->port
);
IND2Adapter* pAdapter = 0;
HRESULT const hr =
NdOpenAdapter(
IID_IND2Adapter,
&LocalAddress,
sizeof(LocalAddress),
(void**)&pAdapter
);
if (ND_SUCCESS != hr)
throw EX_OPEN_ADAPTER;
try
{
stage2(params, work, &LocalAddress, pAdapter);
}
catch (...)
{
ULONG const ul = pAdapter->Release();
LOG("IND2Adapter::Release -> %u", ul);
throw;
}
ULONG const ul = pAdapter->Release();
LOG("IND2Adapter::Release -> %u", ul);
LOG_VOID_RETURN();
}
SOCKADDR get_sockaddr(LPSTR AddressString, INT AddressFamily, uint16_t port)
{
LOG_ENTER();
SOCKADDR saddr;
INT AddressLength = (int)sizeof(saddr);
// raises an exception on failure therefore no need to look at the return code
Win::WSAStringToAddressA(
AddressString,
AddressFamily,
0, // lpProtocolInfo
&saddr, // lpAddress
&AddressLength // lpAddressLength
);
((struct sockaddr_in*)&saddr)->sin_port = htons(port);
LOG_STRUCT_RETURN(SOCKADDR);
return saddr;
}
void RegisterMemory(IND2MemoryRegion* pMemoryRegion, void* buffer, size_t size)
{
LOG_ENTER();
OVERLAPPED ov = { 0 };
ULONG const flags =
ND_MR_FLAG_ALLOW_LOCAL_WRITE |
ND_MR_FLAG_ALLOW_REMOTE_READ |
ND_MR_FLAG_ALLOW_REMOTE_WRITE;
HRESULT hr =
pMemoryRegion->Register(
buffer,
size,
flags,
&ov
);
LOG("IND2MemoryRegion::Register -> %08X", hr);
if (ND_SUCCESS != hr)
{
if (ND_PENDING != hr)
throw EX_REGISTER;
uint64_t count = 1;
while (ND_PENDING == (hr = pMemoryRegion->GetOverlappedResult(&ov, FALSE)))
{
count += 1;
}
LOG("IND2MemoryRegion::GetOverlappedResult -> %08X (called %zu times)", hr, count);
if (ND_SUCCESS != hr)
throw EX_REGISTER_OV;
}
LOG_VOID_RETURN();
}
void DeregisterMemory(IND2MemoryRegion* pMemoryRegion)
{
// do not throw an exception!
LOG_ENTER();
OVERLAPPED ov = { 0 };
HRESULT hr = pMemoryRegion->Deregister(&ov);
LOG("IND2MemoryRegion::Deregister -> %08X", hr);
if (ND_PENDING == hr)
{
uint64_t count = 1;
while (ND_PENDING == (hr = pMemoryRegion->GetOverlappedResult(&ov, FALSE)))
{
count += 1;
}
LOG("IND2MemoryRegion::GetOverlappedResult -> %08X (called %zu times)", hr, count);
}
LOG_VOID_RETURN();
}
| 25.322581
| 91
| 0.582803
|
pcdeadeasy
|
5bd03752bc7988a0f3f32e56f8b1a251641428e5
| 5,548
|
cpp
|
C++
|
tests/job_tests.cpp
|
jacobmcleman/JobBot
|
1ef82a2f2fbf3321ba3ef4f2a006128bed1388c0
|
[
"MIT"
] | null | null | null |
tests/job_tests.cpp
|
jacobmcleman/JobBot
|
1ef82a2f2fbf3321ba3ef4f2a006128bed1388c0
|
[
"MIT"
] | null | null | null |
tests/job_tests.cpp
|
jacobmcleman/JobBot
|
1ef82a2f2fbf3321ba3ef4f2a006128bed1388c0
|
[
"MIT"
] | null | null | null |
/**************************************************************************
Some short tests to test basic job functionality
Author:
Jake McLeman
***************************************************************************/
#include <gtest/gtest.h>
#include "Job.h"
#define UNUSED(thing) (void)thing
using namespace JobBot;
bool testFunc1HasRun;
void TestJobFunc1(Job* job)
{
UNUSED(job);
testFunc1HasRun = true;
}
TinyJobFunction TestJob1(TestJobFunc1);
bool testFunc2HasRun;
void TestJobFunc2(Job* job)
{
UNUSED(job);
testFunc2HasRun = true;
}
HugeJobFunction TestJob2(TestJobFunc2);
bool testFunc3GotData;
void TestJobFunc3(Job* job) { testFunc3GotData = (job->GetData<int>() == 4); }
IOJobFunction TestJob3(TestJobFunc3);
bool testFunc4GotData;
void TestJobFunc4(Job* job)
{
testFunc4GotData = (job->GetData<float>() == 25.12f);
}
GraphicsJobFunction TestJob4(TestJobFunc4);
TEST(JobTests, SizeVerification)
{
ASSERT_EQ((size_t)Job::TARGET_JOB_SIZE, sizeof(Job))
<< "Job was incorrect size";
}
TEST(JobTests, Create)
{
Job* job = Job::Create(TestJob1);
EXPECT_FALSE(job->IsFinished()) << "Job has not been created correctly";
EXPECT_FALSE(job->InProgress()) << "Job has not been created correctly";
}
TEST(JobTests, RunJob)
{
testFunc1HasRun = false;
Job* job = Job::Create(TestJob1);
EXPECT_FALSE(testFunc1HasRun) << "Job has been prematurely executed";
EXPECT_FALSE(job->IsFinished())
<< "Job is marked as finished before it has run";
job->Run();
EXPECT_TRUE(testFunc1HasRun)
<< "Job has been run but has not executed job code";
EXPECT_TRUE(job->IsFinished())
<< "Job has been run but is not marked as finished";
EXPECT_FALSE(job->InProgress())
<< "Job is finished but still marked as in progress";
}
TEST(JobTests, Parent)
{
testFunc1HasRun = false;
testFunc2HasRun = false;
// Create 2 jobs with job2 as a child of job1
Job* job1 = Job::Create(TestJob1);
Job* job2 = Job::CreateChild(TestJob2, job1);
// Make sure that nothing has prematurely fired
EXPECT_FALSE(testFunc1HasRun) << "Job1 has been prematurely executed";
EXPECT_FALSE(job1->IsFinished())
<< "Job1 is marked as finished before it has run";
EXPECT_FALSE(testFunc2HasRun) << "Job2 has been prematurely executed";
EXPECT_FALSE(job2->IsFinished())
<< "Job2 is marked as finished before it has run";
// Run job1 (the parent)
job1->Run();
// Job 1 has now run, but should not be marked done because it has a child
// that has not finished
EXPECT_TRUE(testFunc1HasRun) << "Job1 has not run correctly";
EXPECT_FALSE(job1->IsFinished())
<< "Job1 is marked as finished before all of its children have finished";
EXPECT_FALSE(testFunc2HasRun) << "Job2 has been prematurely executed";
EXPECT_FALSE(job2->IsFinished())
<< "Job2 is marked as finished before it has run";
// Run job2 (the child)
job2->Run();
// Make sure all jobs are now correctly marked as completed
EXPECT_TRUE(testFunc1HasRun) << "Job1 has not run correctly";
EXPECT_TRUE(job1->IsFinished())
<< "Job1 is not marked as finished even though all child jobs are done";
EXPECT_TRUE(testFunc2HasRun) << "Job2 has not run correctly";
EXPECT_TRUE(job2->IsFinished())
<< "Job2 has been run but is not marked as finished";
}
TEST(JobTests, Callback)
{
testFunc1HasRun = false;
testFunc2HasRun = false;
// Create job1 with a callback function
Job* job = Job::Create(TestJob1);
job->SetCallback(TestJob2);
EXPECT_FALSE(testFunc1HasRun) << "Job has been prematurely executed";
EXPECT_FALSE(job->IsFinished())
<< "Job is marked as finished before it has run";
EXPECT_FALSE(testFunc2HasRun) << "Callback has been prematurely executed";
job->Run();
EXPECT_TRUE(testFunc1HasRun)
<< "Job has been run but has not executed job code";
EXPECT_TRUE(job->IsFinished())
<< "Job has been run but is not marked as finished";
EXPECT_TRUE(testFunc2HasRun)
<< "Job has been run but has not executed callback code";
}
TEST(JobTests, Data1)
{
testFunc3GotData = false;
Job* job = Job::Create(TestJob3, 4);
EXPECT_FALSE(testFunc3GotData)
<< "Function somehow already got the data even though it hasn't run yet";
EXPECT_FALSE(job->IsFinished())
<< "Job is marked as finished before it has run";
job->Run();
EXPECT_TRUE(testFunc3GotData)
<< "Function did not correctly recieve the data";
EXPECT_TRUE(job->IsFinished()) << "Job is not marked as finished";
}
TEST(JobTests, Data2)
{
testFunc4GotData = false;
Job* job = Job::Create(TestJob4, 25.12f);
EXPECT_FALSE(testFunc4GotData)
<< "Function somehow already got the data even though it hasn't run yet";
EXPECT_FALSE(job->IsFinished())
<< "Job is marked as finished before it has run";
job->Run();
EXPECT_TRUE(testFunc4GotData) << "Function recieved wrong data";
EXPECT_TRUE(job->IsFinished()) << "Job is not marked as finished";
}
TEST(JobTests, JobTypeChecks)
{
Job* job1 = Job::Create(TestJob1);
Job* job2 = Job::Create(TestJob2);
EXPECT_FALSE(job1->MatchesType(JobType::Huge)) << "Tiny job was huge";
EXPECT_FALSE(job1->MatchesType(JobType::Misc)) << "Tiny job was misc";
EXPECT_TRUE(job1->MatchesType(JobType::Tiny))
<< "Tiny job was not a tiny job";
EXPECT_TRUE(job2->MatchesType(JobType::Huge)) << "Huge job was not huge";
EXPECT_FALSE(job2->MatchesType(JobType::Misc)) << "Huge job was misc";
EXPECT_FALSE(job2->MatchesType(JobType::Tiny)) << "Huge job was tiny";
}
| 29.354497
| 79
| 0.683129
|
jacobmcleman
|
5bd1c4c60b0a518115e14cce3ff262dcad624695
| 1,005
|
cpp
|
C++
|
examples/make_stereo_panorama.cpp
|
jonathanventura/spherical-sfm
|
0f0dafdd66641cebcb57cdb8a87b9ce466ab36eb
|
[
"MIT"
] | 6
|
2020-03-26T15:07:14.000Z
|
2022-02-04T06:27:32.000Z
|
examples/make_stereo_panorama.cpp
|
jonathanventura/spherical-sfm
|
0f0dafdd66641cebcb57cdb8a87b9ce466ab36eb
|
[
"MIT"
] | 1
|
2020-07-09T06:32:52.000Z
|
2020-07-09T07:26:47.000Z
|
examples/make_stereo_panorama.cpp
|
jonathanventura/spherical-sfm
|
0f0dafdd66641cebcb57cdb8a87b9ce466ab36eb
|
[
"MIT"
] | 1
|
2022-03-08T20:30:46.000Z
|
2022-03-08T20:30:46.000Z
|
#include <iostream>
#include <vector>
#include <cmath>
#include <fstream>
#include <gflags/gflags.h>
#include "stereo_panorama_tools.h"
using namespace sphericalsfm;
using namespace stereopanotools;
DEFINE_string(intrinsics, "", "Path to intrinsics (focal centerx centery)");
DEFINE_string(video, "", "Path to video or image search pattern like frame%06d.png");
DEFINE_string(output, "", "Path to output directory");
DEFINE_int32(width, 8192, "Width of output panorama");
DEFINE_bool(loop, true, "Trajectory is a closed loop");
int main( int argc, char **argv )
{
gflags::ParseCommandLineFlags(&argc, &argv, true);
double focal, centerx, centery;
std::ifstream intrinsicsf( FLAGS_intrinsics );
intrinsicsf >> focal >> centerx >> centery;
std::cout << "intrinsics : " << focal << ", " << centerx << ", " << centery << "\n";
Intrinsics intrinsics(focal,centerx,centery);
make_stereo_panoramas( intrinsics, FLAGS_video, FLAGS_output, FLAGS_width, FLAGS_loop );
}
| 30.454545
| 92
| 0.705473
|
jonathanventura
|
5bd4623cc9a5404f3652cce6bd2ce9c8e03da0f5
| 617
|
cpp
|
C++
|
2017/APP5/Q.7.cpp
|
HemensonDavid/Estudando-C
|
fb5a33b399b369dce789bf77c06834da71fe0a4d
|
[
"MIT"
] | null | null | null |
2017/APP5/Q.7.cpp
|
HemensonDavid/Estudando-C
|
fb5a33b399b369dce789bf77c06834da71fe0a4d
|
[
"MIT"
] | null | null | null |
2017/APP5/Q.7.cpp
|
HemensonDavid/Estudando-C
|
fb5a33b399b369dce789bf77c06834da71fe0a4d
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int ismedia(int nota1, int nota2, int nota3, int nota4){
int media=(nota1*2)+(nota2*2)+(nota3*3)+(nota4*3)/10;
if(media>=60){
return 1;
}
}
int main(){
cout<<"Digite sua nota no 1 bimestre: ";
int nota1;
cin>> nota1;
cout<<"Digite sua nota no 2 bimestre: ";
int nota2;
cin>> nota2;
cout<<"Digite sua nota no 3 bimestre: ";
int nota3;
cin>> nota3;
cout<<"Digite sua nota no 4 bimestre: ";
int nota4;
cin>> nota4;
if(ismedia(nota1,nota2,nota3,nota4)==1){
cout<<"Voce nao passou. "<<endl;
}else{
cout<<"voce passou :) "<<endl;
}
//hemenson
}
| 16.675676
| 56
| 0.628849
|
HemensonDavid
|
5bd6994380e19f199c9e9f98d6d356ea80f44954
| 3,721
|
hpp
|
C++
|
include/tcb_manager.hpp
|
Qanora/mstack-cpp
|
a1b6de6983404558e46b87d0e81da715fcdccd55
|
[
"MIT"
] | 15
|
2020-07-20T12:32:38.000Z
|
2022-03-24T19:24:02.000Z
|
include/tcb_manager.hpp
|
Qanora/mstack-cpp
|
a1b6de6983404558e46b87d0e81da715fcdccd55
|
[
"MIT"
] | null | null | null |
include/tcb_manager.hpp
|
Qanora/mstack-cpp
|
a1b6de6983404558e46b87d0e81da715fcdccd55
|
[
"MIT"
] | 5
|
2020-07-20T12:42:58.000Z
|
2021-01-16T10:13:39.000Z
|
#pragma once
#include <memory>
#include <optional>
#include <unordered_map>
#include <unordered_set>
#include "circle_buffer.hpp"
#include "defination.hpp"
#include "packets.hpp"
#include "socket.hpp"
#include "tcb.hpp"
#include "tcp_transmit.hpp"
namespace mstack {
class tcb_manager {
private:
tcb_manager() : active_tcbs(std::make_shared<circle_buffer<std::shared_ptr<tcb_t>>>()) {}
~tcb_manager() = default;
std::shared_ptr<circle_buffer<std::shared_ptr<tcb_t>>> active_tcbs;
std::unordered_map<two_ends_t, std::shared_ptr<tcb_t>> tcbs;
std::unordered_set<ipv4_port_t> active_ports;
std::unordered_map<ipv4_port_t, std::shared_ptr<listener_t>> listeners;
public:
tcb_manager(const tcb_manager&) = delete;
tcb_manager(tcb_manager&&) = delete;
tcb_manager& operator=(const tcb_manager&) = delete;
tcb_manager& operator=(tcb_manager&&) = delete;
static tcb_manager& instance() {
static tcb_manager instance;
return instance;
}
public:
int id() { return 0x06; }
std::optional<tcp_packet_t> gather_packet() {
while (!active_tcbs->empty()) {
std::optional<std::shared_ptr<tcb_t>> tcb = active_tcbs->pop_front();
if (!tcb) continue;
std::optional<tcp_packet_t> tcp_packet = tcb.value()->gather_packet();
if (tcp_packet) return tcp_packet;
}
return std::nullopt;
}
void listen_port(ipv4_port_t ipv4_port, std::shared_ptr<listener_t> listener) {
this->listeners[ipv4_port] = listener;
active_ports.insert(ipv4_port);
}
void register_tcb(
two_ends_t& two_end,
std::optional<std::shared_ptr<circle_buffer<std::shared_ptr<tcb_t>>>> listener) {
DLOG(INFO) << "[REGISTER TCB] " << two_end;
if (!two_end.remote_info || !two_end.local_info) {
DLOG(FATAL) << "[EMPTY TCB]";
}
std::shared_ptr<tcb_t> tcb = std::make_shared<tcb_t>(this->active_tcbs, listener,
two_end.remote_info.value(),
two_end.local_info.value());
tcbs[two_end] = tcb;
}
void receive(tcp_packet_t in_packet) {
two_ends_t two_end = {.remote_info = in_packet.remote_info,
.local_info = in_packet.local_info};
if (tcbs.find(two_end) != tcbs.end()) {
tcp_transmit::tcp_in(tcbs[two_end], in_packet);
} else if (active_ports.find(in_packet.local_info.value()) != active_ports.end()) {
register_tcb(two_end,
this->listeners[in_packet.local_info.value()]->acceptors);
if (tcbs.find(two_end) != tcbs.end()) {
tcbs[two_end]->state = TCP_LISTEN;
tcbs[two_end]->next_state = TCP_LISTEN;
tcp_transmit::tcp_in(tcbs[two_end], in_packet);
} else {
DLOG(ERROR) << "[REGISTER TCB FAIL]";
}
} else {
DLOG(ERROR) << "[RECEIVE UNKNOWN TCP PACKET]";
}
}
};
} // namespace mstack
| 43.267442
| 99
| 0.504703
|
Qanora
|
5bdd86a3c1457620c62c505b2444d4cdcf64f68e
| 4,666
|
hpp
|
C++
|
include/System/Runtime/CompilerServices/RuntimeWrappedException.hpp
|
darknight1050/BeatSaber-Quest-Codegen
|
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
|
[
"Unlicense"
] | null | null | null |
include/System/Runtime/CompilerServices/RuntimeWrappedException.hpp
|
darknight1050/BeatSaber-Quest-Codegen
|
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
|
[
"Unlicense"
] | null | null | null |
include/System/Runtime/CompilerServices/RuntimeWrappedException.hpp
|
darknight1050/BeatSaber-Quest-Codegen
|
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
|
[
"Unlicense"
] | null | null | null |
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Exception
#include "System/Exception.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Runtime::Serialization
namespace System::Runtime::Serialization {
// Forward declaring type: SerializationInfo
class SerializationInfo;
}
// Completed forward declares
// Type namespace: System.Runtime.CompilerServices
namespace System::Runtime::CompilerServices {
// Size: 0x90
#pragma pack(push, 1)
// Autogenerated type: System.Runtime.CompilerServices.RuntimeWrappedException
class RuntimeWrappedException : public System::Exception {
public:
// private System.Object m_wrappedException
// Size: 0x8
// Offset: 0x88
::Il2CppObject* m_wrappedException;
// Field size check
static_assert(sizeof(::Il2CppObject*) == 0x8);
// Creating value type constructor for type: RuntimeWrappedException
RuntimeWrappedException(::Il2CppObject* m_wrappedException_ = {}) noexcept : m_wrappedException{m_wrappedException_} {}
// Creating conversion operator: operator ::Il2CppObject*
constexpr operator ::Il2CppObject*() const noexcept {
return m_wrappedException;
}
// private System.Void .ctor(System.Object thrownObject)
// Offset: 0x1401DE0
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static RuntimeWrappedException* New_ctor(::Il2CppObject* thrownObject) {
static auto ___internal__logger = ::Logger::get().WithContext("System::Runtime::CompilerServices::RuntimeWrappedException::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<RuntimeWrappedException*, creationType>(thrownObject)));
}
// public override System.Void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
// Offset: 0x1401E90
// Implemented from: System.Exception
// Base method: System.Void Exception::GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
void GetObjectData(System::Runtime::Serialization::SerializationInfo* info, System::Runtime::Serialization::StreamingContext context);
// System.Void .ctor(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
// Offset: 0x1401F9C
// Implemented from: System.Exception
// Base method: System.Void Exception::.ctor(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static RuntimeWrappedException* New_ctor(System::Runtime::Serialization::SerializationInfo* info, System::Runtime::Serialization::StreamingContext context) {
static auto ___internal__logger = ::Logger::get().WithContext("System::Runtime::CompilerServices::RuntimeWrappedException::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<RuntimeWrappedException*, creationType>(info, context)));
}
// System.Void .ctor()
// Offset: 0x1402090
// Implemented from: System.Exception
// Base method: System.Void Exception::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static RuntimeWrappedException* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("System::Runtime::CompilerServices::RuntimeWrappedException::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<RuntimeWrappedException*, creationType>()));
}
}; // System.Runtime.CompilerServices.RuntimeWrappedException
#pragma pack(pop)
static check_size<sizeof(RuntimeWrappedException), 136 + sizeof(::Il2CppObject*)> __System_Runtime_CompilerServices_RuntimeWrappedExceptionSizeCheck;
static_assert(sizeof(RuntimeWrappedException) == 0x90);
}
DEFINE_IL2CPP_ARG_TYPE(System::Runtime::CompilerServices::RuntimeWrappedException*, "System.Runtime.CompilerServices", "RuntimeWrappedException");
| 60.597403
| 165
| 0.747964
|
darknight1050
|
5be09ff0afe0e481f52fc2c48e30d71f5aa1fbc0
| 1,185
|
cpp
|
C++
|
testMain.cpp
|
chuanstudyup/GPSM8N
|
e0f6bc6fa5484605557c38a4ec5fcfb6c1dd53c9
|
[
"Apache-2.0"
] | 1
|
2022-03-28T13:57:20.000Z
|
2022-03-28T13:57:20.000Z
|
testMain.cpp
|
chuanstudyup/GPSM8N
|
e0f6bc6fa5484605557c38a4ec5fcfb6c1dd53c9
|
[
"Apache-2.0"
] | null | null | null |
testMain.cpp
|
chuanstudyup/GPSM8N
|
e0f6bc6fa5484605557c38a4ec5fcfb6c1dd53c9
|
[
"Apache-2.0"
] | null | null | null |
// testMain.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
// g++ GPS.cpp testMain.cpp -o testMain
/* NMEA examples
$GNRMC,083712.40,A,3030.83159,N,11424.56558,E,0.150,,291221,,,A*65\r\n
$GNRMC,083712.60,A,3030.83159,N,11424.56559,E,0.157,,291221,,,A*61\r\n
$GNRMC,083712.80,A,3030.83158,N,11424.56558,E,0.033,,291221,,,A*6C\r\n
$GNGGA,083712.80,3030.83158,N,11424.56558,E,1,10,1.00,49.7,M,-10.6,M,,*5B\r\n
*/
#include <iostream>
#include <math.h>
#include "GPS.h"
using std::cout;
using std::endl;
int main()
{
char buf0[200] = "$GNRMC,083708.20,A,3030.";
char buf1[200] = "83171,N,11424.56579,E,0.094,,291221,,,A*68\r\n$GNGGA,0";
char buf2[200] = "83712.80,3030.83158,N,11424.56558,E,1";
char buf3[200] = ",10,1.00,49.7,M,-10.6,M,,*5B\r\n";
GPS gps;
gps.parseNAME(buf0);
gps.parseNAME(buf1);
gps.parseNAME(buf2);
gps.parseNAME(buf3);
cout <<"Lat:"<< gps.lat << endl;
cout <<"Lng:"<< gps.lon << endl;
cout <<"Velocity:"<< gps.velocity << endl;
cout <<"Course:"<< gps.course << endl;
cout << "SVs:" << static_cast<int>(gps.SVs) << endl;
cout << "Altitude:" << gps.altitude << endl;
cout << "HDOP:" << gps.HDOP << endl;
return 0;
}
| 29.625
| 78
| 0.61519
|
chuanstudyup
|
5be0ae2694bfc8d46a7a0329e74bc69410ee79cc
| 1,156
|
cpp
|
C++
|
android-31/android/icu/util/ULocale_Category.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 12
|
2020-03-26T02:38:56.000Z
|
2022-03-14T08:17:26.000Z
|
android-28/android/icu/util/ULocale_Category.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 1
|
2021-01-27T06:07:45.000Z
|
2021-11-13T19:19:43.000Z
|
android-30/android/icu/util/ULocale_Category.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 3
|
2021-02-02T12:34:55.000Z
|
2022-03-08T07:45:57.000Z
|
#include "../../../JArray.hpp"
#include "../../../JString.hpp"
#include "./ULocale_Category.hpp"
namespace android::icu::util
{
// Fields
android::icu::util::ULocale_Category ULocale_Category::DISPLAY()
{
return getStaticObjectField(
"android.icu.util.ULocale$Category",
"DISPLAY",
"Landroid/icu/util/ULocale$Category;"
);
}
android::icu::util::ULocale_Category ULocale_Category::FORMAT()
{
return getStaticObjectField(
"android.icu.util.ULocale$Category",
"FORMAT",
"Landroid/icu/util/ULocale$Category;"
);
}
// QJniObject forward
ULocale_Category::ULocale_Category(QJniObject obj) : java::lang::Enum(obj) {}
// Constructors
// Methods
android::icu::util::ULocale_Category ULocale_Category::valueOf(JString arg0)
{
return callStaticObjectMethod(
"android.icu.util.ULocale$Category",
"valueOf",
"(Ljava/lang/String;)Landroid/icu/util/ULocale$Category;",
arg0.object<jstring>()
);
}
JArray ULocale_Category::values()
{
return callStaticObjectMethod(
"android.icu.util.ULocale$Category",
"values",
"()[Landroid/icu/util/ULocale$Category;"
);
}
} // namespace android::icu::util
| 23.12
| 78
| 0.697232
|
YJBeetle
|
5be4b1c6a414d33b6af76f4904a7e05f7c281c00
| 56
|
hpp
|
C++
|
src/boost_mpl_aux__preprocessed_bcc551_bitor.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 10
|
2018-03-17T00:58:42.000Z
|
2021-07-06T02:48:49.000Z
|
src/boost_mpl_aux__preprocessed_bcc551_bitor.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 2
|
2021-03-26T15:17:35.000Z
|
2021-05-20T23:55:08.000Z
|
src/boost_mpl_aux__preprocessed_bcc551_bitor.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 4
|
2019-05-28T21:06:37.000Z
|
2021-07-06T03:06:52.000Z
|
#include <boost/mpl/aux_/preprocessed/bcc551/bitor.hpp>
| 28
| 55
| 0.803571
|
miathedev
|
5be9cdbd51e0b4addd5637585abfd4f1db2ec933
| 769
|
cpp
|
C++
|
12-10-21/balanced_binary_tree.cpp
|
ahanavish/GDSC-DSA-Interview-Preparation
|
d6cfa402dbbe8ed4f5b96f51e2e0fc0e2eabbdaf
|
[
"MIT"
] | null | null | null |
12-10-21/balanced_binary_tree.cpp
|
ahanavish/GDSC-DSA-Interview-Preparation
|
d6cfa402dbbe8ed4f5b96f51e2e0fc0e2eabbdaf
|
[
"MIT"
] | null | null | null |
12-10-21/balanced_binary_tree.cpp
|
ahanavish/GDSC-DSA-Interview-Preparation
|
d6cfa402dbbe8ed4f5b96f51e2e0fc0e2eabbdaf
|
[
"MIT"
] | 1
|
2021-11-29T06:10:48.000Z
|
2021-11-29T06:10:48.000Z
|
// https://leetcode.com/problems/balanced-binary-tree/
class Solution
{
public:
bool isBalanced(TreeNode *root)
{
vector<int> ans;
int h = is(root, ans);
if (check(ans))
return true;
else
return false;
}
bool check(vector<int> &ans)
{
for (int i = 0; i < ans.size(); i++)
{
if (ans[i] - ans[i + 1] > 1 || ans[i + 1] - ans[i] > 1)
return false;
i++;
}
return true;
}
int is(TreeNode *node, vector<int> &ans)
{
if (!node)
return 0;
int l = is(node->left, ans), r = is(node->right, ans);
ans.push_back(l);
ans.push_back(r);
return max(l, r) + 1;
}
};
| 19.717949
| 67
| 0.443433
|
ahanavish
|
5beeb662e275ac7b93836be860aee060f93fdb61
| 233
|
cpp
|
C++
|
codes/moderncpp/strtol/strtol02/main.cpp
|
eric2003/ModernCMake
|
48fe5ed2f25481a7c93f86af38a692f4563afcaa
|
[
"MIT"
] | 3
|
2022-01-25T07:33:43.000Z
|
2022-03-30T10:25:09.000Z
|
codes/moderncpp/strtol/strtol02/main.cpp
|
eric2003/ModernCMake
|
48fe5ed2f25481a7c93f86af38a692f4563afcaa
|
[
"MIT"
] | null | null | null |
codes/moderncpp/strtol/strtol02/main.cpp
|
eric2003/ModernCMake
|
48fe5ed2f25481a7c93f86af38a692f4563afcaa
|
[
"MIT"
] | 2
|
2022-01-17T13:39:12.000Z
|
2022-03-30T10:25:12.000Z
|
#include <iostream>
int main ( int argc, char **argv )
{
{
if ( argc > 1 )
{
long i = strtol( argv[1], NULL, 0 );
std::cout << " i = " << i << std::endl;
}
}
return 0;
}
| 15.533333
| 52
| 0.377682
|
eric2003
|
5bf1be12a66207f9e5154926b9760b12e52a5f0c
| 3,920
|
cpp
|
C++
|
src/tnl/t_vb_points.cpp
|
OS2World/LIB-GRAPHICS-The_Mesa_3D_Graphics_Library
|
c0e0cfaeefa9e87e4978101fbac7d0372c39f1a3
|
[
"MIT"
] | null | null | null |
src/tnl/t_vb_points.cpp
|
OS2World/LIB-GRAPHICS-The_Mesa_3D_Graphics_Library
|
c0e0cfaeefa9e87e4978101fbac7d0372c39f1a3
|
[
"MIT"
] | null | null | null |
src/tnl/t_vb_points.cpp
|
OS2World/LIB-GRAPHICS-The_Mesa_3D_Graphics_Library
|
c0e0cfaeefa9e87e4978101fbac7d0372c39f1a3
|
[
"MIT"
] | null | null | null |
/* $Id: t_vb_points.c,v 1.10 2002/10/29 20:29:04 brianp Exp $ */
/*
* Mesa 3-D graphics library
* Version: 4.1
*
* Copyright (C) 1999-2002 Brian Paul All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Authors:
* Brian Paul
*/
#include "mtypes.h"
#include "imports.h"
#include "t_context.h"
#include "t_pipeline.h"
struct point_stage_data {
GLvector4f PointSize;
};
#define POINT_STAGE_DATA(stage) ((struct point_stage_data *)stage->privatePtr)
/*
* Compute attenuated point sizes
*/
static GLboolean run_point_stage( GLcontext *ctx,
struct gl_pipeline_stage *stage )
{
struct point_stage_data *store = POINT_STAGE_DATA(stage);
struct vertex_buffer *VB = &TNL_CONTEXT(ctx)->vb;
const GLfloat (*eye)[4] = (const GLfloat (*)[4]) VB->EyePtr->data;
const GLfloat p0 = ctx->Point.Params[0];
const GLfloat p1 = ctx->Point.Params[1];
const GLfloat p2 = ctx->Point.Params[2];
const GLfloat pointSize = ctx->Point._Size;
GLfloat (*size)[4] = store->PointSize.data;
GLuint i;
if (stage->changed_inputs) {
/* XXX do threshold and min/max clamping here? */
for (i = 0; i < VB->Count; i++) {
const GLfloat dist = -eye[i][2];
/* GLfloat dist = GL_SQRT(pos[0]*pos[0]+pos[1]*pos[1]+pos[2]*pos[2]);*/
size[i][0] = pointSize / (p0 + dist * (p1 + dist * p2));
}
}
VB->PointSizePtr = &store->PointSize;
return GL_TRUE;
}
/* If point size attenuation is on we'll compute the point size for
* each vertex in a special pipeline stage.
*/
static void check_point_size( GLcontext *ctx, struct gl_pipeline_stage *d )
{
d->active = ctx->Point._Attenuated && !ctx->VertexProgram.Enabled;
}
static GLboolean alloc_point_data( GLcontext *ctx,
struct gl_pipeline_stage *stage )
{
struct vertex_buffer *VB = &TNL_CONTEXT(ctx)->vb;
struct point_stage_data *store;
stage->privatePtr = MALLOC(sizeof(*store));
store = POINT_STAGE_DATA(stage);
if (!store)
return GL_FALSE;
_mesa_vector4f_alloc( &store->PointSize, 0, VB->Size, 32 );
/* Now run the stage.
*/
stage->run = run_point_stage;
return stage->run( ctx, stage );
}
static void free_point_data( struct gl_pipeline_stage *stage )
{
struct point_stage_data *store = POINT_STAGE_DATA(stage);
if (store) {
_mesa_vector4f_free( &store->PointSize );
FREE( store );
stage->privatePtr = 0;
}
}
const struct gl_pipeline_stage _tnl_point_attenuation_stage =
{
"point size attenuation", /* name */
_NEW_POINT, /* build_state_change */
_NEW_POINT, /* run_state_change */
GL_FALSE, /* active */
VERT_BIT_EYE, /* inputs */
VERT_BIT_POINT_SIZE, /* outputs */
0, /* changed_inputs (temporary value) */
NULL, /* stage private data */
free_point_data, /* destructor */
check_point_size, /* check */
alloc_point_data /* run -- initially set to alloc data */
};
| 31.36
| 78
| 0.688265
|
OS2World
|
5bf4a1b12bd0ba842830ce713cef0b21e2e0da15
| 799
|
cpp
|
C++
|
learncpp.com/11_Inheritance/Question03/src/Main.cpp
|
KoaLaYT/Learn-Cpp
|
0bfc98c3eca9c2fde5bff609c67d7e273fde5196
|
[
"MIT"
] | null | null | null |
learncpp.com/11_Inheritance/Question03/src/Main.cpp
|
KoaLaYT/Learn-Cpp
|
0bfc98c3eca9c2fde5bff609c67d7e273fde5196
|
[
"MIT"
] | null | null | null |
learncpp.com/11_Inheritance/Question03/src/Main.cpp
|
KoaLaYT/Learn-Cpp
|
0bfc98c3eca9c2fde5bff609c67d7e273fde5196
|
[
"MIT"
] | null | null | null |
/**
* Chapter 11 :: Question 3
*
* Fighting with a monster
* use almost everything learned by bar
*
* KoaLaYT 23:15 04/02/2020
*
*/
#include "Player.h"
#include <iostream>
#include <string>
Player initPlayer() {
std::cout << "Enter you name: ";
std::string name{};
std::getline(std::cin, name);
std::cout << "Welcome, " << name << '\n';
return Player{name};
}
int main() {
Player p{initPlayer()};
while (!(p.hasWon() || p.isDead())) {
p.fightMonster();
}
if (p.hasWon()) {
std::cout << "You won! And you have " << p.getGold() << " golds!\n";
}
if (p.isDead()) {
std::cout << "You died at level " << p.getLevel() << " and with "
<< p.getGold() << " gold.\n";
std::cout << "Too bad you can't take it with you!\n";
}
return 0;
}
| 19.02381
| 72
| 0.544431
|
KoaLaYT
|
5bf54790d03dad868eb1e1f926a2969a61ad40ca
| 12,838
|
hpp
|
C++
|
key/key.hpp
|
drypot/san-2.x
|
44e626793b1dc50826ba0f276d5cc69b7c9ca923
|
[
"MIT"
] | 5
|
2019-12-27T07:30:03.000Z
|
2020-10-13T01:08:55.000Z
|
key/key.hpp
|
drypot/san-2.x
|
44e626793b1dc50826ba0f276d5cc69b7c9ca923
|
[
"MIT"
] | null | null | null |
key/key.hpp
|
drypot/san-2.x
|
44e626793b1dc50826ba0f276d5cc69b7c9ca923
|
[
"MIT"
] | 1
|
2020-07-27T22:36:40.000Z
|
2020-07-27T22:36:40.000Z
|
/*
--------------------------------------------------------------------------------
key/key.hpp
copyright(C) kyuhyun park
1993.07.13
-------------------------------------------------------------------------------- */
#ifdef def_key_key_hpp
#error 'key/key.hpp' duplicated.
#endif
#define def_key_key_hpp
#ifndef def_pub_config_hpp
#include <pub/config.hpp>
#endif
/*
--------------------------------------------------------------------------------
shift keys
-------------------------------------------------------------------------------- */
#define def_key_rshift 0x0100
#define def_key_lshift 0x0101
#define def_key_rctrl 0x0102
#define def_key_lctrl 0x0103
#define def_key_ralt 0x0104
#define def_key_lalt 0x0105
#define def_key_rmachine 0x0106
#define def_key_lmachine 0x0107
#define def_key_num_lock 0x0108
#define def_key_caps_lock 0x0109
/*
--------------------------------------------------------------------------------
character keys
-------------------------------------------------------------------------------- */
#define def_key_a00 0x0200
#define def_key_a01 0x0201
#define def_key_a02 0x0202
#define def_key_a03 0x0203
#define def_key_a04 0x0204
#define def_key_a05 0x0205
#define def_key_a06 0x0206
#define def_key_a07 0x0207
#define def_key_a08 0x0208
#define def_key_a09 0x0209
#define def_key_a10 0x020a
#define def_key_a11 0x020b
#define def_key_a12 0x020c
#define def_key_a13 0x020d
#define def_key_a14 0x020e
#define def_key_a15 0x020f
#define def_key_b00 0x0220
#define def_key_b01 0x0221
#define def_key_b02 0x0222
#define def_key_b03 0x0223
#define def_key_b04 0x0224
#define def_key_b05 0x0225
#define def_key_b06 0x0226
#define def_key_b07 0x0227
#define def_key_b08 0x0228
#define def_key_b09 0x0229
#define def_key_b10 0x022a
#define def_key_b11 0x022b
#define def_key_b12 0x022c
#define def_key_b13 0x022d
#define def_key_b14 0x022e
#define def_key_b15 0x022f
#define def_key_c00 0x0240
#define def_key_c01 0x0241
#define def_key_c02 0x0242
#define def_key_c03 0x0243
#define def_key_c04 0x0244
#define def_key_c05 0x0245
#define def_key_c06 0x0246
#define def_key_c07 0x0247
#define def_key_c08 0x0248
#define def_key_c09 0x0249
#define def_key_c10 0x024a
#define def_key_c11 0x024b
#define def_key_c12 0x024c
#define def_key_c13 0x024d
#define def_key_c14 0x024e
#define def_key_c15 0x024f
#define def_key_d00 0x0260
#define def_key_d01 0x0261
#define def_key_d02 0x0262
#define def_key_d03 0x0263
#define def_key_d04 0x0264
#define def_key_d05 0x0265
#define def_key_d06 0x0266
#define def_key_d07 0x0267
#define def_key_d08 0x0268
#define def_key_d09 0x0269
#define def_key_d10 0x026a
#define def_key_d11 0x026b
#define def_key_d12 0x026c
#define def_key_d13 0x026d
#define def_key_d14 0x026e
#define def_key_d15 0x026f
#define def_key_qwt_q 0x0220
#define def_key_qwt_w 0x0221
#define def_key_qwt_e 0x0222
#define def_key_qwt_r 0x0223
#define def_key_qwt_t 0x0224
#define def_key_qwt_y 0x0225
#define def_key_qwt_u 0x0226
#define def_key_qwt_i 0x0227
#define def_key_qwt_o 0x0228
#define def_key_qwt_p 0x0229
#define def_key_qwt_a 0x0240
#define def_key_qwt_s 0x0241
#define def_key_qwt_d 0x0242
#define def_key_qwt_f 0x0243
#define def_key_qwt_g 0x0244
#define def_key_qwt_h 0x0245
#define def_key_qwt_j 0x0246
#define def_key_qwt_k 0x0247
#define def_key_qwt_l 0x0248
#define def_key_qwt_z 0x0260
#define def_key_qwt_x 0x0261
#define def_key_qwt_c 0x0262
#define def_key_qwt_v 0x0263
#define def_key_qwt_b 0x0264
#define def_key_qwt_n 0x0265
#define def_key_qwt_m 0x0266
/*
--------------------------------------------------------------------------------
character keys on keypad
-------------------------------------------------------------------------------- */
#define def_key_pad_0 0x0300
#define def_key_pad_1 0x0301
#define def_key_pad_2 0x0302
#define def_key_pad_3 0x0303
#define def_key_pad_4 0x0304
#define def_key_pad_5 0x0305
#define def_key_pad_6 0x0306
#define def_key_pad_7 0x0307
#define def_key_pad_8 0x0308
#define def_key_pad_9 0x0309
#define def_key_pad_slash 0x030a
#define def_key_pad_asterisk 0x030b
#define def_key_pad_minus 0x030c
#define def_key_pad_plus 0x030d
#define def_key_pad_period 0x030e
/*
--------------------------------------------------------------------------------
special keys
-------------------------------------------------------------------------------- */
#define def_key_esc 0x0400
#define def_key_backspace 0x0401
#define def_key_tab 0x0402
#define def_key_enter 0x0403
#define def_key_space 0x0404
#define def_key_insert 0x0405
#define def_key_delete 0x0406
#define def_key_print_screen 0x0407
#define def_key_scroll_lock 0x0408
#define def_key_pause 0x0409
#define def_key_sys_req 0x040a
#define def_key_break 0x040b
// 0x040c reserved for clear key
#define def_key_hangul 0x040d
#define def_key_hanja 0x040e
/*
--------------------------------------------------------------------------------
special keys on keypad
-------------------------------------------------------------------------------- */
#define def_key_pad_enter 0x0503
#define def_key_pad_insert 0x0505
#define def_key_pad_delete 0x0506
#define def_key_pad_clear 0x050c
/*
--------------------------------------------------------------------------------
movement keys
-------------------------------------------------------------------------------- */
#define def_key_up 0x0600
#define def_key_down 0x0601
#define def_key_left 0x0602
#define def_key_right 0x0603
#define def_key_page_up 0x0604
#define def_key_page_down 0x0605
#define def_key_home 0x0606
#define def_key_end 0x0607
/*
--------------------------------------------------------------------------------
movement keys on keypad
-------------------------------------------------------------------------------- */
#define def_key_pad_up 0x0700
#define def_key_pad_down 0x0701
#define def_key_pad_left 0x0702
#define def_key_pad_right 0x0703
#define def_key_pad_page_up 0x0704
#define def_key_pad_page_down 0x0705
#define def_key_pad_home 0x0706
#define def_key_pad_end 0x0707
/*
--------------------------------------------------------------------------------
function keys
-------------------------------------------------------------------------------- */
#define def_key_f1 0x0800
#define def_key_f2 0x0801
#define def_key_f3 0x0802
#define def_key_f4 0x0803
#define def_key_f5 0x0804
#define def_key_f6 0x0805
#define def_key_f7 0x0806
#define def_key_f8 0x0807
#define def_key_f9 0x0808
#define def_key_f10 0x0809
#define def_key_f11 0x080a
#define def_key_f12 0x080b
/*
--------------------------------------------------------------------------------
function keys on keypad
-------------------------------------------------------------------------------- */
/*
--------------------------------------------------------------------------------
additonal defines
-------------------------------------------------------------------------------- */
#define def_key_type_null 0x0000u
#define def_key_type_shift 0x0100u
#define def_key_type_char 0x0200u
#define def_key_type_pad_char 0x0300u
#define def_key_type_action 0x0400u
#define def_key_type_pad_action 0x0500u
#define def_key_type_cursor 0x0600u
#define def_key_type_pad_cursor 0x0700u
#define def_key_type_function 0x0800u
#define def_key_type_pad_function 0x0900u
#define def_key_mask_rshift 0x0001u
#define def_key_mask_lshift 0x0002u
#define def_key_mask_rctrl 0x0004u
#define def_key_mask_lctrl 0x0008u
#define def_key_mask_ralt 0x0010u
#define def_key_mask_lalt 0x0020u
#define def_key_mask_rmachine 0x0040u
#define def_key_mask_lmachine 0x0080u
#define def_key_mask_num_lock 0x0100u
#define def_key_mask_caps_lock 0x0200u
#define def_key_mask_shift (def_key_mask_rshift | def_key_mask_lshift)
#define def_key_mask_ctrl (def_key_mask_rctrl | def_key_mask_lctrl)
#define def_key_mask_alt (def_key_mask_ralt | def_key_mask_lalt)
#define def_key_mask_machine (def_key_mask_rmachine | def_key_mask_lmachine)
#define def_key_mask_code_type 0xff00u
#define def_key_mask_code_offset 0x00ffu
/*
-------------------------------------------------------------------------------- */
struct cls_key_frame
{
bool make_flg;
uint16 code_u16;
uint16 shifted_u16;
uint16 toggled_u16;
};
#if (defined def_dos) || (defined def_os2 && !defined def_pm)
void key_on();
void key_off();
void key_reset();
bool key_pressed();
void key_get(cls_key_frame*);
#endif
| 45.524823
| 123
| 0.426157
|
drypot
|
7500881c595656b36cf3bf9aa8b7ebdf0d282e2f
| 8,635
|
cpp
|
C++
|
http.cpp
|
kissbeni/tinyhttp
|
2e7dddbbb4ac0824ec457eadfcf00106fce5154c
|
[
"Apache-2.0"
] | 2
|
2021-11-27T18:35:20.000Z
|
2022-03-23T08:11:57.000Z
|
http.cpp
|
kissbeni/tinyhttp
|
2e7dddbbb4ac0824ec457eadfcf00106fce5154c
|
[
"Apache-2.0"
] | null | null | null |
http.cpp
|
kissbeni/tinyhttp
|
2e7dddbbb4ac0824ec457eadfcf00106fce5154c
|
[
"Apache-2.0"
] | null | null | null |
#include "http.hpp"
#include <vector>
/*static*/ TCPClientStream TCPClientStream::acceptFrom(short listener) {
struct sockaddr_in client;
const size_t clientLen = sizeof(client);
short sock = accept(
listener,
reinterpret_cast<struct sockaddr*>(&client),
const_cast<socklen_t*>(reinterpret_cast<const socklen_t*>(&clientLen))
);
if (sock < 0) {
perror("accept failed");
return {-1};
}
return {sock};
}
void TCPClientStream::send(const void* what, size_t size) {
if (::send(mSocket, what, size, MSG_NOSIGNAL) < 0)
throw std::runtime_error("TCP send failed");
}
size_t TCPClientStream::receive(void* target, size_t max) {
ssize_t len;
if ((len = recv(mSocket, target, max, MSG_NOSIGNAL)) < 0)
throw std::runtime_error("TCP receive failed");
return static_cast<size_t>(len);
}
std::string TCPClientStream::receiveLine(bool asciiOnly, size_t max) {
std::string res;
char ch;
while (res.size() < max) {
if (recv(mSocket, &ch, 1, MSG_NOSIGNAL) != 1)
throw std::runtime_error("TCP receive failed");
if (ch == '\r') continue;
if (ch == '\n') break;
if (asciiOnly && !isascii(ch))
throw std::runtime_error("Only ASCII characters were allowed");
res.push_back(ch);
}
return res;
}
void TCPClientStream::close() {
if (mSocket < 0) return;
::close(mSocket);
mSocket = -1;
}
bool HttpRequest::parse(std::shared_ptr<IClientStream> stream) {
std::istringstream iss(stream->receiveLine());
std::vector<std::string> results(std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>());
if (results.size() < 2)
return false;
std::string methodString = results[0];
if (methodString == "GET" ) { mMethod = HttpRequestMethod::GET; }
else if (methodString == "POST" ) { mMethod = HttpRequestMethod::POST; }
else if (methodString == "PUT" ) { mMethod = HttpRequestMethod::PUT; }
else if (methodString == "DELETE" ) { mMethod = HttpRequestMethod::DELETE; }
else if (methodString == "OPTIONS") { mMethod = HttpRequestMethod::OPTIONS; }
else return false;
path = results[1];
ssize_t question = path.find("?");
if (question > 0) {
query = path.substr(question);
path = path.substr(0, question);
}
if (query.empty())
std::cout << methodString << " " << path << std::endl;
else
std::cout << methodString << " " << path << " (Query: " << query << ")" << std::endl;
while (true) {
std::string line = stream->receiveLine();
if (line.empty()) break;
ssize_t sep = line.find(": ");
if (sep <= 0)
return false;
std::string key = line.substr(0, sep), val = line.substr(sep+2);
(*this)[key] = val;
//std::cout << "HEADER: <" << key << "> set to <" << val << ">" << std::endl;
}
std::string contentLength = (*this)["Content-Length"];
ssize_t cl = std::atoll(contentLength.c_str());
if (cl > MAX_HTTP_CONTENT_SIZE)
throw std::runtime_error("request too large");
if (cl > 0) {
char* tmp = new char[cl];
bzero(tmp, cl);
stream->receive(tmp, cl);
mContent = std::string(tmp, cl);
delete[] tmp;
#ifdef TINYHTTP_JSON
if ( (*this)["Content-Type"] == "application/json"
|| (*this)["Content-Type"].rfind("application/json;",0) == 0 // some clients gives us extra data like charset
) {
std::string error;
mContentJson = miniJson::Json::parse(mContent, error);
if (!error.empty())
std::cerr << "Content type was JSON but we couldn't parse it! " << error << std::endl;
}
#endif
}
return true;
}
/*static*/ bool HttpHandlerBuilder::isSafeFilename(const std::string& name, bool allowSlash) {
static const char allowedChars[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.-+@";
for (auto x : name) {
if (x == '/' && !allowSlash)
return false;
bool ok = false;
for (size_t i = 0; allowedChars[i] && !ok; i++)
ok = allowedChars[i] == x;
if (!ok) return false;
}
return true;
}
/*static*/ std::string HttpHandlerBuilder::getMimeType(std::string name) {
static std::map<std::string, std::string> mMimeDatabase;
if (mMimeDatabase.empty()) {
mMimeDatabase.insert({"js", "application/javascript"});
mMimeDatabase.insert({"pdf", "application/pdf"});
mMimeDatabase.insert({"gz", "application/gzip"});
mMimeDatabase.insert({"xml", "application/xml"});
mMimeDatabase.insert({"html", "text/html"});
mMimeDatabase.insert({"htm", "text/html"});
mMimeDatabase.insert({"css", "text/css"});
mMimeDatabase.insert({"txt", "text/plain"});
mMimeDatabase.insert({"png", "image/png"});
mMimeDatabase.insert({"jpg", "image/jpeg"});
mMimeDatabase.insert({"jpeg", "image/jpeg"});
mMimeDatabase.insert({"json", "application/json"});
}
ssize_t pos = name.rfind(".");
if (pos < 0)
return "application/octet-stream";
auto f = mMimeDatabase.find(name.substr(pos+1));
if (f == mMimeDatabase.end())
return "application/octet-stream";
return f->second;
}
HttpServer::HttpServer() {
mDefault404Message = HttpResponse{404, "text/plain", "404 not found"}.buildMessage();
mDefault400Message = HttpResponse{400, "text/plain", "400 bad request"}.buildMessage();
}
void HttpServer::startListening(uint16_t port) {
#ifndef TINYHTTP_FUZZING
mSocket = socket(AF_INET, SOCK_STREAM, 0);
if (mSocket == -1)
throw std::runtime_error("Could not create socket");
struct sockaddr_in remote = {0};
remote.sin_family = AF_INET;
remote.sin_addr.s_addr = htonl(INADDR_ANY);
remote.sin_port = htons(port);
int iRetval;
while (true) {
iRetval = bind(mSocket, reinterpret_cast<struct sockaddr*>(&remote), sizeof(remote));
if (iRetval < 0) {
perror("Failed to bind socket, retrying in 5 seconds...");
usleep(1000 * 5000);
} else break;
}
listen(mSocket, 3);
#else
mSocket = 0;
#endif
printf("Waiting for incoming connections...\n");
while (mSocket != -1) {
#ifdef TINYHTTP_FUZZING
auto stream = std::make_shared<StdinClientStream>();
#else
auto stream = std::shared_ptr<IClientStream>(new TCPClientStream{TCPClientStream::acceptFrom(mSocket)});
#endif
std::thread th([stream,this]() {
ICanRequestProtocolHandover* handover = nullptr;
std::unique_ptr<HttpRequest> handoverRequest;
try {
while (stream->isOpen()) {
HttpRequest req;
try {
if (!req.parse(stream)) {
stream->send(mDefault400Message);
stream->close();
continue;
}
} catch (...) {
stream->send(mDefault400Message);
stream->close();
continue;
}
auto res = processRequest(req.getPath(), req);
if (res) {
auto builtMessage = res->buildMessage();
stream->send(builtMessage);
if (res->acceptProtocolHandover(&handover)) {
handoverRequest = std::make_unique<HttpRequest>(req);
break;
}
goto keep_alive_check;
}
stream->send(mDefault404Message);
keep_alive_check:
if (req["Connection"] != "keep-alive")
break;
}
if (handover) handover->acceptHandover(mSocket, *stream.get(), std::move(handoverRequest));
} catch (std::exception& e) {
std::cerr << "Exception in HTTP client handler (" << e.what() << ")\n";
}
stream->close();
});
#ifdef TINYHTTP_FUZZING
th.join();
break;
#else
th.detach();
#endif
}
puts("Listen loop shut down");
}
void HttpServer::shutdown() {
close(mSocket);
mSocket = -1;
}
| 30.298246
| 122
| 0.550434
|
kissbeni
|
7506f8c3b63aff5e8b7ddfd042bcdccd46e947ac
| 50,640
|
cpp
|
C++
|
element.cpp
|
orkzking/openxfem
|
66889ea05ec108332ab8566b510124ee1a3f334d
|
[
"FTL"
] | null | null | null |
element.cpp
|
orkzking/openxfem
|
66889ea05ec108332ab8566b510124ee1a3f334d
|
[
"FTL"
] | null | null | null |
element.cpp
|
orkzking/openxfem
|
66889ea05ec108332ab8566b510124ee1a3f334d
|
[
"FTL"
] | null | null | null |
/************************************************************************************
Copyright (C) 2005
Stephane BORDAS, Cyrille DUNANT, Vinh Phu NGUYEN, Quang Tri TRUONG, Ravindra DUDDU
This file is part of the XFEM C++ Library (OpenXFEM++) written
and maintained by above authors.
This program is free software; you can redistribute it and/or modify it.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
license text for more details.
Any feedback is welcome. Emails : nvinhphu@gmail.com, ...
*************************************************************************************/
// file ELEMENT.CPP
#include "element.h"
#include "tri_u.h"
#include "tri6.h"
#include "quad_u.h"
#include "plateiso4.h"
#include "tetra4.h"
#include "mitc4.h"
#include "domain.h"
#include "timestep.h"
#include "timinteg.h"
#include "node.h"
#include "dof.h"
#include "material.h"
#include "bodyload.h"
#include "gausspnt.h"
#include "intarray.h"
#include "flotarry.h"
#include "flotmtrx.h"
#include "diagmtrx.h"
#include "enrichmentitem.h"
#include "cracktip.h"
#include "crackinterior.h"
#include "materialinterface.h"
#include "enrichmentfunction.h"
#include "standardquadrature.h"
#include "splitgaussquadrature.h"
#include "vertex.h"
#include "feinterpol.h"
#include "linsyst.h"
#include "functors.h"
#include "skyline.h"
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <map>
#include <algorithm>
#include <iostream>
#include "planelast.h"
using namespace std;
Element :: Element (int n, Domain* aDomain)
: FEMComponent (n, aDomain)
// Constructor. Creates an element with number n, belonging to aDomain.
{
material = 0 ;
numberOfNodes = 0 ;
nodeArray = NULL ;
locationArray = NULL ;
constitutiveMatrix = NULL ;
massMatrix = NULL ;
stiffnessMatrix = NULL ;
bodyLoadArray = NULL ;
gaussPointArray = NULL ;
neighbors = NULL ; // XFEM, NVP 2005
numberOfGaussPoints = 0 ; // XFEM, NVP 2005
numOfGPsForJ_Integral = 0 ; // XFEM, NVP 2005-08-13
numberOfIntegrationRules = 0 ; // XFEM, NVP 2005
quadratureRuleArray= NULL ; // XFEM, NVP 2005
standardFEInterpolation = NULL ; // XFEM, NVP 2005
enrichmentFEInterpolation= NULL ; // XFEM, NVP 2005
enrichmentItemListOfElem = NULL ; // XFEM, NVP 2005
checked = false; // XFEM, NVP 2005
isUpdated = false ; // XFEM, NVP 2005-09-03
isMultiMaterial = false ; // one material element
//materialIDs =
}
Element :: ~Element ()
// Destructor.
{
delete nodeArray ;
delete locationArray ;
delete massMatrix ;
delete stiffnessMatrix ;
delete constitutiveMatrix ;
if (gaussPointArray)
{
for (size_t i = 0 ; i < numberOfGaussPoints ; i++)
delete gaussPointArray[i] ;
delete gaussPointArray ;
}
if (quadratureRuleArray)
{
for (size_t i = 0 ; i < numberOfIntegrationRules ; i++)
delete quadratureRuleArray[i] ;
delete quadratureRuleArray ;
}
delete bodyLoadArray ;
delete enrichmentItemListOfElem ;
delete standardFEInterpolation ;
delete enrichmentFEInterpolation ;
delete neighbors ;
}
FloatMatrix* Element :: ComputeTangentStiffnessMatrix ()
// Computes numerically the tangent stiffness matrix of the receiver, with
// the mesh subject to the total displacements D.
// Remark: geometrical nonlinarities are not acccounted for.
// MODIFIED TO TAKE ACCOUNT FOR MULTIMATERIALS ELEMENT !!!
{
GaussPoint *gp;
FloatMatrix *b,*db,*d;
double dV;
//test ConstantStiffness?
char nlSolverClassName[32] ;
NLSolver* nlSolver = this->domain->giveNLSolver();
nlSolver -> giveClassName(nlSolverClassName) ;
if (stiffnessMatrix) {
delete stiffnessMatrix;
}
stiffnessMatrix = new FloatMatrix();
Material *mat = this->giveMaterial();
for (size_t i = 0 ; i < this->giveNumberOfGaussPoints() ; i++)
{
gp = gaussPointArray[i];
b = this->ComputeBmatrixAt(gp);
// compute D matrix
if(! strcmp(nlSolverClassName,"ConstantStiffness"))
d = this->giveConstitutiveMatrix()->GiveCopy(); // NO USED LONGER !!!
else
d = mat->ComputeConstitutiveMatrix(gp,this); // USE THIS ONE
//d->printYourself();
dV = this->computeVolumeAround(gp);
db = d->Times(b);
stiffnessMatrix->plusProduct(b,db,dV);
delete d;
delete db;
delete b; // SC-Purify-10.09.97
}
stiffnessMatrix->symmetrized();
return stiffnessMatrix->GiveCopy(); // fix memory leaks !!!
}
FloatArray* Element :: ComputeInternalForces (FloatArray* dElem)
// Computes the internal force vector of the receiver, with the domain sub-
// ject to the displacements D.
{
GaussPoint *gp;
FloatMatrix *b;
double dV;
Material *mat = this->giveMaterial();
FloatArray *f = new FloatArray();
for(size_t i = 0 ; i < this->giveNumberOfGaussPoints() ; i++)
{
gp = gaussPointArray[i];
b = this->ComputeBmatrixAt(gp);
mat -> ComputeStress(dElem,this,gp);
dV = this->computeVolumeAround(gp);
f->plusProduct(b,gp->giveStressVector(),dV);
delete b;
}
return f;
}
void Element :: assembleLhsAt (TimeStep* stepN)
// Assembles the left-hand side (stiffness matrix) of the receiver to
// the linear system' left-hand side, at stepN.
{
//FloatMatrix* elemLhs ;
//Skyline* systLhs ;
//IntArray* locArray ;
//elemLhs = this -> ComputeLhsAt(stepN) ;
//systLhs = domain -> giveNLSolver() -> giveLinearSystem() -> giveLhs() ;
//locArray = this -> giveLocationArray() ;
//systLhs -> assemble(elemLhs,locArray) ;
//delete elemLhs ;
}
void Element :: assembleRhsAt (TimeStep* stepN)
// Assembles the right-hand side (load vector) of the receiver to
// the linear system' right-hand side, at stepN.
{
//FloatArray* elemRhs ;
//FloatArray* systRhs ;
//IntArray* locArray ;
//elemRhs = this -> ComputeRhsAt(stepN) ;
//if (elemRhs) {
// systRhs = domain -> giveNLSolver() -> giveLinearSystem() -> giveRhs() ;
// locArray = this -> giveLocationArray() ;
// systRhs -> assemble(elemRhs,locArray) ;
// delete elemRhs ;}
}
void Element :: assembleYourselfAt (TimeStep* stepN)
// Assembles the contributions of the receiver to the linear system, at
// time step stepN. This may, or may not, require assembling the receiver's
// left-hand side.
{
# ifdef VERBOSE
printf ("assembling element %d\n",number) ;
# endif
//CB - Modified by SC - 25.07.97
//because we ALWAYS reform the system!
//if (stepN -> requiresNewLhs())
//CE - Modified by SC - 25.07.97
//this -> assembleLhsAt(stepN) ;
//this -> assembleRhsAt(stepN) ;
}
FloatArray* Element :: ComputeBcLoadVectorAt (TimeStep* stepN)
// Computes the load vector due to the boundary conditions acting on the
// receiver's nodes, at stepN. Returns NULL if this array contains only
// zeroes.
// Modified by NVP 2005-09-04 for XFEM implementation.
{
FloatArray *d, *answer ;
FloatMatrix *k;
d = this -> ComputeVectorOfPrescribed('d',stepN) ;
if(this->domain->isXFEMorFEM() == false && stepN->giveNumber() > 1)
{
FloatArray *previousDPr;
previousDPr = this -> ComputeVectorOfPrescribed ('d',domain -> giveTimeIntegrationScheme() -> givePreviousStep()) ;
d->minus(previousDPr);
delete previousDPr;
}
if (d -> containsOnlyZeroes())
{
answer = NULL ;
} else
{
k = this -> GiveStiffnessMatrix() ;
answer = k -> Times(d) -> negated() ;
delete k ;
}
delete d ;
return answer ;
}
FloatArray* Element :: ComputeBodyLoadVectorAt (TimeStep* stepN)
// Computes numerically the load vector of the receiver due to the body
// loads, at stepN.
{
double dV ;
GaussPoint* gp ;
FloatArray *answer,*f,*ntf ;
FloatMatrix *n,*nt ;
if (this -> giveBodyLoadArray() -> isEmpty()) // no loads
return NULL ;
else {
f = this -> ComputeResultingBodyForceAt(stepN) ;
if (! f) // nil resultant
return NULL ;
else {
answer = new FloatArray(0) ;
for (size_t i = 0 ; this->giveNumberOfGaussPoints() ; i++)
{
gp = gaussPointArray[i] ;
n = this -> ComputeNmatrixAt(gp) ;
dV = this -> computeVolumeAround(gp) ;
nt = n -> GiveTransposition() ;
ntf = nt -> Times(f) -> times(dV) ;
answer -> add(ntf) ;
delete n ;
delete nt ;
delete ntf ;
}
delete f ;
return answer ;
}
}
}
FloatMatrix* Element :: ComputeConsistentMassMatrix ()
// Computes numerically the consistent (full) mass matrix of the receiver.
{
double density,dV ;
FloatMatrix *n,*answer ;
GaussPoint *gp ;
answer = new FloatMatrix() ;
density = this -> giveMaterial() -> give('d') ;
for (size_t i = 0 ; this->giveNumberOfGaussPoints() ; i++)
{
gp = gaussPointArray[i] ;
n = this -> ComputeNmatrixAt(gp) ;
dV = this -> computeVolumeAround(gp) ;
answer -> plusProduct(n,n,density*dV) ;
delete n ;
}
return answer->symmetrized() ;
}
FloatMatrix* Element :: computeLhsAt (TimeStep* stepN)
// Computes the contribution of the receiver to the left-hand side of the
// linear system.
{
TimeIntegrationScheme* scheme ;
scheme = domain -> giveTimeIntegrationScheme() ;
if (scheme -> isStatic())
return this -> ComputeStaticLhsAt (stepN) ;
else if (scheme -> isNewmark())
return this -> ComputeNewmarkLhsAt(stepN) ;
else
{
printf ("Error : unknown time integration scheme : %c\n",scheme) ;
exit(0) ;
return NULL ; //SC
}
}
FloatArray* Element :: ComputeLoadVectorAt (TimeStep* stepN)
// Computes the load vector of the receiver, at stepN.
{
FloatArray* loadVector ;
FloatArray* bodyLoadVector = NULL ;
FloatArray* bcLoadVector = NULL ;
loadVector = new FloatArray(0) ;
bodyLoadVector = this -> ComputeBodyLoadVectorAt(stepN) ;
if (bodyLoadVector)
{
loadVector -> add(bodyLoadVector) ;
delete bodyLoadVector ;
}
// BCLoad vector only at the first iteration
if (this->domain->giveNLSolver()->giveCurrentIteration() == 1)
{
bcLoadVector = this -> ComputeBcLoadVectorAt(stepN) ;
if (bcLoadVector)
{
loadVector -> add(bcLoadVector) ;
delete bcLoadVector ;
}
}
if (loadVector -> isNotEmpty())
return loadVector ;
else
{
delete loadVector ;
return NULL ;
}
}
FloatMatrix* Element :: computeMassMatrix ()
// Returns the lumped mass matrix of the receiver.
{
FloatMatrix* consistentMatrix ;
consistentMatrix = this -> ComputeConsistentMassMatrix() ;
massMatrix = consistentMatrix -> Lumped() ;
delete consistentMatrix ;
return massMatrix ;
}
FloatMatrix* Element :: ComputeNewmarkLhsAt (TimeStep* stepN)
// Computes the contribution of the receiver to the left-hand side of the
// linear system, using Newmark's formula.
{
FloatMatrix *m,*lhs ;
double beta,dt ;
if (stepN->giveNumber() == 0) {
lhs = this -> GiveStiffnessMatrix() ;
} else {
beta = domain -> giveTimeIntegrationScheme() -> giveBeta() ;
if (beta == 0.0)
{
printf ("Error: beta = 0.0 in Newmark \n") ;
exit(0) ;
}
else
{
dt = stepN -> giveTimeIncrement() ;
m = this -> giveMassMatrix() -> Times(1.0 / (beta*dt*dt));
lhs = this -> GiveStiffnessMatrix();
lhs->plus(m);
delete m;
}
}
return lhs ;
}
FloatArray* Element :: ComputeNewmarkRhsAt (TimeStep* stepN, FloatArray* dxacc)
// Computes the contribution of the receiver to the right-hand side of the
// linear system, using Newmark's formula.
{
FloatMatrix *K;
DiagonalMatrix *M;
FloatArray *fExt,*dPred,*rhs,*a,*d,*dElem,*dPrev,*temp;
double beta,dt ;
fExt = this -> ComputeLoadVectorAt(stepN) ;
if (stepN->giveNumber() == 0)
{
// computes also the true stress state at the intial step, through the internal
// forces computation.
K = this -> GiveStiffnessMatrix () ;
d = this -> ComputeVectorOf ('d',stepN) ;
dElem = dxacc->Extract(this->giveLocationArray());
rhs = K -> Times(d) -> add(fExt) -> add (this->ComputeInternalForces(dElem)->negated());
delete d;
delete dElem;
delete K;
}
else
{
dPred = this -> ComputeVectorOf ('D',stepN) ;
dPrev = this -> ComputeVectorOf ('d',domain -> giveTimeIntegrationScheme() -> givePreviousStep()) ;
double aNorm = dxacc->giveNorm();
if (aNorm == 0.)
{ //means iteration zero (dxacc = 0)
dElem = dPred->Minus(dPrev);
rhs = (this->ComputeInternalForces(dElem)->negated()) -> add(fExt);
delete dElem;
} else
{
M = (DiagonalMatrix*) this -> giveMassMatrix () ;
dt = stepN -> giveTimeIncrement() ;
beta = domain -> giveTimeIntegrationScheme() -> giveBeta() ;
dElem = dxacc->Extract(this->giveLocationArray());
a = dElem->Times(1.0 / (beta*dt*dt));
temp = dPred->Minus(dPrev);
temp->add(dElem);
rhs = (M->Times(a->negated())) -> add(this->ComputeInternalForces(temp)->negated()) -> add(fExt);
delete a ;
delete dElem;
delete temp;
}
delete dPred;
delete dPrev;
}
delete fExt ;
return rhs ;
}
int Element :: computeNumberOfDofs ()
// Returns the total number of dofs of the receiver's nodes.
{
int n = 0 ;
for (size_t i = 0 ; i < numberOfNodes ; i++)
n += this -> giveNode(i+1) -> giveNumberOfDofs() ;
return n ;
}
size_t Element :: computeNumberOfDisplacementDofs ()
// **************************************************
// Returns the total number of "true" dofs of the receiver's nodes.
// just read from the input file, the dofs of each node
{
size_t n = 0 ;
for (size_t i = 0 ; i < numberOfNodes ; i++)
{
n += this -> giveNode(i+1) -> readInteger("nDofs") ;
}
return n ;
}
FloatArray* Element :: ComputeResultingBodyForceAt (TimeStep* stepN)
// Computes at stepN the resulting force due to all body loads that act
// on the receiver. This force is used by the element for computing its
// body load vector.
{
int n ;
BodyLoad* load ;
FloatArray *force,*resultant ;
resultant = new FloatArray(0) ;
int nLoads = this -> giveBodyLoadArray() -> giveSize() ;
for (size_t i = 1 ; i <= nLoads ; i++)
{
n = bodyLoadArray -> at(i) ;
load = (BodyLoad*) domain->giveLoad(n) ;
force = load -> ComputeForceOn(this,stepN) ;
resultant -> add(force) ;
delete force ;
}
if (resultant->giveSize() == 0)
{
delete resultant ;
return NULL ;
}
else
return resultant ;
}
FloatArray* Element :: computeRhsAt (TimeStep* stepN, FloatArray* dxacc)
// Computes the contribution of the receiver to the right-hand side of the
// linear system.
{
TimeIntegrationScheme* scheme = domain -> giveTimeIntegrationScheme() ;
if (scheme -> isStatic())
return this -> ComputeStaticRhsAt (stepN,dxacc) ;
else if (scheme -> isNewmark())
return this -> ComputeNewmarkRhsAt(stepN,dxacc) ;
else
{
printf ("Error : unknown time integration scheme : %c\n",scheme) ;
assert(false) ;
return NULL ; //SC
}
}
FloatMatrix* Element :: ComputeStaticLhsAt (TimeStep* stepN)
// Computes the contribution of the receiver to the left-hand side of the
// linear system, in a static analysis.
// Modified by NVP 21-10-2005 for XFEM update
// Only recompute the stiffness matrices for updated elements!!!
{
//if (stepN->giveNumber() == 1)
return this -> ComputeTangentStiffnessMatrix() ;
//else
//{
// if(isUpdated)
/// return this -> ComputeTangentStiffnessMatrix() ;
// return stiffnessMatrix->GiveCopy() ;
//}
}
FloatArray* Element :: ComputeStaticRhsAt (TimeStep* stepN, FloatArray* dxacc)
// Computes the contribution of the receiver to the right-hand side of the
// linear system, in a static analysis.
// Modified by NVP 2005-09-05 for XFEM ( crack growth simulation part).
{
FloatArray *answer,*fInternal,*fExternal,*dElem,*dElemTot;
dElem = dxacc->Extract(this->giveLocationArray());
//add delta prescribed displacement vector - SC 29.04.99
if(this->domain->giveNLSolver()->giveCurrentIteration() != 1)// from second iteration on
{
FloatArray *currentDPr,*previousDPr;
currentDPr = this -> ComputeVectorOfPrescribed('d',stepN) ;
if( (stepN->giveNumber() > 1) && (this->domain->isXFEMorFEM() == false) )
{
previousDPr = this -> ComputeVectorOfPrescribed('d',domain -> giveTimeIntegrationScheme() -> givePreviousStep()) ;
dElemTot = (dElem->Plus(currentDPr))->Minus(previousDPr);
delete previousDPr;
}
else
{
dElemTot = dElem->Plus(currentDPr);
}
delete currentDPr;
}
else // first iteration
{
dElemTot = dElem->Times(1.);
}
fInternal = this->ComputeInternalForces(dElemTot);
fExternal = this->ComputeLoadVectorAt(stepN);
answer = fExternal->Minus(fInternal);
delete dElem;
delete dElemTot;
delete fExternal;
delete fInternal;
return answer;
}
FloatMatrix* Element :: computeStiffnessMatrix ()
// Computes numerically the stiffness matrix of the receiver.
// NOT USED ANYMORE !!!
{
double dV ;
FloatMatrix *b,*db,*d ;
GaussPoint *gp ;
stiffnessMatrix = new FloatMatrix() ;
for (size_t i = 0 ; this->giveNumberOfGaussPoints() ; i++)
{
gp = gaussPointArray[i] ;
b = this -> ComputeBmatrixAt(gp) ;
d = this -> giveConstitutiveMatrix() ;
dV = this -> computeVolumeAround(gp) ;
db = d -> Times(b) ;
stiffnessMatrix -> plusProduct(b,db,dV) ;
delete b ;
delete db ;
}
return stiffnessMatrix -> symmetrized() ;
}
FloatArray* Element :: computeStrainVector (GaussPoint* gp, TimeStep* stepN)
// Computes the vector containing the strains at the Gauss point gp of
// the receiver, at time step stepN. The nature of these strains depends
// on the element's type.
{
FloatMatrix *b ;
FloatArray *u,*Epsilon ;
b = this -> ComputeBmatrixAt(gp) ;
u = this -> ComputeVectorOf('d',stepN) ;
Epsilon = b -> Times(u) ;
gp -> letStrainVectorBe(Epsilon) ; // gp stores Epsilon, not a copy
delete b ;
delete u ;
return Epsilon ;
}
/*
FloatArray* Element :: computeStressAt(GaussPoint* gp,TimeStep* stepN)
// ********************************************************************
// computes stress at Stress point gp.
{
FloatMatrix *b = this -> ComputeBmatrixAt(gp) ;
FloatArray *u = this -> ComputeVectorOf('d',stepN) ;
FloatArray *Epsilon = b -> Times(u) ;
FloatMatrix *D = this->giveConstitutiveMatrix();
FloatArray *stress = D->Times(Epsilon);
delete b ;
delete u ;
delete Epsilon ;
return stress ;
}*/
void Element :: computeStrain (TimeStep* stepN)
// compute strain vector at stepN
{
GaussPoint* gp ;
for (size_t i = 1 ; i <= this->giveNumberOfGaussPoints() ; i++)
{
gp = gaussPointArray[i-1] ;
this -> computeStrainVector(gp,stepN) ;
}
}
FloatArray* Element :: computeStrainIncrement (GaussPoint* gp, FloatArray* dElem)
// Returns the vector containing the strains incr. at point 'gp', with the nodal
// displacements incr. of the receiver given by dElem.
{
FloatArray* depsilon;
FloatMatrix* b;
b = this -> ComputeBmatrixAt(gp);
depsilon = b -> Times(dElem);
delete b;
return depsilon;
}
FloatArray* Element :: ComputeVectorOf (char u, TimeStep* stepN)
// *************************************************************
// Forms the vector containing the values of the unknown 'u' (e.g., the
// displacement) of the dofs of the receiver's nodes.
// Modified by NVP to take into account the enriched DOFs for XFEM. 2005/07/15
// u = [u1 v1 ...un vn | a1 b1 ..an bn ]
{
Node *nodeI ;
int nDofs ;
FloatArray *answer = new FloatArray(this->computeNumberOfDofs()) ;
int k = 0 ;
for (size_t i = 0 ; i < numberOfNodes ; i++)
{
nodeI = this->giveNode(i+1) ;
nDofs = nodeI->giveNumberOfTrueDofs () ;
for (size_t j = 1 ; j <= nDofs ; j++)
answer->at(++k) = nodeI->giveDof(j)->giveUnknown(u,stepN) ;
}
if(this->isEnriched() == false) // non-enriched element
return answer ;
// enriched element
size_t numOfTrueDofs ;
for (size_t i = 0 ; i < numberOfNodes ; i++)
{
nodeI = this->giveNode(i+1) ;
numOfTrueDofs = nodeI->giveNumberOfTrueDofs() ;
nDofs = nodeI->giveNumberOfDofs() - numOfTrueDofs ;
for (size_t j = 1 ; j <= nDofs ; j++)
answer->at(++k) = nodeI->giveDof(j+numOfTrueDofs)->giveUnknown(u,stepN) ;
}
return answer ;
}
FloatArray* Element :: ComputeVectorOfDisplacement (char u, TimeStep* stepN)
// *************************************************************************
// computes the "true" displacement vector of the receiver
// XFEM implementation.
{
Node *nodeI ;
size_t nDofs ;
FloatArray *answer = new FloatArray(this->computeNumberOfDisplacementDofs()) ;
int k = 0 ;
for (size_t i = 0 ; i < numberOfNodes ; i++) {
nodeI = this->giveNode(i+1) ;
nDofs = nodeI->giveNumberOfTrueDofs() ;
for (size_t j = 1 ; j <= nDofs ; j++)
answer->at(++k) = nodeI->giveDof(j)->giveUnknown(u,stepN) ;
}
return answer ;
}
FloatArray* Element :: ComputeVectorOfPrescribed (char u, TimeStep* stepN)
// Forms the vector containing the prescribed values of the unknown 'u'
// (e.g., the prescribed displacement) of the dofs of the receiver's
// nodes. Puts 0 at each free dof.
{
Node *nodeI ;
Dof *dofJ ;
FloatArray *answer ;
int nDofs ;
answer = new FloatArray(this->computeNumberOfDofs()) ;
int k = 0 ;
for (size_t i = 0 ; i < numberOfNodes ; i++)
{
nodeI = this->giveNode(i+1) ;
nDofs = nodeI->giveNumberOfDofs() ;
for (size_t j = 1 ; j <= nDofs ; j++)
{
dofJ = nodeI->giveDof(j) ;
if (dofJ -> hasBc())
answer->at(++k) = dofJ->giveUnknown(u,stepN) ;
else
answer->at(++k) = 0. ;
}
}
return answer ;
}
IntArray* Element :: giveBodyLoadArray ()
// Returns the array which contains the number of every body load that act
// on the receiver.
{
int numberOfLoads ;
if (! bodyLoadArray)
{
numberOfLoads = this -> readIfHas("bodyLoads") ;
bodyLoadArray = new IntArray(numberOfLoads) ;
for (size_t i = 1 ; i <= numberOfLoads ; i++)
bodyLoadArray->at(i) = this->readInteger("bodyLoads",i+1) ;
}
return bodyLoadArray ;
}
FloatMatrix* Element :: giveConstitutiveMatrix ()
// Returns the elasticity matrix {E} of the receiver.
{
if (! constitutiveMatrix)
this -> computeConstitutiveMatrix() ;
return constitutiveMatrix ;
}
IntArray* Element :: giveLocationArray ()
// Returns the location array of the receiver.
// Modified by NVP to take into account the presence of enriched Dofs
{
if (! locationArray)
{
this->computeLocationArray();
}
return locationArray ;
}
IntArray* Element :: computeLocationArray ()
// ******************************************
// Returns the location array of the receiver.
// Modified by NVP to take into account the presence of enriched Dofs
{
IntArray* nodalStandardArray ; // standard scatter vector of node
IntArray* nodalEnrichedArray ; // enriched scatter vector of node
locationArray = new IntArray(0) ; // total scatter vector of element
for(size_t i = 0 ; i < numberOfNodes ; i++)
{
nodalStandardArray = this->giveNode(i+1)->giveStandardLocationArray() ;
locationArray = locationArray -> followedBy(nodalStandardArray) ;
}
// non-enriched elements
if(this->isEnriched() == false)
{
/* // DEBUG ...
std::cout << "Dealing with element " << this->giveNumber() << std::endl ;
for(size_t i = 0 ; i < locationArray->giveSize() ; i++)
std::cout << (*locationArray)[i] << " " ;
std::cout << std::endl ; */
return locationArray ;
}
// enriched elements
for (size_t i = 0 ; i < numberOfNodes ; i++)
{
nodalEnrichedArray = this -> giveNode(i+1) -> giveEnrichedLocationArray() ;
if(nodalEnrichedArray) // enriched node
locationArray = locationArray -> followedBy(nodalEnrichedArray) ;
}
/*// ----------------- DEBUG ONLY 2005-09-29 -------------------------
if(this->isEnriched())
{
std::cout << " Location array of element " << this->giveNumber() << " is :" << endl ;
for(size_t i = 0 ; i < locationArray->giveSize() ; i++)
std::cout << (*locationArray)[i] << " " ;
std::cout << std::endl ;
}
// --------------------------------------------------------------------*/
return locationArray ;
}
GaussPoint** Element :: giveGaussPointArray()
// *******************************************
// 2005-09-03 : modify for crack growth problem
// Some elements need changed Gauss Quadrature.
{
if (gaussPointArray == NULL)
this->computeGaussPoints();
else if(isUpdated)
this->computeGaussPoints();
return gaussPointArray;
}
FloatMatrix* Element :: giveMassMatrix ()
// Returns the mass matrix of the receiver.
{
if (! massMatrix)
this -> computeMassMatrix() ;
return massMatrix ;
}
Material* Element :: giveMaterial ()
// **********************************
// Returns the material of the receiver.
{
if (! material)
{
material = this -> readInteger("mat") ;
//std::cout <<this->giveNumber() << " CUC CUT !!! " ;
}
return domain -> giveMaterial(material) ;
}
Node* Element :: giveNode (int i)
// Returns the i-th node of the receiver.
{
int n ;
if (! nodeArray)
nodeArray = new IntArray(numberOfNodes) ;
n = nodeArray->at(i) ;
if (! n) {
n = this -> readInteger("nodes",i) ;
nodeArray->at(i) = n ;}
return domain -> giveNode(n) ;
}
IntArray* Element ::giveNodeArray()
{
if (! nodeArray)
{
nodeArray = new IntArray(numberOfNodes) ;
for (size_t i = 0 ; i < numberOfNodes ; i++)
(*nodeArray)[i] = this->readInteger("nodes",i+1) ;
}
return nodeArray;
}
size_t Element :: giveNumberOfGaussPoints()
// ****************************************
{
if(numberOfGaussPoints == 0)
this->computeGaussPoints();
return numberOfGaussPoints ;
}
size_t Element :: giveNumOfGPtsForJ_Integral()
// *******************************************
{
if(numOfGPsForJ_Integral == 0)
this->setGaussQuadForJ_Integral();
return numOfGPsForJ_Integral ;
}
FloatMatrix* Element :: GiveStiffnessMatrix ()
// ********************************************
// Returns the stiffness matrix of the receiver.
// Modification made by NVP for multistep problems (XFEM).
// 2005-09-03
{
if (! stiffnessMatrix)
return this -> ComputeTangentStiffnessMatrix() ;
//else if(isUpdated)
// return this -> ComputeTangentStiffnessMatrix() ;
return stiffnessMatrix->GiveCopy() ;
}
void Element :: instanciateYourself ()
// Gets from input file all data of the receiver.
{
int i ;
# ifdef VERBOSE
printf ("instanciating element %d\n",number) ;
# endif
material = this -> readInteger("mat") ;
nodeArray = new IntArray(numberOfNodes) ;
for (i=1 ; i<=numberOfNodes ; i++)
nodeArray->at(i) = this->readInteger("nodes",i) ;
this -> giveBodyLoadArray() ;
}
void Element :: printOutputAt (TimeStep* stepN, FILE* strFile, FILE* s01File)
// Performs end-of-step operations.
{
GaussPoint* gp ;
# ifdef VERBOSE
printf ("element %d printing output\n",number) ;
# endif
fprintf (strFile,"element %d :\n",number) ;
for (size_t i = 0 ; i < this->giveNumberOfGaussPoints() ; i++) {
gp = gaussPointArray[i] ;
this -> computeStrainVector(gp,stepN) ;
//no computation of the stress vector here, it
//has already been done during the calculation
//of Finternal!!!
gp -> computeStressLevel() ;
gp -> printOutput(strFile) ;
gp -> printBinaryResults(s01File) ;
}
}
Element* Element :: typed ()
// Returns a new element, which has the same number than the receiver,
// but is typed (PlaneProblem, or Truss2D,..).
{
Element* newElement ;
char type[32] ;
this -> readString("class",type) ;
newElement = this -> ofType(type) ;
return newElement ;
}
void Element :: updateYourself()
// ******************************
// Updates the receiver at end of step.
// Modified by NVP for XFEM implementation. 2005-09-05
{
# ifdef VERBOSE
printf ("updating element %d\n",number) ;
# endif
if(this->domain->isXFEMorFEM() == false)
{
for (size_t i = 0 ; i < numberOfGaussPoints ; i++)
gaussPointArray[i] -> updateYourself() ;
}
else
{
for (size_t i = 0 ; i < numberOfGaussPoints ; i++)
gaussPointArray[i] -> updateYourselfForXFEM() ;
}
delete locationArray ;
locationArray = NULL ;
}
FloatMatrix* Element ::ComputeBmatrixAt(GaussPoint *aGausspoint)
// **************************************************************
// Computes the general B matrix of the receiver, B = [Bu Ba]
// Including non enriched part and enriched parts if element is enriched
// B = [Bu Ba] with
// Bu = [N1,x 0 N2,x 0 N3,x 0
// 0 N1,y 0 N2,y 0 N3,y
// N1,y N1,x N2,y N2,x N3,y N3,x]
//
// Ba = [(Nbar1(phi-phiAtNode1)),x 0 (Nbar2(phi-phiAtNode2)),x 0 (Nbar3(phi-phiAtNode3)),x 0
// 0(Nbar1(phi-phiAtNode1)),y 0 (Nbar2(phi-phiAtNode2)),y 0 (Nbar3(phi-phiAtNode3)),y
// (Nbar1(phi-phiAtNode1)),y (Nbar1(phi-phiAtNode1)),x ...]
{
// computes the standard part of B matrix : Bu
FloatMatrix *Bu = this->ComputeBuMatrixAt(aGausspoint);
// non enriched elements
if (this->isEnriched() == false)
return Bu;
// enriched elements,then computes the enriched part Ba
FloatMatrix *Ba = new FloatMatrix();
vector<EnrichmentFunction*> *enrFnVector; // vector of enrichment functions
FloatArray *gradPhiGP ; // grad of enr. func. at Gauss points
FloatMatrix *temp ;
double N,dNdx,dNdy,phiGP,phiNode,dPhidXGP,dPhidYGP ;
Mu::Point *Coord = aGausspoint -> giveCoordinates() ; // local coord. of Gauss point
// Get the shape functions multiplied with the enr. functions...
FloatArray *Nbar = this->giveXFEInterpolation()->evalN(Coord);
FloatMatrix *gradNbar = this->giveXFEInterpolation()->evaldNdx(domain,this->giveNodeArray(),Coord);
for(size_t i = 0 ; i < numberOfNodes ; i++)
{
Node* nodeI = this->giveNode(i+1) ;
if (nodeI->getIsEnriched()) // this node is enriched, then continue ...
{
N = (*Nbar)[i]; // shape function Ni
dNdx = gradNbar->at(i+1,1) ; // derivative of Ni w.r.t x coord.
dNdy = gradNbar->at(i+1,2) ; // derivative of Ni w.r.t y coord.
// loop on enrichment items of nodeI
list<EnrichmentItem*> *enrItemList = nodeI->giveEnrItemListOfNode();
for (list<EnrichmentItem*>::iterator iter = enrItemList->begin(); iter != enrItemList->end(); ++iter)
{
// get the enrichment funcs of current enr. item
enrFnVector = (*iter)->giveEnrFuncVector();
//loop on vector of enrichment functions ...
for(size_t k = 0 ; k < enrFnVector->size() ; k++ )
{
EnrichmentFunction* enrFn = (*enrFnVector)[k];
// let Enr. function,enrFn, know for which enr. item it is modeling
enrFn->findActiveEnrichmentItem(*iter);
// value of enrichment function at gauss point
phiGP = enrFn->EvaluateYourSelfAt(aGausspoint);
// value of enrichment function at node
phiNode = enrFn->EvaluateYourSelfAt(this,nodeI);
// grad of enrichment function at Gauss point
gradPhiGP = enrFn->EvaluateYourGradAt(aGausspoint);
dPhidXGP = (*gradPhiGP)[0] ; // derivative of Phi w.r.t x coord.
dPhidYGP = (*gradPhiGP)[1] ; // derivative of Phi w.r.t y coord.
double a = dNdx * (phiGP - phiNode) + N * dPhidXGP ;
double b = dNdy * (phiGP - phiNode) + N * dPhidYGP ;
temp = new FloatMatrix(4,2);
temp->at(1,1) = a ; temp->at(1,2) = 0.0 ;
temp->at(2,1) = 0.0 ; temp->at(2,2) = b ;
temp->at(3,1) = b ; temp->at(3,2) = a ;
Ba = Ba->FollowedBy(temp);
delete temp ; // Purify, 11-10-05
delete gradPhiGP ; // Purify, 11-10-05
} // end of loop on enr. functions
} // end of loop on enr. items
}
} // end of loop on element nodes
FloatMatrix *answer = Bu->FollowedBy(Ba);
delete Ba ; // Purify, 11-10-05
delete Nbar ; delete gradNbar ; // Purify, 11-10-05
return answer;
}
bool Element:: isEnriched()
// ************************
// Returns true if element is enriched (at least one node is enriched)
// and false otherwise
{
size_t count = 0 ;
for(size_t i = 0 ; i < numberOfNodes ; i++)
{
if(this->giveNode(i+1)->getIsEnriched())
{
count += 1 ;
i = numberOfNodes ;
}
}
return (count != 0)? true:false ;
}
Element* Element :: ofType (char* aClass)
// ***************************************
// Returns a new element, which has the same number than the receiver,
// but belongs to aClass (Tri3_U, Tetra4, ...).
{
Element* newElement ;
if (! strcmp(aClass,"Q4U"))
newElement = new Quad4_U(number,domain);
else if (! strcmp(aClass,"T3U"))
newElement = new Tri3_U(number,domain) ;
else if (! strcmp(aClass,"T6U"))
newElement = new Tri6_U(number,domain) ;
else if (! strcmp(aClass,"PQ4"))
newElement = new PlateIsoQ4(number,domain) ;
else if (! strcmp(aClass,"MITC4"))
newElement = new MITC4(number,domain) ;
else if (! strcmp(aClass,"H4U"))
newElement = new Tetra4(number,domain) ;
else
{
printf ("%s : unknown element type \n",aClass) ;
assert(false) ;
}
return newElement ;
}
void Element::treatGeoMeshInteraction()
// ************************************
// Check if element interacts with enrichment item or not. If so, insert this element
// into the list of each enrichment item
// Modified at 2005-09-07 to make it more efficient than before.
// 28-12-2005: MATERIAL INTERFACE IMPLEMENTATION, ASSUMING 2 MATERIALS
{
EnrichmentItem *enrItem;
for(size_t i = 0 ; i < domain->giveNumberOfEnrichmentItems() ; i++)
{
enrItem = domain->giveEnrichmentItem(i+1);
enrItem->treatMeshGeoInteraction(this);
}
}
void Element :: isEnrichedWith(EnrichmentItem* enrItem)
// *****************************************************
// If element is enriched with enrichment item enrItem, then insert
// enrItem into the list of enrichment items
{
if(enrichmentItemListOfElem == NULL)
enrichmentItemListOfElem = new std::list<EnrichmentItem*>;
if( find(enrichmentItemListOfElem->begin(),enrichmentItemListOfElem->end(),enrItem)
== enrichmentItemListOfElem->end())
enrichmentItemListOfElem->push_back(enrItem);
}
std::list<Element*>* Element :: ComputeNeighboringElements()
// **********************************************************
// Loop on Element's nodes and get the nodal support of these nodes
// and insert into list<Element*> neighbors
// Since there are redundancies, first sort this list and then list.unique()
// Criterion for sort is defined by operator < ( compare the element.number)
{
map<Node*,vector<Element*> > nodeElemMap = this->domain->giveNodalSupports();
neighbors = new std::list<Element*> ;
for (size_t i = 0 ; i < numberOfNodes ; i++)
{
Node *aNode = this->giveNode(i+1);
neighbors->insert(neighbors->end(),nodeElemMap[aNode].begin(),nodeElemMap[aNode].end()) ;
}
// removing the redundancies in neighbors ...
neighbors->sort();
neighbors->unique();
neighbors->remove(this); // not contain the receiver !!!
return neighbors ;
}
std::list<Element*>* Element :: giveNeighboringElements()
// *******************************************************
// returns the neighboring elements of the receiver, if it does not exist yet,
// compute it.
{
if (neighbors == NULL)
neighbors = this->ComputeNeighboringElements();
return neighbors ;
}
void Element :: printMyNeighbors()
// *******************************
// Print neighbors of the receiver.
// Useful for debugging
{
neighbors = this->giveNeighboringElements();
std::cout << " Neighbors of element " << number << " : ";
for (list<Element*>::iterator it = neighbors->begin(); it != neighbors->end(); ++it)
std::cout << (*it)->giveNumber() << " " ;
std::cout << std::endl;
}
Mu::Point* Element :: giveMyCenter()
// *********************************
// compute the gravity center of the receiver
{
double sumX = 0.0 ; double sumY = 0.0 ;
for(size_t i = 0 ; i < numberOfNodes ; i++)
{
Node *nodeI = this -> giveNode(i+1);
double xI = nodeI->giveCoordinate(1);
double yI = nodeI->giveCoordinate(2);
sumX += xI ;
sumY += yI ;
}
double xc = sumX/numberOfNodes ;
double yc = sumY/numberOfNodes ;
return new Mu::Point(xc,yc);
}
bool Element :: in(Mu::Circle *c)
// ******************************
// if at least one node of the receiver belong to the circle c, then
// this element is considered locate inside c.
{
size_t count = 0 ;
Mu::Point *p;
Node *aNode;
for(size_t i = 0 ; i < numberOfNodes ; i++)
{
aNode = this->giveNode(i+1) ;
p = aNode->makePoint();
if(c->in(p))
{
count += 1 ;
delete p;
i = numberOfNodes ;
}
}
return (count != 0)? true:false ;
}
std::list<Element*> Element :: conflicts(Mu::Circle *c)
// ****************************************************
// With the help of Cyrille Dunant.
{
checked = true ;
std::list<Element*> ret,temp ;
ret.push_back(this);
std::list<Element*>* myNeighbors = this->giveNeighboringElements();
for (std::list<Element*>::iterator it = myNeighbors->begin(); it != myNeighbors->end(); it++)
{
if( ((*it)->checked == false) && ((*it)->in(c)))
{
temp = (*it)->conflicts(c);
ret.insert(ret.end(),temp.begin(),temp.end());
}
}
return ret ;
}
bool Element :: intersects(Mu::Circle *c)
// **************************************
// Check the intersection between element and circle c
// used for determining the annular domain for J integral computation.
// 2005-08-10.
{
std::vector<double> distanceVect ;
double radius = c->getRadius() ;
double centerX = c->getCenter()->x ;
double centerY = c->getCenter()->y ;
for(size_t i = 0 ; i < numberOfNodes ; i++)
{
double x = this->giveNode(i+1)->giveCoordinate(1);
double y = this->giveNode(i+1)->giveCoordinate(2);
double r = sqrt((x-centerX)*(x-centerX)+(y-centerY)*(y-centerY));
distanceVect.push_back(r-radius);
}
double max = (*std::max_element(distanceVect.begin(),distanceVect.end()));
double min = (*std::min_element(distanceVect.begin(),distanceVect.end()));
return ( max*min <= 0 ? true : false ) ;
}
bool Element::intersects(Mu::Segment *seg)
// ***************************************
{
std::vector<Mu::Point> pts ;
for(size_t i = 0 ; i < numberOfNodes ; i++)
{
Mu::Point *p = this->giveNode(i+1)->makePoint() ;
pts.push_back(*p);
delete p ;
}
bool ret = false ;
for(size_t i = 0 ; i < pts.size() ; i++)
{
Mu::Segment s(pts[i],pts[(i+1)%pts.size()]) ;
ret = ret || seg->intersects(&s) ;
}
return ret ;
}
bool Element :: IsOnEdge(Mu::Point* testPoint)
// *******************************************
// This method allows the tip touch element edge or element node
// 2005-09-06
{
size_t i;
std::vector<Mu::Point> pts ;
for(i = 0 ; i < numberOfNodes ; i++)
{
Mu::Point *p = this->giveNode(i+1)->makePoint() ;
pts.push_back(*p);
delete p ;
}
bool found = false ;
i = 0 ;
while( (i < pts.size()) && (!found) )
{
Mu::Segment s(pts[i],pts[(i+1)%pts.size()]) ;
if(s.on(testPoint))
{
std:: cout << " Ah, I found you ! " << std::endl ;
found = true ;
}
i++ ;
}
return found ;
}
bool Element :: isWithinMe(Mu::Point *p)
// *************************************
// check if p is within the receiver using orientation test.
// Used in method PartitionMyself() to detect kink points
// 2005-09-06
{
double const EPSILON = 0.00000001;
double x0 = p->x ;
double y0 = p->y ;
double delta,x1,y1,x2,y2 ;
size_t count = 0;
for (size_t i = 1 ; i <= numberOfNodes ; i++)
{
// coordinates of first node
x1 = this->giveNode(i)->giveCoordinate(1);
y1 = this->giveNode(i)->giveCoordinate(2);
// coordinates of second node
if(i != numberOfNodes)
{
x2 = this->giveNode(i+1)->giveCoordinate(1);
y2 = this->giveNode(i+1)->giveCoordinate(2);
}
else
{
x2 = this->giveNode(1)->giveCoordinate(1);
y2 = this->giveNode(1)->giveCoordinate(2);
}
delta = (x1-x0)*(y2-y0) - (x2-x0)*(y1-y0) ;
if (delta > EPSILON)
count += 1 ;
}
return (count == numberOfNodes);
}
bool Element :: isCoincidentToMyNode(Mu::Point *p)
// ***********************************************
{
for(size_t i = 0 ; i < numberOfNodes ; i++)
{
Mu::Point *pp = this->giveNode(i+1)->makePoint() ;
if( pp == p )
return true ;
delete pp ;
}
return false ;
}
void Element :: clearChecked()
// ***************************
// set checked false for the next time checking
{
checked = false ;
}
void Element :: printMyEnrItems()
// ******************************
// debug only
{
if(enrichmentItemListOfElem != NULL)
{
std::cout << " Element " << number << " interacted with " ;
for (list<EnrichmentItem*>::iterator it = enrichmentItemListOfElem->begin(); it != enrichmentItemListOfElem->end(); ++it)
{
(*it)->printYourSelf();
}
std::cout << std::endl ;
}
}
/*! RB-SB-2004-10-29
takes a string and appends it with the values of stress
for the receiver. Goes to the next line to allow further
information to be stored in the string. */
void Element :: exportStressResultsToMatlab(string& theStringStress)
// *****************************************************************
{
double val1 = 0.0; double val2 = 0.0; double val3 = 0.0; double val4 = 0.0;
double val5 = 0.0; double vonMises ;
FloatArray* stressveci;
for(size_t i = 1 ; i <= this->giveNumberOfGaussPoints(); i++)
{
stressveci = this->giveGaussPointNumber(i)->giveStressVector();
vonMises = this->giveGaussPointNumber(i)->computeVonMisesStress();//NVP 2005
assert(stressveci->giveSize() == 4);
val1 = stressveci->at(1);
val2 = stressveci->at(2);
val3 = stressveci->at(3);
val4 = stressveci->at(4);
val5 = vonMises ; //NVP 2005
char val1c[50];
char val2c[50];
char val3c[50];
char val4c[50];
char val5c[50]; //NVP 2005
_gcvt( val1, 17, val1c );
_gcvt( val2, 17, val2c );
_gcvt( val3, 17, val3c );
_gcvt( val4, 17, val4c );
_gcvt( val5, 17, val5c ); //NVP 2005
string space(" ");
string newline("\n");
string valString;
valString += val1c;
valString += space;
valString += val2c;
valString += space;
valString += val3c;
valString += space;
valString += val4c;
valString += space;
valString += val5c;
valString += newline;
theStringStress += valString;
}
}
/*! RB-SB-2004-10-29
takes a string and appends it with the values of strain
for all of the receiver's Gauss points. Goes to the next line to allow further
information to be stored in the string. Results are written as
for GAUSS POINT 1 : on row 1 : sigmaxx sigmayy sigmaxy sigmazz
...
for GAUSS POINT N : on row N : sigmaxx sigmayy sigmaxy sigmazz
N is the number of Gauss points of the receiver.
*/
void Element :: exportStrainResultsToMatlab(string& theStringStrain)
// *****************************************************************
{
double val1 = 0.0; double val2 = 0.0; double val3 = 0.0; double val4 = 0.0;//values
FloatArray* strainveci;//strain vector
int ngp = this->giveNumberOfGaussPoints();//number of Gauss points
GaussPoint* gp;//Gauss point
TimeStep* stepN = this->domain->giveTimeIntegrationScheme()->giveCurrentStep();//current step
for (size_t i = 1 ; i <= ngp ; i++)
{
gp = this->giveGaussPointNumber(i); //get Gauss point number i
this->computeStrainVector(gp,stepN); //compute the strain vector to make sure its value exists
strainveci = this->giveGaussPointNumber(i)->giveStrainVector();//get the strain vector
assert(strainveci->giveSize() == 4); //make sure it's ok
val1 = strainveci->at(1); //get the values of the strains
val2 = strainveci->at(2);
val3 = strainveci->at(3);
val4 = strainveci->at(4);
char val1c[50]; //for transformation into chars and strings
char val2c[50];
char val3c[50];
char val4c[50];
_gcvt( val1, 17, val1c );//transform the values val1... into chars val1c taking 14 digits
_gcvt( val2, 17, val2c );
_gcvt( val3, 17, val3c );
_gcvt( val4, 17, val4c );
string space(" ");//define some useful strings for output
string newline("\n");
string valString;
valString += val1c;//concatenate the strings together
valString +=space;
valString += val2c;
valString +=space;
valString += val3c;
valString +=space;
valString += val4c;
valString +=newline;
//final string composed of the four values of the strains at the Gauss point
theStringStrain+=valString;//the final, modified, string used for output
}
}
/*! RB-SB-2004-10-29
Returns the global coordinates of the Gauss points of
the receiver.
*/
void Element :: exportGaussPointsToMatlab(string& theString)
{
GaussPoint* gp; //Gauss point
FloatMatrix* N; //array of shape functions
FloatArray* XI; //array of nodal coordinates
FloatArray* globalCoords; //array of global coords.
//double weight = 0. ; // total weight of Gauss points, for debug only. NVP 2005-07-28
char value[30];
string space(" ");
string newline("\n");
for (size_t k = 1 ; k <= this->giveNumberOfGaussPoints() ; k++)
{
gp = this->giveGaussPointNumber(k);
//weight += gp->giveWeight();
N = this->ComputeNmatrixAt(gp);
XI = this->ComputeGlobalNodalCoordinates();
globalCoords = N->Times(XI);
_gcvt(globalCoords->at(1),17,value);//transforms the double param1 in char param3 with 14 digits
theString+=value;
theString+=space;
_gcvt(globalCoords->at(2),17,value);
theString+=value;
theString+=space;
theString+=newline;
delete N;
delete XI;
delete globalCoords;
}
// _gcvt(weight,3,value);
//theString+=value;
//theString+=space;
//Changed by M. Forton 5/11/11 - Uncomment to fix
//theString += newline;
}
/*! RB-SB-2004-10-29
Returns the array of nodal coordinates for an element.
The values are stored as follows:
[xNode1
yNode1
xNode2
yNode2
...
xNode_numnode
yNode_numnode]
*/
FloatArray* Element :: ComputeGlobalNodalCoordinates()
{
size_t n = this->giveNumberOfNodes();
FloatArray* result = new FloatArray(2*n);
Node* node;
for (int k = 1 ; k <= n ; k++)
{
node = this->giveNode(k);
result->at(2*k-1) = node->giveCoordinate(1);
result->at(2*k) = node->giveCoordinate(2);
}
return result;
}
GaussPoint* Element :: giveGaussPointNumber(int i)
// ************************************************
{
if (gaussPointArray) {
return gaussPointArray[i-1];
}
else {
printf("Sorry, cannot give Gauss point number %d of element %d \n",i,number);
printf("The Gauss Point Array for element %d was never created \n",number);
return NULL;
exit(0);
}
}
/*
void Element :: exportStressPointsToMatlab(string& theStringStress,TimeStep* stepN)
// ********************************************************************************
// NVP - 2005-07-19
{
double val1 = 0.0; double val2 = 0.0; double val3 = 0.0; double val4 = 0.0;
FloatArray *stressveci;
this->computeStressPoints();
for (size_t i = 0 ; i < this->giveNumberOfStressPoints(); i++)
{
stressveci = this->computeStressAt(gpForStressPlot[i],stepN);
double II = stressveci->computeInvariantJ2();
double equiStress = sqrt(3.0 * II) ; // equivalent von Mises stress.
val1 = stressveci->at(1);
val2 = stressveci->at(2);
val3 = stressveci->at(3);
val4 = stressveci->at(4);
double val5 = equiStress ;
char val1c[50];
char val2c[50];
char val3c[50];
char val4c[50];
char val5c[50];
_gcvt( val1, 17, val1c );
_gcvt( val2, 17, val2c );
_gcvt( val3, 17, val3c );
_gcvt( val4, 17, val4c );
_gcvt( val5, 17, val5c );
string space(" ");
string valString;
valString += val1c;
valString += space;
valString += val2c;
valString += space;
valString += val3c;
valString += space;
valString += val4c;
valString += space;
valString += val5c;
valString += space;
theStringStress += valString;
}
string newline("\n");
theStringStress += newline ;
}*/
void Element::reinitializeStiffnessMatrix()
{
delete stiffnessMatrix;
stiffnessMatrix = NULL;
}
void Element::computeNodalLevelSets(EnrichmentItem* enrItem)
{
GeometryEntity *geo = enrItem->giveMyGeo();
for(size_t i = 0 ; i < numberOfNodes ; i++)
{
Node *nodeI = this->giveNode(i+1);
Mu::Point *p = nodeI->makePoint();
double ls = geo->computeSignedDistanceOfPoint(p);
nodeI->setLevelSets(enrItem,ls);
}
}
void Element::updateMaterialID()
{
if(material == 0)
material = 2;
else
material += 1 ;
}
void Element :: resolveConflictsInEnrItems()
// ****************************************
// check if this list contains both a CrackTip and a CrackInterior
// then remove the CrackInterior from the list.
// functor IsType<CrackTip,EnrichmentItem>() defined generically in file "functors.h"
{
list<EnrichmentItem*> ::iterator iter1,iter2;
iter1=find_if(enrichmentItemListOfElem->begin(),enrichmentItemListOfElem->end(),IsType<MaterialInterface,EnrichmentItem>());
iter2=find_if(enrichmentItemListOfElem->begin(),enrichmentItemListOfElem->end(),IsType<CrackInterior,EnrichmentItem>());
if (iter1 != enrichmentItemListOfElem->end() && iter2 != enrichmentItemListOfElem->end())
enrichmentItemListOfElem->remove(*iter2);
}
| 28.337997
| 127
| 0.612638
|
orkzking
|
7507e24f930050d37452586d5f7b9f3c34743c26
| 3,581
|
cpp
|
C++
|
src/TitleScene.cpp
|
ccabrales/ZoneRush
|
0ded2f31580b9a369b19d59268000cff939e2bbd
|
[
"MIT"
] | null | null | null |
src/TitleScene.cpp
|
ccabrales/ZoneRush
|
0ded2f31580b9a369b19d59268000cff939e2bbd
|
[
"MIT"
] | null | null | null |
src/TitleScene.cpp
|
ccabrales/ZoneRush
|
0ded2f31580b9a369b19d59268000cff939e2bbd
|
[
"MIT"
] | null | null | null |
#include "TitleScene.h"
void TitleScene::setup(){
title.load("ZoneRush2.png");
playButton.load("PlaySelected.png");
exitButton.load("Exit.png");
loadingImage.load("Loading.png");
resetPosition();
selectedIndex = 0;
loadState = TITLE;
imageDx = -20.0;
rightEmitter.setPosition(ofVec3f(ofGetWidth()-1,ofGetHeight()/2.0));
rightEmitter.setVelocity(ofVec3f(-310,0.0));
rightEmitter.posSpread = ofVec3f(0,ofGetHeight());
rightEmitter.velSpread = ofVec3f(120,20);
rightEmitter.life = 13;
rightEmitter.lifeSpread = 0;
rightEmitter.numPars = 3;
rightEmitter.size = 12;
rightEmitter.color = ofColor(100,100,200);
rightEmitter.colorSpread = ofColor(70,70,70);
logoEmitter.setPosition(ofVec3f(ofGetWidth()-1, titlePos.y + 50));
logoEmitter.posSpread = ofVec3f(0, -60);
logoEmitter.setVelocity(ofVec3f(-2810,0.0));
logoEmitter.velSpread = ofVec3f(520,20);
logoEmitter.life = 4;
logoEmitter.lifeSpread = 3;
logoEmitter.numPars = 2;
// logoEmitter.size = 12;
logoEmitter.color = ofColor(140,140,220);
logoEmitter.colorSpread = ofColor(70,70,70);
}
void TitleScene::resetPosition(){
playPos = ofPoint((ofGetWidth() / 2.0) - (playButton.getWidth() / 2.0), 3 * ofGetHeight() / 5.0);
exitPos = ofPoint((ofGetWidth() / 2.0) - (exitButton.getWidth() / 2.0), playPos.y+playButton.getHeight() + 10.0);
titlePos = ofPoint((ofGetWidth() / 2.0) - (title.getWidth() / 2.0), ofGetHeight() / 5.0);
loadingPos = ofPoint(ofGetWidth(), (ofGetHeight() / 2.0) - loadingImage.getHeight());
}
void TitleScene::update(){
selectedIndex = 1 - selectedIndex; //Swap between 0 and 1 for the selected index
switch (selectedIndex) {
case 0:
playButton.load("PlaySelected.png");
exitButton.load("Exit.png");
break;
case 1:
playButton.load("Play.png");
exitButton.load("ExitSelected.png");
break;
default:
break;
}
}
void TitleScene::backgroundUpdate(const Track::Data* data, ofxParticleSystem* particleSystem){
if (loadState == TRANSITION) { //update
titlePos.x += imageDx;
playPos.x += imageDx;
exitPos.x += imageDx;
loadingPos.x += imageDx;
if (loadingPos.x <= ((ofGetWidth() / 2.0) - (loadingImage.getWidth() / 2.0)) ) {
loadState = LOAD; //finished transition
}
} else if (loadState == TOGAME) {
loadingPos.x += imageDx;
if (loadingPos.x <= (-loadingImage.getWidth())) loadState = END;
}
rightEmitter.numPars = max((int)(data->intensity*20) + (data->onBeat?12:0), 2);
rightEmitter.setVelocity(data->onBeat?ofVec3f(-510,0.0):ofVec3f(-310,0.0));
particleSystem->addParticles(logoEmitter);
particleSystem->addParticles(rightEmitter);
}
void TitleScene::draw(){
ofPushStyle();
if (loadState == TITLE || loadState == TRANSITION) {
title.draw(titlePos);
playButton.draw(playPos);
exitButton.draw(exitPos);
}
if (loadState != TITLE || loadState != END) loadingImage.draw(loadingPos);
ofPopStyle();
}
void TitleScene::windowResized(int w, int h) {
resetPosition();
}
bool TitleScene::isPlaySelected() {
return selectedIndex == 0;
}
//Toggle the variable flag
void TitleScene::setLoading(LoadState state) {
loadState = state;
if (loadState == TITLE) resetPosition();
}
TitleScene::LoadState TitleScene::getCurrentState() {
return loadState;
}
| 29.352459
| 117
| 0.63055
|
ccabrales
|
7508f423ff4f2dd47d6703130584e1bc6a1e2d1d
| 3,347
|
cpp
|
C++
|
project_booking_qt_gui/ProjectBookingQtUI/ProjectBookingQtUI/reports.cpp
|
VBota1/project_booking
|
13337130e1294df43c243cf1df53edfa736c42b7
|
[
"MIT"
] | null | null | null |
project_booking_qt_gui/ProjectBookingQtUI/ProjectBookingQtUI/reports.cpp
|
VBota1/project_booking
|
13337130e1294df43c243cf1df53edfa736c42b7
|
[
"MIT"
] | 2
|
2019-03-01T09:25:32.000Z
|
2019-03-01T09:26:08.000Z
|
project_booking_qt_gui/ProjectBookingQtUI/ProjectBookingQtUI/reports.cpp
|
VBota1/project_booking
|
13337130e1294df43c243cf1df53edfa736c42b7
|
[
"MIT"
] | null | null | null |
#include "reports.h"
Reports::Reports(QTreeWidget *month,QListWidget *standard,QListWidget *project,QLabel *current,StatusDisplay *statusWidget) {
monthReport=month;
standardReport=standard;
projectReport=project;
currentProject=current;
statusDisplay = statusWidget;
}
void Reports::updateMonthReport(BackendHandler backend, int month){
monthReport->clear();
Result< QList<Data> > report = backend.reportForMonth(month);
if (report.hasError)
{
statusDisplay->update(report.err());
return;
}
Data day;
foreach (day,report.ok()) {
QTreeWidgetItem *dayItem = new QTreeWidgetItem(monthReport);
monthReport->addTopLevelItem(dayItem);
dayItem->setText(0,day.date);
TaskDay task;
foreach (task,day.tasks) {
QTreeWidgetItem *taskItem = new QTreeWidgetItem(dayItem);
taskItem->setText(0,task.task);
QTreeWidgetItem *timeItem = new QTreeWidgetItem(taskItem);
timeItem->setText(0,"time_spent: " + task.time_spent);
QTreeWidgetItem *labelCollectionItem = new QTreeWidgetItem(taskItem);
labelCollectionItem->setText(0,"labels");
QString label;
foreach (label, task.labels) {
QTreeWidgetItem *labelItem = new QTreeWidgetItem(labelCollectionItem);
labelItem->setText(0, label);
}
}
}
}
void Reports::updateStandardReport(BackendHandler backend) {
standardReport->clear();
Result< QList<TaskReport> > report = backend.standardReport();
if (report.hasError)
{
statusDisplay->update(report.err());
return;
}
updateCurrentProject("None");
TaskReport task;
foreach (task,report.ok()){
QString taskText = "name: " + task.name.leftJustified(30,' ',true)
+ "\t time: " + task.time_spent + "\t labels:";
QString label;
foreach(label,task.labels)
taskText.append(" "+label);
if(task.clock_in_timestamp!="None")
{
taskText.append("\t clockedIn: "+task.clock_in_timestamp);
updateCurrentProject(task);
}
standardReport->addItem(taskText);
}
}
void Reports::updateCurrentProject(TaskReport task)
{
QString taskText = task.name + "\t labels:";
QString label;
foreach(label,task.labels)
taskText.append(" "+label);
updateCurrentProject(taskText);
}
void Reports::updateCurrentProject(QString task)
{
currentProject->setText("Active Project: "+task);
currentProject->update();
}
void Reports::updateProjectReport(BackendHandler backend) {
projectReport->clear();
Result< QList<LabelReport> > report = backend.projectLabelReport();
if (report.hasError)
{
statusDisplay->update(report.err());
return;
}
LabelReport project;
foreach(project,report.ok())
{
QString projectText = "project: " + project.label.leftJustified(30,' ',true)
+ "\t time: " + project.time_spent;
projectReport->addItem(projectText);
}
}
void Reports::refresh(){
BackendHandler backend;
updateMonthReport(backend, QDate::currentDate().month());
updateStandardReport(backend);
updateProjectReport(backend);
}
| 27.211382
| 125
| 0.632805
|
VBota1
|
7509db9a401daf1896cb04c933a014f57817ff92
| 362
|
hpp
|
C++
|
sources/dansandu/chocolate/interpolation.hpp
|
dansandu/chocolate
|
a90bf78a6891f578a7718329527ae56b502b57c2
|
[
"MIT"
] | null | null | null |
sources/dansandu/chocolate/interpolation.hpp
|
dansandu/chocolate
|
a90bf78a6891f578a7718329527ae56b502b57c2
|
[
"MIT"
] | null | null | null |
sources/dansandu/chocolate/interpolation.hpp
|
dansandu/chocolate
|
a90bf78a6891f578a7718329527ae56b502b57c2
|
[
"MIT"
] | null | null | null |
#pragma once
#include "dansandu/chocolate/common.hpp"
namespace dansandu::chocolate::interpolation
{
Vector3 interpolate(const Vector3& a, const Vector3& b, const float x, const float y, const float epsilon);
Vector3 interpolate(const Vector3& a, const Vector3& b, const Vector3& c, const float x, const float y,
const float epsilon);
}
| 25.857143
| 107
| 0.720994
|
dansandu
|
7511d416a4978fcd2aa044fd577ad9edd11ae6b8
| 1,495
|
hpp
|
C++
|
libcaf_core/caf/flow/step/map.hpp
|
seewpx/actor-framework
|
65ecf35317b81d7a211848d59e734f43483fe410
|
[
"BSD-3-Clause"
] | null | null | null |
libcaf_core/caf/flow/step/map.hpp
|
seewpx/actor-framework
|
65ecf35317b81d7a211848d59e734f43483fe410
|
[
"BSD-3-Clause"
] | null | null | null |
libcaf_core/caf/flow/step/map.hpp
|
seewpx/actor-framework
|
65ecf35317b81d7a211848d59e734f43483fe410
|
[
"BSD-3-Clause"
] | null | null | null |
// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in
// the main distribution directory for license terms and copyright or visit
// https://github.com/actor-framework/actor-framework/blob/master/LICENSE.
#pragma once
#include "caf/detail/type_traits.hpp"
#include "caf/fwd.hpp"
#include <utility>
namespace caf::flow::step {
template <class F>
class map {
public:
using trait = detail::get_callable_trait_t<F>;
static_assert(!std::is_same_v<typename trait::result_type, void>,
"map functions may not return void");
static_assert(trait::num_args == 1,
"map functions must take exactly one argument");
using input_type = std::decay_t<detail::tl_head_t<typename trait::arg_types>>;
using output_type = std::decay_t<typename trait::result_type>;
explicit map(F fn) : fn_(std::move(fn)) {
// nop
}
map(map&&) = default;
map(const map&) = default;
map& operator=(map&&) = default;
map& operator=(const map&) = default;
template <class Next, class... Steps>
bool on_next(const input_type& item, Next& next, Steps&... steps) {
return next.on_next(fn_(item), steps...);
}
template <class Next, class... Steps>
void on_complete(Next& next, Steps&... steps) {
next.on_complete(steps...);
}
template <class Next, class... Steps>
void on_error(const error& what, Next& next, Steps&... steps) {
next.on_error(what, steps...);
}
private:
F fn_;
};
} // namespace caf::flow::step
| 25.775862
| 80
| 0.671572
|
seewpx
|
75138d319658400837893d58e2aee8f95eb1f383
| 1,081
|
hpp
|
C++
|
libs/fnd/algorithm/include/bksge/fnd/algorithm/reverse.hpp
|
myoukaku/bksge
|
0f8b60e475a3f1709723906e4796b5e60decf06e
|
[
"MIT"
] | 4
|
2018-06-10T13:35:32.000Z
|
2021-06-03T14:27:41.000Z
|
libs/fnd/algorithm/include/bksge/fnd/algorithm/reverse.hpp
|
myoukaku/bksge
|
0f8b60e475a3f1709723906e4796b5e60decf06e
|
[
"MIT"
] | 566
|
2017-01-31T05:36:09.000Z
|
2022-02-09T05:04:37.000Z
|
libs/fnd/algorithm/include/bksge/fnd/algorithm/reverse.hpp
|
myoukaku/bksge
|
0f8b60e475a3f1709723906e4796b5e60decf06e
|
[
"MIT"
] | 1
|
2018-07-05T04:40:53.000Z
|
2018-07-05T04:40:53.000Z
|
/**
* @file reverse.hpp
*
* @brief reverse の定義
*
* @author myoukaku
*/
#ifndef BKSGE_FND_ALGORITHM_REVERSE_HPP
#define BKSGE_FND_ALGORITHM_REVERSE_HPP
#include <bksge/fnd/algorithm/config.hpp>
#if defined(BKSGE_USE_STD_ALGORITHM)
#include <algorithm>
namespace bksge
{
using std::reverse;
} // namespace bksge
#else
#include <bksge/fnd/algorithm/iter_swap.hpp>
#include <bksge/fnd/config.hpp>
namespace bksge
{
/**
* @brief 要素の並びを逆にする。
*
* @tparam BidirectionalIterator
*
* @param first
* @param last
*
* @require *first は Swappable でなければならない
*
* @effect 0 以上 (last - first) / 2 未満の整数 i について、
* iter_swap(first + i, (last - i) - 1) を行う
*
* @complexity 正確に (last - first) / 2 回 swap する
*/
template <typename BidirectionalIterator>
inline void
reverse(
BidirectionalIterator first,
BidirectionalIterator last)
{
for (; first != last && first != --last; ++first)
{
bksge::iter_swap(first, last);
}
}
} // namespace bksge
#endif
#endif // BKSGE_FND_ALGORITHM_REVERSE_HPP
| 16.630769
| 51
| 0.650324
|
myoukaku
|
7518a26a3f9a48b498a5a0f719682f3753612846
| 3,880
|
cc
|
C++
|
src/tot_compare.cc
|
Mu2e/TrackerMCTune
|
6472497f9359b33a236d47f39192a7faffc71dae
|
[
"Apache-2.0"
] | null | null | null |
src/tot_compare.cc
|
Mu2e/TrackerMCTune
|
6472497f9359b33a236d47f39192a7faffc71dae
|
[
"Apache-2.0"
] | 1
|
2021-12-03T14:37:41.000Z
|
2021-12-03T14:37:41.000Z
|
src/tot_compare.cc
|
Mu2e/TrackerMCTune
|
6472497f9359b33a236d47f39192a7faffc71dae
|
[
"Apache-2.0"
] | 2
|
2019-10-31T18:17:00.000Z
|
2021-11-22T21:43:02.000Z
|
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <stdlib.h>
#include <vector>
#include <TFile.h>
#include <TTree.h>
#include <TH1F.h>
#include <TH2F.h>
#include <TF1.h>
#include <TCanvas.h>
#include <TLegend.h>
#include <TApplication.h>
#include <TLatex.h>
#include <TLine.h>
#include <TPaveText.h>
#include <TMath.h>
#include <TProfile.h>
int main(int argc, char** argv)
{
std::string filename[2];
filename[0] = "";
filename[1] = "";
std::string help = "./tot_compare -d <data filename> -s <sim filename>";
std::string inputcommand = std::string(argv[0]);
for (int i=1;i<argc;i++)
inputcommand += " " + std::string(argv[i]);
int c;
while ((c = getopt (argc, argv, "hd:s:")) != -1){
switch (c){
case 'h':
std::cout << help << std::endl;
return 0;
case 'd':
filename[0] = std::string(optarg);
break;
case 's':
filename[1] = std::string(optarg);
break;
case '?':
if (optopt == 'd' || optopt == 's')
std::cout << "Option -" << optopt << " requires an argument." << std::endl;
else
std::cout << "Unknown option `-" << optopt << "'." << std::endl;
return 1;
}
}
if (filename[0].size() == 0 && filename[1].size() == 0 && optind == argc-2){
for (int index = optind; index < argc; index++){
filename[index-optind] = std::string(argv[index]);
}
}
if (filename[0].size() == 0 || filename[1].size() == 0){
std::cout << help << std::endl;
return 1;
}
int argc2 = 0;char **argv2;TApplication theApp("tapp", &argc2, argv2);
std::vector<double> times[2];
std::vector<double> docas[2];
std::vector<double> tots[2];
TH2F* h[2];
for (int ifile=0;ifile<2;ifile++){
TFile *f = new TFile(filename[ifile].c_str());
TTree *t = (TTree*) f->Get("tot");
double t_time, t_tot, t_doca;
t->SetBranchAddress("tot",&t_tot);
t->SetBranchAddress("time",&t_time);
t->SetBranchAddress("doca",&t_doca);
for (int i=0;i<t->GetEntries();i++){
t->GetEntry(i);
tots[ifile].push_back(t_tot);
times[ifile].push_back(t_time);
docas[ifile].push_back(t_doca);
}
h[ifile] = new TH2F(TString::Format("tot_%d",ifile),"tot",32,0,64,120,-20,100);
for (int j=0;j<tots[ifile].size();j++){
if (docas[ifile][j] < 2.5)
h[ifile]->Fill(tots[ifile][j],times[ifile][j]);
}
}
TCanvas *cscatter = new TCanvas("cscatter","scatter",600,600);
h[0]->SetStats(0);
h[0]->SetTitle("");
h[0]->GetXaxis()->SetTitle("Time over threshold (ns)");
h[0]->GetYaxis()->SetTitle("Drift time (ns)");
h[0]->Draw();
h[1]->SetMarkerColor(kRed);
h[1]->Draw("same");
TLegend *l = new TLegend(0.55,0.65,0.85,0.85);
l->AddEntry(h[0],"8-Straw Prototype Data","P");
l->AddEntry(h[1],"G4 + Straw Simulation","P");
l->SetBorderSize(0);
l->Draw();
TCanvas *chist = new TCanvas("chist","chist",600,600);
TProfile *hdata = (TProfile*) h[0]->ProfileX("hdata",1,-1,"S");
TProfile *hsim = (TProfile*) h[1]->ProfileX("hsim",1,-1,"S");
hdata->SetLineColor(kBlue);
hdata->SetTitle("");
hdata->SetStats(0);
hdata->GetXaxis()->SetTitle("Time over threshold (ns)");
hdata->GetYaxis()->SetTitle("Drift time (ns)");
hdata->SetMarkerStyle(22);
// hdata->GetXaxis()->SetRangeUser(4,50);
hdata->Draw();
hsim->SetLineColor(kRed);
hsim->SetFillColor(kRed);
hsim->SetMarkerColor(kRed);
hsim->SetFillStyle(3001);
hsim->Draw("same E2");
TProfile *hsim2 = (TProfile*) hsim->Clone("hsim2");
hsim2->SetLineColor(kRed);
hsim2->SetFillStyle(0);
hsim2->Draw("hist same");
TLegend *l2 = new TLegend(0.55,0.65,0.85,0.85);
l2->AddEntry(hdata,"8-Straw Prototype Data","PL");
l2->AddEntry(hsim,"G4 + Straw Simulation","FL");
l2->SetBorderSize(0);
l2->Draw();
theApp.Run();
return 0;
}
| 26.575342
| 85
| 0.584794
|
Mu2e
|
751f699db40b8db0c4cffb7c35b3f5337e15d5f6
| 1,868
|
cpp
|
C++
|
problems/codejam/2016/2/rather-perplexing-showdown/code.cpp
|
brunodccarvalho/competitive
|
4177c439174fbe749293b9da3445ce7303bd23c2
|
[
"MIT"
] | 7
|
2020-10-15T22:37:10.000Z
|
2022-02-26T17:23:49.000Z
|
problems/codejam/2016/2/rather-perplexing-showdown/code.cpp
|
brunodccarvalho/competitive
|
4177c439174fbe749293b9da3445ce7303bd23c2
|
[
"MIT"
] | null | null | null |
problems/codejam/2016/2/rather-perplexing-showdown/code.cpp
|
brunodccarvalho/competitive
|
4177c439174fbe749293b9da3445ce7303bd23c2
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
// *****
string make(int P, int R, int S) {
assert(P >= 0 && R >= 0 && S >= 0);
if (P + R + S == 1) {
if (P == 1)
return "P";
if (R == 1)
return "R";
if (S == 1)
return "S";
assert(false);
}
int a = (P + R + S) / 2 - S; // P vs R -> P (write PR)
int b = (P + R + S) / 2 - P; // R vs S -> R (write RS)
int c = (P + R + S) / 2 - R; // S vs P -> S (write PS)
if (a < 0 || b < 0 || c < 0)
return "";
auto s = make(a, b, c);
if (s.empty())
return "";
string w;
for (char p : s)
if (p == 'P')
w += "RP";
else if (p == 'R')
w += "SR";
else
w += "SP";
return w;
}
auto get(int N, int P, int R, int S) {
int M = P + R + S;
assert(M == (1 << N));
auto s = make(P, R, S);
if (s.empty())
return "IMPOSSIBLE"s;
for (int n = 1; n < M; n <<= 1) {
for (int i = 0; i < M; i += 2 * n) {
auto a = s.substr(i, n), b = s.substr(i + n, n);
if (a > b) {
s.replace(i, n, b);
s.replace(i + n, n, a);
}
}
}
return s;
}
void test() {
for (int N = 1; N <= 3; N++) {
for (int M = 1 << N, P = 0; P <= M; P++) {
for (int R = 0, S = M - P - R; P + R <= M; R++, S--) {
printf("%d %2d %2d %2d -- %s\n", N, P, R, S, get(N, P, R, S).data());
}
}
}
}
auto solve() {
int N, P, R, S;
cin >> N >> P >> R >> S;
return get(N, P, R, S);
}
// *****
int main() {
// test();
unsigned T;
cin >> T >> ws;
for (unsigned t = 1; t <= T; ++t) {
auto solution = solve();
cout << "Case #" << t << ": " << solution << '\n';
}
return 0;
}
| 21.72093
| 85
| 0.336188
|
brunodccarvalho
|
752307c05d9b1adb8aa85249d908665b5ecf029f
| 2,565
|
hpp
|
C++
|
src/common/thread.hpp
|
longlonghands/fps-challenge
|
020c133a782285364d52b1c98e9661c9aedfd96d
|
[
"MIT"
] | null | null | null |
src/common/thread.hpp
|
longlonghands/fps-challenge
|
020c133a782285364d52b1c98e9661c9aedfd96d
|
[
"MIT"
] | null | null | null |
src/common/thread.hpp
|
longlonghands/fps-challenge
|
020c133a782285364d52b1c98e9661c9aedfd96d
|
[
"MIT"
] | null | null | null |
#pragma once
#include <functional>
#include <memory>
#include <stdexcept>
#include <thread>
namespace common { namespace async {
void sleep(int ms);
/// This class implements a platform-independent
/// wrapper around an operating system thread.
class Thread {
public:
typedef std::shared_ptr<Thread> Ptr;
Thread();
virtual ~Thread();
// call the OS to start the thread
bool start(std::function<void()> target);
bool start(std::function<void(void *)> target, void *arg);
// Waits until the thread exits.
void join();
// Waits until the thread exits.
// The thread should be canceled before calling this method.
// This method must be called from outside the current thread
// context or deadlock will ensue.
bool waitForExit(int timeout = 5000);
// Returns the native thread ID.
std::thread::id id() const;
// Returns the native thread ID of the current thread.
static std::thread::id currentID();
bool isStarted() const;
bool isRunning() const;
protected:
// The context which we send to the thread context.
// This allows us to gracefully handle late callbacks
// and avoid the need for deferred destruction of Runner objects.
struct Context {
typedef Context *ptr;
bool threadIsAlive;
bool OwnerIsAlive;
// Thread-safe POD members
// May be accessed at any time
std::string tid;
bool started;
bool running;
// Non thread-safe members
// Should not be accessed once the Runner is started
std::function<void()> target;
std::function<void(void *)> target1;
void *arg;
// The implementation is responsible for resetting
// the context if it is to be reused.
void reset() {
OwnerIsAlive = true;
threadIsAlive = false;
tid = "";
arg = nullptr;
target = nullptr;
target1 = nullptr;
started = false;
running = false;
}
Context() {
reset();
}
~Context() {
// printf("\ncontext deleting ...\n");
}
};
bool startAsync();
static void runAsync(Context::ptr context);
Thread(const Thread &) = delete;
Thread &operator=(const Thread &) = delete;
Context::ptr m_context;
std::unique_ptr<std::thread> m_handle;
};
}} // namespace tidy::async
| 26.173469
| 71
| 0.579337
|
longlonghands
|
97094f6541bda09c47adf1bc12acd753f4e0a99b
| 1,307
|
cpp
|
C++
|
test/dataalign/test_dataalign.cpp
|
fox000002/ulib-win
|
628c4a0b8193d1ad771aa85598776ff42a45f913
|
[
"Apache-2.0"
] | 4
|
2016-09-07T07:02:52.000Z
|
2019-06-22T08:55:53.000Z
|
test/dataalign/test_dataalign.cpp
|
fox000002/ulib-win
|
628c4a0b8193d1ad771aa85598776ff42a45f913
|
[
"Apache-2.0"
] | null | null | null |
test/dataalign/test_dataalign.cpp
|
fox000002/ulib-win
|
628c4a0b8193d1ad771aa85598776ff42a45f913
|
[
"Apache-2.0"
] | 3
|
2019-06-22T16:00:39.000Z
|
2022-03-09T13:46:27.000Z
|
#include <stdio.h>
#include <windows.h>
int mswindows_handle_hardware_exceptions (DWORD code)
{
printf("Handling exception\n");
if (code == STATUS_DATATYPE_MISALIGNMENT)
{
printf("misalignment fault!\n");
return EXCEPTION_EXECUTE_HANDLER;
}
else
return EXCEPTION_CONTINUE_SEARCH;
}
void test()
{
__try {
char temp[10];
memset(temp, 0, 10);
double *val;
val = (double *)(&temp[3]);
printf("%lf\n", *val);
}
__except(mswindows_handle_hardware_exceptions (GetExceptionCode ()))
{}
}
int main()
{
char a;
char b;
class S1
{
public:
char m_1; // 1-byte element
// 3-bytes of padding are placed here
int m_2; // 4-byte element
double m_3, m_4; // 8-byte elements
};
S1 x;
long y;
S1 z[5];
printf("sizeof S1 : %d\n\n", sizeof(S1));
printf("a = %p\n", &a);
printf("b = %p\n", &b);
printf("x = %p\n", &x);
printf("x.m_1 = %p\n", &x.m_1);
printf("x.m_2 = %p\n", &x.m_2);
printf("x.m_3 = %p\n", &x.m_3);
printf("x.m_4 = %p\n", &x.m_4);
printf("y = %p\n", &y);
printf("z[0] = %p\n", z);
printf("z[1] = %p\n", &z[1]);
test();
return 0;
}
| 20.107692
| 72
| 0.497322
|
fox000002
|
9709fcca401e1a7f071545e31f5dc431f22736ac
| 7,362
|
cpp
|
C++
|
src/engine/private/rendererandroid.cpp
|
dream-overflow/o3d
|
087ab870cc0fd9091974bb826e25c23903a1dde0
|
[
"FSFAP"
] | 2
|
2019-06-22T23:29:44.000Z
|
2019-07-07T18:34:04.000Z
|
src/engine/private/rendererandroid.cpp
|
dream-overflow/o3d
|
087ab870cc0fd9091974bb826e25c23903a1dde0
|
[
"FSFAP"
] | null | null | null |
src/engine/private/rendererandroid.cpp
|
dream-overflow/o3d
|
087ab870cc0fd9091974bb826e25c23903a1dde0
|
[
"FSFAP"
] | null | null | null |
/**
* @file rendererandroid.cpp
* @brief
* @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org)
* @date 2017-12-09
* @copyright Copyright (c) 2001-2017 Dream Overflow. All rights reserved.
* @details
*/
#include "o3d/engine/precompiled.h"
#include "o3d/engine/renderer.h"
// ONLY IF O3D_ANDROID IS SELECTED
#ifdef O3D_ANDROID
#include "o3d/engine/glextdefines.h"
#include "o3d/engine/glextensionmanager.h"
#include "o3d/core/gl.h"
#include "o3d/engine/context.h"
#include "o3d/core/appwindow.h"
#include "o3d/core/application.h"
#include "o3d/core/debug.h"
#ifdef O3D_EGL
#include "o3d/core/private/egldefines.h"
#include "o3d/core/private/egl.h"
#endif
using namespace o3d;
// Create the OpenGL context.
void Renderer::create(AppWindow *appWindow, Bool debug, Renderer *sharing)
{
if (m_state.getBit(STATE_DEFINED)) {
O3D_ERROR(E_InvalidPrecondition("The renderer is already initialized"));
}
if (!appWindow || (appWindow->getHWND() == NULL_HWND)) {
O3D_ERROR(E_InvalidParameter("Invalid application window"));
}
if ((sharing != nullptr) && m_sharing) {
O3D_ERROR(E_InvalidOperation("A shared renderer cannot be sharing"));
}
O3D_MESSAGE("Creating a new OpenGLES context...");
if (GL::getImplementation() == GL::IMPL_EGL) {
//
// EGL implementation
//
#ifdef O3D_EGL
EGLDisplay eglDisplay = EGL::getDisplay(reinterpret_cast<EGLNativeDisplayType>(Application::getDisplay()));
EGLSurface eglSurface = reinterpret_cast<EGLSurface>(appWindow->getHDC());
EGLConfig eglConfig = reinterpret_cast<EGLConfig>(appWindow->getPixelFormat());
// EGL_CONTEXT_OPENGL_DEBUG
EGLint contextAttributes[] = {
/*EGL_CONTEXT_MAJOR_VERSION_KHR*/EGL_CONTEXT_CLIENT_VERSION, 3,
/* EGL_CONTEXT_MINOR_VERSION_KHR, 2,*/
debug ? EGL_CONTEXT_FLAGS_KHR : EGL_NONE, debug ? EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR : EGL_NONE,
// debug ? EGL_CONTEXT_FLAGS_KHR : EGL_NONE, debug ? EGL_CONTEXT_OPENGL_DEBUG : EGL_NONE,
EGL_NONE
};
EGLContext eglContext = eglCreateContext(
eglDisplay,
eglConfig,
sharing ? reinterpret_cast<EGLContext>(sharing->getHGLRC()) : EGL_NO_CONTEXT,
contextAttributes);
if (eglContext == EGL_NO_CONTEXT) {
O3D_ERROR(E_InvalidResult("Unable to create the OpenGLES context"));
}
EGL::makeCurrent(eglDisplay, eglSurface, eglSurface, eglContext);
m_HDC = appWindow->getHDC();
m_HGLRC = reinterpret_cast<_HGLRC>(eglContext);
m_state.enable(STATE_DEFINED);
m_state.enable(STATE_EGL);
#else
O3D_ERROR(E_UnsuportedFeature("Support for EGL is missing"));
#endif
} else {
O3D_ERROR(E_UnsuportedFeature("Support for EGL only"));
}
GLExtensionManager::init();
O3D_MESSAGE("Video renderer: " + getRendererName());
O3D_MESSAGE("OpenGL version: " + getVersionName());
computeVersion();
m_appWindow = appWindow;
m_bpp = appWindow->getBpp();
m_depth = appWindow->getDepth();
m_stencil = appWindow->getStencil();
m_samples = appWindow->getSamples();
if (sharing) {
m_sharing = sharing;
m_sharing->m_shareCount++;
}
if (debug) {
initDebug();
}
m_glContext = new Context(this);
doAttachment(m_appWindow);
}
// delete the renderer
void Renderer::destroy()
{
if (m_state.getBit(STATE_DEFINED)) {
if (m_refCount > 0) {
O3D_ERROR(E_InvalidPrecondition("Unable to destroy a referenced renderer"));
}
if (m_shareCount > 0) {
O3D_ERROR(E_InvalidPrecondition("All shared renderer must be destroyed before"));
}
// unshare
if (m_sharing) {
m_sharing->m_shareCount--;
if (m_sharing->m_shareCount < 0) {
O3D_ERROR(E_InvalidResult("Share counter reference is negative"));
}
m_sharing = nullptr;
}
deletePtr(m_glContext);
if (m_HGLRC && m_appWindow) {
if (m_state.getBit(STATE_EGL)) {
#ifdef O3D_EGL
EGLDisplay eglDisplay = EGL::getDisplay(reinterpret_cast<EGLNativeDisplayType>(Application::getDisplay()));
EGL::makeCurrent(eglDisplay, 0, 0, 0);
EGL::destroyContext(eglDisplay, reinterpret_cast<EGLContext>(m_HGLRC));
#endif
}
m_HGLRC = NULL_HGLRC;
}
m_HDC = NULL_HDC;
m_depth = m_bpp = m_stencil = m_samples = 0;
m_state.zero();
m_version = 0;
if (m_appWindow) {
disconnect(m_appWindow);
m_appWindow = nullptr;
}
m_glErrno = GL_NO_ERROR;
}
}
void *Renderer::getProcAddress(const Char *ext) const
{
return EGL::getProcAddress(ext);
}
// Is it the current OpenGL context.
Bool Renderer::isCurrent() const
{
if (!m_state.getBit(STATE_DEFINED)) {
return False;
}
if (m_state.getBit(STATE_EGL)) {
#ifdef O3D_EGL
return EGL::getCurrentContext() == reinterpret_cast<EGLContext>(m_HGLRC);
#endif
} else {
return False;
}
}
// Set as current OpenGL context
void Renderer::setCurrent()
{
if (!m_state.getBit(STATE_DEFINED)) {
return;
}
if (m_state.getBit(STATE_EGL)) {
#ifdef O3D_EGL
if (EGL::getCurrentContext() == reinterpret_cast<EGLContext>(m_HGLRC)) {
return;
}
EGLDisplay eglDisplay = EGL::getDisplay(reinterpret_cast<EGLNativeDisplayType>(Application::getDisplay()));
if (EGL::makeCurrent(
eglDisplay,
reinterpret_cast<EGLSurface>(m_HDC),
reinterpret_cast<EGLSurface>(m_HDC),
reinterpret_cast<EGLContext>(m_HGLRC))) {
O3D_ERROR(E_InvalidResult("Unable to set the current OpenGL context"));
}
#else
O3D_ERROR(E_InvalidResult("Unable to set the current OpenGL context"));
#endif
} else {
O3D_ERROR(E_InvalidResult("Unable to set the current OpenGL context"));
}
}
Bool Renderer::setVSyncMode(VSyncMode mode)
{
if (!m_state.getBit(STATE_DEFINED)) {
return False;
}
int value = 0;
if (mode == VSYNC_NONE) {
value = 0;
} else if (mode == VSYNC_YES) {
value = 1;
} else if (mode == VSYNC_ADAPTIVE) {
value = -1;
}
if (m_state.getBit(STATE_EGL)) {
#ifdef O3D_EGL
EGLDisplay eglDisplay = EGL::getDisplay(reinterpret_cast<EGLNativeDisplayType>(Application::getDisplay()));
if (!EGL::swapInterval(eglDisplay, value)) {
return False;
}
#else
return False;
#endif
} else {
return False;
}
if (mode == VSYNC_NONE) {
m_state.setBit(STATE_VSYNC, False);
m_state.setBit(STATE_ADAPTIVE_VSYNC, False);
} else if (mode == VSYNC_YES) {
m_state.setBit(STATE_VSYNC, True);
m_state.setBit(STATE_ADAPTIVE_VSYNC, False);
} else if (mode == VSYNC_ADAPTIVE) {
m_state.setBit(STATE_VSYNC, True);
m_state.setBit(STATE_ADAPTIVE_VSYNC, True);
}
return True;
}
#endif // O3D_ANDROID
| 27.470149
| 123
| 0.619669
|
dream-overflow
|
970a0dc9bef87e899dc9a929f4a47aa138c8dc3b
| 3,481
|
cpp
|
C++
|
Codility_CommonPrimerDivisor.cpp
|
CharlieGearsTech/Codility
|
b0c4355eb68f05f24390075e3fe2fe555d40b6b9
|
[
"MIT"
] | 1
|
2021-01-31T22:59:59.000Z
|
2021-01-31T22:59:59.000Z
|
Codility_CommonPrimerDivisor.cpp
|
CharlieGearsTech/Codility
|
b0c4355eb68f05f24390075e3fe2fe555d40b6b9
|
[
"MIT"
] | null | null | null |
Codility_CommonPrimerDivisor.cpp
|
CharlieGearsTech/Codility
|
b0c4355eb68f05f24390075e3fe2fe555d40b6b9
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <assert.h>
#include <math.h>
#include <vector>
#include <algorithm>
#include <numeric>
#include <map>
#include <deque>
#include <stdlib.h>
#include <string>
#include <set>
#include <vector>
#include <new>
#include <memory>
using namespace std;
/*Crea un arreglo en la que los indices muestran el numero divisible de la secuencia y el valor es el numero divisor*/
map<int,int> prepareArrayFactor(int n)
{
map<int,int> f;
auto i = 2u;
/*Rango para numeros que pueden dividir a N*/
while(i+i <=(size_t)n)
{
auto k=i*i;
while(k <= (size_t)n)
{
f[k] = i;
k+=i;
}
i++;
}
return f;
}
/* Encontrar los numeros que multiplicados nos dan a X, X debe de ser un numero menor al tamaño de A*/
vector<int> factorization(int x, map<int,int>& A)
{
vector<int> primeFactors;
/*Revisar unicamente numeros que son divisibles*/
while(A[x] > 0)
{
/*Agregar el divisor a la lista de factorizacion*/
primeFactors.push_back(A[x]);
/* Dividir para disminuir el numero divisible en un factor menor.*/
x /= A[x];
}
/*Agregar el ultimo numero divisor.*/
primeFactors.push_back(x);
return primeFactors;
}
/*Esta solucion se basa en usar la formula de factorizacion que nos devuelve un contenedor con todos los factores de X numero, despues de eso comparamos los arreglos iguales. Uso set para organizar y hacer unicos los factores.*/
int solution(vector<int> &A, vector<int> &B)
{
auto N=A.size();
set<int> holder;
copy(A.begin(),A.end(),inserter(holder,holder.begin()));
copy(B.begin(),B.end(),inserter(holder,holder.begin()));
int max_element=*holder.rbegin();
//O(logN)
auto maxFactorArray=prepareArrayFactor(max_element);
int count=0;
//O(n*logn*logn)
for(auto k=0u; k<N; ++k)
{
auto Afactor=factorization(A[k],maxFactorArray);
auto Bfactor=factorization(B[k],maxFactorArray);
set<int> AfactorSet;
set<int> BfactorSet;
copy(Afactor.begin(),Afactor.end(),inserter(AfactorSet,AfactorSet.begin()));
copy(Bfactor.begin(),Bfactor.end(),inserter(BfactorSet,BfactorSet.begin()));
if(std::equal(AfactorSet.begin(),AfactorSet.end(),BfactorSet.begin()))
++count;
}
return count;
}
/*Imprimir vector<int>s*/
void printV(vector<int>& vRes)
{
for(auto it= vRes.begin(); it != vRes.end();++it)
{
cout<<*it<<"\t";
}
cout<<endl;
}
/*Assertion de vectores de ints*/
void assertV( vector<int>& result, vector<int>&& comp)
{
bool res = std::equal(result.begin(),result.end(),comp.begin());
assert(res);
}
int main()
{
int result;
vector<int> a;
vector<int> b;
a={15,10,3};
b={75,30,5};
result=solution(a,b);
cout<<result<<endl;
assert(result==1);
a.clear();
b.clear();
a={15};
b={75};
result=solution(a,b);
cout<<result<<endl;
assert(result==1);
a.clear();
b.clear();
a={12,12,18};
b={24,25,9};
result=solution(a,b);
cout<<result<<endl;
assert(result==1);
a.clear();
b.clear();
/*This algorithm is unable to execute large number since it allocates all the prime divisor for each element*/
// a={2147483647};
// b={2147483647};
// result=solution(a,b);
// cout<<result<<endl;
// assert(result==1);
// a.clear();
// b.clear();
return 0;
}
| 23.362416
| 228
| 0.607871
|
CharlieGearsTech
|
970df27bbd8f99dc06963233fda0aa18d6bbaf7f
| 2,258
|
hpp
|
C++
|
include/rllib/bundle/Bundle.hpp
|
loriswit/rllib
|
a09a73f8ac353db76454007b2ec95bf438c0fc1a
|
[
"MIT"
] | 1
|
2022-02-15T17:49:44.000Z
|
2022-02-15T17:49:44.000Z
|
include/rllib/bundle/Bundle.hpp
|
loriswit/rllib
|
a09a73f8ac353db76454007b2ec95bf438c0fc1a
|
[
"MIT"
] | null | null | null |
include/rllib/bundle/Bundle.hpp
|
loriswit/rllib
|
a09a73f8ac353db76454007b2ec95bf438c0fc1a
|
[
"MIT"
] | null | null | null |
#ifndef RLLIB_BUNDLE_HPP
#define RLLIB_BUNDLE_HPP
#include <string>
#include <rllib/stream/ByteStream.hpp>
#include <rllib/bundle/FileProperties.hpp>
namespace rl
{
/**
* A bundle is a collection of files packed in a big single file. It is used to store all the game assets.
* In particular, this is where scene are being extracted from the game.
*/
class RL_API Bundle
{
public:
/**
* Creates an empty bundle.
*/
Bundle() = default;
/**
* Creates a bundle loaded from a file.
*
* @param path The path to the bundle file
*/
explicit Bundle(FilePath path);
/**
* Load the bundle from a file.
*
* @param path The path to the bundle file
*/
void load(FilePath path);
/**
* Reads a file in the bundle and returns its content.
*
* @param path The path to the file in the bundle
* @return The content of the file
*/
ByteStream readFile(const FilePath & path) const;
/**
* Overwrites a file in the bundle.
* The file path must already exist in the bundle.
*
* @warning The original content will be lost.
*
* @param path The path to the file in the bundle
* @param data The data that is to be written
*/
void writeFile(const FilePath & path, const ByteStream & data);
/**
* Creates a new bundle file and returns its instance.
*
* @param bundlePath The path to the new bundle file that is to be created
* @param files A list of pairs containing file paths with associated contents
* @return The instance of the new bundle
*/
static Bundle create(FilePath bundlePath, const std::vector<std::pair<FilePath, ByteStream>> & files);
private:
/**
* Finds a file in the bundle index and returns its properties.
*
* @param path The path to the file in the bundle
* @return A pair containing the file properties and the offset of the properties
*/
const std::pair<FileProperties, std::streampos> & findFile(const FilePath & path) const;
FilePath m_path;
std::vector<std::pair<FileProperties, std::streampos>> m_fileList;
std::size_t m_baseOffset = 0;
};
} // namespace rl
#endif //RLLIB_BUNDLE_HPP
| 27.204819
| 106
| 0.647476
|
loriswit
|
9710f58c33f0561bfe2070f30e4e86b72d6a9a41
| 10,075
|
cc
|
C++
|
squid/squid3-3.3.8.spaceify/src/auth/negotiate/auth_negotiate.cc
|
spaceify/spaceify
|
4296d6c93cad32bb735cefc9b8157570f18ffee4
|
[
"MIT"
] | 4
|
2015-01-20T15:25:34.000Z
|
2017-12-20T06:47:42.000Z
|
squid/squid3-3.3.8.spaceify/src/auth/negotiate/auth_negotiate.cc
|
spaceify/spaceify
|
4296d6c93cad32bb735cefc9b8157570f18ffee4
|
[
"MIT"
] | 4
|
2015-05-15T09:32:55.000Z
|
2016-02-18T13:43:31.000Z
|
squid/squid3-3.3.8.spaceify/src/auth/negotiate/auth_negotiate.cc
|
spaceify/spaceify
|
4296d6c93cad32bb735cefc9b8157570f18ffee4
|
[
"MIT"
] | null | null | null |
/*
* DEBUG: section 29 Negotiate Authenticator
* AUTHOR: Robert Collins, Henrik Nordstrom, Francesco Chemolli
*
* SQUID Web Proxy Cache http://www.squid-cache.org/
* ----------------------------------------------------------
*
* Squid is the result of efforts by numerous individuals from
* the Internet community; see the CONTRIBUTORS file for full
* details. Many organizations have provided support for Squid's
* development; see the SPONSORS file for full details. Squid is
* Copyrighted (C) 2001 by the Regents of the University of
* California; see the COPYRIGHT file for full details. Squid
* incorporates software developed and/or copyrighted by other
* sources; see the CREDITS file for full details.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
*
*/
/* The functions in this file handle authentication.
* They DO NOT perform access control or auditing.
* See acl.c for access control and client_side.c for auditing */
#include "squid.h"
#include "auth/negotiate/auth_negotiate.h"
#include "auth/Gadgets.h"
#include "auth/State.h"
#include "cache_cf.h"
#include "mgr/Registration.h"
#include "Store.h"
#include "client_side.h"
#include "HttpHeaderTools.h"
#include "HttpReply.h"
#include "HttpRequest.h"
#include "SquidTime.h"
#include "auth/negotiate/Scheme.h"
#include "auth/negotiate/User.h"
#include "auth/negotiate/UserRequest.h"
#include "wordlist.h"
/**
\defgroup AuthNegotiateInternal Negotiate Authenticator Internals
\ingroup AuthNegotiateAPI
*/
/* Negotiate Scheme */
static AUTHSSTATS authenticateNegotiateStats;
/// \ingroup AuthNegotiateInternal
statefulhelper *negotiateauthenticators = NULL;
/// \ingroup AuthNegotiateInternal
static int authnegotiate_initialised = 0;
/// \ingroup AuthNegotiateInternal
static hash_table *proxy_auth_cache = NULL;
/*
*
* Private Functions
*
*/
void
Auth::Negotiate::Config::rotateHelpers()
{
/* schedule closure of existing helpers */
if (negotiateauthenticators) {
helperStatefulShutdown(negotiateauthenticators);
}
/* NP: dynamic helper restart will ensure they start up again as needed. */
}
void
Auth::Negotiate::Config::done()
{
authnegotiate_initialised = 0;
if (negotiateauthenticators) {
helperStatefulShutdown(negotiateauthenticators);
}
if (!shutting_down)
return;
delete negotiateauthenticators;
negotiateauthenticators = NULL;
if (authenticateProgram)
wordlistDestroy(&authenticateProgram);
debugs(29, DBG_IMPORTANT, "Reconfigure: Negotiate authentication configuration cleared.");
}
void
Auth::Negotiate::Config::dump(StoreEntry * entry, const char *name, Auth::Config * scheme)
{
wordlist *list = authenticateProgram;
storeAppendPrintf(entry, "%s %s", name, "negotiate");
while (list != NULL) {
storeAppendPrintf(entry, " %s", list->key);
list = list->next;
}
storeAppendPrintf(entry, "\n%s negotiate children %d startup=%d idle=%d concurrency=%d\n",
name, authenticateChildren.n_max, authenticateChildren.n_startup, authenticateChildren.n_idle, authenticateChildren.concurrency);
storeAppendPrintf(entry, "%s %s keep_alive %s\n", name, "negotiate", keep_alive ? "on" : "off");
}
Auth::Negotiate::Config::Config() : keep_alive(1)
{ }
void
Auth::Negotiate::Config::parse(Auth::Config * scheme, int n_configured, char *param_str)
{
if (strcasecmp(param_str, "program") == 0) {
if (authenticateProgram)
wordlistDestroy(&authenticateProgram);
parse_wordlist(&authenticateProgram);
requirePathnameExists("auth_param negotiate program", authenticateProgram->key);
} else if (strcasecmp(param_str, "children") == 0) {
authenticateChildren.parseConfig();
} else if (strcasecmp(param_str, "keep_alive") == 0) {
parse_onoff(&keep_alive);
} else {
debugs(29, DBG_CRITICAL, "ERROR: unrecognised Negotiate auth scheme parameter '" << param_str << "'");
}
}
const char *
Auth::Negotiate::Config::type() const
{
return Auth::Negotiate::Scheme::GetInstance()->type();
}
/**
* Initialize helpers and the like for this auth scheme.
* Called AFTER parsing the config file
*/
void
Auth::Negotiate::Config::init(Auth::Config * scheme)
{
if (authenticateProgram) {
authnegotiate_initialised = 1;
if (negotiateauthenticators == NULL)
negotiateauthenticators = new statefulhelper("negotiateauthenticator");
if (!proxy_auth_cache)
proxy_auth_cache = hash_create((HASHCMP *) strcmp, 7921, hash_string);
assert(proxy_auth_cache);
negotiateauthenticators->cmdline = authenticateProgram;
negotiateauthenticators->childs.updateLimits(authenticateChildren);
negotiateauthenticators->ipc_type = IPC_STREAM;
helperStatefulOpenServers(negotiateauthenticators);
}
}
void
Auth::Negotiate::Config::registerWithCacheManager(void)
{
Mgr::RegisterAction("negotiateauthenticator",
"Negotiate User Authenticator Stats",
authenticateNegotiateStats, 0, 1);
}
bool
Auth::Negotiate::Config::active() const
{
return authnegotiate_initialised == 1;
}
bool
Auth::Negotiate::Config::configured() const
{
if (authenticateProgram && (authenticateChildren.n_max != 0)) {
debugs(29, 9, HERE << "returning configured");
return true;
}
debugs(29, 9, HERE << "returning unconfigured");
return false;
}
/* Negotiate Scheme */
void
Auth::Negotiate::Config::fixHeader(Auth::UserRequest::Pointer auth_user_request, HttpReply *rep, http_hdr_type reqType, HttpRequest * request)
{
if (!authenticateProgram)
return;
/* Need keep-alive */
if (!request->flags.proxyKeepalive && request->flags.mustKeepalive)
return;
/* New request, no user details */
if (auth_user_request == NULL) {
debugs(29, 9, HERE << "Sending type:" << reqType << " header: 'Negotiate'");
httpHeaderPutStrf(&rep->header, reqType, "Negotiate");
if (!keep_alive) {
/* drop the connection */
rep->header.delByName("keep-alive");
request->flags.proxyKeepalive = 0;
}
} else {
Auth::Negotiate::UserRequest *negotiate_request = dynamic_cast<Auth::Negotiate::UserRequest *>(auth_user_request.getRaw());
assert(negotiate_request != NULL);
switch (negotiate_request->user()->credentials()) {
case Auth::Failed:
/* here it makes sense to drop the connection, as auth is
* tied to it, even if MAYBE the client could handle it - Kinkie */
rep->header.delByName("keep-alive");
request->flags.proxyKeepalive = 0;
/* fall through */
case Auth::Ok:
/* Special case: authentication finished OK but disallowed by ACL.
* Need to start over to give the client another chance.
*/
if (negotiate_request->server_blob) {
debugs(29, 9, HERE << "Sending type:" << reqType << " header: 'Negotiate " << negotiate_request->server_blob << "'");
httpHeaderPutStrf(&rep->header, reqType, "Negotiate %s", negotiate_request->server_blob);
safe_free(negotiate_request->server_blob);
} else {
debugs(29, 9, HERE << "Connection authenticated");
httpHeaderPutStrf(&rep->header, reqType, "Negotiate");
}
break;
case Auth::Unchecked:
/* semantic change: do not drop the connection.
* 2.5 implementation used to keep it open - Kinkie */
debugs(29, 9, HERE << "Sending type:" << reqType << " header: 'Negotiate'");
httpHeaderPutStrf(&rep->header, reqType, "Negotiate");
break;
case Auth::Handshake:
/* we're waiting for a response from the client. Pass it the blob */
debugs(29, 9, HERE << "Sending type:" << reqType << " header: 'Negotiate " << negotiate_request->server_blob << "'");
httpHeaderPutStrf(&rep->header, reqType, "Negotiate %s", negotiate_request->server_blob);
safe_free(negotiate_request->server_blob);
break;
default:
debugs(29, DBG_CRITICAL, "ERROR: Negotiate auth fixHeader: state " << negotiate_request->user()->credentials() << ".");
fatal("unexpected state in AuthenticateNegotiateFixErrorHeader.\n");
}
}
}
static void
authenticateNegotiateStats(StoreEntry * sentry)
{
helperStatefulStats(sentry, negotiateauthenticators, "Negotiate Authenticator Statistics");
}
/*
* Decode a Negotiate [Proxy-]Auth string, placing the results in the passed
* Auth_user structure.
*/
Auth::UserRequest::Pointer
Auth::Negotiate::Config::decode(char const *proxy_auth)
{
Auth::Negotiate::User *newUser = new Auth::Negotiate::User(Auth::Config::Find("negotiate"));
Auth::UserRequest *auth_user_request = new Auth::Negotiate::UserRequest();
assert(auth_user_request->user() == NULL);
auth_user_request->user(newUser);
auth_user_request->user()->auth_type = Auth::AUTH_NEGOTIATE;
/* all we have to do is identify that it's Negotiate - the helper does the rest */
debugs(29, 9, HERE << "decode Negotiate authentication");
return auth_user_request;
}
| 33.250825
| 151
| 0.669181
|
spaceify
|
9717b27939f1cd716d928179a9561929900d5c66
| 3,709
|
cpp
|
C++
|
src/base/muduo/net/poller/poll_poller.cpp
|
sbfhy/server1
|
b9597a3783a0f7bb929b4b9fa7f621c81740b056
|
[
"BSD-3-Clause"
] | null | null | null |
src/base/muduo/net/poller/poll_poller.cpp
|
sbfhy/server1
|
b9597a3783a0f7bb929b4b9fa7f621c81740b056
|
[
"BSD-3-Clause"
] | null | null | null |
src/base/muduo/net/poller/poll_poller.cpp
|
sbfhy/server1
|
b9597a3783a0f7bb929b4b9fa7f621c81740b056
|
[
"BSD-3-Clause"
] | null | null | null |
#include "muduo/net/poller/poll_poller.h"
#include "muduo/net/common/channel.h"
#include "muduo/base/common/logging.h"
#include "define/define_types.h"
#include <asm-generic/errno-base.h>
#include <assert.h>
#include <errno.h>
#include <poll.h>
#include <sys/cdefs.h>
using namespace muduo;
using namespace muduo::net;
PollPoller::PollPoller(EventLoop* loop)
: Poller(loop)
{
}
PollPoller::~PollPoller() = default;
TimeStamp PollPoller::poll(SDWORD timeoutMs, ChannelList* activeChannels)
{
// XXX pollfds_ shouldn't change
SDWORD numEvents = ::poll(&*m_pollfds.begin(), m_pollfds.size(), timeoutMs);
SDWORD savedErrno = errno;
TimeStamp now(TimeStamp::now());
if (numEvents > 0)
{
LOG_TRACE << numEvents << " events happened";
fillActiveChannels(numEvents, activeChannels);
}
else if (numEvents == 0)
{
LOG_TRACE << " nothing happened";
}
else
{
if (savedErrno != EINTR)
{
errno = savedErrno;
LOG_SYSERR << "PollPoller::poll()";
}
}
return now;
}
void PollPoller::fillActiveChannels(SDWORD numEvents, ChannelList* activeChannels) const
{
for (PollFdList::const_iterator pfd = m_pollfds.begin();
pfd != m_pollfds.end() && numEvents > 0; ++ pfd)
{
if (pfd->revents > 0)
{
-- numEvents;
ChannelMap::const_iterator ch = m_channels.find(pfd->fd);
assert(ch != m_channels.end());
Channel* channel = ch->second;
assert(channel->getFd() == pfd->fd);
channel->setRevents(pfd->revents);
activeChannels->push_back(channel);
}
}
}
void PollPoller::UpdateChannel(Channel* channel)
{
Poller::AssertInLoopThread();
LOG_TRACE << "fd = " << channel->getFd() << " events = " << channel->getEvents();
if (channel->getIndex() < 0)
{
// a new one, add to pollfds_
assert(m_channels.find(channel->getFd()) == m_channels.end());
struct pollfd pfd;
pfd.fd = channel->getFd();
pfd.events = static_cast<SWORD>(channel->getEvents());
pfd.revents = 0;
m_pollfds.push_back(pfd);
SDWORD idx = static_cast<SDWORD>(m_pollfds.size()) - 1;
channel->setIndex(idx);
m_channels[pfd.fd] = channel;
}
else
{
// update existing one
assert(m_channels.find(channel->getFd()) != m_channels.end());
assert(m_channels[channel->getFd()] == channel);
SDWORD idx = channel->getIndex();
assert(0 <= idx && idx < static_cast<SDWORD>(m_pollfds.size()));
struct pollfd& pfd = m_pollfds[idx];
assert(pfd.fd == channel->getFd() || pfd.fd == -channel->getFd()-1);
pfd.fd = channel->getFd();
pfd.events = static_cast<SWORD>(channel->getEvents());
pfd.revents = 0;
if (channel->IsNoneEvent())
{
pfd.fd = -channel->getFd() - 1; // 删除,屏蔽掉这个fd
}
}
}
void PollPoller::RemoveChannel(Channel* channel)
{
Poller::AssertInLoopThread();
LOG_TRACE << "fd = " << channel->getFd();
assert(m_channels.find(channel->getFd()) != m_channels.end());
assert(m_channels[channel->getFd()] == channel);
assert(channel->IsNoneEvent());
SDWORD idx = channel->getIndex();
assert(0 <= idx && idx < static_cast<SDWORD>(m_pollfds.size()));
const struct pollfd& pfd = m_pollfds[idx]; (void)pfd;
assert(pfd.fd == -channel->getFd()-1 && pfd.events == channel->getEvents());
size_t n = m_channels.erase(channel->getFd());
assert(n == 1); (void)n;
if (implicit_cast<size_t>(idx) == m_pollfds.size() - 1)
{
m_pollfds.pop_back();
}
else
{
SDWORD channelAtEnd = m_pollfds.back().fd;
iter_swap(m_pollfds.begin() + idx, m_pollfds.end() - 1);
if (channelAtEnd < 0)
{
channelAtEnd = -channelAtEnd - 1;
}
m_channels[channelAtEnd]->setIndex(idx);
m_pollfds.pop_back();
}
}
| 28.312977
| 88
| 0.640874
|
sbfhy
|
97183bf80c9dbf7b6f32600a7f96ade0928d99f5
| 4,191
|
cpp
|
C++
|
Practice/2018/2018.12.29/BZOJ5417.cpp
|
SYCstudio/OI
|
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
|
[
"MIT"
] | 4
|
2017-10-31T14:25:18.000Z
|
2018-06-10T16:10:17.000Z
|
Practice/2018/2018.12.29/BZOJ5417.cpp
|
SYCstudio/OI
|
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
|
[
"MIT"
] | null | null | null |
Practice/2018/2018.12.29/BZOJ5417.cpp
|
SYCstudio/OI
|
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
|
[
"MIT"
] | null | null | null |
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<vector>
#include<iostream>
using namespace std;
#define mem(Arr,x) memset(Arr,x,sizeof(Arr))
#define ll long long
#define NAME "name"
const int maxL=505000*2;
const int maxAlpha=26;
class Node{
public:
int son[maxAlpha],fail,len;
};
class SAM{
public:
int nodecnt,root,lst,Pos[maxL];
Node S[maxL];
SAM(){
nodecnt=root=lst=1;return;
}
void Init(){
nodecnt=root=lst=1;mem(S[1].son,0);S[1].fail=S[1].len=0;Pos[1]=0;
return;
}
int New(){
int p=++nodecnt;S[p].len=S[p].fail=0;mem(S[p].son,0);Pos[p]=0;return p;
}
void Extend(int c,int id){
int np=New(),p=lst;lst=np;S[np].len=S[p].len+1;Pos[np]=id;
while (p&&!S[p].son[c]) S[p].son[c]=np,p=S[p].fail;
if (!p) S[np].fail=root;
else{
int q=S[p].son[c];
if (S[q].len==S[p].len+1) S[np].fail=q;
else{
int nq=New();S[nq]=S[q];S[q].fail=S[np].fail=nq;S[nq].len=S[p].len+1;Pos[nq]=Pos[q];
while (p&&S[p].son[c]==q) S[p].son[c]=nq,p=S[p].fail;
}
}
return;
}
};
int n,Mtc[maxL];
char Input[maxL];
SAM S,T;
vector<int> TS[maxL];
void dfs_build(int x);
namespace DS{
class SegmentData{
public:
int ls,rs;
};
int nodecnt,root[maxL];
SegmentData S[maxL*20];
void Insert(int &x,int l,int r,int pos);
int Query(int x,int l,int r,int ql,int qr);
int Merge(int x,int y);
void outp(int x,int l,int r);
}
int main(){
//freopen(NAME".in","r",stdin);freopen(NAME".out","w",stdout);
scanf("%s",Input+1);n=strlen(Input+1);
for (int i=1;i<=n;i++){
S.Extend(Input[i]-'a',i);
DS::Insert(DS::root[S.lst],1,n,i);
}
/*
for (int i=1;i<=S.nodecnt;i++)
for (int j=0;j<maxAlpha;j++)
if (S.S[i].son[j]) cout<<i<<"->"<<S.S[i].son[j]<<" "<<(char)(j+'a')<<endl;
for (int i=1;i<=S.nodecnt;i++) cout<<S.S[i].len<<" ";cout<<endl;
for (int i=1;i<=S.nodecnt;i++) cout<<S.S[i].fail<<" ";cout<<endl;
//*/
for (int i=2;i<=S.nodecnt;i++) TS[S.S[i].fail].push_back(i);
dfs_build(1);
int Q;scanf("%d",&Q);
while (Q--){
int L,R,m;scanf("%s",Input+1);scanf("%d%d",&L,&R);
m=strlen(Input+1);T.Init();
for (int i=1;i<=m;i++) T.Extend(Input[i]-'a',i);
for (int i=1,x=1,cnt=0;i<=m;i++){
int c=Input[i]-'a';
//cout<<"running on :"<<i<<endl;
while (x&&((!S.S[x].son[c])||(
!DS::Query(DS::root[S.S[x].son[c]],1,n,L+S.S[S.S[S.S[x].son[c]].fail].len,R)))){
//cout<<"GetQ:"<<S.S[x].son[c]<<" ["<<L<<"+"<<S.S[S.S[S.S[x].son[c]].fail].len<<","<<R<<"]"<<endl;
x=S.S[x].fail,cnt=S.S[x].len;
}
//cout<<"now:"<<x<<" "<<cnt<<endl;
if (x==0){
x=1;cnt=0;Mtc[i]=0;continue;
}
x=S.S[x].son[c];++cnt;
//cout<<"Q:"<<i<<" "<<x<<" "<<S.S[S.S[x].fail].len+1<<" "<<cnt<<endl;
if (S.S[S.S[x].fail].len+1!=cnt){
int l=S.S[S.S[x].fail].len+1,r=cnt;
do{
int mid=(l+r)>>1;
if (DS::Query(DS::root[x],1,n,L+mid-1,R)) cnt=mid,l=mid+1;
else r=mid-1;
}
while (l<=r);
}
Mtc[i]=cnt;
}
ll Ans=0;
//for (int i=1;i<=m;i++) cout<<Mtc[i]<<" ";cout<<endl;
for (int i=1;i<=T.nodecnt;i++) Ans=Ans+max(0,T.S[i].len-max(T.S[T.S[i].fail].len,Mtc[T.Pos[i]]));
printf("%lld\n",Ans);
}
return 0;
}
void dfs_build(int x){
for (int i=0,sz=TS[x].size();i<sz;i++){
dfs_build(TS[x][i]);
DS::root[x]=DS::Merge(DS::root[x],DS::root[TS[x][i]]);
}
return;
}
namespace DS{
void Insert(int &x,int l,int r,int pos){
if (x==0) x=++nodecnt;
if (l==r) return;
int mid=(l+r)>>1;
if (pos<=mid) Insert(S[x].ls,l,mid,pos);
else Insert(S[x].rs,mid+1,r,pos);
return;
}
int Query(int x,int l,int r,int ql,int qr){
//cout<<"Q:"<<x<<" "<<l<<" "<<r<<" "<<ql<<" "<<qr<<endl;
if (ql>qr) return 0;
if (x==0) return 0;if ((l==ql)&&(r==qr)) return 1;
int mid=(l+r)>>1;
if (qr<=mid) return Query(S[x].ls,l,mid,ql,qr);
else if (ql>=mid+1) return Query(S[x].rs,mid+1,r,ql,qr);
else return Query(S[x].ls,l,mid,ql,mid)|Query(S[x].rs,mid+1,r,mid+1,qr);
}
int Merge(int x,int y){
if ((!x)||(!y)) return x+y;
int u=++nodecnt;
S[u].ls=Merge(S[x].ls,S[y].ls);S[u].rs=Merge(S[x].rs,S[y].rs);
return u;
}
void outp(int x,int l,int r){
if (x==0) return;
if (l==r){
return;
}
int mid=(l+r)>>1;
outp(S[x].ls,l,mid);outp(S[x].rs,mid+1,r);return;
}
}
| 25.4
| 102
| 0.545455
|
SYCstudio
|
971cd7c3d55ec832dc00c68b332983eccc0351c9
| 748
|
cpp
|
C++
|
src/Island.cpp
|
luka1199/bridges
|
117c91d714aa19fa4c5138b032583e3efe93d142
|
[
"MIT"
] | null | null | null |
src/Island.cpp
|
luka1199/bridges
|
117c91d714aa19fa4c5138b032583e3efe93d142
|
[
"MIT"
] | 1
|
2019-08-14T13:36:33.000Z
|
2019-08-14T13:36:33.000Z
|
src/Island.cpp
|
luka1199/bridges
|
117c91d714aa19fa4c5138b032583e3efe93d142
|
[
"MIT"
] | null | null | null |
// Copyright 2018,
// Author: Luka Steinbach <luka.steinbach@gmx.de>
#include "./Island.h"
#include <string>
#include <vector>
// _____________________________________________________________________________
Island::Island(int x, int y, int count) : Field(x, y) {
_islandCount = count;
_correctBridgeCount = 0;
_symbol = std::to_string(_islandCount);
}
// _____________________________________________________________________________
Island::~Island() {}
// _____________________________________________________________________________
int Island::getCount() const {
return _islandCount;
}
// _____________________________________________________________________________
std::string Island::getType() const {
return "type_island";
}
| 27.703704
| 80
| 0.798128
|
luka1199
|
971d0e7be632f513340bede6a7f76ecd77082369
| 77,961
|
cpp
|
C++
|
simulation-code/Network.cpp
|
jlubo/memory-consolidation-stc
|
f9934760e12de324360297d7fc7902623169cb4d
|
[
"Apache-2.0"
] | 2
|
2021-03-02T21:46:56.000Z
|
2021-06-30T03:12:07.000Z
|
simulation-code/Network.cpp
|
jlubo/memory-consolidation-stc
|
f9934760e12de324360297d7fc7902623169cb4d
|
[
"Apache-2.0"
] | null | null | null |
simulation-code/Network.cpp
|
jlubo/memory-consolidation-stc
|
f9934760e12de324360297d7fc7902623169cb4d
|
[
"Apache-2.0"
] | 3
|
2021-03-22T12:56:52.000Z
|
2021-09-13T07:42:36.000Z
|
/**************************************************************************************************
*** Model of a network of neurons with long-term plasticity between excitatory neurons ***
**************************************************************************************************/
/*** Copyright 2017-2021 Jannik Luboeinski ***
*** licensed under Apache-2.0 (http://www.apache.org/licenses/LICENSE-2.0) ***/
#include <random>
#include <sstream>
using namespace std;
#include "Neuron.cpp"
struct synapse // structure for synapse definition
{
int presyn_neuron; // the number of the presynaptic neuron
int postsyn_neuron; // the number of the postsynaptic neuron
synapse(int _presyn_neuron, int _postsyn_neuron) // constructor
{
presyn_neuron = _presyn_neuron;
postsyn_neuron = _postsyn_neuron;
}
};
/*** Network class ***
* Represents a network of neurons */
class Network {
#if (PROTEIN_POOLS != POOLS_C && PROTEIN_POOLS != POOLS_PD && PROTEIN_POOLS != POOLS_PCD)
#error "Unsupported option for PROTEIN_POOLS."
#endif
friend class boost::serialization::access;
private:
/*** Computational parameters ***/
double dt; // s, one timestep for numerical simulation
int N; // total number of excitatory plus inhibitory neurons
int t_syn_delay_steps; // constant t_syn_delay converted to timesteps
int t_Ca_delay_steps; // constant t_Ca_delay converted to timesteps
/*** State variables ***/
vector<Neuron> neurons; // vector of all N neuron instances (first excitatory, then inhibitory)
bool** conn; // the binary connectivity matrix, the main diagonal is zero (because there is no self-coupling)
double** Ca; // the matrix of postsynaptic calcium concentrations
double** h; // the matrix of early-phase coupling strengths
double** z; // the matrix of late-phase coupling strengths
int* last_Ca_spike_index; // contains the indices of the last spikes that were important for calcium dynamics
minstd_rand0 rg; // default uniform generator for random numbers to establish connections (seed is chosen in constructor)
uniform_real_distribution<double> u_dist; // uniform distribution, constructed in Network class constructor
normal_distribution<double> norm_dist; // normal distribution to obtain Gaussian white noise, constructed in Network class constructor
int stimulation_end; // timestep by which all stimuli have ended
double* sum_h_diff; // sum of all early-phase changes for each postsynaptic neuron
double* sum_h_diff_p; // sum of E-LTP changes for each postsynaptic neuron
double* sum_h_diff_d; // sum of E-LTD changes for each postsynaptic neuron
protected:
/*** Physical parameters ***/
int Nl_exc; // number of neurons in one line (row or column) of the exc. population (better choose an odd number, for there exists a "central" neuron)
int Nl_inh; // number of neurons in one line (row or column) of the inh. population (better choose an odd number, for there exists a "central" neuron)
double tau_syn; // s, the synaptic time constant
double t_syn_delay; // s, the synaptic transmission delay for PSPs - has to be at least one timestep!
double p_c; // connection probability (prob. that a directed connection exists)
double w_ee; // nC, magnitude of excitatory PSP effecting an excitatory postsynaptic neuron
double w_ei; // nC, magnitude of excitatory PSP effecting an inhibitory postsynaptic neuron
double w_ie; // nC, magnitude of inhibitory PSP effecting an excitatory postsynaptic neuron
double w_ii; // nC, magnitude of inhibitory PSP effecting an inhibitory postsynaptic neuron
/*** Plasticity parameters ***/
double t_Ca_delay; // s, delay for spikes to affect calcium dynamics - has to be at least one timestep!
double Ca_pre; // s^-1, increase in calcium current evoked by presynaptic spike
double Ca_post; // s^-1, increase in calcium current evoked by postsynaptic spike
double tau_Ca; // s, time constant for calcium dynamics
double tau_Ca_steps; // time constant for calcium dynamics in timesteps
double tau_h; // s, time constant for early-phase plasticity
double tau_pp; // h, time constant of LTP-related protein synthesis
double tau_pc; // h, time constant of common protein synthesis
double tau_pd; // h, time constant of LTD-related protein synthesis
double tau_z; // min, time constant of consolidation
double gamma_p; // constant for potentiation process
double gamma_d; // constant for depression process
double theta_p; // threshold for calcium concentration to induce potentiation
double theta_d; // threshold for calcium concentration to induce depotentiation
double sigma_plasticity; // nA s, standard deviation of plasticity noise
double alpha_p; // LTP-related protein synthesis rate
double alpha_c; // common protein synthesis rate
double alpha_d; // LTD-related protein synthesis rate
double h_0; // nA, initial value for early-phase plasticity
double theta_pro_p; // nA s, threshold for LTP-related protein synthesis
double theta_pro_c; // nA s, threshold for common protein synthesis
double theta_pro_d; // nA s, threshold for LTD-related protein synthesis
double theta_tag_p; // nA s, threshold for LTP-related tag
double theta_tag_d; // nA s, threshold for LTD-related tag
double z_max; // upper z bound
public:
#ifdef TWO_NEURONS_ONE_SYNAPSE
bool tag_glob; // specifies if a synapse was tagged ever
bool ps_glob; // specifies if protein synthesis ever occurred in any neuron
#endif
double max_dev; // maximum deviation from h_0 (deviation of the synapse with the largest change)
int tb_max_dev; // time bin at which max_dev was encountered
#if PROTEIN_POOLS == POOLS_C || PROTEIN_POOLS == POOLS_PCD
double max_sum_diff; // maximum sum of early-phase changes (sum of the neuron with the most changes)
int tb_max_sum_diff; // time bin at which max_sum_diff was encountered
#endif
#if PROTEIN_POOLS == POOLS_PD || PROTEIN_POOLS == POOLS_PCD
double max_sum_diff_p; // maximum sum of LTP early-phase changes (sum of the neuron with the most changes)
int tb_max_sum_diff_p; // time bin at which max_sum_diff_p was encountered
double max_sum_diff_d; // maximum sum of LTD early-phase changes (sum of the neuron with the most changes)
int tb_max_sum_diff_d; // time bin at which max_sum_diff_d was encountered
#endif
/*** rowG (macro) ***
* Returns the row number for element n (in consecutive numbering), be *
* aware that it starts with one, unlike the consecutive number (general case for a row/column size of d) *
* - int n: the consecutive element number *
* - int d: the row/column size */
#define rowG(n, d) ((((n) - ((n) % d)) / d) + 1)
/*** colG (macro) ***
* Returns the column number for element n (in consecutive numbering), be *
* aware that it starts with one, unlike the consecutive number (general case for a row/column size of d) *
* - int n: the consecutive element number *
* - int d: the row/column size */
#define colG(n, d) (((n) % d) + 1)
/*** cNN (macro) ***
* Returns a consecutive number for excitatory neuron (i|j) rather than a pair of numbers like (i|j), be *
* aware that it starts with zero, unlike i and j *
* - int i: the row where the neuron is located *
* - int j: the column where the neuron is located */
#define cNN(i, j) (((i)-1)*Nl_exc + ((j)-1))
/*** row (macro) ***
* Returns the row number for excitatory neuron n, be *
* aware that it starts with one, unlike the consecutive number *
* - int n: the consecutive neuron number */
#define row(n) (rowG(n, Nl_exc))
/*** col (macro) ***
* Returns the column number for excitatory neuron n, be *
* aware that it starts with one, unlike the consecutive number *
* - int n: the consecutive neuron number */
#define col(n) (colG(n, Nl_exc))
/*** symm (macro) ***
* Returns the number of the symmetric element for an element given *
* by its consecutive number *
* - int n: the consecutive element number */
#define symm(n) (cNN(col(n),row(n)))
/*** shallBeConnected ***
* Draws a uniformly distributed random number from the interval 0.0 to 1.0 and returns, *
* depending on the connection probability, whether or not a connection shall be established *
* - int m: consecutive number of presynaptic neuron *
* - int n: consecutive number of postsynaptic neuron *
* - return: true if connection shall be established, false if not */
bool shallBeConnected(int m, int n)
{
#ifdef TWO_NEURONS_ONE_SYNAPSE
// in this paradigm, there is only one synapse from neuron 1 to neuron 0
if (m == 1 && n == 0)
{
neurons[m].addOutgoingConnection(n, TYPE_EXC);
return true;
}
#else
// exc.->exc. synapse
if (m < pow2(Nl_exc) && n < pow2(Nl_exc))
{
if (u_dist(rg) <= p_c) // draw random number
{
neurons[n].incNumberIncoming(TYPE_EXC);
neurons[m].addOutgoingConnection(n, TYPE_EXC);
return true;
}
}
// exc.->inh. synapse
else if (m < pow2(Nl_exc) && n >= pow2(Nl_exc))
{
if (u_dist(rg) <= p_c) // draw random number
{
neurons[n].incNumberIncoming(TYPE_EXC);
neurons[m].addOutgoingConnection(n, TYPE_INH);
return true;
}
}
// inh.->exc. synapse
else if (m >= pow2(Nl_exc) && n < pow2(Nl_exc))
{
if (u_dist(rg) <= p_c) // draw random number
{
neurons[n].incNumberIncoming(TYPE_INH);
neurons[m].addOutgoingConnection(n, TYPE_EXC);
return true;
}
}
// inh.->inh. synapse
else if (m >= pow2(Nl_exc) && n >= pow2(Nl_exc))
{
if (u_dist(rg) <= p_c) // draw random number
{
neurons[n].incNumberIncoming(TYPE_INH);
neurons[m].addOutgoingConnection(n, TYPE_INH);
return true;
}
}
#endif
return false;
}
/*** areConnected ***
* Returns whether or not there is a synapse from neuron m to neuron n *
* - int m: the number of the first neuron in consecutive order *
* - int n: the number of the second neuron in consecutive order *
* - return: true if connection from m to n exists, false if not */
bool areConnected(int m, int n) const
{
if (conn[m][n])
return true;
else
return false;
}
/*** saveNetworkParams ***
* Saves all the network parameters (including the neuron and channel parameters) to a given file */
void saveNetworkParams(ofstream *f) const
{
*f << endl;
*f << "Network parameters:" << endl;
*f << "N_exc = " << pow2(Nl_exc) << " (" << Nl_exc << " x " << Nl_exc << ")" << endl;
*f << "N_inh = " << pow2(Nl_inh) << " (" << Nl_inh << " x " << Nl_inh << ")" << endl;
*f << "tau_syn = "
#if SYNAPSE_MODEL == DELTA
<< 0
#elif SYNAPSE_MODEL == MONOEXP
<< tau_syn
#endif
<< " s" << endl;
*f << "t_syn_delay = " << t_syn_delay << " s" << endl;
*f << "h_0 = " << h_0 << " nA s" << endl;
*f << "w_ee = " << dtos(w_ee/h_0,1) << " h_0" << endl;
*f << "w_ei = " << dtos(w_ei/h_0,1) << " h_0" << endl;
*f << "w_ie = " << dtos(w_ie/h_0,1) << " h_0" << endl;
*f << "w_ii = " << dtos(w_ii/h_0,1) << " h_0" << endl;
*f << "p_c = " << p_c << endl;
*f << endl;
*f << "Plasticity parameters"
#if PLASTICITY == OFF
<< " <switched off>"
#endif
<< ": " << endl;
*f << "t_Ca_delay = " << t_Ca_delay << " s" << endl;
*f << "Ca_pre = " << Ca_pre << endl;
*f << "Ca_post = " << Ca_post << endl;
*f << "tau_Ca = " << tau_Ca << " s" << endl;
*f << "tau_h = " << tau_h << " s" << endl;
*f << "tau_pp = " << tau_pp << " h" << endl;
*f << "tau_pc = " << tau_pc << " h" << endl;
*f << "tau_pd = " << tau_pd << " h" << endl;
*f << "tau_z = " << tau_z << " min" << endl;
*f << "z_max = " << z_max << endl;
*f << "gamma_p = " << gamma_p << endl;
*f << "gamma_d = " << gamma_d << endl;
*f << "theta_p = " << theta_p << endl;
*f << "theta_d = " << theta_d << endl;
*f << "sigma_plasticity = " << dtos(sigma_plasticity/h_0,2) << " h_0" << endl;
*f << "alpha_p = " << alpha_p << endl;
*f << "alpha_c = " << alpha_c << endl;
*f << "alpha_d = " << alpha_d << endl;
double nm = 1. / (theta_pro_c/h_0) - 0.001; // compute neuromodulator concentration from threshold theta_pro_c
*f << "theta_pro_p = " << dtos(theta_pro_p/h_0,2) << " h_0" << endl;
*f << "theta_pro_c = " << dtos(theta_pro_c/h_0,2) << " h_0 (nm = " << dtos(nm,2) << ")" << endl;
*f << "theta_pro_d = " << dtos(theta_pro_d/h_0,2) << " h_0" << endl;
*f << "theta_tag_p = " << dtos(theta_tag_p/h_0,2) << " h_0" << endl;
*f << "theta_tag_d = " << dtos(theta_tag_d/h_0,2) << " h_0" << endl;
neurons[0].saveNeuronParams(f); // all neurons have the same parameters, take the first one
}
/*** saveNetworkState ***
* Saves the current state of the whole network to a given file using boost function serialize(...) *
* - file: the file to read the data from *
* - tb: current timestep */
void saveNetworkState(string file, int tb)
{
ofstream savefile(file);
if (!savefile.is_open())
throw runtime_error(string("Network state could not be saved."));
boost::archive::text_oarchive oa(savefile);
oa << tb; // write the current time (in steps) to archive oa
oa << *this; // write this instance to archive oa
savefile.close();
}
/*** loadNetworkState ***
* Load the state of the whole network from a given file using boost function serialize(...); *
* connectivity matrix 'conn' of the old and the new simulation has to be the same! *
* - file: the file to read the data from *
* - return: the simulation time at which the network state was saved (or -1 if nothing was loaded) */
int loadNetworkState(string file)
{
ifstream loadfile(file);
int tb;
if (!loadfile.is_open())
return -1;
boost::archive::text_iarchive ia(loadfile);
ia >> tb; // read the current time (in steps) from archive ia
ia >> *this; // read this instance from archive ia
loadfile.close();
cout << "Network state successfully loaded." << endl;
return tb;
}
/*** serialize ***
* Saves all state variables to a file using serialization from boost *
* - ar: the archive stream *
* - version: the archive version */
template<class Archive> void serialize(Archive &ar, const unsigned int version)
{
for (int m=0; m<N; m++)
{
ar & neurons[m]; // read/write Neuron instances
for (int n=0; n<N; n++)
{
ar & Ca[m][n]; // read/write matrix of postsynaptic Calcium concentrations
ar & h[m][n]; // read/write early-phase weight matrix
ar & z[m][n]; // read/write late-phase weight matrix
}
ar & last_Ca_spike_index[m]; // read/write array of the indices of the last spikes that were important for calcium dynamics
ar & sum_h_diff[m]; // read/write sum of all early-phase changes for each postsynaptic neuron
ar & sum_h_diff_p[m]; // read/write sum of E-LTP changes for each postsynaptic neuron
ar & sum_h_diff_d[m]; // read/write sum of E-LTD changes for each postsynaptic neuron
}
}
/*** processTimeStep ***
* Processes one timestep (of duration dt) for the network [rich mode / compmode == 1] *
* - int tb: current timestep (for evaluating stimulus and for computing spike contributions) *
* - ofstream* txt_spike_raster [optional]: file containing spike times for spike raster plot *
* - return: number of spikes that occurred within the considered timestep in the whole network */
int processTimeStep(int tb, ofstream* txt_spike_raster = NULL)
{
int spike_count = 0; // number of neurons that have spiked in this timestep
int st_PSP = tb - t_syn_delay_steps; // presynaptic spike time for evoking PSP in this timestep tb
int st_CA = tb - t_Ca_delay_steps; // presynaptic spike time for evoking calcium contribution in this timestep tb
bool STC = false; // specifies if at least one synapse is tagged and receives proteins
bool ps_neuron = false; // specifies if at least one neuron is exhibiting protein synthesis
/*******************************************************/
// compute neuronal dynamics
for (int m=0; m<N; m++) // loop over neurons (in consecutive order)
{
neurons[m].processTimeStep(tb, -1); // computation of individual neuron dynamics
// add spikes to raster plot and count spikes in this timestep
if (neurons[m].getActivity())
{
#if SPIKE_PLOTTING == RASTER || SPIKE_PLOTTING == NUMBER_AND_RASTER
*txt_spike_raster << tb*dt << "\t\t" << m << endl; // add this spike to the raster plot
#endif
spike_count += 1;
}
#if COND_BASED_SYN == OFF
#if SYNAPSE_MODEL == DELTA
neurons[m].setSynapticCurrent(0.); // reset synaptic current contributions
#elif SYNAPSE_MODEL == MONOEXP
neurons[m].setSynapticCurrent(neurons[m].getSynapticCurrent() * exp(-dt/tau_syn)); // exponential decay of previous synaptic current contributions
#endif
#else
#if SYNAPSE_MODEL == DELTA
neurons[m].setExcSynapticCurrent(0.); // reset synaptic current contributions
neurons[m].setInhSynapticCurrent(0.); // reset synaptic current contributions
#elif SYNAPSE_MODEL == MONOEXP
neurons[m].setExcSynapticCurrent(neurons[m].getExcSynapticCurrent() * exp(-dt/tau_syn)); // exponential decay of previous synaptic current contributions
neurons[m].setInhSynapticCurrent(neurons[m].getInhSynapticCurrent() * exp(-dt/tau_syn)); // exponential decay of previous synaptic current contributions
//[simple Euler: neurons[m].setExcSynapticCurrent(neurons[m].getExcSynapticCurrent() * (1.-dt/tau_syn)); ]
//[simple Euler: neurons[m].setInhSynapticCurrent(neurons[m].getInhSynapticCurrent() * (1.-dt/tau_syn)); ]
#endif
#endif // COND_BASED_SYN == ON
// Protein dynamics (for neuron m)
#if PLASTICITY == CALCIUM_AND_STC || PLASTICITY == STDP_AND_STC
#ifdef TWO_NEURONS_ONE_SYNAPSE
ps_glob = ps_glob || (sum_h_diff[m] >= theta_pro_c);
#endif
#if PROTEIN_POOLS == POOLS_PD || PROTEIN_POOLS == POOLS_PCD
double pa_p = neurons[m].getPProteinAmount();
double pa_d = neurons[m].getDProteinAmount();
if (sum_h_diff_p[m] > max_sum_diff_p)
{
max_sum_diff_p = sum_h_diff_p[m];
tb_max_sum_diff_p = tb;
}
if (sum_h_diff_d[m] > max_sum_diff_d)
{
max_sum_diff_d = sum_h_diff_d[m];
tb_max_sum_diff_d = tb;
}
ps_neuron = ps_neuron || (sum_h_diff_p[m] >= theta_pro_p) || (sum_h_diff_d[m] >= theta_pro_d);
pa_p = pa_p * exp(-dt/(tau_pp * 3600.)) + alpha_p * step(sum_h_diff_p[m] - theta_pro_p) * (1. - exp(-dt/(tau_pp * 3600.)));
pa_d = pa_d * exp(-dt/(tau_pd * 3600.)) + alpha_d * step(sum_h_diff_d[m] - theta_pro_d) * (1. - exp(-dt/(tau_pd * 3600.)));
// [simple Euler: pa += (- pa + alpha * step(sum_h_diff - theta_pro)) * (dt / (tau_p * 3600.));]
sum_h_diff_p[m] = 0.;
sum_h_diff_d[m] = 0.;
#else
double pa_p = 0.;
double pa_d = 0.;
#endif
#if PROTEIN_POOLS == POOLS_C || PROTEIN_POOLS == POOLS_PCD
double pa_c = neurons[m].getCProteinAmount();
if (sum_h_diff[m] > max_sum_diff)
{
max_sum_diff = sum_h_diff[m];
tb_max_sum_diff = tb;
}
ps_neuron = ps_neuron || (sum_h_diff[m] >= theta_pro_c);
pa_c = pa_c * exp(-dt/(tau_pc * 3600.)) + alpha_c * step(sum_h_diff[m] - theta_pro_c) * (1. - exp(-dt/(tau_pc * 3600.))); // === ESSENTIAL ===
sum_h_diff[m] = 0.;
#else
double pa_c = 0.;
#endif
neurons[m].setProteinAmounts(pa_p, pa_c, pa_d);
#endif // PLASTICITY == CALCIUM_AND_STC || PLASTICITY == STDP_AND_STC
}
/*******************************************************/
// compute synaptic dynamics
for (int m=0; m<N; m++) // loop over presynaptic neurons (in consecutive order)
{
bool delayed_PSP; // specifies if a presynaptic spike occurred t_syn_delay ago
// go through presynaptic spikes for PSPs; start from most recent one
delayed_PSP = neurons[m].spikeAt(st_PSP);
//delayed_PSP = neurons[m].getActivity(); // in case no synaptic delay is used
#if PLASTICITY == CALCIUM || PLASTICITY == CALCIUM_AND_STC
bool delayed_Ca = false; // specifies if a presynaptic spike occurred t_Ca_delay ago
if (m < pow2(Nl_exc)) // plasticity only for exc. -> exc. connections
{
// go through presynaptic spikes for calcium contribution; start from last one that was used plus one
for (int k=last_Ca_spike_index[m]; k<=neurons[m].getSpikeHistorySize(); k++)
{
int st = neurons[m].getSpikeTime(k);
if (st >= st_CA)
{
if (st == st_CA) // if presynaptic spike occurred t_Ca_delay ago
{
delayed_Ca = true; // presynaptic neuron fired t_Ca_delay ago
last_Ca_spike_index[m] = k + 1; // next time, start with the next possible spike
}
break;
}
}
}
#endif
/*******************************************************/
for (int in=0; in<neurons[m].getNumberOutgoing(); in++) // loop over postsynaptic neurons
{
int n = neurons[m].getOutgoingConnection(in); // get index (in consecutive order) of postsynaptic neuron
double h_dev; // the deviation of the early-phase weight from its resting state
// Synaptic current
if (delayed_PSP) // if presynaptic spike occurred t_syn_delay ago
{
if (neurons[m].getType() == TYPE_EXC)
{
double psc; // the postsynaptic current
if (neurons[n].getType() == TYPE_EXC) // E -> E
{
psc = h[m][n] + h_0 * z[m][n];
neurons[n].increaseExcSynapticCurrent(psc);
}
else // E -> I
{
psc = w_ei;
neurons[n].increaseExcSynapticCurrent(psc);
}
#if DENDR_SPIKES == ON
neurons[n].updateDendriteInput(psc); // contribution to dendritic spikes
#endif
}
else
{
if (neurons[n].getType() == TYPE_EXC) // I -> E
{
neurons[n].increaseInhSynapticCurrent(w_ie);
}
else // I -> I
{
neurons[n].increaseInhSynapticCurrent(w_ii);
}
}
}
// Long-term plasticity
if (m < pow2(Nl_exc) && n < pow2(Nl_exc)) // plasticity only for exc. -> exc. connections
{
#if PLASTICITY == CALCIUM || PLASTICITY == CALCIUM_AND_STC
// Calcium dynamics
Ca[m][n] *= exp(-dt/tau_Ca); // === ESSENTIAL ===
if (delayed_Ca) // if presynaptic spike occurred t_Ca_delay ago
Ca[m][n] += Ca_pre;
if (neurons[n].getActivity()) // if postsynaptic spike occurred in previous timestep
Ca[m][n] += Ca_post;
// E-LTP/-LTD
if ((Ca[m][n] >= theta_p) // if there is E-LTP and "STDP-like" condition is fulfilled
#if LTP_FR_THRESHOLD > 0
&& (neurons[m].spikesInInterval(tb-2500,tb+1) > LTP_FR_THRESHOLD/2 && neurons[n].spikesInInterval(tb-2500,tb+1) > LTP_FR_THRESHOLD/2)
#endif
)
{
double noise = sigma_plasticity * sqrt(tau_h) * sqrt(2) * norm_dist(rg) / sqrt(dt); // division by sqrt(dt) was not in Li et al., 2016
double C = 0.1 + gamma_p + gamma_d;
double hexp = exp(-dt*C/tau_h);
h[m][n] = h[m][n] * hexp + (0.1*h_0 + gamma_p + noise) / C * (1.- hexp);
// [simple Euler: h[m][n] += ((0.1 * (h_0 - h[m][n]) + gamma_p * (1-h[m][n]) - gamma_d * h[m][n] + noise)*(dt/tau_h));]
if (abs(h[m][n] - h_0) > abs(max_dev))
{
max_dev = h[m][n] - h_0;
tb_max_dev = tb;
}
}
else if ((Ca[m][n] >= theta_d) // if there is E-LTD
#if LTD_FR_THRESHOLD > 0
&& (neurons[m].spikesInInterval(tb-2500,tb+1) > LTD_FR_THRESHOLD/2 && neurons[n].spikesInInterval(tb-2500,tb+1) > LTD_FR_THRESHOLD/2)
#endif
)
{
double noise = sigma_plasticity * sqrt(tau_h) * norm_dist(rg) / sqrt(dt); // division by sqrt(dt) was not in Li et al., 2016
double C = 0.1 + gamma_d;
double hexp = exp(-dt*C/tau_h);
h[m][n] = h[m][n] * hexp + (0.1*h_0 + noise) / C * (1.- hexp);
// [simple Euler: h[m][n] += ((0.1 * (h_0 - h[m][n]) + gamma_d * h[m][n] + noise)*(dt/tau_h));]
if (abs(h[m][n] - h_0) > abs(max_dev))
{
max_dev = h[m][n] - h_0;
tb_max_dev = tb;
}
}
else // if early-phase weight just decays
{
double hexp = exp(-dt*0.1/tau_h);
h[m][n] = h[m][n] * hexp + h_0 * (1.- hexp);
// [simple Euler: h[m][n] += ((0.1 * (h_0 - h[m][n]))*(dt/tau_h));]
}
h_dev = h[m][n] - h_0;
#if PROTEIN_POOLS == POOLS_PD || PROTEIN_POOLS == POOLS_PCD
if (h_dev > 0.)
sum_h_diff_p[n] += h_dev; // sum of early-phases changes (for LTP-related protein synthesis)
else if (h_dev < 0.)
sum_h_diff_d[n] -= h_dev; // sum of early-phases changes (for LTD-related protein synthesis)
#endif
#if PROTEIN_POOLS == POOLS_C || PROTEIN_POOLS == POOLS_PCD
sum_h_diff[n] += abs(h_dev); // sum of early-phases changes (for protein synthesis)
#endif
#endif // PLASTICITY == CALCIUM || PLASTICITY == CALCIUM_AND_STC
#if PLASTICITY == CALCIUM_AND_STC || PLASTICITY == STDP_AND_STC
// L-LTP/-LTD
if (h_dev >= theta_tag_p) // LTP
{
#if PROTEIN_POOLS == POOLS_PCD
double pa = neurons[n].getPProteinAmount()*neurons[n].getCProteinAmount(); // LTP protein amount times common protein amount from previous timestep
#elif PROTEIN_POOLS == POOLS_PD
double pa = neurons[n].getPProteinAmount(); // LTP protein amountfrom previous timestep
#elif PROTEIN_POOLS == POOLS_C
double pa = neurons[n].getCProteinAmount(); // common protein amount from previous timestep
#endif
#ifdef TWO_NEURONS_ONE_SYNAPSE
tag_glob = true;
#endif
if (pa > EPSILON)
{
//double zexp = exp(-dt / (tau_z * 60.) * pa*(step1 + step2));
double zexp = exp(-dt / (tau_z * 60. * z_max) * pa);
z[m][n] = z[m][n] * zexp + z_max * (1. - zexp);
STC = true;
}
}
else if (-h_dev >= theta_tag_d) // LTD
{
#if PROTEIN_POOLS == POOLS_PCD
double pa = neurons[n].getDProteinAmount()*neurons[n].getCProteinAmount(); // LTD protein amount times common protein amount from previous timestep
#elif PROTEIN_POOLS == POOLS_PD
double pa = neurons[n].getDProteinAmount(); // LTD protein amountfrom previous timestep
#elif PROTEIN_POOLS == POOLS_C
double pa = neurons[n].getCProteinAmount(); // common protein amount from previous timestep
#endif
#ifdef TWO_NEURONS_ONE_SYNAPSE
tag_glob = true;
#endif
if (pa > EPSILON)
{
//double zexp = exp(-dt / (tau_z * 60.) * pa*(step1 + step2));
double zexp = exp(-dt / (tau_z * 60.) * pa);
z[m][n] = z[m][n] * zexp - 0.5 * (1. - zexp);
STC = true;
}
}
// [simple Euler: z[m][n] += (pa * ((1 - z[m][n]) * step1 - (0.5 + z[m][n]) * step2) * (dt / (tau_z * 6.0 * 10)));]
#endif // PLASTICITY == CALCIUM_AND_STC || PLASTICITY == STDP_AND_STC
#if PLASTICITY == STDP
double Ap = 1.2, Am = -1.0;
double tau_syn_stdp = 3e-3;
double tau_p_stdp = 1e-3;
double tau_m_stdp = 20e-3;
double tau_pt_stdp = tau_syn_stdp * tau_p_stdp / (tau_syn_stdp + tau_p_stdp);
double tau_mt_stdp = tau_syn_stdp * tau_m_stdp / (tau_syn_stdp + tau_m_stdp);
double eta = 12e-2;
// if presynaptic neuron m spiked in previous timestep
if (delayed_PSP)
{
int last_post_spike = neurons[n].getSpikeHistorySize();
if (last_post_spike > 0)
{
int tb_post = neurons[n].getSpikeTime(last_post_spike);
double stdp_delta_t = (tb + 1 - tb_post) * dt;
h[m][n] += eta * exp(-abs(stdp_delta_t) / tau_syn_stdp) * (Ap * (1. + abs(stdp_delta_t)/tau_pt_stdp) + Am * (1. + abs(stdp_delta_t)/tau_mt_stdp));
if (h[m][n] < 0.)
h[m][n] = 0.1;//h_0 / 100.; // set to a very small value
}
}
// if postsynaptic neuron n spiked in previous timestep
bool delayed_PSP2 = false;
for (int k=neurons[n].getSpikeHistorySize(); k>0; k--)
{
int st = neurons[n].getSpikeTime(k);
if (st <= st_PSP) // spikes that have already arrived
{
if (st == st_PSP) // if presynaptic spike occurred t_syn_delay ago
{
delayed_PSP2 = true; // presynaptic neuron fired t_syn_delay ago
}
break;
}
}
if (delayed_PSP2)
{
int last_pre_spike = neurons[m].getSpikeHistorySize();
if (last_pre_spike > 0)
{
int tb_pre = neurons[n].getSpikeTime(last_pre_spike);
double stdp_delta_t = (tb_pre - tb - 1) * dt;
h[m][n] += eta * (Ap * exp(-abs(stdp_delta_t) / tau_p_stdp) + Am * exp(-abs(stdp_delta_t) / tau_m_stdp));
if (h[m][n] < 0.)
h[m][n] = 0.1;//h_0 / 100.; // set to a very small value
}
}
#endif // PLASTICITY == STDP
} // plasticity within excitatory population
#if SYN_SCALING == ON
h[m][n] += ( eta_ss * pow2(h[m][n] / g_star) * (- r[n]) ) * dt;
#endif
} // loop over postsynaptic neurons
} // loop over presynaptic neurons
return spike_count;
}
/*** processTimeStep_FF ***
* Processes one timestep for the network only computing late-phase observables [fast-forward mode / compmode == 2] *
* - int tb: current timestep (for printing purposes only) *
* - double delta_t: duration of the fast-forward timestep *
* - ofstream* logf: pointer to log file handle (for printing interesting information) *
* - return: true if late-phase dynamics are persisting, false if not */
int processTimeStep_FF(int tb, double delta_t, ofstream* logf)
{
bool STC = false; // specifies if at least one synapse is tagged and receives proteins
bool ps_neuron = false; // specifies if at least one neuron is exhibiting protein synthesis
/*******************************************************/
// compute neuronal dynamics
for (int m=0; m<N; m++) // loop over neurons (in consecutive order)
{
// Protein dynamics (for neuron m) - computation from analytic functions
#if PLASTICITY == CALCIUM_AND_STC || PLASTICITY == STDP_AND_STC
#ifdef TWO_NEURONS_ONE_SYNAPSE
ps_glob = ps_glob || (sum_h_diff[m] >= theta_pro_c);
#endif
#if PROTEIN_POOLS == POOLS_PD || PROTEIN_POOLS == POOLS_PCD
double pa_p = neurons[m].getPProteinAmount();
double pa_d = neurons[m].getDProteinAmount();
double p_synth_end_p = 0.;
double p_synth_end_d = 0.;
// Potentiation pool
if (sum_h_diff_p[m] > theta_pro_p) // still rising
{
ps_neuron = ps_neuron || true;
p_synth_end_p = tau_h / 0.1 * log(sum_h_diff_p[m] / theta_pro_p);
if (delta_t < p_synth_end_p) // rising phase only
{
pa_p = pa_p * exp(-delta_t/(tau_pp * 3600.)) + alpha_p * (1. - exp(-delta_t/(tau_pp * 3600.)));
}
else // rising phase transitioning to declining phase
{
pa_p = pa_p * exp(-p_synth_end_p/(tau_pp * 3600.)) + alpha_p * (1. - exp(-p_synth_end_p/(tau_pp * 3600.)));
pa_p = pa_p * exp(-(delta_t-p_synth_end_p)/(tau_pp * 3600.));
*logf << "Protein synthesis (P) ending in neuron " << m << " (t = " << p_synth_end_p + tb*dt << " s)" << endl;
}
}
else // declining phase only
{
pa_p = pa_p * exp(-delta_t/(tau_pp * 3600.));
}
// Depression pool
if (sum_h_diff_d[m] > theta_pro_d) // still rising
{
ps_neuron = ps_neuron || true;
p_synth_end_d = tau_h / 0.1 * log(sum_h_diff_d[m] / theta_pro_d);
if (delta_t < p_synth_end_d) // rising phase only
{
pa_d = pa_d * exp(-delta_t/(tau_pd * 3600.)) + alpha_d * (1. - exp(-delta_t/(tau_pd * 3600.)));
}
else // rising phase transitioning to declining phase
{
pa_d = pa_d * exp(-p_synth_end_d/(tau_pd * 3600.)) + alpha_d * (1. - exp(-p_synth_end_d/(tau_pd * 3600.)));
pa_d = pa_d * exp(-(delta_t-p_synth_end_d)/(tau_pd * 3600.));
*logf << "Protein synthesis (D) ending in neuron " << m << " (t = " << p_synth_end_d + tb*dt << " s)" << endl;
}
}
else // declining phase only
{
pa_d = pa_d * exp(-delta_t/(tau_pd * 3600.));
}
sum_h_diff_p[m] = 0.;
sum_h_diff_d[m] = 0.;
#else
double pa_p = 0.;
double pa_d = 0.;
#endif
#if PROTEIN_POOLS == POOLS_C || PROTEIN_POOLS == POOLS_PCD
double pa_c = neurons[m].getCProteinAmount();
double p_synth_end_c = 0.;
// Common pool
if (sum_h_diff[m] > theta_pro_c) // still rising
{
ps_neuron = ps_neuron || true;
p_synth_end_c = tau_h / 0.1 * log(sum_h_diff[m] / theta_pro_c);
if (delta_t < p_synth_end_c) // rising phase only
{
pa_c = pa_c * exp(-delta_t/(tau_pc * 3600.)) + alpha_c * (1. - exp(-delta_t/(tau_pc * 3600.)));
}
else // rising phase transitioning to declining phase
{
pa_c = pa_c * exp(-p_synth_end_c/(tau_pc * 3600.)) + alpha_c * (1. - exp(-p_synth_end_c/(tau_pc * 3600.)));
pa_c = pa_c * exp(-(delta_t-p_synth_end_c)/(tau_pc * 3600.));
*logf << "Protein synthesis (C) ending in neuron " << m << " (t = " << p_synth_end_c + tb*dt << " s)" << endl;
}
}
else // declining phase only
{
pa_c = pa_c * exp(-delta_t/(tau_pc * 3600.));
}
sum_h_diff[m] = 0.;
#else
double pa_c = 0.;
#endif
neurons[m].setProteinAmounts(pa_p, pa_c, pa_d);
#endif // PLASTICITY == CALCIUM_AND_STC || PLASTICITY == STDP_AND_STC
}
/*******************************************************/
// compute synaptic dynamics
for (int m=0; m<N; m++) // loop over presynaptic neurons (in consecutive order)
{
for (int in=0; in<neurons[m].getNumberOutgoing(); in++) // loop over postsynaptic neurons
{
int n = neurons[m].getOutgoingConnection(in); // get index (in consecutive order) of postsynaptic neuron
double h_dev; // the deviation of the early-phase weight from its resting state
// Long-term plasticity
if (m < pow2(Nl_exc) && n < pow2(Nl_exc)) // plasticity only for exc. -> exc. connections
{
#if PLASTICITY == CALCIUM || PLASTICITY == CALCIUM_AND_STC
// early-phase weight just decays
double hexp = exp(-delta_t*0.1/tau_h);
h[m][n] = h[m][n] * hexp + h_0 * (1.- hexp);
// [simple Euler: h[m][n] += ((0.1 * (h_0 - h[m][n]))*(delta_t/tau_h));]
h_dev = h[m][n] - h_0;
#if PROTEIN_POOLS == POOLS_PD || PROTEIN_POOLS == POOLS_PCD
if (h_dev > 0.)
sum_h_diff_p[n] += h_dev; // sum of early-phases changes (for LTP-related protein synthesis)
else if (h_dev < 0.)
sum_h_diff_d[n] -= h_dev; // sum of early-phases changes (for LTD-related protein synthesis)
#endif
#if PROTEIN_POOLS == POOLS_C || PROTEIN_POOLS == POOLS_PCD
sum_h_diff[n] += abs(h_dev); // sum of early-phases changes (for protein synthesis)
#endif
#endif // PLASTICITY == CALCIUM || PLASTICITY == CALCIUM_AND_STC
#if PLASTICITY == CALCIUM_AND_STC || PLASTICITY == STDP_AND_STC
// L-LTP/-LTD
if (h_dev >= theta_tag_p) // LTP
{
#if PROTEIN_POOLS == POOLS_PCD
double pa = neurons[n].getPProteinAmount()*neurons[n].getCProteinAmount(); // LTP protein amount times common protein amount from previous timestep
#elif PROTEIN_POOLS == POOLS_PD
double pa = neurons[n].getPProteinAmount(); // LTP protein amountfrom previous timestep
#elif PROTEIN_POOLS == POOLS_C
double pa = neurons[n].getCProteinAmount(); // common protein amount from previous timestep
#endif
#ifdef TWO_NEURONS_ONE_SYNAPSE
tag_glob = true;
#endif
if (pa > EPSILON)
{
//double zexp = exp(-delta_t / (tau_z * 60.) * pa*(step1 + step2));
double zexp = exp(-delta_t / (tau_z * 60. * z_max) * pa);
z[m][n] = z[m][n] * zexp + z_max * (1. - zexp);
STC = true;
}
}
else if (-h_dev >= theta_tag_d) // LTD
{
#if PROTEIN_POOLS == POOLS_PCD
double pa = neurons[n].getDProteinAmount()*neurons[n].getCProteinAmount(); // LTD protein amount times common protein amount from previous timestep
#elif PROTEIN_POOLS == POOLS_PD
double pa = neurons[n].getDProteinAmount(); // LTD protein amountfrom previous timestep
#elif PROTEIN_POOLS == POOLS_C
double pa = neurons[n].getCProteinAmount(); // common protein amount from previous timestep
#endif
#ifdef TWO_NEURONS_ONE_SYNAPSE
tag_glob = true;
#endif
if (pa > EPSILON)
{
//double zexp = exp(-delta_t / (tau_z * 60.) * pa*(step1 + step2));
double zexp = exp(-delta_t / (tau_z * 60.) * pa);
z[m][n] = z[m][n] * zexp - 0.5 * (1. - zexp);
STC = true;
}
}
// [simple Euler: z[m][n] += (pa * ((1 - z[m][n]) * step1 - (0.5 + z[m][n]) * step2) * (delta_t / (tau_z * 6.0 * 10)));]
#endif // PLASTICITY == CALCIUM_AND_STC || PLASTICITY == STDP_AND_STC
} // plasticity within excitatory population
} // loop over postsynaptic neurons
} // loop over presynaptic neurons
if (!STC) // no late-phase dynamics can take place anymore
{
return false;
}
return true;
}
/*** getSumDiff ***
* Returns the sum of absolute values of weight differences to the initial value for a specific neuron *
* - n: number of the neuron to be considered *
* - return: sum_h_diff for a specific neuron */
double getSumDiff(int n)
{
return sum_h_diff[n];
}
#ifdef TWO_NEURONS_ONE_SYNAPSE
/*** getPlasticityType ***
* Returns the kind of plasticity evoked by the stimulus *
* - return: 0 for ELTP, 1 for ELTP with tag, 2 for LLTP, 3 for ELTD, 4 for ELTD with tag, 5 for LLTD, -1 else */
int getPlasticityType()
{
if (max_dev > EPSILON) // LTP
{
if (!tag_glob)
return 0;
else
{
if (!ps_glob)
return 1;
else
return 2;
}
}
else if (max_dev < -EPSILON) // LTD
{
if (!tag_glob)
return 3;
else
{
if (!ps_glob)
return 4;
else
return 5;
}
}
return -1;
}
/*** getMaxDev ***
* Returns the maximum deviation from h_0 *
* - return: max_dev*/
double getMaxDev()
{
return max_dev;
}
#endif
/*** getTagVanishTime ***
* Returns the time by which all tags will have vanished, based on *
* the largest early-phase deviation from the mean h_0 (max_dev) *
* - return: the time difference */
double getTagVanishTime()
{
double tag_vanish = tau_h / 0.1 * log(abs(max_dev) / min(theta_tag_p, theta_tag_d));
if (abs(max_dev) > EPSILON && tag_vanish > EPSILON)
return tag_vanish + tb_max_dev*dt;
else
return 0.;
}
/*** getProteinSynthesisEnd ***
* Returns the time (for every pool) by which all protein synthesis will halt, based on the *
* largest sum of early-phase deviations from the mean h_0 (max_sum_diff*) *
* - return: the times for the different pools (P,C,D) in a vector */
vector<double> getProteinSynthesisEnd()
{
vector<double> ret(3,0.);
#if PROTEIN_POOLS == POOLS_C || PROTEIN_POOLS == POOLS_PCD
if (max_sum_diff > theta_pro_c)
ret[1] = tau_h / 0.1 * log(max_sum_diff / theta_pro_c) + tb_max_sum_diff*dt;
#endif
#if PROTEIN_POOLS == POOLS_PD || PROTEIN_POOLS == POOLS_PCD
if (max_sum_diff_p > theta_pro_p)
ret[0] = tau_h / 0.1 * log(max_sum_diff_p / theta_pro_p) + tb_max_sum_diff_p*dt;
if (max_sum_diff_d > theta_pro_d)
ret[2] = tau_h / 0.1 * log(max_sum_diff_d / theta_pro_d) + tb_max_sum_diff_d*dt;
#endif
return ret;
}
/*** getThreshold ***
* Returns a specified threshold value (for tag or protein synthesis) *
* - plast: the type of plasticity (1: LTP, 2: LTD)
* - which: the type of threshold (1: early-phase calcium treshold, 2: tagging threshold, 3: protein synthesis threshold)
* - return: the threshold value */
double getThreshold(int plast, int which)
{
if (plast == 1) // LTP
{
if (which == 1) // early-phase calcium treshold
return theta_p;
else if (which == 2) // tagging threshold
return theta_tag_p;
else // protein synthesis threshold
return theta_pro_p;
}
else // LTD
{
if (which == 1) // early-phase calcium treshold
return theta_d;
else if (which == 2) // tagging threshold
return theta_tag_d;
else // protein synthesis threshold
return theta_pro_d;
}
}
/*** setRhombStimulus ***
* Sets a spatially rhomb-shaped firing rate stimulus in the exc. population *
* - Stimulus& _st: shape of one stimulus period *
* - int center: the index of the neuron in the center of the rhomb *
* - int radius: the "radius" of the rhomb in neurons (radius 3 corresponds to a rhomb containing 25 neurons, radius 4 to 41, radius 5 to 61, radius 9 to 181) */
void setRhombStimulus(Stimulus& _st, int center, int radius)
{
for (int i=-radius; i<=radius; i++)
{
int num_cols = (radius-abs(i));
for (int j=-num_cols; j<=num_cols; j++)
{
neurons[center+i*Nl_exc+j].setCurrentStimulus(_st); // set temporal course of current stimulus for given neuron
}
}
setStimulationEnd(_st.getStimulationEnd());
}
/*** setRhombPartialRandomStimulus ***
* Sets stimulation for randomly drawn neurons out of a rhomb shape in the exc. population *
* - Stimulus& _st: shape of one stimulus period *
* - int center: the index of the neuron in the center of the rhomb *
* - int radius: the "radius" of the rhomb in neurons (radius 3 corresponds to a rhomb containing 25 neurons) *
* - double fraction: the fraction of neurons in the rhomb that shall be stimulated */
void setRhombPartialRandomStimulus(Stimulus& _st, int center, int radius, double fraction)
{
int total_assembly_size = 2*pow2(radius) + 2*radius + 1; // total number of neurons within the rhomb
int ind = 0, count = 0;
uniform_int_distribution<int> rhomb_dist(1, total_assembly_size);
int* indices; // array of indices (consectuive neuron numbers) for rhomb neurons
indices = new int[total_assembly_size];
// gather indices of neurons belonging to the rhomb
for (int i=-radius; i<=radius; i++)
{
int num_cols = (radius-abs(i));
for (int j=-num_cols; j<=num_cols; j++)
{
indices[ind++] = center+i*Nl_exc+j;
}
}
// draw random neurons out of the rhomb
while(count < fraction*total_assembly_size)
{
int chosen_n = rhomb_dist(rg);
if (indices[chosen_n-1] >= 0) // found a neuron that has not be assigned a stimulus
{
neurons[indices[chosen_n-1]].setCurrentStimulus(_st); // set temporal course of current stimulus for given neuron
count++;
indices[chosen_n-1] = -1;
}
}
setStimulationEnd(_st.getStimulationEnd());
delete[] indices;
}
/*** setRhombPartialStimulus ***
* Sets stimulation for first fraction of neurons out of a rhomb shape in the exc. population *
* - Stimulus& _st: shape of one stimulus period *
* - int center: the index of the neuron in the center of the rhomb *
* - int radius: the "radius" of the rhomb in neurons (radius 3 corresponds to a rhomb containing 25 neurons) *
* - double fraction: the fraction of neurons in the rhomb that shall be stimulated */
void setRhombPartialStimulus(Stimulus& _st, int center, int radius, double fraction)
{
int count = int(fraction * (2*radius*(radius+1)+1));
for (int i=-radius; i<=radius; i++)
{
int num_cols = (radius-abs(i));
for (int j=-num_cols; j<=num_cols; j++)
{
neurons[center+i*Nl_exc+j].setCurrentStimulus(_st); // set temporal course of current stimulus for given neuron
count--;
if (count == 0)
break;
}
if (count == 0)
break;
}
setStimulationEnd(_st.getStimulationEnd());
}
/*** setRandomStimulus ***
* Sets a randomly distributed firing rate stimulus in the exc. population *
* - Stimulus& _st: shape of one stimulus period *
* - int num: the number of neurons to be drawn (i.e., to be stimulated) *
* - ofstream* f [optional]: handle to a file for output of the randomly drawn neuron numbers *
* - int range_start [optional]: the lowest neuron number that can be drawn *
* - int range_end [optional]: one plus the highest neuron number that can be drawn (-1: highest possible) */
void setRandomStimulus(Stimulus& _st, int num, ofstream* f = NULL, int range_start=0, int range_end=-1)
{
int range_len = (range_end == -1) ? (pow2(Nl_exc) - range_start) : (range_end - range_start); // the number of neurons eligible for being drawn
bool* stim_neurons = new bool [range_len];
uniform_int_distribution<int> u_dist_neurons(0, range_len-1); // uniform distribution to draw neuron numbers
int neurons_left = num;
if (f != NULL)
*f << "Randomly drawn neurons for stimulation:" << " { ";
for (int i=0; i<range_len; i++)
stim_neurons[i] = false;
while (neurons_left > 0)
{
int neur = u_dist_neurons(rg); // draw a neuron
if (!stim_neurons[neur]) // if the stimulus has not yet been assigned to the drawn neuron
{
neurons[neur+range_start].setCurrentStimulus(_st); // set temporal course of current stimulus for drawn neuron
stim_neurons[neur] = true;
neurons_left--;
if (f != NULL)
*f << neur+range_start << ", "; // print stimulated neuron to file
}
}
setStimulationEnd(_st.getStimulationEnd());
if (f != NULL)
*f << " }" << endl;
delete[] stim_neurons;
}
/*** setSingleNeuronStimulus ***
* Sets a firing rate stimulus for a specified neuron *
* - int m: number of the neuron to be stimulated *
* - Stimulus& _st: shape of one stimulus period */
void setSingleNeuronStimulus(int m, Stimulus& _st)
{
neurons[m].setCurrentStimulus(_st);
setStimulationEnd(_st.getStimulationEnd());
}
/*** setBlockStimulus ***
* Sets a stimulus for a given block of n neurons in the network *
* - Stimulus& _st: shape of one stimulus period *
* - int n: the number of neurons that shall be stimulated *
* - int off [optional]: the offset that defines at which neuron number the block begins */
void setBlockStimulus(Stimulus& _st, int n, int off=0)
{
for (int i=off; i<(n+off); i++)
{
neurons[i].setCurrentStimulus(_st); // set temporal course of current stimulus for given neuron
}
setStimulationEnd(_st.getStimulationEnd());
}
/*** setConstCurrent ***
* Sets the constant current for all neurons to a newly defined value
* - double _I_const: constant current in nA */
void setConstCurrent(double _I_const)
{
for (int m=0; m<N; m++)
{
neurons[m].setConstCurrent(_I_const);
}
}
#if STIPULATE_CA == ON
/*** stipulateRhombAssembly ***
* Stipulates a rhomb-shaped cell assembly with strong interconnections *
* - int center: the index of the neuron in the center of the rhomb *
* - int radius: the "radius" of the rhomb in neurons (radius 3 corresponds to a rhomb containing 25 neurons, radius 5 to 61 neurons) */
void stipulateRhombAssembly(int center, int radius)
{
double value = 2*h_0; // stipulated value
for (int i=-radius; i<=radius; i++)
{
int num_cols = (radius-abs(i));
for (int j=-num_cols; j<=num_cols; j++)
{
int m = center+i*Nl_exc+j;
for (int k=-radius; k<=radius; k++)
{
int num_cols = (radius-abs(k));
for (int l=-num_cols; l<=num_cols; l++)
{
int n = center+k*Nl_exc+l;
if (conn[m][n]) // set all connections within the assembly to this value
h[m][n] = value;
}
}
}
}
}
/*** stipulateFirstNeuronsAssembly ***
* Stipulates an cell assembly consisting of the first neurons with strong interconnections *
* - int n: the number of neurons that shall be stimulated */
void stipulateFirstNeuronsAssembly(int n)
{
double value = 2*h_0; // stipulated value
for (int i=0; i<n; i++)
{
for (int j=0; j<n; j++)
{
if (conn[i][j]) // set all connections within the assembly to this value
h[i][j] = value;
}
}
}
#endif
/*** setSigma ***
* Sets the standard deviation for the external input current for all neurons to a newly defined value
* - double _sigma: standard deviation in nA s^(1/2) */
void setSigma(double _sigma)
{
for (int m=0; m<N; m++)
{
neurons[m].setSigma(_sigma);
}
}
/*** setSynTimeConstant ***
* Sets the synaptic time constant *
* - double _tau_syn: synaptic time constant in s */
void setSynTimeConstant(double _tau_syn)
{
tau_syn = _tau_syn;
for (int m=0; m<N; m++)
{
neurons[m].setTauOU(tau_syn);
}
}
/*** setCouplingStrengths ***
* Sets the synaptic coupling strengths *
* - double _w_ee: coupling strength for exc. -> exc. connections in units of h_0 *
* - double _w_ei: coupling strength for exc. -> inh. connections in units of h_0 *
* - double _w_ie: coupling strength for inh. -> exc. connections in units of h_0 *
* - double _w_ii: coupling strength for inh. -> inh. connections in units of h_0 */
void setCouplingStrengths(double _w_ee, double _w_ei, double _w_ie, double _w_ii)
{
w_ee = _w_ee * h_0;
w_ei = _w_ei * h_0;
w_ie = _w_ie * h_0;
w_ii = _w_ii * h_0;
}
/*** getInitialWeight ***
* Returns the initial exc.->exc. weight (typically h_0) */
double getInitialWeight()
{
return w_ee;
}
/*** getSynapticCalcium ***
* Returns the calcium amount at a given synapse *
* - synapse s: structure specifying pre- and postsynaptic neuron *
* - return: the synaptic calcium amount */
double getSynapticCalcium(synapse s) const
{
return Ca[s.presyn_neuron][s.postsyn_neuron];
}
/*** getEarlySynapticStrength ***
* Returns the early-phase synaptic strength at a given synapse *
* - synapse s: structure specifying pre- and postsynaptic neuron *
* - return: the early-phase synaptic strength */
double getEarlySynapticStrength(synapse s) const
{
return h[s.presyn_neuron][s.postsyn_neuron];
}
/*** getLateSynapticStrength ***
* Returns the late-phase synaptic strength at a given synapse *
* - synapse s: structure specifying pre- and postsynaptic neuron *
* - return: the late-phase synaptic strength */
double getLateSynapticStrength(synapse s) const
{
return z[s.presyn_neuron][s.postsyn_neuron];
}
/*** getMeanEarlySynapticStrength ***
* Returns the mean early-phase synaptic strength (averaged over all synapses within the given set of neurons) *
* - int n: the number of neurons that shall be considered (e.g., n=Nl_exc^2 for all excitatory neurons, or n=N for all neurons) *
* - int off [optional]: the offset that defines at which neuron number the considered range begins *
* - return: the mean early-phase synaptic strength */
double getMeanEarlySynapticStrength(int n, int off=0) const
{
double h_mean = 0.;
int c_number = 0;
for (int i=off; i < (n+off); i++)
{
for (int j=off; j < (n+off); j++)
{
if (conn[i][j])
{
c_number++;
h_mean += h[i][j];
}
}
}
h_mean /= c_number;
return h_mean;
}
/*** getMeanLateSynapticStrength ***
* Returns the mean late-phase synaptic strength (averaged over all synapses within the given set of neurons) *
* - int n: the number of neurons that shall be considered (e.g., n=Nl_exc^2 for all excitatory neurons, or n=N for all neurons) *
* - int off [optional]: the offset that defines at which neuron number the considered range begins *
* - return: the mean late-phase synaptic strength */
double getMeanLateSynapticStrength(int n, int off=0) const
{
double z_mean = 0.;
int c_number = 0;
for (int i=off; i < (n+off); i++)
{
for (int j=off; j < (n+off); j++)
{
if (conn[i][j])
{
c_number++;
z_mean += z[i][j];
}
}
}
z_mean /= c_number;
return z_mean;
}
/*** getSDEarlySynapticStrength ***
* Returns the standard deviation of the early-phase synaptic strength (over all synapses within the given set of neurons) *
* - double mean: the mean of the early-phase syn. strength within the given set
* - int n: the number of neurons that shall be considered (e.g., n=Nl_exc^2 for all excitatory neurons, or n=N for all neurons) *
* - int off [optional]: the offset that defines at which neuron number the considered range begins *
* - return: the std. dev. of the early-phase synaptic strength */
double getSDEarlySynapticStrength(double mean, int n, int off=0) const
{
double h_sd = 0.;
int c_number = 0;
for (int i=off; i < (n+off); i++)
{
for (int j=off; j < (n+off); j++)
{
if (conn[i][j])
{
c_number++;
h_sd += pow2(h[i][j] - mean);
}
}
}
h_sd = sqrt(h_sd / c_number);
return h_sd;
}
/*** getSDLateSynapticStrength ***
* Returns the standard deviation of the late-phase synaptic strength (over all synapses within the given set of neurons) *
* - double mean: the mean of the late-phase syn. strength within the given set
* - int n: the number of neurons that shall be considered (e.g., n=Nl_exc^2 for all excitatory neurons, or n=N for all neurons) *
* - int off [optional]: the offset that defines at which neuron number the considered range begins *
* - return: the std. dev. of the late-phase synaptic strength */
double getSDLateSynapticStrength(double mean, int n, int off=0) const
{
double z_sd = 0.;
int c_number = 0;
for (int i=off; i < (n+off); i++)
{
for (int j=off; j < (n+off); j++)
{
if (conn[i][j])
{
c_number++;
z_sd += pow2(z[i][j] - mean);
}
}
}
z_sd = sqrt(z_sd / c_number);
return z_sd;
}
/*** getMeanCProteinAmount ***
* Returns the mean protein amount (averaged over all neurons within the given set) *
* - int n: the number of neurons that shall be considered (e.g., n=Nl_exc^2 for all excitatory neurons, or n=N for all neurons) *
* - int off [optional]: the offset that defines at which neuron number the considered range begins *
* - return: the mean protein amount */
double getMeanCProteinAmount(int n, int off=0) const
{
double pa = 0.;
for (int i=off; i < (n+off); i++)
{
pa += neurons[i].getCProteinAmount();
}
pa /= n;
return pa;
}
/*** getSDCProteinAmount ***
* Returns the standard deviation of the protein amount (over all neurons within the given set) *
* - double mean: the mean of the protein amount within the given set
* - int n: the number of neurons that shall be considered (e.g., n=Nl_exc^2 for all excitatory neurons, or n=N for all neurons) *
* - int off [optional]: the offset that defines at which neuron number the considered range begins *
* - return: the std. dev. of the protein amount */
double getSDCProteinAmount(double mean, int n, int off=0) const
{
double pa_sd = 0.;
for (int i=off; i < (n+off); i++)
{
pa_sd += pow2(neurons[i].getCProteinAmount() - mean);
}
pa_sd = sqrt(pa_sd / n);
return pa_sd;
}
/*** readConnections ***
* Reads the connectivity matrix from a file, either given by a text-converted numpy array or a plain matrix structure *
* - file: a text file where the matrix is located *
* - format: 0 for plain matrix structure, 1 for numpy structure with square brackets
* - return: 2 - successful, 1 - file could not opened, 0 - dimension mismatch */
int readConnections(string file, int format = 0)
{
ifstream f(file, ios::in); // the file handle
string buf; // buffer to read one line
int m, n = 0; // pre- and postsynaptic neuron
int initial_brackets = 0; // specifies if the initial brackets have been read yet
if (!f.is_open()) // check if file was opened successfully
return 1;
for (int a=0;a<N;a++) // reset connections of all neurons
neurons[a].resetConnections();
if (format == 0)
m = -1;
else
m = 0;
while (getline(f, buf)) // while end of file has not yet been reached
{
if (format == 0 && buf.size() > 0)
{
m++;
n = 0;
}
for (int i=0; i<buf.size(); i++) // go through all characters in this line
{
if (format == 1 && buf[i] == '[')
{
if (initial_brackets < 2) // still reading the initial brackets
initial_brackets++;
else
{
m++;
n = 0;
}
}
else if (buf[i] == '1')
{
if (m < pow2(Nl_exc) && n < pow2(Nl_exc)) // exc. -> exc.
{
neurons[m].addOutgoingConnection(n, TYPE_EXC);
//cout << m << " -> " << n << " added" << endl;
neurons[n].incNumberIncoming(TYPE_EXC);
}
else if (m < pow2(Nl_exc) && n >= pow2(Nl_exc)) // exc. -> inh.
{
neurons[m].addOutgoingConnection(n, TYPE_INH);
//cout << m << " -> " << n << " added" << endl;
neurons[n].incNumberIncoming(TYPE_EXC);
}
else if (m >= pow2(Nl_exc) && n < pow2(Nl_exc)) // inh. -> exc.
{
neurons[m].addOutgoingConnection(n, TYPE_EXC);
//cout << m << " -> " << n << " added" << endl;
neurons[n].incNumberIncoming(TYPE_INH);
}
else if (m >= pow2(Nl_exc) && n >= pow2(Nl_exc)) // inh. -> inh.
{
neurons[m].addOutgoingConnection(n, TYPE_INH);
//cout << m << " -> " << n << " added" << endl;
neurons[n].incNumberIncoming(TYPE_INH);
}
conn[m][n] = true;
n++;
}
else if (buf[i] == '0')
{
conn[m][n] = false;
n++;
}
}
}
f.close();
reset();
if (m != (N-1) || n != N) // if dimensions do not match
return 0;
return 2;
}
/*** printConnections ***
* Prints the connection matrix to a given file (either in numpy structure or in plain matrix structure) *
* - file: a text file where the matrix is located *
* - format: 0 for plain matrix structure, 1 for numpy structure with square brackets
* - return: 2 - successful, 1 - file could not opened */
int printConnections(string file, int format = 0)
{
ofstream f(file); // the file handle
if (!f.is_open()) // check if file was opened successfully
return 1;
if (format == 1)
f << "[";
for (int m=0;m<N;m++)
{
if (format == 1)
f << "[";
for (int n=0;n<N;n++)
{
if (conn[m][n])
f << "1 ";
else
f << "0 ";
}
if (format == 1)
f << "]";
f << endl;
}
if (format == 1)
f << "]";
f.close();
return 2;
}
/*** printConnections2 ***
* FOR TESTING THE CONNECTIONS SAVED IN ARRAYS IN NEURONS *
* - file: a text file where the matrix is located *
* - format: 0 for plain matrix structure, 1 for numpy structure with square brackets
* - return: 2 - successful, 1 - file could not opened *
int printConnections2(string file, int format = 0)
{
ofstream f(file); // the file handle
if (!f.is_open()) // check if file was opened successfully
return 1;
if (format == 1)
f << "[";
for (int m=0;m<N;m++)
{
if (format == 1)
f << "[";
int in=0;
for (int n=0;n<N;n++)
{
if (conn[m][n] && neurons[m].getNumberOutgoing() > in && neurons[m].getOutgoingConnection(in) == n)
{
f << "1 ";
in++;
}
else
f << "0 ";
}
if (format == 1)
f << "]";
f << endl;
}
if (format == 1)
f << "]";
f.close();
return 2;
}*/
/*** printAllInitialWeights ***
* Prints the connection matrix to a given file (either in numpy structure or in plain matrix structure) *
* - file: a text file where the matrix is located *
* - format: 0 for plain matrix structure, 1 for numpy structure with square brackets
* - return: 2 - successful, 1 - file could not opened */
int printAllInitialWeights(string file, int format = 0)
{
ofstream f(file); // the file handle
if (!f.is_open()) // check if file was opened successfully
return 1;
if (format == 1)
f << "[";
for (int m=0;m<N;m++)
{
if (format == 1)
f << "[";
for (int n=0;n<N;n++)
{
// Output of all initial weights
if (conn[m][n])
{
if (m < pow2(Nl_exc) && n < pow2(Nl_exc)) // exc. -> exc.
f << h[m][n] << " ";
else if (m < pow2(Nl_exc) && n >= pow2(Nl_exc)) // exc. -> inh.
f << w_ei << " ";
else if (m >= pow2(Nl_exc) && n < pow2(Nl_exc)) // inh. -> exc.
f << w_ie << " ";
else if (m >= pow2(Nl_exc) && n >= pow2(Nl_exc)) // inh. -> inh.
f << w_ii << " ";
}
else
f << 0. << " ";
}
if (format == 1)
f << "]";
f << endl;
}
if (format == 1)
f << "]";
f.close();
return 2;
}
/*** readCouplingStrengths ***
* Reads the excitatory coupling strengths from a text file that contains a matrix for early-phase weights and a matrix *
* for late-phase weights, each terminated by a blank line *
* - file: a text file where the matrix is located *
* - return: 2 - successful, 1 - file could not opened, 0 - dimension mismatch */
int readCouplingStrengths(string file)
{
int phase = 1; // 1: reading early-phase values, 2: reading late-phase values
int m = 0, n; // pre- and postsynaptic neuron
double strength;
ifstream f(file, ios::in); // the file handle
string buf; // buffer to read one line
if (!f.is_open())
return 1;
// Read early- and late-phase matrix
while (getline (f, buf))
{
istringstream iss(buf);
if (!buf.empty())
{
n = 0;
while(iss >> strength)
{
if (phase == 1)
h[m][n] = strength;
else
z[m][n] = strength;
n++;
}
m++;
}
else // blank line encountered
{
if (phase == 1) // now begins the second phase
{
if (m != pow2(Nl_exc) || n != pow2(Nl_exc)) // if dimensions do not match
{
f.close();
return 0;
}
phase = 2;
m = 0;
n = 0;
}
else
break;
}
}
f.close();
if (m != pow2(Nl_exc) || n != pow2(Nl_exc)) // if dimensions do not match
{
return 0;
}
return 2;
}
/*** setStimulationEnd ***
* Tells the Network instance the end of stimulation (even if not all stimuli are yet set) *
* - int stim_end: the timestep in which stimulation ends */
void setStimulationEnd(int stim_end)
{
if (stim_end > stimulation_end)
stimulation_end = stim_end;
}
/*** setSpikeStorageTime ***
* Sets the number of timesteps for which spikes have to be kept in RAM *
* - int storage_steps: the size of the storage timespan in timesteps */
void setSpikeStorageTime(int storage_steps)
{
for (int m=0; m<N; m++)
{
neurons[m].setSpikeHistoryMemory(storage_steps);
}
}
/*** resetLastSpikeIndex ***
* Resets the last spike index of a neuron important to its calcium dynamics *
* - int m: the neuron number */
void resetLastSpikeIndex(int m)
{
last_Ca_spike_index[m] = 1;
}
/*** resetPlasticity ***
* Depending on the arguments, undoes plastic changes that the network has undergone, *
* resets calcium values or protein values *
* - bool early_phase: resets all early-phase weights and calcium concentrations *
* - bool late_phase: resets all late-phase weights *
* - bool calcium: resets all calcium concentrations *
* - bool proteins: resets all neuronal protein pools */
void resetPlasticity(bool early_phase, bool late_phase, bool calcium, bool proteins)
{
for (int m=0; m<N; m++)
{
if (proteins)
neurons[m].setProteinAmounts(0., 0., 0.);
for (int n=0; n<N; n++) // reset synapses
{
if (early_phase)
{
if (conn[m][n])
h[m][n] = h_0;
else
h[m][n] = 0.;
}
if (calcium)
Ca[m][n] = 0.;
if (late_phase)
z[m][n] = 0.;
}
}
}
/*** reset ***
* Resets the network and all neurons to initial state (but maintain connectivity) */
void reset()
{
rg.seed(getClockSeed()); // set new seed by clock's epoch
u_dist.reset(); // reset the uniform distribution for random numbers
norm_dist.reset(); // reset the normal distribution for random numbers
for (int m=0; m<N; m++)
{
neurons[m].reset();
for (int n=0; n<N; n++) // reset synapses
{
if (conn[m][n])
h[m][n] = h_0;
else
h[m][n] = 0.;
Ca[m][n] = 0.;
z[m][n] = 0.;
}
resetLastSpikeIndex(m);
sum_h_diff[m] = 0.;
sum_h_diff_p[m] = 0.;
sum_h_diff_d[m] = 0.;
}
stimulation_end = 0;
max_dev = 0.;
tb_max_dev = 0;
#if PROTEIN_POOLS == POOLS_C || PROTEIN_POOLS == POOLS_PCD
max_sum_diff = 0.;
tb_max_sum_diff = 0;
#endif
#if PROTEIN_POOLS == POOLS_PD || PROTEIN_POOLS == POOLS_PCD
max_sum_diff_p = 0.;
tb_max_sum_diff_p = 0;
max_sum_diff_d = 0.;
tb_max_sum_diff_d = 0;
#endif
#ifdef TWO_NEURONS_ONE_SYNAPSE
tag_glob = false;
ps_glob = false;
#endif
}
/*** setCaConstants ***
* Set constants for the calcium dynamics *
* - double _theta_p: the potentiation threshold *
* - double _theta_d: the potentiation threshold */
void setCaConstants(double _theta_p, double _theta_d, double _Ca_pre, double _Ca_post)
{
theta_p = _theta_p;
theta_d = _theta_d;
Ca_pre = _Ca_pre;
Ca_post = _Ca_post;
}
/*** setPSThresholds ***
* Set thresholds for the onset of protein synthesis *
* - double _theta_pro_P: the threshold for P synthesis (in units of h0) *
* - double _theta_pro_C: the threshold for C synthesis (in units of h0) *
* - double _theta_pro_D: the threshold for D synthesis (in units of h0) */
void setPSThresholds(double _theta_pro_P, double _theta_pro_C, double _theta_pro_D)
{
theta_pro_p = _theta_pro_P*h_0;
theta_pro_c = _theta_pro_C*h_0;
theta_pro_d = _theta_pro_D*h_0;
}
/*** Constructor ***
* Sets all parameters, creates neurons and synapses *
* --> it is required to call setSynTimeConstant and setCouplingStrengths immediately *
* after calling this constructor! *
* - double _dt: the length of one timestep in s *
* - int _Nl_exc: the number of neurons in one line in excitatory population (row/column) *
* - int _Nl_inh: the number of neurons in one line in inhibitory population (row/column) - line structure so that stimulation of inhib. *
population could be implemented more easily *
* - double _p_c: connection probability *
* - double _sigma_plasticity: standard deviation of the plasticity *
* - double _z_max: the upper z bound */
Network(const double _dt, const int _Nl_exc, const int _Nl_inh, double _p_c, double _sigma_plasticity, double _z_max) :
dt(_dt), rg(getClockSeed()), u_dist(0.0,1.0), norm_dist(0.0,1.0), Nl_exc(_Nl_exc), Nl_inh(_Nl_inh), z_max(_z_max)
{
N = pow2(Nl_exc) + pow2(Nl_inh); // total number of neurons
p_c = _p_c; // set connection probability
t_syn_delay = 0.003; // from https://www.britannica.com/science/nervous-system/The-neuronal-membrane#ref606406, accessed 18-06-21
#if defined TWO_NEURONS_ONE_SYNAPSE && !defined TWO_NEURONS_ONE_SYNAPSE_ALT
t_syn_delay = dt;
#endif
t_syn_delay_steps = int(t_syn_delay/dt);
// Biophysical parameters for stimulation, Ca dynamics and early phase
t_Ca_delay = 0.0188; // from Graupner and Brunel (2012), hippocampal slices
t_Ca_delay_steps = int(t_Ca_delay/dt);
Ca_pre = 1.0; // from Graupner and Brunel (2012), hippocampal slices
Ca_post = 0.2758; // from Graupner and Brunel (2012), hippocampal slices
tau_Ca = 0.0488; // from Graupner and Brunel (2012), hippocampal slices
tau_Ca_steps = int(tau_Ca/dt);
tau_h = 688.4; // from Graupner and Brunel (2012), hippocampal slices
gamma_p = 1645.6; // from Graupner and Brunel (2012), hippocampal slices
gamma_d = 313.1; // from Graupner and Brunel (2012), hippocampal slices
h_0 = 0.5*(gamma_p/(gamma_p+gamma_d)); // from Li et al. (2016)
theta_p = 3.0; // from Li et al. (2016)
theta_d = 1.2; // from Li et al. (2016)
sigma_plasticity = _sigma_plasticity; // from Graupner and Brunel (2012) but corrected by 1/sqrt(1000)
// Biophysical parameters for protein synthesis and late phase
tau_pp = 1.0; // from Li et al. (2016)
tau_pc = 1.0; // from Li et al. (2016)
tau_pd = 1.0; // from Li et al. (2016)
alpha_p = 1.0; // from Li et al. (2016)
alpha_c = 1.0; // from Li et al. (2016)
alpha_d = 1.0; // from Li et al. (2016)
tau_z = 60.0; // from Li et al. (2016) - includes "gamma"
theta_pro_p = 0.5*h_0; //
theta_pro_c = 0.5*h_0; // from Li et al. (2016)
theta_pro_d = 0.5*h_0; //
theta_tag_p = 0.2*h_0; // from Li et al. (2016)
theta_tag_d = 0.2*h_0; // from Li et al. (2016)
// Create neurons and synapse matrices
neurons = vector<Neuron> (N, Neuron(_dt));
conn = new bool* [N];
Ca = new double* [N];
h = new double* [N];
z = new double* [N];
last_Ca_spike_index = new int [N];
sum_h_diff = new double [N];
sum_h_diff_p = new double [N];
sum_h_diff_d = new double [N];
for (int m=0; m<N; m++)
{
if (m < pow2(Nl_exc)) // first Nl_exc^2 neurons are excitatory
neurons[m].setType(TYPE_EXC);
else // remaining neurons are inhibitory
neurons[m].setType(TYPE_INH);
conn[m] = new bool [N];
Ca[m] = new double [N];
h[m] = new double [N];
z[m] = new double [N];
// create synaptic connections
for (int n=0; n<N; n++)
{
conn[m][n] = false; // necessary for resetting the connections
if (m != n) // if not on main diagonal (which should remain zero)
{
conn[m][n] = shallBeConnected(m, n); // use random generator depending on connection probability
}
}
}
#ifdef TWO_NEURONS_ONE_SYNAPSE
neurons[1].setPoisson(true);
#ifdef PLASTICITY_OVER_FREQ
neurons[0].setPoisson(true);
#endif
#endif
}
/*** Destructor ***
* Cleans up the allocated memory for arrays */
~Network()
{
for(int i=0; i<N; i++)
{
delete[] conn[i];
delete[] Ca[i];
delete[] h[i];
delete[] z[i];
}
delete[] conn;
delete[] Ca;
delete[] h;
delete[] z;
delete[] last_Ca_spike_index;
delete[] sum_h_diff;
delete[] sum_h_diff_p;
delete[] sum_h_diff_d;
}
/* =============================================================================================================================== */
/* ==== Functions redirecting to corresponding functions in Neuron class ========================================================= */
/* Two versions are given for each function, one for consecutive and one for row/column numbering */
/*** getType ***
* Returns the type of neuron (i|j) (inhbitory/excitatory) *
* - int i: the row where the neuron is located *
* - int j: the column where the neuron is located *
* - return: the neuron type */
int getType(int i, int j) const
{
return neurons[cNN(i,j)].getType();
}
int getType(int m) const
{
return neurons[m].getType();
}
/*** getVoltage ***
* Returns the membrane potential of neuron (i|j) *
* - int i: the row where the neuron is located *
* - int j: the column where the neuron is located *
* - return: the membrane potential in mV */
double getVoltage(int i, int j) const
{
return neurons[cNN(i,j)].getVoltage();
}
double getVoltage(int m) const
{
return neurons[m].getVoltage();
}
/*** getThreshold ***
* Returns the value of the dynamic membrane threshold of neuron (i|j) *
* - return: the membrane threshold in mV */
double getThreshold(int i, int j) const
{
return neurons[cNN(i,j)].getThreshold();
}
double getThreshold(int m) const
{
return neurons[m].getThreshold();
}
/*** getCurrent ***
* Returns total current effecting neuron (i|j) *
* - int i: the row where the neuron is located *
* - int j: the column where the neuron is located *
* - return: the instantaneous current in nA */
double getCurrent(int i, int j) const
{
return neurons[cNN(i,j)].getCurrent();
}
double getCurrent(int m) const
{
return neurons[m].getCurrent();
}
/*** getStimulusCurrent ***
* Returns current evoked by external stimulation in neuron (i|j) *
* - int i: the row where the neuron is located *
* - int j: the column where the neuron is located *
* - return: the instantaneous current stimulus in nA */
double getStimulusCurrent(int i, int j) const
{
return neurons[cNN(i,j)].getStimulusCurrent();
}
double getStimulusCurrent(int m) const
{
return neurons[m].getStimulusCurrent();
}
/*** getBGCurrent ***
* Returns background noise current entering neuron (i|j) *
* - int i: the row where the neuron is located *
* - int j: the column where the neuron is located *
* - return: the instantaneous fluctuating current in nA */
double getBGCurrent(int i, int j) const
{
return neurons[cNN(i,j)].getBGCurrent();
}
double getBGCurrent(int m) const
{
return neurons[m].getBGCurrent();
}
/*** getConstCurrent ***
* Returns the constant current elicited by the surrounding network (not this network!) in neuron (i|j) *
* - int i: the row where the neuron is located *
* - int j: the column where the neuron is located *
* - return: the constant current in nA */
double getConstCurrent(int i, int j) const
{
return neurons[cNN(i,j)].getConstCurrent();
}
double getConstCurrent(int m) const
{
return neurons[m].getConstCurrent();
}
/*** getSigma ***
* Returns the standard deviation of the white noise entering the external current *
* - int i: the row where the neuron is located *
* - int j: the column where the neuron is located *
* - return: the standard deviation in nA s^(1/2) */
double getSigma(int i, int j) const
{
return neurons[cNN(i,j)].getSigma();
}
double getSigma(int m) const
{
return neurons[m].getSigma();
}
/*** getSynapticCurrent ***
* Returns the synaptic current that arrived in the previous timestep *
* - int i: the row where the neuron is located *
* - int j: the column where the neuron is located *
* - return: the synaptic current in nA */
double getSynapticCurrent(int i, int j) const
{
return neurons[cNN(i,j)].getSynapticCurrent();
}
double getSynapticCurrent(int m) const
{
return neurons[m].getSynapticCurrent();
}
#if DENDR_SPIKES == ON
/*** getDendriticCurrent ***
* Returns the current that dendritic spiking caused in the previous timestep *
* - int i: the row where the neuron is located *
* - int j: the column where the neuron is located *
* - return: the synaptic current in nA */
double getDendriticCurrent(int i, int j) const
{
return neurons[cNN(i,j)].getDendriticCurrent();
}
double getDendriticCurrent(int m) const
{
return neurons[m].getDendriticCurrent();
}
#endif
#if COND_BASED_SYN == ON
/*** getExcSynapticCurrent ***
* Returns the internal excitatory synaptic current that arrived in the previous timestep *
* - return: the excitatory synaptic current in nA */
double getExcSynapticCurrent(int i, int j) const
{
return neurons[cNN(i,j)].getExcSynapticCurrent();
}
double getExcSynapticCurrent(int m) const
{
return neurons[m].getExcSynapticCurrent();
}
/*** getInhSynapticCurrent ***
* Returns the internal inhibitory synaptic current that arrived in the previous timestep *
* - return: the inhibitory synaptic current in nA */
double getInhSynapticCurrent(int i, int j) const
{
return neurons[cNN(i,j)].getInhSynapticCurrent();
}
double getInhSynapticCurrent(int m) const
{
return neurons[m].getInhSynapticCurrent();
}
#endif
/*** getActivity ***
* Returns true if neuron (i|j) is spiking in this instant of duration dt *
* - int i: the row where the neuron is located *
* - int j: the column where the neuron is located *
* - return: whether neuron is firing or not */
bool getActivity(int i, int j) const
{
return neurons[cNN(i,j)].getActivity();
}
bool getActivity(int m) const
{
return neurons[m].getActivity();
}
/*** spikeAt ***
* Returns whether or not a spike has occurred at a given spike, begins searching *
* from latest spike *
* - int t_step: the timebin at which the spike should have occurred *
* - int i: the row where the neuron is located *
* - int j: the column where the neuron is located *
* - return: true if a spike occurred, false if not */
bool spikeAt(int t_step, int i, int j) const
{
return neurons[cNN(i,j)].spikeAt(t_step);
}
bool spikeAt(int t_step, int m) const
{
return neurons[m].spikeAt(t_step);
}
/*** getSpikeTime ***
* Returns the spike time for a given spike number (in temporal order, starting with 1) of neuron (i|j) *
* ATTENTION: argument n should not exceed the result of getSpikeHistorySize() *
* - int n: the number of the considered spike (in temporal order, starting with 1) *
* - int i: the row where the neuron is located *
* - int j: the column where the neuron is located *
* - return: the spike time for the n-th spike (or -1 if there exists none) */
int getSpikeTime(int n, int i, int j) const
{
return neurons[cNN(i,j)].getSpikeTime(n);
}
int getSpikeTime(int n, int m) const
{
return neurons[m].getSpikeTime(n);
}
/*** removeSpikes ***
* Removes a specified set of spikes from history, to save memory *
* - int start: the number of the spike to start with (in temporal order, starting with 1)
* - int end: the number of the spike to end with (in temporal order, starting with 1) *
* - int i: the row where the neuron is located *
* - int j: the column where the neuron is located */
void removeSpikes(int start, int end, int i, int j)
{
neurons[cNN(i,j)].removeSpikes(start, end);
}
void removeSpikes(int start, int end, int m)
{
neurons[m].removeSpikes(start, end);
}
/*** getSpikeCount ***
* Returns the number of spikes that have occurred since the last reset (including those that have been removed) of neuron (i|j) *
* - return: the number of spikes */
int getSpikeCount(int i, int j) const
{
return neurons[cNN(i,j)].getSpikeCount();
}
int getSpikeCount(int m) const
{
return neurons[m].getSpikeCount();
}
/*** getSpikeHistorySize ***
* Returns the current size of the spike history vector of neuron (i|j) *
* - return: the size of the spike history vector */
int getSpikeHistorySize(int i, int j) const
{
return neurons[cNN(i,j)].getSpikeHistorySize();
}
int getSpikeHistorySize(int m) const
{
return neurons[m].getSpikeHistorySize();
}
/*** setCurrentStimulus ***
* Sets a current stimulus for neuron (i|j)
* - Stimulus& _cst: shape of one stimulus period *
* - int i: the row where the neuron is located *
* - int j: the column where the neuron is located */
void setCurrentStimulus(Stimulus& _cst, int i, int j)
{
neurons[cNN(i,j)].setCurrentStimulus(_cst);
}
void setCurrentStimulus(Stimulus& _cst, int m)
{
neurons[m].setCurrentStimulus(_cst);
}
/*** getNumberIncoming ***
* Returns the number of either inhibitory or excitatory incoming connections to this neuron *
* from other neurons in the network *
* - int type: the type of incoming connections (inh./exc.)
* - int i: the row where the neuron is located *
* - int j: the column where the neuron is located *
* - return: the number of incoming connections */
int getNumberIncoming(int type, int i, int j) const
{
return neurons[cNN(i,j)].getNumberIncoming(type);
}
int getNumberIncoming(int type, int m) const
{
return neurons[m].getNumberIncoming(type);
}
/*** getNumberOutgoing ***
* Returns the number of connections outgoing from this neuron to other *
* neurons of a specific type *
* - int type: the type of postsynaptic neurons (inh./exc.)
* - int i: the row where the neuron is located *
* - int j: the column where the neuron is located *
* - return: the number of outgoing connections */
int getNumberOutgoing(int type, int i, int j) const
{
return neurons[cNN(i,j)].getNumberOutgoing(type);
}
int getNumberOutgoing(int type, int m) const
{
return neurons[m].getNumberOutgoing(type);
}
/*** getPProteinAmount ***
* Returns the LTP-related protein amount in a neuron *
* - int i: the row where the neuron is located *
* - int j: the column where the neuron is located *
* - return: momentary LTP-related protein amount */
double getPProteinAmount(int i, int j) const
{
return neurons[cNN(i,j)].getPProteinAmount();
}
double getPProteinAmount(int m) const
{
return neurons[m].getPProteinAmount();
}
/*** getCProteinAmount ***
* Returns the common protein amount in a neuron *
* - int i: the row where the neuron is located *
* - int j: the column where the neuron is located *
* - return: momentary LTP-related protein amount */
double getCProteinAmount(int i, int j) const
{
return neurons[cNN(i,j)].getCProteinAmount();
}
double getCProteinAmount(int m) const
{
return neurons[m].getCProteinAmount();
}
/*** getDProteinAmount ***
* Returns the LTD-related protein amount in a neuron *
* - int i: the row where the neuron is located *
* - int j: the column where the neuron is located *
* - return: momentary LTD-related protein amount */
double getDProteinAmount(int i, int j) const
{
return neurons[cNN(i,j)].getDProteinAmount();
}
double getDProteinAmount(int m) const
{
return neurons[m].getDProteinAmount();
}
/*** saveNeuronParams ***
* Saves all the neuron parameters (including the channel parameters) to a given file; *
* all neurons have the same parameters, so the first one is taken */
void saveNeuronParams(ofstream *f) const
{
neurons[0].saveNeuronParams(f);
}
/* =============================================================================================================================== */
};
| 32.375831
| 161
| 0.659689
|
jlubo
|
9725f2cc945f31ed11817f4d8f9bcff7d992073b
| 558
|
hpp
|
C++
|
Classes/PlaneLayer.hpp
|
nickqiao/AirWar
|
1cd8b418a1a3ec240bc02581ecff034218939b59
|
[
"Apache-2.0"
] | 2
|
2017-10-14T06:27:15.000Z
|
2021-11-05T20:27:28.000Z
|
Classes/PlaneLayer.hpp
|
nickqiao/AirWar
|
1cd8b418a1a3ec240bc02581ecff034218939b59
|
[
"Apache-2.0"
] | null | null | null |
Classes/PlaneLayer.hpp
|
nickqiao/AirWar
|
1cd8b418a1a3ec240bc02581ecff034218939b59
|
[
"Apache-2.0"
] | null | null | null |
//
// PlaneLayer.hpp
// AirWar
//
// Created by nick on 2017/1/19.
// Copyright © 2017年 chenyuqiao. All rights reserved.
//
#include "cocos2d.h"
USING_NS_CC;
const int AIRPLANE=747;
class PlaneLayer : public Layer {
public:
PlaneLayer();
~PlaneLayer();
static PlaneLayer* create();
virtual bool init();
void MoveTo(Point location);
void Blowup(int passScore);
void RemovePlane();
public:
static PlaneLayer* sharedPlane;
bool isAlive;
int score;
};
| 12.976744
| 54
| 0.587814
|
nickqiao
|
972e40c3e8102a66fd486836e97db36718a93fd6
| 1,287
|
cpp
|
C++
|
ProducerConsumer/worker.cpp
|
bloodMaster/ProducerConsumer
|
934130b029bff0ce0f314ca65a76f8cbf9b879df
|
[
"MIT"
] | null | null | null |
ProducerConsumer/worker.cpp
|
bloodMaster/ProducerConsumer
|
934130b029bff0ce0f314ca65a76f8cbf9b879df
|
[
"MIT"
] | null | null | null |
ProducerConsumer/worker.cpp
|
bloodMaster/ProducerConsumer
|
934130b029bff0ce0f314ca65a76f8cbf9b879df
|
[
"MIT"
] | null | null | null |
#include "worker.hpp"
#include <iostream>
#include <random>
std::mutex s_mutex;
std::atomic<int> Worker::s_numOfActiveProducers;
std::atomic<bool> Worker::s_shouldWork = true;
Worker::DataContainer Worker::s_dataContainer;
const unsigned int Worker::s_maxSizeOfQueue = 100;
const unsigned int Worker::s_allowedSizeForProduction = 80;
std::mutex Worker::s_mutex;
std::condition_variable Worker::s_producers;
std::condition_variable Worker::s_consumers;
void Worker::
signalHandler(int sigNum)
{
s_shouldWork = false;
}
void Worker::
start()
{
m_thread = std::thread(&Worker::work, this);
}
void Worker::
join()
{
m_thread.join();
}
int Worker::
randNumber(int lowerBound, int upperBound)
{
static thread_local std::mt19937 gen;
std::uniform_int_distribution<int> d(lowerBound, upperBound);
return d(gen);
}
void Worker::
sleep()
{
std::this_thread::sleep_for(std::chrono::milliseconds(randNumber(0, 100)));
}
void Logger::
work()
{
while (s_shouldWork || 0 != s_numOfActiveProducers)
{
log();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
void Logger::
log()
{
std::unique_lock<std::mutex> uniqueLock(s_mutex);
std::cout << "Num of elements: " << s_dataContainer.size() << "\n";
}
| 19.208955
| 77
| 0.685315
|
bloodMaster
|
97314d6ac911c17d6d79f8ee95e6d033767e7c29
| 73,926
|
cpp
|
C++
|
httpendpoints.cpp
|
qbit-t/qb
|
c1fd82df3838f8526fc5e335254529ab6f953f78
|
[
"MIT"
] | 1
|
2021-02-14T04:04:50.000Z
|
2021-02-14T04:04:50.000Z
|
httpendpoints.cpp
|
qbit-t/qb
|
c1fd82df3838f8526fc5e335254529ab6f953f78
|
[
"MIT"
] | null | null | null |
httpendpoints.cpp
|
qbit-t/qb
|
c1fd82df3838f8526fc5e335254529ab6f953f78
|
[
"MIT"
] | 1
|
2021-08-28T07:42:43.000Z
|
2021-08-28T07:42:43.000Z
|
#include "httprequesthandler.h"
#include "httpreply.h"
#include "httprequest.h"
#include "log/log.h"
#include "json.h"
#include "tinyformat.h"
#include "httpendpoints.h"
#include "vm/vm.h"
#include <iostream>
using namespace qbit;
void HttpMallocStats::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) {
/* request
{
"jsonrpc": "1.0",
"id": "curltext",
"method": "mallocstats",
"params": [
"<thread_id>", -- (string, optional) thread id
"<class_index>", -- (string, optional) class to dump
"<path>" -- (string, required if class provided) path to dump to
]
}
*/
/* reply
{
"result":
{
"table": [] -- (string array) details
},
"error": -- (object or null) error description
{
"code": "EFAIL",
"message": "<explanation>"
},
"id": "curltext" -- (string) request id
}
*/
// id
json::Value lId;
if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
// params
json::Value lParams;
if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) {
// extract parameters
if (lParams.size() <= 1) {
// param[0]
size_t lThreadId = 0; // 0
if (lParams.size() == 1) {
json::Value lP0 = lParams[0];
if (lP0.isString()) {
if (!convert<size_t>(lP0.getString(), lThreadId)) {
reply = HttpReply::stockReply("E_INCORRECT_VALUE_TYPE", "Incorrect parameter type"); return;
}
} else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
}
char lStats[204800] = {0};
#if defined(JM_MALLOC)
if (!lThreadId) {
_jm_threads_print_stats(lStats);
} else {
_jm_thread_print_stats(lThreadId, lStats,
JM_ARENA_BASIC_STATS /*|
JM_ARENA_CHUNK_STATS |
JM_ARENA_DIRTY_BLOCKS_STATS |
JM_ARENA_FREEE_BLOCKS_STATS*/, JM_ALLOC_CLASSES);
}
#endif
std::string lValue(lStats);
std::vector<std::string> lParts;
boost::split(lParts, lValue, boost::is_any_of("\n\t"), boost::token_compress_on);
// prepare reply
json::Document lReply;
lReply.loadFromString("{}");
json::Value lKeyObject = lReply.addObject("result");
json::Value lKeyArrayObject = lKeyObject.addArray("table");
for (std::vector<std::string>::iterator lString = lParts.begin(); lString != lParts.end(); lString++) {
json::Value lItem = lKeyArrayObject.newArrayItem();
lItem.setString(*lString);
}
lReply.addObject("error").toNull();
lReply.addString("id", lId.getString());
// pack
pack(reply, lReply);
// finalize
finalize(reply);
} else {
// param[0]
size_t lThreadId = 0; // 0
json::Value lP0 = lParams[0];
if (lP0.isString()) {
if (!convert<size_t>(lP0.getString(), lThreadId)) {
reply = HttpReply::stockReply("E_INCORRECT_VALUE_TYPE", "Incorrect parameter type"); return;
}
} else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
// param[1]
int lClassIndex = 0; // 1
json::Value lP1 = lParams[1];
if (lP0.isString()) {
if (!convert<int>(lP1.getString(), lClassIndex)) {
reply = HttpReply::stockReply("E_INCORRECT_VALUE_TYPE", "Incorrect parameter type"); return;
}
} else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
// param[2]
std::string lPath; // 2
json::Value lP2 = lParams[2];
if (lP2.isString()) {
lPath = lP2.getString();
} else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
//
#if defined(JM_MALLOC)
_jm_thread_dump_chunk(lThreadId, 0, lClassIndex, (char*)lPath.c_str());
#endif
// prepare reply
json::Document lReply;
lReply.loadFromString("{}");
lReply.addString("result", "ok");
lReply.addObject("error").toNull();
lReply.addString("id", lId.getString());
// pack
pack(reply, lReply);
// finalize
finalize(reply);
}
} else {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
}
void HttpGetKey::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) {
/* request
{
"jsonrpc": "1.0",
"id": "curltext",
"method": "getkey",
"params": [
"<address_id>" -- (string, optional) address
]
}
*/
/* reply
{
"result": -- (object) address details
{
"address": "<address>", -- (string) address, base58 encoded
"pkey": "<public_key>", -- (string) public key, hex encoded
"skey": "<secret_key>", -- (string) secret key, hex encoded
"seed": [] -- (string array) seed words
},
"error": -- (object or null) error description
{
"code": "EFAIL",
"message": "<explanation>"
},
"id": "curltext" -- (string) request id
}
*/
// id
json::Value lId;
if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
// params
json::Value lParams;
if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) {
// extract parameters
std::string lAddress; // 0
if (lParams.size()) {
// param[0]
json::Value lP0 = lParams[0];
if (lP0.isString()) lAddress = lP0.getString();
else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
}
// process
SKeyPtr lKey;
if (lAddress.size()) {
PKey lPKey;
if (!lPKey.fromString(lAddress)) {
reply = HttpReply::stockReply("E_PKEY_INVALID", "Public key is invalid");
return;
}
lKey = wallet_->findKey(lPKey);
if (!lKey || !lKey->valid()) {
reply = HttpReply::stockReply("E_SKEY_NOT_FOUND", "Key was not found");
return;
}
} else {
lKey = wallet_->firstKey();
if (!lKey->valid()) {
reply = HttpReply::stockReply("E_SKEY_IS_ABSENT", "Key is absent");
return;
}
}
PKey lPFoundKey = lKey->createPKey();
// prepare reply
json::Document lReply;
lReply.loadFromString("{}");
json::Value lKeyObject = lReply.addObject("result");
lKeyObject.addString("address", lPFoundKey.toString());
lKeyObject.addString("pkey", lPFoundKey.toHex());
lKeyObject.addString("skey", lKey->toHex());
json::Value lKeyArrayObject = lKeyObject.addArray("seed");
for (std::vector<SKey::Word>::iterator lWord = lKey->seed().begin(); lWord != lKey->seed().end(); lWord++) {
json::Value lItem = lKeyArrayObject.newArrayItem();
lItem.setString((*lWord).wordA());
}
lReply.addObject("error").toNull();
lReply.addString("id", lId.getString());
// pack
pack(reply, lReply);
// finalize
finalize(reply);
} else {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
}
void HttpNewKey::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) {
/* request
{
"jsonrpc": "1.0",
"id": "curltext",
"method": "newkey",
"params": [
...
]
}
*/
/* reply
{
"result": -- (object) address details
{
"address": "<address>", -- (string) address, base58 encoded
"pkey": "<public_key>", -- (string) public key, hex encoded
"skey": "<secret_key>", -- (string) secret key, hex encoded
"seed": [] -- (string array) seed words
},
"error": -- (object or null) error description
{
"code": "EFAIL",
"message": "<explanation>"
},
"id": "curltext" -- (string) request id
}
*/
// id
json::Value lId;
if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
// params
json::Value lParams;
if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) {
//
std::list<std::string> lSeedWords;
if (lParams.size()) {
// param[0]
for (int lIdx = 0; lIdx < lParams.size(); lIdx++) {
//
json::Value lP0 = lParams[lIdx];
if (lP0.isString()) lSeedWords.push_back(lP0.getString());
else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
}
}
// process
SKeyPtr lKey = wallet_->createKey(lSeedWords);
if (!lKey->valid()) {
reply = HttpReply::stockReply("E_SKEY_IS_INVALID", "Key is invalid");
return;
}
PKey lPFoundKey = lKey->createPKey();
// prepare reply
json::Document lReply;
lReply.loadFromString("{}");
json::Value lKeyObject = lReply.addObject("result");
lKeyObject.addString("address", lPFoundKey.toString());
lKeyObject.addString("pkey", lPFoundKey.toHex());
lKeyObject.addString("skey", lKey->toHex());
json::Value lKeyArrayObject = lKeyObject.addArray("seed");
for (std::vector<SKey::Word>::iterator lWord = lKey->seed().begin(); lWord != lKey->seed().end(); lWord++) {
json::Value lItem = lKeyArrayObject.newArrayItem();
lItem.setString((*lWord).wordA());
}
lReply.addObject("error").toNull();
lReply.addString("id", lId.getString());
// pack
pack(reply, lReply);
// finalize
finalize(reply);
} else {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
}
void HttpGetBalance::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) {
/* request
{
"jsonrpc": "1.0",
"id": "curltext",
"method": "getbalance",
"params": [
"<asset_id>" -- (string, optional) asset
]
}
*/
/* reply
{
"result": "1.0", -- (string) corresponding asset balance
"error": -- (object or null) error description
{
"code": "EFAIL",
"message": "<explanation>"
},
"id": "curltext" -- (string) request id
}
*/
// id
json::Value lId;
if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
// params
json::Value lParams;
if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) {
// extract parameters
uint256 lAsset; // 0
if (lParams.size()) {
// param[0]
json::Value lP0 = lParams[0];
if (lP0.isString()) lAsset.setHex(lP0.getString());
else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
}
// process
amount_t lScale = QBIT;
if (!lAsset.isNull() && lAsset != TxAssetType::qbitAsset()) {
// locate asset type
EntityPtr lAssetEntity = wallet_->persistentStore()->entityStore()->locateEntity(lAsset);
if (lAssetEntity && lAssetEntity->type() == Transaction::ASSET_TYPE) {
TxAssetTypePtr lAssetType = TransactionHelper::to<TxAssetType>(lAssetEntity);
lScale = lAssetType->scale();
} else {
reply = HttpReply::stockReply("E_ASSET", "Asset type was not found");
return;
}
}
// process
double lBalance = 0.0;
double lPendingBalance = 0.0;
IMemoryPoolPtr lMempool = wallet_->mempoolManager()->locate(MainChain::id()); // main chain only
IConsensus::ChainState lState = lMempool->consensus()->chainState();
if (lState == IConsensus::SYNCHRONIZED) {
if (!lAsset.isNull()) {
amount_t lPending = 0, lActual = 0;
wallet_->balance(lAsset, lPending, lActual);
lPendingBalance = ((double)lPending) / lScale;
lBalance = ((double)lActual) / lScale;
} else {
amount_t lPending = 0, lActual = 0;
wallet_->balance(TxAssetType::qbitAsset(), lPending, lActual);
lPendingBalance = ((double)wallet_->pendingBalance()) / lScale;
lBalance = ((double)wallet_->balance()) / lScale;
}
} else if (lState == IConsensus::SYNCHRONIZING) {
reply = HttpReply::stockReply("E_NODE_SYNCHRONIZING", "Synchronization is in progress...");
return;
} else {
reply = HttpReply::stockReply("E_NODE_NOT_SYNCHRONIZED", "Not synchronized");
return;
}
// prepare reply
json::Document lReply;
lReply.loadFromString("{}");
json::Value lKeyObject = lReply.addObject("result");
lKeyObject.addString("available", strprintf(TxAssetType::scaleFormat(lScale), lBalance));
if (lPendingBalance > lBalance) lKeyObject.addString("pending", strprintf(TxAssetType::scaleFormat(lScale), lPendingBalance-lBalance));
else lKeyObject.addString("pending", strprintf(TxAssetType::scaleFormat(lScale), 0));
lReply.addObject("error").toNull();
lReply.addString("id", lId.getString());
// pack
pack(reply, lReply);
// finalize
finalize(reply);
} else {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
}
void HttpSendToAddress::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) {
/* request
{
"jsonrpc": "1.0",
"id": "curltext",
"method": "sendtoaddress",
"params": [
"<asset_id>", -- (string) asset or "*"
"<address>", -- (string) address
"0.1" -- (string) amount
]
}
*/
/* reply
{
"result": "<tx_id>", -- (string) txid
"error": -- (object or null) error description
{
"code": "EFAIL",
"message": "<explanation>"
},
"id": "curltext" -- (string) request id
}
*/
// id
json::Value lId;
if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
// params
json::Value lParams;
if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) {
// extract parameters
std::string lAssetString; // 0
PKey lAddress; // 1
double lValue; // 2
if (lParams.size() == 3) {
// param[0]
json::Value lP0 = lParams[0];
if (lP0.isString()) lAssetString = lP0.getString();
else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
// param[1]
json::Value lP1 = lParams[1];
if (lP1.isString()) lAddress.fromString(lP1.getString());
else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
// param[2]
json::Value lP2 = lParams[2];
if (lP2.isString()) {
if (!convert<double>(lP2.getString(), lValue)) {
reply = HttpReply::stockReply("E_INCORRECT_VALUE_TYPE", "Incorrect parameter type"); return;
}
} else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
} else {
reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters");
return;
}
uint256 lAsset;
if (lAssetString == "*") lAsset = TxAssetType::qbitAsset();
else lAsset.setHex(lAssetString);
// locate scale
amount_t lScale = QBIT;
if (!lAsset.isNull() && lAsset != TxAssetType::qbitAsset()) {
// locate asset type
EntityPtr lAssetEntity = wallet_->persistentStore()->entityStore()->locateEntity(lAsset);
if (lAssetEntity && lAssetEntity->type() == Transaction::ASSET_TYPE) {
TxAssetTypePtr lAssetType = TransactionHelper::to<TxAssetType>(lAssetEntity);
lScale = lAssetType->scale();
} else {
reply = HttpReply::stockReply("E_ASSET", "Asset type was not found");
return;
}
}
// prepare reply
json::Document lReply;
lReply.loadFromString("{}");
// process
std::string lCode, lMessage;
TransactionContextPtr lCtx = nullptr;
try {
// create tx
lCtx = wallet_->createTxSpend(lAsset, lAddress, (amount_t)(lValue * (double)lScale));
if (lCtx->errors().size()) {
reply = HttpReply::stockReply("E_TX_CREATE_SPEND", *lCtx->errors().begin());
return;
}
// push to memory pool
IMemoryPoolPtr lMempool = wallet_->mempoolManager()->locate(MainChain::id()); // all spend txs - to the main chain
if (lMempool) {
//
if (lMempool->pushTransaction(lCtx)) {
// check for errors
if (lCtx->errors().size()) {
// unpack
if (!unpackTransaction(lCtx->tx(), uint256(), 0, 0, 0, false, false, lReply, reply)) return;
// rollback transaction
wallet_->rollback(lCtx);
// error
lCode = "E_TX_MEMORYPOOL";
lMessage = *lCtx->errors().begin();
lCtx = nullptr;
} else if (!lMempool->consensus()->broadcastTransaction(lCtx, wallet_->firstKey()->createPKey().id())) {
lCode = "E_TX_NOT_BROADCASTED";
lMessage = "Transaction is not broadcasted";
}
// we good
if (lCtx) {
// find and broadcast for active clients
peerManager_->notifyTransaction(lCtx);
}
} else {
lCode = "E_TX_EXISTS";
lMessage = "Transaction already exists";
// unpack
if (!unpackTransaction(lCtx->tx(), uint256(), 0, 0, 0, false, false, lReply, reply)) return;
// rollback transaction
wallet_->rollback(lCtx);
// reset
lCtx = nullptr;
}
} else {
reply = HttpReply::stockReply("E_MEMPOOL", "Corresponding memory pool was not found");
return;
}
}
catch(qbit::exception& ex) {
reply = HttpReply::stockReply(ex.code(), ex.what());
return;
}
if (lCtx != nullptr) lReply.addString("result", lCtx->tx()->hash().toHex());
if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull();
else {
json::Value lError = lReply.addObject("error");
lError.addString("code", lCode);
lError.addString("message", lMessage);
}
lReply.addString("id", lId.getString());
// pack
pack(reply, lReply);
// finalize
finalize(reply);
} else {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
}
void HttpGetPeerInfo::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) {
/* request
{
"jsonrpc": "1.0",
"id": "curltext",
"method": "getpeerinfo",
"params": []
}
*/
/* reply
{
"result": {
"peers": [
{
"id": "<peer_id>", -- (string) peer default address id (uint160)
"endpoint": "address:port", -- (string) peer endpoint
"outbound": true|false, -- (bool) is outbound connection
"roles": "<peer_roles>", -- (string) peer roles
"status": "<peer_status>", -- (string) peer status
"latency": <latency>, -- (int) latency, ms
"time": "<peer_time>", -- (string) peer_time, s
"chains": [
{
"id": "<chain_id>", -- (string) chain id
...
}
]
},
...
],
},
"error": -- (object or null) error description
{
"code": "EFAIL",
"message": "<explanation>"
},
"id": "curltext" -- (string) request id
}
*/
// id
json::Value lId;
if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
// params
json::Value lParams;
if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) {
// prepare reply
json::Document lReply;
lReply.loadFromString("{}");
json::Value lKeyObject = lReply.addObject("result");
json::Value lArrayObject = lKeyObject.addArray("peers");
// get peers
std::list<IPeerPtr> lPeers;
peerManager_->allPeers(lPeers);
// peer manager
json::Value lPeerManagerObject = lReply.addObject("manager");
lPeerManagerObject.addUInt("clients", peerManager_->clients());
lPeerManagerObject.addUInt("peers_count", lPeers.size());
for (std::list<IPeerPtr>::iterator lPeer = lPeers.begin(); lPeer != lPeers.end(); lPeer++) {
//
if ((*lPeer)->status() == IPeer::UNDEFINED) continue;
json::Value lItem = lArrayObject.newArrayItem();
lItem.toObject(); // make object
if ((*lPeer)->status() == IPeer::BANNED || (*lPeer)->status() == IPeer::POSTPONED) {
lItem.addString("endpoint", (*lPeer)->key());
lItem.addString("status", (*lPeer)->statusString());
lItem.addUInt("in_queue", (*lPeer)->inQueueLength());
lItem.addUInt("out_queue", (*lPeer)->outQueueLength());
lItem.addUInt("pending_queue", (*lPeer)->pendingQueueLength());
lItem.addUInt("received_count", (*lPeer)->receivedMessagesCount());
lItem.addUInt64("received_bytes", (*lPeer)->bytesReceived());
lItem.addUInt("sent_count", (*lPeer)->sentMessagesCount());
lItem.addUInt64("sent_bytes", (*lPeer)->bytesSent());
continue;
}
lItem.addString("id", (*lPeer)->addressId().toHex());
lItem.addString("endpoint", (*lPeer)->key());
lItem.addString("status", (*lPeer)->statusString());
lItem.addUInt64("time", (*lPeer)->time());
lItem.addBool("outbound", (*lPeer)->isOutbound() ? true : false);
lItem.addUInt("latency", (*lPeer)->latency());
lItem.addString("roles", (*lPeer)->state()->rolesString());
if ((*lPeer)->state()->address().valid())
lItem.addString("address", (*lPeer)->state()->address().toString());
lItem.addUInt("in_queue", (*lPeer)->inQueueLength());
lItem.addUInt("out_queue", (*lPeer)->outQueueLength());
lItem.addUInt("pending_queue", (*lPeer)->pendingQueueLength());
lItem.addUInt("received_count", (*lPeer)->receivedMessagesCount());
lItem.addUInt64("received_bytes", (*lPeer)->bytesReceived());
lItem.addUInt("sent_count", (*lPeer)->sentMessagesCount());
lItem.addUInt64("sent_bytes", (*lPeer)->bytesSent());
if ((*lPeer)->state()->client()) {
//
json::Value lDAppsArray = lItem.addArray("dapps");
for(std::vector<State::DAppInstance>::const_iterator lInstance = (*lPeer)->state()->dApps().begin();
lInstance != (*lPeer)->state()->dApps().end(); lInstance++) {
json::Value lDApp = lDAppsArray.newArrayItem();
lDApp.addString("name", lInstance->name());
lDApp.addString("instance", lInstance->instance().toHex());
}
} else {
//
json::Value lChainsObject = lItem.addArray("chains");
std::vector<State::BlockInfo> lInfos = (*lPeer)->state()->infos();
for (std::vector<State::BlockInfo>::iterator lInfo = lInfos.begin(); lInfo != lInfos.end(); lInfo++) {
//
json::Value lChain = lChainsObject.newArrayItem();
lChain.toObject(); // make object
lChain.addString("dapp", lInfo->dApp().size() ? lInfo->dApp() : "none");
lChain.addUInt64("height", lInfo->height());
lChain.addString("chain", lInfo->chain().toHex());
lChain.addString("block", lInfo->hash().toHex());
}
}
}
//lReply.addString("result", strprintf(QBIT_FORMAT, lBalance));
lReply.addObject("error").toNull();
lReply.addString("id", lId.getString());
// pack
pack(reply, lReply);
// finalize
finalize(reply);
} else {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
}
void HttpCreateDApp::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) {
/* request
{
"jsonrpc": "1.0",
"id": "curltext",
"method": "createdapp",
"params": [
"<address>", -- (string) owners' address
"<short_name>", -- (string) dapp short name, should be unique
"<description>", -- (string) dapp description
"<instances_tx>", -- (short) dapp instances tx types (transaction::type)
"<sharding>" -- (string, optional) static|dynamic, default = 'static'
]
}
*/
/* reply
{
"result": "<tx_dapp_id>", -- (string) txid = dapp_id
"error": -- (object or null) error description
{
"code": "EFAIL",
"message": "<explanation>"
},
"id": "curltext" -- (string) request id
}
*/
// id
json::Value lId;
if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
// params
json::Value lParams;
if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) {
// extract parameters
PKey lAddress; // 0
std::string lShortName; // 1
std::string lDescription; // 2
Transaction::Type lInstances; // 3
std::string lSharding = "static"; // 4
if (lParams.size() == 4 || lParams.size() == 5) {
// param[0]
json::Value lP0 = lParams[0];
if (lP0.isString()) lAddress.fromString(lP0.getString());
else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
// param[1]
json::Value lP1 = lParams[1];
if (lP1.isString()) lShortName = lP1.getString();
else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
// param[2]
json::Value lP2 = lParams[2];
if (lP2.isString()) lDescription = lP2.getString();
else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
// param[3]
json::Value lP3 = lParams[3];
if (lP3.isString()) {
unsigned short lValue;
if (!convert<unsigned short>(lP3.getString(), lValue)) {
reply = HttpReply::stockReply("E_INCORRECT_VALUE_TYPE", "Incorrect parameter type"); return;
}
lInstances = (Transaction::Type)lValue;
} else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
// param[4]
if (lParams.size() == 5) {
json::Value lP4 = lParams[4];
if (lP4.isString()) lSharding = lP4.getString();
else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
}
} else {
reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters");
return;
}
// prepare reply
json::Document lReply;
lReply.loadFromString("{}");
// process
std::string lCode, lMessage;
TransactionContextPtr lCtx = nullptr;
try {
// create tx
lCtx = wallet_->createTxDApp(lAddress, lShortName, lDescription, (lSharding == "static" ? TxDApp::STATIC : TxDApp::DYNAMIC), lInstances);
if (lCtx->errors().size()) {
reply = HttpReply::stockReply("E_TX_CREATE_DAPP", *lCtx->errors().begin());
return;
}
// push to memory pool
IMemoryPoolPtr lMempool = wallet_->mempoolManager()->locate(MainChain::id()); // dapp -> main chain
if (lMempool) {
//
if (lMempool->pushTransaction(lCtx)) {
// check for errors
if (lCtx->errors().size()) {
// unpack
if (!unpackTransaction(lCtx->tx(), uint256(), 0, 0, 0, false, false, lReply, reply)) return;
// rollback transaction
wallet_->rollback(lCtx);
// error
lCode = "E_TX_MEMORYPOOL";
lMessage = *lCtx->errors().begin();
lCtx = nullptr;
} else if (!lMempool->consensus()->broadcastTransaction(lCtx, wallet_->firstKey()->createPKey().id())) {
lCode = "E_TX_NOT_BROADCASTED";
lMessage = "Transaction is not broadcasted";
}
} else {
lCode = "E_TX_EXISTS";
lMessage = "Transaction already exists";
// unpack
if (!unpackTransaction(lCtx->tx(), uint256(), 0, 0, 0, false, false, lReply, reply)) return;
// rollback transaction
wallet_->rollback(lCtx);
// reset
lCtx = nullptr;
}
} else {
reply = HttpReply::stockReply("E_MEMPOOL", "Corresponding memory pool was not found");
return;
}
}
catch(qbit::exception& ex) {
reply = HttpReply::stockReply(ex.code(), ex.what());
return;
}
if (lCtx != nullptr) lReply.addString("result", lCtx->tx()->hash().toHex());
if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull();
else {
json::Value lError = lReply.addObject("error");
lError.addString("code", lCode);
lError.addString("message", lMessage);
}
lReply.addString("id", lId.getString());
// pack
pack(reply, lReply);
// finalize
finalize(reply);
} else {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
}
void HttpCreateShard::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) {
/* request
{
"jsonrpc": "1.0",
"id": "curltext",
"method": "createshard",
"params": [
"<address>", -- (string) creators' address (not owner)
"<dapp_name>", -- (string) dapp name
"<short_name>", -- (string) shard short name, should be unique
"<description>" -- (string) shard description
]
}
*/
/* reply
{
"result": "<tx_shard_id>", -- (string) txid = shard_id
"error": -- (object or null) error description
{
"code": "EFAIL",
"message": "<explanation>"
},
"id": "curltext" -- (string) request id
}
*/
// id
json::Value lId;
if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
// params
json::Value lParams;
if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) {
// extract parameters
PKey lAddress; // 0
std::string lDAppName; // 1
std::string lShortName; // 2
std::string lDescription; // 3
if (lParams.size() == 4) {
// param[0]
json::Value lP0 = lParams[0];
if (lP0.isString()) lAddress.fromString(lP0.getString());
else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
// param[1]
json::Value lP1 = lParams[1];
if (lP1.isString()) lDAppName = lP1.getString();
else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
// param[2]
json::Value lP2 = lParams[2];
if (lP2.isString()) lShortName = lP2.getString();
else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
// param[3]
json::Value lP3 = lParams[3];
if (lP3.isString()) lDescription = lP3.getString();
else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
} else {
reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters");
return;
}
// prepare reply
json::Document lReply;
lReply.loadFromString("{}");
// process
std::string lCode, lMessage;
TransactionContextPtr lCtx = nullptr;
try {
// create tx
lCtx = wallet_->createTxShard(lAddress, lDAppName, lShortName, lDescription);
if (lCtx->errors().size()) {
reply = HttpReply::stockReply("E_TX_CREATE_SHARD", *lCtx->errors().begin());
return;
}
// push to memory pool
IMemoryPoolPtr lMempool = wallet_->mempoolManager()->locate(MainChain::id()); // dapp -> main chain
if (lMempool) {
//
if (lMempool->pushTransaction(lCtx)) {
// check for errors
if (lCtx->errors().size()) {
// unpack
if (!unpackTransaction(lCtx->tx(), uint256(), 0, 0, 0, false, false, lReply, reply)) return;
// rollback transaction
wallet_->rollback(lCtx);
// error
lCode = "E_TX_MEMORYPOOL";
lMessage = *lCtx->errors().begin();
lCtx = nullptr;
} else if (!lMempool->consensus()->broadcastTransaction(lCtx, wallet_->firstKey()->createPKey().id())) {
lCode = "E_TX_NOT_BROADCASTED";
lMessage = "Transaction is not broadcasted";
}
} else {
lCode = "E_TX_EXISTS";
lMessage = "Transaction already exists";
// unpack
if (!unpackTransaction(lCtx->tx(), uint256(), 0, 0, 0, false, false, lReply, reply)) return;
// rollback transaction
wallet_->rollback(lCtx);
// reset
lCtx = nullptr;
}
} else {
reply = HttpReply::stockReply("E_MEMPOOL", "Corresponding memory pool was not found");
return;
}
}
catch(qbit::exception& ex) {
reply = HttpReply::stockReply(ex.code(), ex.what());
return;
}
if (lCtx != nullptr) lReply.addString("result", lCtx->tx()->hash().toHex());
if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull();
else {
json::Value lError = lReply.addObject("error");
lError.addString("code", lCode);
lError.addString("message", lMessage);
}
lReply.addString("id", lId.getString());
// pack
pack(reply, lReply);
// finalize
finalize(reply);
} else {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
}
void HttpGetTransaction::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) {
/* request
{
"jsonrpc": "1.0",
"id": "curltext",
"method": "gettransaction",
"params": [
"<tx_id>" -- (string) tx hash (id)
]
}
*/
/* reply
{
"result": {
"id": "<tx_id>", -- (string) tx hash (id)
"chain": "<chain_id>", -- (string) chain / shard hash (id)
"type": "<tx_type>", -- (string) tx type: COINBASE, SPEND, SPEND_PRIVATE & etc.
"version": <version>, -- (int) version (0-256)
"timelock: <lock_time>, -- (int64) lock time (future block)
"block": "<block_id>", -- (string) block hash (id), optional
"height": <height>, -- (int64) block height, optional
"index": <index>, -- (int) tx block index
"mempool": false|true, -- (bool) mempool presence, optional
"properties": {
... -- (object) tx type-specific properties
},
"in": [
{
"chain": "<chain_id>", -- (string) source chain/shard hash (id)
"asset": "<asset_id>", -- (string) source asset hash (id)
"tx": "<tx_id>", -- (string) source tx hash (id)
"index": <index>, -- (int) source tx out index
"ownership": {
"raw": "<hex>", -- (string) ownership script (hex)
"qasm": [ -- (array, string) ownership script disassembly
"<qasm> <p0>, ... <pn>",
...
]
}
}
],
"out": [
{
"asset": "<asset_id>", -- (string) destination asset hash (id)
"destination": {
"raw": "<hex>", -- (string) destination script (hex)
"qasm": [ -- (array, string) destination script disassembly
"<qasm> <p0>, ... <pn>",
...
]
}
}
]
},
"error": -- (object or null) error description
{
"code": "EFAIL",
"message": "<explanation>"
},
"id": "curltext" -- (string) request id
}
*/
// id
json::Value lId;
if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
// params
json::Value lParams;
if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) {
// extract parameters
uint256 lTxId; // 0
if (lParams.size() == 1) {
// param[0]
json::Value lP0 = lParams[0];
if (lP0.isString()) lTxId.setHex(lP0.getString());
else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
} else {
reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters");
return;
}
// prepare reply
json::Document lReply;
lReply.loadFromString("{}");
// process
TransactionPtr lTx;
std::string lCode, lMessage;
// try to lookup transaction
ITransactionStoreManagerPtr lStoreManager = wallet_->storeManager();
IMemoryPoolManagerPtr lMempoolManager = wallet_->mempoolManager();
if (lStoreManager && lMempoolManager) {
//
uint256 lBlock;
uint64_t lHeight = 0;
uint64_t lConfirms = 0;
uint32_t lIndex = 0;
bool lCoinbase = false;
bool lMempool = false;
std::vector<ITransactionStorePtr> lStorages = lStoreManager->storages();
for (std::vector<ITransactionStorePtr>::iterator lStore = lStorages.begin(); lStore != lStorages.end(); lStore++) {
lTx = (*lStore)->locateTransaction(lTxId);
if (lTx && (*lStore)->transactionInfo(lTxId, lBlock, lHeight, lConfirms, lIndex, lCoinbase)) {
break;
}
}
// try mempool
if (!lTx) {
std::vector<IMemoryPoolPtr> lMempools = lMempoolManager->pools();
for (std::vector<IMemoryPoolPtr>::iterator lPool = lMempools.begin(); lPool != lMempools.end(); lPool++) {
lTx = (*lPool)->locateTransaction(lTxId);
if (lTx) {
lMempool = true;
break;
}
}
}
if (lTx) {
//
if (!unpackTransaction(lTx, lBlock, lHeight, lConfirms, lIndex, lCoinbase, lMempool, lReply, reply))
return;
} else {
reply = HttpReply::stockReply("E_TX_NOT_FOUND", "Transaction not found");
return;
}
} else {
reply = HttpReply::stockReply("E_STOREMANAGER", "Transactions store manager not found");
return;
}
if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull();
else {
json::Value lError = lReply.addObject("error");
lError.addString("code", lCode);
lError.addString("message", lMessage);
}
lReply.addString("id", lId.getString());
// pack
pack(reply, lReply);
// finalize
finalize(reply);
} else {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
}
void HttpGetEntity::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) {
/* request
{
"jsonrpc": "1.0",
"id": "curltext",
"method": "getentity",
"params": [
"<entity_name>" -- (string) entity name
]
}
*/
/* reply
{
"result": {
"id": "<tx_id>", -- (string) tx hash (id)
"chain": "<chain_id>", -- (string) chain / shard hash (id)
"type": "<tx_type>", -- (string) tx type: COINBASE, SPEND, SPEND_PRIVATE & etc.
"version": <version>, -- (int) version (0-256)
"timelock: <lock_time>, -- (int64) lock time (future block)
"block": "<block_id>", -- (string) block hash (id), optional
"height": <height>, -- (int64) block height, optional
"index": <index>, -- (int) tx block index
"mempool": false|true, -- (bool) mempool presence, optional
"properties": {
... -- (object) tx type-specific properties
},
"in": [
{
"chain": "<chain_id>", -- (string) source chain/shard hash (id)
"asset": "<asset_id>", -- (string) source asset hash (id)
"tx": "<tx_id>", -- (string) source tx hash (id)
"index": <index>, -- (int) source tx out index
"ownership": {
"raw": "<hex>", -- (string) ownership script (hex)
"qasm": [ -- (array, string) ownership script disassembly
"<qasm> <p0>, ... <pn>",
...
]
}
}
],
"out": [
{
"asset": "<asset_id>", -- (string) destination asset hash (id)
"destination": {
"raw": "<hex>", -- (string) destination script (hex)
"qasm": [ -- (array, string) destination script disassembly
"<qasm> <p0>, ... <pn>",
...
]
}
}
]
},
"error": -- (object or null) error description
{
"code": "EFAIL",
"message": "<explanation>"
},
"id": "curltext" -- (string) request id
}
*/
// id
json::Value lId;
if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
// params
json::Value lParams;
if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) {
// extract parameters
std::string lName; // 0
if (lParams.size() == 1) {
// param[0]
json::Value lP0 = lParams[0];
if (lP0.isString()) lName = lP0.getString();
else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
} else {
reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters");
return;
}
// prepare reply
json::Document lReply;
lReply.loadFromString("{}");
// process
TransactionPtr lTx;
std::string lCode, lMessage;
// try to lookup transaction
ITransactionStoreManagerPtr lStoreManager = wallet_->storeManager();
IMemoryPoolManagerPtr lMempoolManager = wallet_->mempoolManager();
if (lStoreManager && lMempoolManager) {
//
uint256 lBlock;
uint64_t lHeight = 0;
uint64_t lConfirms = 0;
uint32_t lIndex = 0;
bool lCoinbase = false;
bool lMempool = false;
ITransactionStorePtr lStorage = lStoreManager->locate(MainChain::id());
EntityPtr lTx = lStorage->entityStore()->locateEntity(lName);
// try mempool
if (!lTx) {
IMemoryPoolPtr lMainpool = lMempoolManager->locate(MainChain::id());
lTx = lMainpool->locateEntity(lName);
if (lTx) {
lMempool = true;
}
} else {
lStorage->transactionInfo(lTx->id(), lBlock, lHeight, lConfirms, lIndex, lCoinbase);
}
if (lTx) {
//
if (!unpackTransaction(lTx, lBlock, lHeight, lConfirms, lIndex, lCoinbase, lMempool, lReply, reply))
return;
} else {
reply = HttpReply::stockReply("E_TX_NOT_FOUND", "Transaction not found");
return;
}
} else {
reply = HttpReply::stockReply("E_STOREMANAGER", "Transactions store manager not found");
return;
}
if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull();
else {
json::Value lError = lReply.addObject("error");
lError.addString("code", lCode);
lError.addString("message", lMessage);
}
lReply.addString("id", lId.getString());
// pack
pack(reply, lReply);
// finalize
finalize(reply);
} else {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
}
void HttpGetBlock::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) {
/* request
{
"jsonrpc": "1.0",
"id": "curltext",
"method": "getblock",
"params": [
"<block_id>" -- (string) block hash (id)
]
}
*/
/* reply
{
"result": {
"id": "<tx_id>", -- (string) block hash (id)
"chain": "<chain_id>", -- (string) chain / shard hash (id)
"height": <height>, -- (int64) block height
"version": <version>, -- (int) version (0-256)
"time: <time>, -- (int64) block time
"prev": "<prev_id>", -- (string) prev block hash (id)
"root": "<merkle_root_hash>", -- (string) merkle root hash
"origin": "<miner_id>", -- (string) miner address id
"bits": <pow_bits>, -- (int) pow bits
"nonce": <nonce_counter>, -- (int) found nonce
"pow": [
<int>, <int> ... <int> -- (aray) found pow cycle
],
"transactions": [
{
"id": "<tx_id>", -- (string) tx hash (id)
"size": "<size>" -- (int) tx size
}
]
},
"error": -- (object or null) error description
{
"code": "EFAIL",
"message": "<explanation>"
},
"id": "curltext" -- (string) request id
}
*/
// id
json::Value lId;
if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
// params
json::Value lParams;
if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) {
// extract parameters
uint256 lBlockId; // 0
if (lParams.size() == 1) {
// param[0]
json::Value lP0 = lParams[0];
if (lP0.isString()) lBlockId.setHex(lP0.getString());
else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
} else {
reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters");
return;
}
// prepare reply
json::Document lReply;
lReply.loadFromString("{}");
// process
BlockPtr lBlock;
std::string lCode, lMessage;
// height
uint64_t lHeight = 0;
// try to lookup transaction
ITransactionStoreManagerPtr lStoreManager = wallet_->storeManager();
if (lStoreManager) {
//
std::vector<ITransactionStorePtr> lStorages = lStoreManager->storages();
for (std::vector<ITransactionStorePtr>::iterator lStore = lStorages.begin(); lStore != lStorages.end(); lStore++) {
lBlock = (*lStore)->block(lBlockId);
if (lBlock) {
(*lStore)->blockHeight(lBlockId, lHeight);
break;
}
}
if (lBlock) {
//
json::Value lRootObject = lReply.addObject("result");
lRootObject.addString("id", lBlock->hash().toHex());
lRootObject.addString("chain", lBlock->chain().toHex());
lRootObject.addUInt64("height", lHeight);
lRootObject.addInt("version", lBlock->version());
lRootObject.addUInt64("time", lBlock->time());
lRootObject.addString("prev", lBlock->prev().toHex());
lRootObject.addString("root", lBlock->root().toHex());
lRootObject.addString("origin", lBlock->origin().toHex());
lRootObject.addInt("bits", lBlock->bits());
lRootObject.addInt("nonce", lBlock->nonce());
json::Value lPowObject = lRootObject.addArray("pow");
int lIdx = 0;
for (std::vector<uint32_t>::iterator lNumber = lBlock->cycle_.begin(); lNumber != lBlock->cycle_.end(); lNumber++, lIdx++) {
//
json::Value lItem = lPowObject.newArrayItem();
//lItem.toObject();
//lItem.addInt("index", lIdx);
//lItem.addUInt("number", *lNumber);
lItem.setUInt(*lNumber);
}
json::Value lTransactionsObject = lRootObject.addArray("transactions");
BlockTransactionsPtr lTransactions = lBlock->blockTransactions();
for (std::vector<TransactionPtr>::iterator lTransaction = lTransactions->transactions().begin(); lTransaction != lTransactions->transactions().end(); lTransaction++) {
//
json::Value lItem = lTransactionsObject.newArrayItem();
lItem.toObject();
TransactionContextPtr lCtx = TransactionContext::instance(*lTransaction);
lItem.addString("id", lCtx->tx()->id().toHex());
lItem.addUInt("size", lCtx->size());
}
} else {
reply = HttpReply::stockReply("E_BLOCK_NOT_FOUND", "Block not found");
return;
}
} else {
reply = HttpReply::stockReply("E_STOREMANAGER", "Store manager not found");
return;
}
if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull();
else {
json::Value lError = lReply.addObject("error");
lError.addString("code", lCode);
lError.addString("message", lMessage);
}
lReply.addString("id", lId.getString());
// pack
pack(reply, lReply);
// finalize
finalize(reply);
} else {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
}
void HttpGetBlockHeader::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) {
/* request
{
"jsonrpc": "1.0",
"id": "curltext",
"method": "getblock",
"params": [
"<block_id>" -- (string) block hash (id)
]
}
*/
/* reply
{
"result": {
"id": "<tx_id>", -- (string) block hash (id)
"chain": "<chain_id>", -- (string) chain / shard hash (id)
"height": <height>, -- (int64) block height
"version": <version>, -- (int) version (0-256)
"time: <time>, -- (int64) block time
"prev": "<prev_id>", -- (string) prev block hash (id)
"root": "<merkle_root_hash>", -- (string) merkle root hash
"origin": "<miner_id>", -- (string) miner address id
"bits": <pow_bits>, -- (int) pow bits
"nonce": <nonce_counter>, -- (int) found nonce
"pow": [
<int>, <int> ... <int> -- (aray) found pow cycle
]
},
"error": -- (object or null) error description
{
"code": "EFAIL",
"message": "<explanation>"
},
"id": "curltext" -- (string) request id
}
*/
// id
json::Value lId;
if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
// params
json::Value lParams;
if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) {
// extract parameters
uint256 lBlockId; // 0
if (lParams.size() == 1) {
// param[0]
json::Value lP0 = lParams[0];
if (lP0.isString()) lBlockId.setHex(lP0.getString());
else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
} else {
reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters");
return;
}
// prepare reply
json::Document lReply;
lReply.loadFromString("{}");
// process
BlockPtr lBlock;
std::string lCode, lMessage;
// height
uint64_t lHeight = 0;
// try to lookup transaction
ITransactionStoreManagerPtr lStoreManager = wallet_->storeManager();
if (lStoreManager) {
//
std::vector<ITransactionStorePtr> lStorages = lStoreManager->storages();
for (std::vector<ITransactionStorePtr>::iterator lStore = lStorages.begin(); lStore != lStorages.end(); lStore++) {
lBlock = (*lStore)->block(lBlockId);
if (lBlock) {
(*lStore)->blockHeight(lBlockId, lHeight);
break;
}
}
if (lBlock) {
//
json::Value lRootObject = lReply.addObject("result");
lRootObject.addString("id", lBlock->hash().toHex());
lRootObject.addString("chain", lBlock->chain().toHex());
lRootObject.addUInt64("height", lHeight);
lRootObject.addInt("version", lBlock->version());
lRootObject.addUInt64("time", lBlock->time());
lRootObject.addString("prev", lBlock->prev().toHex());
lRootObject.addString("root", lBlock->root().toHex());
lRootObject.addString("origin", lBlock->origin().toHex());
lRootObject.addInt("bits", lBlock->bits());
lRootObject.addInt("nonce", lBlock->nonce());
json::Value lPowObject = lRootObject.addArray("pow");
int lIdx = 0;
for (std::vector<uint32_t>::iterator lNumber = lBlock->cycle_.begin(); lNumber != lBlock->cycle_.end(); lNumber++, lIdx++) {
//
json::Value lItem = lPowObject.newArrayItem();
//lItem.toObject();
//lItem.addInt("index", lIdx);
//lItem.addUInt("number", *lNumber);
lItem.setUInt(*lNumber);
}
} else {
reply = HttpReply::stockReply("E_BLOCK_NOT_FOUND", "Block not found");
return;
}
} else {
reply = HttpReply::stockReply("E_STOREMANAGER", "Store manager not found");
return;
}
if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull();
else {
json::Value lError = lReply.addObject("error");
lError.addString("code", lCode);
lError.addString("message", lMessage);
}
lReply.addString("id", lId.getString());
// pack
pack(reply, lReply);
// finalize
finalize(reply);
} else {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
}
void HttpGetBlockHeaderByHeight::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) {
/* request
{
"jsonrpc": "1.0",
"id": "curltext",
"method": "getblockheaderbyheight",
"params": [
"<chain_id>" -- (string) chain (id)
"<block_height>" -- (string) block height (id)
]
}
*/
/* reply
{
"result": {
"id": "<tx_id>", -- (string) block hash (id)
"chain": "<chain_id>", -- (string) chain / shard hash (id)
"height": <height>, -- (int64) block height
"version": <version>, -- (int) version (0-256)
"time: <time>, -- (int64) block time
"prev": "<prev_id>", -- (string) prev block hash (id)
"root": "<merkle_root_hash>", -- (string) merkle root hash
"origin": "<miner_id>", -- (string) miner address id
"bits": <pow_bits>, -- (int) pow bits
"nonce": <nonce_counter>, -- (int) found nonce
"pow": [
<int>, <int> ... <int> -- (aray) found pow cycle
]
},
"error": -- (object or null) error description
{
"code": "EFAIL",
"message": "<explanation>"
},
"id": "curltext" -- (string) request id
}
*/
// id
json::Value lId;
if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
// params
json::Value lParams;
if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) {
// extract parameters
uint256 lChainId; // 0
uint64_t lBlockHeight = 0; // 1
if (lParams.size() == 2) {
// param[0]
json::Value lP0 = lParams[0];
if (lP0.isString()) lChainId.setHex(lP0.getString());
else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
// param[1]
json::Value lP1 = lParams[1];
if (!convert<uint64_t>(lP1.getString(), lBlockHeight)) {
reply = HttpReply::stockReply("E_INCORRECT_VALUE_TYPE", "Incorrect parameter type"); return;
}
} else {
reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters");
return;
}
// prepare reply
json::Document lReply;
lReply.loadFromString("{}");
// process
BlockPtr lBlock;
std::string lCode, lMessage;
// try to lookup transaction
ITransactionStoreManagerPtr lStoreManager = wallet_->storeManager();
if (lStoreManager) {
//
ITransactionStorePtr lStore = lStoreManager->locate(lChainId);
if (!lStore) { reply = HttpReply::stockReply("E_STORE_NOT_FOUND", "Storage not found"); return; }
BlockHeader lHeader;
if (!lStore->blockHeader(lBlockHeight, lHeader)) {
reply = HttpReply::stockReply("E_BLOCK_NOT_FOUND", "Block was not found"); return;
}
//
json::Value lRootObject = lReply.addObject("result");
lRootObject.addString("id", lHeader.hash().toHex());
lRootObject.addString("chain", lHeader.chain().toHex());
lRootObject.addUInt64("height", lBlockHeight);
lRootObject.addInt("version", lHeader.version());
lRootObject.addUInt64("time", lHeader.time());
lRootObject.addString("prev", lHeader.prev().toHex());
lRootObject.addString("root", lHeader.root().toHex());
lRootObject.addString("origin", lHeader.origin().toHex());
lRootObject.addInt("bits", lHeader.bits());
lRootObject.addInt("nonce", lHeader.nonce());
json::Value lPowObject = lRootObject.addArray("pow");
int lIdx = 0;
for (std::vector<uint32_t>::iterator lNumber = lHeader.cycle_.begin(); lNumber != lHeader.cycle_.end(); lNumber++, lIdx++) {
//
json::Value lItem = lPowObject.newArrayItem();
//lItem.toObject();
//lItem.addInt("index", lIdx);
//lItem.addUInt("number", *lNumber);
lItem.setUInt(*lNumber);
}
} else {
reply = HttpReply::stockReply("E_STOREMANAGER", "Store manager not found");
return;
}
if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull();
else {
json::Value lError = lReply.addObject("error");
lError.addString("code", lCode);
lError.addString("message", lMessage);
}
lReply.addString("id", lId.getString());
// pack
pack(reply, lReply);
// finalize
finalize(reply);
} else {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
}
void HttpCreateAsset::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) {
/* request
{
"jsonrpc": "1.0",
"id": "curltext",
"method": "createasset",
"params": [
"<address>", -- (string) owners' address
"<short_name>", -- (string) asset short name, should be unique
"<description>", -- (string) asset description
"<chunk>", -- (long) asset single chunk
"<scale>", -- (long) asset unit scale
"<chunks>", -- (long) asset unspend chunks
"<type>" -- (string, optional) asset type: limited, unlimited, pegged
]
}
*/
/* reply
{
"result": "<tx_asset_id>", -- (string) txid = asset_id
"error": -- (object or null) error description
{
"code": "EFAIL",
"message": "<explanation>"
},
"id": "curltext" -- (string) request id
}
*/
// id
json::Value lId;
if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
// params
json::Value lParams;
if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) {
// extract parameters
PKey lAddress; // 0
std::string lShortName; // 1
std::string lDescription; // 2
amount_t lChunk; // 3
amount_t lScale; // 4
amount_t lChunks; // 5
std::string lType = "limited"; // 6
if (lParams.size() == 6 || lParams.size() == 7) {
// param[0]
json::Value lP0 = lParams[0];
if (lP0.isString()) lAddress.fromString(lP0.getString());
else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
// param[1]
json::Value lP1 = lParams[1];
if (lP1.isString()) lShortName = lP1.getString();
else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
// param[2]
json::Value lP2 = lParams[2];
if (lP2.isString()) lDescription = lP2.getString();
else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
// param[3]
json::Value lP3 = lParams[3];
if (lP3.isString()) {
amount_t lValue;
if (!convert<amount_t>(lP3.getString(), lValue)) {
reply = HttpReply::stockReply("E_INCORRECT_VALUE_TYPE", "Incorrect parameter type"); return;
}
lChunk = lValue;
} else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
// param[4]
json::Value lP4 = lParams[4];
if (lP4.isString()) {
amount_t lValue;
if (!convert<amount_t>(lP4.getString(), lValue)) {
reply = HttpReply::stockReply("E_INCORRECT_VALUE_TYPE", "Incorrect parameter type"); return;
}
lScale = lValue;
} else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
// param[5]
json::Value lP5 = lParams[5];
if (lP5.isString()) {
amount_t lValue;
if (!convert<amount_t>(lP5.getString(), lValue)) {
reply = HttpReply::stockReply("E_INCORRECT_VALUE_TYPE", "Incorrect parameter type"); return;
}
lChunks = lValue;
} else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
// param[6]
if (lParams.size() == 7) {
json::Value lP6 = lParams[6];
if (lP6.isString()) lType = lP6.getString();
else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
}
} else {
reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters");
return;
}
// prepare reply
json::Document lReply;
lReply.loadFromString("{}");
// process
std::string lCode, lMessage;
TransactionContextPtr lCtx = nullptr;
try {
// create tx
lCtx = wallet_->createTxAssetType(lAddress, lShortName, lDescription, lChunk, lScale, lChunks, (lType == "limited" ? TxAssetType::LIMITED : TxAssetType::UNLIMITED));
if (lCtx->errors().size()) {
reply = HttpReply::stockReply("E_TX_CREATE_ASSET", *lCtx->errors().begin());
return;
}
// push to memory pool
IMemoryPoolPtr lMempool = wallet_->mempoolManager()->locate(MainChain::id()); // dapp -> main chain
if (lMempool) {
//
if (lMempool->pushTransaction(lCtx)) {
// check for errors
if (lCtx->errors().size()) {
// unpack
if (!unpackTransaction(lCtx->tx(), uint256(), 0, 0, 0, false, false, lReply, reply)) return;
// rollback transaction
wallet_->rollback(lCtx);
// error
lCode = "E_TX_MEMORYPOOL";
lMessage = *lCtx->errors().begin();
lCtx = nullptr;
} else if (!lMempool->consensus()->broadcastTransaction(lCtx, wallet_->firstKey()->createPKey().id())) {
lCode = "E_TX_NOT_BROADCASTED";
lMessage = "Transaction is not broadcasted";
}
} else {
lCode = "E_TX_EXISTS";
lMessage = "Transaction already exists";
// unpack
if (!unpackTransaction(lCtx->tx(), uint256(), 0, 0, 0, false, false, lReply, reply)) return;
// rollback transaction
wallet_->rollback(lCtx);
// reset
lCtx = nullptr;
}
} else {
reply = HttpReply::stockReply("E_MEMPOOL", "Corresponding memory pool was not found");
return;
}
}
catch(qbit::exception& ex) {
reply = HttpReply::stockReply(ex.code(), ex.what());
return;
}
if (lCtx != nullptr) lReply.addString("result", lCtx->tx()->hash().toHex());
if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull();
else {
json::Value lError = lReply.addObject("error");
lError.addString("code", lCode);
lError.addString("message", lMessage);
}
lReply.addString("id", lId.getString());
// pack
pack(reply, lReply);
// finalize
finalize(reply);
} else {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
}
void HttpCreateAssetEmission::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) {
/* request
{
"jsonrpc": "1.0",
"id": "curltext",
"method": "createassetemission",
"params": [
"<address>", -- (string) owners' address
"<asset>" -- (string) asset id
]
}
*/
/* reply
{
"result": "<tx_emission_id>", -- (string) txid = emission_id
"error": -- (object or null) error description
{
"code": "EFAIL",
"message": "<explanation>"
},
"id": "curltext" -- (string) request id
}
*/
// id
json::Value lId;
if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
// params
json::Value lParams;
if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) {
// extract parameters
PKey lAddress; // 0
uint256 lAsset; // 1
if (lParams.size() == 2) {
// param[0]
json::Value lP0 = lParams[0];
if (lP0.isString()) lAddress.fromString(lP0.getString());
else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
// param[1]
json::Value lP1 = lParams[1];
if (lP1.isString()) lAsset.setHex(lP1.getString());
else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
} else {
reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters");
return;
}
// prepare reply
json::Document lReply;
lReply.loadFromString("{}");
// process
std::string lCode, lMessage;
TransactionContextPtr lCtx = nullptr;
try {
// create tx
lCtx = wallet_->createTxLimitedAssetEmission(lAddress, lAsset);
if (lCtx->errors().size()) {
reply = HttpReply::stockReply("E_TX_CREATE_ASSET_EMISSION", *lCtx->errors().begin());
return;
}
// push to memory pool
IMemoryPoolPtr lMempool = wallet_->mempoolManager()->locate(MainChain::id()); // dapp -> main chain
if (lMempool) {
//
if (lMempool->pushTransaction(lCtx)) {
// check for errors
if (lCtx->errors().size()) {
// unpack
if (!unpackTransaction(lCtx->tx(), uint256(), 0, 0, 0, false, false, lReply, reply)) return;
// rollback transaction
wallet_->rollback(lCtx);
// error
lCode = "E_TX_MEMORYPOOL";
lMessage = *lCtx->errors().begin();
lCtx = nullptr;
} else if (!lMempool->consensus()->broadcastTransaction(lCtx, wallet_->firstKey()->createPKey().id())) {
lCode = "E_TX_NOT_BROADCASTED";
lMessage = "Transaction is not broadcasted";
}
} else {
lCode = "E_TX_EXISTS";
lMessage = "Transaction already exists";
// unpack
if (!unpackTransaction(lCtx->tx(), uint256(), 0, 0, 0, false, false, lReply, reply)) return;
// rollback transaction
wallet_->rollback(lCtx);
// reset
lCtx = nullptr;
}
} else {
reply = HttpReply::stockReply("E_MEMPOOL", "Corresponding memory pool was not found");
return;
}
}
catch(qbit::exception& ex) {
reply = HttpReply::stockReply(ex.code(), ex.what());
return;
}
if (lCtx != nullptr) lReply.addString("result", lCtx->tx()->hash().toHex());
if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull();
else {
json::Value lError = lReply.addObject("error");
lError.addString("code", lCode);
lError.addString("message", lMessage);
}
lReply.addString("id", lId.getString());
// pack
pack(reply, lReply);
// finalize
finalize(reply);
} else {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
}
void HttpGetState::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) {
/* request
{
"jsonrpc": "1.0",
"id": "curltext",
"method": "getstate",
"params": []
}
*/
/* reply
{
"result": {
"state": {
...
}
}
},
"error": -- (object or null) error description
{
"code": "EFAIL",
"message": "<explanation>"
},
"id": "curltext" -- (string) request id
}
*/
// id
json::Value lId;
if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
// params
json::Value lParams;
if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) {
// prepare reply
json::Document lReply;
lReply.loadFromString("{}");
json::Value lKeyObject = lReply.addObject("result");
json::Value lStateObject = lKeyObject.addObject("state");
// get peers
std::list<IPeerPtr> lPeers;
peerManager_->allPeers(lPeers);
// peer manager
lStateObject.addString("version", strprintf("%d.%d.%d.%d",
QBIT_VERSION_MAJOR, QBIT_VERSION_MINOR, QBIT_VERSION_REVISION, QBIT_VERSION_BUILD));
lStateObject.addUInt("clients", peerManager_->clients());
lStateObject.addUInt("peers_count", lPeers.size());
uint64_t lInQueue = 0;
uint64_t lOutQueue = 0;
uint64_t lPendingQueue = 0;
uint64_t lReceivedCount = 0;
uint64_t lReceivedBytes = 0;
uint64_t lSentCount = 0;
uint64_t lSentBytes = 0;
for (std::list<IPeerPtr>::iterator lPeer = lPeers.begin(); lPeer != lPeers.end(); lPeer++) {
//
if ((*lPeer)->status() == IPeer::UNDEFINED) continue;
//
if ((*lPeer)->status() == IPeer::BANNED || (*lPeer)->status() == IPeer::POSTPONED) {
//
lInQueue += (*lPeer)->inQueueLength();
lOutQueue += (*lPeer)->outQueueLength();
lPendingQueue += (*lPeer)->pendingQueueLength();
lReceivedCount += (*lPeer)->receivedMessagesCount();
lReceivedBytes += (*lPeer)->bytesReceived();
lSentCount += (*lPeer)->sentMessagesCount();
lSentBytes += (*lPeer)->bytesSent();
continue;
}
lInQueue += (*lPeer)->inQueueLength();
lOutQueue += (*lPeer)->outQueueLength();
lPendingQueue += (*lPeer)->pendingQueueLength();
lReceivedCount += (*lPeer)->receivedMessagesCount();
lReceivedBytes += (*lPeer)->bytesReceived();
lSentCount += (*lPeer)->sentMessagesCount();
lSentBytes += (*lPeer)->bytesSent();
}
//
lStateObject.addUInt("in_queue", lInQueue);
lStateObject.addUInt("out_queue", lOutQueue);
lStateObject.addUInt("pending_queue", lPendingQueue);
lStateObject.addUInt("received_count", lReceivedCount);
lStateObject.addUInt64("received_bytes", lReceivedBytes);
lStateObject.addUInt("sent_count", lSentCount);
lStateObject.addUInt64("sent_bytes", lSentBytes);
//
StatePtr lState = peerManager_->consensusManager()->currentState();
//
json::Value lChainsObject = lStateObject.addArray("chains");
std::vector<State::BlockInfo> lInfos = lState->infos();
for (std::vector<State::BlockInfo>::iterator lInfo = lInfos.begin(); lInfo != lInfos.end(); lInfo++) {
//
json::Value lChain = lChainsObject.newArrayItem();
lChain.toObject(); // make object
// get mempool
IMemoryPoolPtr lMempool = peerManager_->memoryPoolManager()->locate(lInfo->chain());
if (lMempool) {
//
json::Value lMempoolObject = lChain.addObject("mempool");
size_t lTx = 0, lCandidatesTx = 0, lPostponedTx = 0;
lMempool->statistics(lTx, lCandidatesTx, lPostponedTx);
lMempoolObject.addUInt64("txs", lTx);
lMempoolObject.addUInt64("candidates", lCandidatesTx);
lMempoolObject.addUInt64("postponed", lPostponedTx);
}
// get consensus
IConsensusPtr lConsensus = peerManager_->consensusManager()->locate(lInfo->chain());
lChain.addString("dapp", lInfo->dApp().size() ? lInfo->dApp() : "none");
lChain.addUInt64("height", lInfo->height());
lChain.addString("chain", lInfo->chain().toHex());
lChain.addString("block", lInfo->hash().toHex());
if (lConsensus) {
lChain.addUInt64("time", lConsensus->currentTime());
lChain.addString("state", lConsensus->chainStateString());
}
// sync job
IConsensus::ChainState lState = lConsensus->chainState();
if (lState == IConsensus::SYNCHRONIZING) {
SynchronizationJobPtr lJob = nullptr;
for (std::list<IPeerPtr>::iterator lPeer = lPeers.begin(); lPeer != lPeers.end(); lPeer++) {
//
if ((*lPeer)->status() == IPeer::ACTIVE) {
//
SynchronizationJobPtr lNewJob = (*lPeer)->locateJob(lInfo->chain());
if (!lJob) lJob = lNewJob;
else if (lNewJob && lJob && lJob->timestamp() < lNewJob->timestamp()) {
lJob = lNewJob;
}
}
}
if (lJob) {
json::Value lSyncObject = lChain.addObject("synchronization");
lSyncObject.addString("type", lJob->typeString());
if (lJob->type() != SynchronizationJob::PARTIAL)
lSyncObject.addUInt64("remains", lJob->pendingBlocks());
}
}
}
lReply.addObject("error").toNull();
lReply.addString("id", lId.getString());
// pack
pack(reply, lReply);
// finalize
finalize(reply);
} else {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
}
void HttpReleasePeer::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) {
/* request
{
"jsonrpc": "1.0",
"id": "curltext",
"method": "releasepeer",
"params": [
"<peer_address>" -- (string) peer IP address
]
}
*/
/* reply
{
"result": "<peer_address>", -- (string) peer IP address
"error": -- (object or null) error description
{
"code": "EFAIL",
"message": "<explanation>"
},
"id": "curltext" -- (string) request id
}
*/
// id
json::Value lId;
if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
// params
json::Value lParams;
if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) {
// extract parameters
std::string lAddress; // 0
if (lParams.size() == 1) {
// param[0]
json::Value lP0 = lParams[0];
if (lP0.isString()) lAddress = lP0.getString();
else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
} else {
reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters");
return;
}
// prepare reply
json::Document lReply;
lReply.loadFromString("{}");
peerManager_->release(lAddress);
lReply.addString("result", lAddress);
lReply.addObject("error").toNull();
lReply.addString("id", lId.getString());
// pack
pack(reply, lReply);
// finalize
finalize(reply);
} else {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
}
void HttpGetEntitiesCount::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) {
/* request
{
"jsonrpc": "1.0",
"id": "curltext",
"method": "getentitiescount",
"params": [
"<dapp_name>" -- (string, required) dapp name
]
}
*/
/* reply
{
"result": -- (object) details
{
...
},
"error": -- (object or null) error description
{
"code": "EFAIL",
"message": "<explanation>"
},
"id": "curltext" -- (string) request id
}
*/
// id
json::Value lId;
if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
// params
json::Value lParams;
if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) {
// extract parameters
std::string lDApp; // 0
if (lParams.size()) {
// param[0]
json::Value lP0 = lParams[0];
if (lP0.isString()) lDApp = lP0.getString();
else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
} else {
reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters");
return;
}
//
json::Document lReply;
lReply.loadFromString("{}");
json::Value lRootObject = lReply.addObject("result");
json::Value lDAppObject = lRootObject.addArray(lDApp);
//
std::map<uint256, uint32_t> lShardInfo;
ITransactionStorePtr lStorage = peerManager_->consensusManager()->storeManager()->locate(MainChain::id());
//
std::vector<ISelectEntityCountByShardsHandler::EntitiesCount> lEntitiesCount;
if (lStorage->entityStore()->entityCountByDApp(lDApp, lShardInfo)) {
for (std::map<uint256, uint32_t>::iterator lItem = lShardInfo.begin(); lItem != lShardInfo.end(); lItem++) {
//
json::Value lDAppItem = lDAppObject.newArrayItem();
lDAppItem.toObject();
lDAppItem.addString("shard", lItem->first.toHex());
lDAppItem.addUInt("count", lItem->second);
}
}
lReply.addObject("error").toNull();
lReply.addString("id", lId.getString());
// pack
pack(reply, lReply);
// finalize
finalize(reply);
} else {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
}
void HttpGetUnconfirmedTransactions::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) {
/* request
{
"jsonrpc": "1.0",
"id": "curltext",
"method": "getunconfirmedtxs",
"params": [
"<chain_id>" -- (string) chain hash (id)
]
}
*/
/* reply
{
"result": {
"txs": [
"...",
"..."
]
},
"error": -- (object or null) error description
{
"code": "EFAIL",
"message": "<explanation>"
},
"id": "curltext" -- (string) request id
}
*/
// id
json::Value lId;
if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
// params
json::Value lParams;
if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) {
// extract parameters
uint256 lChainId; // 0
if (lParams.size() == 1) {
// param[0]
json::Value lP0 = lParams[0];
if (lP0.isString()) lChainId.setHex(lP0.getString());
else { reply = HttpReply::stockReply(HttpReply::bad_request); return; }
} else {
reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters");
return;
}
// prepare reply
json::Document lReply;
lReply.loadFromString("{}");
json::Value lResultObject = lReply.addObject("result");
json::Value lTxsArrayObject = lResultObject.addArray("txs");
// process
std::string lCode, lMessage;
// try to lookup transaction
IMemoryPoolManagerPtr lMempoolManager = wallet_->mempoolManager();
if (lMempoolManager) {
//
IMemoryPoolPtr lMempool = lMempoolManager->locate(lChainId);
//
if (lMempool) {
//
uint64_t lTotal = 0;
std::list<uint256> lTxs;
lMempool->selectTransactions(lTxs, lTotal, 10000 /*max*/);
lResultObject.addUInt64("total", lTotal);
//
for (std::list<uint256>::iterator lTx = lTxs.begin(); lTx != lTxs.end(); lTx++) {
//
json::Value lItem = lTxsArrayObject.newArrayItem();
lItem.setString(lTx->toHex());
}
} else {
reply = HttpReply::stockReply("E_MEMPOOL_NOT_FOUND", "Memory pool was not found");
return;
}
} else {
reply = HttpReply::stockReply("E_POOLMANAGER", "Pool manager not found");
return;
}
if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull();
else {
json::Value lError = lReply.addObject("error");
lError.addString("code", lCode);
lError.addString("message", lMessage);
}
lReply.addString("id", lId.getString());
// pack
pack(reply, lReply);
// finalize
finalize(reply);
} else {
reply = HttpReply::stockReply(HttpReply::bad_request);
return;
}
}
| 29.487834
| 171
| 0.627141
|
qbit-t
|
9734163529bf58d4bd81ddf95bf6f89ab05f743b
| 1,032
|
cpp
|
C++
|
C++/05_Dynamic_Programming/MEDIUM_DECODE_WAYS.cpp
|
animeshramesh/interview-prep
|
882e8bc8b4653a713754ab31a3b08e05505be2bc
|
[
"Apache-2.0"
] | null | null | null |
C++/05_Dynamic_Programming/MEDIUM_DECODE_WAYS.cpp
|
animeshramesh/interview-prep
|
882e8bc8b4653a713754ab31a3b08e05505be2bc
|
[
"Apache-2.0"
] | null | null | null |
C++/05_Dynamic_Programming/MEDIUM_DECODE_WAYS.cpp
|
animeshramesh/interview-prep
|
882e8bc8b4653a713754ab31a3b08e05505be2bc
|
[
"Apache-2.0"
] | null | null | null |
/* A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
The number of ways decoding "12" is 2.
*/
// https://stackoverflow.com/questions/20342462/review-an-answer-decode-ways
// https://www.youtube.com/watch?v=aCKyFYF9_Bg
// Solution from http://bangbingsyb.blogspot.com/2014/11/leetcode-decode-ways.html
int numDecodings(string s) {
if(s.empty() || s[0]<'1' || s[0]>'9') return 0;
vector<int> dp(s.size()+1,0);
dp[0] = dp[1] = 1; // dp[i] is the number of ways to decode str[0:i]
for(int i=1; i<s.size(); i++)
{
if(!isdigit(s[i])) return 0;
int v = (s[i-1]-'0')*10 + (s[i]-'0');
if(v<=26 && v>9) dp[i+1] += dp[i-1];
if(s[i]!='0') dp[i+1] += dp[i];
if(dp[i+1]==0) return 0;
}
return dp[s.size()];
}
| 32.25
| 97
| 0.592054
|
animeshramesh
|
9734922a52146c96dae481fb1d6da9230ee6ff94
| 1,810
|
cpp
|
C++
|
libraries/physics/src/ContactConstraint.cpp
|
ey6es/hifi
|
23f9c799dde439e4627eef45341fb0d53feff80b
|
[
"Apache-2.0"
] | null | null | null |
libraries/physics/src/ContactConstraint.cpp
|
ey6es/hifi
|
23f9c799dde439e4627eef45341fb0d53feff80b
|
[
"Apache-2.0"
] | null | null | null |
libraries/physics/src/ContactConstraint.cpp
|
ey6es/hifi
|
23f9c799dde439e4627eef45341fb0d53feff80b
|
[
"Apache-2.0"
] | null | null | null |
//
// ContactConstraint.cpp
// libraries/physcis/src
//
// Created by Andrew Meadows 2014.07.24
// Copyright 2014 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include <SharedUtil.h>
#include "ContactConstraint.h"
#include "VerletPoint.h"
ContactConstraint::ContactConstraint(VerletPoint* pointA, VerletPoint* pointB)
: _pointA(pointA), _pointB(pointB), _strength(1.0f) {
assert(_pointA != NULL && _pointB != NULL);
_offset = _pointB->_position - _pointA->_position;
}
float ContactConstraint::enforce() {
_pointB->_position += _strength * (_pointA->_position + _offset - _pointB->_position);
return 0.0f;
}
float ContactConstraint::enforceWithNormal(const glm::vec3& normal) {
glm::vec3 delta = _pointA->_position + _offset - _pointB->_position;
// split delta into parallel (pDelta) and perpendicular (qDelta) components
glm::vec3 pDelta = glm::dot(delta, normal) * normal;
glm::vec3 qDelta = delta - pDelta;
// use the relative sizes of the components to decide how much perpenducular delta to use
// (i.e. dynamic friction)
float lpDelta = glm::length(pDelta);
float lqDelta = glm::length(qDelta);
float qFactor = lqDelta > lpDelta ? (lpDelta / lqDelta - 1.0f) : 0.0f;
// recombine the two components to get the final delta
delta = pDelta + qFactor * qDelta;
// attenuate strength by how much _offset is perpendicular to normal
float distance = glm::length(_offset);
float strength = _strength * ((distance > EPSILON) ? glm::abs(glm::dot(_offset, normal)) / distance : 1.0f);
// move _pointB
_pointB->_position += strength * delta;
return strength * glm::length(delta);
}
| 33.518519
| 112
| 0.692265
|
ey6es
|
9734eb840112ee3d67af26b01b7786ba873b5526
| 2,839
|
hpp
|
C++
|
include/boost/http_proto/detail/copied_strings.hpp
|
alandefreitas/http_proto
|
dc64cbdd44048a2c06671282b736f7edacb39a42
|
[
"BSL-1.0"
] | 6
|
2021-11-17T03:23:50.000Z
|
2021-11-25T15:58:02.000Z
|
include/boost/http_proto/detail/copied_strings.hpp
|
alandefreitas/http_proto
|
dc64cbdd44048a2c06671282b736f7edacb39a42
|
[
"BSL-1.0"
] | 6
|
2021-11-17T16:13:52.000Z
|
2022-01-31T04:17:47.000Z
|
include/boost/http_proto/detail/copied_strings.hpp
|
samd2/http_proto
|
486729f1a68b7611f143e18c7bae8df9b908e9aa
|
[
"BSL-1.0"
] | 3
|
2021-11-17T03:01:12.000Z
|
2021-11-17T14:14:45.000Z
|
//
// Copyright (c) 2019 Vinnie Falco (vinnie.falco@gmail.com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/CPPAlliance/http_proto
//
#ifndef BOOST_HTTP_PROTO_DETAIL_COPIED_STRINGS_HPP
#define BOOST_HTTP_PROTO_DETAIL_COPIED_STRINGS_HPP
#include <boost/http_proto/string_view.hpp>
#include <functional>
namespace boost {
namespace http_proto {
namespace detail {
// Makes copies of string_view parameters as
// needed when the storage for the parameters
// overlap the container being modified.
class basic_copied_strings
{
struct dynamic_buf
{
dynamic_buf* next;
};
string_view s_;
char* local_buf_;
std::size_t local_remain_;
dynamic_buf* dynamic_list_ = nullptr;
bool
is_overlapping(
string_view s) const noexcept
{
auto const b1 = s_.data();
auto const e1 = b1 + s_.size();
auto const b2 = s.data();
auto const e2 = b2 + s.size();
auto const less_equal =
std::less_equal<char const*>();
if(less_equal(e1, b2))
return false;
if(less_equal(e2, b1))
return false;
return true;
}
public:
~basic_copied_strings()
{
while(dynamic_list_)
{
auto p = dynamic_list_;
dynamic_list_ =
dynamic_list_->next;
delete[] p;
}
}
basic_copied_strings(
string_view s,
char* local_buf,
std::size_t local_size) noexcept
: s_(s)
, local_buf_(local_buf)
, local_remain_(local_size)
{
}
string_view
maybe_copy(
string_view s)
{
if(! is_overlapping(s))
return s;
if(local_remain_ >= s.size())
{
std::memcpy(local_buf_,
s.data(), s.size());
s = string_view(
local_buf_, s.size());
local_buf_ += s.size();
local_remain_ -= s.size();
return s;
}
auto const n =
sizeof(dynamic_buf);
auto p = new dynamic_buf[1 +
sizeof(n) * ((s.size() +
sizeof(n) - 1) /
sizeof(n))];
std::memcpy(p + 1,
s.data(), s.size());
s = string_view(reinterpret_cast<
char const*>(p + 1), s.size());
p->next = dynamic_list_;
dynamic_list_ = p;
return s;
}
};
class copied_strings
: public basic_copied_strings
{
char buf_[4096];
public:
copied_strings(
string_view s)
: basic_copied_strings(
s, buf_, sizeof(buf_))
{
}
};
} // detail
} // http_proto
} // boost
#endif
| 22.712
| 79
| 0.559352
|
alandefreitas
|
97384c308cf5a7f11846cde620d00a08f7c3b3c2
| 536
|
cpp
|
C++
|
ALP/sequencia/L01_ex01.cpp
|
khrystie/fatec_ads
|
a5fec2c612943342f731a46814d4f6df67eb692f
|
[
"MIT"
] | null | null | null |
ALP/sequencia/L01_ex01.cpp
|
khrystie/fatec_ads
|
a5fec2c612943342f731a46814d4f6df67eb692f
|
[
"MIT"
] | null | null | null |
ALP/sequencia/L01_ex01.cpp
|
khrystie/fatec_ads
|
a5fec2c612943342f731a46814d4f6df67eb692f
|
[
"MIT"
] | null | null | null |
/*
Exercício: Faça um algoritmo que receba 2 números inteiros e apresente a soma desses números.
*/
#include <iostream>
int main() {
//declaração de variáveis
int num1, num2;
// atribuir valor 0
num1=0;
num2=0;
std::cout << "Programa que lê dois números inteiros e retorna o valor da soma\n";
std::cout <<"Digite o primeiro número inteiro: \n";
std::cin >> num1;
std::cout <<"Digite o segundo número inteiro: \n";
std::cin >> num2;
std::cout <<"A soma dos dois números inteiros é: \n" <<num1+num2;
}
| 22.333333
| 95
| 0.652985
|
khrystie
|
9738b40e93cc34db346f6f331cea0a1ca13bae6d
| 372
|
cp
|
C++
|
Lin/Mod/X11.cp
|
romiras/BlackBox-linux
|
3abf415f181024d3ce9456883910d4eb68c5a676
|
[
"BSD-2-Clause"
] | 2
|
2016-03-17T08:27:55.000Z
|
2020-05-02T08:42:08.000Z
|
Lin/Mod/X11.cp
|
romiras/BlackBox-linux
|
3abf415f181024d3ce9456883910d4eb68c5a676
|
[
"BSD-2-Clause"
] | null | null | null |
Lin/Mod/X11.cp
|
romiras/BlackBox-linux
|
3abf415f181024d3ce9456883910d4eb68c5a676
|
[
"BSD-2-Clause"
] | null | null | null |
MODULE LinX11 ["libX11.so"];
IMPORT LinLibc;
TYPE
Display* = INTEGER;
PROCEDURE XFreeFontNames* (list: LinLibc.StrArray);
PROCEDURE XListFonts* (display: Display; pattern: LinLibc.PtrSTR; maxnames: INTEGER;
VAR actual_count_return: INTEGER): LinLibc.StrArray;
PROCEDURE XOpenDisplay* (VAR [nil] display_name: LinLibc.PtrSTR): Display;
END LinX11.
| 26.571429
| 86
| 0.733871
|
romiras
|
9738eda77042cec54309a95c28906a00687bea7c
| 8,818
|
cpp
|
C++
|
Classes/Helpers/AnimationHelper.cpp
|
funkyzooink/fresh-engine
|
de15fa6ebe1b686819b28cd92ee8a6771c4ff878
|
[
"MIT"
] | 3
|
2019-10-09T09:17:49.000Z
|
2022-03-02T17:57:05.000Z
|
Classes/Helpers/AnimationHelper.cpp
|
funkyzooink/fresh-engine
|
de15fa6ebe1b686819b28cd92ee8a6771c4ff878
|
[
"MIT"
] | 33
|
2019-10-08T18:45:48.000Z
|
2022-01-05T21:53:02.000Z
|
Classes/Helpers/AnimationHelper.cpp
|
funkyzooink/fresh-engine
|
de15fa6ebe1b686819b28cd92ee8a6771c4ff878
|
[
"MIT"
] | 7
|
2019-10-10T11:31:58.000Z
|
2021-02-08T14:24:30.000Z
|
/****************************************************************************
Copyright (c) 2014-2019 Gabriel Heilig
fresh-engine
funkyzooink@gmail.com
****************************************************************************/
#include "AnimationHelper.h"
#include "../GameData/Constants.h"
#include "../GameData/GameConfig.h"
#include "../GameData/Gamedata.h"
#include "cocos2d.h"
// MARK: Animation Helper
void AnimationHelper::levelinfoFadeInAnimation(cocos2d::Node* node1, cocos2d::Node* node2)
{
auto visibleSize = cocos2d::Director::getInstance()->getVisibleSize();
switch (GAMECONFIG.getLevelInfoPopupType())
{
case 1:
{
node1->runAction(cocos2d::Sequence::create(
cocos2d::MoveTo::create(
1.0F, cocos2d::Vec2(visibleSize.width / 2 - CONSTANTS.getOffset() * 2, node1->getPosition().y)),
nullptr));
node2->runAction(cocos2d::Sequence::create(
cocos2d::MoveTo::create(1.0F, cocos2d::Vec2(visibleSize.width / 2 - node2->getContentSize().width / 2,
node2->getPosition().y)),
nullptr));
break;
}
default:
{
auto position = node1->getPosition();
node1->setPosition(position.x, visibleSize.height);
node2->setVisible(true);
node1->runAction(cocos2d::Sequence::create(cocos2d::MoveTo::create(1.0F, position), nullptr));
break;
}
}
}
void AnimationHelper::levelInfoFadeOutAnimation(cocos2d::Node* node1, cocos2d::Node* node2)
{
auto visibleSize = cocos2d::Director::getInstance()->getVisibleSize();
switch (GAMECONFIG.getLevelInfoPopupType())
{
case 1:
{
node1->runAction(cocos2d::Sequence::create(
cocos2d::MoveTo::create(1.0F, cocos2d::Vec2(visibleSize.width, node1->getPosition().y)), nullptr));
node2->runAction(cocos2d::Sequence::create(
cocos2d::MoveTo::create(1.5F, cocos2d::Vec2(-visibleSize.width, node2->getPosition().y)), nullptr));
break;
}
default:
{
node2->setVisible(true);
node1->runAction(cocos2d::Sequence::create(
cocos2d::MoveTo::create(1.5F, cocos2d::Vec2(node1->getPosition().x, -visibleSize.height)), nullptr));
break;
}
}
}
void AnimationHelper::fadeIn(cocos2d::Node* from, cocos2d::Node* to)
{
auto duration = 0.8F;
auto visibleSize = cocos2d::Director::getInstance()->getVisibleSize();
if (to != nullptr)
{
to->setVisible(true); // make sure both nodes are visible
auto toPosition = cocos2d::Vec2(to->getPosition().x, 0.0);
switch (GAMECONFIG.getMainSceneAnimation())
{
case 1:
{
to->setPosition(toPosition.x, visibleSize.height);
to->runAction(cocos2d::Sequence::create(cocos2d::MoveTo::create(duration, toPosition), nullptr));
break;
}
default:
{
to->setPosition(toPosition);
break;
}
}
}
if (from != nullptr)
{
from->setVisible(true); // make sure both nodes are visible
auto fromPosition = cocos2d::Vec2(from->getPosition().x, -visibleSize.height);
switch (GAMECONFIG.getMainSceneAnimation())
{
case 1:
{
from->setPosition(0.0, 0.0);
from->runAction(cocos2d::Sequence::create(cocos2d::MoveTo::create(duration, fromPosition), nullptr));
break;
}
default:
{
from->setPosition(fromPosition);
break;
}
}
}
}
void AnimationHelper::fadeOut(cocos2d::Node* from, cocos2d::Node* to)
{
auto duration = 0.8F;
auto visibleSize = cocos2d::Director::getInstance()->getVisibleSize();
if (to != nullptr)
{
to->setVisible(true); // make sure both nodes are visible
auto toPosition = cocos2d::Vec2(to->getPosition().x, 0.0F);
switch (GAMECONFIG.getMainSceneAnimation())
{
case 1:
{
to->setPosition(toPosition.x, -visibleSize.height);
to->runAction(cocos2d::Sequence::create(cocos2d::MoveTo::create(duration, toPosition), nullptr));
break;
}
default:
{
to->setPosition(toPosition);
break;
}
}
}
if (from != nullptr)
{
from->setVisible(true); // make sure both nodes are visible
auto fromPosition = cocos2d::Vec2(from->getPosition().x, visibleSize.height);
switch (GAMECONFIG.getMainSceneAnimation())
{
case 1:
{
from->setPosition(0.0, 0.0);
from->runAction(cocos2d::Sequence::create(cocos2d::MoveTo::create(duration, fromPosition), nullptr));
break;
}
default:
{
from->setPosition(fromPosition);
break;
}
}
}
}
cocos2d::TransitionScene* AnimationHelper::sceneTransition(cocos2d::Scene* scene)
{
return cocos2d::TransitionFade::create(0.2f, scene);
}
cocos2d::FiniteTimeAction* AnimationHelper::blinkAnimation()
{
float blinkDuration = 0.05F;
return cocos2d::Sequence::create(cocos2d::FadeOut::create(blinkDuration), cocos2d::FadeIn::create(blinkDuration),
cocos2d::FadeOut::create(blinkDuration), cocos2d::FadeIn::create(blinkDuration),
nullptr);
}
cocos2d::Action* AnimationHelper::getActionForTag(const std::string& tag)
{
auto animationCache = cocos2d::AnimationCache::getInstance()->getAnimation(tag);
if (animationCache == nullptr)
{
return nullptr;
}
auto animation = cocos2d::Animate::create(animationCache);
auto repeatForever = cocos2d::RepeatForever::create(animation);
return repeatForever;
}
std::map<AnimationHelper::AnimationTagEnum, std::string> AnimationHelper::initAnimations(
const std::string& type, const std::map<std::string, std::vector<std::string>>& animationMap)
{
std::map<AnimationHelper::AnimationTagEnum, std::string> _animationEnumMap;
_animationEnumMap[AnimationHelper::AnimationTagEnum::ATTACK_LEFT_ANIMATION] = type + "_attack_left";
_animationEnumMap[AnimationHelper::AnimationTagEnum::FALL_LEFT_ANIMATION] = type + "_jump_left_down";
_animationEnumMap[AnimationHelper::AnimationTagEnum::HIT_LEFT_ANIMATION] = type + "_hit_left";
_animationEnumMap[AnimationHelper::AnimationTagEnum::IDLE_LEFT_ANIMATION] = type + "_idle_left";
_animationEnumMap[AnimationHelper::AnimationTagEnum::JUMP_LEFT_ANIMATION] = type + "_jump_left_up";
_animationEnumMap[AnimationHelper::AnimationTagEnum::WALK_LEFT_ANIMATION] = type + "_walk_left";
_animationEnumMap[AnimationHelper::AnimationTagEnum::ATTACK_RIGHT_ANIMATION] = type + "_attack_right";
_animationEnumMap[AnimationHelper::AnimationTagEnum::FALL_RIGHT_ANIMATION] = type + "_jump_right_down";
_animationEnumMap[AnimationHelper::AnimationTagEnum::HIT_RIGHT_ANIMATION] = type + "_hit_right";
_animationEnumMap[AnimationHelper::AnimationTagEnum::IDLE_RIGHT_ANIMATION] = type + "_idle_right";
_animationEnumMap[AnimationHelper::AnimationTagEnum::JUMP_RIGHT_ANIMATION] = type + "_jump_right_up";
_animationEnumMap[AnimationHelper::AnimationTagEnum::WALK_RIGHT_ANIMATION] = type + "_walk_right";
cocos2d::Animation* animation = nullptr;
for (auto const& entry : animationMap)
{
auto animationTag = type + "_" + entry.first; // TODO this needs to be the same as in animationEnumMap
// TODO check if created tag is part of animationEnum otherwise abort
animation = prepareVector(entry.second, 0.2F);
// check times! 0.5 for staticshooter idle
// check times! 0.2 for jumps falls and walking animation
cocos2d::AnimationCache::getInstance()->addAnimation(animation, animationTag);
}
return _animationEnumMap;
}
cocos2d::Animation* AnimationHelper::prepareVector(const std::vector<std::string>& filenames, float duration)
{
cocos2d::Vector<cocos2d::SpriteFrame*> spriteVector(filenames.size());
for (const std::string& file : filenames)
{
cocos2d::SpriteFrame* spriteFrame = cocos2d::SpriteFrameCache::getInstance()->getSpriteFrameByName(file);
spriteVector.pushBack(spriteFrame);
}
cocos2d::Animation* animation = cocos2d::Animation::createWithSpriteFrames(spriteVector, duration, 1);
return animation;
};
| 37.683761
| 118
| 0.612611
|
funkyzooink
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.