blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
247
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 4
111
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
58
| visit_date
timestamp[ns]date 2015-07-25 18:16:41
2023-09-06 10:45:08
| revision_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| github_id
int64 3.89k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 25
values | gha_event_created_at
timestamp[ns]date 2012-06-07 00:51:45
2023-09-14 21:58:52
⌀ | gha_created_at
timestamp[ns]date 2008-03-27 23:40:48
2023-08-24 19:49:39
⌀ | gha_language
stringclasses 159
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
10.5M
| extension
stringclasses 111
values | filename
stringlengths 1
195
| text
stringlengths 7
10.5M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0b6ca5bf33529e8b5cad6a85ffda17d285289cad
|
74a0bd5552e2ffc94162ea9a2ffba3b46120d60d
|
/Mega_project_list/05_Text/07_Text_Editor/_18_Text_EditorApp.cpp
|
32f2e1eb85c5b34a0006e20540ebb3790be3f7df
|
[] |
no_license
|
dmytrofrolov/Cpp
|
9103f5979e710061d8bf03465fc87b7fc3ff7bc9
|
a216cadd3903c1e73381bf6d12a394af472cfc93
|
refs/heads/master
| 2016-09-09T22:08:01.471867
| 2015-05-04T19:06:49
| 2015-05-04T19:06:49
| 25,148,597
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 944
|
cpp
|
_18_Text_EditorApp.cpp
|
/***************************************************************
* Name: _18_Text_EditorApp.cpp
* Purpose: Code for Application Class
* Author: Dmytro Frolov (dimaf@i.ua)
* Created: 2015-01-11
**************************************************************/
#ifdef WX_PRECOMP
#include "wx_pch.h"
#endif
#ifdef __BORLANDC__
#pragma hdrstop
#endif //__BORLANDC__
#include "_18_Text_EditorApp.h"
#include "_18_Text_EditorMain.h"
//#include "wx/settings.h"
IMPLEMENT_APP(_18_Text_EditorApp);
bool _18_Text_EditorApp::OnInit()
{
_18_Text_Editor_Frame* dlg = new _18_Text_Editor_Frame(0L, _("wxWidgets Text Editor"));
//dlg->SetBackgroundColour( wxSystemSettings::GetColour( wxNullColour ) );
dlg->SetBackgroundColour( wxNullColour );
wxFont::SetDefaultEncoding(wxFONTENCODING_CP1251);
dlg->SetMinSize(wxSize(350, 235));
dlg->SetIcon(wxICON(aaaa)); // To Set App Icon
dlg->Show();
return true;
}
|
79f2dae7bbbcaeed259f660a56cf74a334d2354f
|
498f5629f15083ac5dbbb3ba73f90bf59067f2e5
|
/codeforces/test.cpp
|
d6245c4b10b947fe92d5b20c81199b6b7e372b52
|
[] |
no_license
|
priyanshuN/Algorithms
|
b3103722fd6657d6507d72d73ba80b35e3a196dd
|
22559ffc50939256f2324afd313d4a32bb63f6ac
|
refs/heads/master
| 2022-01-31T06:17:52.577691
| 2022-01-08T14:33:56
| 2022-01-08T14:33:56
| 244,685,281
| 1
| 0
| null | 2022-01-08T14:33:57
| 2020-03-03T16:24:45
|
C++
|
UTF-8
|
C++
| false
| false
| 540
|
cpp
|
test.cpp
|
#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
// for getting input from input.txt
freopen("G:/codes/Result/input.txt", "r", stdin);
// for writing output to output.txt
freopen("G:/codes/Result/output.txt", "w", stdout);
// for writing error to error.txt
freopen("G:/codes/Result/error.txt", "w", stderr);
#endif
string s;
cin>>s;
cout<<s<<endl;
float n=0.345;
int t=2;
while(t--){
n=n*10;
//cout<<int(n);
if(int(n)==34){
cout<<n;
}
}
}
|
4f1a09facf9b9bb587a722a0e35e7d614aef6b64
|
d1a639c3555bcefcf0f876792cdcd0e2f9713519
|
/PacMan/ghost.cpp
|
07d5df6960931daed0dc3851a0b6f440f9e0cf58
|
[] |
no_license
|
Seshelle/PacMan
|
201fda911188c56f8e85e5577ad759d24da480e1
|
da58a1bc4f38ecca2867d39651cafbc2f7bbe13e
|
refs/heads/master
| 2021-01-22T20:35:25.615786
| 2015-07-31T22:56:23
| 2015-07-31T22:56:23
| 40,027,995
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,008
|
cpp
|
ghost.cpp
|
#include <SFML/Graphics.hpp>
#include "ghost.h"
Ghost::Ghost(char which, double x, double y, sf::Sprite spr){
dotCounter = 0;
name = which;
sprite = spr;
speed = 0.019;
setMode('h');
if (name == 'b'){
sprite.setTextureRect(sf::IntRect(228, 64, 16, 16));
}
else if (name == 'p'){
sprite.setTextureRect(sf::IntRect(228, 80, 16, 16));
}
else if (name == 'i'){
sprite.setTextureRect(sf::IntRect(228, 96, 16, 16));
}
else if (name == 'c'){
sprite.setTextureRect(sf::IntRect(228, 112, 16, 16));
}
sprite.setOrigin(8, 8);
sprite.setPosition(x, y);
currentTile = 0;
}
Ghost::Ghost(){
}
void Ghost::setGhost(char which, double x, double y, sf::Sprite spr){
name = which;
sprite = spr;
speed = 0.019;
mode = 'c';
sprite.setTextureRect(sf::IntRect(228, 64, 16, 16));
sprite.setOrigin(8, 8);
sprite.setPosition(x, y);
}
void Ghost::setMode(char newMode){
if (mode != newMode){
mode = newMode;
if (mode == 'f'){
sprite.setTextureRect(sf::IntRect(356, 64, 16, 16));
fright = 20000;
speed = 0.015;
}
if (mode == 'h'){
dotCounter = 0;
if (name == 'b'){
sprite.setTextureRect(sf::IntRect(228, 64, 16, 16));
}
else if (name == 'p'){
sprite.setTextureRect(sf::IntRect(228, 80, 16, 16));
}
else if (name == 'i'){
sprite.setTextureRect(sf::IntRect(228, 96, 16, 16));
}
else if (name == 'c'){
sprite.setTextureRect(sf::IntRect(228, 112, 16, 16));
}
}
reverse();
}
}
char Ghost::getMode(){
return mode;
}
void Ghost::move(char face){
facing = face;
}
void Ghost::reverse(){
if (facing == 'l'){
facing = 'r';
}
if (facing == 'r'){
facing = 'l';
}
if (facing == 'u'){
facing = 'd';
}
if (facing == 'd'){
facing = 'u';
}
}
void Ghost::update(){
if (mode == 'h'){
if (name == 'b'){
sprite.setPosition(14 * 8, (14 * 8) + 4);
if (dotCounter >= 0){
sprite.setPosition(14 * 8, (14 * 8) + 4);
mode = 'c';
}
}
if (name == 'i'){
sprite.setPosition(12 * 8, 18 * 8);
if (dotCounter >= 17){
sprite.setPosition(14 * 8, (14 * 8) + 4);
mode = 'c';
}
}
if (name == 'p'){
sprite.setPosition(14 * 8, 18 * 8);
if (dotCounter >= 7){
sprite.setPosition(14 * 8, (14 * 8) + 4);
mode = 'c';
}
}
if (name == 'c'){
sprite.setPosition(16 * 8, 18 * 8);
if (dotCounter >= 32){
sprite.setPosition(14 * 8, (14 * 8) + 4);
mode = 'c';
}
}
}
else{
int xtile = sprite.getPosition().x / 8;
int ytile = sprite.getPosition().y / 8;
if (mode == 'f'){
fright--;
if (fright < 0){
mode = 'c';
speed = 0.019;
if (name == 'b'){
sprite.setTextureRect(sf::IntRect(228, 64, 16, 16));
}
else if (name == 'p'){
sprite.setTextureRect(sf::IntRect(228, 80, 16, 16));
}
else if (name == 'i'){
sprite.setTextureRect(sf::IntRect(228, 96, 16, 16));
}
else if (name == 'c'){
sprite.setTextureRect(sf::IntRect(228, 112, 16, 16));
}
}
}
switch (facing){
case 'u':
sprite.move(0, -speed);
sprite.setPosition((xtile * 8) + 4, sprite.getPosition().y);
break;
case 'l':
sprite.move(-speed, 0);
sprite.setPosition(sprite.getPosition().x, (ytile * 8) + 4);
break;
case 'd':
sprite.move(0, speed);
sprite.setPosition((xtile * 8) + 4, sprite.getPosition().y);
break;
case 'r':
sprite.move(speed, 0);
sprite.setPosition(sprite.getPosition().x, (ytile * 8) + 4);
break;
default:
break;
}
if (xtile == 27){
sprite.setPosition(8, sprite.getPosition().y);
}
else if (xtile == 0){
sprite.setPosition(215, sprite.getPosition().y);
}
}
}
int Ghost::getTileX(){
return (sprite.getPosition().x / 8);
}
int Ghost::getTileY(){
return (sprite.getPosition().y / 8);
}
void Ghost::setCurrentTile(int tile){
currentTile = tile;
}
int Ghost::getCurrentTile(){
return currentTile;
}
char Ghost::getFacing(){
return facing;
}
char Ghost::getName(){
return name;
}
void Ghost::add(){
dotCounter++;
}
sf::Sprite Ghost::getSprite(){
return sprite;
}
|
6b9cd265bbe49c2efd8372e3faed85d383421210
|
76511d5894d205bf6d1af8451036a0c4c4b3f053
|
/BarayugaRaphael_CSC5_42829/Ternary_1/main.cpp
|
f6eeb476b63d966fd695fc78c0ec4e7153eab22c
|
[] |
no_license
|
Rbarayuga/BarayugaRaphael_CSC5_42829
|
b1c3abeb75b34fbb2834ec892dfa2de5acad5a55
|
c9c26ba3ccfee9123bc3445f184cf835425559eb
|
refs/heads/master
| 2021-01-18T21:47:40.026143
| 2016-06-06T14:48:34
| 2016-06-06T14:48:34
| 52,335,888
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,301
|
cpp
|
main.cpp
|
/*
* File: main.cpp
* Author: Raphael M.B. Barayuga
* Purpose:Lab
* Created on March 14, 2016, 9:52 AM
*/
//System Libraries
#include <iostream>
using namespace std;
/*
//Global Constants
//User Libraries
*/
int main(int argc, char** argv) {
bool x=true;
bool y=true;
// ! = not
// && = and
// || = or
// ^= exclusively order
cout<<(x?'T':'F')<<(y?'T':'F')<<(!x?'T':'F')<<(!y?'T':'F')<<(x&&y?'T':'F')<<
(x||y?'T':'F')<<(x^y?'T':'F')<<(x^y^y?'T':'F')<<(x^y^x?'T':'F')<<
(!(x&&y)?'T':'F')<<(!x||!y?'T':'F')<<(!x&&!y?'T':'F')<<endl;
x=true;
y=false;
cout<<(x?'T':'F')<<(y?'T':'F')<<(!x?'T':'F')<<(!y?'T':'F')<<(x&&y?'T':'F')<<
(x||y?'T':'F')<<(x^y?'T':'F')<<(x^y^y?'T':'F')<<(x^y^x?'T':'F')<<
(!(x&&y)?'T':'F')<<(!x||!y?'T':'F')<<(!x&&!y?'T':'F')<<endl;
x=false;
y=true;
cout<<(x?'T':'F')<<(y?'T':'F')<<(!x?'T':'F')<<(!y?'T':'F')<<(x&&y?'T':'F')<<
(x||y?'T':'F')<<(x^y?'T':'F')<<(x^y^y?'T':'F')<<(x^y^x?'T':'F')<<
(!(x&&y)?'T':'F')<<(!x||!y?'T':'F')<<(!x&&!y?'T':'F')<<endl;
x=false;
y=false;
cout<<(x?'T':'F')<<(y?'T':'F')<<(!x?'T':'F')<<(!y?'T':'F')<<(x&&y?'T':'F')<<
(x||y?'T':'F')<<(x^y?'T':'F')<<(x^y^y?'T':'F')<<(x^y^x?'T':'F')<<
(!(x&&y)?'T':'F')<<(!x||!y?'T':'F')<<(!x&&!y?'T':'F')<<endl;
//Exit Stage Right
return 0;
}
|
3a248a0ee27f4a7994475fe1284f668c352e3b25
|
de8525032ab89b4f7d5e6ad8b4db396d02cff421
|
/cpp(还没清理)/P1276 校门外的树(增强版).cpp
|
e3271a183301cf279be22dafda7a1ef332414957
|
[] |
no_license
|
1753262762/CPP
|
a99c0a714f707dd9e87ebdb8f6242cef2d878d30
|
fa1505ac30027006114aa54e4b49226e035f7ca0
|
refs/heads/master
| 2020-06-04T21:10:56.605120
| 2019-06-16T13:53:37
| 2019-06-16T13:53:37
| 192,193,445
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 537
|
cpp
|
P1276 校门外的树(增强版).cpp
|
#include<bits/stdc++.h>
using namespace std;
int tree[10005],l,n,cnt,ans;
int main() {
cin>>l>>n;
memset(tree, 1, sizeof(tree));
while (n--) {
bool sf;
int c,d;
cin>>sf>>c>>d;
if (!sf) {
for (int i=c; i<=d; i++) {
if (tree[i] == 2) {
++cnt;
}
tree[i] = 0;
}
} else {
for (int i=c; i<=d; i++) {
if (!tree[i]) {
tree[i] = 2;
}
}
}
}
for (int i=0; i<=l; i++) {
if (tree[i]==2) {
ans++;
}
}
cout<<ans<<endl;
cout<<cnt<<endl;
return 0;
}
|
f292aba029f9dc9ac3f771636a9ddd70d644a4fc
|
0eff74b05b60098333ad66cf801bdd93becc9ea4
|
/second/download/httpd/gumtree/httpd_patch_hunk_1904.cpp
|
0e32cf18fc02651ea965bb0f1939010230e63093
|
[] |
no_license
|
niuxu18/logTracker-old
|
97543445ea7e414ed40bdc681239365d33418975
|
f2b060f13a0295387fe02187543db124916eb446
|
refs/heads/master
| 2021-09-13T21:39:37.686481
| 2017-12-11T03:36:34
| 2017-12-11T03:36:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,269
|
cpp
|
httpd_patch_hunk_1904.cpp
|
return NULL;
}
static const char *set_max_clients (cmd_parms *cmd, void *dummy,
const char *arg)
{
- int max_clients;
const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
if (err != NULL) {
return err;
}
- /* It is ok to use ap_threads_per_child here because we are
- * sure that it gets set before MaxClients in the pre_config stage. */
max_clients = atoi(arg);
- if (max_clients < ap_threads_per_child) {
- ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
- "WARNING: MaxClients (%d) must be at least as large",
- max_clients);
- ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
- " as ThreadsPerChild (%d). Automatically",
- ap_threads_per_child);
- ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
- " increasing MaxClients to %d.",
- ap_threads_per_child);
- max_clients = ap_threads_per_child;
- }
- ap_daemons_limit = max_clients / ap_threads_per_child;
- if ((max_clients > 0) && (max_clients % ap_threads_per_child)) {
- ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
- "WARNING: MaxClients (%d) is not an integer multiple",
- max_clients);
- ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
- " of ThreadsPerChild (%d), lowering MaxClients to %d",
- ap_threads_per_child,
- ap_daemons_limit * ap_threads_per_child);
- ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
- " for a maximum of %d child processes,",
- ap_daemons_limit);
- max_clients = ap_daemons_limit * ap_threads_per_child;
- }
- if (ap_daemons_limit > server_limit) {
- ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
- "WARNING: MaxClients of %d would require %d servers,",
- max_clients, ap_daemons_limit);
- ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
- " and would exceed the ServerLimit value of %d.",
- server_limit);
- ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
- " Automatically lowering MaxClients to %d. To increase,",
- server_limit * ap_threads_per_child);
- ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
- " please see the ServerLimit directive.");
- ap_daemons_limit = server_limit;
- }
- else if (ap_daemons_limit < 1) {
- ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
- "WARNING: Require MaxClients > 0, setting to 1");
- ap_daemons_limit = 1;
- }
return NULL;
}
static const char *set_threads_per_child (cmd_parms *cmd, void *dummy,
const char *arg)
{
const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
if (err != NULL) {
return err;
}
- ap_threads_per_child = atoi(arg);
- if (ap_threads_per_child > thread_limit) {
- ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
- "WARNING: ThreadsPerChild of %d exceeds ThreadLimit "
- "value of %d", ap_threads_per_child,
- thread_limit);
- ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
- "threads, lowering ThreadsPerChild to %d. To increase, please"
- " see the", thread_limit);
- ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
- " ThreadLimit directive.");
- ap_threads_per_child = thread_limit;
- }
- else if (ap_threads_per_child < 1) {
- ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
- "WARNING: Require ThreadsPerChild > 0, setting to 1");
- ap_threads_per_child = 1;
- }
+ threads_per_child = atoi(arg);
return NULL;
}
static const char *set_server_limit (cmd_parms *cmd, void *dummy, const char *arg)
{
- int tmp_server_limit;
-
const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
if (err != NULL) {
return err;
}
- tmp_server_limit = atoi(arg);
- /* you cannot change ServerLimit across a restart; ignore
- * any such attempts
- */
- if (first_server_limit &&
- tmp_server_limit != server_limit) {
- /* how do we log a message? the error log is a bit bucket at this
- * point; we'll just have to set a flag so that ap_mpm_run()
- * logs a warning later
- */
- changed_limit_at_restart = 1;
- return NULL;
- }
- server_limit = tmp_server_limit;
-
- if (server_limit > MAX_SERVER_LIMIT) {
- ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
- "WARNING: ServerLimit of %d exceeds compile time limit "
- "of %d servers,", server_limit, MAX_SERVER_LIMIT);
- ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
- " lowering ServerLimit to %d.", MAX_SERVER_LIMIT);
- server_limit = MAX_SERVER_LIMIT;
- }
- else if (server_limit < 1) {
- ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
- "WARNING: Require ServerLimit > 0, setting to 1");
- server_limit = 1;
- }
+ server_limit = atoi(arg);
return NULL;
}
static const char *set_thread_limit (cmd_parms *cmd, void *dummy, const char *arg)
{
- int tmp_thread_limit;
-
const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
if (err != NULL) {
return err;
}
- tmp_thread_limit = atoi(arg);
- /* you cannot change ThreadLimit across a restart; ignore
- * any such attempts
- */
- if (first_thread_limit &&
- tmp_thread_limit != thread_limit) {
- /* how do we log a message? the error log is a bit bucket at this
- * point; we'll just have to set a flag so that ap_mpm_run()
- * logs a warning later
- */
- changed_limit_at_restart = 1;
- return NULL;
- }
- thread_limit = tmp_thread_limit;
-
- if (thread_limit > MAX_THREAD_LIMIT) {
- ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
- "WARNING: ThreadLimit of %d exceeds compile time limit "
- "of %d servers,", thread_limit, MAX_THREAD_LIMIT);
- ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
- " lowering ThreadLimit to %d.", MAX_THREAD_LIMIT);
- thread_limit = MAX_THREAD_LIMIT;
- }
- else if (thread_limit < 1) {
- ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
- "WARNING: Require ThreadLimit > 0, setting to 1");
- thread_limit = 1;
- }
+ thread_limit = atoi(arg);
return NULL;
}
static const command_rec worker_cmds[] = {
-UNIX_DAEMON_COMMANDS,
LISTEN_COMMANDS,
AP_INIT_TAKE1("StartServers", set_daemons_to_start, NULL, RSRC_CONF,
"Number of child processes launched at server startup"),
AP_INIT_TAKE1("MinSpareThreads", set_min_spare_threads, NULL, RSRC_CONF,
"Minimum number of idle threads, to handle request spikes"),
AP_INIT_TAKE1("MaxSpareThreads", set_max_spare_threads, NULL, RSRC_CONF,
|
3cea18ddd90b0ced018a6f8663b7d91bd3c3fc39
|
37ac89cff929d932c732066d7333b3597a11b86e
|
/Classes/MoriorGames/Vendor/Config/StaticBushConfig.cpp
|
8822916902220a7f5579eb51a206b1b9ec5a9d8e
|
[] |
no_license
|
moriorgames/bfai
|
bb6b81cd398559c98feb642fba0aad8025273535
|
ad7737285cc4b15d3ce9aa2b31afc196476b8163
|
refs/heads/master
| 2018-10-22T19:10:21.392915
| 2018-07-30T16:54:26
| 2018-07-30T16:54:26
| 120,993,649
| 2
| 0
| null | 2018-05-24T04:54:14
| 2018-02-10T07:11:47
|
C++
|
UTF-8
|
C++
| false
| false
| 306
|
cpp
|
StaticBushConfig.cpp
|
#include "StaticBushConfig.h"
std::vector<std::pair<short, short>> StaticBushConfig::get()
{
return {
{8, 3}, {-8, 3}, {8, -3}, {-8, -3},
{-4, 3}, {-3, 3}, {-2, 3}, {-1, 3}, {0, 3}, {1, 3}, {2, 3},
{4, -3}, {3, -3}, {2, -3}, {1, -3}, {0, -3}, {-1, -3}, {-2, -3},
};
}
|
c2c5255fe70f8a9d6a9c32f49333c20446439c97
|
0978677c499f42452ae8a4b9bfc959a20bd12083
|
/leetcode/l00101.cpp
|
fb3f77fbfcd839478dc9e9b109d192d319941ec7
|
[] |
no_license
|
ZeroNerodaHero/exercise
|
7ee9ae1f20d83dd1cedcaf6355bbb9702fc9086b
|
d1a49ecbcd1de4976a700053329c76359383a10d
|
refs/heads/main
| 2023-07-09T16:29:04.045827
| 2021-08-15T21:10:48
| 2021-08-15T21:10:48
| 363,310,234
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 890
|
cpp
|
l00101.cpp
|
class Solution {
public:
bool dfs(string& s, int n, string& p, int m){
if(dp[n][m] >= 0){
return dp[n][m];
}
bool ret = 0;
if(p[m-1] == '*'){
ret = dfs(s,n,p,m-2);
if(!ret && (p[m-2] == s[n-1] || p[m-2] == '.')){
ret = dfs(s,n-1,p,m);
}
} else{
if(p[m-1] == s[n-1] || p[m-1] == '.')
ret = dfs(s, n-1, p, m-1);
}
dp[n][m] = ret;
return ret;
}
bool isMatch(string s, string p) {
int ns = s.size(), np = p.size();
memset(dp,-1,sizeof(dp)); dp[0][0] = 1;
for(int i = 1; i <= ns; i++) dp[i][0] = 0;
for(int i = 1; i <= np; i++){
if(p[i-1] == '*') dp[0][i] = dp[0][i-2];
else dp[0][i] = 0;
}
return dfs(s,ns,p,np);
}
int dp[32][32];
};
|
1fbefbfd8ec479cff0697f4dcde0c7d4520859f8
|
fd76642e994966799473b4cd36694312b103f369
|
/Customer_service/test_banking.cpp
|
5bb20377855a95288e6502b1ad68e2c052358ee5
|
[] |
no_license
|
alexshvedov1997/Customer_service
|
24b431306af0b56974ead420cbba68df2e204e55
|
f52b7dd505f22da3312801339ee023798bbc2e04
|
refs/heads/master
| 2021-05-23T13:49:02.775345
| 2020-04-05T20:00:23
| 2020-04-05T20:00:23
| 253,320,562
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,637
|
cpp
|
test_banking.cpp
|
#include<iostream>
#include<cstdlib>
#include<ctime>
#include"queue.h"
const int MIN_PER_HR = 60;
bool newcustomer(double x);
using namespace std;
int main(){
srand(time(0));
cout<<"Case study: banking autamstic"<<endl;
cout<<"Enter the number";
int qs;
cin>>qs;
Queue line(qs);
cout<<"Enter the number of simulation"<<endl;
int hours;
cin>>hours;
long cycletime = MIN_PER_HR*hours;
cout<<"Enter the average number of customers per hours"<<endl;
double perhours;
cin>>perhours;
double min_per_cust;
min_per_cust = MIN_PER_HR/perhours;
Item temp;
long turnaways = 0;
long customers = 0;
long served = 0;
long sum_line = 0;
int wait_time = 0;
long line_wait = 0;
for(int cycle = 0; cycle < cycletime; cycle++){
if(newcustomer(min_per_cust)){
if(line.isfull()){
turnaways++;
}
else{
customers++;
temp.set(cycle);
line.enqueue(temp);
}
}
if (wait_time <= 0 && !line.isempty()){
line.dequeue(temp);
wait_time = temp.ptime();
line_wait += cycle-temp.when();
served++;
}
if(wait_time>0)
wait_time--;
sum_line += line.queuecount();
}
if(customers > 0){
cout<<"customers accept " << customers<< endl;
cout << " customers served " <<served<<endl;
cout<<"turnawways: " << turnaways<< endl;
cout<<"average queue size: "<<endl;
cout.precision(2);
cout.setf(ios_base::fixed, ios_base::floatfield);
cout<<(double) sum_line/cycletime<<endl;
cout<<"average wait time: "<<(double) line_wait / served<<"minutes"<<endl;
}
else
cout<<" No customers"<<endl;
cout<<"Done!"<<endl;
return 0;
}
bool newcustomer(double x){
return (rand()*x / RAND_MAX <1);
}
|
61bb7aeb3439e4aafac56e1f03f0d1ad24abfe0c
|
1444f2455c568216550cad3ec0ff63e61c43225e
|
/belt_task/include/task_robot.h
|
b53dc0e303a361924c98f565164c4070afb86c03
|
[] |
no_license
|
RobotEmperor/SDU-Control-Task-ROS
|
7b7ebe6a81310a44105ee2811ce8193a9aeccebd
|
13d34669f9a6a692abb98b1b227c1fcd6a716296
|
refs/heads/master
| 2023-08-16T11:40:20.234383
| 2021-01-21T12:30:12
| 2021-01-21T12:30:12
| 291,659,443
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,873
|
h
|
task_robot.h
|
/*
* task_robot.h
*
* Created on: Aug 19, 2020
* Author: yik
*/
#ifndef SDU_CONTROL_TASK_ROS_BELT_TASK_INCLUDE_TASK_ROBOT_H_
#define SDU_CONTROL_TASK_ROS_BELT_TASK_INCLUDE_TASK_ROBOT_H_
//#define WC_FILE "/home/yik/sdu_ws/SDU-Control-Tasks/belt_task/config/wc/UR10e_2018/UR10e.xml"
#include <Eigen/Dense>
#include "log.h"
//ur_rtde library
#include <ur_rtde/rtde_receive_interface.h>
#include <ur_rtde/rtde_control_interface.h>
//rw_robwork
#include <rw/invkin/ClosedFormIKSolverUR.hpp>
#include <rw/invkin/JacobianIKSolver.hpp>
#include <rw/kinematics.hpp>
#include <rw/loaders/WorkCellLoader.hpp>
#include <rw/math.hpp>
#include <rw/models/SerialDevice.hpp>
#include <rw/models/WorkCell.hpp>
#include <rw/pathplanning/PlannerConstraint.hpp>
#include <rw/pathplanning/QSampler.hpp>
#include <rw/proximity/CollisionDetector.hpp>
#include <rwlibs/proximitystrategies/ProximityStrategyFactory.hpp>
#include "tool_estimation.h"
#include "sdu_math/end_point_to_rad_cal.h"
#include "sdu_math/control_function.h"
#include "sdu_math/statistics_math.h"
#include "task_motion.h"
#include "data_logging.h"
#include <unistd.h>
using namespace ur_rtde;
using namespace rw::models;
using rw::invkin::ClosedFormIKSolverUR;
using rw::kinematics::State;
using rw::loaders::WorkCellLoader;
class TaskRobot
{
public:
TaskRobot();
TaskRobot(std::string robot_name, std::string init_path);
~TaskRobot();
void parse_init_data_(const std::string &path);
void initialize(std::string robot_ip, bool gazebo_check);
void init_model(std::string wc_file, std::string robot_model);
void move_to_init_pose();
void estimation_of_belt_position(double radious);
bool tasks(std::string command);
bool hybrid_controller();
void terminate_robot();
void terminate_data_log();
void set_force_controller_x_gain(double kp,double ki,double kd);
void set_force_controller_y_gain(double kp,double ki,double kd);
void set_force_controller_z_gain(double kp,double ki,double kd);
void set_force_controller_eaa_x_gain(double kp,double ki,double kd);
void set_force_controller_eaa_y_gain(double kp,double ki,double kd);
void set_force_controller_eaa_z_gain(double kp,double ki,double kd);
void set_position_controller_x_gain(double kp,double ki,double kd);
void set_position_controller_y_gain(double kp,double ki,double kd);
void set_position_controller_z_gain(double kp,double ki,double kd);
void set_position_controller_eaa_x_gain(double kp,double ki,double kd);
void set_position_controller_eaa_y_gain(double kp,double ki,double kd);
void set_position_controller_eaa_z_gain(double kp,double ki,double kd);
void set_robust_value(double robust_value);
void set_belt_change_values(double x, double y, double z);
void set_tf_static_robot(rw::math::Transform3D<> tf_base_to_staric_robot, rw::math::Transform3D<> tf_base_to_bearing_staric_robot);
std::vector<double> get_raw_ft_data_();
std::vector<double> get_contacted_ft_data_();
std::vector<double> get_error_ee_pose_();
std::vector<double> get_actual_tcp_speed_();
std::vector<double> get_current_q_();
rw::math::Transform3D<> get_tf_current_();
rw::math::Transform3D<> get_tf_base_to_bearing_();
bool get_finish_task();
private:
struct PIDControllerGain
{
double x_kp;
double x_ki;
double x_kd;
double y_kp;
double y_ki;
double y_kd;
double z_kp;
double z_ki;
double z_kd;
double eaa_x_kp;
double eaa_x_ki;
double eaa_x_kd;
double eaa_y_kp;
double eaa_y_ki;
double eaa_y_kd;
double eaa_z_kp;
double eaa_z_ki;
double eaa_z_kd;
};
PIDControllerGain force_controller_gain_;
PIDControllerGain position_controller_gain_;
State state_;
std::string robot_name_;
//robot interface
std::shared_ptr<RTDEReceiveInterface> rtde_receive_;
std::shared_ptr<RTDEControlInterface> rtde_control_;
//traj and task motion
std::shared_ptr<EndEffectorTraj> robot_fifth_traj_;
std::shared_ptr<TaskMotion> robot_task_;
//tool estimation
std::shared_ptr<ToolEstimation> tool_estimation_;
//cusum_method
std::shared_ptr<StatisticsMath> statistics_math_;
//pid controller
std::shared_ptr<PID_function> force_x_compensator_;
std::shared_ptr<PID_function> force_y_compensator_;
std::shared_ptr<PID_function> force_z_compensator_;
std::shared_ptr<PID_function> position_x_controller_;
std::shared_ptr<PID_function> position_y_controller_;
std::shared_ptr<PID_function> position_z_controller_;
//data logging
std::shared_ptr<DataLogging> data_log_;
//robot states
std::vector<double> joint_positions_; //(6);
std::vector<double> actual_tcp_pose_; //(6);
std::vector<double> actual_tcp_speed_; //(6);
std::vector<double> target_tcp_pose_; //(6);
std::vector<double> acutal_tcp_acc_; //(3);
std::vector<double> raw_ft_data_; //(6);
std::vector<double> filtered_tcp_ft_data_; //(6);
std::vector<double> contacted_ft_data_; //(6);
std::vector<double> contacted_ft_no_offset_data_; //(6);
std::vector<double> current_q_; //(6);
std::vector<double> pid_compensation_; //(6);
//control states
std::vector<double> set_point_vector_; //(6);
std::vector<double> desired_pose_vector_; //(6);
std::vector<double> desired_force_torque_vector_; //(6);
std::vector<double> compensated_pose_vector_; //(6);
std::vector<double> error_ee_pose_; //(6);
std::vector<double> compensated_q_; //(6);
//controller gains
std::vector<double> force_controller_; //(6);
std::vector<double> position_controller_; //(6);
std::vector<double> data_current_belt_;
std::vector<double> data_desired_belt_;
std::vector<double> data_bearing_tcp_belt_;
//task motion
std::string previous_task_command_;
//tf
rw::math::Transform3D<> tf_tcp_desired_pose_;
rw::math::Transform3D<> tf_modified_pose_;
rw::math::Transform3D<> tf_current_;
rw::math::Transform3D<> tf_desired_;
rw::math::Transform3D<> tf_base_to_bearing_;
rw::math::Wrench6D<> current_ft_;
rw::math::Wrench6D<> current_ft_no_offset_;
rw::math::Wrench6D<> tf_tcp_current_force_;
rw::math::Transform3D<> tf_base_to_static_robot_;
rw::math::Transform3D<> tf_base_to_bearing_static_robot_;
//control
double control_time_;
double time_count_;
double tool_mass_;
double belt_robust_value_;
double change_x_, change_y_, change_z_;
double current_belt_x_, current_belt_y_, current_belt_z_;
double desired_belt_x_, desired_belt_y_, desired_belt_z_;
bool contact_check_;
bool control_check_;
bool previous_phase_;
//solution check
int preferred_solution_number_;
bool joint_vel_limits_;
std::vector<rw::math::Q> solutions_;
//model identification
std::string wc_file_;
WorkCell::Ptr wc_;
SerialDevice::Ptr device_;
std::shared_ptr<ClosedFormIKSolverUR> solver_;
// gazebo
bool gazebo_check_;
//
bool flag;
bool finish_task_;
rw::math::Transform3D<> tf_bearing_to_static_robot;
rw::math::Transform3D<> tf_bearing_to_rubber_point;
rw::math::Transform3D<> tf_bearing_to_moveable_robot_start;
rw::math::Transform3D<> tf_bearing_to_moveable_robot;
rw::math::Transform3D<> tf_bearing_to_error;
rw::math::Transform3D<> distance_tf_static_robot_to_moveable_robot;
rw::math::Transform3D<> distance_tf_static_robot_to_moveable_robot_start;
rw::math::Transform3D<> tf_static_robot_to_bearing;
rw::math::Transform3D<> tf_static_robot_to_rubber_point;
rw::math::Transform3D<> tf_moveable_robot_to_bearing;
rw::math::Transform3D<> tf_moveable_robot_to_init_belt_;
rw::math::Transform3D<> tf_moveable_robot_to_error;
rw::math::Transform3D<> temp;
rw::math::Vector3D<> init_current_belt_;
rw::math::Vector3D<> current_belt_;
rw::math::Vector3D<> desired_belt_;
rw::math::Vector3D<> error_;
rw::math::Transform3D<> tf_bearing_current_belt_;
rw::math::Transform3D<> tf_bearing_desired_belt_;
rw::math::Transform3D<> tf_tcp_current_belt_;
rw::math::Transform3D<> tf_tcp_desired_belt_;
};
#endif /* SDU_CONTROL_TASKS_BELT_TASK_INCLUDE_TASK_ROBOT_H_ */
|
2f19496abac854ff41fb9b56b4e46b9ec9686963
|
4ad88bb75796c61c5096f59261df01484a505e2a
|
/data.cpp
|
9f5a7460407c92158f5f83657c678d3460f71e28
|
[] |
no_license
|
xingchen1968/dailyemail
|
90b67f698f212404cf358aaacb7d63a287a7e107
|
7d773d0e2ad99de19d917e298f3d1674ce348e8f
|
refs/heads/master
| 2023-04-10T21:15:36.229128
| 2020-08-04T15:22:21
| 2020-08-04T15:22:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,869
|
cpp
|
data.cpp
|
#include <bits/stdc++.h>
using namespace std;
map<string, set<string>> pre, cur;
#define old_file "old.md"
#define new_file "new.md"
#define result_file "result.html"
string getname(string str)
{
stringstream ss;
string title, name;
ss << str;
ss >> title >> name;
return name;
}
void parser(char *path, map<string, set<string>> &cur)
{
ifstream in(path);
string str, name;
while (getline(in, str))
{
//cout << str << endl;
if (!str.length())
continue;
else if (str[0] == '#')
name = getname(str);
else
cur[name].insert(str);
};
in.close();
}
struct html
{
string head, tail;
vector<pair<string, string>> data1, data2, data3;
void setcols(string s1, string s2)
{
head = "<html><body><table border=\"1\" align=\"center\"><tr><th>" + s1 + "</th><th>" + s2 + "</th></tr>";
tail = "</table></body></html>";
}
void print(char *path)
{
ofstream out(path);
setcols("大学", "新增信息");
out << head << endl;
for (auto item : data1)
out << "<tr><th>" << item.first << "</th><th>" << item.second << "</th></tr>" << endl;
out << tail << endl;
setcols("大学", "移去信息");
out << head << endl;
for (auto item : data2)
out << "<tr><th>" << item.first << "</th><th>" << item.second << "</th></tr>" << endl;
out << tail << endl;
setcols("大学", "目前信息");
out << head << endl;
for (auto item : data3)
out << "<tr><th>" << item.first << "</th><th>" << item.second << "</th></tr>" << endl;
out << tail << endl;
}
};
void diff_result(char *path)
{
html result;
for (auto item : pre)
{
if (cur.count(item.first))
{
for (auto info : item.second)
{
if (cur[item.first].find(info) == cur[item.first].end())
result.data2.push_back({item.first, info});
}
}
else
{
for (auto info : item.second)
result.data2.push_back({item.first, info});
}
}
for (auto item : cur)
{
if (pre.count(item.first))
{
for (auto info : item.second)
{
if (pre[item.first].find(info) == pre[item.first].end())
result.data1.push_back({item.first, info});
}
}
else
{
for (auto info : item.second)
result.data1.push_back({item.first, info});
}
for (auto info : item.second)
result.data3.push_back({item.first, info});
}
result.print(path);
}
int main()
{
parser(new_file, cur);
parser(old_file, pre);
diff_result(result_file);
return 0;
}
|
4c84ca0f6cffc8d8a4431ad7f994c54ef151d970
|
b93d253b0fd1229597518cbfa62f0900b5689b24
|
/test/ev/node_potential_test.cpp
|
3e3bdebf712a55468582cd5dab8f643d669bfb8f
|
[
"BSD-2-Clause"
] |
permissive
|
praveenmunagapati/charge
|
3e95e58e13dc16d998cf59bd7b58fcf7cd86ef1c
|
85e35f7a6c8b8c161ecd851124d1363d5a450573
|
refs/heads/master
| 2020-04-13T16:39:17.330291
| 2017-12-26T14:51:24
| 2017-12-26T14:51:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,510
|
cpp
|
node_potential_test.cpp
|
#include "ev/node_potentials.hpp"
#include "ev/graph_transform.hpp"
#include "common/graph_transform.hpp"
#include <catch.hpp>
using namespace charge;
using namespace charge::ev;
TEST_CASE("Check omega potential", "[omega potential]")
{
// Path from 0 to 3 is the fastest but not
// if you include the charging station at (5)
// and battery constrains.
//
// 0->3 : duration >= 8, consumption >= (200 + 200 - 350)
//
// 0 -> 1 -> 2 -> 3
// | |
// 4------(5)-----6
//
ev::TradeoffGraph graph(7, std::vector<ev::TradeoffGraph::edge_t> {
{0, 1, ev::make_constant(3, 200)},
{0, 4, ev::make_constant(6, 100)},
{1, 2, {3, 7, common::HyperbolicFunction {2500, 2, 100}}},
{2, 3, {2, 3, common::HyperbolicFunction {1000, 1, -600}}},
{4, 5, ev::make_constant(6, 100)},
{5, 6, ev::make_constant(6, 100)},
{6, 3, ev::make_constant(6, 100)}
});
const auto capacity = 300;
const auto min_charging_rate = -100;
auto reverse_duration_graph = common::invert(ev::tradeoff_to_min_duration(graph));
auto reverse_consumption_graph = common::invert(ev::tradeoff_to_min_consumption(graph));
auto reverse_omega_graph = common::invert(ev::tradeoff_to_omega_graph(graph, min_charging_rate));
OmegaNodePotentials potential {capacity, min_charging_rate, reverse_duration_graph, reverse_consumption_graph, reverse_omega_graph};
common::MinIDQueue queue(graph.num_nodes());
potential.recompute(queue, 3);
ev::PiecewieseTradeoffFunction path_01 {{
graph.weight(graph.edge(0, 1))
}};
ev::PiecewieseTradeoffFunction path_12 {{
{10, 10, common::HyperbolicFunction {2500, 5, 300}}
}};
ev::PiecewieseTradeoffFunction path_04 {{
graph.weight(graph.edge(0, 4))
}};
ev::PiecewieseTradeoffFunction path_45 {{
ev::make_constant(12, 200)
}};
ev::PiecewieseTradeoffFunction path_56 {{
ev::make_constant(18, 300)
}};
ev::PiecewieseTradeoffFunction path_63 {{
ev::make_constant(24, 400)
}};
// Simulate dijkstra query from 0 to 3
CHECK(potential.key(0, 0, ev::make_constant(0, 0)) == 8000);
CHECK(potential.key(1, 3000, path_01) == 8000);
CHECK(potential.key(4, 6000, path_04) == 25000);
CHECK(potential.key(5, 12000, path_45) == 25000);
CHECK(potential.key(6, 18000, path_56) == 25000);
CHECK(potential.key(3, 24000, path_63) == 25000);
}
|
08312ee387b169faa9e80d84c75f219191504f0c
|
65ecf082f5580d7ccf9aa0be5cd8cb1541083bb1
|
/Listas-master/Lista 4/questão 20.cpp
|
e0bfc7e03ae0dedcbda82ae86572d193b9bcb890
|
[] |
no_license
|
weslleydcs/C
|
59d20035dcb50bd9f47ba6b871e4c8f465b40310
|
663cca56e1aaa603dc932752e4f64266d5cb605d
|
refs/heads/master
| 2021-01-11T12:06:35.343490
| 2019-02-11T07:42:28
| 2019-02-11T07:42:28
| 76,559,114
| 3
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 178
|
cpp
|
questão 20.cpp
|
#include <stdio.h>
int main()
{
char str[255];
printf("Digite uma String[Maximo de 255 caracteres]:\n");
gets(str);
printf("\n\nVoce digitou: \n%s", str);
return 0;
}
|
d2de2526f0d5fbce64cf15ced3e729925601ecdf
|
1ae40287c5705f341886bbb5cc9e9e9cfba073f7
|
/Osmium/SDK/FN_Feedback_classes.hpp
|
e830dcec8aeceee5c9ec83297576862bb86ddb7d
|
[] |
no_license
|
NeoniteDev/Osmium
|
183094adee1e8fdb0d6cbf86be8f98c3e18ce7c0
|
aec854e60beca3c6804f18f21b6a0a0549e8fbf6
|
refs/heads/master
| 2023-07-05T16:40:30.662392
| 2023-06-28T23:17:42
| 2023-06-28T23:17:42
| 340,056,499
| 14
| 8
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 16,105
|
hpp
|
FN_Feedback_classes.hpp
|
#pragma once
// Fortnite (4.5-CL-4159770) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// WidgetBlueprintGeneratedClass Feedback.Feedback_C
// 0x00F8 (0x04C0 - 0x03C8)
class UFeedback_C : public UFortGameFeedbackBase
{
public:
struct FPointerToUberGraphFrame UberGraphFrame; // 0x03C8(0x0008) (Transient, DuplicateTransient)
class UIconTextButton_C* BugButton; // 0x03D0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UIconTextButton_C* CancelButton; // 0x03D8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UIconTextButton_C* CommentButton; // 0x03E0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UCommonTextBlock* CommonTextBlock_1; // 0x03E8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UWidgetSwitcher* EntryProgressSwitcher; // 0x03F0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UVerticalBox* EntryVbox; // 0x03F8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UHorizontalBox* HB_AutofillPlayerNameContainer; // 0x0400(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UImage* Image_1; // 0x0408(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UVerticalBox* InteractableVBox; // 0x0410(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class ULightbox_C* Lightbox; // 0x0418(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UImage* MainIcon; // 0x0420(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UIconTextButton_C* PlayerButton; // 0x0428(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UIconTextButton_C* PopulateName_Killer_Button; // 0x0430(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UIconTextButton_C* PopulateName_Spectator_Button; // 0x0438(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class USizeBox* ProgressSizeBox; // 0x0440(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UVerticalBox* ProgressVBox; // 0x0448(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UBorder* RootBorder; // 0x0450(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UOverlay* RootOverlay; // 0x0458(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UIconTextButton_C* SendButton; // 0x0460(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UCommonTextBlock* Title; // 0x0468(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UCommonBorder* TouchToCloseZone; // 0x0470(0x0008) (ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
struct FText NewVar_1; // 0x0478(0x0018) (Edit, BlueprintVisible, DisableEditOnInstance)
struct FText KillersName; // 0x0490(0x0018) (Edit, BlueprintVisible, DisableEditOnInstance)
struct FText SpectatingName; // 0x04A8(0x0018) (Edit, BlueprintVisible, DisableEditOnInstance)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("WidgetBlueprintGeneratedClass Feedback.Feedback_C");
return ptr;
}
struct FEventReply TouchToClose(const struct FGeometry& MyGeometry, const struct FPointerEvent& MouseEvent);
void SetupAutoFillPlayerFields(const struct FText& KillersName, const struct FText& SpectatingName);
void Setup_For_Reporting_Player(const struct FText& PlayerName);
void InitializeFeedback();
bool IsAllTextNotEmpty();
void AddButtonFeedbackTypes();
void BindDelegates();
void OnBeginIntro();
void BndEvt__CancelButton_K2Node_ComponentBoundEvent_0_CommonButtonClicked__DelegateSignature(class UCommonButton* Button);
void BndEvt__SendButton_K2Node_ComponentBoundEvent_1_CommonButtonClicked__DelegateSignature(class UCommonButton* Button);
void HandleTextChanged(const struct FText& Text);
void OnActivated();
void ForceSelect_PopulateName_Killer_Button();
void ForceSelect_PopulateName_Spectator_Button();
void BndEvt__PopulateName_Spectator_Button_K2Node_ComponentBoundEvent_629_CommonSelectedStateChanged__DelegateSignature(class UCommonButton* Button, bool Selected);
void BndEvt__PopulateName_Killer_Button_K2Node_ComponentBoundEvent_664_CommonSelectedStateChanged__DelegateSignature(class UCommonButton* Button, bool Selected);
void OnInitiateDebugInfoForFeedbackComplete();
void Construct();
void ExecuteUbergraph_Feedback(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
8e1c32cd1ab7014ed6018dd786257bc5ce156f27
|
f3637e1f4cdc2757ad0097a63d2643dd1acf9f66
|
/src/GetData.cpp
|
4b0e82f4012c434f782739f24f5d2ae970c43958
|
[] |
no_license
|
zj611/ekf
|
df6f6be41191961c442457a2798f536732d1ae69
|
8cd0b2b1ca61f1fbb1205731f02383bb6005f8a3
|
refs/heads/master
| 2021-01-07T00:34:04.141810
| 2020-02-19T08:21:00
| 2020-02-19T08:21:00
| 241,527,377
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,096
|
cpp
|
GetData.cpp
|
//
// Created by Zhangjun on 2020/2/19.
//
#include <fstream>
#include "GetData.h"
void GetData(std::string input_file_name,
std::vector<MeasurementPackage> &measurement_pack_list,
std::vector<GroundTruthPackage> &groundtruth_pack_list){
// 打开数据,若失败则输出失败信息,返回并终止程序
// Open file. if failed return -1 & end program
std::ifstream input_file(input_file_name.c_str(), std::ifstream::in);
if (!input_file.is_open()) {
std::cout << "Failed to open file named : " << input_file_name << std::endl;
return;
}
// measurement_pack_list:毫米波雷达/激光雷达实际测得的数据。
// groundtruth_pack_list:每次测量时,障碍物位置的真值。
// 通过while循环将雷达测量值和真值全部读入内存,存入measurement_pack_list和groundtruth_pack_list中
std::string line;
while (getline(input_file, line)) {
std::string sensor_type;
MeasurementPackage meas_package;
GroundTruthPackage gt_package;
std::istringstream iss(line);
long long int timestamp;
// 读取当前行的第一个元素,L代表Lidar数据,R代表Radar数据
iss >> sensor_type;
if (sensor_type.compare("L") == 0) {
// 该行第二个元素为测量值x,第三个元素为测量值y,第四个元素为时间戳(纳秒)
meas_package.sensor_type_ = MeasurementPackage::LASER;
meas_package.raw_measurements_ = Eigen::VectorXd(2);
float x;
float y;
iss >> x;
iss >> y;
meas_package.raw_measurements_ << x, y;
iss >> timestamp;
meas_package.timestamp_ = timestamp;
measurement_pack_list.push_back(meas_package);
} else if (sensor_type.compare("R") == 0) {
// 该行第二个元素为距离pho,第三个元素为角度phi,第四个元素为径向速度pho_dot,第五个元素为时间戳(纳秒)
meas_package.sensor_type_ = MeasurementPackage::RADAR;
meas_package.raw_measurements_ = Eigen::VectorXd(3);
float rho;
float phi;
float rho_dot;
iss >> rho;
iss >> phi;
iss >> rho_dot;
meas_package.raw_measurements_ << rho, phi, rho_dot;
iss >> timestamp;
meas_package.timestamp_ = timestamp;
measurement_pack_list.push_back(meas_package);
}
// 当前行的最后四个元素分别是x方向上的距离真值,y方向上的距离真值,x方向上的速度真值,y方向上的速度真值
float x_gt;
float y_gt;
float vx_gt;
float vy_gt;
iss >> x_gt;
iss >> y_gt;
iss >> vx_gt;
iss >> vy_gt;
gt_package.gt_values_ = Eigen::VectorXd(4);
gt_package.gt_values_ << x_gt, y_gt, vx_gt, vy_gt;
groundtruth_pack_list.push_back(gt_package);
}
std::cout << "Success to load data." << std::endl;
}
|
df41fa6a7107a8eddbea0c1ded8883de17dd8e50
|
3ad3d4bd48cac4b24d5425ba2edee320d00472ef
|
/Event/Event.h
|
182f25a91aaed1a0dec9c9dc9547509e1c4087d6
|
[] |
no_license
|
Valkea/Home-Brew-Tools
|
697b71838c5652d7b80b55e97b74fbbf2cb1c1b7
|
ec10a9f7270cb4163535f560fd57576a214f051f
|
refs/heads/master
| 2021-09-26T20:57:00.398188
| 2018-11-02T12:39:15
| 2018-11-02T12:39:15
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,770
|
h
|
Event.h
|
/*/////////////////////////////////////////////////////////////////////////////////////////////////
Auteur : Letremble Emmanuel
Date : 13.02.2011
Description : This class should provide a base event class.
///// Class list //////////////////////////////////////////////////////////////////////////////////
- Event [4] 4 bytes
///// ETA /////////////////////////////////////////////////////////////////////////////////////////
** Bugs - none ATM
***************************************************************************************************/
///////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef HEADER_EVENT
#define HEADER_EVENT
#include <iostream> // cout
#include "EventTypes.h" // EventType
#include <functional> // std::ref
namespace hbt /// [home brew tools]
{
//*************************************************************************************************/
///// Event ///////////////////////////////////////////////////////////////////////////////////////
/** This class is a base class for all derived "Event" classes.
Its purpose is to offer a common base to transfer event parameters into one unique container.\n
Thus a "ClockEvent" class and a "WeaponEvent" class would have the same "Event" base plus
special parameters relevant to their own state. This way a function, functor or method can
wait for an "Event" and receive any classes derived from it, or wait for a specific derivation.
Then informations related to the event (as timeScale, cpuCycles, etc. for a ClockEvent) can
be extracted and used or transfered at once as one parameter.
@ingroup event */
class Event
{
public:
//== EventTypes =====================================
static const EventType& DISPATCH;
static const EventType& REGISTER;
static const EventType& UNREGISTER;
//== Constructors ===================================
Event( const EventType& evtType );
///< A constructor
~Event();
///< A destructor
Event ( const Event& obj );
///< A copy constructor.
/// @param obj The Event instance to copy.
Event ( Event&& obj );
///< A move constructor.
/// @param obj The Event instance to move.
//== Public members =================================
const EventType& type; //[4] 4 bytes | 0 byte padding
};//--------------------------------------------------------->[4] 4 bytes
std::ostream& operator<<( std::ostream& os, const Event& evt);
///< Returns a formated text output with Event informations.
/// @param os The target stream. @param evt The Event that must display informations.
} // hbt end
#endif
|
245f697b9f3e2cfd0fd1febd5501cd3e1bd852c0
|
50ce6308a63c7210d7512147e730fff1b2ebc9ad
|
/ActivationFunctionsLib/src/activationfunction.h
|
81fe69b0fd58acd57eba2deaec94ff53047e6297
|
[] |
no_license
|
muyilangjun1/Convnet
|
cb18557f1c11aeda788d426e4a10a13cb9bb334b
|
71b06002033856671851bf631963c418482765bb
|
refs/heads/master
| 2020-03-26T11:21:23.711294
| 2018-08-09T14:15:51
| 2018-08-09T14:15:51
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,310
|
h
|
activationfunction.h
|
#ifndef _ACTIVATION_FUNCTIONS_H_
#define _ACTIVATION_FUNCTIONS_H_
#include <iostream>
#include <math.h>
#include <ExceptionHandler.h>
using namespace std;
using namespace exceptionh;
namespace activeF {
float ActivationF(float x, float alpha = 1.0, bool derivative = false, int AFindex = 1);
float sigmoidFunc(float x, bool derivative = false);
float tanhFunc(float x, bool derivative = false);
float cotFunc(float x, bool derivative = false);
float SoftsignFunc(float x, bool derivative = false);
float ISRUFunc(float alpha, float x, bool derivative = false);
float LeakyReLUFunc(float x, bool derivative = false);
float PReLUFunc(float alpha, float x, bool derivative = false);
float ELUFunc(float alpha, float x, bool derivative = false);
float ISRLUFunc(float alpha, float x, bool derivative = false);
float SoftPlusFunc(float x, bool derivative = false);
float BentIdentityFunc(float x, bool derivative = false);
float SiLUFunc(float x, float FuncResult, float DivFuncResult, bool derivative = false);
float SoftEXPFunc(float alpha, float x, bool derivative = false);
float SinusoidFunc(float x, bool derivative = false);
float ReLUFunc(float x, bool derivative = false);
float SincFunc(float x, bool derivative = false);
float GaussianFunc(float x, bool derivative = false);
}
#endif
|
1423816165139773aaa32bc626b53e2f5e8b73f1
|
0906dc2dd7f2ce8c4d260b8ddefcf2c566810319
|
/Difference Finder/Gyte_DifferenceFinder/sourceCodes/RegisterImage.h
|
e43a3624bdc4576e1724650ddc55d7cd0f289976
|
[] |
no_license
|
Coker/AOGAS
|
4e63d8677e1af89985d2d78e270754bc34eeea10
|
5d2f703236c9c0b2655f0e1a850063d86d7ff3e2
|
refs/heads/master
| 2020-05-23T13:49:42.572091
| 2013-10-04T15:15:09
| 2013-10-04T15:15:09
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 816
|
h
|
RegisterImage.h
|
///////////////////////////////////////////////////////////
// RegisterImage.h
// Implementation of the Class RegisterImage
// Created on: 25-Tem-2013 11:46:57
// Original author: Coker
///////////////////////////////////////////////////////////
#if !defined(EA_332DCCD2_6FC9_4757_BF58_C04B54CFF93D__INCLUDED_)
#define EA_332DCCD2_6FC9_4757_BF58_C04B54CFF93D__INCLUDED_
#include <opencv/cv.h>
#include "AffRect.h"
namespace GYTE_DIFF_FINDER {
class RegisterImage
{
public:
RegisterImage();
RegisterImage(cv::Mat rgbPano);
virtual ~RegisterImage();
AffRect getAffineRect(cv::Mat rgbImage, char outputPath[] );
void setPano(cv::Mat panoImage);
private:
cv::Mat rgbPano;
};
} // end of GYTE_DIFF_FINDER namespace
#endif // !defined(EA_332DCCD2_6FC9_4757_BF58_C04B54CFF93D__INCLUDED_)
|
abe7ced042b505e5defb37335540c5bba4992ce5
|
51670767ba9db31287a3221d509b6a86e08ffb39
|
/main.cpp
|
998abb10f50a27d74a3379845cb6c7d518b40b8c
|
[] |
no_license
|
AnthonyVildoso/fibonaci
|
da89a2d4acd19b11fba1544c8038760381808bbd
|
d8b3d389f1688af8803f6178792a504e34e27899
|
refs/heads/master
| 2021-01-19T06:38:38.772347
| 2017-04-06T21:12:03
| 2017-04-06T21:12:03
| 87,474,420
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 313
|
cpp
|
main.cpp
|
#include <iostream>
using namespace std;
int main()
{
int fn,cont,sum,f;
cont=0;
sum=1;
f=0;
cout<<"Fibonacci:";
cin>>fn;
cout<<0<<endl;
cout<<1<<endl;
for(int x=0;x<fn-2;x++){
f=cont+sum;
cout<<f<<endl;
cont=sum;
sum=f;
}
return 0;
}
|
cab2472fbd20dbd09247adc4239dc5dd9895e22f
|
e5d0e2c7baa1d5a9bd8a49678bdcc2489e360029
|
/COciHandle.h
|
a2835072abee4cde4a6ca7a3769454fe6ef4d84b
|
[] |
no_license
|
slapware/CatalogThumb
|
9a52077e8aca1d7f7889ceedaf8e1631c8e988f5
|
0ec37f2ed90093ed49324c1b340090a74937bf82
|
refs/heads/master
| 2021-01-01T16:36:37.831650
| 2017-09-10T16:18:16
| 2017-09-10T16:18:16
| 97,869,753
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,183
|
h
|
COciHandle.h
|
#pragma once
#ifdef WIN32
#pragma warning( disable : 4267 ) // Disable warning messages
#endif
#ifdef _DEBUG
#define _RWCONFIG 15s
#else
#define _RWCONFIG 12s
#endif
#include <rw/pointer/RWBodyBase.h>
#include <rw/pointer/RWHandleBase.h>
#include "COciImp.h"
#define _ThisClass CCOciHandle
using namespace std;
namespace slapware // begin SlapWare namespace
{
class CCOciHandle : public RWHandleBase
{
public:
CCOciHandle(void);
~CCOciHandle(void);
CCOciHandle(const RWCString& _server, const RWCString _user, const RWCString _pswd);
bool check(void);
bool DoSelect(const RWCString& _param1, const RWCString& _param2);
RWCString GetURL();
RWCString GetType();
RWDBStatus GetStatus();
int GetCount(RWCString& pSql);
int GetStrInt(RWCString& pSql, RWCString& param1, int& param2);
int GetStrStr(RWCString& pSql, RWCString& param1, RWCString& param2);
int Update(RWCString& pSql);
int make_docMap(RWCString& pSql, map<int,RWCString>&myRef);
protected:
CCOciImp & body() const;
};
} // end SlapWare namespace
#undef _ThisClass
|
f6270f9cc806c62917b76492bea1629b1565b6d7
|
f0698e8e17d8a56777b02819b1bf22427212b939
|
/esculturas.cpp
|
7ef27393c26812f24da78a1a76e7b059e93d666e
|
[] |
no_license
|
Oswal-Fuentes/Examen120172-OswalFuentes
|
594630f24947f1aa8f59bd50e8881d52a137770c
|
ff790aa35cab3424d8a550a0a50c3b1b4420847a
|
refs/heads/master
| 2021-01-21T15:14:25.710648
| 2017-05-20T00:12:23
| 2017-05-20T00:12:23
| 91,836,221
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 650
|
cpp
|
esculturas.cpp
|
#include <string>
#include "esculturas.h"
#include "obras.h"
using namespace std;
Esculturas::Esculturas(string id,string nombre,string autor,string artista,string fecha_ingreso, int peso,string material){
this->id=id;
this->nombre=nombre;
this->autor=autor;
this->artista=artista;
this->fecha_ingreso=fecha_ingreso;
this->peso=peso;
this->material=material;
}
Esculturas::Esculturas(){
}
int Esculturas::getPeso(){
return peso;
}
void Esculturas::setPeso(int peso){
this->peso=peso;
}
string Esculturas::getMaterial(){
return material;
}
void Esculturas::setMaterial(string material){
this->material=material;
}
|
26364bba392bb1cfda1693d8218772f1f7f16d48
|
90454c8f485b87f15650561923882f732c8c5ada
|
/Plugins/RuntimeGeometryUtils/Source/RuntimeGeometryUtils/Public/DynamicPMCActor.h
|
44af58be9fc9e4d40b3a54451773efb962119701
|
[
"MIT"
] |
permissive
|
monizka/UnrealRuntimeToolsFrameworkDemo
|
758b528529ae4938ca7e9825d1d1a096a925b35a
|
07aac135dc975c4833ae081a69be9f725412ffa0
|
refs/heads/main
| 2023-04-18T05:43:35.603794
| 2021-04-22T08:52:36
| 2021-04-22T08:52:36
| 358,448,113
| 0
| 1
|
MIT
| 2021-04-16T02:07:53
| 2021-04-16T02:07:53
| null |
UTF-8
|
C++
| false
| false
| 786
|
h
|
DynamicPMCActor.h
|
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "ProceduralMeshComponent.h"
#include "DynamicMeshBaseActor.h"
#include "DynamicPMCActor.generated.h"
UCLASS()
class RUNTIMEGEOMETRYUTILS_API ADynamicPMCActor : public ADynamicMeshBaseActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
ADynamicPMCActor();
public:
UPROPERTY(VisibleAnywhere)
UProceduralMeshComponent* MeshComponent = nullptr;
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
protected:
/**
* ADynamicBaseActor API
*/
virtual void OnMeshEditedInternal() override;
protected:
virtual void UpdatePMCMesh();
};
|
667eccefd8d40cd9f42cdeebd698b9aecefbddfc
|
ae31542273a142210a1ff30fb76ed9d45d38eba9
|
/src/backend/gporca/server/include/unittest/dxl/statistics/CJoinCardinalityTest.h
|
66b425d8816080d18bb6e46f0097228174de407d
|
[
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"PostgreSQL",
"OpenSSL",
"LicenseRef-scancode-stream-benchmark",
"ISC",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-ssleay-windows",
"BSD-2-Clause",
"Python-2.0"
] |
permissive
|
greenplum-db/gpdb
|
8334837bceb2d5d51a684500793d11b190117c6a
|
2c0f8f0fb24a2d7a7da114dc80f5f5a2712fca50
|
refs/heads/main
| 2023-08-22T02:03:03.806269
| 2023-08-21T22:59:53
| 2023-08-22T01:17:10
| 44,781,140
| 6,417
| 2,082
|
Apache-2.0
| 2023-09-14T20:33:42
| 2015-10-23T00:25:17
|
C
|
UTF-8
|
C++
| false
| false
| 3,191
|
h
|
CJoinCardinalityTest.h
|
//---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2017 VMware, Inc. or its affiliates.
//
// @filename:
// CJoinCardinalityTest.h
//
// @doc:
// Test for join cardinality estimation
//---------------------------------------------------------------------------
#ifndef GPNAUCRATES_CJoinCardinalityTest_H
#define GPNAUCRATES_CJoinCardinalityTest_H
#include "naucrates/statistics/CBucket.h"
#include "naucrates/statistics/CHistogram.h"
#include "naucrates/statistics/CPoint.h"
#include "naucrates/statistics/CStatistics.h"
#include "naucrates/statistics/CStatsPredDisj.h"
namespace gpnaucrates
{
//---------------------------------------------------------------------------
// @class:
// CJoinCardinalityTest
//
// @doc:
// Static unit tests for join cardinality estimation
//
//---------------------------------------------------------------------------
class CJoinCardinalityTest
{
// shorthand for functions for generating the join predicates
typedef CStatsPredJoinArray *(FnPdrgpstatjoin)(CMemoryPool *mp);
private:
// test case for join evaluation
struct SStatsJoinSTestCase
{
// input stats dxl file
const CHAR *m_szInputFile;
// output stats dxl file
const CHAR *m_szOutputFile;
// is the join a left outer join
BOOL m_fLeftOuterJoin;
// join predicate generation function pointer
FnPdrgpstatjoin *m_pf;
}; // SStatsJoinSTestCase
// test case for join evaluation with NDVRemain
struct SStatsJoinNDVRemainTestCase
{
// column identifier for the first histogram
ULONG m_ulCol1;
// column identifier for the second histogram
ULONG m_ulCol2;
// number of buckets in the output
ULONG m_ulBucketsJoin;
// cumulative number of distinct values in the buckets of the join histogram
CDouble m_dNDVBucketsJoin;
// NDV remain of the join histogram
CDouble m_dNDVRemainJoin;
// frequency of the NDV remain in the join histogram
CDouble m_dFreqRemainJoin;
}; // SStatsJoinNDVRemainTestCase
// int4 histogram test cases
struct SHistogramTestCase
{
// number of buckets in the histogram
ULONG m_num_of_buckets;
// number of distinct values per bucket
CDouble m_dNDVPerBucket;
// percentage of tuples that are null
BOOL m_fNullFreq;
// number of remain distinct values
CDouble m_dNDVRemain;
}; // SHistogramTestCase
// helper method to generate a single join predicate
static CStatsPredJoinArray *PdrgpstatspredjoinSingleJoinPredicate(
CMemoryPool *mp);
// helper method to generate generate multiple join predicates
static CStatsPredJoinArray *PdrgpstatspredjoinMultiplePredicates(
CMemoryPool *mp);
// helper method to generate join predicate over columns that contain null values
static CStatsPredJoinArray *PdrgpstatspredjoinNullableCols(CMemoryPool *mp);
public:
// unittests
static GPOS_RESULT EresUnittest();
// test join cardinality estimation over histograms with NDVRemain information
static GPOS_RESULT EresUnittest_JoinNDVRemain();
// join buckets tests
static GPOS_RESULT EresUnittest_Join();
}; // class CJoinCardinalityTest
} // namespace gpnaucrates
#endif // !GPNAUCRATES_CJoinCardinalityTest_H
// EOF
|
ddd03f4c958c5a745e643c7c969e79c8fae1bf60
|
d130998ed6cf84e571e8e076774fadbf87334afe
|
/Assignment 4 - Expression Tree Operations/StackADT.cpp
|
1613ba4a021cf9af632ed5aa7edceb5145658195
|
[] |
no_license
|
saarthdeshpande/Advanced-Data-Structures
|
d582404d3e071d8f21aac99e4280840d85227d09
|
52d3b9a0944c7e598c851f3787de03e301461de4
|
refs/heads/master
| 2020-12-01T08:41:17.225828
| 2020-04-08T19:42:24
| 2020-04-08T19:42:24
| 230,593,132
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 631
|
cpp
|
StackADT.cpp
|
/*
* StackADT.cpp
*
* Created on: 05-Feb-2020
* Author: g9
*/
#include "StackADT.h"
StackADT::StackADT() {
// TODO Auto-generated constructor stub
top = NULL;
}
StackADT::~StackADT() {
// TODO Auto-generated destructor stub
}
bool StackADT::isempty()
{
if(top == NULL)
return 1;
return 0;
}
void StackADT::push(BNode *x)
{
StackNode *n = new StackNode;
n -> data = x;
n -> next = top;
top = n;
}
BNode * StackADT::pop()
{
BNode *returnNode = top -> data;
StackNode *topNode;
topNode = top;
top = top -> next;
delete topNode;
return returnNode;
}
BNode* StackADT::peep()
{
return top -> data;
}
|
07cc24191bd8d5a4ea07575b9e2f8cef16e0a2e5
|
4f4f85d98f0f2df9cbda343e120181888636bbde
|
/source/myFuntor.h
|
d18ca71b665c6fa2f76eedcd35c43b2a541d21bf
|
[] |
no_license
|
treejames/calculator
|
1c2a88fe2e95024607e5adf836f427d05ab7c472
|
07d928978c6737b1e93a8bd1dc6b186e536b2559
|
refs/heads/master
| 2017-11-15T13:08:10.086937
| 2014-05-11T06:41:55
| 2014-05-11T06:41:55
| 34,618,366
| 0
| 1
| null | 2015-04-26T15:45:22
| 2015-04-26T15:45:22
| null |
UTF-8
|
C++
| false
| false
| 10,299
|
h
|
myFuntor.h
|
#if !defined(AFX_MYFUNTOR_H_INCLUDED_)
#define AFX_MYFUNTOR_H_INCLUDED_
#pragma once
#include <cmath>
#include <vector>
#include <functional>
using namespace std;
#define PI 3.1415926
class operatorAndFunctor
{
public:
operatorAndFunctor(){}
virtual ~operatorAndFunctor(){}
virtual double operator()(vector<double> ¶meters)const = 0;
};
class plus_functor : public operatorAndFunctor
{
public:
double operator()(vector<double> ¶meters)const
{
plus<double> plus_std_functor;
return plus_std_functor(parameters[0], parameters[1]);
}
};
class minus_functor : public operatorAndFunctor
{
public:
double operator()(vector<double> ¶meters)const
{
minus<double> minus_std_functor;
return minus_std_functor(parameters[0], parameters[1]);
}
};
class negate_functor : public operatorAndFunctor
{
public:
double operator()(vector<double> ¶meters)const
{
negate<double> negate_std_functor;
return negate_std_functor(parameters[0]);
}
};
class multiplies_functor : public operatorAndFunctor
{
public:
double operator()(vector<double> ¶meters)const
{
multiplies<double> multiplies_std_functor;
return multiplies_std_functor(parameters[0], parameters[1]);
}
};
class divides_functor : public operatorAndFunctor
{
public:
double operator()(vector<double> ¶meters)const
{
divides<double> divides_std_functor;
if (abs(parameters[1]) < 10e-9)
{
string errMsg = "A error of \"divisor is zero\" has occur.";
return 0;
}
return divides_std_functor(parameters[0], parameters[1]);
}
};
class modulus_functor : public operatorAndFunctor
{
public:
double operator()(vector<double> ¶meters)const
{
modulus<int> modulus_std_functor;
if ((int)parameters[1] <= 0)
{
string errMsg = "The second parameter of modulus must be positive.";
return 0;
}
return modulus_std_functor((int)parameters[0], (int)parameters[1]);
}
};
class abs_functor : public operatorAndFunctor
{
public:
double operator()(vector<double> ¶meters)const
{
return abs(parameters[0]);
}
};
class pow_functor : public operatorAndFunctor
{
public:
double operator()(vector<double> ¶meters)const
{
// std::cout << " " << parameters[0] << " " << parameters[1] << endl;
return pow(parameters[0], parameters[1]);
}
};
class exp_functor : public operatorAndFunctor
{
public:
double operator()(vector<double> ¶meters)const
{
return exp(parameters[0]);
}
};
class log_functor : public operatorAndFunctor
{
public:
double operator()(vector<double> ¶meters)const
{
if (parameters[0] <= 0 || parameters[1] <= 0)
{
string errMsg = "The parameters of log() both must be positive.";
return 0;
}
return log(parameters[0]) / log(parameters[1]);
}
};
class ln_functor : public operatorAndFunctor
{
public:
double operator()(vector<double> ¶meters)const
{
if (parameters[0] <= 0)
{
string errMsg = "The parameter of ln() must be positive.";
return 0;
}
return log(parameters[0]);
}
};
class sqrt_functor : public operatorAndFunctor
{
public:
double operator()(vector<double> ¶meters)const
{
if (parameters[0] < 0)
{
string errMsg = "The parameter of sqrt() must be non-negative.";
return 0;
}
return sqrt(parameters[0]);
}
};
class sin_functor : public operatorAndFunctor
{
public:
double operator()(vector<double> ¶meters)const
{
return sin(parameters[0] * PI / 180);
}
};
class cos_functor : public operatorAndFunctor
{
public:
double operator()(vector<double> ¶meters)const
{
return cos(parameters[0] * PI / 180);
}
};
class tan_functor : public operatorAndFunctor
{
public:
double operator()(vector<double> ¶meters)const
{
return tan(parameters[0] * PI / 180);
}
};
class arcsin_functor : public operatorAndFunctor
{
public:
double operator()(vector<double> ¶meters)const
{
return asin(parameters[0]);
}
};
class arccos_functor : public operatorAndFunctor
{
public:
double operator()(vector<double> ¶meters)const
{
return acos(parameters[0]);
}
};
class arctan_functor : public operatorAndFunctor
{
public:
double operator()(vector<double> ¶meters)const
{
return atan(parameters[0]);
}
};
class fact_functor : public operatorAndFunctor
{
public:
double operator()(vector<double> ¶meters)const
{
int n = (int)parameters[0];
if (n < 0)
return -1;
if (n == 0)
return 1;
int i, result = 1;
for (i = 1; i <= n; i++)
result *= i;
return result;
}
};
class double_factorial_functor : public operatorAndFunctor
{
public:
double operator()(vector<double> ¶meters)const
{
int n = (int)parameters[0];
if (n < 0)
return -1;
if (n == 0)
return 0;
int i, result = 1;
for (i = (n % 2 == 0 ? 2 : 1); i <= n; i += 2)
result *= i;
return result;
}
};
class cb_functor : public operatorAndFunctor
{
public:
double operator()(vector<double> ¶meters)const
{
int m = (int)parameters[0];
int n = (int)parameters[1];
if (n <= 0 || m <= 0 || m > n)
return 0;
int numerator = 1;
int denominator = 1;
for (int i = 0; i < m; i++)
{
numerator *= (n-i);
denominator *= (m-i);
}
return (double)numerator / (double)denominator;
}
};
class max_functor : public operatorAndFunctor
{
public:
double operator()(vector<double> ¶meters)const
{
double curtMax = parameters[0];
for (vector<double>::const_iterator it = parameters.begin(); it != parameters.end(); it++)
{
if (*it > curtMax)
curtMax = *it;
}
return curtMax;
}
};
class min_functor : public operatorAndFunctor
{
public:
double operator()(vector<double> ¶meters)const
{
double curtMax = parameters[0];
for (vector<double>::const_iterator it = parameters.begin(); it != parameters.end(); it++)
{
if (*it < curtMax)
curtMax = *it;
}
return curtMax;
}
};
class ceil_functor : public operatorAndFunctor
{
public:
double operator()(vector<double> ¶meters)const
{
return ceil(parameters[0]);
}
};
class floor_functor : public operatorAndFunctor
{
public:
double operator()(vector<double> ¶meters)const
{
return floor(parameters[0]);
}
};
class sinh_functor : public operatorAndFunctor
{
public:
double operator()(vector<double> ¶meters)const
{
return sinh(parameters[0]);
}
};
class cosh_functor : public operatorAndFunctor
{
public:
double operator()(vector<double> ¶meters)const
{
return cosh(parameters[0]);
}
};
class tanh_functor : public operatorAndFunctor
{
public:
double operator()(vector<double> ¶meters)const
{
return tanh(parameters[0]);
}
};
class avg_functor : public operatorAndFunctor
{
public:
double operator()(vector<double> ¶meters)const {
double sum = 0;
int num = 0;
for (vector<double>::const_iterator it = parameters.begin(); it != parameters.end(); it++) {
sum += *it;
num++;
}
//cout << sum << endl;
return (sum / num);
}
};
class sum_functor : public operatorAndFunctor {
public:
double operator()(vector<double> ¶meters)const {
double sum = 0.0;
for (vector<double>::const_iterator it = parameters.begin(); it != parameters.end(); it++) {
sum += *it;
}
return sum;
}
};
class var_functor :public operatorAndFunctor {
public:
double operator()(vector<double> ¶meters)const {
double sum = 0.0;
double Svar = 0.0;
int num = 0;
double average = 0.0;
for (vector<double>::const_iterator it = parameters.begin(); it != parameters.end(); it++) {
sum += *it;
num++;
}
average = sum / num;
for (vector<double>::const_iterator it1 = parameters.begin(); it1 != parameters.end(); it1++) {
Svar += pow(average - *it1, 2);
}
return (Svar / (num - 1));
}
};
class varp_functor : public operatorAndFunctor {
public:
double operator()(vector<double> ¶meters)const {
double sum = 0.0;
double Svarp = 0.0;
int num = 0;
double average = 0.0;
for (vector<double>::const_iterator it = parameters.begin(); it != parameters.end(); it++) {
sum += *it;
num++;
}
average = sum / num;
for (vector<double>::const_iterator it2 = parameters.begin(); it2 != parameters.end(); it2++) {
Svarp += pow(average - *it2, 2);
}
return (Svarp / num);
}
};
class stdev_functor : public operatorAndFunctor {
public:
double operator()(vector<double> ¶meters)const {
double sum = 0.0;
double Svar = 0.0;
int num = 0;
double average = 0.0;
for (vector<double>::const_iterator it = parameters.begin(); it != parameters.end(); it++) {
sum += *it;
num++;
}
average = sum / num;
for (vector<double>::const_iterator it3 = parameters.begin(); it3 != parameters.end(); it3++) {
Svar += pow(average - *it3, 2);
}
return (pow((Svar / (num - 1)), 0.5));
}
};
class stdevp_functor : public operatorAndFunctor {
public:
double operator()(vector<double> ¶meters)const {
double sum = 0.0;
double Svarp = 0.0;
int num = 0;
double average = 0.0;
for (vector<double>::const_iterator it = parameters.begin(); it != parameters.end(); it++) {
sum += *it;
num++;
}
average = sum / num;
for (vector<double>::const_iterator it4 = parameters.begin(); it4 != parameters.end(); it4++) {
Svarp += pow(average - *it4, 2);
}
return (pow((Svarp / num), 0.5));
}
};
class mod_functor : public operatorAndFunctor {
public:
double operator()(vector<double> ¶meters)const {
return ((int)parameters[0] % (int)parameters[1]);
}
};
class cubroot_functor : public operatorAndFunctor {
double operator()(vector<double> ¶meters)const
{
return pow(parameters[0], 0.5);
}
};
class yroot_functor : public operatorAndFunctor {
double operator()(vector<double> ¶meters)const {
return pow(parameters[0], 1.0 / parameters[1]);
}
};
#endif
|
e5f55dfba8be68e11e1c6de1d5cd4ce8264b7e24
|
772bcce89bc039899ce284f12a880e378d58fb00
|
/Clasa a X-a/Probleme diverse/Diverse/patrate.cpp
|
942b42eb2ffbe72c1af2595900bba9f90356b35a
|
[] |
no_license
|
IvanciuVlad/PbInfo
|
462767533b61544f65111005a26ec739c7b1e81e
|
3f0ee0763db788e862e9708c7ef3597795252e30
|
refs/heads/master
| 2020-05-02T14:33:23.532883
| 2019-03-27T15:47:15
| 2019-03-27T15:47:15
| 178,014,190
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 275
|
cpp
|
patrate.cpp
|
#include<iostream>
using namespace std;
int main()
{
unsigned long long n, t1, t2, d = 666013;
cin >> n;
t1 = (n*(n+1))/2;
t2 = (n + 1)*(n + 2)/2;
if(t1%3 == 0)
t1 /= 3;
else
t2 /= 3;
cout << ((t1%d) * (t2%d))%d;
return 0;
}
|
03dd15afe8f4684a43cdcbb1515405389a5936b5
|
c193e9ae2e2f444bdeceeba183a8ffc159dcac02
|
/include/LDParse/Geom.hpp
|
c25db20c1b3115056047429acb051f3fded62a22
|
[] |
no_license
|
elfprince13/LDParse
|
7aba574661e5a078b0645c9b0395d33f358b01af
|
877667417d6cab57c04aed9cb3d5bfe7efa0589c
|
refs/heads/master
| 2021-07-16T07:22:14.775547
| 2017-01-13T05:58:35
| 2017-01-13T05:58:35
| 60,742,545
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,358
|
hpp
|
Geom.hpp
|
//
// Geom.hpp
// LDParse
//
// Created by Thomas Dickerson on 1/15/16.
// Copyright © 2016 StickFigure Graphic Productions. All rights reserved.
//
#ifndef Geom_hpp
#define Geom_hpp
#include <stdio.h>
#include <tuple>
#include <vector>
#include <string>
#include <map>
namespace LDParse{
typedef std::pair<bool, uint32_t> ColorRef;
typedef std::tuple<float, float, float> Position;
typedef std::tuple<Position, Position, Position> Line;
typedef std::tuple<Position, Position, Position> Triangle;
typedef std::tuple<Position, Position, Position, Position> Quad;
typedef std::tuple<Line, Line> OptLine;
typedef std::tuple<Position,
float, float, float,
float, float, float,
float, float, float> TransMatrix;
template<typename ...AttrTypes> class Mesh {
public:
typedef Mesh<AttrTypes...> SelfType;
typedef std::tuple<std::vector<AttrTypes> ...> AttrsType;
template<size_t i> using AttrType = typename std::tuple_element<i, AttrsType>::type;
AttrsType attributes;
std::vector<uint32_t> indices;
std::vector<uint32_t> bfIndices; // We may store reverse copies of certain triangles
template<typename ...TxFormFs> void mergeMesh(const SelfType &merge, std::tuple<TxFormFs ...> txformFs = std::make_tuple(identity<AttrTypes>() ...)){
const size_t offset = vertexCount();
//size_t indexCt = indices.size();
mergeHelper(merge, txformFs);
const auto offsetF = [](uint32_t &index){ index += offset; };
appendVector(indices, merge.indices, offsetF);
appendVector(bfIndices, merge.bfIndices, offsetF);
//size_t niCt = indices.size();
/*for(size_t i = indexCt; i < niCt; ++i){
indices[i] += offset;
}*/
}
size_t vertexCount() const {
return std::get<0>(attributes).size();
}
size_t rangeAll() const {
return std::make_pair(0, vertexCount());
}
template<typename T> using IdentityF = void(*)(const T&);
template<typename T> static const IdentityF<T> identity(){ return nullptr; }
template<size_t i> inline void transform(void (*txformF)(AttrType<i>&)){ transform(txformF, rangeAll()); }
template<size_t i> void transform(void (*txformF)(AttrType<i>&), const std::pair<size_t, size_t> &range){
transform(std::get<i>(attributes), txformF, range);
}
template<typename T> inline void transform(std::vector<T> &v, void (*txformF)(T&), const std::pair<size_t, size_t> &range){
if(txformF != nullptr) for(size_t j = range.first; j < range.second; ++j) txFormF(v[j]);
}
private:
template<std::size_t> struct int_{};
template<size_t N = std::tuple_size<AttrsType>::value> void mergeHelper(const SelfType &merge, std::tuple<void(AttrTypes&) ...> txformFs, int_<N> elemCt = int_<N>()){
constexpr size_t i = std::tuple_size<AttrsType>::value - N;
AttrType<i> &thisAttr = std::get<i>(attributes);
const AttrType<i> &mergeAttr = std::get<i>(merge.attributes);
appendVector(thisAttr, mergeAttr);
mergeHelper(merge, txformFs, int_<N-1>());
}
void mergeHelper(const SelfType &merge, std::tuple<void(AttrTypes&) ...> txformFs, int_<0>){}
template<typename T> void appendVector(std::vector<T> &l, const std::vector<T> &r, void(*txformF)(T&)){
size_t begin = l.size();
l.insert(l.end(), r.begin(), r.end());
size_t end = l.size();
transform(l, txformF, std::make_pair(begin, end));
}
};
}
#endif /* Geom_hpp */
|
96bf93cf2518d6117a764687d4a87b16621a8511
|
b8cacbf61492f7f9deabcb465c3171c245fbbb9d
|
/AirQualityMonitor/AirQualityMonitor/AirQualityMonitor.cpp
|
82160278334a54bacf137c57488d039c1618806a
|
[
"MIT"
] |
permissive
|
gmalara/pms3003-dust-sensor-pc-client
|
71330c2bc3f73b49cf0817d23a2edd1aea00560e
|
c48a683a339774b95c42ec2091d7ae3366012345
|
refs/heads/master
| 2021-09-14T17:01:57.251333
| 2018-05-16T09:27:19
| 2018-05-16T09:27:19
| 112,312,955
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,887
|
cpp
|
AirQualityMonitor.cpp
|
#include "AirQualityMonitor.h"
#include "libusb.h"
#include <iostream>
namespace {
using namespace std;
const auto kEndpointAddress = 1;
const int kBuff_length = 24;
const uint16_t kExpected_sensor_id = 60000;
const uint16_t kFirstByteOfSequence = 0x42;
void DescribeDevice(libusb_device_handle* dev_handle, libusb_device_descriptor desc) {
unsigned char data[200] = "\0";
if (dev_handle) {
libusb_get_string_descriptor_ascii(dev_handle, desc.iProduct, data, 200);
cout << "Product: " << data << "\n";
memcpy(data, "\0", 100);
libusb_get_string_descriptor_ascii(dev_handle, desc.iManufacturer, data, 200);
cout << "Manufacturer: " << data << "\n";
memcpy(data, "\0", 100);
libusb_get_string_descriptor_ascii(dev_handle, desc.iSerialNumber, data, 200);
cout << "SerialNo: " << data << "\n\n\n\n";
memcpy(data, "\0", 100);
}
}
libusb_device_handle* OpenDevice(libusb_context* ctx, libusb_device_descriptor desc) {
cout << "Opening device, product: " << desc.idProduct << ", vendor: " << desc.idVendor << endl;
auto dev_handle = libusb_open_device_with_vid_pid(ctx, desc.idVendor, desc.idProduct);
if (dev_handle == NULL)
cout << "Cannot open device" << endl;
DescribeDevice(dev_handle, desc);
return dev_handle;
}
bool DeviceMatch(const libusb_device_descriptor& desc) {
auto deviceMatch = desc.idProduct == kExpected_sensor_id;
cout << boolalpha << "DeviceMatch: " << deviceMatch << endl;
return deviceMatch;
}
pair<bool, libusb_device_descriptor> FindDeviceAndPrintInfo(libusb_context* ctx, libusb_device* dev) {
libusb_device_descriptor desc;
int r = libusb_get_device_descriptor(dev, &desc);
if (r < 0) {
cout << "failed to get device descriptor" << endl;
return make_pair(false, desc);
}
if (!DeviceMatch(desc))
return make_pair(false, desc);
cout << "Number of possible configurations: " << (int)desc.bNumConfigurations << " \n";
cout << "Device Class: " << (int)desc.bDeviceClass << " \n";
cout << "VendorID: " << desc.idVendor << " \n";
cout << "ProductID: " << desc.idProduct << endl;
cout << "SerialNo: " << desc.iSerialNumber << endl;
libusb_config_descriptor* config = nullptr;
r = libusb_get_config_descriptor(dev, 0, &config);
if (r < 0)
cout << "Failed to get device config" << endl;
else {
cout << "Interfaces: " << (int)config->bNumInterfaces << " |||\n";
const libusb_interface* inter;
const libusb_interface_descriptor* interdesc;
const libusb_endpoint_descriptor* epdesc;
for (int i = 0; i < (int)config->bNumInterfaces; i++) {
inter = &config->interface[i];
cout << "Number of alternate settings: " << inter->num_altsetting << " \n";
for (int j = 0; j < inter->num_altsetting; j++) {
interdesc = &inter->altsetting[j];
cout << "Interface Number: " << (int)interdesc->bInterfaceNumber << " \n";
cout << "Number of endpoints: " << (int)interdesc->bNumEndpoints << " \n";
for (int k = 0; k < (int)interdesc->bNumEndpoints; k++) {
epdesc = &interdesc->endpoint[k];
cout << "Descriptor Type: " << (int)epdesc->bDescriptorType << " \n";
cout << "End Point Address: " << (int)epdesc->bEndpointAddress << " \n";
}
}
cout << "---------" << endl;
}
}
libusb_free_config_descriptor(config);
return make_pair(true, desc);
}
}
void AirQualityMonitor::PublishMeasurements(Measurements& m) { onUpdate(m); }
void AirQualityMonitor::SubscribeObserver(IAirQualityMonitor::UpdateHandler::slot_type update) { onUpdate.connect(update); }
AirQualityMonitor::AirQualityMonitor() { }
AirQualityMonitor::~AirQualityMonitor() {
onUpdate.disconnect_all_slots();
shuttingDown_.store(true);
}
void AirQualityMonitor::Start(){
RunLoop();
}
void AirQualityMonitor::RunLoop() {
deviceCommunication_ = std::async(std::launch::async, [this]()
{
libusb_device** devs; //pointer to pointer of device, used to retrieve a list of devices
libusb_context* ctx = nullptr; //a libusb session
int r; //for return values
ssize_t cnt; //holding number of devices in list
r = libusb_init(&ctx); //initialize a library session
if (r < 0) {
std::cout << "Init Error " << r << std::endl; //there was an error
return;
}
libusb_set_debug(ctx, LIBUSB_LOG_LEVEL_WARNING); //set verbosity level to 3
cnt = libusb_get_device_list(ctx, &devs); //get the list of devices
if (cnt < 0)
cout << "Get Device Error" << std::endl; //there was an error
cout << cnt << " Devices in list." << endl; //print total number of usb devices
ssize_t i; //for iterating through the list
for (i = 0; i < cnt; i++) {
auto successDescriptorPair = FindDeviceAndPrintInfo(ctx, devs[i]);
auto deviceFound = successDescriptorPair.first;
if (deviceFound) {
auto dev_handle = OpenDevice(ctx, successDescriptorPair.second);
libusb_claim_interface(dev_handle, 0);
struct libusb_transfer* transfer = libusb_alloc_transfer(0);
unsigned char buf[kBuff_length * 2];
int actualLength = kBuff_length * 2;
DescribeDevice(dev_handle, successDescriptorPair.second);
while (!shuttingDown_) {
std::this_thread::sleep_for(std::chrono::milliseconds(500));
auto ret = libusb_bulk_transfer(dev_handle, kEndpointAddress | LIBUSB_ENDPOINT_IN, buf, kBuff_length * 2, &actualLength, 5000);
Measurements m;
if (m.HandleIncomingData(buf, actualLength))
PublishMeasurements(m);
}
cout << boolalpha << "Closing Device. \n ";
libusb_close(dev_handle);
break;
}
libusb_free_device_list(devs, 1); //free the list, unref the devices in it
libusb_exit(ctx); //close the session
// Exit
cout << endl << "Finnished.";
return;
}
});
}
|
ee371f8e81359e342cdccef19a6d10183813bb40
|
2daa2b4a4c61ddbaf0fe7b66cf4bff05bb28461f
|
/src/common/messages.hpp
|
ab64ca1d1664848db8b0c9fc72235d944bb2ae86
|
[] |
no_license
|
yurai007/maze
|
0662ddfff09effcebb519f415edf5f2278f6d209
|
9cceca98cfaf9afff647fd2f314d274aef949de8
|
refs/heads/master
| 2020-12-29T02:32:14.780469
| 2017-02-19T17:12:22
| 2017-02-19T17:12:22
| 38,566,350
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,713
|
hpp
|
messages.hpp
|
#ifndef MESSAGES_HPP
#define MESSAGES_HPP
#include <boost/mpl/vector.hpp>
#include <boost/mpl/find.hpp>
#include <boost/mpl/size.hpp>
#include <boost/mpl/for_each.hpp>
#include "byte_buffer.hpp"
namespace networking
{
namespace messages
{
struct get_chunk;
struct get_chunk_response;
struct position_changed;
struct position_changed_response;
struct client_shutdown;
struct client_shutdown_response;
struct get_id;
struct get_id_response;
struct fireball_triggered;
struct fireball_triggered_response;
struct internal_error_message;
using registered_messages = boost::mpl::vector<get_chunk, get_chunk_response, position_changed,
position_changed_response, client_shutdown, client_shutdown_response, get_id, get_id_response,
fireball_triggered, fireball_triggered_response, internal_error_message>;
template <class T>
struct message_numerator
{
static char message_id()
{
using iter = typename boost::mpl::find<registered_messages, T>::type;
static_assert(iter::pos::value < boost::mpl::size<registered_messages>::value,
"message is NOT registered");
return (char)iter::pos::value;
}
};
struct get_chunk : public message_numerator<get_chunk>
{
unsigned ld_x, ld_y, ru_x, ru_y;
get_chunk() = default;
get_chunk(unsigned ld_xx, unsigned ld_yy, unsigned ru_xx, unsigned ru_yy) :
ld_x(ld_xx), ld_y(ld_yy), ru_x(ru_xx), ru_y(ru_yy) {}
void serialize_to_buffer(serialization::byte_buffer &buffer) const
{
buffer.put_unsigned_int(ld_x);
buffer.put_unsigned_int(ld_y);
buffer.put_unsigned_int(ru_x);
buffer.put_unsigned_int(ru_y);
}
void deserialize_from_buffer(serialization::byte_buffer &buffer)
{
ld_x = buffer.get_unsigned_int();
ld_y = buffer.get_unsigned_int();
ru_x = buffer.get_unsigned_int();
ru_y = buffer.get_unsigned_int();
}
};
struct get_chunk_response : public message_numerator<get_chunk_response>
{
get_chunk_response() = default;
get_chunk_response(const std::string &chunk)
{
content = chunk;
}
void serialize_to_buffer(serialization::byte_buffer &buffer) const
{
buffer.put_string(content);
}
void deserialize_from_buffer(serialization::byte_buffer &buffer)
{
content = buffer.get_string();
}
std::string content;
};
struct position_changed : public message_numerator<position_changed>
{
int player_id, old_x, old_y, new_x, new_y;
position_changed() = default;
position_changed(int player_id_, int old_xx, int old_yy, int new_xx, int new_yy)
: player_id(player_id_), old_x(old_xx), old_y(old_yy), new_x(new_xx), new_y(new_yy) {}
void serialize_to_buffer(serialization::byte_buffer &buffer) const
{
buffer.put_int(player_id);
buffer.put_int(old_x);
buffer.put_int(old_y);
buffer.put_int(new_x);
buffer.put_int(new_y);
}
void deserialize_from_buffer(serialization::byte_buffer &buffer)
{
player_id = buffer.get_int();
old_x = buffer.get_int();
old_y = buffer.get_int();
new_x = buffer.get_int();
new_y = buffer.get_int();
}
};
struct position_changed_response : public message_numerator<position_changed_response>
{
position_changed_response() = default;
void serialize_to_buffer(serialization::byte_buffer &buffer) const
{
buffer.put_string(content);
}
void deserialize_from_buffer(serialization::byte_buffer &buffer)
{
content = buffer.get_string();
}
std::string content {"OK"};
};
struct client_shutdown : public message_numerator<client_shutdown>
{
client_shutdown() = default;
client_shutdown(int player_id_) : player_id(player_id_) {}
void serialize_to_buffer(serialization::byte_buffer &buffer) const
{
buffer.put_int(player_id);
}
void deserialize_from_buffer(serialization::byte_buffer &buffer)
{
player_id = buffer.get_int();
}
int player_id;
};
struct client_shutdown_response : public message_numerator<client_shutdown_response>
{
client_shutdown_response() = default;
void serialize_to_buffer(serialization::byte_buffer &buffer) const
{
buffer.put_string(content);
}
void deserialize_from_buffer(serialization::byte_buffer &buffer)
{
content = buffer.get_string();
}
std::string content {"OK"};
};
struct get_id : public message_numerator<get_id>
{
get_id() = default;
void serialize_to_buffer(serialization::byte_buffer &buffer) const
{
buffer.put_string(content);
}
void deserialize_from_buffer(serialization::byte_buffer &buffer)
{
content = buffer.get_string();
}
std::string content {"id"};
};
struct get_id_response : public message_numerator<get_id_response>
{
get_id_response() = default;
void serialize_to_buffer(serialization::byte_buffer &buffer) const
{
buffer.put_int(player_id);
}
void deserialize_from_buffer(serialization::byte_buffer &buffer)
{
player_id = buffer.get_int();
}
int player_id;
};
struct fireball_triggered : public message_numerator<fireball_triggered>
{
int player_id, pos_x, pos_y;
char direction;
fireball_triggered() = default;
fireball_triggered(int player_id_, int pos_x_, int pos_y_, char direction_) :
player_id(player_id_), pos_x(pos_x_), pos_y(pos_y_), direction(direction_) {}
void serialize_to_buffer(serialization::byte_buffer &buffer) const
{
buffer.put_int(player_id);
buffer.put_int(pos_x);
buffer.put_int(pos_y);
buffer.put_char(direction);
}
void deserialize_from_buffer(serialization::byte_buffer &buffer)
{
player_id = buffer.get_int();
pos_x = buffer.get_int();
pos_y = buffer.get_int();
direction = buffer.get_char();
}
} __attribute__((packed));
struct fireball_triggered_response : public message_numerator<fireball_triggered_response>
{
fireball_triggered_response() = default;
void serialize_to_buffer(serialization::byte_buffer &buffer) const
{
buffer.put_string(content);
}
void deserialize_from_buffer(serialization::byte_buffer &buffer)
{
content = buffer.get_string();
}
std::string content {"OK"};
};
struct internal_error_message : public message_numerator<internal_error_message>
{
internal_error_message() = default;
void serialize_to_buffer(serialization::byte_buffer &buffer) const
{
buffer.put_string(content);
}
void deserialize_from_buffer(serialization::byte_buffer &buffer)
{
content = buffer.get_string();
}
std::string content {"NOK"};
};
struct verify
{
template<typename Msg> void operator()(Msg)
{
assert((unsigned)Msg::message_id() == counter);
counter++;
}
static unsigned counter;
};
extern void verify_messages();
}
}
#endif // MESSAGES_HPP
|
93bd40a224af698a6ce8bd3f349ac6cf70e49d6b
|
51afb12493dd1001cc2952144b23bd26acf49e63
|
/CryptoGuard/src/Hashing/HMAC.cpp
|
ff015e37012821f98d429a43205778d8628b2093
|
[
"MIT"
] |
permissive
|
GitDaroth/CryptoGuard
|
7dc806948a7d84d5ffdec6e97ee7812212748563
|
a53391af3d1a1c6b80cb94734034825f2e1bb452
|
refs/heads/master
| 2022-12-23T12:30:52.412032
| 2020-10-07T18:50:34
| 2020-10-07T18:50:34
| 297,121,873
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 544
|
cpp
|
HMAC.cpp
|
#include "Hashing/HMAC.h"
#include "Hashing/SHA256.h"
std::string HMAC::hash(std::string key, std::string message)
{
if (key.length() > 64)
{
key = SHA256::hash(key);
}
if (key.length() < 64)
{
for (int i = key.length(); i < 64; i++)
{
key += (char)0x00;
}
}
std::string outerPadKey;
for (int i = 0; i < 64; i++)
{
outerPadKey += key[i] ^ 0x5c;
}
std::string innerPadKey;
for (int i = 0; i < 64; i++)
{
innerPadKey += key[i] ^ 0x36;
}
return SHA256::hash(outerPadKey + SHA256::hash(innerPadKey + message));
}
|
fd7457196819816d9ef9a3dd8b867e40d3b8e432
|
e9c38ab5aa68c97090e4e85ccad8b490c9657269
|
/src_tif/igs_tif_error.cxx
|
af18a843729184a2d2ac9a0e1174d344e6abb09f
|
[
"MIT"
] |
permissive
|
emanofu/lib_rw_image
|
4219e944fff784263394af87f129fc4b1a16dde8
|
dd1e888691631cbd46b6a510e6c85ee8b5587937
|
refs/heads/master
| 2020-04-14T12:30:29.645125
| 2014-12-25T06:40:01
| 2014-12-25T06:40:01
| 28,473,378
| 0
| 1
| null | null | null | null |
EUC-JP
|
C++
| false
| false
| 2,437
|
cxx
|
igs_tif_error.cxx
|
#include <cstring> /* strlen() */
#include <cstdio> /* vsnprintf() */
#include <cstdarg> /* vsnprintf() */
#include "igs_tif_error.h"
namespace {
size_t copy_char(const char *src, const size_t dest_len, char *dest) {
/* dest_lenは終端文字も含む大きさ */
/* 入れる場所に大きさがなければなにもコピーしない */
if (dest_len <= 1) { return 0; }
/* コピーする大きさを得る */
size_t siz = strlen(src);
/* 大きさをオーバーしたら可能な分だけ入れる */
if ((dest_len-1) < siz) { siz = dest_len-1; }
if (0 < siz) { memmove(dest, src, siz); dest[siz] = '\0'; }
/* コピーした数をかえす */
return siz;
}
size_t copy_va( const char* fmt, va_list ap, const size_t dest_len, char *dest ) {
/* dest_lenは終端文字も含む大きさ */
/* 入れる場所に大きさがなければなにもコピーしない */
if (dest_len <= 1) { return 0; }
#if defined _WIN32 & (1200 == _MSC_VER) // vc6 compile_type
const int i_ret = _vsnprintf( dest, dest_len, fmt,ap );
#elif defined _WIN32 & (1400 == _MSC_VER) // vc2005 compile_type
const int i_ret = vsnprintf_s(dest, dest_len,dest_len, fmt,ap );
#else
const int i_ret = vsnprintf( dest, dest_len, fmt,ap );
#endif
if (dest_len < static_cast<size_t>(i_ret)) {
/* 切り詰められたのでそちらの数を返す */
return dest_len;
}
return i_ret;
}
}
/*----------
libtiffのvariable argumentエラーメッセージをchar文字列にする
注意:スレッドセーフではない
#include <tiffio.h>
#include <cstdarg>
typedef void (*TIFFErrorHandler)(const char* module, const char* fmt, va_list ap);
TIFFErrorHandler TIFFSetErrorHandler(TIFFErrorHandler handler);
Exsample1: "tmp.tif: 0: Invalid strip byte count, strip 0"
Exsample2: "tmp: Not a TIFF file, bad magic number 25462 (0x6376)
----------*/
namespace { char _ca_msg[1000]; }
void igs::tif::error_handler(
const char* module,
const char* fmt,
va_list ap
) {
/* 初期化 */
size_t siz = 0;
_ca_msg[0] = '\0';
/* 入力ファイル名("tmp.tif"等) */
siz += copy_char(module,1000-siz,&(_ca_msg[siz]));
/* 区切り */
siz += copy_char(": ", 1000-siz,&(_ca_msg[siz]));
/* libtiffのエラーメッセージ */
siz += copy_va(fmt,ap, 1000-siz,&(_ca_msg[siz]));
}
/* libtiff関数エラーのときのエラーメッセージをchar文字列で得る */
char *igs::tif::get_error_msg(void) { return _ca_msg; }
|
56f3a3291b9cc89c69429d05f56073e00f361721
|
0577a46d8d28e1fd8636893bbdd2b18270bb8eb8
|
/chromium/base/allocator/partition_allocator/partition_tag.h
|
36e54b128c40ef38e6d6e6533f134c2c942e4796
|
[
"BSD-3-Clause"
] |
permissive
|
ric2b/Vivaldi-browser
|
388a328b4cb838a4c3822357a5529642f86316a5
|
87244f4ee50062e59667bf8b9ca4d5291b6818d7
|
refs/heads/master
| 2022-12-21T04:44:13.804535
| 2022-12-17T16:30:35
| 2022-12-17T16:30:35
| 86,637,416
| 166
| 41
|
BSD-3-Clause
| 2021-03-31T18:49:30
| 2017-03-29T23:09:05
| null |
UTF-8
|
C++
| false
| false
| 5,792
|
h
|
partition_tag.h
|
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef BASE_ALLOCATOR_PARTITION_ALLOCATOR_PARTITION_TAG_H_
#define BASE_ALLOCATOR_PARTITION_ALLOCATOR_PARTITION_TAG_H_
// This file defines types and functions for `MTECheckedPtr<T>` (cf.
// `tagging.h`, which deals with real ARM MTE).
#include <string.h>
#include "base/allocator/partition_allocator/partition_alloc_base/compiler_specific.h"
#include "base/allocator/partition_allocator/partition_alloc_base/debug/debugging_buildflags.h"
#include "base/allocator/partition_allocator/partition_alloc_config.h"
#include "base/allocator/partition_allocator/partition_alloc_constants.h"
#include "base/allocator/partition_allocator/partition_alloc_forward.h"
#include "base/allocator/partition_allocator/partition_alloc_notreached.h"
#include "base/allocator/partition_allocator/partition_cookie.h"
#include "base/allocator/partition_allocator/partition_page.h"
#include "base/allocator/partition_allocator/partition_tag_bitmap.h"
#include "base/allocator/partition_allocator/partition_tag_types.h"
#include "base/allocator/partition_allocator/reservation_offset_table.h"
#include "base/allocator/partition_allocator/tagging.h"
#include "build/build_config.h"
namespace partition_alloc {
#if defined(PA_ENABLE_MTE_CHECKED_PTR_SUPPORT_WITH_64_BITS_POINTERS)
static_assert(
sizeof(PartitionTag) == internal::tag_bitmap::kPartitionTagSize,
"sizeof(PartitionTag) must be equal to bitmap::kPartitionTagSize.");
PA_ALWAYS_INLINE PartitionTag* NormalBucketPartitionTagPointer(uintptr_t addr) {
uintptr_t bitmap_base =
internal::SuperPageTagBitmapAddr(addr & internal::kSuperPageBaseMask);
const size_t bitmap_end_offset =
internal::PartitionPageSize() + internal::ReservedTagBitmapSize();
PA_DCHECK((addr & internal::kSuperPageOffsetMask) >= bitmap_end_offset);
uintptr_t offset_in_super_page =
(addr & internal::kSuperPageOffsetMask) - bitmap_end_offset;
size_t offset_in_bitmap = offset_in_super_page >>
internal::tag_bitmap::kBytesPerPartitionTagShift
<< internal::tag_bitmap::kPartitionTagSizeShift;
// No need to tag, as the tag bitmap region isn't protected by MTE.
return reinterpret_cast<PartitionTag*>(bitmap_base + offset_in_bitmap);
}
PA_ALWAYS_INLINE PartitionTag* DirectMapPartitionTagPointer(uintptr_t addr) {
uintptr_t first_super_page = internal::GetDirectMapReservationStart(addr);
PA_DCHECK(first_super_page) << "not managed by a direct map: " << addr;
auto* subsequent_page_metadata = GetSubsequentPageMetadata(
internal::PartitionSuperPageToMetadataArea<internal::ThreadSafe>(
first_super_page));
return &subsequent_page_metadata->direct_map_tag;
}
PA_ALWAYS_INLINE PartitionTag* PartitionTagPointer(uintptr_t addr) {
// UNLIKELY because direct maps are far less common than normal buckets.
if (PA_UNLIKELY(internal::IsManagedByDirectMap(addr))) {
return DirectMapPartitionTagPointer(addr);
}
return NormalBucketPartitionTagPointer(addr);
}
PA_ALWAYS_INLINE PartitionTag* PartitionTagPointer(const void* ptr) {
// Disambiguation: UntagPtr relates to hwardware MTE, and it strips the tag
// from the pointer. Whereas, PartitionTagPointer relates to software MTE
// (i.e. MTECheckedPtr) and it returns a pointer to the tag in memory.
return PartitionTagPointer(UntagPtr(ptr));
}
namespace internal {
PA_ALWAYS_INLINE void DirectMapPartitionTagSetValue(uintptr_t addr,
PartitionTag value) {
*DirectMapPartitionTagPointer(addr) = value;
}
PA_ALWAYS_INLINE void NormalBucketPartitionTagSetValue(uintptr_t slot_start,
size_t size,
PartitionTag value) {
PA_DCHECK((size % tag_bitmap::kBytesPerPartitionTag) == 0);
PA_DCHECK((slot_start % tag_bitmap::kBytesPerPartitionTag) == 0);
size_t tag_count = size >> tag_bitmap::kBytesPerPartitionTagShift;
PartitionTag* tag_ptr = NormalBucketPartitionTagPointer(slot_start);
if (sizeof(PartitionTag) == 1) {
memset(tag_ptr, value, tag_count);
} else {
while (tag_count-- > 0)
*tag_ptr++ = value;
}
}
PA_ALWAYS_INLINE PartitionTag PartitionTagGetValue(void* ptr) {
return *PartitionTagPointer(ptr);
}
PA_ALWAYS_INLINE void PartitionTagIncrementValue(uintptr_t slot_start,
size_t size) {
PartitionTag tag = *PartitionTagPointer(slot_start);
PartitionTag new_tag = tag;
++new_tag;
new_tag += !new_tag; // Avoid 0.
#if BUILDFLAG(PA_DCHECK_IS_ON)
PA_DCHECK(internal::IsManagedByNormalBuckets(slot_start));
// This verifies that tags for the entire slot have the same value and that
// |size| doesn't exceed the slot size.
size_t tag_count = size >> tag_bitmap::kBytesPerPartitionTagShift;
PartitionTag* tag_ptr = PartitionTagPointer(slot_start);
while (tag_count-- > 0) {
PA_DCHECK(tag == *tag_ptr);
tag_ptr++;
}
#endif
NormalBucketPartitionTagSetValue(slot_start, size, new_tag);
}
} // namespace internal
#else // No-op versions
PA_ALWAYS_INLINE PartitionTag* PartitionTagPointer(void* ptr) {
PA_NOTREACHED();
return nullptr;
}
namespace internal {
PA_ALWAYS_INLINE PartitionTag PartitionTagGetValue(void*) {
return 0;
}
PA_ALWAYS_INLINE void PartitionTagIncrementValue(uintptr_t slot_start,
size_t size) {}
} // namespace internal
#endif // defined(PA_ENABLE_MTE_CHECKED_PTR_SUPPORT_WITH_64_BITS_POINTERS)
} // namespace partition_alloc
#endif // BASE_ALLOCATOR_PARTITION_ALLOCATOR_PARTITION_TAG_H_
|
0afa93f3d3f8d78b3a5677b3108309d422142935
|
4b2a1c790afbd6561e8c3a78bed5b71aec574320
|
/modules/task_1/kustova_a_max_vector/max_vector.h
|
c70c40ade10abc8ba339ad6563adc30d48521b7f
|
[
"BSD-3-Clause"
] |
permissive
|
BoytsovVA/pp_2020_autumn_engineer
|
3deed88861a8e43950e3280e1f1c51e7c5edfd83
|
15d4048d49a5a72036ee488920670535a67a513a
|
refs/heads/master
| 2023-01-25T04:08:16.855429
| 2020-11-22T13:53:06
| 2020-11-22T13:53:06
| 305,137,409
| 1
| 0
|
BSD-3-Clause
| 2020-11-22T13:53:07
| 2020-10-18T15:47:41
| null |
UTF-8
|
C++
| false
| false
| 383
|
h
|
max_vector.h
|
// Copyright 2020 Kustova Anastasiya
#ifndef MODULES_TASK_1_KUSTOVA_A_MAX_VECTOR_MAX_VECTOR_H_
#define MODULES_TASK_1_KUSTOVA_A_MAX_VECTOR_MAX_VECTOR_H_
#include <vector>
#include <string>
std::vector<int> generateVector(int n);
int getParallelMax(std::vector<int> vec, int len);
int getLocalMax(std::vector<int> vec);
#endif // MODULES_TASK_1_KUSTOVA_A_MAX_VECTOR_MAX_VECTOR_H_
|
bde9b4557653da5e100cc76f444555313fe74563
|
3f5187228abb77300eb63a6765a9c5acaefd1f2f
|
/PA 7/Data.h
|
9b9dfc7d0968a76f349a7e1a601c460359fc5889
|
[] |
no_license
|
Jospinking/CPT_S-122
|
e7c14fbf8baaea8ad372a6daf9f2dc9901e3d577
|
be22ee2ea7d17146a7e5619bf052fc7c7a98065b
|
refs/heads/main
| 2023-01-05T13:29:37.147583
| 2020-11-09T21:46:00
| 2020-11-09T21:46:00
| 311,472,271
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 603
|
h
|
Data.h
|
#pragma once
#include <string>
#include "Stack.h"
using namespace std;
class Data
{
public:
Data(int record_number, long id, string first_name, string last_name,
string email, string units, string program, string level
) : record_number(record_number), id(id), first_name(first_name)
, last_name(last_name), email(email), units(units), program(program),
level(level), absences(0)
{}
Data() {}
int record_number;
long id;
string first_name;
string last_name;
string email;
string units;
string program;
string level;
int absences;
Stack absence_dates;
};
|
2250c1d18231a42c67e3c50e9e0afa9a615d4691
|
9a3f8c3d4afe784a34ada757b8c6cd939cac701d
|
/leetNumZeroFilledSubarr.cpp
|
637d768f991af3516aac9f37e1f728518e23f353
|
[] |
no_license
|
madhav-bits/Coding_Practice
|
62035a6828f47221b14b1d2a906feae35d3d81a8
|
f08d6403878ecafa83b3433dd7a917835b4f1e9e
|
refs/heads/master
| 2023-08-17T04:58:05.113256
| 2023-08-17T02:00:53
| 2023-08-17T02:00:53
| 106,217,648
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,900
|
cpp
|
leetNumZeroFilledSubarr.cpp
|
/*
*
//******************************************************2348. Number of Zero-Filled Subarrays.******************************************************
https://leetcode.com/problems/number-of-zero-filled-subarrays/
*******************************************************************TEST CASES:************************************************************
//These are the examples I had created, tweaked and worked on.
[1,3,0,0,2,0,0,4]
[0,0,0,2,0,0]
[2,10,2019]
[0,0,0,0,0]
[1,2,3,4,5]
[0]
[0,0]
// Time Complexity: O(n).
// Space Complexity: O(1).
//********************************************************THIS IS LEET ACCEPTED CODE.***************************************************
*/
//************************************************************Solution 1:************************************************************
//*****************************************************THIS IS LEET ACCEPTED CODE.***********************************************
// Time Complexity: O(n).
// Space Complexity: O(1).
// This algorithm is iteration based. Here, we form subarrays with zeroes and whenever we add new zero to a subarray, it forms subarrays statring from length
// [1, total #consec. zeroes] with all indices in the subarray respectively, so for every zero, we inc. the subarray length and add it to res, else we reset
// the subarray length to 0.
class Solution {
public:
long long zeroFilledSubarray(vector<int>& v) {
long long int res=0;
int len=0;
for(int i=0;i<v.size();i++) {
if(v[i]==0) len++; // Tracking #zeroes in the subarray.
else len=0;
res+=0ll+len; // Adding #zeroes as curr. index forms zeroes subarray with all indices in subarray
} // as start indices.
return res; // Returning the total #zero-filled subarrays.
}
};
|
78031a793e02405825ae6f8a3075bf14e28d34ef
|
cf56272527c1859a0c17e152a600882f4ef6fded
|
/Engine/GraphicsEngine/RasterZsiros/GraphicsApiD3D11/src/IndexBufferD3D11.cpp
|
9d1231e2b90e7b7d5fde2ccc550f1725d6927cc5
|
[] |
no_license
|
Almahmudrony/ExcessiveEngine
|
d56d29ba2d7d5fd32efdca6cec64f0e6356a0e46
|
6e4124e363bbd9ee1ebba0c20c4d71bda986f9df
|
refs/heads/master
| 2021-01-01T18:58:16.594424
| 2017-05-01T18:59:21
| 2017-05-01T18:59:21
| null | 0
| 0
| null | null | null | null |
ISO-8859-2
|
C++
| false
| false
| 901
|
cpp
|
IndexBufferD3D11.cpp
|
////////////////////////////////////////////////////////////////////////////////
// GraphicsEngine/src/IndexBufferD3D11.cpp
// 2012.oct.12, zsiroskenyer team, Péter Kardos
////////////////////////////////////////////////////////////////////////////////
// Direct3D 11 index buffer implementation
////////////////////////////////////////////////////////////////////////////////
#include "IndexBufferD3D11.h"
#include <d3d11.h>
cIndexBufferD3D11::cIndexBufferD3D11(ID3D11Buffer* buffer, size_t byteSize, eUsage usage)
:buffer(buffer), usage(usage), byteSize(byteSize) {
}
cIndexBufferD3D11::~cIndexBufferD3D11() {
buffer->Release();
}
void cIndexBufferD3D11::Release() {
delete this;
}
size_t cIndexBufferD3D11::GetByteSize() const {
return byteSize;
}
eUsage cIndexBufferD3D11::GetUsage() const {
return usage;
}
ID3D11Buffer* cIndexBufferD3D11::GetBufferPointer() const {
return buffer;
}
|
fdd5dcee3d7ce91cbc39b0d8a2006ca5c939a60a
|
309fceba389acdb74c4de9570bfc7c43427372df
|
/Project2010/Bishamon/include/ml/type/ml_basic.h
|
8b028da1296cb9960506e26de3875e85bf3c08f0
|
[] |
no_license
|
Mooliecool/DemiseOfDemon
|
29a6f329b4133310d92777a6de591e9b37beea94
|
f02f7c68d30953ddcea2fa637a8ac8f7c53fc8b9
|
refs/heads/master
| 2020-07-16T06:07:48.382009
| 2017-06-08T04:21:48
| 2017-06-08T04:21:48
| null | 0
| 0
| null | null | null | null |
SHIFT_JIS
|
C++
| false
| false
| 3,564
|
h
|
ml_basic.h
|
#ifndef LIBMATCHLOCK_INC_ML_TYPE_ML_BASIC_H
#define LIBMATCHLOCK_INC_ML_TYPE_ML_BASIC_H
#include "../utility/ml_assert.h"
namespace ml{
/// @addtogroup type
/// @{
/// @addtogroup type_basic
/// @{
typedef signed char si8; ///<8ビット符号あり整数
typedef unsigned char ui8; ///<8ビット符号なし整数
typedef signed short si16; ///<16ビット符号あり整数
typedef unsigned short ui16; ///<16ビット符号なし整数
#ifdef BM3_64
typedef signed int si32;
typedef unsigned int ui32;
#else
typedef signed long si32; ///<32ビット符号あり整数
typedef unsigned long ui32; ///<32ビット符号なし整数
#endif
#if defined(_MSC_VER)
typedef signed __int64 si64; ///<64ビット符号あり整数
typedef unsigned __int64 ui64; ///<64ビット符号なし整数
#elif defined(__MWERKS__)
typedef signed long long si64; ///<64ビット符号あり整数
typedef unsigned long long ui64; ///<63ビット符号なし整数
#elif defined(__GNUC__)
typedef signed long long si64; ///<64ビット符号あり整数
typedef unsigned long long ui64; ///<63ビット符号なし整数
#elif defined(__SNC__)
typedef signed long long si64; ///<64ビット符号あり整数
typedef unsigned long long ui64; ///<63ビット符号なし整数
#else
/// @cond internal
ML_STATIC_ASSERT(false);
/// @endcond
#endif
typedef float f32; ///<32ビット浮動小数点
typedef double f64; ///<64ビット浮動小数点
typedef ui8 min_size_basic_type; ///<最小サイズ型
typedef ui64 max_size_basic_type; ///<最大サイズ型
#ifdef BM3_64
typedef si64 ptr_size_si;
typedef ui64 ptr_size_ui;
#else
typedef si32 ptr_size_si; ///<ポインタが収まる符号あり整数
typedef ui32 ptr_size_ui; ///<ポインタが収まる符号なし整数
#endif
/// @cond internal
ML_STATIC_ASSERT(sizeof(si8) == 8 / 8);
ML_STATIC_ASSERT(sizeof(ui8) == 8 / 8);
ML_STATIC_ASSERT(sizeof(si16) == 16 / 8);
ML_STATIC_ASSERT(sizeof(ui16) == 16 / 8);
ML_STATIC_ASSERT(sizeof(si32) == 32 / 8);
ML_STATIC_ASSERT(sizeof(ui32) == 32 / 8);
ML_STATIC_ASSERT(sizeof(f32) == 32 / 8);
ML_STATIC_ASSERT(sizeof(f64) == 64 / 8);
ML_STATIC_ASSERT(sizeof(si64) == 64 / 8);
ML_STATIC_ASSERT(sizeof(ui64) == 64 / 8);
ML_STATIC_ASSERT(sizeof(ptr_size_si) >= sizeof(si8 *) );
ML_STATIC_ASSERT(sizeof(ptr_size_si) >= sizeof(ui8 *) );
ML_STATIC_ASSERT(sizeof(ptr_size_si) >= sizeof(si16 *));
ML_STATIC_ASSERT(sizeof(ptr_size_si) >= sizeof(ui16 *));
ML_STATIC_ASSERT(sizeof(ptr_size_si) >= sizeof(si32 *));
ML_STATIC_ASSERT(sizeof(ptr_size_si) >= sizeof(ui32 *));
ML_STATIC_ASSERT(sizeof(ptr_size_si) >= sizeof(f32 *) );
ML_STATIC_ASSERT(sizeof(ptr_size_si) >= sizeof(f64 *) );
ML_STATIC_ASSERT(sizeof(ptr_size_si) >= sizeof(si64 *));
ML_STATIC_ASSERT(sizeof(ptr_size_si) >= sizeof(ui64 *));
ML_STATIC_ASSERT(sizeof(ptr_size_ui) >= sizeof(si8 *) );
ML_STATIC_ASSERT(sizeof(ptr_size_ui) >= sizeof(ui8 *) );
ML_STATIC_ASSERT(sizeof(ptr_size_ui) >= sizeof(si16 *));
ML_STATIC_ASSERT(sizeof(ptr_size_ui) >= sizeof(ui16 *));
ML_STATIC_ASSERT(sizeof(ptr_size_ui) >= sizeof(si32 *));
ML_STATIC_ASSERT(sizeof(ptr_size_ui) >= sizeof(ui32 *));
ML_STATIC_ASSERT(sizeof(ptr_size_ui) >= sizeof(f32 *) );
ML_STATIC_ASSERT(sizeof(ptr_size_ui) >= sizeof(f64 *) );
ML_STATIC_ASSERT(sizeof(ptr_size_ui) >= sizeof(si64 *));
ML_STATIC_ASSERT(sizeof(ptr_size_ui) >= sizeof(ui64 *));
ML_STATIC_ASSERT(sizeof(ptr_size_si) >= sizeof(ptr_size_ui));
/// @endcond
/// @}
/// @}
} // namespace ml
#endif // #ifndef LIBMATCHLOCK_INC_ML_TYPE_ML_BASIC_H
|
ba40bab9a7b29c0f9e19c3653e8fede720bb2ed5
|
5a62a874bd207d6dd99710ec425bd67988d16cf9
|
/hello2.cpp
|
51124646d20de3ad1a4036382386093d03fcb906
|
[] |
no_license
|
yangpan3z9/OSclass
|
14ff504e6ca589eebd0ff098a46db95abd8199a2
|
506e1cc36832464ac612bbe501a16d024b675d97
|
refs/heads/master
| 2022-12-14T01:46:31.480571
| 2020-09-08T18:27:03
| 2020-09-08T18:27:03
| 293,823,774
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 110
|
cpp
|
hello2.cpp
|
// C++ test
#include <iostream>
int main()
{
std::cout <<" Hello c++ file test"<<std::endl;
return 0;
}
|
298438e744495decd1587224b8c54d2a5827460b
|
837f6e6d06a50699b829581fd8681c2c9c942de0
|
/SPlisHSPlasH/NonPressureForceBase.cpp
|
ed1dc6cc2905e7899f46aa3a56335796feaa422f
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
InteractiveComputerGraphics/SPlisHSPlasH
|
75cb0428ed00db48b8720a6c9f7aef8f4b3654d2
|
8454e9f454fef20771dfe98d318904da62764b4c
|
refs/heads/master
| 2023-08-25T00:28:23.170422
| 2023-08-21T10:30:34
| 2023-08-21T10:30:34
| 74,058,995
| 1,376
| 305
|
MIT
| 2023-08-17T14:36:21
| 2016-11-17T19:14:23
|
C++
|
UTF-8
|
C++
| false
| false
| 256
|
cpp
|
NonPressureForceBase.cpp
|
#include "NonPressureForceBase.h"
using namespace SPH;
NonPressureForceBase::NonPressureForceBase(FluidModel *model)
{
m_model = model;
}
NonPressureForceBase::~NonPressureForceBase(void)
{
}
void NonPressureForceBase::init()
{
initParameters();
}
|
3cbe147c6b16c02131f97953b1897000b1b8db31
|
8c31c25cc687fa8d0f2de029ce8df4dfb7199d26
|
/Basic_Pat/1071.cpp
|
265c8eeeba6a262e756ad70f5d241076cb59a1f6
|
[] |
no_license
|
yuyilei/Pat_Basic_Level
|
6cc0be2de73de052f7ea655957b67388bed4e178
|
ac5534bb2cd979dbcf2a7b89fd1c92a97e980ac9
|
refs/heads/master
| 2021-09-10T04:21:03.890757
| 2018-03-21T00:44:35
| 2018-03-21T00:44:35
| 73,559,535
| 5
| 4
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 750
|
cpp
|
1071.cpp
|
#include<cstdio>
#include<iostream>
using namespace std ;
int main() {
int all , m , n1 , n2 , b , t ;
cin >> all >> m ;
for ( int i = 0 ; i < m ; i++ ){
cin >> n1 >> b >> t >> n2 ;
if ( all <= 0 ) {
cout << "Game Over." << endl ;
return 0 ;
}
if ( t > all )
cout << "Not enough tokens. Total = " << all << "." << endl ;
else if (((n1 > n2 )&& b == 0 )|| ((n1 < n2 ) && b == 1 ) ) {
all += t ;
cout << "Win " << t << "! " << "Total = " << all << "." << endl ;
}
else {
all -= t ;
cout << "Lose " << t << ". " << "Total = " << all << "." << endl ;
}
}
return 0 ;
}
|
65db2a7d476f5c913675f06eeb4f37f875afb022
|
422a0e7a01814d9b6843e08d1e3deb7f4ae24b23
|
/MarketSimulation/market.h
|
24baae8ab4a794804820b147258063d9bb2fa223
|
[] |
no_license
|
logworthy/marketsim
|
876d4d15690f1447f5982a2a2309831d940f1dd8
|
cbb84d5758e03ace21a58cde777db75ad6ada09e
|
refs/heads/master
| 2020-04-05T23:46:49.624159
| 2013-09-03T11:01:30
| 2013-09-03T11:01:30
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,762
|
h
|
market.h
|
#ifndef MARKET_H
#define MARKET_H
#include <QObject>
#include <QTimer>
#include <QFile>
#include <QTime>
class Market : public QObject
{
Q_OBJECT
public:
explicit Market(QString storedPathFile, QObject *parent = 0,
int evolveTimeMS = 5000);
virtual ~Market();
double getPrice1();
double getPrice2();
double getWealth();
double getAllocation();
double getIndex();
double getIndexChange();
void updateAllocation(double newAllocation);
void recordData(bool async, bool simWindow = true);
void startMarket();
const static int EXPERIMENT_RUNNING_TIME = 60*30; // seconds to run simulation
QTime* experimentTime;
signals:
void priceChange(double time);
void newTime(QString);
void allocationUpdated(double amtToAsset1);
public slots:
private:
bool usingStoredPath;
double price1;
double mu1;
double sigma1;
double price2;
double mu2;
double sigma2;
double dt;
double allocation;
double shares1;
double shares2;
double wealth;
double startingAvgPrice;
double lastAvgPrice;
QTimer* timeTimer;
QTimer* evolveTimer;
QFile* storedPath;
QFile* logFile;
QFile* swapLogFile;
QFile* simLogFile;
std::pair<double, double> dWienerSample();
std::pair<double, double> stdNormalSample();
void loadNextPriceFromFile();
private slots:
void updatePrice();
void updateTime();
};
#endif // MARKET_H
|
a851e73411ab28306074c1f34d8f843bc267a40f
|
e23a4f57ce5474d468258e5e63b9e23fb6011188
|
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Stack/155_MinStack.cpp
|
4e86610364d3f1512c2d175d86dc30b173669d76
|
[] |
no_license
|
syurskyi/Python_Topics
|
52851ecce000cb751a3b986408efe32f0b4c0835
|
be331826b490b73f0a176e6abed86ef68ff2dd2b
|
refs/heads/master
| 2023-06-08T19:29:16.214395
| 2023-05-29T17:09:11
| 2023-05-29T17:09:11
| 220,583,118
| 3
| 2
| null | 2023-02-16T03:08:10
| 2019-11-09T02:58:47
|
Python
|
UTF-8
|
C++
| false
| false
| 511
|
cpp
|
155_MinStack.cpp
|
/*
* @Author: xuezaigds@gmail.com
* @Last Modified time: 2016-04-15 16:10:01
*/
class MinStack {
public:
void push(int x) {
data.push(x);
if(min_n.empty() || x <= getMin()){
min_n.push(x);
}
}
void pop() {
if(top() == getMin()){
min_n.pop();
}
data.pop();
}
int top() {
return data.top();
}
int getMin() {
return min_n.top();
}
private:
stack<int> data;
stack<int> min_n;
};
|
4ae4e7cb13306b09bb66f4ef635d76b67b660aa7
|
3492a5933604f2057f8a035f6f68931936b05175
|
/arith/coder.h
|
ea66e25ffdfae5a331cdbd863c46eef8a8b0b40b
|
[
"BSD-3-Clause"
] |
permissive
|
bl4ck1c3/harry
|
eacd2ec1a948efb9267a02db78cedf2192bcce79
|
a69429b6a6a573df22fa105b02914a1ac2b21bf0
|
refs/heads/master
| 2020-03-12T15:12:23.763716
| 2018-04-17T11:47:06
| 2018-04-17T11:47:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,133
|
h
|
coder.h
|
/*
* Copyright (C) 2017, Max von Buelow
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD 3-Clause license. See the LICENSE.txt file for details.
*/
/*
* Implementation of an Arithmetic Coder.
*
* Related publications:
* Moffat, Alistair, Radford M. Neal, and Ian H. Witten. "Arithmetic coding revisited." ACM Transactions on Information Systems (TOIS) 16.3 (1998): 256-294.
*/
#pragma once
#include <stdint.h>
#include <algorithm>
#include <istream>
#include <ostream>
#include "bitstream.h"
namespace arith {
template <typename TF = uint64_t>
struct Coder {
typedef TF FreqType;
static const int b = sizeof(TF) * 8;
static const TF HALF = TF(1) << (b - 1);
static const TF QUARTER = TF(1) << (b - 2);
};
template <typename TF = uint64_t, typename TBO = uint64_t>
struct Encoder : Coder<TF> {
using Coder<TF>::b;
using Coder<TF>::HALF;
using Coder<TF>::QUARTER;
TF L, R; // L = low, R = range
TBO bits_outstanding;
bitostream os;
bool flushed;
Encoder(std::ostream &_os) : os(_os), L(0), R(HALF), bits_outstanding(0), flushed(false)
{}
~Encoder()
{
flush();
}
Encoder(const Encoder&) = delete;
Encoder &operator=(const Encoder&) = delete;
void flush()
{
if (flushed) return;
flushed = true;
for (int i = b - 1; i >= 0; --i) {
bit_plus_follow((L >> i) & 1);
}
os.flush();
}
void operator()(TF l, TF h, TF t)
{
TF r = R / t;
L = L + r * l;
if (h < t)
R = r * (h - l);
else
R = R - r * l;
while (R <= QUARTER) {
if (L <= HALF && L + R <= HALF) {
bit_plus_follow(0);
} else if (L >= HALF) {
bit_plus_follow(1);
L -= HALF;
} else {
++bits_outstanding;
L -= QUARTER;
}
L *= 2;
R *= 2;
}
}
template <typename S>
void operator()(S &freq, typename S::SymType s)
{
TF l, h, t = freq.total();
freq.range(s, l, h);
(*this)(l, h, t);
}
private:
void write_one_bit(unsigned char bit)
{
os << bit;
}
void bit_plus_follow(unsigned char x)
{
write_one_bit(x);
while (bits_outstanding > 0) {
write_one_bit(!x);
--bits_outstanding;
}
}
};
template <typename TF = uint64_t>
struct Decoder : Coder<TF> {
using Coder<TF>::b;
using Coder<TF>::HALF;
using Coder<TF>::QUARTER;
TF R, D, r; // R = range
bitistream is;
Decoder(std::istream &_is) : is(_is), R(HALF), D(0)
{
for (int i = 0; i < b; ++i) {
D = 2 * D + read_one_bit();
}
}
Decoder(const Decoder&) = delete;
Decoder &operator=(const Decoder&) = delete;
TF decode_target(TF t)
{
r = R / t;
return std::min(t - 1, D / r);
}
void operator()(TF l, TF h, TF t)
{
// r already set by decode_target
D = D - r * l;
if (h < t)
R = r * (h - l);
else
R = R - r * l;
while (R <= QUARTER) {
R *= 2;
D = 2 * D + read_one_bit();
}
}
template <typename S>
typename S::SymType operator()(S &freq)
{
TF l, h, t = freq.total();
TF target = decode_target(t);
typename S::SymType s = freq.symbol(target, l, h);
(*this)(l, h, t);
return s;
}
private:
unsigned char read_one_bit()
{
unsigned char bit;
is >> bit;
return bit;
}
};
}
|
6c2e1cc96f294c3a6fc0c3f798771aa270175910
|
0bc8ede923979fe128fb285ff078ea49fa3879fa
|
/src/jpp/Jeep/JPrint.hh
|
cad2b94f2d463cdba557adf9a6901848b74cb241
|
[
"MIT"
] |
permissive
|
KM3NeT/jppy
|
2f70ccab27352ea905d14f8ba01db449a8143929
|
609aee22d2097d7218f0125dbb4c82bf39099ef7
|
refs/heads/master
| 2022-11-23T20:39:55.149023
| 2022-11-07T08:22:19
| 2022-11-07T08:22:19
| 243,485,643
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,472
|
hh
|
JPrint.hh
|
#ifndef __JEEP__JPRINT__
#define __JEEP__JPRINT__
#include <string>
#include <ostream>
#include <sstream>
#include <iomanip>
#include "JLang/JManip.hh"
#include "Jeep/JStreamToolkit.hh"
/**
* \file
* I/O formatting auxiliaries.
* \author mdejong
*/
namespace JEEP {}
namespace JPP { using namespace JEEP; }
namespace JEEP {
/**
* Get output stream for conversion to std::string.
*
* Note that the stream is emptied before use.
*
* \return output stream
*/
inline std::ostream& getOstream()
{
static std::ostringstream buffer;
buffer.str("");
return buffer;
}
/**
* Get output C-string.
*
* Note that this method is needed to guarentee livetime of underlying std::string.
*
* \param input input
* \return C-string
*/
inline const char* getCString(const std::string& input)
{
static std::string buffer;
buffer = input;
return buffer.c_str();
}
}
/**
* Auxiliary data structure for streaming of STL containers.
*
* This manipulator transfers the following stream operation to method JEEP::writeObject
* so that all STL containers can directly be printed.
*/
struct JEEPZ
{
protected:
/**
* Auxiliary class for format STL containers.
*/
struct JStream
{
/**
* Constructor.
*
* \param out output stream
*/
JStream(std::ostream& out) :
out(out)
{}
/**
* Write value to output stream.
*
* \param value value
* \return this JSTDStreamer
*/
template<class T>
std::ostream& operator<<(const T& value)
{
return JEEP::writeObject(out, value);
}
private:
std::ostream& out;
};
public:
/**
* Default constructor.
*/
JEEPZ()
{}
/**
* Format specifier.
*
* \param out output stream
* \param format format
* \return output stream
*/
friend inline JStream operator<<(std::ostream& out, const JEEPZ& format)
{
return JStream(out);
}
};
/**
* Make string.
*
* \param A std::ostream compatible construct
* \return std::string
*/
#define MAKE_STRING(A) (static_cast<std::ostringstream&>(JEEP::getOstream() << A << std::flush)).str()
/**
* Make C-string.
*
* \param A std::ostream compatible construct
* \return C-string
*/
#define MAKE_CSTRING(A) JEEP::getCString(MAKE_STRING(A))
#endif
|
6ac75e94c99b9bf7ed2017a6749c5398a55f0ca9
|
33be137cc86b78bce45820fc81383b0784b69c36
|
/sources/arquade/game/g_monster.cpp
|
9bc5dbb7f6f28f94167a12ed1768cf73c38533ab
|
[] |
no_license
|
Paril/quake2-source-archive
|
010d9758448ae61442d7d12a7198d4c4874665d4
|
6eb7a72cd2187dc0caef151f9af5e6f4b090dd8a
|
refs/heads/main
| 2023-07-12T16:50:16.098868
| 2021-08-22T12:30:00
| 2021-08-22T12:30:00
| 341,576,903
| 10
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 17,631
|
cpp
|
g_monster.cpp
|
/*
Copyright (C) 1997-2001 Id Software, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "g_local.h"
//
// monster weapons
//
//FIXME mosnters should call these with a totally accurate direction
// and we can mess it up based on skill. Spread should be for normal
// and we can tighten or loosen based on skill. We could muck with
// the damages too, but I'm not sure that's such a good idea.
void monster_fire_bullet (edict_t *self, vec3_t start, vec3_t dir, int damage, int kick, int hspread, int vspread, int flashtype)
{
fire_bullet (self, start, dir, damage, kick, hspread, vspread, MOD_UNKNOWN);
gi.WriteByte (SVC_MUZZLEFLASH2);
gi.WriteShort (self - g_edicts);
gi.WriteByte (flashtype);
gi.multicast (start, MULTICAST_PVS);
}
void monster_fire_shotgun (edict_t *self, vec3_t start, vec3_t aimdir, int damage, int kick, int hspread, int vspread, int count, int flashtype)
{
fire_shotgun (self, start, aimdir, damage, kick, hspread, vspread, count, MOD_UNKNOWN);
gi.WriteByte (SVC_MUZZLEFLASH2);
gi.WriteShort (self - g_edicts);
gi.WriteByte (flashtype);
gi.multicast (start, MULTICAST_PVS);
}
void monster_fire_blaster (edict_t *self, vec3_t start, vec3_t dir, int damage, int speed, int flashtype, int effect)
{
fire_blaster (self, start, dir, damage, speed, effect, false);
gi.WriteByte (SVC_MUZZLEFLASH2);
gi.WriteShort (self - g_edicts);
gi.WriteByte (flashtype);
gi.multicast (start, MULTICAST_PVS);
}
void monster_fire_grenade (edict_t *self, vec3_t start, vec3_t aimdir, int damage, int speed, int flashtype)
{
fire_grenade (self, start, aimdir, damage, speed, 2.5, damage+40);
gi.WriteByte (SVC_MUZZLEFLASH2);
gi.WriteShort (self - g_edicts);
gi.WriteByte (flashtype);
gi.multicast (start, MULTICAST_PVS);
}
void monster_fire_rocket (edict_t *self, vec3_t start, vec3_t dir, int damage, int speed, int flashtype)
{
fire_rocket (self, start, dir, damage, speed, damage+20, damage);
gi.WriteByte (SVC_MUZZLEFLASH2);
gi.WriteShort (self - g_edicts);
gi.WriteByte (flashtype);
gi.multicast (start, MULTICAST_PVS);
}
void monster_fire_railgun (edict_t *self, vec3_t start, vec3_t aimdir, int damage, int kick, int flashtype)
{
fire_rail (self, start, aimdir, damage, kick);
gi.WriteByte (SVC_MUZZLEFLASH2);
gi.WriteShort (self - g_edicts);
gi.WriteByte (flashtype);
gi.multicast (start, MULTICAST_PVS);
}
void monster_fire_bfg (edict_t *self, vec3_t start, vec3_t aimdir, int damage, int speed, int kick, float damage_radius, int flashtype)
{
fire_bfg (self, start, aimdir, damage, speed, damage_radius);
gi.WriteByte (SVC_MUZZLEFLASH2);
gi.WriteShort (self - g_edicts);
gi.WriteByte (flashtype);
gi.multicast (start, MULTICAST_PVS);
}
//
// Monster utility functions
//
static void M_FliesOff (edict_t *self)
{
self->s.effects &= ~EF_FLIES;
self->s.sound = 0;
}
static void M_FliesOn (edict_t *self)
{
if (self->waterlevel)
return;
self->s.effects |= EF_FLIES;
self->s.sound = gi.soundindex ("infantry/inflies1.wav");
self->think = M_FliesOff;
self->nextthink = level.time + 60;
}
void M_FlyCheck (edict_t *self)
{
if (self->waterlevel)
return;
if (random() > 0.5)
return;
self->think = M_FliesOn;
self->nextthink = level.time + 5 + 10 * random();
}
void AttackFinished (edict_t *self, float time)
{
self->monsterinfo.attack_finished = level.time + time;
}
void M_CheckGround (edict_t *ent)
{
vec3_t point;
cmTrace_t trace;
if (ent->flags & (FL_SWIM|FL_FLY))
return;
if (ent->velocity[2] > 100)
{
ent->groundentity = NULL;
return;
}
// if the hull point one-quarter unit down is solid the entity is on ground
point[0] = ent->s.origin[0];
point[1] = ent->s.origin[1];
point[2] = ent->s.origin[2] - 0.25;
trace = gi.trace (ent->s.origin, ent->mins, ent->maxs, point, ent, CONTENTS_MASK_MONSTERSOLID);
// check steepness
if ( trace.plane.normal[2] < 0.7 && !trace.startSolid)
{
ent->groundentity = NULL;
return;
}
// ent->groundentity = trace.ent;
// ent->groundentity_linkcount = trace.ent->linkcount;
// if (!trace.startsolid && !trace.allsolid)
// Vec3Copy (trace.endpos, ent->s.origin);
if (!trace.startSolid && !trace.allSolid)
{
Vec3Copy (trace.endPos, ent->s.origin);
ent->groundentity = trace.ent;
ent->groundentity_linkcount = trace.ent->linkCount;
ent->velocity[2] = 0;
}
}
void M_CatagorizePosition (edict_t *ent)
{
vec3_t point;
int cont;
//
// get waterlevel
//
point[0] = ent->s.origin[0];
point[1] = ent->s.origin[1];
point[2] = ent->s.origin[2] + ent->mins[2] + 1;
cont = gi.pointcontents (point);
if (!(cont & CONTENTS_MASK_WATER))
{
ent->waterlevel = 0;
ent->watertype = 0;
return;
}
ent->watertype = cont;
ent->waterlevel = 1;
point[2] += 26;
cont = gi.pointcontents (point);
if (!(cont & CONTENTS_MASK_WATER))
return;
ent->waterlevel = 2;
point[2] += 22;
cont = gi.pointcontents (point);
if (cont & CONTENTS_MASK_WATER)
ent->waterlevel = 3;
}
void M_WorldEffects (edict_t *ent)
{
int dmg;
if (ent->health > 0)
{
if (!(ent->flags & FL_SWIM))
{
if (ent->waterlevel < 3)
{
ent->air_finished = level.time + 12;
}
else if (ent->air_finished < level.time)
{ // drown!
if (ent->pain_debounce_time < level.time)
{
dmg = 2 + 2 * floor(level.time - ent->air_finished);
if (dmg > 15)
dmg = 15;
T_Damage (ent, world, world, vec3Origin, ent->s.origin, vec3Origin, dmg, 0, DAMAGE_NO_ARMOR, MOD_WATER);
ent->pain_debounce_time = level.time + 1;
}
}
}
else
{
if (ent->waterlevel > 0)
{
ent->air_finished = level.time + 9;
}
else if (ent->air_finished < level.time)
{ // suffocate!
if (ent->pain_debounce_time < level.time)
{
dmg = 2 + 2 * floor(level.time - ent->air_finished);
if (dmg > 15)
dmg = 15;
T_Damage (ent, world, world, vec3Origin, ent->s.origin, vec3Origin, dmg, 0, DAMAGE_NO_ARMOR, MOD_WATER);
ent->pain_debounce_time = level.time + 1;
}
}
}
}
if (ent->waterlevel == 0)
{
if (ent->flags & FL_INWATER)
{
gi.sound (ent, CHAN_BODY, gi.soundindex("player/watr_out.wav"), 1, ATTN_NORM, 0);
ent->flags &= ~FL_INWATER;
}
return;
}
if ((ent->watertype & CONTENTS_LAVA) && !(ent->flags & FL_IMMUNE_LAVA))
{
if (ent->damage_debounce_time < level.time)
{
ent->damage_debounce_time = level.time + 0.2;
T_Damage (ent, world, world, vec3Origin, ent->s.origin, vec3Origin, 10*ent->waterlevel, 0, 0, MOD_LAVA);
}
}
if ((ent->watertype & CONTENTS_SLIME) && !(ent->flags & FL_IMMUNE_SLIME))
{
if (ent->damage_debounce_time < level.time)
{
ent->damage_debounce_time = level.time + 1;
T_Damage (ent, world, world, vec3Origin, ent->s.origin, vec3Origin, 4*ent->waterlevel, 0, 0, MOD_SLIME);
}
}
if ( !(ent->flags & FL_INWATER) )
{
if (!(ent->svFlags & SVF_DEADMONSTER))
{
if (ent->watertype & CONTENTS_LAVA)
if (random() <= 0.5)
gi.sound (ent, CHAN_BODY, gi.soundindex("player/lava1.wav"), 1, ATTN_NORM, 0);
else
gi.sound (ent, CHAN_BODY, gi.soundindex("player/lava2.wav"), 1, ATTN_NORM, 0);
else if (ent->watertype & CONTENTS_SLIME)
gi.sound (ent, CHAN_BODY, gi.soundindex("player/watr_in.wav"), 1, ATTN_NORM, 0);
else if (ent->watertype & CONTENTS_WATER)
gi.sound (ent, CHAN_BODY, gi.soundindex("player/watr_in.wav"), 1, ATTN_NORM, 0);
}
ent->flags |= FL_INWATER;
ent->damage_debounce_time = 0;
}
}
void M_droptofloor (edict_t *ent)
{
vec3_t end;
cmTrace_t trace;
ent->s.origin[2] += 1;
Vec3Copy (ent->s.origin, end);
end[2] -= 256;
trace = gi.trace (ent->s.origin, ent->mins, ent->maxs, end, ent, CONTENTS_MASK_MONSTERSOLID);
if (trace.fraction == 1 || trace.allSolid)
return;
Vec3Copy (trace.endPos, ent->s.origin);
gi.linkentity (ent);
M_CheckGround (ent);
M_CatagorizePosition (ent);
}
void M_SetEffects (edict_t *ent)
{
ent->s.effects &= ~(EF_COLOR_SHELL|EF_POWERSCREEN);
ent->s.renderFx &= ~(RF_SHELL_RED|RF_SHELL_GREEN|RF_SHELL_BLUE);
if (ent->monsterinfo.aiflags & AI_RESURRECTING)
{
ent->s.effects |= EF_COLOR_SHELL;
ent->s.renderFx |= RF_SHELL_RED;
}
if (ent->health <= 0)
return;
if (ent->powerarmor_time > level.time)
{
if (ent->monsterinfo.power_armor_type == POWER_ARMOR_SCREEN)
{
ent->s.effects |= EF_POWERSCREEN;
}
else if (ent->monsterinfo.power_armor_type == POWER_ARMOR_SHIELD)
{
ent->s.effects |= EF_COLOR_SHELL;
ent->s.renderFx |= RF_SHELL_GREEN;
}
}
}
void M_MoveFrame (edict_t *self)
{
mmove_t *move;
int index;
move = self->monsterinfo.currentmove;
self->nextthink = level.time + FRAMETIME;
if ((self->monsterinfo.nextframe) && (self->monsterinfo.nextframe >= move->firstframe) && (self->monsterinfo.nextframe <= move->lastframe))
{
self->s.frame = self->monsterinfo.nextframe;
self->monsterinfo.nextframe = 0;
}
else
{
if (self->s.frame == move->lastframe)
{
if (move->endfunc)
{
move->endfunc (self);
// regrab move, endfunc is very likely to change it
move = self->monsterinfo.currentmove;
// check for death
if (self->svFlags & SVF_DEADMONSTER)
return;
}
}
if (self->s.frame < move->firstframe || self->s.frame > move->lastframe)
{
self->monsterinfo.aiflags &= ~AI_HOLD_FRAME;
self->s.frame = move->firstframe;
}
else
{
if (!(self->monsterinfo.aiflags & AI_HOLD_FRAME))
{
self->s.frame++;
if (self->s.frame > move->lastframe)
self->s.frame = move->firstframe;
}
}
}
index = self->s.frame - move->firstframe;
if (move->frame[index].aifunc)
if (!(self->monsterinfo.aiflags & AI_HOLD_FRAME))
move->frame[index].aifunc (self, move->frame[index].dist * self->monsterinfo.scale);
else
move->frame[index].aifunc (self, 0);
if (move->frame[index].thinkfunc)
move->frame[index].thinkfunc (self);
}
void monster_think (edict_t *self)
{
M_MoveFrame (self);
if (self->linkCount != self->monsterinfo.linkcount)
{
self->monsterinfo.linkcount = self->linkCount;
M_CheckGround (self);
}
M_CatagorizePosition (self);
M_WorldEffects (self);
M_SetEffects (self);
}
/*
================
monster_use
Using a monster makes it angry at the current activator
================
*/
void monster_use (edict_t *self, edict_t *other, edict_t *activator)
{
if (self->enemy)
return;
if (self->health <= 0)
return;
if (activator->flags & FL_NOTARGET)
return;
if (!(activator->client) && !(activator->monsterinfo.aiflags & AI_GOOD_GUY))
return;
// delay reaction so if the monster is teleported, its sound is still heard
self->enemy = activator;
FoundTarget (self);
}
void monster_start_go (edict_t *self);
void monster_triggered_spawn (edict_t *self)
{
self->s.origin[2] += 1;
KillBox (self);
self->solid = SOLID_BBOX;
self->movetype = MOVETYPE_STEP;
self->svFlags &= ~SVF_NOCLIENT;
self->air_finished = level.time + 12;
gi.linkentity (self);
monster_start_go (self);
if (self->enemy && !(self->spawnflags & 1) && !(self->enemy->flags & FL_NOTARGET))
{
FoundTarget (self);
}
else
{
self->enemy = NULL;
}
}
void monster_triggered_spawn_use (edict_t *self, edict_t *other, edict_t *activator)
{
// we have a one frame delay here so we don't telefrag the guy who activated us
self->think = monster_triggered_spawn;
self->nextthink = level.time + FRAMETIME;
if (activator->client)
self->enemy = activator;
self->use = monster_use;
}
void monster_triggered_start (edict_t *self)
{
self->solid = SOLID_NOT;
self->movetype = MOVETYPE_NONE;
self->svFlags |= SVF_NOCLIENT;
self->nextthink = 0;
self->use = monster_triggered_spawn_use;
}
/*
================
monster_death_use
When a monster dies, it fires all of its targets with the current
enemy as activator.
================
*/
void monster_death_use (edict_t *self)
{
self->flags &= ~(FL_FLY|FL_SWIM);
self->monsterinfo.aiflags &= AI_GOOD_GUY;
if (self->item)
{
Drop_Item (self, self->item);
self->item = NULL;
}
if (self->deathtarget)
self->target = self->deathtarget;
if (!self->target)
return;
G_UseTargets (self, self->enemy);
}
//============================================================================
bool monster_start (edict_t *self)
{
if (deathmatch->floatVal && !allowDMMonsters)
{
G_FreeEdict (self);
return false;
}
if ((self->spawnflags & 4) && !(self->monsterinfo.aiflags & AI_GOOD_GUY))
{
self->spawnflags &= ~4;
self->spawnflags |= 1;
// gi.dprintf("fixed spawnflags on %s at %s\n", self->classname, vtos(self->s.origin));
}
if (!(self->monsterinfo.aiflags & AI_GOOD_GUY))
level.total_monsters++;
self->nextthink = level.time + FRAMETIME;
self->svFlags |= SVF_MONSTER;
self->s.renderFx |= RF_FRAMELERP;
self->takedamage = DAMAGE_AIM;
self->air_finished = level.time + 12;
self->use = monster_use;
self->max_health = self->health;
self->clipMask = CONTENTS_MASK_MONSTERSOLID;
self->s.skinNum = 0;
self->deadflag = DEAD_NO;
self->svFlags &= ~SVF_DEADMONSTER;
if (!self->monsterinfo.checkattack)
self->monsterinfo.checkattack = M_CheckAttack;
Vec3Copy (self->s.origin, self->s.oldOrigin);
if (st.item)
{
self->item = FindItemByClassname (st.item);
if (!self->item)
gi.dprintf("%s at %s has bad item: %s\n", self->classname, vtos(self->s.origin), st.item);
}
// randomize what frame they start on
if (self->monsterinfo.currentmove)
self->s.frame = self->monsterinfo.currentmove->firstframe + (rand() % (self->monsterinfo.currentmove->lastframe - self->monsterinfo.currentmove->firstframe + 1));
return true;
}
void monster_start_go (edict_t *self)
{
vec3_t v;
if (self->health <= 0)
return;
// check for target to combat_point and change to combattarget
if (self->target)
{
bool notcombat;
bool fixup;
edict_t *target;
target = NULL;
notcombat = false;
fixup = false;
while ((target = G_Find (target, FOFS(targetname), self->target)) != NULL)
{
if (strcmp(target->classname, "point_combat") == 0)
{
self->combattarget = self->target;
fixup = true;
}
else
{
notcombat = true;
}
}
if (notcombat && self->combattarget)
gi.dprintf("%s at %s has target with mixed types\n", self->classname, vtos(self->s.origin));
if (fixup)
self->target = NULL;
}
// validate combattarget
if (self->combattarget)
{
edict_t *target;
target = NULL;
while ((target = G_Find (target, FOFS(targetname), self->combattarget)) != NULL)
{
if (strcmp(target->classname, "point_combat") != 0)
{
gi.dprintf("%s at (%i %i %i) has a bad combattarget %s : %s at (%i %i %i)\n",
self->classname, (int)self->s.origin[0], (int)self->s.origin[1], (int)self->s.origin[2],
self->combattarget, target->classname, (int)target->s.origin[0], (int)target->s.origin[1],
(int)target->s.origin[2]);
}
}
}
if (self->target)
{
self->goalentity = self->movetarget = G_PickTarget(self->target);
if (!self->movetarget)
{
gi.dprintf ("%s can't find target %s at %s\n", self->classname, self->target, vtos(self->s.origin));
self->target = NULL;
self->monsterinfo.pausetime = 100000000;
self->monsterinfo.stand (self);
}
else if (strcmp (self->movetarget->classname, "path_corner") == 0)
{
Vec3Subtract (self->goalentity->s.origin, self->s.origin, v);
self->ideal_yaw = self->s.angles[YAW] = VecToYaw(v);
self->monsterinfo.walk (self);
self->target = NULL;
}
else
{
self->goalentity = self->movetarget = NULL;
self->monsterinfo.pausetime = 100000000;
self->monsterinfo.stand (self);
}
}
else
{
self->monsterinfo.pausetime = 100000000;
self->monsterinfo.stand (self);
}
self->think = monster_think;
self->nextthink = level.time + FRAMETIME;
}
void walkmonster_start_go (edict_t *self)
{
if (!(self->spawnflags & 2) && level.time < 1)
{
M_droptofloor (self);
if (self->groundentity)
if (!M_walkmove (self, 0, 0))
gi.dprintf ("%s in solid at %s\n", self->classname, vtos(self->s.origin));
}
if (!self->yaw_speed)
self->yaw_speed = 20;
self->viewheight = 25;
monster_start_go (self);
if (self->spawnflags & 2)
monster_triggered_start (self);
}
void walkmonster_start (edict_t *self)
{
self->think = walkmonster_start_go;
monster_start (self);
}
void flymonster_start_go (edict_t *self)
{
if (!M_walkmove (self, 0, 0))
gi.dprintf ("%s in solid at %s\n", self->classname, vtos(self->s.origin));
if (!self->yaw_speed)
self->yaw_speed = 10;
self->viewheight = 25;
monster_start_go (self);
if (self->spawnflags & 2)
monster_triggered_start (self);
}
void flymonster_start (edict_t *self)
{
self->flags |= FL_FLY;
self->think = flymonster_start_go;
monster_start (self);
}
void swimmonster_start_go (edict_t *self)
{
if (!self->yaw_speed)
self->yaw_speed = 10;
self->viewheight = 10;
monster_start_go (self);
if (self->spawnflags & 2)
monster_triggered_start (self);
}
void swimmonster_start (edict_t *self)
{
self->flags |= FL_SWIM;
self->think = swimmonster_start_go;
monster_start (self);
}
|
a72b6c943e1d11d481ae634a01b6e8b29d2e2928
|
3b430b359fbfc65fecf9096a7b8466d1e5847aaf
|
/TorusRadiusMajorResize.cpp
|
5c2f3105ddd3d08fe653c1d01cfd89f029df07ea
|
[] |
no_license
|
neilforrest/protohaptic
|
084d094da8558e10a0c7826493c1888b9aad8387
|
7556b07863caea90721d9b30cf98976d1640e801
|
refs/heads/master
| 2016-09-06T04:15:42.727421
| 2015-01-23T23:37:05
| 2015-01-23T23:37:05
| 33,373,753
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,727
|
cpp
|
TorusRadiusMajorResize.cpp
|
#include "stdafx.h"
#include "TorusRadiusMajorResize.h"
/** Construct a new radius transformation on given shape.
(x, y, z) is the starting position of the proxy */
CTorusRadiusMajorResize::CTorusRadiusMajorResize(CTorus *torus, HLdouble x, HLdouble y, HLdouble z)
{
m_shape= torus;
m_proxyStartPos[0]= x;
m_proxyStartPos[1]= y;
m_proxyStartPos[2]= z;
}
/** Set the current position of the proxy.
The shape under control will be transformed accordingly */
void CTorusRadiusMajorResize::setProxyPos(HLdouble x, HLdouble y, HLdouble z)
{
double A[3][3]= {
{ m_shape->getRotation()[0], m_shape->getRotation()[1], m_shape->getRotation()[2] },
{ m_shape->getRotation()[4], m_shape->getRotation()[5], m_shape->getRotation()[6] },
{ m_shape->getRotation()[8], m_shape->getRotation()[9], m_shape->getRotation()[10] } };
double pV[3]= { x-m_shape->getLocationX(),
y-m_shape->getLocationY(),
z-m_shape->getLocationZ() };
double rV[3]= { pV[0]*A[0][0] + pV[1]*A[0][1]+ pV[2]*A[0][2],
pV[0]*A[1][0] + pV[1]*A[1][1]+ pV[2]*A[1][2],
pV[0]*A[2][0] + pV[1]*A[2][1]+ pV[2]*A[2][2] };
float delta_ratio= (float)(rV[0])/m_shape->getSizeX();
((CTorus*)m_shape)->setRadiusMajor ( delta_ratio );
}
/** Returns an integer constant representing the type of transformation (i.e. ratio)
See Transform.h for a list of possible values */
int CTorusRadiusMajorResize::getType()
{
return TRANSFORM_TORUS_RADIUS_RESIZE_MAJOR;
}
/** Destroy the ratio transform */
CTorusRadiusMajorResize::~CTorusRadiusMajorResize()
{
}
/** Returns the shape being transformed */
CShape* CTorusRadiusMajorResize::getShape()
{
return m_shape;
}
|
0dc28c02d4872f19d43e38766b2790d256f5c8bf
|
ee69c1ff209333ab6a27297c2a749611b00a758a
|
/Patient.h
|
a681e4f7642ee0e338526cef245761a93f93ec15
|
[] |
no_license
|
JayPatel77470/covid-data-project
|
7ca4c364e50f78c7d724c5ada311ba1e70f50f8a
|
363eca0c89b5dcc58ba2b4c6302f0ba323cae570
|
refs/heads/main
| 2023-08-03T02:43:27.205903
| 2021-09-20T16:30:49
| 2021-09-20T16:30:49
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,453
|
h
|
Patient.h
|
/* Citation and Sources...
Final Project Milestone 5
Module: Patient
Filename: Patient.cpp
Version 1.0
Author Jay Girishkumar Patel
Revision History
-----------------------------------------------------------
Date Reason
2021/07/04 Preliminary release
2021/07/18 Created this module
-----------------------------------------------------------
I have done all the coding by myself and only copied the code
that my professor provided to complete my workshops and assignments.
-----------------------------------------------------------
*/
#ifndef PATIENT_H_
#define PATIENT_H_
#include "IOAble.h"
#include "Ticket.h"
#include "utils.h"
#include <fstream>
namespace sdds {
class Patient : public IOAble{
char* m_name;
int m_OHIPNumber;
Ticket m_ticket;
bool m_IOFlag;
public:
Patient(int TicketNumber = 0, bool IOFlag = false);
Patient(const Patient&) = delete;
Patient& operator=(const Patient&) = delete;
~Patient();
virtual char type() const = 0;
bool fileIO() const;
void fileIO(bool IOFlag);
bool operator==(const char characterToCompare)const;
bool operator==(const Patient& obj)const;
void setArrivalTime();
operator Time() const;
int number()const;
std::ostream& csvWrite(std::ostream&) const;
std::istream& csvRead(std::istream&);
std::ostream& write(std::ostream&) const;
std::istream& read(std::istream&);
};
}
#endif // PATIENT_H_
|
fe79b736f75ca8b1a143b60599eeaf9f2d4a0ef3
|
97de00811f25a9f2b3900cbdd5e897227000f35f
|
/test003/test_homework3_3/cube.h
|
8b4c4a56f0c8fe00900c05d975d3e3edb84b67ea
|
[] |
no_license
|
impressionyang/CPP_programs
|
61c125eb7928d1d8ea4e7a9165474fd3f87f4306
|
1d5625b4737decf41a67a3dc8898c0de397dfb51
|
refs/heads/master
| 2020-03-18T01:23:52.076792
| 2018-05-26T08:01:30
| 2018-05-26T08:01:30
| 134,140,305
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 223
|
h
|
cube.h
|
#ifndef CUBE_H_INCLUDED
#define CUBE_H_INCLUDED
class Cube{
private:
int length;
int width;
int height;
int volume;
public:
Cube();
void cal_v();
int get_volume();
};
#endif // CUBE_H_INCLUDED
|
d187efe05de978dd026cfa353e3b5c08ab1c793a
|
78325b6aa3c811f9598a72799d14a47c66e5cf3b
|
/A13 VectorADT ListADT/ListADT.h
|
7e605e244ae2708096e40c2237e2b2080110115c
|
[] |
no_license
|
jcangeles/CSC340
|
2301a39c2ae897463bd4cf0666643e0ce289e2b9
|
d37becf10b8976c05169af4a3de77c8b4dab0df4
|
refs/heads/master
| 2020-04-19T15:37:23.705184
| 2019-01-30T04:38:50
| 2019-01-30T04:38:50
| 168,279,725
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 832
|
h
|
ListADT.h
|
#ifndef ListADT_h
#define ListADT_h
#include <iostream>
#include <new>
using namespace std;
class ListADT {
private:
class Node {
public:
Node() :value(0), next(nullptr) {};
Node(int newVal) :value(newVal), next(nullptr) {};
int value;
Node *next;
};
Node * head;
int size;
public:
friend std::ostream& operator<< (std::ostream& outStr, ListADT& list);
//CONSTRUCTORS
~ListADT(); //destructor
ListADT(); //nullptr->head, 0->size
ListADT(const ListADT& clone);
ListADT& operator=(const ListADT& rhs);
//MEMBERFUNCTIONS
void push_front(int newVal); //add newVal to the front of a list
void push_back(int newVal); //add newVal to the back of a list
void pop_front();
void pop_back();
int operator[](int i);
int length() const;
};
#endif /* ListADT_hpp */
|
d32aa16736de3f0a79d99dd0ad58221d49651e08
|
9e01fb3c84122eba75eb12fa00c096b959c7c646
|
/qcharts_tp/include/private/bar_p.h
|
a49586c6ba5e7a7e78d5b73216ff01512a7b6664
|
[] |
no_license
|
wangyun123/Third
|
1723a174c4a624bb7a23c43881ef3f6bf9f55313
|
bd5bdd4113ece866b73d93a761a949f5aeeea84d
|
refs/heads/master
| 2021-01-01T17:15:43.470612
| 2014-09-02T07:19:50
| 2014-09-02T07:19:50
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,569
|
h
|
bar_p.h
|
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc
** All rights reserved.
** For any questions to Digia, please use contact form at http://qt.digia.com
**
** This file is part of the Qt Commercial Charts Add-on.
**
** $QT_BEGIN_LICENSE$
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.
**
** If you have questions regarding the use of this file, please use
** contact form at http://qt.digia.com
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef BAR_H
#define BAR_H
#include "qchartglobal.h"
#include <QGraphicsRectItem>
QTCOMMERCIALCHART_BEGIN_NAMESPACE
class QBarSet;
// Single visual bar item of chart
class Bar : public QObject, public QGraphicsRectItem
{
Q_OBJECT
public:
Bar(QBarSet *barset, QString category, QGraphicsItem *parent = 0);
public:
void mousePressEvent(QGraphicsSceneMouseEvent *event);
void hoverEnterEvent(QGraphicsSceneHoverEvent *event);
void hoverLeaveEvent(QGraphicsSceneHoverEvent *event);
Q_SIGNALS:
void clicked(QString category);
void clicked(QBarSet *barset, QString category);
void hovered(bool status);
void hovered(QBarSet *barset, bool status);
private:
QString m_category;
QBarSet *m_barset;
};
QTCOMMERCIALCHART_END_NAMESPACE
#endif // BAR_H
|
c7a2d24187e7dc09152061df1490cdeaf742f57f
|
895e6faac9c72c443e284ec586599dda433b253b
|
/include/unpacker/SimpleDataChunk.h
|
3e6ad62bc04318a4fdfaf648e014d44a3ef7642d
|
[] |
no_license
|
cdpruitt/HiRA-analysis
|
994a3062180c2541b80360c877fe9bff57ea4579
|
e892f63c25c39574286adc778c0878eef2b4281b
|
refs/heads/master
| 2021-01-12T09:37:33.786049
| 2016-12-22T02:48:49
| 2016-12-22T02:48:49
| 76,203,335
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 604
|
h
|
SimpleDataChunk.h
|
#ifndef SIMPLE_DATA_CHUNK_H
#define SIMPLE_DATA_CHUNK_H
#include "DataChunk.h"
#include "Datum.h"
#include <iostream>
#include <vector>
class SimpleDataChunk : public DataChunk
{
public:
SimpleDataChunk(std::string n, unsigned int s);
void add(DataChunk*);
void extractData(std::ifstream& evtfile);
void print(std::ofstream& evtfile);
virtual void branch(TTree*& tree);
void add(Datum d);
unsigned int getDataValue(unsigned int i);
void reset();
std::vector<Datum> data;
private:
std::string name;
};
#endif
|
e99d58055761be4f1a1204bfd6d67d55e4b46ac3
|
5f30897ec79f5ff410d11fd2f056644d2ee43933
|
/Skill/Miscellanious/Codeforces/800/1417A.cpp
|
bf375b9815fec686d11a93adbccf204675785f55
|
[] |
no_license
|
Puneethnaik/CompetitiveCoding
|
d86f8323d65e70c260e101e6a53bf67ac284d36d
|
97848e4ed51335220e7e96bbe23321f2a6ae7698
|
refs/heads/main
| 2023-07-26T23:05:08.807849
| 2021-09-05T04:48:28
| 2021-09-05T04:48:28
| 388,463,039
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 573
|
cpp
|
1417A.cpp
|
#include <bits/stdc++.h>
#define FOR(i, a, b) for(int i = a ; i < b ; i++)
#define FORN(i, n) FOR(i, 0, n)
#define vti vector<int>
#define vt(x) vector<x>
#define all(x) x.begin(), x.end()
#define read(x) cin >> x
using namespace std;
void solve() {
int n, k;
cin >> n >> k;
vti arr(n);
FORN(i, n) {
cin >> arr[i];
}
sort(all(arr));
int ans = 0;
FORN(i, n - 1) {
ans += (k - arr[i + 1]) / arr[0];
}
cout << ans << endl;
}
int main() {
int t;
cin >> t;
while(t--) {
solve();
}
return 0;
}
|
cb50866f9758a0218e2e4764facd29c8d9a8e0eb
|
b333d109191136e5ab0a830ec1c68df401fc3b21
|
/maps/include/maps/G3SkyMapMask.h
|
04fc1c2be5064e39d693c182798aa497574b06d5
|
[
"BSD-2-Clause"
] |
permissive
|
CMB-S4/spt3g_software
|
6d6ff8a6101976eab0e172ff196fe522b7d05ed9
|
6dd855dddcca1b887d058ac18eaf9a68bebea1a7
|
refs/heads/master
| 2023-08-17T05:02:01.227621
| 2023-08-16T19:32:32
| 2023-08-16T19:32:32
| 89,958,167
| 10
| 11
|
BSD-2-Clause
| 2023-09-11T16:45:18
| 2017-05-01T20:01:44
|
C++
|
UTF-8
|
C++
| false
| false
| 4,102
|
h
|
G3SkyMapMask.h
|
#ifndef _G3_SKYMAPMASK_H
#define _G3_SKYMAPMASK_H
#include <vector>
#include <boost/python.hpp>
/*
* The following implements a companion object to a G3SkyMap containing
* booleans for whether to use (true) or ignore (false) certain pixels.
* The pixelization is stored externally in the parent map, as is the
* (potential) translation from 2D to 1D pixel indices.
*
* By default, initializes to all zeroes. If use_data = True, it will
* interpret the input sky map both as projection information and as a
* source of data, initializing the mask to True where the input map is
* non-zero.
*/
class G3SkyMap;
class G3SkyMapMask : public G3FrameObject {
public:
G3SkyMapMask(const G3SkyMap &parent, bool use_data = false,
bool zero_nans = false, bool zero_infs = false);
G3SkyMapMask(const G3SkyMap &parent, boost::python::object v,
bool zero_nans = false, bool zero_infs = false);
G3SkyMapMask(const G3SkyMapMask &);
virtual ~G3SkyMapMask() {};
// Copy
boost::shared_ptr<G3SkyMapMask> Clone(bool copy_data = true) const;
boost::shared_ptr<G3SkyMapMask> ArrayClone(boost::python::object v,
bool zero_nans = false, bool zero_infs = false) const;
// Return a (modifiable) pixel value
std::vector<bool>::reference operator [] (size_t i);
bool operator [] (size_t i) const { return this->at(i); };
bool at(size_t i) const;
// Logic operations:
G3SkyMapMask &operator |=(const G3SkyMapMask &rhs);
G3SkyMapMask &operator &=(const G3SkyMapMask &rhs);
G3SkyMapMask &operator ^=(const G3SkyMapMask &rhs);
G3SkyMapMask &invert(); // Basically ~=
bool all() const;
bool any() const;
size_t sum() const;
size_t size() const;
std::vector<uint64_t> NonZeroPixels() const;
G3SkyMapMask operator ~() const;
G3SkyMapMask operator |(const G3SkyMapMask &rhs) const;
G3SkyMapMask operator &(const G3SkyMapMask &rhs) const;
G3SkyMapMask operator ^(const G3SkyMapMask &rhs) const;
G3SkyMapMask operator ==(const G3SkyMapMask &rhs) const;
G3SkyMapMask operator !=(const G3SkyMapMask &rhs) const;
void ApplyMask(const G3SkyMapMask &rhs, bool inverse=false);
// Information
bool IsCompatible(const G3SkyMap &map) const;
bool IsCompatible(const G3SkyMapMask &mask) const;
bool IsDense() const { return true; }
// The map for projection info
boost::shared_ptr<const G3SkyMap> Parent() const { return parent_; }
// Return a 1-or-0 sky-map with the contents of the mask (e.g. for plotting)
boost::shared_ptr<G3SkyMap> MakeBinaryMap() const;
class const_iterator {
public:
typedef std::pair<uint64_t, bool> value_type;
typedef value_type & reference;
typedef value_type * pointer;
const_iterator(const G3SkyMapMask &mask, bool begin);
bool operator==(const const_iterator & other) const {
return index_ == other.index_;
};
bool operator!=(const const_iterator & other) const {
return index_ != other.index_;
};
reference operator*() { return value_; };
pointer operator->() { return &value_; };
const_iterator operator++();
const_iterator operator++(int) { const_iterator i = *this; ++(*this); return i; }
private:
uint64_t index_;
value_type value_;
const G3SkyMapMask &mask_;
void set_value() {
value_.first = index_;
value_.second = mask_.at(index_);
}
};
const_iterator begin() const { return const_iterator(*this, true); };
const_iterator end() const { return const_iterator(*this, false); };
private:
G3SkyMapMask() {} // Fake out for serialization
template <class A> void load(A &ar, const unsigned v);
template <class A> void save(A &ar, const unsigned v) const;
friend class cereal::access;
std::vector<bool> data_;
boost::shared_ptr<const G3SkyMap> parent_;
// Populate
void FillFromMap(const G3SkyMap &m, bool zero_nans = false, bool zero_infs = false);
void FillFromArray(boost::python::object v, bool zero_nans = false, bool zero_infs = false);
SET_LOGGER("G3SkyMapMask");
};
namespace cereal {
template <class A> struct specialize<A, G3SkyMapMask, cereal::specialization::member_load_save> {};
}
G3_POINTERS(G3SkyMapMask);
G3_SERIALIZABLE(G3SkyMapMask, 2);
#endif
|
d02c5b645d00094d644a2ef0dc81266de4405564
|
9a2362a2b1c2fe92e3e06ad90c86356fa3799530
|
/sort/sort.cpp
|
267ebc058b9661502ea81684675520ea1b512302
|
[] |
no_license
|
bhutley/broad
|
13cd57cb5d047b9c3aa248c5fce1323ef8e26657
|
b151fb9fe7feead0f27c616d7e6d7c2df32e77fa
|
refs/heads/master
| 2021-04-09T10:49:43.671867
| 2018-03-15T17:27:28
| 2018-03-15T17:27:28
| 125,400,546
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 843
|
cpp
|
sort.cpp
|
/**
* STL std::sort() example.
*
* Time complexity is O(n log n)
*
* The gnu STL implementation uses a hybrid sorting algo. Introsort is
* used first, which starts with quicksort and then switches to
* heapsort if the recursion depth exceeds a certain level.
*/
#include <algorithm>
#include <vector>
#include <iostream>
void
output_numbers(const std::vector<int> &numbers)
{
for (std::vector<int>::const_iterator it = numbers.begin(); it != numbers.end(); ++it)
{
if (it != numbers.begin())
std::cout << ',';
std::cout << *it;
}
std::cout << std::endl;
}
int
main()
{
const int arr[] = {2, 29, 3, 13, 5, 7, 11, 17};
std::vector<int> numbers(arr, arr + sizeof(arr) / sizeof(arr[0]));
std::sort(numbers.begin(), numbers.end());
output_numbers(numbers);
return 0;
}
|
a910af3b1257043065475828a8be79b909cc8277
|
a92cd1decd8a028f67300ce99a7fa35ed9b78c81
|
/src/utils/sourcelua_swarm/public/tier1/lconvar.cpp
|
aac610ec646940a8bfea88d4d2213777263afac5
|
[] |
no_license
|
AluminumKen/hl2sb-src
|
06bcae8db4e460ce8c99842b0d5448a54baf4614
|
308feb9dab8815d89ac9c392a1337edc18846aae
|
refs/heads/master
| 2016-09-01T14:27:25.418233
| 2013-05-26T09:57:30
| 2013-05-26T09:57:30
| 49,325,598
| 1
| 0
| null | null | null | null |
WINDOWS-1252
|
C++
| false
| false
| 4,823
|
cpp
|
lconvar.cpp
|
//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======//
//
// Purpose:
//
// $Workfile: $
// $Date: $
//
//-----------------------------------------------------------------------------
// $NoKeywords: $
//===========================================================================//
#define lconvar_cpp
#include "convar.h"
#include "../LuaManager.h"
#include "lconvar.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
/*
** access functions (stack -> C)
*/
LUA_API const lua_ConVar *lua_toconvar (lua_State *L, int idx) {
const lua_ConVar **ppConVar = (const lua_ConVar **)luaL_checkudata(L, idx, "ConVar");
return *ppConVar;
}
/*
** push functions (C -> stack)
*/
LUA_API void lua_pushconvar (lua_State *L, const lua_ConVar *pConVar) {
const lua_ConVar **ppConVar = (const lua_ConVar **)lua_newuserdata(L, sizeof(lua_ConVar));
*ppConVar = pConVar;
luaL_getmetatable(L, "ConVar");
lua_setmetatable(L, -2);
}
LUALIB_API const lua_ConVar *luaL_checkconvar (lua_State *L, int narg) {
const lua_ConVar *d = lua_toconvar(L, narg);
if (&d == NULL) /* avoid extra test when d is not 0 */
luaL_typerror(L, narg, "ConVar");
return d;
}
static int ConVar_AddFlags (lua_State *L) {
const_cast<ConVar *>(luaL_checkconvar(L, 1))->AddFlags(luaL_checkint(L, 2));
return 0;
}
static int ConVar_GetBool (lua_State *L) {
lua_pushboolean(L, luaL_checkconvar(L, 1)->GetBool());
return 1;
}
static int ConVar_GetDefault (lua_State *L) {
lua_pushstring(L, luaL_checkconvar(L, 1)->GetDefault());
return 1;
}
static int ConVar_GetFloat (lua_State *L) {
lua_pushnumber(L, luaL_checkconvar(L, 1)->GetFloat());
return 1;
}
static int ConVar_GetHelpText (lua_State *L) {
lua_pushstring(L, luaL_checkconvar(L, 1)->GetHelpText());
return 1;
}
static int ConVar_GetInt (lua_State *L) {
lua_pushinteger(L, luaL_checkconvar(L, 1)->GetInt());
return 1;
}
static int ConVar_GetMax (lua_State *L) {
float maxVal;
lua_pushboolean(L, luaL_checkconvar(L, 1)->GetMax(maxVal));
lua_pushnumber(L, maxVal);
return 2;
}
static int ConVar_GetMin (lua_State *L) {
float minVal;
lua_pushboolean(L, luaL_checkconvar(L, 1)->GetMin(minVal));
lua_pushnumber(L, minVal);
return 2;
}
static int ConVar_GetName (lua_State *L) {
lua_pushstring(L, luaL_checkconvar(L, 1)->GetName());
return 1;
}
static int ConVar_GetString (lua_State *L) {
lua_pushstring(L, luaL_checkconvar(L, 1)->GetString());
return 1;
}
static int ConVar_IsCommand (lua_State *L) {
lua_pushboolean(L, luaL_checkconvar(L, 1)->IsCommand());
return 1;
}
static int ConVar_IsFlagSet (lua_State *L) {
lua_pushboolean(L, luaL_checkconvar(L, 1)->IsFlagSet(luaL_checkint(L, 2)));
return 1;
}
static int ConVar_IsRegistered (lua_State *L) {
lua_pushboolean(L, luaL_checkconvar(L, 1)->IsRegistered());
return 1;
}
static int ConVar_Revert (lua_State *L) {
const_cast<ConVar *>(luaL_checkconvar(L, 1))->Revert();
return 0;
}
static int ConVar___tostring (lua_State *L)
{
lua_pushfstring(L, "ConVar: \"%s\" = \"%s\"", luaL_checkconvar(L, 1)->GetName(), luaL_checkconvar(L, 1)->GetString());
return 1;
}
static const luaL_Reg ConVarmeta[] = {
{"AddFlags", ConVar_AddFlags},
{"GetBool", ConVar_GetBool},
{"GetDefault", ConVar_GetDefault},
{"GetFloat", ConVar_GetFloat},
{"GetHelpText", ConVar_GetHelpText},
{"GetInt", ConVar_GetInt},
{"GetMax", ConVar_GetMax},
{"GetMin", ConVar_GetMin},
{"GetName", ConVar_GetName},
{"GetString", ConVar_GetString},
{"IsCommand", ConVar_IsCommand},
{"IsFlagSet", ConVar_IsFlagSet},
{"IsRegistered", ConVar_IsRegistered},
{"Revert", ConVar_Revert},
{"__tostring", ConVar___tostring},
{NULL, NULL}
};
static int luasrc_ConVar (lua_State *L) {
ConVar *pConVar = new ConVar(luaL_checkstring(L, 1), luaL_checkstring(L, 2), luaL_optint(L, 3, 0), luaL_optstring(L, 4, 0), luaL_optboolean(L, 5, 0), luaL_optnumber(L, 6, 0.0), luaL_optboolean(L, 7, 0), luaL_optnumber(L, 8, 0));
cvar->RegisterConCommand(pConVar);
lua_pushconvar(L, pConVar);
return 1;
}
static const luaL_Reg ConVar_funcs[] = {
{"ConVar", luasrc_ConVar},
{NULL, NULL}
};
/*
** Open ConVar object
*/
int luaopen_ConVar (lua_State *L) {
luaL_newmetatable(L, "ConVar");
luaL_register(L, NULL, ConVarmeta);
lua_pushvalue(L, -1); /* push metatable */
lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */
lua_pushstring(L, "convar");
lua_setfield(L, -2, "__type"); /* metatable.__type = "convar" */
lua_pop(L, 2);
luaL_register(L, "_G", ConVar_funcs);
return 1;
}
|
75b7c8b902eed90c68cb453a6761823e94399ee3
|
13d789d505fdb75b1dff45f0ea173ecc1d6ca440
|
/src/tensor_calculus.hpp
|
e1eedceac44c44b4380649cb63870110fcde1934
|
[
"MIT"
] |
permissive
|
bstaber/TrilinosUQComp
|
209d39abe41aef14cfb0c2da039476f1a0815ba1
|
12ada5a678338a1da962113a4fad708f93b19e03
|
refs/heads/master
| 2022-03-30T10:33:09.066090
| 2020-01-10T15:48:01
| 2020-01-10T15:48:01
| 92,018,402
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,895
|
hpp
|
tensor_calculus.hpp
|
/*
Brian Staber (brian.staber@gmail.com)
*/
#ifndef TENSOR_CALCULUS_HPP
#define TENSOR_CALCULUS_HPP
#include "meshpp.hpp"
void tensor_product(double scalarAB, Epetra_SerialDenseVector & A, Epetra_SerialDenseVector & B, Epetra_SerialDenseMatrix & AoB, double scalarThis){
AoB.Multiply('N','T',scalarAB,A,B,scalarThis);
}
void sym_tensor_product(double scalarAB, Epetra_SerialDenseVector & A, Epetra_SerialDenseVector & B, Epetra_SerialDenseMatrix & AoB, double scalarThis){
AoB(0,0) = AoB(0,0)*scalarThis + A(0)*B(0)*scalarAB; AoB(0,1) = AoB(0,1)*scalarThis + A(5)*B(5)*scalarAB; AoB(0,2) = AoB(0,2)*scalarThis + A(4)*B(4)*scalarAB; AoB(0,3) = AoB(0,3)*scalarThis + scalarAB*((A(4)*B(5))/2.0 + (A(5)*B(4))/2.0); AoB(0,4) = AoB(0,4)*scalarThis + scalarAB*((A(0)*B(4))/2.0 + (A(4)*B(0))/2.0); AoB(0,5) = AoB(0,5)*scalarThis + scalarAB*((A(0)*B(5))/2.0 + (A(5)*B(0))/2.0);
AoB(1,0) = AoB(1,0)*scalarThis + A(5)*B(5)*scalarAB; AoB(1,1) = AoB(1,1)*scalarThis + A(1)*B(1)*scalarAB; AoB(1,2) = AoB(1,2)*scalarThis + A(3)*B(3)*scalarAB; AoB(1,3) = AoB(1,3)*scalarThis + scalarAB*((A(1)*B(3))/2.0 + (A(3)*B(1))/2.0); AoB(1,4) = AoB(1,4)*scalarThis + scalarAB*((A(3)*B(5))/2.0 + (A(5)*B(3))/2.0); AoB(1,5) = AoB(1,5)*scalarThis + scalarAB*((A(1)*B(5))/2.0 + (A(5)*B(1))/2.0);
AoB(2,0) = AoB(2,0)*scalarThis + A(4)*B(4)*scalarAB; AoB(2,1) = AoB(2,1)*scalarThis + A(3)*B(3)*scalarAB; AoB(2,2) = AoB(2,2)*scalarThis + A(2)*B(2)*scalarAB; AoB(2,3) = AoB(2,3)*scalarThis + scalarAB*((A(2)*B(3))/2.0 + (A(3)*B(2))/2.0); AoB(2,4) = AoB(2,4)*scalarThis + scalarAB*((A(2)*B(4))/2.0 + (A(4)*B(2))/2.0); AoB(2,5) = AoB(2,5)*scalarThis + scalarAB*((A(3)*B(4))/2.0 + (A(4)*B(3))/2.0);
AoB(3,0) = AoB(3,0)*scalarThis + A(5)*B(4)*scalarAB; AoB(3,1) = AoB(3,1)*scalarThis + A(1)*B(3)*scalarAB; AoB(3,2) = AoB(3,2)*scalarThis + A(3)*B(2)*scalarAB; AoB(3,3) = AoB(3,3)*scalarThis + scalarAB*((A(1)*B(2))/2.0 + (A(3)*B(3))/2.0); AoB(3,4) = AoB(3,4)*scalarThis + scalarAB*((A(3)*B(4))/2.0 + (A(5)*B(2))/2.0); AoB(3,5) = AoB(3,5)*scalarThis + scalarAB*((A(1)*B(4))/2.0 + (A(5)*B(3))/2.0);
AoB(4,0) = AoB(4,0)*scalarThis + A(0)*B(4)*scalarAB; AoB(4,1) = AoB(4,1)*scalarThis + A(5)*B(3)*scalarAB; AoB(4,2) = AoB(4,2)*scalarThis + A(4)*B(2)*scalarAB; AoB(4,3) = AoB(4,3)*scalarThis + scalarAB*((A(4)*B(3))/2.0 + (A(5)*B(2))/2.0); AoB(4,4) = AoB(4,4)*scalarThis + scalarAB*((A(0)*B(2))/2.0 + (A(4)*B(4))/2.0); AoB(4,5) = AoB(4,5)*scalarThis + scalarAB*((A(0)*B(3))/2.0 + (A(5)*B(4))/2.0);
AoB(5,0) = AoB(5,0)*scalarThis + A(0)*B(5)*scalarAB; AoB(5,1) = AoB(5,1)*scalarThis + A(5)*B(1)*scalarAB; AoB(5,2) = AoB(5,2)*scalarThis + A(4)*B(3)*scalarAB; AoB(5,3) = AoB(5,3)*scalarThis + scalarAB*((A(4)*B(1))/2.0 + (A(5)*B(3))/2.0); AoB(5,4) = AoB(5,4)*scalarThis + scalarAB*((A(0)*B(3))/2.0 + (A(4)*B(5))/2.0); AoB(5,5) = AoB(5,5)*scalarThis + scalarAB*((A(0)*B(1))/2.0 + (A(5)*B(5))/2.0);
}
#endif
|
a29c639b4d98dd86c44f84858e7e4f9b8716d6c2
|
234fc62a54192a67abf2b6bd25fc74d020f398d4
|
/Cursos/Fase4/Examen/C. Moscas/moscasA.cpp
|
ff29e71b8273ab4f5719e642430e6b38352bf40b
|
[] |
no_license
|
DiCZDC/ooi-2021
|
87ab05a164404906fe1da39adf52c37bc5528cd9
|
b70a9a5193041e23a4037bd9655fcc67668803a6
|
refs/heads/master
| 2023-05-10T12:36:06.524313
| 2021-06-15T23:34:34
| 2021-06-15T23:34:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,772
|
cpp
|
moscasA.cpp
|
// https://omegaup.com/arena/problem/moscas/#problems
#include <bits/stdc++.h>
#define TIEMPO_MAX 60000
using namespace std;
int main() {
int moscas;
cin >> moscas;
// Vector para guardar la cantidad de moscas vivas durante el tiempo.
// El indice i representa la cantidad de moscas vivas en el tiempo i
vector<int> moscas_vivas_en_tiempo(TIEMPO_MAX + 1, 0); // El problema dice que el tiempo maximo es de 0 hasta 60,000
// Leer tiempo de inicio de vida y muerte de cada mosca
for (int mosca = 0; mosca < moscas; ++mosca) {
int t_n, t_m;
cin >> t_n >> t_m;
// Para esta mosca, marcar su tiempo de vida en el arreglo
for (int i = t_n; i < t_m; ++i) {
moscas_vivas_en_tiempo[i]++; // Incrementar la cantidad de moscas vivas en el tiempo i
}
}
// Buscar el valor maximo de moscas vivas a traves del tiempo
int maximo = 0;
for (int i = 1; i <= TIEMPO_MAX; ++i) {
if (moscas_vivas_en_tiempo[i] > maximo) {
maximo = moscas_vivas_en_tiempo[i];
}
}
// Imprimir el maximo
cout << maximo << "\n";
// Imprimir todos los rangos donde se encontró la población máxima de moscas
for (int i = 1; i <= TIEMPO_MAX; ++i) {
int inicio_rango;
int fin_rango;
if (moscas_vivas_en_tiempo[i] == maximo) {
inicio_rango = i; // Aqui inicia el rango
// Incrementar el valor de i mientras sea igual al maximo
while (i <= TIEMPO_MAX && moscas_vivas_en_tiempo[i] == maximo) {
i++;
}
// Ahora i tiene el valor del final del rango
fin_rango = i;
cout << inicio_rango << " " << fin_rango << "\n";
}
}
return 0;
}
|
ac450322d218a4640440630ff14254e3cb31944b
|
b4f0a64b306642c47bd563b071567216ef10cd99
|
/book_sample/Chpater 5 - Screen Space Effects/Screen SpACE Light Rays/SSLRManager.h
|
7b229349ca660a0f41d17f8c4920e76b0726853f
|
[
"MIT"
] |
permissive
|
jjuiddong/HLSL-Development-Cookbook
|
515cc8671965da045c850c986f5d09725153d46e
|
8a322f4e7924fe0c7e757bd2453ce0adeb282aeb
|
refs/heads/master
| 2021-08-23T14:48:01.677625
| 2017-12-05T08:50:36
| 2017-12-05T08:50:36
| 113,155,720
| 20
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,534
|
h
|
SSLRManager.h
|
#pragma once
class CSSLRManager
{
public:
CSSLRManager();
~CSSLRManager();
HRESULT Init(UINT width, UINT height);
void Deinit();
// Render the screen space light rays on top of the scene
void Render(ID3D11DeviceContext* pd3dImmediateContext, ID3D11RenderTargetView* pLightAccumRTV, ID3D11ShaderResourceView* pMiniDepthSRV, const D3DXVECTOR3& vSunDir, const D3DXVECTOR3& vSunColor);
private:
// Prepare the occlusion map
void PrepareOcclusion(ID3D11DeviceContext* pd3dImmediateContext, ID3D11ShaderResourceView* pMiniDepthSRV);
// Ray trace the occlusion map to generate the rays
void RayTrace(ID3D11DeviceContext* pd3dImmediateContext, const D3DXVECTOR2& vSunPosSS, const D3DXVECTOR3& vSunColor);
// Combine the rays with the scene
void Combine(ID3D11DeviceContext* pd3dImmediateContext, ID3D11RenderTargetView* pLightAccumRTV);
UINT m_nWidth;
UINT m_nHeight;
float m_fInitDecay;
float m_fDistDecay;
float m_fMaxDeltaLen;
ID3D11Texture2D* m_pOcclusionTex;
ID3D11UnorderedAccessView* m_pOcclusionUAV;
ID3D11ShaderResourceView* m_pOcclusionSRV;
ID3D11Texture2D* m_pLightRaysTex;
ID3D11RenderTargetView* m_pLightRaysRTV;
ID3D11ShaderResourceView* m_pLightRaysSRV;
// Shaders
ID3D11Buffer* m_pOcclusionCB;
ID3D11ComputeShader* m_pOcclusionCS;
ID3D11Buffer* m_pRayTraceCB;
ID3D11VertexShader* m_pFullScreenVS;
ID3D11PixelShader* m_pRayTracePS;
ID3D11PixelShader* m_pCombinePS;
// Additive blend state to add the light rays on top of the scene lights
ID3D11BlendState* m_pAdditiveBlendState;
};
|
228382a1fc210eca722e00ff36dcfbad0d324a34
|
284622dfae9f9a51f9e4a210732efa28e115ed78
|
/程序设计4/斐波拉契数列第n项.cpp
|
e5dd2b2f0358b308cca1e968f9c53d2c4a525b36
|
[] |
no_license
|
wam730/The-assignment-of-C-course
|
cc86dbb7b39b54edadd885f697e7e27ef490f76a
|
b45a4ea198db8cb5d7c5725e4410b4ffbf54b48c
|
refs/heads/master
| 2022-06-13T03:48:32.488997
| 2020-05-06T11:04:02
| 2020-05-06T11:04:02
| 258,688,728
| 2
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 930
|
cpp
|
斐波拉契数列第n项.cpp
|
#include <stdio.h>
#include <cstdlib>
int main()
{
long int A=1,A1=0,A2=1,i=0,an,n,sn=0;
char a;
printf("*欢迎使用本程序*\n我们将为您计算斐波拉契数列的第n项、写出其前n项、计算前n项的和\n");
printf("请输入第几项n=");
scanf("%d",&n);
printf("前n项为: \n");
if(n==1) printf("a1=1\n斐波拉契数列的前1项的和为S1=0");
else if(n==2) printf("a1=1\na2=2\n斐波拉契数列的前2项的和为:S2=1");
else if(n==3) printf("a1=1\na2=2\na3=3\n斐波拉契数列的前3项的和为:S3=2");
else if(n>3&&n<=45)
{printf("a1=0\na2=1\na3=1\n");
while(i<n-3)
{A1=A2;
A2=A;
A=A1+A2;
an=A;
sn=sn+an;
printf("a%d=%d\n",i+4,an);
i++;}
printf("斐波拉契数列的前%d项的和为:S%d=%d\n",n,n,sn+2);}
else printf("数据溢出,请输入更小的正整数!\n");
printf(" by wyj\n");
system("pause");
return 0;
}
|
253f45fee3917bcd622879bea47d1e960563dbe1
|
19d50543968dd8fad21cb6cf703430df7f9dc221
|
/dpcpp/components/cooperative_groups.dp.hpp
|
e2212285954e0b06912b8c4fc1d48981c54cc784
|
[
"LicenseRef-scancode-proprietary-license",
"BSD-3-Clause",
"CECILL-2.0",
"MIT",
"LGPL-2.1-only",
"Unlicense",
"LGPL-2.1-or-later",
"GPL-1.0-or-later",
"CECILL-C",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] |
permissive
|
ginkgo-project/ginkgo
|
53bb384acc3bdcfa0e4a89810fdc4e9390fa4144
|
1100cbd2d86a9aa7388f1ace6aae2466e3bdf518
|
refs/heads/develop
| 2023-08-31T06:54:12.481543
| 2023-08-30T12:28:15
| 2023-08-30T12:28:15
| 117,122,510
| 352
| 102
|
BSD-3-Clause
| 2023-09-13T15:56:48
| 2018-01-11T16:14:21
|
C++
|
UTF-8
|
C++
| false
| false
| 16,432
|
hpp
|
cooperative_groups.dp.hpp
|
/*******************************<GINKGO LICENSE>******************************
Copyright (c) 2017-2023, the Ginkgo authors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************<GINKGO LICENSE>*******************************/
#ifndef GKO_DPCPP_COMPONENTS_COOPERATIVE_GROUPS_DP_HPP_
#define GKO_DPCPP_COMPONENTS_COOPERATIVE_GROUPS_DP_HPP_
#include <type_traits>
#include <ginkgo/config.hpp>
#include "dpcpp/base/config.hpp"
#include "dpcpp/base/dpct.hpp"
namespace gko {
namespace kernels {
namespace dpcpp {
/**
* Ginkgo uses cooperative groups to handle communication among the threads.
*
* However, DPCPP's implementation of cooperative groups is still quite limited
* in functionality, and some parts are not supported on all hardware
* interesting for Ginkgo. For this reason, Ginkgo exposes only a part of the
* original functionality, and possibly extends it if it is required. Thus,
* developers should include and use this header and the gko::group namespace
* instead of the standard cooperative_groups.h header. The interface exposed
* by Ginkgo's implementation is equivalent to the standard interface, with some
* useful extensions.
*
* A cooperative group (both from standard DPCPP and from Ginkgo) is not a
* specific type, but a concept. That is, any type satisfying the interface
* imposed by the cooperative groups API is considered a cooperative
* group (a.k.a. "duck typing"). To maximize the generality of components that
* need cooperative groups, instead of creating the group manually, consider
* requesting one as an input parameter. Make sure its type is a template
* parameter to maximize the set of groups for which your algorithm can be
* invoked. To maximize the amount of contexts in which your algorithm can be
* called and avoid hidden requirements, do not depend on a specific setup of
* kernel launch parameters (i.e. grid dimensions and block dimensions).
* Instead, use the thread_rank() method of the group to distinguish between
* distinct threads of a group.
*
* The original DPCPP implementation does not provide ways to verify if a
* certain type represents a cooperative group. Ginkgo's implementation provides
* metafunctions which do that. Additionally, not all cooperative groups have
* equivalent functionality, so Ginkgo splits the cooperative group concept into
* three sub-concepts which describe what functionality is available. Here is a
* list of concepts and their interfaces:
*
* ```c++
* concept Group {
* unsigned size() const;
* unsigned thread_rank() const;
* };
*
* concept SynchronizableGroup : Group {
* void sync();
* };
*
* concept CommunicatorGroup : SynchronizableGroup {
* template <typename T>
* T shfl(T var, int srcLane);
* T shfl_up(T var, unsigned delta);
* T shfl_down(T var, unsigned delta);
* T shfl_xor(T var, int laneMask);
* int all(int predicate);
* int any(int predicate);
* unsigned ballot(int predicate);
* };
* ```
*
* To check if a group T satisfies one of the concepts, one can use the
* metafunctions is_group<T>::value, is_synchronizable_group<T>::value and
* is_communicator_group<T>::value.
*
* @note Please note that the current implementation of cooperative groups
* contains only a subset of functionalities provided by those APIs. If
* you need more functionality, please add the appropriate implementations
* to existing cooperative groups, or create new groups if the existing
* groups do not cover your use-case. For an example, see the
* enable_extended_shuffle mixin, which adds extended shuffles support
* to built-in DPCPP cooperative groups.
*/
namespace group {
// metafunctions
namespace detail {
template <typename T>
struct is_group_impl : std::false_type {};
template <typename T>
struct is_synchronizable_group_impl : std::false_type {};
template <typename T>
struct is_communicator_group_impl : std::true_type {};
} // namespace detail
/**
* Check if T is a Group.
*/
template <typename T>
using is_group = detail::is_group_impl<std::decay_t<T>>;
/**
* Check if T is a SynchronizableGroup.
*/
template <typename T>
using is_synchronizable_group =
detail::is_synchronizable_group_impl<std::decay_t<T>>;
/**
* Check if T is a CommunicatorGroup.
*/
template <typename T>
using is_communicator_group =
detail::is_communicator_group_impl<std::decay_t<T>>;
// types
namespace detail {
/**
* This is a limited implementation of the DPCPP thread_block_tile.
*/
template <unsigned Size>
class thread_block_tile : public sycl::sub_group {
using sub_group = sycl::sub_group;
using id_type = sub_group::id_type;
using mask_type = config::lane_mask_type;
public:
// note: intel calls nd_item.get_sub_group(), but it still call
// sycl::sub_group() to create the sub_group.
template <typename Group>
explicit thread_block_tile(const Group& parent_group)
: data_{Size, 0}, sub_group()
{
#ifndef NDEBUG
assert(this->get_local_range().get(0) == Size);
#endif
data_.rank = this->get_local_id();
}
__dpct_inline__ unsigned thread_rank() const noexcept { return data_.rank; }
__dpct_inline__ unsigned size() const noexcept { return Size; }
__dpct_inline__ void sync() const noexcept { this->barrier(); }
#define GKO_BIND_SHFL(ShflOpName, ShflOp) \
template <typename ValueType, typename SelectorType> \
__dpct_inline__ ValueType ShflOpName(ValueType var, SelectorType selector) \
const noexcept \
{ \
return this->ShflOp(var, selector); \
} \
static_assert(true, \
"This assert is used to counter the false positive extra " \
"semi-colon warnings")
GKO_BIND_SHFL(shfl, shuffle);
GKO_BIND_SHFL(shfl_xor, shuffle_xor);
// the shfl_up of out-of-range value gives undefined behavior, we
// manually set it as the original value such that give the same result as
// cuda/hip.
template <typename ValueType, typename SelectorType>
__dpct_inline__ ValueType shfl_up(ValueType var,
SelectorType selector) const noexcept
{
const auto result = this->shuffle_up(var, selector);
return (data_.rank < selector) ? var : result;
}
// the shfl_down of out-of-range value gives undefined behavior, we
// manually set it as the original value such that give the same result as
// cuda/hip.
template <typename ValueType, typename SelectorType>
__dpct_inline__ ValueType shfl_down(ValueType var,
SelectorType selector) const noexcept
{
const auto result = this->shuffle_down(var, selector);
return (data_.rank + selector >= Size) ? var : result;
}
/**
* Returns a bitmask containing the value of the given predicate
* for all threads in the group.
* This means that the ith bit is equal to the predicate of the
* thread with thread_rank() == i in the group.
* Note that the whole group needs to execute the same operation.
*/
__dpct_inline__ mask_type ballot(int predicate) const noexcept
{
// todo: change it when OneAPI update the mask related api
return sycl::reduce_over_group(
*this, (predicate != 0) ? mask_type(1) << data_.rank : mask_type(0),
sycl::plus<mask_type>());
}
/**
* Returns true iff the predicate is true for at least one threads in the
* group. Note that the whole group needs to execute the same operation.
*/
__dpct_inline__ bool any(int predicate) const noexcept
{
return sycl::any_of_group(*this, (predicate != 0));
}
/**
* Returns true iff the predicate is true for all threads in the group.
* Note that the whole group needs to execute the same operation.
*/
__dpct_inline__ bool all(int predicate) const noexcept
{
return sycl::all_of_group(*this, (predicate != 0));
}
private:
struct alignas(8) {
unsigned size;
unsigned rank;
} data_;
};
// specialization for 1
template <>
class thread_block_tile<1> {
using mask_type = config::lane_mask_type;
static constexpr unsigned Size = 1;
public:
template <typename Group>
explicit thread_block_tile(const Group& parent_group) : data_{Size, 0}
{}
__dpct_inline__ unsigned thread_rank() const noexcept { return data_.rank; }
__dpct_inline__ unsigned size() const noexcept { return Size; }
__dpct_inline__ void sync() const noexcept {}
#define GKO_DISABLE_SHFL(ShflOpName) \
template <typename ValueType, typename SelectorType> \
__dpct_inline__ ValueType ShflOpName(ValueType var, SelectorType selector) \
const noexcept \
{ \
return var; \
} \
static_assert(true, \
"This assert is used to counter the false positive extra " \
"semi-colon warnings")
GKO_DISABLE_SHFL(shfl);
GKO_DISABLE_SHFL(shfl_up);
GKO_DISABLE_SHFL(shfl_down);
GKO_DISABLE_SHFL(shfl_xor);
/**
* Returns a bitmask containing the value of the given predicate
* for all threads in the group.
* This means that the ith bit is equal to the predicate of the
* thread with thread_rank() == i in the group.
* Note that the whole group needs to execute the same operation.
*/
__dpct_inline__ mask_type ballot(int predicate) const noexcept
{
return (predicate != 0) ? mask_type(1) : mask_type(0);
}
/**
* Returns true iff the predicate is true for at least one threads in the
* group. Note that the whole group needs to execute the same operation.
*/
__dpct_inline__ bool any(int predicate) const noexcept
{
return (predicate != 0);
}
/**
* Returns true iff the predicate is true for all threads in the group.
* Note that the whole group needs to execute the same operation.
*/
__dpct_inline__ bool all(int predicate) const noexcept
{
return (predicate != 0);
}
private:
struct alignas(8) {
unsigned size;
unsigned rank;
} data_;
};
} // namespace detail
using detail::thread_block_tile;
// Only support tile_partition with 2, 4, 8, 16, 32, 64.
template <unsigned Size, typename Group>
__dpct_inline__
std::enable_if_t<(Size > 1) && Size <= 64 && !(Size & (Size - 1)),
detail::thread_block_tile<Size>>
tiled_partition(const Group& group)
{
return detail::thread_block_tile<Size>(group);
}
template <unsigned Size, typename Group>
__dpct_inline__ std::enable_if_t<Size == 1, detail::thread_block_tile<Size>>
tiled_partition(const Group& group)
{
return detail::thread_block_tile<Size>(group);
}
namespace detail {
template <unsigned Size>
struct is_group_impl<thread_block_tile<Size>> : std::true_type {};
template <unsigned Size>
struct is_synchronizable_group_impl<thread_block_tile<Size>> : std::true_type {
};
template <unsigned Size>
struct is_communicator_group_impl<thread_block_tile<Size>> : std::true_type {};
} // namespace detail
class thread_block {
friend __dpct_inline__ thread_block this_thread_block(sycl::nd_item<3>&);
public:
__dpct_inline__ unsigned thread_rank() const noexcept { return data_.rank; }
__dpct_inline__ unsigned size() const noexcept { return data_.size; }
__dpct_inline__ void sync() const noexcept { group_.barrier(); }
private:
__dpct_inline__ thread_block(sycl::nd_item<3>& group)
: group_{group},
data_{static_cast<unsigned>(group.get_local_range().size()),
static_cast<unsigned>(group.get_local_linear_id())}
{}
struct alignas(8) {
unsigned size;
unsigned rank;
} data_;
sycl::nd_item<3>& group_;
};
__dpct_inline__ thread_block this_thread_block(sycl::nd_item<3>& group)
{
return thread_block(group);
}
namespace detail {
template <>
struct is_group_impl<thread_block> : std::true_type {};
template <>
struct is_synchronizable_group_impl<thread_block> : std::true_type {};
} // namespace detail
/**
* This is a limited implementation of the DPCPP grid_group that works even on
* devices that do not support device-wide synchronization and without special
* kernel launch syntax.
*
* Note that this implementation does not support large grids, since it uses 32
* bits to represent sizes and ranks, while at least 73 bits (63 bit grid + 10
* bit block) would have to be used to represent the full space of thread ranks.
*/
class grid_group {
friend __dpct_inline__ grid_group this_grid(sycl::nd_item<3>&);
public:
__dpct_inline__ unsigned size() const noexcept { return data_.size; }
__dpct_inline__ unsigned thread_rank() const noexcept { return data_.rank; }
private:
__dpct_inline__ grid_group(sycl::nd_item<3>& group)
: data_{static_cast<unsigned>(group.get_global_range().size()),
static_cast<unsigned>(group.get_global_linear_id())}
{}
struct alignas(8) {
unsigned size;
unsigned rank;
} data_;
};
// Not using this, as grid_group is not universally supported.
// grid_group this_grid()
// using cooperative_groups::this_grid;
// Instead, use our limited implementation:
__dpct_inline__ grid_group this_grid(sycl::nd_item<3>& group)
{
return grid_group(group);
}
} // namespace group
} // namespace dpcpp
} // namespace kernels
} // namespace gko
// Enable group can directly use group function
#if GINKGO_DPCPP_MAJOR_VERSION < 6
inline namespace cl {
#endif
namespace sycl {
namespace detail {
template <unsigned Size>
struct is_sub_group<
::gko::kernels::dpcpp::group::detail::thread_block_tile<Size>>
: std::true_type {};
namespace spirv {
template <typename Group>
struct group_scope;
template <unsigned Size>
struct group_scope<
::gko::kernels::dpcpp::group::detail::thread_block_tile<Size>> {
static constexpr __spv::Scope::Flag value = __spv::Scope::Flag::Subgroup;
};
} // namespace spirv
} // namespace detail
} // namespace sycl
#if GINKGO_DPCPP_MAJOR_VERSION < 6
} // namespace cl
#endif
#endif // GKO_DPCPP_COMPONENTS_COOPERATIVE_GROUPS_DP_HPP_
|
cda749b507f3072077a7be47db1f1032d43e3cf3
|
53fd6d2e69f6dc06aebccd4c1861f6d31f1d6412
|
/projects/client/audio/aura_processing/source/aura/processing/utility.cpp
|
60d2481623da3f226c4ba2f1414176b0dd6ca2a1
|
[
"MIT"
] |
permissive
|
silentorb/mythic-cpp
|
2c36e5e9e341c57d0cd6f3b5a0d8d06aaf52d9b0
|
97319d158800d77e1a944c47c13523662bc07e08
|
refs/heads/master
| 2020-10-01T09:40:58.577920
| 2019-12-12T04:52:50
| 2019-12-12T04:52:50
| 227,509,036
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 334
|
cpp
|
utility.cpp
|
#include "utility.h"
#include <cmath>
namespace aura {
namespace processing {
// float to_dB(float value) {
// return (std::pow(10, value) - 1) / (10 - 1);
// }
float inverse_dB(float value) {
const auto base = 10;
return (std::pow(base, 1 - value) + 1) / (base - 1) + 1;
}
}
}
|
9fd4e5a3b9f2d970ee16a26f37cafc1b39f02a28
|
386fad5de6b1a6a9e5557947bd1aeffda8821656
|
/ZeroJudge/c031.cpp
|
4e5bac00e5c831c0e48de290ac483e2edad36da7
|
[] |
no_license
|
xxyyzz/Competitive-Programming_Solutions
|
6c1f06232ab63f85d913bdd27a90eff892bfe18d
|
cca393f4330e784eb0f9edb44df290adc105ce3b
|
refs/heads/master
| 2021-06-02T13:33:48.530485
| 2016-09-25T14:15:37
| 2016-09-25T14:15:37
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 306
|
cpp
|
c031.cpp
|
#include <iostream>
using namespace std;
int main()
{
int n, a, b, c, d;
while(scanf("%d",&n)!=EOF)
{
for (d=1, c=n; c>d; d++) c-=d;
if ( d%2==1 ) a=d-c+1;
else a=c;
b=d+1-a;
cout << "TERM " << n << " IS " << a << "/" << b << endl;
}
return 0;
}
|
988752f5670e74a823688cc62d6d3c07a2f6b4b6
|
0d45b4a2b55a3288b8e631b8d7884b2e7346d7cc
|
/Robogotchi/mathvector.h
|
dfd7e346dafd3c813245a55fb3f3bd8835f29aa9
|
[
"MIT"
] |
permissive
|
drhugoz/Robogotchi
|
4bd104eda7478ae3761f772571e0a086fc311422
|
f4b8c4fdc5804c67b7819ffa1e228d27f5ec1fc7
|
refs/heads/master
| 2020-06-17T04:18:14.403754
| 2019-12-11T16:01:42
| 2019-12-11T16:01:42
| 195,794,102
| 0
| 0
|
MIT
| 2019-12-11T16:01:43
| 2019-07-08T10:57:19
| null |
UTF-8
|
C++
| false
| false
| 1,170
|
h
|
mathvector.h
|
#ifndef MATHVECTOR_H
#define MATHVECTOR_H
#include <math.h>
#include "model.h"
class MathVector
{
public:
MathVector() : x(0), y(0), z(0) {}
MathVector(const double _x, const double _y, const double _z) : x(_x), y(_y), z(_z) {}
MathVector(point l, point r);
friend MathVector operator*(const MathVector& l, const MathVector& r)
{
int x = l.getY() * r.getZ() - l.getZ() * r.getY();
int y = l.getZ() * r.getX() - l.getX() * r.getZ();
int z = l.getX() * r.getY() - l.getY() * r.getX();
return MathVector(x, y, z);
}
friend double operator&(const MathVector& l, const MathVector& r)
{
return l.x * r.x + l.y * r.y + l.z * r.z;
}
friend double operator^(MathVector& l, MathVector& r)
{
return acos((l & r) / (l.length() * r.length()));
}
double length();
void normalize();
double getX() const {return x;}
double getY() const {return y;}
double getZ() const {return z;}
void setX(const double _x) {x = _x;}
void setY(const double _y) {y = _y;}
void setZ(const double _z) {z = _z;}
private:
double x, y, z;
};
#endif // MATHVECTOR_H
|
7054d0fad1be81bbfb191f9278f521b9591d7709
|
3b0ac5056287bc8a0b4e87cf1eb11d70306339ba
|
/ui/CriterionRatingModel.h
|
df0b75505f36ba0e01d52bd91f04a1fe6fb06aaa
|
[
"MIT"
] |
permissive
|
m0gg/ahp-qt5
|
d82eaa9547b3dafef0ea4d60d07d6edd3fc2a398
|
486c5d574e5bd2f7ab99e28729931733a130be8b
|
refs/heads/master
| 2016-09-05T11:19:45.698779
| 2014-10-10T01:13:12
| 2014-10-10T01:13:12
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 702
|
h
|
CriterionRatingModel.h
|
#ifndef CRITERIONRATINGMODEL_H
#define CRITERIONRATINGMODEL_H
#include <QAbstractTableModel>
#include "libahp.h"
class CriterionRatingModel : public QAbstractTableModel {
Q_OBJECT
private:
AHPSet& ahpSet;
vector<double> rating;
public:
CriterionRatingModel(AHPSet& ahpSet, QObject *parent = 0);
int rowCount(const QModelIndex &parent = QModelIndex()) const ;
int columnCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
Qt::ItemFlags flags(const QModelIndex & index) const;
};
#endif /* CRITERIONRATINGMODEL_H */
|
e5e44097459646adc2137719a26d760d9a6a771a
|
14e30c5f520f0ed28117914101d9bdf2f3d5dac7
|
/project/source/mesh/mesh.cpp
|
1b8f52bb24b3d2fd8a097b98c3192fe089c83d46
|
[] |
no_license
|
danielePiracci/arlight
|
f356eb5a162d0cd62a759720cbc6da41a820642f
|
15a68c4c80c97f2fe7458e7ddf03f3e1063e25a4
|
refs/heads/master
| 2016-08-11T13:45:35.252916
| 2011-01-24T20:22:50
| 2011-01-24T20:22:50
| 44,962,821
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 551
|
cpp
|
mesh.cpp
|
/// \file mesh/mesh.cpp
/// \author Juan Carlos De Abreu (jcabreur@gmail.com)
/// \date 2009/11/07
/// \version 1.0
///
/// \brief This file implements the DissertationProject::Mesh class,
/// declared at mesh/mesh.h.
#include "mesh/mesh.h"
#include "base/locator_inl.h"
BEGIN_PROJECT_NAMESPACE();
Mesh::Mesh() {
mesh_renderer_ = Locator::GetRenderer()->GetNewMeshRenderer();
}
Mesh::~Mesh() {
mesh_renderer_.reset();
}
void Mesh::Render(bool apply_material) {
mesh_renderer_->Render();
}
END_PROJECT_NAMESPACE();
|
50a97bf3af05d3ec9a02574b5ad9761de10dd766
|
32a5b7b638603eec56452d4fa553dd4e558a731c
|
/src/methods/WeightedAlignmentVoter.hpp
|
87b0aea3c3d4fa40831037a2a7d25f8216ea7e41
|
[] |
no_license
|
joannatko/SANA
|
1af9db3842bba22f05d1f63275bf53015845080a
|
c8a043d7b1b8eca4f897a32288b4105cd14f2cf7
|
refs/heads/SANA1.1
| 2020-04-10T11:19:05.189371
| 2019-02-28T05:09:07
| 2019-02-28T05:09:07
| 160,989,636
| 1
| 0
| null | 2018-12-09T01:54:07
| 2018-12-09T00:05:36
|
Emacs Lisp
|
UTF-8
|
C++
| false
| false
| 840
|
hpp
|
WeightedAlignmentVoter.hpp
|
#ifndef WEIGHTEDALIGNMENTVOTER_HPP
#define WEIGHTEDALIGNMENTVOTER_HPP
#include <iostream>
#include "Method.hpp"
#include "../measures/localMeasures/LocalMeasure.hpp"
using namespace std;
class WeightedAlignmentVoter: public Method {
public:
WeightedAlignmentVoter(Graph* G1, Graph* G2, LocalMeasure* nodeSim);
Alignment run();
void describeParameters(ostream& stream);
string fileNameSuffix(const Alignment& A);
private:
LocalMeasure* nodeSim;
vector<uint> A;
void updateNeighbors(const vector<bool>& alreadyAlignedG1, const vector<bool>& alreadyAlignedG2, uint node, const vector<vector<double> >& nodeSimMatrix, vector<vector<double> >& simMatrix);
uint addBestPair(const vector<vector<double> >& simMatrix, vector<bool>& alreadyAlignedG1, vector<bool>& alreadyAlignedG2);
};
#endif
|
dfce2e8c71d8005e9c1dd11fd0705de8aa6faae3
|
9f82a4168ed99fa9a20ca82ffa93936bc25b5d9b
|
/q1_180915.cpp
|
a264ce351d945bf1d0d5f16fc71c84b8ab57bb3a
|
[] |
no_license
|
OOP2019lab/lab2-180915hassanAli
|
7866bc96d74dde21416d200dfb0c3707922d110a
|
e96b194c9dc2f71f85bf1972892f3505c7c14c84
|
refs/heads/master
| 2020-04-19T02:29:47.448616
| 2019-01-28T05:43:46
| 2019-01-28T05:43:46
| 167,904,938
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,912
|
cpp
|
q1_180915.cpp
|
#include <iostream>
#include <string>
#include "gitHubUserq1.h"
using namespace std;
//returns address of arr where UserName found, returns null otherwise
gitHubUser* searchUser(gitHubUser* users, int size, string UserName) {
for (int c = 0; c < size; ++c) {
if (users[c].userName == UserName) {
return &users[c];
}
}
return nullptr;
}
//checks if username already exists
//returns 1 if Username already exists in arr
bool exists(gitHubUser* arr, int size, string UserName) {
for (int c = 0; c < size; ++c) {
if (arr[c].userName == UserName) {
return 1;
}
}
return 0;
}
//inputs a unique username and stores it in arr
void InputUserName(gitHubUser * arr, int size,int UserNum) {
//temp username variable
string UserName;
cout << "enter username: ";
cin >> UserName;
while (exists(arr, size, UserName) == 1) {
cout << "this username already exists, enter another username: ";
cin >> UserName;
}
arr[UserNum].userName = UserName;
}
//fills arr from userinput upto size passed
void inputFromUser(gitHubUser * arr,int size) {
for (int UserCount = 0; UserCount < size; ++UserCount) {
cout << "enter name: ";
cin >> arr[UserCount].firstName;
InputUserName(arr, size, UserCount);
cout << "Enter password: ";
cin >> arr[UserCount].password;
cout << "Enter email: ";
cin >> arr[UserCount].email;
cout << "Enter folderCount: ";
cin >> arr[UserCount].folderCount;
}
}
//takes two structs gitHubUser as parameters and returns 1 if they are equal
bool Comparison(gitHubUser UserA, gitHubUser UserB) {
if (UserA.firstName != UserB.firstName)
return 0;
if (UserA.userName != UserB.userName)
return 0;
if (UserA.password != UserB.password)
return 0;
if (UserA.email != UserB.email)
return 0;
if (UserA.folderCount != UserB.folderCount)
return 0;
return 1;
}
//tests the comparision function
void ComparisionTest() {
gitHubUser DummyA, DummyB;
DummyA.userName = "a";
DummyA.firstName = "a";
DummyA.password = "a";
DummyA.email = "a";
DummyA.folderCount = 1;
DummyB.userName = "a";
DummyB.firstName = "b";
DummyB.password = "a";
DummyB.email = "a";
DummyB.folderCount = 1;
if (Comparison(DummyA, DummyB) == 1) {
cout << endl << "the two users are identical";
}
else {
cout << endl << "the two users are different";
}
cout << endl;
}
void main() {
ComparisionTest();
//testing input and UserName uniquness
int NumOfUsers = 4;
gitHubUser * UserArr=new gitHubUser[NumOfUsers];
inputFromUser(UserArr, NumOfUsers);
//testing searchUser
cout << endl << "Enter userName to search ";
string TestUserName;
cin >> TestUserName;
cout << searchUser(UserArr, NumOfUsers, TestUserName);
//delete Dynamic arr
delete[] UserArr;
UserArr = nullptr;
int dum;
cin >> dum;
}
|
84d6e0580c12f74880574f8179d934714c7235b9
|
0141a8f26284dbfd824d9b054a899f6b6d7510eb
|
/abc/abc/abc156/c.cpp
|
9d68f16e1cc895766370cee843fe851bfc320f82
|
[] |
no_license
|
yunotama/atcoder
|
2da758f479da6aaaa17c88f13995e42554cb0701
|
ddb16580416d04abaa6c4d543dc82a62706d283a
|
refs/heads/master
| 2021-03-15T06:20:52.038947
| 2020-03-12T13:19:34
| 2020-03-12T13:19:34
| 246,830,843
| 0
| 0
| null | 2020-03-12T13:19:36
| 2020-03-12T12:39:16
| null |
UTF-8
|
C++
| false
| false
| 513
|
cpp
|
c.cpp
|
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < n; i++)
#define INF 10000000000
using namespace std;
using ll = long long;
int main()
{
int n;
cin >> n;
vector<int> x(n);
rep(i,n){
cin >> x[i];
}
sort(x.begin(), x.end());
int ans = 100000000, tmp;
for (int i = 1; i <= 100;i++)
{
tmp = 0;
rep(j,n){
tmp += (x[j] - i)*(x[j] - i);
}
ans = min(ans, tmp);
}
cout << ans << endl;
}
|
a8d089766627da6131f70d22b3308eb9930b5f4e
|
49aef59a754ded1be83520c78a2d55b58bf57336
|
/Common/Graphics/Chart.hpp
|
097aa633c4ce2b83ad0668dd14041f5635d353dc
|
[] |
no_license
|
andreyV512/Coating
|
048fe1764e6d0beb91e3d4832fb660f058f97b6b
|
2d98bed2ff91faeb8561d99e6253bcd39123e829
|
refs/heads/master
| 2023-04-14T20:25:14.481248
| 2021-04-27T10:34:04
| 2021-04-27T10:34:04
| 347,822,035
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 710
|
hpp
|
Chart.hpp
|
#pragma once
#include <Windows.h>
#include <Gdiplus.h>
#include "templates/typelist.hpp"
using namespace Gdiplus;
#pragma warning(disable : 4355)
template<class Chart, class List>class ChartDraw : public Chart
{
template<class O, class P>struct __draw__{void operator()(O &o){
o.Draw();
}};
public:
typedef List items_list;
typedef VL::Factory<List> TItems;
TItems items;
public:
ChartDraw(Gdiplus::Bitmap *&backScreen_): Chart(backScreen_), items((Chart &)*this){}
void Draw(Gdiplus::Graphics &graph)
{
Chart::Draw(graph);
VL::foreach<List, __draw__>()(items);
}
template<class lst>void DrawItems(Gdiplus::Graphics &graph)
{
Chart::Draw(graph);
VL::foreach<lst, __draw__>()(items);
}
};
|
a06af74cdaad1f5d237f6059ad72af3d8686a9dd
|
7a0a85326daf6499b6fa59cf26362b214015e988
|
/include/webots_ros_interface/motor.h
|
fd9d252b4e45f8eddd2a9d13fecf59574a9ba9b7
|
[] |
no_license
|
janfelixklein/webots_ros_interface
|
2b8bda83b30e882086f92a4edeba1ed2220e1029
|
cb115a624ce87edd744409f875cd9b6dc1650f99
|
refs/heads/master
| 2020-06-13T04:01:45.613495
| 2019-08-01T07:50:20
| 2019-08-01T07:50:20
| 194,527,487
| 0
| 0
| null | 2019-08-01T07:50:21
| 2019-06-30T14:48:30
|
C++
|
UTF-8
|
C++
| false
| false
| 1,956
|
h
|
motor.h
|
#include <ros/ros.h>
#include <webots_ros/set_float.h>
#include <webots_ros/Float64Stamped.h>
#include <std_msgs/Float64.h>
#include <actionlib/server/simple_action_server.h>
#include <webots_ros_interface/position_controlAction.h>
class Motor
{
public:
Motor(ros::NodeHandle* nh_pointer, std::string controllerName, std::string motorName, std::string controlType, std::string cmdTopic);
Motor(ros::NodeHandle* nh_pointer, std::string controllerName, std::string motorName, std::string controlType, std::string sensorTopic, std::string actionName);
void sendPosition(double position);
void sendVelocity(double velocity);
std::string controllerName_;
std::string motorName_;
std::string motorPositionServicePath_;
std::string motorVelocityServicePath_;
double processValue_;
std::string cmdTopic_;
std::string sensorTopic_;
std::string controlType_;
bool actionInterface_;
std::string actionName_;
private:
void init();
bool initPositionClient();
bool initVelocityClient();
bool initVelocityControl();
void createCmdSub();
void createSensorSub();
void cmdCallback(const std_msgs::Float64::ConstPtr& msg);
void sensorCallback(const webots_ros::Float64Stamped::ConstPtr& msg);
void executeCB(const webots_ros_interface::position_controlGoalConstPtr &goal);
ros::NodeHandle* nh_;
ros::ServiceClient MotorPositionClient_;
ros::ServiceClient MotorVelocityClient_;
ros::Subscriber cmdSub_;
ros::Subscriber sensorSub_;
actionlib::SimpleActionServer<webots_ros_interface::position_controlAction> *as_;
// create messages that are used to published feedback/result
webots_ros_interface::position_controlFeedback feedback_;
webots_ros_interface::position_controlResult result_;
};
|
a306ba9375ff3c640a594473a2d15eee17f2efb6
|
9fb3ac362370dbaaec9ff680ce530eca041d4b08
|
/Lab_6_Vector_Math/I_FlightPath/FlightPath.cpp
|
89b8dd43a1b45d2253b66b8c6e693e263ddc0c50
|
[] |
no_license
|
ankurpatel42/COSC363-Computer-Graphics
|
49baaf69b60e48fe496b121cdef71f677ae34106
|
15e4e4a33c57c07d6344a8874e186a37d6385217
|
refs/heads/main
| 2023-07-08T21:48:44.334582
| 2021-08-13T02:26:55
| 2021-08-13T02:26:55
| 395,497,556
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,218
|
cpp
|
FlightPath.cpp
|
// ========================================================================
// COSC363: Computer Graphics (2021)
//
// FILE NAME: FlightPath.cpp
// See Lab06.pdf for details.
// ========================================================================
#include <iostream>
#include <fstream>
#include <cmath>
#include <GL/freeglut.h>
using namespace std;
float angle = -40; //Scene rotation angle
const int NPTS = 70; //Number of points on the flight path
int option = 1; //1: model view, 2: room view
float ptx[NPTS], pty[NPTS], ptz[NPTS];
GLUquadric *q;
int indx = 0;
void timer(int value) {
if (value < 10000) {
if (indx == NPTS) {
indx = 0;
glutPostRedisplay();
glutTimerFunc(65, timer, value);
}
else {
indx++;
glutPostRedisplay();
glutTimerFunc(65, timer, value);
}
}
}
//Reads flight path data from FlightPath.txt
void loadFlightPath()
{
ifstream ifile;
ifile.open("FlightPath.txt");
if (!ifile){
std::cout << "File not found!" << std::endl;
throw;
}
for (int i = 0; i < NPTS; i++)
ifile >> ptx[i] >> pty[i] >> ptz[i];
ifile.close();
}
void drawFin()
{
glColor3f(1, 0, 0);
glNormal3f(0, 0, 1);
glBegin(GL_TRIANGLES);
glVertex3f(-1, 0.5, 0);
glVertex3f(2, 0.5, 0);
glVertex3f(-1, 4, 0);
glEnd();
}
void drawModel()
{
glColor3f(0, 1, 1);
glPushMatrix(); //body
glRotatef(90, 0, 1, 0);
gluCylinder(q, 1, 1, 7, 36, 5);
gluDisk(q, 0, 1, 36, 3);
glPopMatrix();
glColor3f(0, 0, 1);
glPushMatrix(); //nose
glTranslatef(7, 0, 0);
glRotatef(90, 0, 1, 0);
glutSolidCone(1, 2, 36, 3);
glPopMatrix();
for (int i = 0; i < 3; i++) //3 fins
{
glPushMatrix();
glRotatef(120 * i, 1, 0, 0);
drawFin();
glPopMatrix();
}
}
void drawRoom()
{
glDisable(GL_LIGHTING);
glColor3f(0.7, 0.7, 0.7); //Floor colour
for(int i = -100; i <= 100; i +=5)
{
glBegin(GL_LINES); //A set of grid lines on the floor-plane
glVertex3f(-100, 0, i);
glVertex3f(100, 0, i);
glVertex3f(i, 0, -100);
glVertex3f(i, 0, 100);
glEnd();
}
glEnable(GL_LIGHTING);
glBegin(GL_QUADS); //4 walls
glColor3f(0.75, 0.75, 0.75);
glNormal3f(0, 0, 1);
glVertex3f(-100, 0, -100);
glVertex3f(100, 0, -100);
glVertex3f(100, 140, -100);
glVertex3f(-100, 140, -100);
glNormal3f(0, 0, -1);
glVertex3f(-100, 0, 100);
glVertex3f(100, 0, 100);
glVertex3f(100, 140, 100);
glVertex3f(-100, 140, 100);
glColor3f(1, 0.75, 0.75);
glNormal3f(1, 0, 0);
glVertex3f(-100, 0, -100);
glVertex3f(-100, 140, -100);
glVertex3f(-100, 140, 100);
glVertex3f(-100, 0, 100);
glNormal3f(-1, 0, 0);
glVertex3f(100, 0, -100);
glVertex3f(100, 140, -100);
glVertex3f(100, 140, 100);
glVertex3f(100, 0, 100);
glColor3f(1, 1, 0.6);
glNormal3f(0, -1, 0);
glVertex3f(-100, 140, 100);
glVertex3f(100, 140, 100);
glVertex3f(100, 140, -100);
glVertex3f(-100, 140, -100);
glEnd();
}
void drawFlightPath()
{
glColor3f(0.0, 0.0, 1.0);
glDisable(GL_LIGHTING);
glBegin(GL_LINE_LOOP);
for (int i = 0; i < NPTS; i++)
glVertex3f(ptx[i], pty[i], ptz[i]);
glEnd();
glEnable(GL_LIGHTING);
}
//---------------------------------------------
void initialise(void)
{
float grey[4] = {0.2, 0.2, 0.2, 1.0};
float white[4] = {1.0, 1.0, 1.0, 1.0};
float black[4] = { 0, 0, 0, 1 };
q = gluNewQuadric();
loadFlightPath();
glEnable(GL_DEPTH_TEST);
glEnable(GL_NORMALIZE);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glLightfv(GL_LIGHT0, GL_AMBIENT, grey);
glLightfv(GL_LIGHT0, GL_DIFFUSE, white);
glLightfv(GL_LIGHT0, GL_SPECULAR, white);
glEnable(GL_SMOOTH);
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, black);
glClearColor (1.0, 1.0, 1.0, 0.0);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluPerspective(80.0, 1.0, 10.0, 500.0);
}
//------------------------------------------
void display(void)
{
float lgt_pos[]={0, 50.0f, 0.0f, 1.0f}; //light0 position (above the origin)
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
if (option == 2)
gluLookAt(0., 10, 30.0, 0., 0., 0., 0., 1., 0.);
else
gluLookAt(0., 80, 100.0, 0., 50., 0., 0., 1., 0.);
glLightfv(GL_LIGHT0, GL_POSITION, lgt_pos); //light position
glRotatef(angle, 0, 1, 0);
//points from vector P
float currentPointOnPath_x = ptx[indx];
float currentPointOnPath_y = pty[indx];
float currentPointOnPath_z = ptz[indx];
//points from vector q
float nextPointOnPath_x = ptx[indx+1];
float nextPointOnPath_y = pty[indx+1];
float nextPointOnPath_z = ptz[indx+1];
//vector v (q - p)
float v[] = {nextPointOnPath_x - currentPointOnPath_x, nextPointOnPath_y - currentPointOnPath_y, nextPointOnPath_z - currentPointOnPath_z};
//--------------------------normalize v-----------------------------
float length_v = 0;
for(int i = 0; i < 3; i++) {
length_v += (pow(v[i], 2));
}
length_v = pow(length_v, 0.5);
for(int i = 0; i < 3; i++) {
v[i] = v[i] / length_v; //vector v now normalized
}
//------------------------------------------------------------------
float u[] = {1.0, 0.0, 0.0};
float dot_product_u_and_v = 0;
for (int i = 0; i < 3; i++) {
dot_product_u_and_v += (u[i] * v[i]);
}
float theta = acos(dot_product_u_and_v) * 180.0 / M_PI;
float w[] = {(u[1] * v[2]) - (u[2] * v[1]), (u[2] * v[0]) - (u[0] * v[2]), (u[0] * v[1]) - (u[1] * v[0])}; //cross product (w = axis of rotation)
drawRoom();
drawFlightPath();
glPushMatrix();
glTranslatef(currentPointOnPath_x, currentPointOnPath_y, currentPointOnPath_z);
glRotatef(theta, w[0], w[1], w[2]);
drawModel();
glPopMatrix();
glutSwapBuffers();
}
// Keyboard call-back function
void keyboard(unsigned char key, int x, int y)
{
if (key == '1') option = 1;
else if (key == '2') option = 2;
glutPostRedisplay();
}
// Special keyboard call-back function
void special(int key, int x, int y)
{
if(key==GLUT_KEY_LEFT) angle--;
else if(key==GLUT_KEY_RIGHT) angle++;
glutPostRedisplay();
}
//----------------------------------------------
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize (700, 700);
glutInitWindowPosition (100, 100);
glutCreateWindow ("Flight");
initialise ();
glutTimerFunc(50, timer, 0);
glutDisplayFunc(display);
glutSpecialFunc(special);
glutKeyboardFunc(keyboard);
glutMainLoop();
return 0;
}
|
f84d5bf18fe20acd9892cad524314280dcae43a4
|
c73cc130284575492876b11193963f86fdc03b1e
|
/cpp/template_metaprogramming/constexpr/template_argument_test.cpp
|
0e11c43b121066eadd514730dc2442b17d88b482
|
[] |
no_license
|
nae9on/_help_
|
d3d46f68019299a8c6322ca10b511c0880396658
|
afa4be3caeba6dc1c1d63b3bb137039cb7800be6
|
refs/heads/master
| 2023-01-24T15:25:09.953564
| 2023-01-22T21:15:09
| 2023-01-22T21:15:09
| 178,942,396
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 603
|
cpp
|
template_argument_test.cpp
|
/*
* template_argument_test.cpp
*
* Created on: Aug 19, 2019
* Author: akadar
*/
#include <iostream>
#include <string>
template<typename T> bool odd_or_even(T x){
constexpr bool checkInt = std::is_same<T, int>::value;
// static_assert expects a bool constexpr
static_assert(checkInt,"template argument is not int");
return x%2;
}
int template_argument_test(){
int x = 10;
std::cout << (odd_or_even(x) ? "Is odd\n" : "Is even\n");
float y = 10;
//std::cout << (odd_or_even(y) ? "Is odd" : "Is even"); // Error static assertion failed
std::cout<<"y = "<<y<<"\n";
return 0;
}
|
d591f0b3f38976a507884960f0ccc4612b112d54
|
ee191db1a2b25c89f9987b0e264fe2ffbaa8977b
|
/libraries/LoopCheck/LoopCheck.h
|
044b02398384d1a61b4cab63ef8ffd2722d55d8e
|
[] |
no_license
|
RobertPatzke/homeautomation
|
755845c5d5edae88af9dd3daea78db6bdd2cf1aa
|
5278dac6e422ac3724efcb1c1ccf0d829b824a59
|
refs/heads/master
| 2023-03-06T05:05:18.953054
| 2021-05-11T13:05:32
| 2021-05-11T13:05:32
| 103,811,109
| 6
| 5
| null | 2018-02-17T09:01:48
| 2017-09-17T07:29:38
|
C++
|
UTF-8
|
C++
| false
| false
| 9,290
|
h
|
LoopCheck.h
|
//-----------------------------------------------------------------------------
// Thema: Social Manufacturing Network / Development Environment
// Datei: LoopCheck.h
// Editor: Robert Patzke
// URI/URL: www.mfp-portal.de
//-----------------------------------------------------------------------------
// Lizenz: CC-BY-SA (siehe Wikipedia: Creative Commons)
//
#ifndef _LoopCheck_h
#define _LoopCheck_h
//-----------------------------------------------------------------------------
#define PeriodMinTime 5000
// Wenn der Aufrufzyklus der Loop diese Zeit (in Mikrosekunden) überschreitet,
// dann wird ein Alarmbit gesetzt und ein Alarmzähler inkrementiert
#ifndef LoopScreeningGrades
#define LoopScreeningGrades 6
#endif
#define NrOfTimerTasks 10
#define NrOfOnceTasks 4
#define NrOfToggleTasks 4
#define CalcAverageDepth 32
#ifdef UseGithubPath
#include "../environment/environment.h"
#else
#include "environment.h"
#endif
#if defined(smnSimLinux) || defined(smnSimWindows)
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define SYSMICSEC locMicros()
#endif
#ifdef smnSimWindows
#include <Windows.h>
#endif
#ifdef smnSloeber
#include "Arduino.h"
#define SYSMICSEC micros()
#endif
#ifdef smnESP8266
#define DIV(x,y) locDiv(x,y)
#else
#define DIV(x,y) div(x,y)
#endif
typedef struct _OpHourMeter
{
int Years;
int Days;
int Hours;
int Minutes;
int Seconds;
int Milliseconds;
} OpHourMeter;
typedef struct _lcDateTime
{
int Year;
int Month;
int Day;
int Hour;
int Minute;
int Second;
int Millisecond;
} lcDateTime;
typedef struct _LoopStatistics
{
unsigned int loopTime; // Schleifenzeit in Mikrosekunden
unsigned int loopMaxTime; // Maximale Schleifenzeit
unsigned int loopMinTime; // Minimale Schleifenzeit
unsigned int loopAvgTime; // Mittlere Schleifenzeit
unsigned int bgTime; // Zeit außerhalb der Schleife
unsigned int bgMaxTime; // Maximale Außenzeit
unsigned int bgMinTime; // Minimale Außenzeit
unsigned int bgAvgTime; // Mittlere Außenzeit
unsigned int loopPeriod; // Zeit zwischen loop-Aufrufen
unsigned int maxPeriod; // Maximale Aufrufdistanz
unsigned int minPeriod; // Minimale Aufrufdistanz
bool periodAlarm; // Aufrufdistanz > PeriodMinTime
unsigned int alarmCount; // Anzahl der Überschreitungen
unsigned int rtScreening[LoopScreeningGrades];
// Echtzeitüberwachung (Klassierung der ms Überschreitungen)
} LoopStatistics;
// ---------------------------------------------------------------------------
// class LoopCheck
// ---------------------------------------------------------------------------
//
class LoopCheck
{
// -------------------------------------------------------------------------
// Klassenspezifische Datentypen
// -------------------------------------------------------------------------
//
typedef struct _TimerTask
{
bool counterStarted;
bool finished;
bool firstRun;
unsigned long startCount;
unsigned long runCounter;
unsigned int repCounter;
} TimerTask;
typedef struct _OnceTask
{
bool finished;
bool firstRun;
unsigned int waitCounter;
} OnceTask;
private:
// -------------------------------------------------------------------------
// Lokale Variablen
// -------------------------------------------------------------------------
//
unsigned long checkStartMicros; // Zeit des ersten Aufrufs von begin()
unsigned long backgroundMicros; // Zeit, die außerhalb von loop()
// verstrichen ist (in Mikrosekunden)
unsigned long loopMicros; // Zeit, die innerhalb von loop()
// verstrichen ist (in Mikrosekunden)
unsigned long loopStartMicros; // Loop-Startzeit (us seit CPU-Start)
unsigned long lastClockMicros;
unsigned long lastStartMicros;
unsigned long lastRestMicros;
unsigned long loopEndMicros; // Loop-Endezeit (us seit CPU-Start)
unsigned long clockCycleMicros; // Abstand zwischen zwei clock ticks
unsigned long mainStartMicros; // Zählerstand bei Programmstart
unsigned long backgroundMaxMicros; // Maximale Zeit außerhalb loop()
unsigned long backgroundMinMicros; // Minimale Zeit außerhalb loop()
unsigned long backgroundAvgMicros; // Mittlere Zeit außerhal loop() {32}
unsigned long backgroundSumMicros; // Summe für Mittelwertberechnung
unsigned long loopMaxMicros; // Maximale Zeit innerhalb loop()
unsigned long loopMinMicros; // Minimale Zeit innerhalb loop()
unsigned long loopAvgMicros; // Mittlere Zeit innerhalb loop()
unsigned long loopSumMicros; // Summe für Mittelwertberechnung
unsigned long loopCounter; // Anzahl der loop()-Durchläufe
unsigned int loopScreening[LoopScreeningGrades];
int calcAvgCounter; // Zähler für die Mittelwertbildung
bool firstLoop; // Spezielle Kennzeichnung erste loop()
bool taskHappened; // Kennzeichnung: Es lief ein LoopTask
TimerTask timerTaskList[NrOfTimerTasks]; // Steuerung der zyklischen
// Tasks (Timer-Ersatz in loop())
OnceTask onceTaskList[NrOfOnceTasks];
bool toggleTaskList[NrOfToggleTasks];
int year; // Betriebsstundenzähler gesamt
int day;
int hour;
int min;
int sec;
int msec;
bool toggleMilli;
int dtYear; // Zeit / Uhr
int dtMonth;
int dtDay;
int dtHour;
int dtMin;
int dtSec;
int dtmSec;
int febLen;
char dateTimeStr[30];
unsigned int periodMicros; // Zeit zwischen zwei loop-Aufrufen
unsigned int periodMinMicros;
unsigned int periodMaxMicros;
bool periodFailAlarm; // periodMicros > Millisekunde
unsigned int periodFailCount; // Anzahl der Überschreitungen
unsigned long measureTimeSet; // Mikrosekunden-Offset Zeitmessung
private:
// -------------------------------------------------------------------------
// Lokale Funktionen
// -------------------------------------------------------------------------
//
void initTasks();
void initStatistics();
void initClock();
unsigned long locMicros();
#ifdef smnESP8266
div_t locDiv(int numer, int denom);
#endif
public:
// -------------------------------------------------------------------------
// Konstruktoren und Initialisierungen
// -------------------------------------------------------------------------
//
LoopCheck();
// -------------------------------------------------------------------------
// Anwenderfunktionen
// -------------------------------------------------------------------------
//
void begin(); // Diese Funktion muss am Anfang der Schleife aufgerufen
// werden.
void end(); // Diese Funktion muss am Ende der Schleife aufgerufen
// werden.
bool timerMicro(int taskIdx, unsigned long repeatTime, unsigned int repetitions);
// Diese Funktion muss als Bedingung (if) aufgerufen werden, um den
// nachfolgenden Block {} mit der Wiederholzeit <repeatTime> auszuführen
// Für jede Taskschleife muss ein anderer Index <taskIdx> aus dem Bereich
// 0 <= taskIdx < MaxNrOfLoopTasks angegeben werden.
// Mit <repetitions> wird angegeben, wie oft der Durchlauf überhaupt erfolgt.
// Der Wert 0 gibt an, dass der Task für immer läuft
bool timerMilli(int taskIdx, unsigned long repeatTime, unsigned int repetitions);
bool once(int taskIdx, unsigned int nrOfLoops);
// Diese Funktion liefert nur einmal den Wert <true>
// nach Ablauf von nrOfLoops Aufrufen
bool toggle(int taskIdx);
// Diese Funktion liefert abwechselnd die Werte <true> oder <false>
unsigned long timerCycle(int taskIdx);
// Rückgabe des aktuellen Timerablaufes (startet ab 0).
unsigned long operationTime(OpHourMeter *opHourMeter);
// Die Zeit ab Start der CPU
unsigned long getStatistics(LoopStatistics *statistics);
// Statistik über Ablaufzeiten
void resetStatistics();
// Rücksetzen der Statistikdaten
bool setDateTime(const char *dtStr);
// Setzen der Uhr über standardisierten String
bool setDateTime(lcDateTime dt);
// Setzen der Uhr über lokal definierte Struktur
bool getDateTime(lcDateTime *dt);
// Abfragen der Uhr über lokal definierte Struktur
const char * refDateTime();
// Zeiger auf Datum/Uhrzeit holen
void startTimeMeasure();
// Zeitmessung starten
unsigned long getTimeMeasure();
// Zeitmesswert holen
// -------------------------------------------------------------------------
// Anwendervariablen
// -------------------------------------------------------------------------
//
};
//-----------------------------------------------------------------------------
#endif
|
581dc8d26d6c1d6ff6509a750fab9123464bdf68
|
1a584afbab70f63fbbaae896bfa56147a195b32c
|
/cekeikon/kcek/rndtrain.cpp
|
4a5aa68f376e1abecc96b8d11fa98ff56e2f4cc7
|
[] |
no_license
|
joaosoares/hae2
|
09151ddc11b833907123b879026426783c2bc2b4
|
6e0a07a2dfb79f1d9663b4a7f0a51a8fdddf162b
|
refs/heads/master
| 2020-03-25T23:58:16.886200
| 2018-08-10T16:42:37
| 2018-08-10T16:42:37
| 144,301,453
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 603
|
cpp
|
rndtrain.cpp
|
#include <cekeikon.h>
void rndtrain(int argc, char** argv)
{ if (argc<3) erro("Erro: RndTrain treino.img boo.xml (ou .yaml)");
Mat_<FLT> tr; le(tr,argv[1]);
{ // se tem menos de 20 linhas, copia para dar pelo menos 20 linhas.
int nl=tr.rows;
int i=0;
while (tr.rows<20) {
tr.push_back(tr.row(i));
i++;
if (i>=nl) i=0;
}
}
Mat_<FLT> trent=tr(Rect(0,0,tr.cols-1,tr.rows));
Mat_<FLT> trsai=tr(Rect(tr.cols-1,0,1,tr.rows));
printf("Treinando...\n");
CvRTrees ind;
ind.train(trent,CV_ROW_SAMPLE,trsai);
ind.save(argv[2]);
}
|
3ade04605e9f8805c66a096360b60e810500da07
|
e255448fb9950c1426014406ad9ce5d330c4f141
|
/CppTutorials/School/Problem-Based-Learning/main.cpp
|
c3e2732aaf6129330a9f2c87088980cfc7611429
|
[] |
no_license
|
Jayz07/PersonalTutorials
|
80e6faf0ca7a143de30d3731d134105a22e2d531
|
3736a40f56a2eb9594b9dd752ac27a93bcc1f9ee
|
refs/heads/master
| 2021-01-20T19:26:24.060387
| 2016-07-27T14:27:56
| 2016-07-27T14:27:56
| 62,096,876
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,565
|
cpp
|
main.cpp
|
#include <iostream>
#include <fstream>
#include <string>
#include <windows.h>
#include<direct.h>
using namespace std;
void loginScreen();
void doLogin();
void addUser();
void logOut();
void employeeScreen(string user, string permissionName);
void adminScreen(string user, string permissionName);
void employeeSelection(int option, string user, string permissionName);
void takeOrder(string user, string permissionName);
void closeOrder();
void modifyOrder();
void showMenu();
int main(){
loginScreen();
cout <<"Press Enter to Continue";
cin.ignore();
cin.get();
return 0;
}
void doLogin(){
string userIn, passIn, user, pass, permissionName;
int permission;
int loginStatus;
ifstream reader;
reader.open("Resource//Login//User.txt");
if(!reader){
cout <<"WARNING FILE NOT FOUND" <<endl;
cout <<"executing admin mode" <<endl;
adminScreen("DEBUG","DEBUG");
}
cout << "Username: ";
cin>>userIn;
cout << "Password: ";
cin >>passIn;
while(true){
reader >>user >>pass >>permission;
if(!(user.compare(userIn)) && !(pass.compare(passIn))){
loginStatus = 1;
break;
}
if(reader.eof()){
loginStatus = 2;
break;
}
}
switch(loginStatus){
case 1:
Sleep(1000);
cout <<"Login Success" <<endl
<<"Welcome " <<userIn <<endl;
Sleep(1000);
break;
case 2:
Sleep(1000);
cout <<"Invalid username or password" <<endl;
Sleep(1000);
loginScreen();
break;
}//end of login
//Enter screen depending on permission
switch(permission){
case 1:
permissionName = "EMPLOYEE";
employeeScreen(user,permissionName);
break;
case 2:
//adminScreen(user,permissionName);
break;
}
}
void employeeScreen(string user, string permissionName){
int option;
system("cls");
cout <<"Jayztech Restaurant Management System" <<endl;
cout <<"Welcome " <<user <<". You are logged in as " <<permissionName <<endl;
cout <<"---------------------------------" <<endl;
cout <<"Please select option" <<endl
<<"1. Take Order" <<endl
<<"2. Close Order" <<endl
<<"3. Modify Order" <<endl
<<"4. Show Menu" <<endl
<<"5. Logout" <<endl
<<"---------------------------------" <<endl;
cout <<"Option: ";
cin>>option;
while(cin.fail()){
cin.clear();
cin.ignore();
employeeScreen(user, permissionName);
}
employeeSelection(option, user, permissionName);
}
void loginScreen(){
system("cls");
cout <<"Welcome to Jayztech Restaurant Management System" <<endl
<<"Please Login" <<endl;
doLogin();
}
void employeeSelection(int option, string user, string permissionName){
switch(option){
case 1:
takeOrder(user, permissionName);
break;
case 2:
//closeOrder();
break;
case 3:
//modifyOrder();
break;
case 4:
//showMenu();
break;
case 5:
logOut();
break;
default:
cout <<"Incorrect Input" <<endl;
Sleep(1000);
employeeScreen(user,permissionName);
}
}
void takeOrder(string user, string permissionName){
int table, customer;
ofstream order;
system("cls");
cout <<"Jayztech Restaurant Management System" <<endl;
cout <<"Welcome " <<user <<". You are logged in as " <<permissionName <<endl;
cout <<"---------------------------------" <<endl;
cout <<"Table: ";
cin >>table;
while(cin.fail()){
cin.clear();
cin.ignore(1000, '\n');
cout <<"Please input Number";
cout <<"Table: ";
cin >>table;
}
cout <<"Number of Customers: ";
cin>>customer;
}
void logOut(){
cout <<"Logging Out....." <<endl;
Sleep(2000);
loginScreen();
}
void addUser(){
string user[9999];
string pass[9999];
string permission[9999];
int numElements = 0;
string userIn, passIn;
int permissionIn;
char check;
ifstream reader;
reader.open("Resource//Login//User.txt");
if(!reader){
cout <<"File not found" <<endl <<"Making new file...."<<endl;
ofstream makeFile;
int check = _mkdir("Resource");
check = _mkdir("Resource//Login");
makeFile.open("Resource//Login//User.txt");
makeFile.close();
if(check == 0){
cout <<"File successfully made" <<endl;
}
}else{
while(!reader.eof()){
reader >>user[numElements] >>pass[numElements] >>permission[numElements];
numElements++;
}
}
reader.close();
cout <<"Adding user system" <<endl;
cout <<"Enter username: ";
cin >> userIn;
cout <<"Enter password: ";
cin >> passIn;
cout <<"1 for employee 2 for admin" <<endl;
cin >>permissionIn;
while(cin.fail()||!(permissionIn == 1||permissionIn ==2)){
cin.clear();
cin.ignore(INT_MAX, '\n');
cout <<"1 for employee 2 for admin" <<endl;
cin>>permissionIn;
}
cout <<"Adding username: " <<userIn <<" with password: " <<passIn <<" with permission " <<permissionIn <<endl;
cout <<"Enter Y to continue, anything to cancel the program" <<endl;
cin >>check;
if(toupper(check) == 'Y'){
ofstream writer;
writer.open("Resource/Login/User.txt");
for(int x = 0; x <numElements; x++){
writer << user[x] <<" " << pass[x] <<" " <<permission[x] <<endl;
}
writer << userIn <<" " << passIn<<" " <<permissionIn;
writer.close();
cout <<"Operation successful";
}else{
cout <<"operation cancelled" <<endl;
}
}
void showMenu(){
string fcode[99999];
string fname[99999];
double fprice[99999];
string bcode[99999];
string bname[99999];
double bprice[99999];
ifstream fReader;
fReader.open("Resource//Menu//Food.txt");
//not done yet
}
|
fdc48ffbe6c9fe498e52a7a2c34d73fcd6b874dd
|
f22df2f3323dad233e185ed28deb15d62d957ca3
|
/GestCollOnQt/GUI/Biblioteca/bibliotecaform.h
|
f77512658a76ccbff34009fef57738a97df11cdc
|
[] |
no_license
|
mirkoviviani76/gestcoll
|
a4779bb0d9e0a8e64a8c7212abd8a6a4e19b5ca0
|
7477c0337183d6324993f29ac167d64df76794e1
|
refs/heads/master
| 2021-01-10T06:42:52.181258
| 2016-02-12T09:52:11
| 2016-02-12T09:52:11
| 51,519,105
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 931
|
h
|
bibliotecaform.h
|
#ifndef BIBLIOTECAFORM_H
#define BIBLIOTECAFORM_H
#include <QWidget>
#include "bibliotecasortfilterproxymodel.h"
#include <bibliotecaitem.h>
#include "bibliotecaxml.h"
namespace Ui {
class BibliotecaForm;
}
class BibliotecaForm : public QWidget
{
Q_OBJECT
public:
explicit BibliotecaForm(QWidget *parent = 0);
~BibliotecaForm();
void setModel(BibliotecaSortFilterProxyModel* model);
void setEditable(bool editable);
void fillData();
protected:
void changeEvent(QEvent *e);
private:
BibliotecaSortFilterProxyModel* model;
Ui::BibliotecaForm *ui;
bool editable;
private slots:
void on_listView_activated(QModelIndex index);
void on_textBrowser_anchorClicked(const QUrl &arg1);
void on_filter_textChanged(const QString &filterText);
public slots:
bool selectItem(const BibliotecaItem* item);
};
#endif // BIBLIOTECAFORM_H
|
321c98f15977dc5901e94c7e39c166418e069639
|
af9278d9d20af9e4d1cb69b473210196235e43e1
|
/TCPSocket.h
|
898090e16ffa864acde2614496c61f1444f78cb9
|
[] |
no_license
|
lishion/ISocket
|
2144b6d415b867509ba4b7a4c9441ad488d84d42
|
dabc01de9998a79e84a7a6fd3115b919052578ab
|
refs/heads/master
| 2021-01-23T01:18:44.694013
| 2017-04-12T02:40:02
| 2017-04-12T02:40:02
| 85,899,373
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 934
|
h
|
TCPSocket.h
|
#pragma once
#include "Socket.h"
namespace ISOCKET{
class TCPSocket:public Socket
{
public:
TCPSocket(void);
TCPSocket* startListen(int max);//开始监听,max 连接队列最大值
TCPSocket* startListen(); //开始监听,默认10个
TCPSocket* getConection(); //得到连接
void getConection(TCPSocket *socket);//得到连接并用于初始化一个Socket*类型的指针
TCPSocket* connectTo(char *s,int port);//建立连接
TCPSocket* connectTo(ISocketAddr addr);
int read(char *buf,int len,const Socket *socket);//通过一个Socket对象接收,多用于服务器
int read(char *buf,int len);//利用自身的SOCKET接收,多用于客户端
int read(char *buf,int len,SOCKET socket);//通过原始的SOCKET接受
int write(char *buf,int len,const Socket* socket);//发送,同上
int write(char *buf,int len);
int write(char *buf,int len,SOCKET socket);
~TCPSocket(void);
};
}
|
9ce70da60b1aff401c68fe67bc7bba2437f5ec23
|
4c1439e5293ab4a5b3d5f9e46feda118a240baf4
|
/src/io/queryReader/CSVQueryReader.hpp
|
6e4f0ad27110ff5af12aced47670ff0a9ead6477
|
[] |
no_license
|
lucdon/LCRIndexing
|
ac13cd77a3bea400832d44d00b098c9bc66e452e
|
9f5adb426a5b70f3b57efb2d8d6c4867995e23f2
|
refs/heads/master
| 2023-06-17T18:01:11.244331
| 2021-07-08T20:37:36
| 2021-07-08T20:37:36
| 382,639,025
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 418
|
hpp
|
CSVQueryReader.hpp
|
#pragma once
#include "io/QueryReader.hpp"
class CSVQueryReader : public QueryReader {
private:
inline static const std::string fileType = ".csv";
public:
const std::string &fileName() override {
return fileType;
}
std::unique_ptr<ReachQuerySet> readQueries(const std::string &filePath) override;
std::unique_ptr<LCRQuerySet> readLabeledQueries(const std::string &filePath) override;
};
|
8f9d877b9bce8ca071941fbb39c68de297dafc14
|
3437b352757b15f463096dbe8782b2b60847ea32
|
/week_4/unique_ptr/unique_ptr.h
|
957faa4b00bff7a9818a4431dc202a70f65ea0fb
|
[] |
no_license
|
MercyFlesh/cxx_brown_belt
|
ef73dcaaaaac6b1b36bfec6e6d5811fee5498cee
|
8f15d04feff14704c1e011b9e4b0e4c72f7a1e7e
|
refs/heads/master
| 2023-03-15T02:38:25.354700
| 2021-03-23T21:37:46
| 2021-03-23T21:37:46
| 308,676,829
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,206
|
h
|
unique_ptr.h
|
#pragma once
#include <cstddef>
template <typename T>
class UniquePtr {
private:
T* ptr_;
public:
UniquePtr()
: ptr_(nullptr)
{
}
UniquePtr(T* ptr)
: ptr_(ptr)
{
}
UniquePtr(const UniquePtr&) = delete;
UniquePtr(UniquePtr&& other)
{
ptr_ = other.ptr_;
other.ptr_ = nullptr;
}
UniquePtr& operator= (const UniquePtr&) = delete;
UniquePtr& operator= (std::nullptr_t)
{
delete ptr_;
ptr_ = nullptr;
return *this;
}
UniquePtr& operator= (UniquePtr&& other)
{
delete ptr_;
ptr_ = other.ptr_;
other.ptr_ = nullptr;
return *this;
}
~UniquePtr()
{
delete ptr_;
ptr_ = nullptr;
}
T& operator* () const
{
return *ptr_;
}
T* operator-> () const
{
return ptr_;
}
T* Release()
{
T* temp = move(ptr_);
ptr_ = nullptr;
return temp;
}
void Reset(T* ptr)
{
delete ptr_;
ptr_ = ptr;
}
void Swap(UniquePtr& other)
{
swap(ptr_, other.ptr_);
}
T* Get() const
{
return ptr_;
}
};
|
fd9e515e83ce40d1826be880621c2e19e86eea4c
|
a8fa56874784c26ee268b0a0d14c69ee27bf2905
|
/source/laplace/math/spline.impl.h
|
93427b610f30c333f5aa07af262faea1bba20445
|
[
"MIT"
] |
permissive
|
ogryzko/laplace
|
00d89ee0b68153d1470781298009dc7fc61165aa
|
be63caa0c6d1c4fceab02ab5b41b6d307ef7baaf
|
refs/heads/main
| 2023-08-27T13:36:27.634379
| 2021-09-21T06:17:02
| 2021-09-21T06:17:02
| 416,058,413
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,442
|
h
|
spline.impl.h
|
/* laplace/math/spline.impl.h
*
* Copyright (c) 2021 Mitya Selivanov
*
* This file is part of the Laplace project.
*
* Laplace 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 MIT License for more details.
*/
#ifndef laplace_math_spline_impl_h
#define laplace_math_spline_impl_h
namespace laplace::math {
template <typename time_, typename type_>
inline void spline<time_, type_>::set_linear(type_ begin,
type_ end) {
this->m_piece = linear_piece { begin, end };
}
template <typename time_, typename type_>
inline void spline<time_, type_>::set_bezier(
std::array<type_, 4> points) {
this->m_piece = bezier_piece { points };
}
template <typename time_, typename type_>
inline void spline<time_, type_>::set_hermite(
type_ begin, type_ end, std::array<type_, 2> tangents) {
this->m_piece = hermite_piece { begin, end, tangents };
}
template <typename time_, typename type_>
inline auto spline<time_, type_>::solve(time_ t) const
-> type_ {
return this->is_linear()
? linear(std::get<0>(this->m_piece).begin,
std::get<0>(this->m_piece).end, t)
:
this->is_bezier()
? bezier(std::get<1>(this->m_piece).points, t)
:
this->is_hermite()
? hermite(std::get<2>(this->m_piece).begin,
std::get<2>(this->m_piece).end,
std::get<2>(this->m_piece).tangents, t)
:
type_(0);
}
template <typename time_, typename type_>
inline auto spline<time_, type_>::get_begin() -> type_ {
return this->is_linear() ? std::get<0>(this->m_piece).begin :
this->is_bezier()
? std::get<1>(this->m_piece).points[0]
:
this->is_hermite() ? std::get<2>(this->m_piece).begin
:
type_(0);
}
template <typename time_, typename type_>
inline auto spline<time_, type_>::get_end() -> type_ {
return this->is_linear() ? std::get<0>(this->m_piece).end :
this->is_bezier()
? std::get<1>(this->m_piece).points[3]
:
this->is_hermite() ? std::get<2>(this->m_piece).end
:
type_(0);
}
template <typename time_, typename type_>
inline auto spline<time_, type_>::operator()(time_ t) const
-> type_ {
return this->solve(t);
}
template <typename time_, typename type_>
inline auto spline<time_, type_>::is_linear() const -> bool {
return this->m_piece.index() == 0;
}
template <typename time_, typename type_>
inline auto spline<time_, type_>::is_bezier() const -> bool {
return this->m_piece.index() == 1;
}
template <typename time_, typename type_>
inline auto spline<time_, type_>::is_hermite() const -> bool {
return this->m_piece.index() == 2;
}
template <typename time_, typename type_>
inline auto spline<time_, type_>::linear(type_ begin,
type_ end, time_ t)
-> type_ {
return lerp(begin, end, t);
}
template <typename time_, typename type_>
inline auto spline<time_, type_>::bezier(
std::array<type_, 4> points, time_ t) -> type_ {
auto t2 = t * t;
auto t3 = t2 * t;
auto to = 1. - t;
auto to2 = to * to;
auto to3 = to2 * to;
return type_(to3) * points[0] + type_(to2 * t) * points[1] +
type_(to * t2) * points[2] + type_(t3) * points[3];
}
template <typename time_, typename type_>
inline auto spline<time_, type_>::hermite(
type_ begin, type_ end, std::array<type_, 2> tangents,
time_ t) -> type_ {
auto t2 = t * t;
auto t3 = t2 * t;
auto a = (time_(2) * t3 - time_(3) * t2 + time_(1));
auto b = (t3 - time_(2) * t2 + t);
auto c = (time_(-2) * t3 + time_(3) * t2);
auto d = (t3 - t2);
return type_(a) * begin + type_(b) * tangents[0] +
type_(c * end) + type_(d) * tangents[1];
}
template <typename time_, typename type_>
inline auto spline<time_, type_>::flat()
-> const spline<time_, type_> & {
static spline<time_, type_> s;
return s;
}
}
#endif
|
193e83f913b98173cfef4a893f8920abdadd7566
|
46cce0f5350dd7bef7a22bb0a1246f003f40916c
|
/ui/widgets/satellitecoordinatespage.h
|
61ddac7c07ce1883439f1029c99c7523301071ff
|
[] |
no_license
|
veodev/av_training
|
6e65d43b279d029c85359027b5c68bd251ad24ff
|
ecb8c3cdc58679ada38c30df36a01751476f9015
|
refs/heads/master
| 2020-04-28T22:23:39.485893
| 2019-09-23T13:16:29
| 2019-09-23T13:16:29
| 175,615,879
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,146
|
h
|
satellitecoordinatespage.h
|
#ifndef SATELLITECOORDINATESPAGE_H
#define SATELLITECOORDINATESPAGE_H
#include <QWidget>
#include <QGeoPositionInfo>
#include <QGeoSatelliteInfo>
#include "geoposition.h"
namespace Ui
{
class SatelliteCoordinatesPage;
}
class SatelliteCoordinatesPage : public QWidget
{
Q_OBJECT
public:
explicit SatelliteCoordinatesPage(QWidget* parent = 0);
~SatelliteCoordinatesPage();
void setAntennaStatus(GeoPosition::AntennaStatus antennaStatus);
void setSatellitesInUse(int countSatellites);
void setGeoPositionInfo(const QGeoPositionInfo& info);
public slots:
void setVisible(bool visible);
signals:
void switchToVisibleSatellitesPage();
protected:
bool event(QEvent* e);
private slots:
void positionUpdated(const QGeoPositionInfo& info);
void satellitesInUseUpdated(const QList<QGeoSatelliteInfo>& satellites);
void antennaStatusChanged(GeoPosition::AntennaStatus antennaStatus);
void on_visibleSatellitesButton_released();
private:
Ui::SatelliteCoordinatesPage* ui;
GeoPosition* _geoPosition;
GeoPosition::AntennaStatus _antennaStatus;
};
#endif // SATELLITECOORDINATESPAGE_H
|
c540229fd8a4a3245fac7c8fdf31f54bb11ab953
|
a6289bf362cfcdd4454a92403dceb4232bb85183
|
/ScreenCapture/ScreenCapture/ScreenCapture.cpp
|
ea11bc37cabe55e8fe3d3415733752dbea79c615
|
[] |
no_license
|
y0n0622/vs2008Code
|
b696fc604bcbf4b019a701ebdbfa7d1838d41341
|
03835a584086168ce3c8a8798be290795521198a
|
refs/heads/master
| 2023-02-04T15:32:29.076525
| 2020-12-24T12:35:27
| 2020-12-24T12:35:27
| 149,395,659
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 8,792
|
cpp
|
ScreenCapture.cpp
|
// ScreenCapture.cpp : 定义应用程序的入口点。
//
#include "stdafx.h"
#include "ScreenCapture.h"
#include <Windows.h>
#define MAX_LOADSTRING 100
// 全局变量:
HINSTANCE hInst; // 当前实例
TCHAR szTitle[MAX_LOADSTRING]; // 标题栏文本
TCHAR szWindowClass[MAX_LOADSTRING]; // 主窗口类名
// 此代码模块中包含的函数的前向声明:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
HDC g_srcMemDc;
HDC g_grayMemDc;
int screenW;
int screenH;
RECT rect = {0}; //画图的矩形区域
bool isDrawing = false;
bool isSelect = false;
void GetScreenCapture();
void CovertToGrayBitmap(HBITMAP hSourceBmp,HDC sourceDc);
void WriteDatatoClipBoard();
int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPTSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: 在此放置代码。
MSG msg;
HACCEL hAccelTable;
// 初始化全局字符串
LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDC_SCREENCAPTURE, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// 执行应用程序初始化:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_SCREENCAPTURE));
// 主消息循环:
while (GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
//
// 函数: MyRegisterClass()
//
// 目的: 注册窗口类。
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_SCREENCAPTURE));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = 0;//MAKEINTRESOURCE(IDC_SCREENCAPTURE);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassEx(&wcex);
}
//
// 函数: InitInstance(HINSTANCE, int)
//
// 目的: 保存实例句柄并创建主窗口
//
// 注释:
//
// 在此函数中,我们在全局变量中保存实例句柄并
// 创建和显示主程序窗口。
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
hInst = hInstance; // 将实例句柄存储在全局变量中
hWnd = CreateWindow(szWindowClass, szTitle, WS_POPUP,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, SW_MAXIMIZE);
UpdateWindow(hWnd);
return TRUE;
}
//
// 函数: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// 目的: 处理主窗口的消息。
//
// WM_COMMAND - 处理应用程序菜单
// WM_PAINT - 绘制主窗口
// WM_DESTROY - 发送退出消息并返回
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
LOGBRUSH brush;
brush.lbStyle=BS_NULL;
HBRUSH hBrush=CreateBrushIndirect(&brush);
LOGPEN pen;
POINT penWidth;
penWidth.x=2;
penWidth.y=2;
pen.lopnColor=0x0000FFFF;
pen.lopnStyle=PS_SOLID;
pen.lopnWidth=penWidth;
HPEN hPen=CreatePenIndirect(&pen);
switch (message)
{
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// 分析菜单选择:
switch (wmId)
{
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
break;
case WM_CREATE:
GetScreenCapture();
break;
case WM_PAINT:
{
hdc = BeginPaint(hWnd, &ps);
HDC memDc = CreateCompatibleDC(hdc);
HBITMAP bmp = CreateCompatibleBitmap(hdc, screenW, screenH);
SelectObject(memDc, bmp);
BitBlt(memDc, 0, 0, screenW,screenH, g_grayMemDc, 0, 0, SRCCOPY);
SelectObject(memDc, hBrush);
SelectObject(memDc, hPen);
if (isDrawing || isSelect)
{
BitBlt(memDc, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, g_srcMemDc, rect.left, rect.top, SRCCOPY);
Rectangle(memDc, rect.left, rect.top, rect.right, rect.bottom);
}
BitBlt(hdc, 0, 0, screenW, screenH, memDc, 0, 0, SRCCOPY);
DeleteObject(bmp);
DeleteObject(memDc);
EndPaint(hWnd, &ps);
}
break;
case WM_LBUTTONDOWN:
{
if (!isSelect)
{
POINT pt;
GetCursorPos(&pt);
rect.left = pt.x;
rect.top = pt.y;
rect.right = pt.x;
rect.bottom = pt.y;
isDrawing = true;
InvalidateRgn(hWnd, 0, false);
}
}
break;
case WM_LBUTTONUP:
{
if (isDrawing && !isSelect)
{
isDrawing = false;
POINT pt;
GetCursorPos(&pt);
rect.right = pt.x;
rect.bottom = pt.y;
isSelect = true;
InvalidateRgn(hWnd, 0, false);
}
}
break;
case WM_MOUSEMOVE:
{
if (isDrawing&& !isSelect)
{
POINT pt;
GetCursorPos(&pt);
rect.right = pt.x;
rect.bottom = pt.y;
InvalidateRgn(hWnd, 0, false);
}
}
break;
case WM_LBUTTONDBLCLK:
{
if (isSelect)
{
WriteDatatoClipBoard();
InvalidateRgn(hWnd, 0, false);
ShowWindow(hWnd, SW_MINIMIZE);
}
isSelect = false;
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// “关于”框的消息处理程序。
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
void GetScreenCapture()
{
HDC disDc = ::CreateDC(L"DISPLAY", 0, 0, 0); //创建屏幕相关的DC
screenW = GetDeviceCaps(disDc, HORZRES);//水平分辨率
screenH = GetDeviceCaps(disDc, VERTRES);//垂直分辨率
g_srcMemDc = CreateCompatibleDC(disDc); //创建于屏幕兼容的DC(内存DC)
HBITMAP hbMap = CreateCompatibleBitmap(disDc, screenW, screenH); //模拟一张画布,其中是没有数据的
SelectObject(g_srcMemDc, hbMap); //将画图选入内存DC,其中还是没有数据的
BitBlt(g_srcMemDc, 0, 0, screenW, screenH, disDc, 0, 0, SRCCOPY); //将屏幕的dc中的画图,拷贝至内存DC中
//获取屏幕的灰度图片
g_grayMemDc = CreateCompatibleDC(disDc);
HBITMAP grayMap = CreateCompatibleBitmap(disDc, screenW, screenH); //模拟一张画布,其中是没有数据的
SelectObject(g_grayMemDc, grayMap); //将画图选入内存DC,其中还是没有数据的
BitBlt(g_grayMemDc, 0, 0, screenW, screenH, disDc, 0, 0, SRCCOPY); //将屏幕的dc中的画图,拷贝至内存DC中
CovertToGrayBitmap(grayMap, g_grayMemDc); //将彩色图片转换灰度图片
DeleteObject(hbMap);
DeleteObject(grayMap);
DeleteObject(disDc);
}
void CovertToGrayBitmap(HBITMAP hSourceBmp,HDC sourceDc)
{
HBITMAP retBmp=hSourceBmp;
BITMAPINFO bmpInfo;
ZeroMemory(&bmpInfo,sizeof(BITMAPINFO));
bmpInfo.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
GetDIBits(sourceDc,retBmp,0,0,NULL,&bmpInfo,DIB_RGB_COLORS);
BYTE* bits=new BYTE[bmpInfo.bmiHeader.biSizeImage];
GetBitmapBits(retBmp,bmpInfo.bmiHeader.biSizeImage,bits);
int bytePerPixel=4;//默认32位
if(bmpInfo.bmiHeader.biBitCount==24)
{
bytePerPixel=3;
}
for(DWORD i=0;i<bmpInfo.bmiHeader.biSizeImage;i+=bytePerPixel)
{
BYTE r=*(bits+i);
BYTE g=*(bits+i+1);
BYTE b=*(bits+i+2);
*(bits+i)=*(bits+i+1)=*(bits+i+2)=(r+b+g)/3;
}
SetBitmapBits(hSourceBmp,bmpInfo.bmiHeader.biSizeImage,bits);
delete[] bits;
}
void WriteDatatoClipBoard()
{
HDC hMemDc,hScrDc;
HBITMAP hBmp,hOldBmp;
int width,height;
width=rect.right-rect.left;
height=rect.bottom-rect.top;
hScrDc=CreateDC(L"DISPLAY",NULL,NULL,NULL);
hMemDc=CreateCompatibleDC(hScrDc);
hBmp=CreateCompatibleBitmap(hScrDc,width,height);
hOldBmp=(HBITMAP)SelectObject(hMemDc,hBmp);
BitBlt(hMemDc,0,0,width,height,g_srcMemDc,rect.left,rect.top,SRCCOPY);
hBmp=(HBITMAP)SelectObject(hMemDc,hOldBmp);
DeleteDC(hMemDc);
DeleteDC(hScrDc);
//复制到剪贴板
if(OpenClipboard(0))
{
EmptyClipboard();
SetClipboardData(CF_BITMAP,hBmp);
CloseClipboard();
}
DeleteObject(hBmp);
DeleteObject(hMemDc);
DeleteObject(hScrDc);
}
|
007e9bbb9253c62a1a29116d55edeedd08ca259e
|
bb5258ea8c1f8cbcc247b92971cd926264479002
|
/ds4/code/4_client_desktop/delegate/client/client_delegate.cpp
|
a6b4371a1e34d910408be6adab22f0f05a50ad35
|
[
"MIT"
] |
permissive
|
demonsaw/Code
|
16fa41f07600e83f16713a657ac8fffa0b6b7f9b
|
b036d455e9e034d7fd178e63d5e992242d62989a
|
refs/heads/master
| 2021-11-07T21:37:03.738542
| 2021-10-26T03:47:14
| 2021-10-26T03:47:14
| 98,356,418
| 134
| 19
|
MIT
| 2019-01-06T03:20:12
| 2017-07-25T22:50:36
|
C++
|
UTF-8
|
C++
| false
| false
| 7,180
|
cpp
|
client_delegate.cpp
|
//
// The MIT License(MIT)
//
// Copyright(c) 2014 Demonsaw LLC
//
// 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 <QPainter>
#include "component/chat_component.h"
#include "component/room_component.h"
#include "component/client/client_component.h"
#include "delegate/client/client_delegate.h"
#include "entity/entity.h"
#include "font/font_awesome.h"
#include "resource/resource.h"
#include "system/type.h"
#include "utility/value.h"
#include "window/main_window.h"
Q_DECLARE_METATYPE(eja::entity::ptr);
namespace eja
{
// Constructor
client_delegate::client_delegate(QObject* parent /*= nullptr*/) : QStyledItemDelegate(parent)
{
m_circle_font = QFont(software::font_awesome);
m_circle_font.setPixelSize(resource::get_circle_size());
m_icon_font = QFont(software::font_awesome);
m_icon_font.setPixelSize(resource::get_icon_size());
}
// Utility
void client_delegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
if (option.state & QStyle::State_Enabled)
{
// Entity
const auto variant = index.data(Qt::DisplayRole);
const auto entity = variant.value<entity::ptr>();
if (!entity)
return;
painter->save();
painter->setRenderHint(QPainter::Antialiasing, true);
const auto icon_size = resource::get_icon_size() + (resource::get_icon_padding() * 2);
// Name
if (entity->has<client_component>())
{
// HACK: Remove tree offset
const_cast<QStyleOptionViewItem&>(option).rect.setLeft(option.rect.left() - resource::get_tree_view_indent());
const_cast<QStyleOptionViewItem&>(option).rect.setRight(option.rect.right() + resource::get_tree_view_indent());
QStyledItemDelegate::paint(painter, option, index);
const auto client = entity->get<client_component>();
QString name = QString::fromStdString(client->get_name());
if (!entity->has_owner())
{
if (client->is_troll())
name += suffix::troll;
}
QRect rect(option.rect.left() + resource::get_row_height(), option.rect.top(), option.rect.width() - resource::get_row_height(), option.rect.height());
painter->drawText(rect, Qt::TextSingleLine | Qt::AlignVCenter, name);
// Size
if (entity->has_owner() && entity->has<chat_list_component>())
{
const auto chat_list = entity->get<chat_list_component>();
if (chat_list->has_rows())
{
// Text
const auto number = QString::number(chat_list->get_rows());
const auto width = option.rect.width() - resource::get_tree_view_indent() - resource::get_icon_size() - (resource::get_icon_padding() * 2);
rect = QRect(option.rect.left(), option.rect.top(), width, option.rect.height());
painter->drawText(rect, Qt::TextSingleLine | Qt::AlignVCenter | Qt::AlignRight, number);
// Alpha
int fa;
if (chat_list->is_notify())
{
fa = fa::envelope;
const auto& app = main_window::get_app();
if (app.is_user_colors())
painter->setPen(QColor(client->get_color()));
else
painter->setPen(option.palette.color(QPalette::WindowText));
}
else
{
fa = fa::envelope_o;
auto color = option.palette.color(QPalette::WindowText);
color.setAlpha(32);
painter->setPen(color);
}
// Icon
painter->setFont(m_icon_font);
const auto left = option.rect.right() - resource::get_tree_view_indent() - icon_size;
rect = QRect(left, option.rect.top(), option.rect.right() - left - resource::get_tree_view_indent(), option.rect.height());
painter->drawText(rect, Qt::TextSingleLine | Qt::AlignCenter, QString(fa));
painter->setPen(option.palette.color(QPalette::WindowText));
}
}
// Icon
auto fa = fa::circle;
if (client->is_mute())
fa = fa::ban;
else if (client->is_verified())
fa = fa::check_circle;
else if (client->is_troll())
fa = fa::question_circle;
painter->setFont(m_circle_font);
const auto& app = main_window::get_app();
if (app.is_user_colors())
painter->setPen(QColor(client->get_color()));
rect = QRect(option.rect.left(), option.rect.top(), resource::get_row_height(), resource::get_row_height());
painter->drawText(rect, Qt::TextSingleLine | Qt::AlignCenter, QString(fa));
}
else
{
QStyledItemDelegate::paint(painter, option, index);
// Name
const auto room = entity->get<room_component>();
QRect rect(option.rect.left() + icon_size, option.rect.top(), option.rect.width() - icon_size, option.rect.height());
painter->drawText(rect, Qt::TextSingleLine | Qt::AlignVCenter, QString::fromStdString(room->get_name()));
// Text
const auto number = QString::number(room->get_size());
rect = QRect(option.rect.left(), option.rect.top(), option.rect.width() - icon_size, option.rect.height());
painter->drawText(rect, Qt::TextSingleLine | Qt::AlignVCenter | Qt::AlignRight, number);
// Alpha
auto color = option.palette.color(QPalette::WindowText);
color.setAlpha(32);
painter->setPen(color);
// Icon
painter->setFont(m_icon_font);
const auto left = option.rect.right() - icon_size;
rect = QRect(left, option.rect.top(), option.rect.right() - left, option.rect.height());
painter->drawText(rect, Qt::TextSingleLine | Qt::AlignCenter, QString(fa::user_o));
painter->setPen(option.palette.color(QPalette::WindowText));
// Icon
painter->setFont(m_icon_font);
if (room->has_color())
{
const auto& app = main_window::get_app();
if (app.is_user_colors())
painter->setPen(QColor(room->get_color()));
}
rect = QRect(option.rect.left() + resource::get_icon_padding(), option.rect.top() + (resource::get_row_height() / 2) - (resource::get_icon_size() / 2), resource::get_icon_size(), resource::get_icon_size());
painter->drawText(rect, Qt::TextSingleLine | Qt::AlignCenter, QString(fa::hash_tag));
}
painter->restore();
}
}
QSize client_delegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const
{
return QSize(option.rect.width(), resource::get_row_height());
}
}
|
4315ffa2395fea5f9db47b737b2d24c2baec0010
|
2af943fbfff74744b29e4a899a6e62e19dc63256
|
/RefactoringITKStatisticsClasses/src/itkJointDomainImageToListAdaptor.h
|
fe3a3203bd9981469f36e697df5e44788cd0da82
|
[] |
no_license
|
lheckemann/namic-sandbox
|
c308ec3ebb80021020f98cf06ee4c3e62f125ad9
|
0c7307061f58c9d915ae678b7a453876466d8bf8
|
refs/heads/master
| 2021-08-24T12:40:01.331229
| 2014-02-07T21:59:29
| 2014-02-07T21:59:29
| 113,701,721
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,742
|
h
|
itkJointDomainImageToListAdaptor.h
|
/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: $RCSfile: itkJointDomainImageToListAdaptor.h,v $
Language: C++
Date: $Date: 2003/12/15 01:00:46 $
Version: $Revision: 1.11 $
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#ifndef __itkJointDomainImageToListAdaptor_h
#define __itkJointDomainImageToListAdaptor_h
#include "itkMacro.h"
#include "itkFixedArray.h"
#include "itkPoint.h"
#include "itkPixelTraits.h"
#include "itkImageToListAdaptor.h"
#include "itkImageRegionConstIteratorWithIndex.h"
#include "itkEuclideanDistance.h"
#include "itkListSample.h"
namespace itk{
namespace Statistics{
/** \class ImageJointDomainTraits
* \brief This class provides the type defintion for the measurement
* vector in the joint domain (range domain -- pixel values + spatial
* domain -- pixel's physical coordinates).
*
* \sa JointDomainImageToListAdaptor
*/
template< class TImage >
struct ImageJointDomainTraits
{
typedef ImageJointDomainTraits Self ;
typedef PixelTraits< typename TImage::PixelType > PixelTraitsType ;
typedef typename PixelTraitsType::ValueType RangeDomainMeasurementType ;
typedef typename TImage::IndexType::IndexValueType IndexValueType ;
itkStaticConstMacro(ImageDimension, unsigned int, TImage::ImageDimension) ;
itkStaticConstMacro(Dimension,
unsigned int,
TImage::ImageDimension +
PixelTraitsType::Dimension ) ;
typedef float CoordinateRepType ;
typedef Point< CoordinateRepType, itkGetStaticConstMacro(ImageDimension) > PointType ;
typedef JoinTraits< RangeDomainMeasurementType, CoordinateRepType >
JoinTraitsType ;
typedef typename JoinTraitsType::ValueType MeasurementType ;
typedef FixedArray< MeasurementType, itkGetStaticConstMacro(Dimension) >
MeasurementVectorType ;
} ; // end of ImageJointDomainTraits
/** \class JointDomainImageToListAdaptor
* \brief This adaptor returns measurement vectors composed of an
* image pixel's range domain value (pixel value) and spatial domain
* value (pixel's physical coordiantes).
*
* This class is a derived class of the ImageToListAdaptor. This class
* overrides the GetMeasurementVector method. The GetMeasurementVector
* returns a measurement vector that consist of a pixel's physical
* coordinates and intensity value. For example, if the image
* dimension is 3, and the pixel value is two component vector, the
* measurement vector is a 5 component vector. The first three
* component will be x, y, z physical coordinates (not index) and the
* rest two component is the pixel values. The type of component is
* float or which is determined by the ImageJointDomainTraits
* class. When the pixel value type is double, the component value
* type of a measurement vector is double. In other case, the
* component value type is float becase the physical coordinate value
* type is float. Since the measurment vector is a composition of
* spatial domain and range domain, for many statistical analysis, we
* want to normalize the values from both domains. For this purpose,
* there is the SetNormalizationFactors method. With the above example
* (5 component measurement vector), you can specify a 5 component
* normalization factor array. With such factors, the
* GetMeasurementVector method returns a measurement vector whose each
* component is divided by the corresponding component of the factor array.
*
* \sa Sample, ListSampleBase, ImageToListAdaptor
*/
template < class TImage >
class ITK_EXPORT JointDomainImageToListAdaptor
: public ImageToListAdaptor<
TImage,
typename ImageJointDomainTraits< TImage >::MeasurementVectorType >
{
public:
typedef ImageJointDomainTraits< TImage > ImageJointDomainTraitsType ;
typedef typename ImageJointDomainTraitsType::MeasurementVectorType
MeasurementVectorType ;
typedef typename ImageJointDomainTraitsType::MeasurementType
MeasurementType ;
typedef typename ImageJointDomainTraitsType::RangeDomainMeasurementType
RangeDomainMeasurementType ;
typedef typename ImageJointDomainTraitsType::PointType PointType ;
typedef typename ImageJointDomainTraitsType::CoordinateRepType
CoordinateRepType ;
/** Standard class typedefs */
typedef JointDomainImageToListAdaptor Self;
typedef ImageToListAdaptor< TImage, MeasurementVectorType >
Superclass;
typedef SmartPointer< Self > Pointer;
typedef SmartPointer<const Self> ConstPointer;
/** Run-time type information (and related methods). */
itkTypeMacro(JointDomainImageToListAdaptor, ImageToListAdaptor) ;
/** Method for creation through the object factory. */
itkNewMacro(Self) ;
/** the number of components in a measurement vector */
itkStaticConstMacro(MeasurementVectorSize,
unsigned int,
ImageJointDomainTraitsType::Dimension) ;
typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType;
virtual void SetMeasurementVectorSize( unsigned int s )
{
// Measurement vector size for this class is fixed as the pixel's
// dimension. This method should have no effect
if( s != MeasurementVectorSize )
{
itkExceptionMacro( << "Cannot set measurement vector size of "
<< " JointDomainImageToListAdaptor to " << s );
}
}
MeasurementVectorSizeType GetMeasurementVectorSize() const
{
return MeasurementVectorSize;
}
/** typedefs for Measurement vector, measurement,
* Instance Identifier, frequency, size, size element value */
typedef typename Superclass::FrequencyType FrequencyType ;
typedef typename Superclass::InstanceIdentifier InstanceIdentifier ;
typedef typename TImage::IndexType ImageIndexType ;
typedef typename TImage::IndexType::IndexValueType ImageIndexValueType ;
typedef typename TImage::SizeType ImageSizeType ;
typedef typename TImage::RegionType ImageRegionType ;
typedef ImageRegionConstIteratorWithIndex< TImage > ImageIteratorType ;
typedef MeasurementVectorType ValueType ;
itkStaticConstMacro(RangeDomainDimension,
unsigned int,
itk::PixelTraits<
typename TImage::PixelType >::Dimension) ;
typedef FixedArray< RangeDomainMeasurementType,
itkGetStaticConstMacro( RangeDomainDimension ) >
RangeDomainMeasurementVectorType ;
typedef std::vector< InstanceIdentifier > InstanceIdentifierVectorType ;
typedef FixedArray< float, itkGetStaticConstMacro(MeasurementVectorSize) >
NormalizationFactorsType ;
/** Sets the normalization factors */
void SetNormalizationFactors(NormalizationFactorsType& factors) ;
/** Gets the measurement vector specified by the instance
* identifier. This method overrides superclass method. */
inline const MeasurementVectorType & GetMeasurementVector(const InstanceIdentifier &id) const;
/** Computes the image region (rectangular) that enclose the ball
* defined by the mv (center) and the radius. */
inline void ComputeRegion(const MeasurementVectorType& mv,
const double radius,
ImageRegionType& region) const;
/** Fills he result id vectors with instances that fall within a
* ball specified by the mv (center) and radius. This method utilizes
* the ComputRegion */
inline void Search(const MeasurementVectorType& mv,
const double radius,
InstanceIdentifierVectorType& result) const;
protected:
JointDomainImageToListAdaptor() ;
virtual ~JointDomainImageToListAdaptor() {}
void PrintSelf(std::ostream& os, Indent indent) const;
private:
JointDomainImageToListAdaptor(const Self&) ; //purposely not implemented
void operator=(const Self&) ; //purposely not implemented
NormalizationFactorsType m_NormalizationFactors ;
mutable MeasurementVectorType m_TempVector ;
mutable PointType m_TempPoint ;
mutable ImageIndexType m_TempIndex ;
mutable RangeDomainMeasurementVectorType m_TempRangeVector ;
} ; // end of class JointDomainImageToListAdaptor
} // end of namespace Statistics
} // end of namespace itk
#ifndef ITK_MANUAL_INSTANTIATION
#include "itkJointDomainImageToListAdaptor.txx"
#endif
#endif
|
73d2e60abaefac6666c830c06d4747b4e7c3ae1b
|
707d3744bc9d639b9264bb1487c9124af399f544
|
/Classes/GameBoard.cpp
|
9938fb3a72dc0af56e43a9c3db5a750ed21b7665
|
[
"Apache-2.0"
] |
permissive
|
dongshunyao/IconBattle
|
4178137e2ae10bb1fbda34c7cbe47ac1825db940
|
ae3dcd8a2256f31a59c1488d1254f9bc3fd72d54
|
refs/heads/master
| 2023-07-24T20:50:21.557976
| 2023-07-14T15:54:47
| 2023-07-14T15:54:47
| 256,798,123
| 2
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 24,973
|
cpp
|
GameBoard.cpp
|
#include "GameScene.h"
void GameScene::initGameBoard()
{
moveHighLight = ImageView::create(theme->gameSceneMouseMoveOn);
moveHighLight->setPosition(invisiblePosition);
addChild(moveHighLight, 3);
selectedHighLight = ImageView::create(theme->gameSceneMouseSelected);
selectedHighLight->setPosition(invisiblePosition);
addChild(selectedHighLight, 5);
// 鼠标监听
auto mouseListener = EventListenerMouse::create();
// 鼠标按下
mouseListener->onMouseDown = [&](Event* event)
{
if (boardLock) return;
const auto e = dynamic_cast<EventMouse*>(event);
// 只按下左键为有效操作
if (e->getMouseButton() == EventMouse::MouseButton::BUTTON_LEFT)
{
Sound::getInstance()->play(Sound::getInstance()->click);
auto cursorX = e->getCursorX();
auto cursorY = e->getCursorY();
log("Click: Position %f, %f; Index %d, %d;", cursorX, cursorY, getIndexByPosition(Pair(cursorX, cursorY)));
// 还未选中过方块
if (firstSelectedBlockIndex == Pair(-1, -1))
{
firstSelectedBlockIndex = getIndexByPosition(Pair(cursorX, cursorY));
selectedHighLight->setPosition(Vec2(getPositionByIndex(firstSelectedBlockIndex).first,
getPositionByIndex(firstSelectedBlockIndex).second));
}
else if (firstSelectedBlockIndex.first != -1 && secondSelectedBlockIndex.first == -1)
{
//已经选中一个方块
secondSelectedBlockIndex = getIndexByPosition(Pair(cursorX, cursorY));
// 判断第二方块是否相邻
switch (secondSelectedBlockIndex.first - firstSelectedBlockIndex.first)
{
case 1:
case -1:
{
// 不相邻,现选择的方块变为第一块
if (firstSelectedBlockIndex.second != secondSelectedBlockIndex.second)
{
firstSelectedBlockIndex = getIndexByPosition(Pair(cursorX, cursorY));
selectedHighLight->setPosition(Vec2(getPositionByIndex(firstSelectedBlockIndex).first,
getPositionByIndex(firstSelectedBlockIndex).second));
secondSelectedBlockIndex = {-1, -1};
}
break;
}
case 0:
{
// 不相邻,现选择的方块变为第一块
if (firstSelectedBlockIndex.second - secondSelectedBlockIndex.second != -1
&& firstSelectedBlockIndex.second - secondSelectedBlockIndex.second != 1)
{
firstSelectedBlockIndex = getIndexByPosition(Pair(cursorX, cursorY));
selectedHighLight->setPosition(Vec2(getPositionByIndex(firstSelectedBlockIndex).first,
getPositionByIndex(firstSelectedBlockIndex).second));
secondSelectedBlockIndex = {-1, -1};
}
break;
}
// 不相邻,现选择的方块变为第一块
default:
{
firstSelectedBlockIndex = getIndexByPosition(Pair(cursorX, cursorY));
selectedHighLight->setPosition(Vec2(getPositionByIndex(firstSelectedBlockIndex).first,
getPositionByIndex(firstSelectedBlockIndex).second));
secondSelectedBlockIndex = {-1, -1};
break;
}
}
}
if (selectedHighLight->getPosition() == Vec2(409, 34)) selectedHighLight->setPosition(invisiblePosition);
}
};
// 鼠标弹起
mouseListener->onMouseUp = [&](Event* event)
{
const auto e = dynamic_cast<EventMouse*>(event);
// 只弹起左键为有效操作
if (e->getMouseButton() == EventMouse::MouseButton::BUTTON_LEFT)
{
// 已经选中两块则尝试交换,否则不进行操作
if (firstSelectedBlockIndex != Pair(-1, -1) && secondSelectedBlockIndex != Pair(-1, -1))
trySwapBlock(firstSelectedBlockIndex, secondSelectedBlockIndex);
}
};
// 鼠标移动
mouseListener->onMouseMove = [&](Event* event)
{
const auto e = dynamic_cast<EventMouse*>(event);
auto cursorX = e->getCursorX();
auto cursorY = e->getCursorY();
if (e->getMouseButton() == EventMouse::MouseButton::BUTTON_UNSET)
{
if (boardLock)
{
moveHighLight->setPosition(invisiblePosition);
return;
}
const auto block = getIndexByPosition(Pair(cursorX, cursorY));
if (block != Pair(-1, -1))
{
const auto position = getPositionByIndex(block);
moveHighLight->setPosition(Vec2(position.first, position.second));
}
else moveHighLight->setPosition(invisiblePosition);
}
};
// 添加监听器
getEventDispatcher()->addEventListenerWithSceneGraphPriority(mouseListener, this);
// 刷新棋盘并下落开始
refreshBoard();
runAction(Sequence::createWithTwoActions(DelayTime::create(1.1f), CallFunc::create([&]() { dropBlock(); })));
}
Actor* GameScene::addActor(const int type, const Pair position)
{
const auto actor = Actor::create(type, position);
addChild(actor, 1);
return actor;
}
Pair GameScene::getPositionByIndex(const Pair index)
{
// (495,120)为左下角第一个宝石的中心坐标
return {495 + 86 * index.second, 120 + 86 * index.first};
}
Pair GameScene::getIndexByPosition(const Pair position)
{
// 棋盘可点击范围在452~1140(width),77~765(height),棋盘中心点为(796,421)
if (position.first <= 452 || position.first >= 452 + 688) return {-1, -1};
if (position.second <= 77 || position.second >= 77 + 688) return {-1, -1};
// 宝石大小为64,与缝隙总长86
auto xIndex = (position.second - 77) / 86, yIndex = (position.first - 452) / 86;
assert(xIndex >= 0 && xIndex <= 7);
assert(yIndex >= 0 && yIndex <= 7);
return {xIndex, yIndex};
}
void GameScene::refreshBoard()
{
// 下半部置空
for (auto i = 0; i < 2 * BOARD_SIZE; i++)
for (auto j = 0; j < BOARD_SIZE; j++)
{
if (board[i][j].type != -1)
{
removeChild(board[i][j].actor);
// 强制回收
// board[i][j].actor->release();
}
board[i][j] = Block();
}
// 上半部生成
for (auto i = BOARD_SIZE; i < 2 * BOARD_SIZE; i++)
for (auto j = 0; j < BOARD_SIZE; j++)
{
// 禁止块
const auto banX = i >= BOARD_SIZE + 2 && board[i - 1][j].type == board[i - 2][j].type
? board[i - 2][j].type
: -1;
const auto banY = j >= 2 && board[i][j - 1].type == board[i][j - 2].type
? board[i][j - 2].type
: -1;
auto type = getRandomNumber(TYPE_NUMBER);
while (type == banX || type == banY) type = getRandomNumber(TYPE_NUMBER);
board[i][j] = Block(type, addActor(type, getPositionByIndex({i, j})));
}
}
void GameScene::dropBlock()
{
for (auto i = 0; i < BOARD_SIZE; i++)
for (auto j = 0; j < BOARD_SIZE; j++)
{
if (board[i][j].type == -1)
{
auto upperI = i;
while (board[upperI][j].type == -1)
{
upperI++;
assert(upperI < 2 * BOARD_SIZE);
}
const auto nowBlock = getPositionByIndex({i, j});
board[upperI][j].actor->dropTo(nowBlock);
swap(board[i][j], board[upperI][j]);
}
}
runAction(Sequence::createWithTwoActions(DelayTime::create(0.5),
CallFunc::create([&]() { mainCallback(); })));
}
bool GameScene::canKill() const
{
for (auto i = 0; i < BOARD_SIZE; i++)
for (auto j = 0; j < BOARD_SIZE; j++)
{
if (i > 0 && i < BOARD_SIZE - 1 &&
(board[i - 1][j].type == board[i][j].type && board[i][j].type == board[i + 1][j].type))
return true;
if (j > 0 && j < BOARD_SIZE - 1 &&
(board[i][j - 1].type == board[i][j].type && board[i][j].type == board[i][j + 1].type))
return true;
}
return false;
}
bool GameScene::canKill(const Pair blockAIndex, const Pair blockBIndex)
{
swap(board[blockAIndex.first][blockAIndex.second], board[blockBIndex.first][blockBIndex.second]);
const auto flag = canKill();
swap(board[blockAIndex.first][blockAIndex.second], board[blockBIndex.first][blockBIndex.second]);
return flag;
}
void GameScene::trySwapBlock(const Pair blockAIndex, const Pair blockBIndex)
{
selectedHighLight->setPosition(invisiblePosition);
firstSelectedBlockIndex = {-1, -1};
secondSelectedBlockIndex = {-1, -1};
minusStepNumber();
boardLock = true;
log("[LOCK] Try Swap: 1st (%d,%d), 2ed (%d,%d)", blockAIndex.first, blockAIndex.second, blockBIndex.first,
blockBIndex.second);
ActorInformationList actorList;
// 均为Super块
if (board[blockAIndex.first][blockAIndex.second].type == SUPER_TYPE && board[blockBIndex.first][blockBIndex.second].
type == SUPER_TYPE)
{
for (auto i = 0; i < BOARD_SIZE; i++)
for (auto j = 0; j < BOARD_SIZE; j++) actorList.push_back(ActorInformation(i, j));
killBlock({KillInformation(DOUBLE_SUPER_KILL, DOUBLE_SUPER_KILL_SCORE, actorList)}, isClassical);
return;
}
// 有一个Super块
if (board[blockAIndex.first][blockAIndex.second].type == SUPER_TYPE)
{
for (auto i = 0; i < BOARD_SIZE; i++)
for (auto j = 0; j < BOARD_SIZE; j++)
{
if (board[i][j].type == board[blockBIndex.first][blockBIndex.second].type)
actorList.push_back(ActorInformation(i, j));
}
actorList.push_back(ActorInformation(blockAIndex));
killBlock({KillInformation(SUPER_KILL, SUPER_KILL_SCORE, actorList)}, isClassical);
return;
}
if (board[blockBIndex.first][blockBIndex.second].type == SUPER_TYPE)
{
for (auto i = 0; i < BOARD_SIZE; i++)
for (auto j = 0; j < BOARD_SIZE; j++)
{
if (board[i][j].type == board[blockAIndex.first][blockAIndex.second].type)
actorList.push_back(ActorInformation(i, j));
}
actorList.push_back(ActorInformation(blockBIndex));
killBlock({KillInformation(SUPER_KILL, SUPER_KILL_SCORE, actorList)}, isClassical);
return;
}
if (canKill(blockAIndex, blockBIndex)) swapSuccess(blockAIndex, blockBIndex);
else swapFail(blockAIndex, blockBIndex);
}
HintOperation GameScene::isImpasse()
{
const auto beginTime = clock();
for (auto i = 0; i < BOARD_SIZE; i++)
for (auto j = 0; j < BOARD_SIZE; j++)
if (board[i][j].type == SUPER_TYPE)
{
log("Hit: Use %d ms; Super (%d, %d);", clock() - beginTime, i, j);
return {{i, j}, {-1, -1}};
}
for (auto i = 1; i < BOARD_SIZE; i++)
for (auto j = 0; j < BOARD_SIZE; j++)
if (canKill({i, j}, {i - 1, j}))
{
log("Hit: Use %d ms; Normal (%d, %d), (%d, %d);", clock() - beginTime, i, j, i - 1, j);
return {{i, j}, {i - 1, j}};
}
for (auto i = 0; i < BOARD_SIZE; i++)
for (auto j = 1; j < BOARD_SIZE; j++)
if (canKill({i, j}, {i, j - 1}))
{
log("Hit: Use %d ms; Normal (%d, %d), (%d, %d);", clock() - beginTime, i, j, i, j - 1);
return {{i, j}, {i, j - 1}};
}
log("Impasse: Use %d ms;", clock() - beginTime);
return {{-1, -1}, {-1, -1}};
}
bool GameScene::showHint()
{
if (boardLock) return false;
boardLock = true;
const auto hint = isImpasse();
log("[LOCK] Hint: (%d, %d); (%d, %d);", hint.first.first, hint.first.second, hint.second.first, hint.second.second);
assert(hint != HintOperation({-1, -1},{-1,-1}));
showSingleParticle(hint.first, 1);
if (hint.second != Pair(-1, -1)) showSingleParticle(hint.second, 1);
boardLock = false;
log("[UNLOCK] Hint");
return true;
}
void GameScene::swapSuccess(const Pair blockAIndex, const Pair blockBIndex)
{
board[blockAIndex.first][blockAIndex.second].actor->moveTo(getPositionByIndex(blockBIndex));
board[blockBIndex.first][blockBIndex.second].actor->moveTo(getPositionByIndex(blockAIndex));
swap(board[blockAIndex.first][blockAIndex.second], board[blockBIndex.first][blockBIndex.second]);
runAction(Sequence::createWithTwoActions(DelayTime::create(0.4f),
CallFunc::create([&]() { mainCallback(); })));
}
void GameScene::swapFail(const Pair blockAIndex, const Pair blockBIndex)
{
board[blockAIndex.first][blockAIndex.second].actor->moveToAndBack(getPositionByIndex(blockBIndex));
board[blockBIndex.first][blockBIndex.second].actor->moveToAndBack(getPositionByIndex(blockAIndex));
runAction(Sequence::createWithTwoActions(DelayTime::create(0.65f),
CallFunc::create([&]() { mainCallback(); })));
}
void GameScene::mainCallback()
{
if (canKill())
{
log("[CAN_KILL]");
killBlock(getKillList(isClassical), isClassical);
}
else
{
if (stepNumber == 0 || currentScore >= totalScore)
{
log("[END]");
endGame();
return;
}
if (isImpasse() == HintOperation({-1, -1}, {-1, -1}))
{
log("[IMPASSE]");
refreshBoard();
dropBlock();
return;
}
log("[UNLOCK]");
boardLock = false;
}
}
KillInformationList GameScene::getKillList(const bool isClassical) const
{
KillInformationList killList;
set<Pair> visit;
// 检查十字消
if (!isClassical)
for (auto i = 0; i < BOARD_SIZE; i++)
for (auto j = 0; j < BOARD_SIZE; j++)
{
if (board[i][j].type == SUPER_TYPE || visit.count({i, j})) continue;
auto iLength = 1, jLength = 1;
ActorInformationList actorList;
actorList.push_back(ActorInformation(i, j));
for (auto iIndex = i + 1;
iIndex < BOARD_SIZE && board[iIndex][j].type == board[i][j].type && !visit.count({iIndex, j});
iIndex++)
{
iLength++;
actorList.push_back(ActorInformation(iIndex, j));
}
for (auto iIndex = i - 1;
iIndex >= 0 && board[iIndex][j].type == board[i][j].type && !visit.count({iIndex, j});
iIndex--)
{
iLength++;
actorList.push_back(ActorInformation(iIndex, j));
}
for (auto jIndex = j + 1;
jIndex < BOARD_SIZE && board[i][jIndex].type == board[i][j].type && !visit.count({i, jIndex});
jIndex++)
{
jLength++;
actorList.push_back(ActorInformation(i, jIndex));
}
for (auto jIndex = j - 1;
jIndex >= 0 && board[i][jIndex].type == board[i][j].type && !visit.count({i, jIndex});
jIndex--)
{
jLength++;
actorList.push_back(ActorInformation(i, jIndex));
}
// 双三
if (iLength == 3 && jLength == 3)
{
// 找最小点,添加3*3
ActorInformationList tempList;
auto iIndex = 3 * BOARD_SIZE, jIndex = 3 * BOARD_SIZE;
for (const auto& it : actorList)
{
if (it.blockIndex.first < iIndex) iIndex = it.blockIndex.first;
if (it.blockIndex.second < jIndex) jIndex = it.blockIndex.second;
}
for (auto iDelta = 0; iDelta < 3; iDelta++)
for (auto jDelta = 0; jDelta < 3; jDelta++)
tempList.push_back({
iIndex + iDelta, jIndex + jDelta
});
killList.push_back({DOUBLE_BASE_KILL, DOUBLE_BASE_KILL_SCORE, tempList});
}
else if (iLength >= 3 && jLength >= 3) // 双四
killList.push_back({DOUBLE_FOUR_KILL, DOUBLE_FOUR_KILL_SCORE, actorList, {i, j}});
if (iLength >= 3 && jLength >= 3)
for (const auto& it : actorList) visit.insert(it.blockIndex);
}
// 检查五消
for (auto i = 0; i < BOARD_SIZE; i++)
for (auto j = 0; j < BOARD_SIZE; j++)
{
if (board[i][j].type == SUPER_TYPE || visit.count({i, j})) continue;
// 竖直
if (i > 1 && i < BOARD_SIZE - 2
&& (board[i][j].type == board[i + 1][j].type &&
board[i][j].type == board[i + 2][j].type &&
board[i][j].type == board[i - 1][j].type &&
board[i][j].type == board[i - 2][j].type)
&& (!visit.count({i, j}) &&
!visit.count({i + 1, j}) &&
!visit.count({i + 2, j}) &&
!visit.count({i - 1, j}) &&
!visit.count({i - 2, j})))
{
visit.insert({i, j});
visit.insert({i + 1, j});
visit.insert({i + 2, j});
visit.insert({i - 1, j});
visit.insert({i - 2, j});
if (isClassical)
{
killList.push_back({
FIVE_VERTICAL_KILL,
FIVE_KILL_SCORE,
{
ActorInformation(i, j),
ActorInformation(i + 1, j),
ActorInformation(i + 2, j),
ActorInformation(i - 1, j),
ActorInformation(i - 2, j)
}
});
}
else
{
ActorInformationList actorList;
if (j != 0)
for (auto iIndex = 0; iIndex < BOARD_SIZE; iIndex++) actorList.push_back({iIndex, j - 1});
if (j != BOARD_SIZE - 1)
for (auto iIndex = 0; iIndex < BOARD_SIZE; iIndex++) actorList.push_back({iIndex, j + 1});
for (auto iIndex = 0; iIndex < BOARD_SIZE; iIndex++) actorList.push_back({iIndex, j});
killList.push_back({FIVE_VERTICAL_KILL, FIVE_KILL_SCORE, actorList});
}
}
// 水平
if (j > 1 && j < BOARD_SIZE - 2
&& (board[i][j].type == board[i][j + 1].type &&
board[i][j].type == board[i][j + 2].type &&
board[i][j].type == board[i][j - 1].type &&
board[i][j].type == board[i][j - 2].type)
&& (!visit.count({i, j}) &&
!visit.count({i, j + 1}) &&
!visit.count({i, j + 2}) &&
!visit.count({i, j - 1}) &&
!visit.count({i, j - 2})))
{
visit.insert({i, j});
visit.insert({i, j + 1});
visit.insert({i, j + 2});
visit.insert({i, j - 1});
visit.insert({i, j - 2});
if (isClassical)
{
killList.push_back({
FIVE_HORIZONTAL_KILL,
FIVE_KILL_SCORE,
{
ActorInformation(i, j),
ActorInformation(i, j + 1),
ActorInformation(i, j + 2),
ActorInformation(i, j - 1),
ActorInformation(i, j - 2)
}
});
}
else
{
ActorInformationList actorList;
if (i != 0)
for (auto jIndex = 0; jIndex < BOARD_SIZE; jIndex++) actorList.push_back({i - 1, jIndex});
if (i != BOARD_SIZE - 1)
for (auto jIndex = 0; jIndex < BOARD_SIZE; jIndex++) actorList.push_back({i + 1, jIndex});
for (auto jIndex = 0; jIndex < BOARD_SIZE; jIndex++) actorList.push_back({i, jIndex});
killList.push_back({FIVE_HORIZONTAL_KILL, FIVE_KILL_SCORE, actorList});
}
}
}
// 检查四消
for (auto i = 0; i < BOARD_SIZE; i++)
for (auto j = 0; j < BOARD_SIZE; j++)
{
if (board[i][j].type == SUPER_TYPE || visit.count({i, j})) continue;
// 竖直
if (i > 0 && i < BOARD_SIZE - 2
&& (board[i][j].type == board[i + 1][j].type &&
board[i][j].type == board[i + 2][j].type &&
board[i][j].type == board[i - 1][j].type)
&& (!visit.count({i, j}) &&
!visit.count({i + 1, j}) &&
!visit.count({i + 2, j}) &&
!visit.count({i - 1, j})))
{
visit.insert({i, j});
visit.insert({i + 1, j});
visit.insert({i + 2, j});
visit.insert({i - 1, j});
if (isClassical)
{
killList.push_back({
FOUR_VERTICAL_KILL,
FOUR_KILL_SCORE,
{
ActorInformation(i, j),
ActorInformation(i + 1, j),
ActorInformation(i + 2, j),
ActorInformation(i - 1, j)
}
});
}
else
{
ActorInformationList actorList;
for (auto iIndex = 0; iIndex < BOARD_SIZE; iIndex++) actorList.push_back({iIndex, j});
killList.push_back({FOUR_VERTICAL_KILL, FOUR_KILL_SCORE, actorList});
}
}
// 水平
if (j > 0 && j < BOARD_SIZE - 2
&& (board[i][j].type == board[i][j + 1].type &&
board[i][j].type == board[i][j + 2].type &&
board[i][j].type == board[i][j - 1].type)
&& (!visit.count({i, j}) &&
!visit.count({i, j + 1}) &&
!visit.count({i, j + 2}) &&
!visit.count({i, j - 1})))
{
visit.insert({i, j});
visit.insert({i, j + 1});
visit.insert({i, j + 2});
visit.insert({i, j - 1});
if (isClassical)
{
killList.push_back({
FOUR_HORIZONTAL_KILL,
FOUR_KILL_SCORE,
{
ActorInformation(i, j),
ActorInformation(i, j + 1),
ActorInformation(i, j + 2),
ActorInformation(i, j - 1)
}
});
}
else
{
ActorInformationList actorList;
for (auto jIndex = 0; jIndex < BOARD_SIZE; jIndex++) actorList.push_back({i, jIndex});
killList.push_back({FOUR_HORIZONTAL_KILL, FOUR_KILL_SCORE, actorList});
}
}
}
// 检查三消
for (auto i = 0; i < BOARD_SIZE; i++)
for (auto j = 0; j < BOARD_SIZE; j++)
{
if (board[i][j].type == SUPER_TYPE || visit.count({i, j})) continue;
// 竖直
if (i > 0 && i < BOARD_SIZE - 1
&& (board[i][j].type == board[i + 1][j].type &&
board[i][j].type == board[i - 1][j].type)
&& (!visit.count({i, j}) &&
!visit.count({i + 1, j}) &&
!visit.count({i - 1, j})))
{
visit.insert({i, j});
visit.insert({i + 1, j});
visit.insert({i - 1, j});
killList.push_back({
BASE_VERTICAL_KILL,
BASE_KILL_SCORE,
{
ActorInformation(i, j),
ActorInformation(i + 1, j),
ActorInformation(i - 1, j)
}
});
}
// 水平
if (j > 0 && j < BOARD_SIZE - 1
&& (board[i][j].type == board[i][j + 1].type &&
board[i][j].type == board[i][j - 1].type
)
&& (!visit.count({i, j}) &&
!visit.count({i, j + 1}) &&
!visit.count({i, j - 1})))
{
visit.insert({i, j});
visit.insert({i, j + 1});
visit.insert({i, j - 1});
killList.push_back({
BASE_HORIZONTAL_KILL,
BASE_KILL_SCORE,
{
ActorInformation(i, j),
ActorInformation(i, j + 1),
ActorInformation(i, j - 1)
}
});
}
}
return killList;
}
void GameScene::killBlock(const KillInformationList& killList, const bool isClassical)
{
// 所有被消除的块与得分
map<Pair, int> killBlock;
// 记录所有得分块
for (const auto& killInfo : killList)
for (const auto& actorInfo : killInfo.killActorList)
killBlock[actorInfo.blockIndex] += killInfo.killScore;
// 消除所有得分块
for (const auto& block : killBlock)
{
const auto blockIndex = block.first;
// 展示分数
showScore(ActorInformation(blockIndex, -1, block.second));
board[blockIndex.first][blockIndex.second].actor->disappear();
board[blockIndex.first][blockIndex.second] = Block();
// 产生下落块
auto iIndex = BOARD_SIZE;
while (board[iIndex][blockIndex.second].type != -1)
{
iIndex++;
assert(iIndex < 2 * BOARD_SIZE);
}
const auto type = getRandomNumber(TYPE_NUMBER);
const auto nowBlock = addActor(type, getPositionByIndex({iIndex, blockIndex.second}));
board[iIndex][blockIndex.second] = Block(type, nowBlock);
}
// 添加Super块
if (!isClassical)
for (const auto& killInfo : killList)
{
if (killInfo.newBlockIndex != Pair(-1, -1))
{
const auto newActor = addActor(SUPER_TYPE, getPositionByIndex(killInfo.newBlockIndex));
board[killInfo.newBlockIndex.first][killInfo.newBlockIndex.second] = Block(SUPER_TYPE, newActor);
// 删除下落块
auto iIndex = 2 * BOARD_SIZE - 1;
while (board[iIndex][killInfo.newBlockIndex.second].type == -1)
{
iIndex--;
assert(iIndex >= BOARD_SIZE);
}
removeChild(board[iIndex][killInfo.newBlockIndex.second].actor);
board[iIndex][killInfo.newBlockIndex.second] = Block();
}
}
// 放特效音效
for (const auto& killInfo : killList)
{
switch (killInfo.killType)
{
case BASE_HORIZONTAL_KILL:
case BASE_VERTICAL_KILL:
{
Sound::getInstance()->play(Sound::getInstance()->threeKill);
break;
}
case FOUR_HORIZONTAL_KILL:
{
Sound::getInstance()->play(Sound::getInstance()->fourKill);
if (!isClassical)
showOneLineParticle(killInfo.killActorList[0].blockIndex, false);
break;
}
case FOUR_VERTICAL_KILL:
{
Sound::getInstance()->play(Sound::getInstance()->fourKill);
if (!isClassical)
showOneLineParticle(killInfo.killActorList[0].blockIndex, true);
break;
}
case FIVE_HORIZONTAL_KILL:
{
Sound::getInstance()->play(Sound::getInstance()->fiveKill);
if (!isClassical)
{
set<int> index;
for (const auto& actor : killInfo.killActorList) index.insert(actor.blockIndex.first);
for (auto it : index) showOneLineParticle({it, 0}, false);
}
break;
}
case FIVE_VERTICAL_KILL:
{
Sound::getInstance()->play(Sound::getInstance()->fiveKill);
if (!isClassical)
{
set<int> index;
for (const auto& actor : killInfo.killActorList) index.insert(actor.blockIndex.second);
for (auto it : index) showOneLineParticle({0, it}, true);
}
break;
}
case DOUBLE_BASE_KILL:
{
assert(!isClassical);
Sound::getInstance()->play(Sound::getInstance()->boom);
auto iIndex = 3 * BOARD_SIZE, jIndex = 3 * BOARD_SIZE;
for (const auto& actor : killInfo.killActorList)
{
if (actor.blockIndex.first < iIndex) iIndex = actor.blockIndex.first;
if (actor.blockIndex.second < jIndex) jIndex = actor.blockIndex.second;
}
showExplosion({iIndex + 1, jIndex + 1});
break;
}
case DOUBLE_FOUR_KILL:
{
assert(!isClassical);
Sound::getInstance()->play(Sound::getInstance()->superCreate);
for (const auto& actor : killInfo.killActorList) showSingleParticle(actor.blockIndex, 1);
break;
}
case SUPER_KILL:
{
assert(!isClassical);
Sound::getInstance()->play(Sound::getInstance()->boom);
for (const auto& actor : killInfo.killActorList) showSingleParticle(actor.blockIndex, 0);
break;
}
case DOUBLE_SUPER_KILL:
{
assert(!isClassical);
Sound::getInstance()->play(Sound::getInstance()->boom);
showFullBoardParticle();
break;
}
default:
assert(false);
}
}
runAction(Sequence::create(DelayTime::create(0.3f), CallFunc::create([&]() { dropBlock(); }), nullptr));
}
|
80d91865b216bdfcd0078c8a3d225830e3e20ff8
|
90047daeb462598a924d76ddf4288e832e86417c
|
/chrome/browser/chromeos/arc/wallpaper/arc_wallpaper_service.cc
|
3ae9e9eaf8f53c40e6699b81b2b10bce3494df42
|
[
"BSD-3-Clause"
] |
permissive
|
massbrowser/android
|
99b8c21fa4552a13c06bbedd0f9c88dd4a4ad080
|
a9c4371682c9443d6e1d66005d4db61a24a9617c
|
refs/heads/master
| 2022-11-04T21:15:50.656802
| 2017-06-08T12:31:39
| 2017-06-08T12:31:39
| 93,747,579
| 2
| 2
|
BSD-3-Clause
| 2022-10-31T10:34:25
| 2017-06-08T12:36:07
| null |
UTF-8
|
C++
| false
| false
| 8,954
|
cc
|
arc_wallpaper_service.cc
|
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/arc/wallpaper/arc_wallpaper_service.h"
#include <stdlib.h>
#include <deque>
#include "ash/shell.h"
#include "ash/wallpaper/wallpaper_controller.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/task_scheduler/post_task.h"
#include "chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager.h"
#include "chrome/browser/image_decoder.h"
#include "components/arc/arc_bridge_service.h"
#include "components/signin/core/account_id/account_id.h"
#include "components/user_manager/user_manager.h"
#include "components/wallpaper/wallpaper_files_id.h"
#include "components/wallpaper/wallpaper_layout.h"
#include "components/wallpaper/wallpaper_resizer.h"
#include "content/public/browser/browser_thread.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/image/image_util.h"
using user_manager::UserManager;
namespace arc {
namespace {
constexpr char kAndroidWallpaperFilename[] = "android.jpg";
// The structure must not go out from a method invoked on BrowserThread::UI
// because the primary account referenced by the class will be released.
struct PrimaryAccount {
const AccountId& id;
const bool is_active;
};
PrimaryAccount GetPrimaryAccount() {
UserManager* const user_manager = UserManager::Get();
const AccountId& account_id = user_manager->GetPrimaryUser()->GetAccountId();
return {account_id,
account_id == user_manager->GetActiveUser()->GetAccountId()};
}
std::vector<uint8_t> EncodeImagePng(const gfx::ImageSkia image) {
std::vector<uint8_t> result;
gfx::PNGCodec::FastEncodeBGRASkBitmap(*image.bitmap(), true, &result);
return result;
}
ash::WallpaperController* GetWallpaperController() {
if (!ash::Shell::HasInstance())
return nullptr;
return ash::Shell::Get()->wallpaper_controller();
}
} // namespace
// Store for mapping between ImageSkia ID and Android wallpaper ID.
// Skia image ID is used to keep track of the wallpaper on the Chrome side, and
// we need to map it to the Android's wallpaper ID in ARC++. Because setting
// wallpaper is async operation, the caller stores the pair of ImageSkia ID and
// wallpaper ID when it requests setting a wallpaper, then it obtains the
// corresponding Andorid ID when the completion of setting a wallpaper is
// notified.
class ArcWallpaperService::AndroidIdStore {
public:
AndroidIdStore() = default;
// Remembers a pair of image and Android ID.
void Push(const gfx::ImageSkia& image, int32_t android_id) {
pairs_.push_back(
{wallpaper::WallpaperResizer::GetImageId(image), android_id});
}
// Gets Android ID for |image_id|. Returns -1 if it does not found Android ID
// corresponding to |image_id|. Sometimes the corresonpding |Pop| is not
// called after |Push| is invoked, thus |Pop| removes older pairs in addition
// to the pair of given |image_id| when the pair is found.
int32_t Pop(uint32_t image_id) {
for (size_t i = 0; i < pairs_.size(); ++i) {
if (pairs_[i].image_id == image_id) {
const int32_t result = pairs_[i].android_id;
pairs_.erase(pairs_.begin(), pairs_.begin() + i + 1);
return result;
}
}
return -1;
}
private:
struct Pair {
uint32_t image_id;
int32_t android_id;
};
std::deque<Pair> pairs_;
DISALLOW_COPY_AND_ASSIGN(AndroidIdStore);
};
class ArcWallpaperService::DecodeRequest : public ImageDecoder::ImageRequest {
public:
DecodeRequest(ArcWallpaperService* service, int32_t android_id)
: service_(service), android_id_(android_id) {}
~DecodeRequest() override = default;
// ImageDecoder::ImageRequest overrides.
void OnImageDecoded(const SkBitmap& bitmap) override {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
// Make the SkBitmap immutable as we won't modify it. This is important
// because otherwise it gets duplicated during painting, wasting memory.
SkBitmap immutable_bitmap(bitmap);
immutable_bitmap.setImmutable();
gfx::ImageSkia image = gfx::ImageSkia::CreateFrom1xBitmap(immutable_bitmap);
image.MakeThreadSafe();
service_->android_id_store()->Push(image, android_id_);
chromeos::WallpaperManager* const wallpaper_manager =
chromeos::WallpaperManager::Get();
const PrimaryAccount& account = GetPrimaryAccount();
wallpaper::WallpaperFilesId wallpaper_files_id =
wallpaper_manager->GetFilesId(account.id);
// TODO(crbug.com/618922): Allow specifying layout.
wallpaper_manager->SetCustomWallpaper(
account.id, wallpaper_files_id, kAndroidWallpaperFilename,
wallpaper::WALLPAPER_LAYOUT_CENTER_CROPPED,
user_manager::User::CUSTOMIZED, image,
account.is_active /*update_wallpaper*/);
// TODO(crbug.com/618922): Register the wallpaper to Chrome OS wallpaper
// picker. Currently the new wallpaper does not appear there. The best way
// to make this happen seems to do the same things as wallpaper_api.cc and
// wallpaper_private_api.cc.
}
void OnDecodeImageFailed() override {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
DLOG(ERROR) << "Failed to decode wallpaper image.";
// Android regards the new wallpaper was set to Chrome. Invoke
// OnWallpaperDataChanged to notify that the previous wallpaper is still
// used in chrome. Note that |wallpaper_id| is not passed back to ARC in
// this case.
service_->OnWallpaperDataChanged();
}
private:
// ArcWallpaperService owns DecodeRequest, so it will outlive this.
ArcWallpaperService* const service_;
const int32_t android_id_;
DISALLOW_COPY_AND_ASSIGN(DecodeRequest);
};
ArcWallpaperService::ArcWallpaperService(ArcBridgeService* bridge_service)
: ArcService(bridge_service),
binding_(this),
android_id_store_(new AndroidIdStore()) {
arc_bridge_service()->wallpaper()->AddObserver(this);
}
ArcWallpaperService::~ArcWallpaperService() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
ash::WallpaperController* wc = GetWallpaperController();
if (wc)
wc->RemoveObserver(this);
arc_bridge_service()->wallpaper()->RemoveObserver(this);
}
void ArcWallpaperService::OnInstanceReady() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
mojom::WallpaperInstance* wallpaper_instance =
ARC_GET_INSTANCE_FOR_METHOD(arc_bridge_service()->wallpaper(), Init);
DCHECK(wallpaper_instance);
wallpaper_instance->Init(binding_.CreateInterfacePtrAndBind());
ash::WallpaperController* wc = GetWallpaperController();
DCHECK(wc);
wc->AddObserver(this);
}
void ArcWallpaperService::OnInstanceClosed() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
ash::WallpaperController* wc = GetWallpaperController();
if (wc)
wc->RemoveObserver(this);
}
void ArcWallpaperService::SetWallpaper(const std::vector<uint8_t>& data,
int32_t wallpaper_id) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (wallpaper_id == 0)
wallpaper_id = -1;
// Previous request will be cancelled at destructor of
// ImageDecoder::ImageRequest.
decode_request_ = base::MakeUnique<DecodeRequest>(this, wallpaper_id);
ImageDecoder::StartWithOptions(decode_request_.get(), data,
ImageDecoder::DEFAULT_CODEC, true,
gfx::Size());
}
void ArcWallpaperService::SetDefaultWallpaper() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
// Previous request will be cancelled at destructor of
// ImageDecoder::ImageRequest.
decode_request_.reset();
const PrimaryAccount& account = GetPrimaryAccount();
chromeos::WallpaperManager::Get()->SetDefaultWallpaper(account.id,
account.is_active);
}
void ArcWallpaperService::GetWallpaper(const GetWallpaperCallback& callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
ash::WallpaperController* wc = ash::Shell::Get()->wallpaper_controller();
gfx::ImageSkia wallpaper = wc->GetWallpaper();
base::PostTaskWithTraitsAndReplyWithResult(
FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND},
base::Bind(&EncodeImagePng, wallpaper), callback);
}
void ArcWallpaperService::OnWallpaperDataChanged() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
auto* const wallpaper_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service()->wallpaper(), OnWallpaperChanged);
const ash::WallpaperController* const wc = GetWallpaperController();
const int32_t android_id =
wc ? android_id_store_->Pop(wc->GetWallpaperOriginalImageId()) : -1;
if (!wallpaper_instance)
return;
wallpaper_instance->OnWallpaperChanged(android_id);
}
} // namespace arc
|
221df423af4c843ac3446f63177a750e21884ccc
|
4653c0a797bf312660c8322004382483aadb04b3
|
/src/imageParticleSystem.cpp
|
9e41ff58331c00d96de5e8d8a14889639cc0e17c
|
[] |
no_license
|
KatharinaMina/SpielauswertungMapping
|
41865605ee70bd5a2452531ff760f92275ff1c19
|
ded58dabc77f95b42659ece9d9f10965a97aa731
|
refs/heads/master
| 2022-01-11T20:02:32.961841
| 2019-06-21T13:47:25
| 2019-06-21T13:47:25
| 171,855,483
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,831
|
cpp
|
imageParticleSystem.cpp
|
#include "imageParticleSystem.h"
ImageParticleSystem::ImageParticleSystem(int sceneSizeX, int sceneSizeY, ofImage fileImageHex, string imageName) {
this->imageToDraw = new DrawableImage(imageName, sceneSizeX, sceneSizeY);
this->imageHeight = imageToDraw->getHeight();
this->imageWidth = imageToDraw->getWidth();
this->sceneSizeX = sceneSizeX;
this->sceneSizeY = sceneSizeY;
this->fileImageHex = fileImageHex;
setAttractorsFromHexagonFromPicture();
maxParticle = 50;
setSymbolAttractorIsSet(true);
setCloudAttractorIsSet(false);
ticksToMoveImageToTop = 200;
counterToMoveImageToTop = 0;
fileImageCloud.loadImage("Hexagon.png");
imageReachedTopAndAttractorIsChanged = false;
}
//----------------------------------------------------------
void ImageParticleSystem::updateParticleSystem() {
double deltaT = ofGetLastFrameTime();
time += deltaT;
if ((cloudAttractorIsSet == false) && (particles.size() < picPix / 7) && (this->imageToDraw->imageIsOnTop(sceneSizeY) == false)) { //Creating particles for symbol on bottom
createParticlesForHexagonInSymbol();
}
else if ((cloudAttractorIsSet == false) && (particles.size() < picPix / 7) && (this->imageToDraw->imageIsOnTop(sceneSizeY))) { //Creating particles for symbol in cloud
createParticlesForHexagonInCloud();
}
else if ((cloudAttractorIsSet == false) && (particles.size() > picPix / 7)) { //Deleting unused particles for hexagon on bottom
deleteParticlesForHexagon();
}
else if ((cloudAttractorIsSet == true) && (particles.size() > picPix / 7)) { //Deleting unused particles for rocketeffect
//deleteParticlesForRocketEffect();
}
//Movement
for (int p = 0; p < particles.size(); p++) {
if (p * 7 < attractors.size()) {
if (cloudAttractorIsSet == true) { //Movement at rocketeffect
particles.at(p)->updateParticle(deltaT, attractors[p * 7],
cloudAttractorIsSet, this->imageToDraw->imageIsOnTop(sceneSizeY), true, imageHeight, imageWidth, sceneSizeX, sceneSizeY);
}
else if (symbolAttractorIsSet == true) //Movement at Symbol at the bottom
{
particles.at(p)->updateParticle(deltaT, attractors[p * 7],
cloudAttractorIsSet, this->imageToDraw->imageIsOnTop(sceneSizeY), true, imageHeight, imageWidth, sceneSizeX, sceneSizeY);
if (this->imageToDraw->imageIsOnTop(sceneSizeY)) //Deleting the particle after they left scene at right
{
deleteParticleAfterLeavingOntheRightAndCreateThemOnTheLeft(p);
}
}
}
}
if (counterToMoveImageToTop < ticksToMoveImageToTop) { //Delay (every Frame) before the symbol and particle pass to the rocket effect
counterToMoveImageToTop++;
}
else if (counterToMoveImageToTop == ticksToMoveImageToTop) { //Symbol and particles do over in rocketeffect
changeAttractorImage(fileImageCloud);
setCloudAttractorIsSet(true);
}
if (this->imageToDraw->imageIsOnTop(sceneSizeY)) { //Symbol and particles reached max. y-position and attractor gets changed from rocketeffect to hexagon
setAttractorsFromHexagonFromPicture();
cloudAttractorIsSet = false;
}
}
//----------------------------------------------------------
void ImageParticleSystem::createParticlesForHexagonInSymbol()
{
int newPix = (picPix / 7) - particles.size();
for (int i = 1; i <= newPix; i++) { //Go through pixel i = 1 (there is no pixel 0)
particles.push_back(new Particle);
int x = sceneSizeX / 2;
int y = sceneSizeY;
particles.back()->setup(ofVec2f(x, y), 20);
}
}
//----------------------------------------------------------
void ImageParticleSystem::createParticlesForHexagonInCloud()
{
int newPix = (picPix / 7) - particles.size();
for (int i = 1; i <= newPix; i++) { //Go through pixel i = 1 (there is no pixel 0)
particles.push_back(new Particle);
int x = sceneSizeX / 2;
int y = imageToDraw->getImagePosY(sceneSizeY) + imageHeight;
particles.back()->setup(ofVec2f(x, y), 20);
}
}
//----------------------------------------------------------
void ImageParticleSystem::deleteParticlesForRocketEffect()
{
int newPix = (particles.size() - (picPix / 7));
for (int i = 0; i < newPix; i++) {
delete particles.at(0); //Deleting particle object
particles.erase(particles.begin()); //Deleting pointer to particle
}
}
//----------------------------------------------------------
void ImageParticleSystem::deleteParticlesForHexagon()
{
int newPix = (particles.size() - (picPix / 7));
for (int i = 0; i < newPix; i++) {
delete particles.at(0); //Deleting particle object
particles.erase(particles.begin()); //Deleting pointer to particle
}
}
//----------------------------------------------------------
void ImageParticleSystem::deleteParticleAfterLeavingOntheRightAndCreateThemOnTheLeft(int p)
{
bool particleToDelete = particles.at(p)->deleteAfterLeavingSceneX();
if (particleToDelete) {
delete particles.at(0); //Deleting particle object
particles.erase(particles.begin()); //Deleting pointer to particle
//Durchgehen ab Partikel i = 1 da es kein Pixel 0 gibt
particles.push_back(new Particle);
int x = -50;
int y = imageToDraw->getHeight();
particles.back()->setup(ofVec2f(x, y), 20);
}
}
//----------------------------------------------------------
void ImageParticleSystem::changeAttractorImage(ofImage newAttractorImage) { //Attractor is changed between hexagon and cloud
attractors = pixelInVector(newAttractorImage);
}
//----------------------------------------------------------
void ImageParticleSystem::setAttractorsFromHexagonFromPicture() { //Hexagon is attracot (pixel from hexagon get converted in attractors)
int picWidth = fileImageHex.getWidth();
int picHeight = fileImageHex.getHeight();
ofPixels pix;
pix = fileImageHex.getPixels();
vector<ofVec2f> pxPos;
picPix = 0;
for (int i = 3; i <= pix.size(); i += 4) { //i specifys that every fourth color information of the pixel is handled (rgba)
if (pix[i] > 0) {
int width = pix.getWidth();
int y = i / 4 / width;
int x = i / 4 % width;
ofVec2f vec;
vec.set(x + imageToDraw->getImagePosX(sceneSizeX), y + imageToDraw->getImagePosY(sceneSizeY)); //Gets position of image and so that the attractor follows movement
pxPos.push_back(vec);
picPix++;
}
}
attractors = pxPos;
}
//----------------------------------------------------------
vector<ofVec2f> ImageParticleSystem::pixelInVector(ofImage a) { //Read in all the coloured pixels of image and vonvert them in vectors
int picWidth = a.getWidth();
int picHeight = a.getHeight();
ofPixels pix;
pix = a.getPixels();
vector<ofVec2f> pxPos;
picPix = 0;
for (int i = 3; i <= pix.size(); i += 4) { //i specifys that every fourth color information of the pixel is handled (rgba)
if (pix[i] > 0) {
int width = pix.getWidth();
int y = i / 4 / width;
int x = i / 4 % width;
ofVec2f vec;
vec.set(x + ((sceneSizeX / 2) - picWidth / 2), y - ((sceneSizeY)-picHeight - 7));
pxPos.push_back(vec);
picPix++;
}
}
return pxPos;
}
//----------------------------------------------------------
void ImageParticleSystem::drawImageParticleSystem() { //Drawing of symbols and particles
imageToDraw->updateImage(sceneSizeX, sceneSizeY);
for (int i = 0; i < particles.size(); i++) {
particles.at(i)->draw();
}
}
//----------------------------------------------------------
void ImageParticleSystem::setSymbolAttractorIsSet(bool value) {
imageToDraw->symbolAttractorIsSet = value;
symbolAttractorIsSet = value;
}
//----------------------------------------------------------
void ImageParticleSystem::setCloudAttractorIsSet(bool value) {
imageToDraw->cloudAttractorIsSet = value;
cloudAttractorIsSet = value;
}
|
a4a0803fc8b786ef71e6f17a839706b690f79d15
|
076ba173f5b518977d30f4336c63b177a5a7f66d
|
/cases/surfers_in_channel_flow_x/param/env/objects/static/surfer__us_0o05__surftimeconst_1o5/group/homogeneous/_member/choice.h
|
6ea5c8c3756e5e33098d38826b06fa392585ab12
|
[
"MIT"
] |
permissive
|
C0PEP0D/sheld0n
|
a661b27ffee7b087731f0a3e9f92c2ee26d7d560
|
a1b9a065cfaa2e3faf5a749f14201a84baa41ce9
|
refs/heads/master
| 2023-04-28T20:53:27.684636
| 2023-04-18T21:20:00
| 2023-04-18T21:20:00
| 421,041,396
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 627
|
h
|
choice.h
|
#ifndef C0P_PARAM_OBJECTS_SURFER__US_0O05__SURFTIMECONST_1O5_GROUP_HOMOGENEOUS_MEMBER_CHOICE_H
#define C0P_PARAM_OBJECTS_SURFER__US_0O05__SURFTIMECONST_1O5_GROUP_HOMOGENEOUS_MEMBER_CHOICE_H
#pragma once
// THIS FILE SHOULD NOT BE EDITED DIRECTLY BY THE USERS.
// THIS FILE WILL BE AUTOMATICALLY EDITED WHEN THE
// CHOOSE COMMAND IS USED
// choose your object
#include "param/env/objects/static/surfer__us_0o05__surftimeconst_1o5/group/homogeneous/_member/agent/choice.h"
namespace c0p {
using SurferUs0O05Surftimeconst1O5GroupHomogeneousMemberStep = SurferUs0O05Surftimeconst1O5GroupHomogeneousMemberAgentStep;
}
#endif
|
36b8a548d7420ce14db8eff5c6b56f7246d34c18
|
f0e15c3b7b88561b3acdd34dca9365633f241632
|
/program/エフェクト/Bullet.cpp
|
9da61a3a4bf39d9c555b84f12fbc68c1fe6b7669
|
[] |
no_license
|
Saitouyukihiro/3DGame_Progress
|
f8bd6fbb9b93b49c6b1b143ef2a10dc0531c18ef
|
fe0ebac5513cc4fe41bb06aaab88692b770b1b81
|
refs/heads/master
| 2023-03-28T14:22:29.372673
| 2021-03-30T02:31:22
| 2021-03-30T02:31:22
| 319,807,541
| 0
| 0
| null | null | null | null |
SHIFT_JIS
|
C++
| false
| false
| 8,294
|
cpp
|
Bullet.cpp
|
#include "main.h"
#include "bullet.h"
#include "Model.h"
#include "camera.h"
#include "Object.h"
#include "Effect.h"
#include "wall.h"
//グローバル変数
LPDIRECT3DTEXTURE9 g_pTextureBullet[BULLETTYPE_MAX] = {};//テクスチャへのポインタ
//頂点バッファのポインタ
LPDIRECT3DVERTEXBUFFER9 g_pVtxBuffBullet = NULL; //頂点バッファへのポインタ
Bullet g_aBullet[MAX_BULLET];
//初期化処理
void InitBullet(void)
{
LPDIRECT3DDEVICE9 pDevice;//デバイスのポインタ
int nCntBullet;
pDevice = GetDevice();//デバイスの取得
//弾の初期化
for (nCntBullet = 0; nCntBullet < MAX_BULLET; nCntBullet++)
{
g_aBullet[nCntBullet].pos = D3DXVECTOR3(0.0f, 0.0f, 0.0f);
g_aBullet[nCntBullet].rot = D3DXVECTOR3(0.0f, 0.0f, 0.0f);
g_aBullet[nCntBullet].bUse = false;
g_aBullet[nCntBullet].nlife = 0;
g_aBullet[nCntBullet].ntype = 0;
}
//テクスチャの読み込み
D3DXCreateTextureFromFile(pDevice, "date/TEXTURE/はね.png", &g_pTextureBullet[BULLETTYPE_PLAYER]);
//頂点バッファの生成
pDevice->CreateVertexBuffer(sizeof(VERTEX_3D) * 4 * MAX_BULLET, D3DUSAGE_WRITEONLY, FVF_VERTEX_3D, D3DPOOL_MANAGED, &g_pVtxBuffBullet, NULL);
VERTEX_3D*pVtx;//頂点情報へのポインタ
//頂点バッファをロックし、頂点データへのポインタを取得
g_pVtxBuffBullet->Lock(0, 0, (void**)&pVtx, 0);
for (nCntBullet = 0; nCntBullet < MAX_BULLET; nCntBullet++)
{
//頂点の座標
pVtx[0].pos = D3DXVECTOR3(g_aBullet[nCntBullet].pos.x - (MAX_BULLET_SIZE_X / 2), g_aBullet[nCntBullet].pos.y + (MAX_BULLET_SIZE_Y / 2), g_aBullet[nCntBullet].pos.z);
pVtx[1].pos = D3DXVECTOR3(g_aBullet[nCntBullet].pos.x + (MAX_BULLET_SIZE_X / 2), g_aBullet[nCntBullet].pos.y + (MAX_BULLET_SIZE_Y / 2), g_aBullet[nCntBullet].pos.z);
pVtx[2].pos = D3DXVECTOR3(g_aBullet[nCntBullet].pos.x - (MAX_BULLET_SIZE_X / 2), g_aBullet[nCntBullet].pos.y, g_aBullet[nCntBullet].pos.z);
pVtx[3].pos = D3DXVECTOR3(g_aBullet[nCntBullet].pos.x + (MAX_BULLET_SIZE_X / 2), g_aBullet[nCntBullet].pos.y, g_aBullet[nCntBullet].pos.z);
//ベクトルの設定
pVtx[0].nor = D3DXVECTOR3(0.0f, 1.0f, 0.0f);
pVtx[1].nor = D3DXVECTOR3(0.0f, 1.0f, 0.0f);
pVtx[2].nor = D3DXVECTOR3(0.0f, 1.0f, 0.0f);
pVtx[3].nor = D3DXVECTOR3(0.0f, 1.0f, 0.0f);
//頂点の色
pVtx[0].col = D3DCOLOR_RGBA(255, 255, 255, 255);
pVtx[1].col = D3DCOLOR_RGBA(255, 255, 255, 255);
pVtx[2].col = D3DCOLOR_RGBA(255, 255, 255, 255);
pVtx[3].col = D3DCOLOR_RGBA(255, 255, 255, 255);
//テクスチャのUV座標
pVtx[0].tex = D3DXVECTOR2(0.0f, 0.0f);
pVtx[1].tex = D3DXVECTOR2(1.0f, 0.0f);
pVtx[2].tex = D3DXVECTOR2(0.0f, 1.0f);
pVtx[3].tex = D3DXVECTOR2(1.0f, 1.0f);
pVtx += 4;
}
//頂点バッファをアンロック
g_pVtxBuffBullet->Unlock();
}
//終了処理
void UninitBullet(void)
{
int nCntBullet;
for (nCntBullet = 0; nCntBullet == BULLETTYPE_MAX; nCntBullet++)
{
//テクスチャの破棄
if (g_pTextureBullet[nCntBullet] != NULL)
{
g_pTextureBullet[nCntBullet]->Release();
g_pTextureBullet[nCntBullet] = NULL;
}
//頂点バッファも破棄
if (g_pVtxBuffBullet != NULL)
{
g_pVtxBuffBullet->Release();
g_pVtxBuffBullet = NULL;
}
}
}
//更新処理
void UpdateBullet(void)
{
int nCntBullet;
Object * pObject = GetObject();
Wall * pWall = GetWall();
for (nCntBullet = 0; nCntBullet < MAX_BULLET; nCntBullet++)
{
if (g_aBullet[nCntBullet].bUse == true)
{
g_aBullet[nCntBullet].pos.x += sinf(g_aBullet[nCntBullet].rot.y) * 6;
g_aBullet[nCntBullet].pos.z += cosf(g_aBullet[nCntBullet].rot.y) * 6;
g_aBullet[nCntBullet].pos.y += tanf(g_aBullet[nCntBullet].rot.x) * 6;
g_aBullet[nCntBullet].nlife--;
//オブジェクトと弾の当たり判定
for (int nCntObject = 0; nCntObject < MAX_OBJECT; nCntObject++)
{
if (pObject[nCntObject].bUse == true)
{
if (g_aBullet[nCntBullet].pos.x >= pObject[nCntObject].pos.x + (pObject[nCntObject].VtxMinObject.x) && g_aBullet[nCntBullet].pos.x <= pObject[nCntObject].pos.x + (pObject[nCntObject].VtxMaxObject.x) &&
g_aBullet[nCntBullet].pos.y >= pObject[nCntObject].pos.y + (pObject[nCntObject].VtxMinObject.y) && g_aBullet[nCntBullet].pos.y <= pObject[nCntObject].pos.y + (pObject[nCntObject].VtxMaxObject.y) &&
g_aBullet[nCntBullet].pos.z >= pObject[nCntObject].pos.z + (pObject[nCntObject].VtxMinObject.z) && g_aBullet[nCntBullet].pos.z <= pObject[nCntObject].pos.z + (pObject[nCntObject].VtxMaxObject.z))
{
g_aBullet[nCntBullet].bUse = false;
}
}
}
/*for (int nCntWall = 0; nCntWall < MAX_WALL; nCntWall++)
{
if (pWall[nCntWall].bUse == true)
{
if (g_aBullet[nCntBullet].pos.x > pWall[nCntWall].pos.x - (pWall[nCntWall].fWhidth) &&
g_aBullet[nCntBullet].pos.x < pWall[nCntWall].pos.x + (pWall[nCntWall].fWhidth)&&
g_aBullet[nCntBullet].pos.y > pWall[nCntWall].pos.y - (pWall[nCntWall].fHight) &&
g_aBullet[nCntBullet].pos.y < pWall[nCntWall].pos.y + (pWall[nCntWall].fHight))
{
g_aBullet[nCntBullet].bUse = false;
}
}
}*/
SetEffect(g_aBullet[nCntBullet].pos, D3DXCOLOR(255, 0, 255, 255), 8, 8, EFFECTTYPE_PLAYER, 7);
//射程圏外になったら消す
if (g_aBullet[nCntBullet].nlife <= 0)
{
g_aBullet[nCntBullet].bUse = false;
}
}
}
}
//描画処理
void DrawBullet(void)
{
int nCntBullet;
LPDIRECT3DDEVICE9 pDevice;//デバイスのポインタ
D3DXMATRIX mtxView;
D3DXMATRIX mtxTrans;
pDevice = GetDevice();//デバイスを取得する
for (nCntBullet = 0; nCntBullet < MAX_BULLET; nCntBullet++)
{
if (g_aBullet[nCntBullet].bUse == true)
{
//Zテスト関係
/*pDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
pDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);*/
//アルファテスト関係
pDevice->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE);
pDevice->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATER);
pDevice->SetRenderState(D3DRS_ALPHAREF, 0);
//マトリックス初期化
D3DXMatrixIdentity(&g_aBullet[nCntBullet].mtxWorld);
//ビューマトリックスの取得
pDevice->GetTransform(D3DTS_VIEW, &mtxView);
//ポリゴンをカメラに対して正面に
D3DXMatrixInverse(&g_aBullet[nCntBullet].mtxWorld, NULL, &mtxView);
g_aBullet[nCntBullet].mtxWorld._41 = 0.0f;
g_aBullet[nCntBullet].mtxWorld._42 = 0.0f;
g_aBullet[nCntBullet].mtxWorld._43 = 0.0f;
//位置を反映
D3DXMatrixTranslation(&mtxTrans, g_aBullet[nCntBullet].pos.x, g_aBullet[nCntBullet].pos.y, g_aBullet[nCntBullet].pos.z);
D3DXMatrixMultiply(&g_aBullet[nCntBullet].mtxWorld, &g_aBullet[nCntBullet].mtxWorld, &mtxTrans);
//ワールドマトリックスの設定
pDevice->SetTransform(D3DTS_WORLD, &g_aBullet[nCntBullet].mtxWorld);
//頂点バッファをデバイスのデータストリームに設定
pDevice->SetStreamSource(0, g_pVtxBuffBullet, 0, sizeof(VERTEX_3D));
pDevice->SetFVF(FVF_VERTEX_3D);//頂点フォーマットの設定
pDevice->SetTexture(0, g_pTextureBullet[0]);//テクスチャの設定
//ポリゴンの描画
pDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, nCntBullet * 4, 2);
//Zテスト関係
/*pDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_LESSEQUAL);
pDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);*/
//アルファテスト関係
pDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
pDevice->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_ALWAYS);
pDevice->SetRenderState(D3DRS_ALPHAREF, 0x00);
}
}
}
//弾の設定処理
void SetBullet(D3DXVECTOR3 pos, D3DXVECTOR3 rot, int ntype)
{
int nCntBullet;
for (nCntBullet = 0; nCntBullet < MAX_BULLET; nCntBullet++)
{
if (g_aBullet[nCntBullet].bUse == false)
{
g_aBullet[nCntBullet].pos = pos;
g_aBullet[nCntBullet].ntype = ntype;
g_aBullet[nCntBullet].rot = rot;
g_aBullet[nCntBullet].nlife = 100;
g_aBullet[nCntBullet].bUse = true;
break;
}
}
}
Bullet *GetBullet(void)
{
return &g_aBullet[0];
}
|
a44622400636ea5c9abeaa47dc72342d722db1ee
|
5a3ff25304ee2fd2d5fee54a07ce0c5bc1ea37de
|
/BattlecodeBots/MAY I live forever/PlayerData.h
|
97a406cc331f7cdb439d89bebb3b5bc12064de23
|
[] |
no_license
|
Wesxdz/battlecode-2018
|
29b105af484cf46523a4eb021c2af8e043893a1e
|
87ecf0aa7e52124303be08aaac7a35ff49eaf215
|
refs/heads/master
| 2021-03-16T08:41:36.825260
| 2018-01-28T19:43:35
| 2018-01-28T19:43:35
| 116,757,703
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 702
|
h
|
PlayerData.h
|
#ifndef PLAYERDATA_H
#define PLAYERDATA_H
#include "bc.h"
#include <map>
#include <vector>
#include "MapLocation.h"
class PlayerData
{
public:
static PlayerData* pd;
PlayerData();
//Updates unit counts and vector of our units.
void Update();
std::map<bc_UnitType, int> teamUnitCounts;
std::map<bc_UnitType, int> inProductionCounts;
std::map<bc_UnitType, int> enemyUnitCounts;
std::map<bc_UnitType, float> unitPriority;
void GatherUnitData();
void ClearUnitCounts();
std::vector<MapLocation> teamSpawnPositions;
std::vector<MapLocation> enemySpawnPositions;
int optimalFlightTime;
std::vector<int> optimalLaunchRounds;
std::map<bc_UnitType, int> enemyResearchBranches;
};
#endif
|
2b891eb31c07a1ea46b7c9f40c361e34c0148ac8
|
c3cb63277addd243fa97afc26e08cfdbfc285600
|
/Sem5/PDP/Lab6_Bonus/numberDiff.h
|
1c9235e79394141ef74e07b7f383f5cc05f1aa9a
|
[] |
no_license
|
Sueetan/UBB
|
142f7eafcc0940f6fe06b7a0bb48435d6ea06e77
|
c35c823a7086b97d8d50d0100a10612144658bde
|
refs/heads/master
| 2022-12-28T15:07:34.617641
| 2020-05-31T21:55:55
| 2020-05-31T21:55:55
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 225
|
h
|
numberDiff.h
|
//
// Created by Diana on 11/13/2019.
//
#ifndef LAB1_CPP_NUMBERDIFF_H
#define LAB1_CPP_NUMBERDIFF_H
#include <vector>
using namespace std;
void numberDiff(vector<int> *a, vector<int> *b);
#endif //LAB1_CPP_NUMBERDIFF_H
|
3c0ea80e0c8761b11d220765bb0663322d11eef6
|
a587b515c9215cb54f12202a511acad976ff4c30
|
/week03-210704-210710/pkpete/1339 단어 수학.cpp
|
6023e885b3d0c7aa65637772dc9ad5c9218ae954
|
[] |
no_license
|
DevKTak/inflearn-daily-algorithm-study
|
05d5e9e676859c2a7baa1f111f63c8b208225208
|
cfcb67de3da576c5fc81f3c63e7f9393402e79f8
|
refs/heads/main
| 2023-07-02T03:54:04.642717
| 2021-07-23T09:12:52
| 2021-07-23T09:12:52
| 379,280,288
| 0
| 0
| null | 2021-06-22T13:31:10
| 2021-06-22T13:31:10
| null |
UTF-8
|
C++
| false
| false
| 530
|
cpp
|
1339 단어 수학.cpp
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int arr[26];
int n;
vector<string> v;
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
string str;
cin >> str;
v.push_back(str);
}
for (int i = 0; i < v.size(); i++) {
int num = 1;
for (int j = v[i].size() - 1; j >= 0; j--) {
arr[v[i][j] - 'A'] += num;
num *= 10;
}
}
sort(arr, arr + 26);
int num = 9;
int sum = 0;
for (int i = 25; i >= 0; i--) {
if (arr[i] == 0) break;
sum += arr[i] * num--;
}
cout << sum;
}
|
15a679808420f94850149747260261e523a938bb
|
fa31f98455f6bb89be3a825ee8d7b96e901def93
|
/code/senior projet/a2d.cpp
|
b41a6c7040f0c6cec64ae8742c96265f8b09c5ad
|
[] |
no_license
|
Rouble/senior-project
|
65b15ce231da58e7b57977f229049790bfbce7cc
|
a5d9ae2d7708f227dc65a9718e038d561004683d
|
refs/heads/master
| 2021-01-13T16:10:38.557050
| 2013-11-28T07:07:22
| 2013-11-28T07:07:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,052
|
cpp
|
a2d.cpp
|
/* a2d.cpp
*
* Created: 3/10/2013 ☢ 19:24:20 ☢
* Author: Chris
*/
#define F_CPU 8000000UL //define cpu frequency as 8MHz for the _delay_() macro
#include <util/delay.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include "a2d.h"
void ADCon()
{
ADCSRA = (1<<ADEN); //enables the ADC
}
void ADCoff()
{
ADCSRA &= 0x7F; //disable ADC to save power
}
char readval(char channel)
{
char result = 0;
ADMUX = 0x60 | channel; //set ADC channel to read
ADCSRB = 0;
SMCR = (1<<SM0)|(1<<SE); //set the sleep mode to adc noise reduction
ADCSRA |= (1<<ADSC)|(1<<ADIE); //Start conversion prescaler = 1/2
asm volatile("sleep"::); //put the mcu to sleep till woken by adc interrupt
result = ADCH;
return result; //return lower ADC result byte
}
// wrappers to clarify what pin is being read
char readleftvert()
{
return readval(0x00);
}
char readlefthoriz()
{
return readval(0x01);
}
char readrightvert()
{
return readval(0x04);
}
char readrighthoriz()
{
return readval(0x05);
}
ISR(ADC_vect)
{
SMCR = 0;
}
|
c389f143dcf522d72784694f0192fdcf8bf94688
|
7969f7152717cdc1b6d0b8ad5d5bf454b43d8fc9
|
/src/app/webrtc/mediastream.cc
|
fd57f57aa98a05f22ce75143f751757a470b7783
|
[
"BSD-3-Clause",
"BSL-1.0",
"LicenseRef-scancode-public-domain"
] |
permissive
|
dmikushin/libjingle
|
933cdd6721080f1c3e0316b13b9834ede4eedd75
|
b9754327f3e4361cea9d27683a3b5817afb99819
|
refs/heads/master
| 2020-07-30T11:51:13.086498
| 2019-10-06T23:57:21
| 2019-10-06T23:57:21
| 210,223,581
| 0
| 0
|
NOASSERTION
| 2019-09-22T22:40:04
| 2019-09-22T22:40:03
| null |
UTF-8
|
C++
| false
| false
| 5,678
|
cc
|
mediastream.cc
|
/*
* libjingle
* Copyright 2011, Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "app/webrtc/mediastream.h"
#include "base/logging.h"
namespace webrtc {
template <class V>
static typename V::iterator FindTrack(V* vector,
const std::string& track_id) {
typename V::iterator it = vector->begin();
for (; it != vector->end(); ++it) {
if ((*it)->id() == track_id) {
break;
}
}
return it;
};
// TODO(perkj): Remove when there are no callers to audio_tracks()
class AudioMediaStreamTrackList
: public MediaStreamTrackListInterface<AudioTrackInterface> {
public:
explicit AudioMediaStreamTrackList(MediaStreamInterface* stream)
: media_stream_(stream) {
}
virtual size_t count() const OVERRIDE {
return media_stream_->GetAudioTracks().size();
}
virtual AudioTrackInterface* at(size_t index) OVERRIDE {
return media_stream_->GetAudioTracks().at(index);
}
virtual AudioTrackInterface* Find(const std::string& id) OVERRIDE {
return media_stream_->FindAudioTrack(id);
}
protected:
~AudioMediaStreamTrackList() {}
private:
talk_base::scoped_refptr<MediaStreamInterface> media_stream_;
};
// TODO(perkj): Remove when there are no callers to video_tracks().
class VideoMediaStreamTrackList
: public MediaStreamTrackListInterface<VideoTrackInterface> {
public:
explicit VideoMediaStreamTrackList(MediaStreamInterface* stream)
: media_stream_(stream) {
}
virtual size_t count() const OVERRIDE {
return media_stream_->GetVideoTracks().size();
}
virtual VideoTrackInterface* at(size_t index) OVERRIDE {
return media_stream_->GetVideoTracks().at(index);
}
virtual VideoTrackInterface* Find(const std::string& id) OVERRIDE {
return media_stream_->FindVideoTrack(id);
}
protected:
~VideoMediaStreamTrackList() {}
private:
talk_base::scoped_refptr<MediaStreamInterface> media_stream_;
};
talk_base::scoped_refptr<MediaStream> MediaStream::Create(
const std::string& label) {
talk_base::RefCountedObject<MediaStream>* stream =
new talk_base::RefCountedObject<MediaStream>(label);
return stream;
}
MediaStream::MediaStream(const std::string& label)
: label_(label) {
}
bool MediaStream::AddTrack(AudioTrackInterface* track) {
return AddTrack<AudioTrackVector, AudioTrackInterface>(&audio_tracks_, track);
}
bool MediaStream::AddTrack(VideoTrackInterface* track) {
return AddTrack<VideoTrackVector, VideoTrackInterface>(&video_tracks_, track);
}
bool MediaStream::RemoveTrack(AudioTrackInterface* track) {
return RemoveTrack<AudioTrackVector>(&audio_tracks_, track);
}
bool MediaStream::RemoveTrack(VideoTrackInterface* track) {
return RemoveTrack<VideoTrackVector>(&video_tracks_, track);
}
talk_base::scoped_refptr<AudioTrackInterface>
MediaStream::FindAudioTrack(const std::string& track_id) {
AudioTrackVector::iterator it = FindTrack(&audio_tracks_, track_id);
if (it == audio_tracks_.end())
return NULL;
return *it;
}
talk_base::scoped_refptr<VideoTrackInterface>
MediaStream::FindVideoTrack(const std::string& track_id) {
VideoTrackVector::iterator it = FindTrack(&video_tracks_, track_id);
if (it == video_tracks_.end())
return NULL;
return *it;
}
template <typename TrackVector, typename Track>
bool MediaStream::AddTrack(TrackVector* tracks, Track* track) {
typename TrackVector::iterator it = FindTrack(tracks, track->id());
if (it != tracks->end())
return false;
tracks->push_back(track);
FireOnChanged();
return true;
}
template <typename TrackVector>
bool MediaStream::RemoveTrack(TrackVector* tracks,
MediaStreamTrackInterface* track) {
typename TrackVector::iterator it = FindTrack(tracks, track->id());
if (it == tracks->end())
return false;
tracks->erase(it);
FireOnChanged();
return true;
}
AudioTracks* MediaStream::audio_tracks() {
if (!audio_track_list_) {
audio_track_list_ =
new talk_base::RefCountedObject<AudioMediaStreamTrackList>(this);
}
return audio_track_list_;
}
VideoTracks* MediaStream::video_tracks() {
if (!video_track_list_) {
video_track_list_ =
new talk_base::RefCountedObject<VideoMediaStreamTrackList>(this);
}
return video_track_list_;
}
} // namespace webrtc
|
746063c8f2cb60b3b6ee2dad5c6a506cd74d9f03
|
c8a8b1b2739ff50c3565cdc1497e6abf4492b3dd
|
/src/csapex_core/include/csapex/param/parameter_provider.h
|
86fede973aaa79de1dd35d1fb035e81c3c086222
|
[] |
permissive
|
betwo/csapex
|
645eadced88e65d6e78aae4049a2cda5f0d54b4b
|
dd8e24f14cdeef59bedb8f974ebdc0b0c656ab4c
|
refs/heads/master
| 2022-06-13T06:15:10.306698
| 2022-06-01T08:50:51
| 2022-06-01T09:03:05
| 73,413,991
| 0
| 0
|
BSD-3-Clause
| 2020-01-02T14:01:01
| 2016-11-10T19:26:29
|
C++
|
UTF-8
|
C++
| false
| false
| 1,129
|
h
|
parameter_provider.h
|
#ifndef PARAMETER_PROVIDER_H
#define PARAMETER_PROVIDER_H
/// COMPONENT
#include "parameter.h"
#include <csapex_core/csapex_param_export.h>
/// SYSTEM
#include <string>
#include <vector>
#include <map>
namespace csapex
{
namespace param
{
class CSAPEX_PARAM_EXPORT ParameterProvider
{
public:
ParameterProvider();
const Parameter::Ptr operator()(const std::string& name) const;
Parameter& operator[](const std::string& name);
virtual Parameter::Ptr getParameter(const std::string& name) = 0;
virtual const Parameter::Ptr getConstParameter(const std::string& name) const = 0;
};
class StaticParameterProvider : public ParameterProvider
{
typedef std::vector<Parameter::Ptr> Vec;
typedef std::map<std::string, Parameter::Ptr> Map;
public:
StaticParameterProvider(const Vec& params);
StaticParameterProvider(const Map& params);
Parameter::Ptr getParameter(const std::string& name) override;
const Parameter::Ptr getConstParameter(const std::string& name) const override;
private:
Map params_;
};
} // namespace param
} // namespace csapex
#endif // PARAMETER_PROVIDER_H
|
d33c1f9df9aa198ecd4403e3270335ec1edd131e
|
13647ff9ad7b8e30cdf928baf3f6c3019c6817b9
|
/include/topo/MapCollection.cpp
|
9b9230c8a454aed1630711c84b46a8df88691907
|
[] |
no_license
|
StumboEugen/topology_map
|
26875a266482472548228f5e1197976ccec41724
|
fae5e814d726f9829af8d37a4b63588b125a3621
|
refs/heads/master
| 2020-03-16T15:37:53.475318
| 2019-11-15T07:03:02
| 2019-11-15T07:03:02
| 132,752,314
| 1
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,415
|
cpp
|
MapCollection.cpp
|
//
// Created by stumbo on 18-5-15.
//
#include "Topo.h"
/**
* @brief deduce every MapCandidate in \b this to arrive at next NodeInstance.
* the first step of arriving a node is deducing it in every map.
* some conflicts may happen and the map can be ruled out.
* if the edge moving on has never moved on, we consider the next node is a brand new node here
* @param instance the new NodeInstance just arrived
* @param arriveAt the gate just arrived at
* @param dis_x distance x since last move
* @param dis_y distance y since last move
* @param yaw orientation since last move (unused)
*/
void MapCollection::arriveNodeInstance(NodeInstance *instance, uint8_t arriveAt,
double dis_x, double dis_y, double yaw) {
if (maps.empty()) {
auto firstMap = new MapCandidate(instance);
maps.insert(firstMap);
} else {
MapCandidate* currentPathRelatedMap = currentPath.getRelatedMap();
auto iter = maps.begin();
while (iter != maps.end()) {
auto & map = *iter;
if(!map->arriveAtNode(instance, arriveAt, dis_x, dis_y, yaw)) {
if (currentPathRelatedMap == map)
{
currentPath.setInvalid();
}
map->removeUseages();
delete map;
iter = maps.erase(iter);
} else {
iter ++;
}
}
}
currentPath.stepForward();
}
/**
* @brief directly add a new MapCandidate
* this is used to build MapCollection in other situation
* @param newMap the new MapCandidate
*/
void MapCollection::addNewMap(MapCandidate *newMap) {
maps.insert(newMap);
}
/**
* @brief set every MapCandidate 's robot to move throuth a gate.
* @param exit the gate to move through
*/
void MapCollection::everyMapThroughGate(gateId exit) {
for (const auto & map: maps) {
map->setLeaveFrom(exit);
}
}
/**
* @brief convert MapCollection to JSON structure with a limited amount of maps
* the maps with highest confidence would be converted.
* @param mapCount the count of map you would like to save (0 == whole)
* @see MapCollection::toJS()
*/
JSobj MapCollection::toJSWithSortedMaps(size_t mapCount) {
JSobj obj;
if (mapCount == 0 || mapCount > maps.size()) {
mapCount = maps.size();
}
sortByConfidence(mapCount);
for (int i = 0; i < mapCount; i++) {
obj.append(orderedMaps[i]->toJS());
}
return std::move(obj);
}
/**
* @brief convert MapCollection to JSON structure
* @return
* [] array of MapCandidate
* @see MapCandidate::toJS()
*/
JSobj MapCollection::toJS() const {
JSobj obj;
for (const auto & mapIns: maps) {
obj.append(mapIns->toJS());
}
return std::move(obj);
}
/**
* @brief clear all MapCandidate s.
* @see MapCandidate::~MapCandidate()
* @warning the usages in NodeInstance would not be cleared, because the ptr of NodeInstance
* may has been deleted.
*/
void MapCollection::clear() {
for (const auto & map: maps) {
delete map;
}
maps.clear();
orderedMaps.clear();
}
/**
* @brief add TopoNode to MapCollection directly.
* this is used for UI building mode
*/
void MapCollection::addNodeDirectly(TopoNode * node) {
if (maps.size() > 1) {
std::cerr << "[MapCollection::addNodeDirectly]"
"You try to add node directly, but there are more than 1 map candidate"
<< endl;
}
if (maps.empty()) {
maps.insert(new MapCandidate(node->getInsCorrespond()));
}
(*maps.begin())->addNodeDirectly(node);
}
/**
* @brief add TopoEdge to MapCollection directly.
* this is used for UI building mode
*/
void MapCollection::addEdgeDirectly(TopoEdge * edge) {
if (maps.size() > 1) {
std::cerr << "[MapCollection::addNodeDirectly]"
"You try to add node directly, but there are more than 1 map candidate"
<< endl;
}
if (maps.empty()) {
maps.insert(new MapCandidate(edge->getNodeA()->getInsCorrespond()));
}
(*maps.begin())->addEdgeDirectly(edge);
}
/**
* sort the map according to confidence. the sorted map will be stored in
* \link orderedMaps \endlink.
* @param topCount the amount of maps to sort
* @attention the \link orderedMaps \endlink orderedMaps contains all maps and the topCount
* of map are sorted
*/
void MapCollection::sortByConfidence(size_t topCount) {
size_t experience = parent->getNodeCollection().experienceSize();
auto comp = [experience](MapCandidate * a, MapCandidate * b){
return a->getConfidence(experience) > b->getConfidence(experience) ;
};
orderedMaps.clear();
orderedMaps.reserve(maps.size());
orderedMaps.assign(maps.size(), nullptr);
copy(maps.begin(), maps.end(), orderedMaps.begin());
if (topCount == 0 || topCount > maps.size()) {
topCount = maps.size();
}
partial_sort(orderedMaps.begin(), orderedMaps.begin() + topCount, orderedMaps.end(), comp);
}
/**
* @brief purge assigned number of maps according to the confidence.
* @param survivorCount the amount of survivors
*/
void MapCollection::purgeBadMaps(int survivorCount) {
if (survivorCount > maps.size()) {
survivorCount = static_cast<int>(maps.size());
}
sortByConfidence(static_cast<size_t>(survivorCount));
for (int i = survivorCount; i < orderedMaps.size(); i++) {
MapCandidate* map2delete = orderedMaps[i];
map2delete->removeUseages();
maps.erase(map2delete);
if (currentPath.getRelatedMap() == map2delete) {
currentPath.setInvalid();
}
delete map2delete;
}
orderedMaps.erase(orderedMaps.begin() + survivorCount, orderedMaps.end());
}
/**
* @brief constructor of MapCollection.
* @param parent the MapArranger that contains this
*/
MapCollection::MapCollection(MapArranger *parent)
:parent(parent)
{
}
/**
* @brief calculate the sum of confidence
* this is for calculate the normalized posibility
* @return the sum
* @note the sum will be stored in MapCollection::sumOfConfidence
*/
double MapCollection::calSumOfConfidence() {
sumOfConfidence = 0;
for (const auto & map: maps) {
sumOfConfidence += map->getConfidence(parent->getNodeCollection().experienceSize());
}
return sumOfConfidence;
}
|
60648afd93c479acc5aca07518948b121915f20c
|
cd9d6dbd70bc51762d8ac775021b0c42bfbe08bf
|
/Problem 2.cpp
|
e64945f38cdb3ff1b8b8027953dee35e80fc96a3
|
[] |
no_license
|
Jallibad/ProjectEuler
|
b8849cc7dee83532c60ac9106e8dcfd1a4c8374c
|
c6accaeac7f8698b6291ac3e17e7dd66438a3d04
|
refs/heads/master
| 2020-12-25T14:12:50.548322
| 2018-11-06T18:27:46
| 2018-11-06T18:27:46
| 45,752,225
| 0
| 0
| null | 2016-07-10T17:57:10
| 2015-11-07T19:59:21
|
Haskell
|
UTF-8
|
C++
| false
| false
| 280
|
cpp
|
Problem 2.cpp
|
#include <iostream>
int main()
{
int answer = 0;
int current = 2;
int next = 3;
while (current <= 4000000) //Upper bound of 4,000,000
{
answer += current;
int temp = next;
next += current;
current = temp+next;
next += current;
}
std::cout << answer;
return 0;
}
|
3faf401951961514ca9b16549097ea81e68694eb
|
c001e4fb7cb7ade5b087c929b0246a0c58f6285c
|
/problems/building-roads/building-roads/main.cpp
|
ccafc749b362d888cc50eb6ba9c1b665d2da9d77
|
[] |
no_license
|
sabiusa/cses
|
ce057b959362aaf29db8a2de8a5f32926ea4d853
|
7a14b8bf4fecd41c7f15e3953b757c371d3c48b3
|
refs/heads/main
| 2023-07-14T05:11:59.811401
| 2021-07-30T11:55:41
| 2021-07-30T11:55:41
| 346,602,755
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 923
|
cpp
|
main.cpp
|
//
// main.cpp
// building-roads
//
// Created by Saba Khutsishvili on 4/13/21.
//
#include <iostream>
#include <vector>
using namespace std;
#define ll long long
#define ull unsigned long long
const ll N = 1e5+1;
vector<vector<ll>> adj(N);
vector<ll> vis(N, 0);
void dfs(ll i) {
vis[i] = 1;
for (ll c : adj[i]) {
if (vis[c] == 0) {
dfs(c);
}
}
}
int main() {
ll n, m, a, b;
cin >> n >> m;
while (m--) {
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
vector<ll> ans;
for (ll i = 1; i <= n; ++i) {
if (vis[i] == 0) {
dfs(i);
if (i > 1) {
ans.push_back(i);
}
}
}
cout << ans.size() << "\n";
for (ull i = 0; i < ans.size(); ++i) {
cout << 1 << " " << ans[i] << "\n";
}
cout << "\n";
return 0;
}
|
8d78ec77b0a5b42979d157d921ae35d14b9ce81c
|
d4fc237d44bc9da1d1e3fce5fffd5195380615d8
|
/lib/Reader/include/Vector.h
|
448a18f9a79aabdaa2140b937827bb1f986cfdc5
|
[] |
no_license
|
bensonbits/vHelix
|
0aa2c10fd6ead8fd09275ffa0ad50959ba1d6800
|
c05a06a432438bb9a9f1f90407385f8334d6febc
|
refs/heads/master
| 2020-08-31T16:34:19.473879
| 2020-06-03T13:21:48
| 2020-06-03T13:21:48
| 218,731,218
| 0
| 0
| null | 2019-10-31T09:37:30
| 2019-10-31T09:37:30
| null |
UTF-8
|
C++
| false
| false
| 1,043
|
h
|
Vector.h
|
/*
* Vector.h
*
* Created on: 9 maj 2012
* Author: johan
*/
#ifndef _VHELIX_MA_PARSER_VECTOR_H_
#define _VHELIX_MA_PARSER_VECTOR_H_
#define _USE_MATH_DEFINES
#include <cmath>
#include <ostream>
namespace Helix {
/*
* A simple 3 component vector class
*/
template<typename T>
class VectorT {
public:
T x, y, z;
inline VectorT(T _x = T(0), T _y = T(0), T _z = T(0)) : x(_x), y(_y), z(_z) {
}
inline VectorT(const VectorT<T> & copy) : x(copy.x), y(copy.y), z(copy.z) {
}
inline VectorT<T> & operator=(const VectorT<T> & copy) {
x = copy.x;
y = copy.y;
z = copy.z;
return *this;
}
inline T dot(const VectorT & v) {
return x * v.x + y * v.y + z * v.z;
}
inline T length() const {
return sqrt(dot(*this));
}
};
typedef VectorT<double> Vector;
}
template<typename T>
std::ostream & operator<< (std::ostream & stream, const Helix::VectorT<T> & vector) {
stream << vector.x << ", " << vector.y << ", " << vector.z;
return stream;
}
#endif /* _VHELIX_MA_PARSER_VECTOR_H_ */
|
2fd49a6166f5b7a67accd154f614532d5e2f5d41
|
ace05d94c93fd79f75289f79e29f0f2c6c7908ab
|
/DavisReader.ino
|
f7941cf923628d76bec3d4a0700fad9f7a228af4
|
[] |
no_license
|
X-Terminator/DavisReader
|
266dc6e2bc24495dd7e8ca004d9eb2a6e3289440
|
dffe7dbc1841e4c4020746e23f1216d487c5125f
|
refs/heads/master
| 2020-04-14T06:55:45.023771
| 2018-12-31T21:47:44
| 2018-12-31T21:47:44
| 163,699,093
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 38,796
|
ino
|
DavisReader.ino
|
/*** INCLUDES ***/
#include <SoftwareSerial.h>
#include "WiFi_MQTT.h"
/*** DEFINES***/
#define DAVIS_WRITE(a) Serial.print(a)
#define DAVIS_DATA_AVAILABLE(a) Serial.available()
#define MSG_DBG(...) g_DebugSerial.printf(__VA_ARGS__);g_DebugSerial.println();
#define MSG_DBG_NO_LINE(...) g_DebugSerial.printf(__VA_ARGS__);
//#define DEBUG_LOW_LEVEL
#define ACK 0x06
#define NACK 0x21
#define NACK2 0x15
#define CANCEL 0x18
#define ESC 0x1B
#define RESP_OK_STR "\n\rOK\n\r"
#define RESP_DONE_STR "DONE\n\r"
#define DAVIS_WAKEUP_TIMEOUT_MS 1200
#define DAVIS_COMMAND_TIMEOUT_MS 500
#define DAVIS_BYTE_TIMEOUT_MS 50
#define DAVIS_LOOP_COMMAND_TIMEOUT_MS 3000
// Forecast Icons
#define FORECAST_ICON_RAIN 0x01
#define FORECAST_ICON_CLOUD 0x02
#define FORECAST_ICON_PART_CLOUD 0x04
#define FORECAST_ICON_SUN 0x08
#define FORECAST_ICON_SNOW 0x10
// Data conversion macros
#define DAVIS_CONVERT_TEMPERATURE_10TH(raw) (((((float)raw / 10.0f) - 32.0f) * 5.0f) / 9.0f)
#define DAVIS_CONVERT_EXTRA_TEMPERATURE(raw) (((((float)raw - 90.0f) - 32.0f) * 5.0f) / 9.0f)
#define DAVIS_CONVERT_WINDSPEED(mph) ((float)mph * 1.609344f)
#define DAVIS_CONVERT_RAINRATE(clicks) ((float)clicks * 0.2f)
#define DAVIS_CONVERT_BATT_VOLTAGE(raw) ((((float)raw * 300.0f)/512.0f)/100.0)
#define DAVIS_CONVERT_BAR_PRESSURE(raw) ((((float)raw * 33.86389f) / 1000.0))
#define DAVIS_CONVERT_DEW_POINT(raw) ((((float)raw - 32.0f) * 5.0f) / 9.0f)
#define DATE_TO_DATESTAMP(d,m,y) (uint16_t)((uint16_t)d + m*32 + (y-2000)*512)
#define TIME_TO_TIMESTAMP(h,m) (uint16_t)((uint16_t)h*100 + m)
#define DATESTAMP_DAY(ds) (uint8_t)(ds & 0x1F)
#define DATESTAMP_MONTH(ds) (uint8_t)((ds >> 5) & 0x0F)
#define DATESTAMP_YEAR(ds) (uint16_t)(((ds >> 9) & 0x7F) + 2000)
#define TIMESTAMP_HOUR(ts) (uint8_t)(ts/100)
#define TIMESTAMP_MIN(ts) (uint8_t)(ts - (100*(ts/100)))
#define DUMP_BYTES(buf, cnt, dbg_type) \
if (dbg_type & DEBUG_HEX) { \
for (int i = 0; i < cnt; i++) { \
MSG_DBG_NO_LINE("%02X ", buf[i]); \
} \
} \
if (dbg_type & DEBUG_ASCII) { \
if (dbg_type & DEBUG_HEX) { \
MSG_DBG_NO_LINE("- "); \
} \
for (int i = 0; i < cnt; i++) { \
if ((buf[i] != '\n') && (buf[i] != '\r')) { \
MSG_DBG_NO_LINE("%c", (char)buf[i]); \
} \
} \
}
#define PRINT_RESPONSE_TYPE(r) \
(r == RESP_INVALID ? "INVALID" : \
(r == RESP_OK ? "OK" : \
(r == RESP_ACK ? "ACK" : \
(r == RESP_NACK ? "NACK" : \
(r == RESP_TIMEOUT ? "TIMEOUT" : "?")))))
#define IS_GOOD_RESPONSE(r) ((r == RESP_OK) || (r == RESP_ACK))
/*** TYPE DEFINITIONS ***/
typedef enum {
DEBUG_NONE = 0,
DEBUG_HEX = 1,
DEBUG_ASCII = 2,
DEBUG_HEXASCII = 3
} DebugType;
typedef enum {
RESP_INVALID = 0,
RESP_OK,
RESP_ACK,
RESP_NACK,
RESP_TIMEOUT
} DavisCommandResponse;
#pragma pack(push)
#pragma pack(1)
typedef struct
{
uint8_t Seconds;
uint8_t Minutes;
uint8_t Hours;
uint8_t Day;
uint8_t Month;
uint8_t Year;
uint16_t CRC;
} TimePacket __attribute__((packed));
typedef struct
{
uint8_t Identifier[3]; // 0
uint8_t BarTrend; // 3
uint8_t PacketType; // 4
uint16_t NextRecord; // 5
int16_t Barometer; // 7
int16_t InTemperature; // 9
uint8_t InHumidity; // 11
int16_t OutTemperature; // 12
uint8_t WindSpeed; // 14
uint8_t AvgWindSpeed; // 15
uint16_t WindDirection; // 16
uint8_t ExtraTemps[7]; // 18
uint8_t SoilTemps[4]; // 25
uint8_t LeafTemps[4]; // 29
uint8_t OutHumidity; // 33
uint8_t ExtraHumidity[7];// 34
uint16_t RainRate; // 41
uint8_t UVindex; // 42
uint16_t SolarRadiation; // 44
uint16_t StormRain; // 46
uint16_t StormDate; // 48
uint16_t RainDay; // 50
uint16_t RainMonth; // 52
uint16_t RainYear; // 54
uint16_t ET_Day; // 56
uint16_t ET_Month; // 58
uint16_t ET_Year; // 60
uint8_t SoilMoisture[4];// 62
uint8_t LeafWetness[4]; // 66
uint8_t Alarms_Inside; // 70
uint8_t Alarms_Rain; // 71
uint8_t Alarms_Outside[2]; // 72
uint8_t Alarms_ExtraTempHum[8]; // 74
uint8_t Alarms_SoilLeaf[4]; // 82
uint8_t Battery_Transmitter; // 86
uint16_t Battery_Console; // 87
uint8_t ForecastIcons; // 89
uint8_t ForecastRule; // 90
uint16_t TimeSunrise; // 91
uint16_t TimeSunset; // 93
uint8_t LF; // 95
uint8_t CR; // 96
uint16_t CRC; // 97
} LoopPacket __attribute__((packed));
typedef struct
{
uint8_t Identifier[3]; // 0
uint8_t BarTrend; // 3
uint8_t PacketType; // 4
uint16_t Unused; // 5
int16_t Barometer; // 7
int16_t InTemperature; // 9
uint8_t InHumidity; // 11
int16_t OutTemperature; // 12
uint8_t WindSpeed; // 14
uint8_t Unused2; // 15
uint16_t WindDirection; // 16
uint16_t AvgWindSpeed10; // 18
uint16_t AvgWindSpeed2; // 20
uint16_t AvgWindGust; // 22
uint16_t WindGustDirection; // 24
uint8_t Unused3[4]; // 26
int16_t DewPoint; // 30
uint8_t Unused4; // 32
uint8_t OutHumidity; // 33
uint8_t Unused5; // 34
int16_t HeatIndex; // 35
int16_t WindChill; // 37
int16_t THSWIndex; // 39
uint16_t RainRate; // 41
uint8_t UVindex; // 42
uint16_t SolarRadiation; // 44
uint16_t StormRain; // 46
uint16_t StormDate; // 48
uint16_t RainDay; // 50
uint16_t Rain15Min; // 52
uint16_t RainHour; // 54
uint16_t ET_Day; // 56
uint16_t Rain24Hrs; // 58
uint8_t BarReduction; // 60
uint16_t BarOffset; // 61
uint16_t BarCalibNr; // 63
uint16_t BarRaw; // 65
uint16_t BarAbs; // 67
uint16_t Altimeter; // 69
uint8_t Unused6[2]; // 71
uint8_t Next10minWindGPtr; // 73
uint8_t Next15minWindGPtr; // 74
uint8_t NextHourlyWindGPtr; // 75
uint8_t NextDailyWindGPtr; // 76
uint8_t NextMinuteRainGPtr; // 77
uint8_t NextStormRainGPtr; // 78
uint8_t MinuteIndex; // 79
uint8_t NextMonthlyRain; // 80
uint8_t NextYearlyRain; // 81
uint8_t NextSeasonalRain; // 82
uint8_t Unused7[2*6]; // 83
uint8_t LF; // 95
uint8_t CR; // 96
uint16_t CRC; // 97
} Loop2Packet __attribute__((packed));
typedef struct
{
uint16_t DateStamp; // 0
uint16_t TimeStamp; // 2
int16_t OutTemperature; // 4
int16_t OutTempHigh; // 6
int16_t OutTempLow; // 8
uint16_t RainFall; // 10
uint16_t HighRainRate; // 12
uint16_t Barometer; // 14
uint16_t SolarRadiation; // 16
uint16_t WindSamples; // 18
int16_t InTemperature; // 20
uint8_t InHumidity; // 22
uint8_t OutHumidity; // 23
uint8_t AvgWindSpeed; // 24
uint8_t HighWindSpeed; // 25
uint8_t HighWindDirection; // 26
uint8_t PrevWindDirection; // 27
uint8_t AvgUVIndex; // 28
uint8_t ET; // 29
uint16_t HighSolarRadiation; // 30
uint8_t HighUVIndex; // 32
uint8_t ForecastRule; // 33
uint8_t LeafTemp[2]; // 34
uint8_t LeafWetness[2]; // 36
uint8_t SoilTemp[4]; // 38
uint8_t RecordType; // 42
uint8_t ExtraHum[2]; // 43
uint8_t ExtraTemp[3]; // 45
uint8_t SoilMoisture[4];// 48
} ArchiveRecordRevB __attribute__((packed));
typedef struct
{
uint8_t SeqNr; // 0
ArchiveRecordRevB Record[5]; // 1
uint8_t Unused[4]; // 261
uint16_t CRC; // 265
} ArchivePage __attribute__((packed));
#pragma pack(pop)
/*** GLOBAL VARIABLES ***/
SoftwareSerial g_DebugSerial(3, 1); // RX, TX
Settings g_Settings = {
.UpdateIntervalSec = 60
};
StationData g_StationData;
char g_CustomCommand[CMD_MAX_SIZE];
char g_CustomCommandResponse[CMD_RESP_MAX_SIZE];
bool g_CustomCommandPending = false;
bool g_TriggerArchiveDownload = false;
bool g_TriggerArchiveDownloadWithDateTime = false;
bool g_GetTimeCommand;
bool g_SetTimeCommand;
DateTimeStruct g_DateTimeStruct;
/*** PRIVATE VARIABLES ***/
static unsigned long s_PrevTimeMs;
static bool s_InitOk = false;
static struct {
uint8_t Value;
const char *ForeCastString;
} s_ForeCasts[] = {
{0x08 ,"Sun Mostly Clear"},
{0x06 ,"Partly Cloudy"},
{0x02 ,"Mostly Cloudy"},
{0x03 ,"Mostly Cloudy, Rain within 12 hours"},
{0x12 ,"Mostly Cloudy, Snow within 12 hours"},
{0x13 ,"Mostly Cloudy, Rain or Snow within 12 hours"},
{0x07 ,"Partly Cloudy, Rain within 12 hours"},
{0x16 ,"Partly Cloudy, Snow within 12 hours"},
{0x17 ,"Partly Cloudy, Rain or Snow within 12 hours"}
};
// CRC table
static const uint16_t s_CRC_TABLE [] = {
0x0, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
0x1231, 0x210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,
0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,
0x2462, 0x3443, 0x420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485,
0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,
0x3653, 0x2672, 0x1611, 0x630, 0x76d7, 0x66f6, 0x5695, 0x46b4,
0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,
0x48c4, 0x58e5, 0x6886, 0x78a7, 0x840, 0x1861, 0x2802, 0x3823,
0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,
0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0xa50, 0x3a33, 0x2a12,
0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,
0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0xc60, 0x1c41,
0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,
0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0xe70,
0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,
0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f,
0x1080, 0xa1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,
0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e,
0x2b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,
0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,
0x34e2, 0x24c3, 0x14a0, 0x481, 0x7466, 0x6447, 0x5424, 0x4405,
0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c,
0x26d3, 0x36f2, 0x691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,
0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab,
0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x8e1, 0x3882, 0x28a3,
0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,
0x4a75, 0x5a54, 0x6a37, 0x7a16, 0xaf1, 0x1ad0, 0x2ab3, 0x3a92,
0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9,
0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0xcc1,
0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8,
0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0xed1, 0x1ef0,
};
static uint16_t s_ArchivePageNr = 0;
static uint16_t s_ArchivePageCount = 0;
static uint16_t s_ArchiveRecordStart = 0;
static uint8_t s_ArchivePageBuf[sizeof(ArchivePage)];
/*** PRIVATE FUNCTIONS ***/
uint16_t CalcCrc(uint8_t * inDataPtr, uint16_t inSize)
{
uint16_t lvCRC = 0;
for (int i = 0; i < inSize; i++)
{
lvCRC = s_CRC_TABLE[(lvCRC >> 8) ^ inDataPtr[i]] ^ (lvCRC << 8);
}
return lvCRC;
}
static bool Davis_Init(void);
static bool Davis_SetTime(uint16_t inYear, uint8_t inMonth, uint8_t inDay, uint8_t inHours, uint8_t inMinutes, uint8_t inSeconds);
static bool Davis_GetTime(uint16_t *outYear=0, uint8_t *outMonth=0, uint8_t *outDay=0, uint8_t *outHours=0, uint8_t *outMinutes=0, uint8_t *outSeconds=0);
static bool Davis_SetTime(DateTimeStruct *inDateTimeStruct);
static bool Davis_GetTime(DateTimeStruct *outDateTimeStruct);
DavisCommandResponse Davis_ReadCommandResponse(uint16_t inTimeoutMs, DebugType inDebug = DEBUG_HEX);
static void Davis_FlushRx(DebugType inDebug = DEBUG_HEX);
static void Davis_Write(const uint8_t *inBuf, uint16_t inSize, DebugType inDebug = DEBUG_HEX);
static void Davis_Write(const char *inBuf, DebugType inDebug = DEBUG_HEXASCII);
static void Davis_Write(uint8_t inByte, DebugType inDebug = DEBUG_HEXASCII);
static uint16_t Davis_Read(uint8_t *outBuf, uint16_t inBufSize, bool inStopOnNewLine, uint16_t inByteTimeoutMs = DAVIS_BYTE_TIMEOUT_MS, DebugType inDebug = DEBUG_HEX);
static bool Davis_ReadByte(uint8_t *outByte, DebugType inDebug = DEBUG_HEX);
static bool Davis_SendCommand(const char *inCommand, char *outResponse, uint16_t inMaxResponseLength, bool inBinaryResponse=false, uint16_t inTimeoutMs = DAVIS_COMMAND_TIMEOUT_MS);
static uint16_t Davis_SendRawCommand(const char *inCommand, char *outResponse, uint16_t inMaxResponseLength, uint16_t inByteTimeoutMs = DAVIS_BYTE_TIMEOUT_MS);
static bool Davis_WakeUp(void);
static bool Davis_ConvertLoopData(LoopPacket* inLoopPacket, StationData * outStationData);
static bool Davis_ConvertLoop2Data(Loop2Packet* inLoopPacket, StationData * outStationData);
static bool Davis_StartReadArchiveData(uint16_t *outPageCount, uint16_t *outFirstRecord, uint16_t inYear = 2000, uint8_t inMonth = 1, uint8_t inDay = 1, uint8_t inHour = 0, uint8_t inMinute = 0);
static bool Davis_StartReadArchiveData(uint16_t *outPageCount, uint16_t *outFirstRecord, uint16_t inDateStamp, uint16_t inTimeStamp);
static void Davis_StoptReadArchiveData();
static bool Davis_ContinueReadArchiveData(ArchivePage **outArchivePage, uint16_t *outPageNr, uint8_t inRetries);
void setup()
{
// put your setup code here, to run once:
Serial.begin(19200);
Serial.swap();
pinMode(1, OUTPUT);
// D1 is the VCC for the RS232 transceiver
pinMode(D1, OUTPUT);
digitalWrite(D1, HIGH); // turn the RS232 transceiver on
delay(1000);
// set the data rate for the SoftwareSerial port
g_DebugSerial.begin(19200);
s_PrevTimeMs = millis();
#ifdef WIFI_ENABLED
WiFi_MQTT_Init();
#endif //WIFI_ENABLED
// MSG_DBG("sizeof(LoopPacket): %d", sizeof(LoopPacket));
// MSG_DBG("sizeof(Loop2Packet): %d", sizeof(Loop2Packet));
// MSG_DBG("sizeof(s_CRC_TABLE): %d", sizeof(s_CRC_TABLE));
// MSG_DBG("sizeof(ArchiveRecordRevB): %d", sizeof(ArchiveRecordRevB));
// MSG_DBG("sizeof(ArchivePage): %d", sizeof(ArchivePage));
}
typedef enum {
STATE_INIT = 0,
STATE_IDLE,
STATE_GET_ARCHIVE_DATA,
} State;
static State s_State = STATE_INIT;
void loop()
{
static unsigned long s_LastUpdateTime = 0;
static bool s_Once = false;
#ifdef WIFI_ENABLED
WiFi_MQTT_Tick();
#endif //WIFI_ENABLED
switch (s_State)
{
case STATE_INIT:
if (Davis_Init())
{
MSG_DBG("Davis Init OK!");
s_InitOk = true;
MQTT_SendConfig();
s_State = STATE_IDLE;
}
else
{
delay(2000);
}
break;
case STATE_IDLE:
if (g_CustomCommandPending)
{
if (Davis_WakeUp())
{
MSG_DBG("Sending custom command: %s", g_CustomCommand);
uint16_t lvResponseSize = Davis_SendRawCommand(g_CustomCommand, g_CustomCommandResponse, CMD_RESP_MAX_SIZE);
MSG_DBG("Response Size: %d bytes", lvResponseSize);
MQTT_SendRaw(MQTT_TOPIC_RESP_RAW, (uint8_t*)g_CustomCommandResponse, lvResponseSize);
g_CustomCommandPending = false;
}
}
if ((s_LastUpdateTime == 0) || ((millis() - s_LastUpdateTime) >= (unsigned long)g_Settings.UpdateIntervalSec * 1000))
{
s_LastUpdateTime = millis();
if (Davis_WakeUp())
{
bool lvSendUpdate = false;
char lvLoopResponse[sizeof(LoopPacket)];
uint16_t lvCRC;
if (Davis_SendCommand("LOOP 1", lvLoopResponse, sizeof(LoopPacket), true, DAVIS_LOOP_COMMAND_TIMEOUT_MS))
{
lvCRC = CalcCrc((uint8_t*)lvLoopResponse, sizeof(LoopPacket));
if (lvCRC == 0)
{
LoopPacket* lvLoopPacket = (LoopPacket*) lvLoopResponse;
if (Davis_ConvertLoopData(lvLoopPacket, &g_StationData))
{
MQTT_SendRaw(MQTT_TOPIC_RAW_LOOP, (uint8_t*)lvLoopPacket, sizeof(LoopPacket));
delay(500);
lvSendUpdate = true;
}
else
{
MSG_DBG("Error converting LOOP data!");
}
//MSG_DBG("NextRecord: %d", lvLoopPacket->NextRecord);
MSG_DBG("InTemperature: %.2f C", ((((float)lvLoopPacket->InTemperature / 10.0f) - 32.0f) * 5.0f) / 9.0f);
MSG_DBG("InHumidity: %d %%", lvLoopPacket->InHumidity);
}
else
{
MSG_DBG("Error: CRC failure in LOOP packet! (CRC: 0x%04X)", lvCRC);
}
}
if (Davis_WakeUp())
{
if (Davis_SendCommand("LPS 2 1", lvLoopResponse, sizeof(Loop2Packet), true, DAVIS_LOOP_COMMAND_TIMEOUT_MS))
{
lvCRC = CalcCrc((uint8_t*)lvLoopResponse, sizeof(Loop2Packet));
if (lvCRC == 0)
{
Loop2Packet* lvLoop2Packet = (Loop2Packet*) lvLoopResponse;
if (Davis_ConvertLoop2Data(lvLoop2Packet, &g_StationData))
{
MQTT_SendRaw(MQTT_TOPIC_RAW_LOOP2, (uint8_t*)lvLoop2Packet, sizeof(Loop2Packet));
delay(500);
lvSendUpdate = true;
}
else
{
MSG_DBG("Error converting LOOP2 data!");
}
}
else
{
MSG_DBG("Error: CRC failure in LOOP2 packet! (CRC: 0x%04X)", lvCRC);
}
}
}
delay(1000);
if (lvSendUpdate)
{
MQTT_SendState();
}
}
else
{
MSG_DBG("Could not wake-up Davis");
}
}
if (g_TriggerArchiveDownload || g_TriggerArchiveDownloadWithDateTime)
{
if (Davis_WakeUp())
{
s_ArchivePageNr = 0;
s_ArchivePageCount = 0;
s_ArchiveRecordStart = 0;
const char *lvResponse;
if (!g_TriggerArchiveDownloadWithDateTime)
{
MSG_DBG("Starting download of archived data.");
if (Davis_StartReadArchiveData(&s_ArchivePageCount, &s_ArchiveRecordStart))
{
s_State = STATE_GET_ARCHIVE_DATA;
lvResponse = "GetArchive: OK";
}
else
{
MSG_DBG("Error. Could not start archive data retrieval!");
lvResponse = "GetArchive: ERROR";
}
}
else
{
MSG_DBG("Starting download of archived data. Start time: %04d-%02d-%02d %02d:%02d", g_DateTimeStruct.Year, g_DateTimeStruct.Month, g_DateTimeStruct.Day, g_DateTimeStruct.Hours, g_DateTimeStruct.Minutes);
if (Davis_StartReadArchiveData(&s_ArchivePageCount, &s_ArchiveRecordStart, g_DateTimeStruct.Year, g_DateTimeStruct.Month, g_DateTimeStruct.Day, g_DateTimeStruct.Hours, g_DateTimeStruct.Minutes))
{
s_State = STATE_GET_ARCHIVE_DATA;
lvResponse = "GetArchive: OK";
}
else
{
MSG_DBG("Error. Could not start archive data retrieval!");
lvResponse = "GetArchive: ERROR";
}
}
MQTT_SendRaw(MQTT_TOPIC_RESP, (uint8_t*)lvResponse, strlen(lvResponse));
g_TriggerArchiveDownload = false;
g_TriggerArchiveDownloadWithDateTime = false;
}
}
if (g_GetTimeCommand && Davis_WakeUp())
{
char lvResponse[32];
if (Davis_GetTime(&g_DateTimeStruct))
{
snprintf(lvResponse, sizeof(lvResponse), PSTR("GetTime: %04d-%02d-%02d %02d:%02d:%02d"), g_DateTimeStruct.Year, g_DateTimeStruct.Month, g_DateTimeStruct.Day, g_DateTimeStruct.Hours, g_DateTimeStruct.Minutes, g_DateTimeStruct.Seconds);
}
else
{
snprintf(lvResponse, sizeof(lvResponse), PSTR("GetTime: ERROR"));
}
MQTT_SendRaw(MQTT_TOPIC_RESP, (uint8_t*)lvResponse, strlen(lvResponse));
g_GetTimeCommand = false;
}
if (g_SetTimeCommand && Davis_WakeUp())
{
char lvResponse[32];
if (Davis_SetTime(&g_DateTimeStruct))
{
snprintf(lvResponse, sizeof(lvResponse), PSTR("SetTime: OK"));
}
else
{
snprintf(lvResponse, sizeof(lvResponse), PSTR("SetTime: ERROR"));
}
MQTT_SendRaw(MQTT_TOPIC_RESP, (uint8_t*)lvResponse, strlen(lvResponse));
g_SetTimeCommand = false;
}
break;
case STATE_GET_ARCHIVE_DATA:
ArchivePage *lvArchivePage;
uint16_t lvPageNr;
if (Davis_ContinueReadArchiveData(&lvArchivePage, &lvPageNr, 3))
{
MSG_DBG("Page %d. SeqNr: %03d", lvPageNr, lvArchivePage->SeqNr);
for (int j = 0; j < 5; j++)
{
ArchiveRecordRevB *lvArchiveRecord = &lvArchivePage->Record[j];
uint16_t lvDateStamp = lvArchiveRecord->DateStamp;
uint16_t lvTimeStamp = lvArchiveRecord->TimeStamp;
if ((lvPageNr == 0) && (j < s_ArchiveRecordStart))
{
MSG_DBG(" - [%d] Record Date: %02d-%02d-%04d %02d:%02d (Skipped)", j, DATESTAMP_DAY(lvDateStamp), DATESTAMP_MONTH(lvDateStamp), DATESTAMP_YEAR(lvDateStamp), TIMESTAMP_HOUR(lvTimeStamp), TIMESTAMP_MIN(lvTimeStamp));
}
else if ((lvDateStamp == 0xFFFF) || (lvDateStamp == 0xFFFF))
{
MSG_DBG(" - [%d] Record Date: %02d-%02d-%04d %02d:%02d (Skipped)", j, DATESTAMP_DAY(lvDateStamp), DATESTAMP_MONTH(lvDateStamp), DATESTAMP_YEAR(lvDateStamp), TIMESTAMP_HOUR(lvTimeStamp), TIMESTAMP_MIN(lvTimeStamp));
}
else
{
MSG_DBG(" - [%d] Record Date: %02d-%02d-%04d %02d:%02d", j, DATESTAMP_DAY(lvDateStamp), DATESTAMP_MONTH(lvDateStamp), DATESTAMP_YEAR(lvDateStamp), TIMESTAMP_HOUR(lvTimeStamp), TIMESTAMP_MIN(lvTimeStamp));
char lvTopic[128];
snprintf(lvTopic, sizeof(lvTopic), PSTR("%s/%04d%02d%02d_%02d%02d"), MQTT_TOPIC_ARCHIVE, DATESTAMP_YEAR(lvDateStamp), DATESTAMP_MONTH(lvDateStamp), DATESTAMP_DAY(lvDateStamp), TIMESTAMP_HOUR(lvTimeStamp), TIMESTAMP_MIN(lvTimeStamp));
MQTT_SendRaw(lvTopic, (uint8_t*)lvArchiveRecord, sizeof(ArchiveRecordRevB));
}
}
}
else
{
Davis_StoptReadArchiveData();
s_State = STATE_IDLE;
}
break;
}
}
static bool Davis_Init(void)
{
if (Davis_WakeUp())
{
char lvTemp[64];
if (Davis_SendCommand("NVER", g_StationData.FWVersion, sizeof(g_StationData.FWVersion)))
{
MSG_DBG("Davis FWVersion: %s", g_StationData.FWVersion);
}
if (Davis_SendCommand("VER", g_StationData.FWDate, sizeof(g_StationData.FWDate)))
{
MSG_DBG("Davis FWDate: %s", g_StationData.FWDate);
}
if (Davis_SendCommand("RECEIVERS", (char*)&g_StationData.Receivers, sizeof(g_StationData.Receivers)))
{
MSG_DBG("Davis RECEIVERS: 0x%02X", g_StationData.Receivers);
}
if (Davis_SendCommand("RXCHECK", lvTemp, sizeof(lvTemp)))
{
MSG_DBG("Davis RXCHECK: %s", lvTemp);
}
Davis_GetTime();
return true;
}
return false;
}
static bool Davis_GetTime(uint16_t *outYear, uint8_t *outMonth, uint8_t *outDay, uint8_t *outHours, uint8_t *outMinutes, uint8_t *outSeconds)
{
uint8_t lvPacket[8];
if (Davis_SendCommand("GETTIME", (char*)lvPacket, sizeof(lvPacket), true))
{
TimePacket *lvTimePacket = (TimePacket *)lvPacket;
MSG_DBG("Current Time: %02d-%02d-%04d %02d:%02d:%02d", lvTimePacket->Day, lvTimePacket->Month, (uint16_t)1900+lvTimePacket->Year, lvTimePacket->Hours, lvTimePacket->Minutes, lvTimePacket->Seconds);
if (outYear)
{
*outYear = (uint16_t)1900+lvTimePacket->Year;
}
if (outMonth)
{
*outMonth = lvTimePacket->Month;
}
if (outDay)
{
*outDay = lvTimePacket->Day;
}
if (outHours)
{
*outHours = lvTimePacket->Hours;
}
if (outMinutes)
{
*outMinutes = lvTimePacket->Minutes;
}
if (outSeconds)
{
*outSeconds = lvTimePacket->Seconds;
}
return true;
}
return false;
}
static bool Davis_SetTime(uint16_t inYear, uint8_t inMonth, uint8_t inDay, uint8_t inHours, uint8_t inMinutes, uint8_t inSeconds)
{
uint8_t lvPacket[8];
TimePacket *lvTimePacket = (TimePacket*)lvPacket;
lvTimePacket->Seconds = inSeconds;
lvTimePacket->Minutes = inMinutes;
lvTimePacket->Hours = inHours;
lvTimePacket->Day = inDay;
lvTimePacket->Month = inMonth;
lvTimePacket->Year = (inYear > 1900 ? (inYear - 1900) : inYear);
uint16_t lvCRC = CalcCrc((uint8_t*)lvPacket, 6);
lvPacket[6] = (uint8_t)(lvCRC >> 8);
lvPacket[7] = (uint8_t)(lvCRC & 0xFF);
if (Davis_SendCommand("SETTIME", 0, 0))
{
MSG_DBG("Setting date+time to: %02d-%02d-%04d %02d:%02d:%02d", lvTimePacket->Day, lvTimePacket->Month, (uint16_t)1900+lvTimePacket->Year, lvTimePacket->Hours, lvTimePacket->Minutes, lvTimePacket->Seconds);
Davis_Write(lvPacket, sizeof(lvPacket));
DavisCommandResponse lvResponse = Davis_ReadCommandResponse(5000);
if (lvResponse != RESP_ACK)
{
MSG_DBG("Error: Invalid response: %s", PRINT_RESPONSE_TYPE(lvResponse));
return false;
}
else
{
MSG_DBG("Time set OK!");
return true;
}
}
return false;
}
static bool Davis_SetTime(DateTimeStruct *inDateTimeStruct)
{
return Davis_SetTime(inDateTimeStruct->Year, inDateTimeStruct->Month, inDateTimeStruct->Day, inDateTimeStruct->Hours, inDateTimeStruct->Minutes, inDateTimeStruct->Seconds);
}
static bool Davis_GetTime(DateTimeStruct *outDateTimeStruct)
{
return Davis_GetTime(&outDateTimeStruct->Year, &outDateTimeStruct->Month, &outDateTimeStruct->Day, &outDateTimeStruct->Hours, &outDateTimeStruct->Minutes, &outDateTimeStruct->Seconds);
}
static void Davis_FlushRx(DebugType inDebug)
{
uint16_t lvBytesFlushed = 0;
uint8_t lvByte;
// flush RX buffer
while(Serial.available())
{
lvByte = Serial.read();
#ifdef DEBUG_LOW_LEVEL
if (inDebug)
{
if (lvBytesFlushed == 0)
{
MSG_DBG_NO_LINE("FL: ");
}
if (inDebug & DEBUG_HEX)
{
MSG_DBG_NO_LINE("%02X ", lvByte);
}
}
#endif //DEBUG_LOW_LEVEL
lvBytesFlushed++;
}
#ifdef DEBUG_LOW_LEVEL
if (inDebug && (lvBytesFlushed > 0))
{
MSG_DBG("");
}
#endif //DEBUG_LOW_LEVEL
}
static void Davis_Write(const uint8_t *inBuf, uint16_t inSize, DebugType inDebug)
{
Serial.write(inBuf, inSize);
#ifdef DEBUG_LOW_LEVEL
if (inDebug)
{
MSG_DBG_NO_LINE("TX: ");
DUMP_BYTES(inBuf, inSize, inDebug);
MSG_DBG("");
}
#endif //DEBUG_LOW_LEVEL
}
static void Davis_Write(const char *inBuf, DebugType inDebug)
{
Davis_Write((const uint8_t *)inBuf, strlen(inBuf), inDebug);
}
static void Davis_Write(uint8_t inByte, DebugType inDebug)
{
Davis_Write((const uint8_t *)&inByte, 1, inDebug);
}
static bool Davis_ReadByte(uint8_t *outByte, DebugType inDebug)
{
if (Serial.available())
{
*outByte = Serial.read();
#ifdef DEBUG_LOW_LEVEL
if (inDebug)
{
MSG_DBG("RX: %02X", *outByte);
}
#endif //DEBUG_LOW_LEVEL
return true;
}
return false;
}
static uint16_t Davis_Read(uint8_t *outBuf, uint16_t inBufSize, bool inStopOnNewLine, uint16_t inByteTimeoutMs, DebugType inDebug)
{
uint16_t lvBytesReceived = 0;
unsigned long lvByteTime = millis();
while ((lvBytesReceived < inBufSize) && ((millis() - lvByteTime) < inByteTimeoutMs))
{
if (Davis_ReadByte(&outBuf[lvBytesReceived], DEBUG_NONE))
{
lvByteTime = millis();
if ((inStopOnNewLine) && (outBuf[lvBytesReceived] == '\n'))
{
outBuf[lvBytesReceived] = '\0';
lvBytesReceived++;
break;
}
lvBytesReceived++;
}
}
#ifdef DEBUG_LOW_LEVEL
if (inDebug)
{
MSG_DBG_NO_LINE("RX: ");
DUMP_BYTES(outBuf, lvBytesReceived, inDebug);
MSG_DBG("");
}
#endif //DEBUG_LOW_LEVEL
return lvBytesReceived;
}
static DavisCommandResponse Davis_ReadCommandResponse(uint16_t inTimeoutMs, DebugType inDebug)
{
DavisCommandResponse lvResponse = RESP_INVALID;
unsigned long lvStartTime = millis();
char lvResponseBuf[8];
unsigned char lvIdx = 0;
while ((lvResponse == RESP_INVALID) && (lvIdx < sizeof(lvResponseBuf)) && ((millis() - lvStartTime) < inTimeoutMs))
{
if (Davis_ReadByte((uint8_t*)&lvResponseBuf[lvIdx], DEBUG_NONE))
{
if (lvResponseBuf[lvIdx] == ACK)
{
lvResponse = RESP_ACK;
}
else if (lvResponseBuf[lvIdx] == NACK)
{
lvResponse = RESP_NACK;
}
lvIdx++;
if ((lvIdx == strlen(RESP_OK_STR)) && (memcmp(lvResponseBuf, RESP_OK_STR, strlen(RESP_OK_STR)) == 0))
{
lvResponse = RESP_OK;
}
}
}
if (lvResponse == RESP_INVALID)
{
lvResponse = RESP_TIMEOUT;
}
#ifdef DEBUG_LOW_LEVEL
if (inDebug)
{
MSG_DBG_NO_LINE("RX: ");
DUMP_BYTES(lvResponseBuf, lvIdx, inDebug);
MSG_DBG("(%s)", PRINT_RESPONSE_TYPE(lvResponse));
}
#endif //DEBUG_LOW_LEVEL
return lvResponse;
}
static bool Davis_SendCommand(const char *inCommand, char *outResponse, uint16_t inMaxResponseLength, bool inBinaryResponse, uint16_t inTimeoutMs)
{
// flush RX buffer
Davis_FlushRx();
Davis_Write(inCommand);
Davis_Write("\n");
DavisCommandResponse lvResponse = Davis_ReadCommandResponse(inTimeoutMs);
if (!IS_GOOD_RESPONSE(lvResponse))
{
MSG_DBG("Command '%s' did not return good response! Response: %s", inCommand, PRINT_RESPONSE_TYPE(lvResponse));
return false;
}
if (outResponse)
{
uint16_t lvResponseSize = Davis_Read((uint8_t*)outResponse, inMaxResponseLength, !inBinaryResponse, DAVIS_BYTE_TIMEOUT_MS, (inBinaryResponse ? DEBUG_HEX : DEBUG_HEXASCII));
if ((inBinaryResponse && (lvResponseSize != inMaxResponseLength)) || (!inBinaryResponse && (outResponse[lvResponseSize-1] != '\0')))
{
MSG_DBG("Timeout while waiting for response from '%s' command! (Response: '%s')", inCommand, outResponse);
return false;
}
}
return true;
}
static uint16_t Davis_SendRawCommand(const char *inCommand, char *outResponse, uint16_t inMaxResponseLength, uint16_t inByteTimeoutMs)
{
//unsigned long lvByteTime;
uint16_t lvBytesReceived = 0;
// flush RX buffer
Davis_FlushRx();
Davis_Write(inCommand);
if (inCommand[strlen(inCommand)-1] != '\n')
{
Davis_Write("\n");
}
lvBytesReceived = Davis_Read((uint8_t*)outResponse, inMaxResponseLength, false);
return lvBytesReceived;
}
static bool Davis_StartReadArchiveData(uint16_t *outPageCount, uint16_t *outFirstRecord, uint16_t inDateStamp, uint16_t inTimeStamp)
{
uint16_t lvDateStamp = inDateStamp;
uint16_t lvTimeStamp = inTimeStamp;
if (Davis_SendCommand("DMPAFT", 0, 0))
{
unsigned long lvByteTime;
uint8_t lvDateTimeStamp[6];
uint16_t lvCRC;
lvDateTimeStamp[0] = (uint8_t)(lvDateStamp & 0xFF);
lvDateTimeStamp[1] = (uint8_t)(lvDateStamp >> 8);
lvDateTimeStamp[2] = (uint8_t)(lvTimeStamp & 0xFF);
lvDateTimeStamp[3] = (uint8_t)(lvTimeStamp >> 8);
lvCRC = CalcCrc((uint8_t*)lvDateTimeStamp, 4);
lvDateTimeStamp[4] = (uint8_t)(lvCRC >> 8);
lvDateTimeStamp[5] = (uint8_t)(lvCRC & 0xFF);
//lvDateTimeStamp[6] = '\n';
Davis_Write(lvDateTimeStamp, sizeof(lvDateTimeStamp));
uint8_t lvResponse[7];
uint16_t lvBytesReceived = Davis_Read(lvResponse, sizeof(lvResponse), false, 100*DAVIS_BYTE_TIMEOUT_MS);
lvCRC = CalcCrc((uint8_t*)lvResponse+1, 6);
if ((lvBytesReceived != sizeof(lvResponse) || (lvResponse[0] != ACK) || (lvCRC != 0)))
{
MSG_DBG_NO_LINE("Invalid response after DMPAFT datetimestamp (%d bytes, CRC: 0x04X): ", lvBytesReceived, lvCRC);
for (int i = 0; i < lvBytesReceived; i++)
{
MSG_DBG_NO_LINE("%02X ", lvResponse[i]);
}
MSG_DBG("");
return false;
}
*outPageCount = ((uint16_t)lvResponse[2] << 8) + lvResponse[1];
*outFirstRecord = ((uint16_t)lvResponse[4] << 8) + lvResponse[3];
MSG_DBG("Page Count: %d", *outPageCount);
MSG_DBG("First Record: %d", *outFirstRecord);
s_ArchivePageNr = 0;
s_ArchivePageCount = *outPageCount;
return true;
}
return false;
}
static bool Davis_StartReadArchiveData(uint16_t *outPageCount, uint16_t *outFirstRecord, uint16_t inYear, uint8_t inMonth, uint8_t inDay, uint8_t inHour, uint8_t inMinute)
{
MSG_DBG("Requesting archive data from %04d-%02d-%02d %02d:%02d", inYear, inMonth, inDay, inHour, inMinute);
uint16_t lvDateStamp = DATE_TO_DATESTAMP(inDay, inMonth, inYear);
uint16_t lvTimeStamp = TIME_TO_TIMESTAMP(inHour, inMinute);
return Davis_StartReadArchiveData(outPageCount, outFirstRecord, lvDateStamp, lvTimeStamp);
}
static bool Davis_ContinueReadArchiveData(ArchivePage **outArchivePage, uint16_t *outPageNr, uint8_t inRetries)
{
if (s_ArchivePageNr < s_ArchivePageCount)
{
uint8_t lvRetries = 0;
Davis_Write(ACK);
while (lvRetries < inRetries)
{
uint16_t lvBytesReceived = Davis_Read(s_ArchivePageBuf, sizeof(s_ArchivePageBuf), false, 100*DAVIS_BYTE_TIMEOUT_MS);
if (lvBytesReceived == sizeof(s_ArchivePageBuf))
{
uint16_t lvCRC = CalcCrc(s_ArchivePageBuf, lvBytesReceived);
if (lvCRC == 0)
{
// CRC valid
*outArchivePage = (ArchivePage *)s_ArchivePageBuf;
*outPageNr = s_ArchivePageNr;
s_ArchivePageNr++;
return true;
}
else
{
MSG_DBG("invalid CRC on page %d", s_ArchivePageNr);
Davis_Write(NACK);
lvRetries++;
}
}
else
{
MSG_DBG("Not enough bytes received for page %d (%d)", s_ArchivePageNr, lvBytesReceived);
Davis_Write(NACK);
lvRetries++;
}
}
if (lvRetries >= inRetries)
{
MSG_DBG("Retry limit reached on page %d (%d)", s_ArchivePageNr, lvRetries);
Davis_StoptReadArchiveData();
}
}
return false;
}
static void Davis_StoptReadArchiveData()
{
Davis_Write(ESC);
}
static bool Davis_WakeUp(void)
{
//Console Wakeup procedure:
//1. Send a Line Feed character, ‘\n’ (decimal 10, hex 0x0A).
//2. Listen for a returned response of Line Feed and Carriage Return characters, (‘\n\r’).
//3. If there is no response within a reasonable interval (say 1.2 seconds), then try steps 1 and
//2 again up to a total of 3 attempts.
//4. If the console has not woken up after 3 attempts, then signal a connection error
char lvResponseBuf[2];
bool lvCorrectResponseReceived = false;
uint8_t lvWakeupAttempts = 3;
//MSG_DBG("Attempting wake-up of Davis console.");
do
{
// flush RX buffer
Davis_FlushRx();
Davis_Write("\n\n");
//lvStartTime = millis();
//lvIdx = 0;
lvCorrectResponseReceived = false;
lvResponseBuf[0] = 0;
lvResponseBuf[1] = 0;
Davis_Read((uint8_t*)lvResponseBuf, sizeof(lvResponseBuf), false, DAVIS_WAKEUP_TIMEOUT_MS);
if ((lvResponseBuf[0] == '\n') && (lvResponseBuf[1] == '\r'))
{
lvCorrectResponseReceived = true;
}
} while(!lvCorrectResponseReceived && (--lvWakeupAttempts > 0));
if (!lvCorrectResponseReceived)
{
MSG_DBG("Failed to wake-up Davis Weather Station!");
return false;
}
//MSG_DBG("Wake-up successful!");
return true;
}
static bool Davis_ConvertLoopData(LoopPacket* inLoopPacket, StationData * outStationData)
{
outStationData->InsideTemperature = DAVIS_CONVERT_TEMPERATURE_10TH(inLoopPacket->InTemperature);
outStationData->OutsideTemperature = DAVIS_CONVERT_TEMPERATURE_10TH(inLoopPacket->OutTemperature);
outStationData->BarometricPressure = DAVIS_CONVERT_BAR_PRESSURE(inLoopPacket->Barometer);
outStationData->BarometricTrend = inLoopPacket->BarTrend;
outStationData->InsideHumidity = inLoopPacket->InHumidity;
outStationData->OutsideHumidity = inLoopPacket->OutHumidity;
outStationData->WindSpeed = DAVIS_CONVERT_WINDSPEED(inLoopPacket->WindSpeed);
outStationData->AvgWindSpeed = DAVIS_CONVERT_WINDSPEED(inLoopPacket->AvgWindSpeed);
outStationData->WindDirection = inLoopPacket->WindDirection;
for (int i = 0; i < 7; i++)
{
outStationData->ExtraTemps[i] = DAVIS_CONVERT_EXTRA_TEMPERATURE(inLoopPacket->ExtraTemps[i]);
}
for (int i = 0; i < 4; i++)
{
outStationData->SoilTemps[i] = DAVIS_CONVERT_EXTRA_TEMPERATURE(inLoopPacket->SoilTemps[i]);
}
for (int i = 0; i < 4; i++)
{
outStationData->LeafTemps[i] = DAVIS_CONVERT_EXTRA_TEMPERATURE(inLoopPacket->LeafTemps[i]);
}
for (int i = 0; i < 7; i++)
{
outStationData->ExtraHumidity[i] = inLoopPacket->ExtraHumidity[i];
}
outStationData->RainRate = DAVIS_CONVERT_RAINRATE(inLoopPacket->RainRate);
outStationData->RainDaily = DAVIS_CONVERT_RAINRATE(inLoopPacket->RainDay);
outStationData->UVindex = inLoopPacket->UVindex;
outStationData->SolarRadiation = inLoopPacket->SolarRadiation;
outStationData->Battery_Transmitter = inLoopPacket->Battery_Transmitter;
outStationData->Battery_Console = DAVIS_CONVERT_BATT_VOLTAGE(inLoopPacket->Battery_Console);
outStationData->ForecastIcons = inLoopPacket->ForecastIcons;
outStationData->ForecastRule = inLoopPacket->ForecastRule;
snprintf(outStationData->TimeSunrise, sizeof(outStationData->TimeSunrise), "%02d:%02d", (inLoopPacket->TimeSunrise / 100), inLoopPacket->TimeSunrise % 100);
snprintf(outStationData->TimeSunset, sizeof(outStationData->TimeSunset), "%02d:%02d", (inLoopPacket->TimeSunset / 100), inLoopPacket->TimeSunset % 100);
return true;
}
static bool Davis_ConvertLoop2Data(Loop2Packet* inLoop2Packet, StationData * outStationData)
{
outStationData->DewPoint = DAVIS_CONVERT_DEW_POINT(inLoop2Packet->DewPoint);
outStationData->WindChillTemp = DAVIS_CONVERT_DEW_POINT(inLoop2Packet->WindChill);
outStationData->Rain15min = DAVIS_CONVERT_RAINRATE(inLoop2Packet->Rain15Min);
outStationData->RainHour = DAVIS_CONVERT_RAINRATE(inLoop2Packet->RainHour);
outStationData->Rain24Hrs = DAVIS_CONVERT_RAINRATE(inLoop2Packet->Rain24Hrs);
return true;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.