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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
181663fadcb2fefce31a219eff1bcaa0a9d6f133 | 0674e81a160161996251fb4b063c801330ccd1e2 | /other/inc/2012/echris.cpp | 4ede790e15da83613fbee0182439d368a619b489 | [] | no_license | joshuabezaleel/cp | 8a2c9b44605810da4367efeb981f822ae5e1e9a2 | 57f365458cca38c3c0fb1f5af1c6b44b74f3b53e | refs/heads/master | 2022-07-19T00:39:34.395495 | 2020-05-23T20:37:20 | 2020-05-23T20:37:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,065 | cpp | echris.cpp | #include<iostream>
#include<cstring>
#include<cstdio>
#include<vector>
#include<set>
#include<algorithm>
using namespace std;
int kasus,vertex;
vector<int> edge[1001];
set<string> kode;
string dfs(int x,int parent) {
string hasil = "";
vector<string> mau;
for (int i=0;i<edge[x].size();++i) {
if (edge[x][i] == parent) continue;
mau.push_back("0"+dfs(edge[x][i],x)+"1");
}
sort(mau.begin(),mau.end());
for (int i=0;i<mau.size();++i) hasil += mau[i];
return hasil;
}
int main() {
scanf("%d",&kasus);
for (int l=1;l<=kasus;++l) {
scanf("%d",&vertex);
for (int i=1;i<=vertex;++i) edge[i].clear();
kode.clear();
for (int i=1,j,k;i<vertex;++i) scanf("%d %d",&j,&k),edge[j].push_back(k),edge[k].push_back(j);
for (int i=1;i<=vertex;++i) {
string hasil = dfs(i,0);
kode.insert(hasil);
}
printf("Case #%d: %d\n",l,(int)kode.size());
}
return 0;
}
|
b8cca2e1b69f6b010556588b5c339da3dc19e149 | b15153a01f724e8d3579f2c3a7e87a69fc4bd3b7 | /libuvxx_rtsp/include/details/media_framers/_mpa_audio_framer.hpp | dbd57ea8f00c6a46306b6a911dd064c0f6c3d65f | [] | no_license | UIKit0/libuvxx | e2e931e1625ec4224281696ada0e5e5bcf247fa0 | b795fe6addeab18fe8ed090bd0c30c57d4c3be65 | refs/heads/master | 2020-12-26T04:05:57.509265 | 2015-08-20T09:14:46 | 2015-08-20T09:14:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 442 | hpp | _mpa_audio_framer.hpp | #pragma once
#include "media_session.hpp"
#include "_media_framer_base.hpp"
namespace uvxx { namespace rtsp { namespace details { namespace media_framers
{
class _mpa_audio_framer : public _media_framer_base
{
public:
explicit _mpa_audio_framer(const media_subsession& subsession);
virtual ~_mpa_audio_framer();
protected:
virtual void sample_receieved(bool packet_marker_bit) override;
};
}}}} |
df0f68061a477a139a6d9fe54f5bcf6dfcb26083 | 1dd361b07e88814c2afa5e8bc36aa1b045d12858 | /ChutesAndLaddersGame.cpp | c8c9fd4f5941fd9c718cdfab93197660829a771f | [] | no_license | xdo0410/project2 | 1651981c257a16699fb78ec044f3ae81167aecd6 | f54ab24be018c3d4f7e28826874fdd4c987879b1 | refs/heads/master | 2021-01-13T09:08:02.156878 | 2016-11-08T07:11:45 | 2016-11-08T07:11:45 | 72,506,793 | 0 | 0 | null | 2016-11-01T05:30:55 | 2016-11-01T05:30:55 | null | UTF-8 | C++ | false | false | 2,688 | cpp | ChutesAndLaddersGame.cpp | //
// ChutesAndLaddersGame.cpp
//
#include <iostream>
#include <string>
#include "ChutesAndLaddersGame.hpp"
#include "GameBoard.hpp"
#include "Player.hpp"
using namespace std;
// TODO: implement the constructor with all your team members
// constructor with the default value of a minimum players
ChutesAndLaddersGame::ChutesAndLaddersGame(int nPlayers) : winner("no winner") {
playerQueue = new ArrayQueue<Player>(nPlayers);
player1 = new Player("Player 1");
player2 = new Player("Player 2");
playerQueue->enqueue(*player1);
playerQueue->enqueue(*player2);
}
// TODO: implement the destructor
// destructor - dequeue players from the queue
ChutesAndLaddersGame::~ChutesAndLaddersGame() {
while(!(playerQueue->empty()))
{
playerQueue->dequeue();
}
delete playerQueue;
delete player1;
delete player2;
}
// TO DO: implement this function properly
// reset the game - rebuild the list of players
// (i.e., the list should be the same as in the constructor).
// Place all players at the figurative square zero
void ChutesAndLaddersGame::resetGame() {
while(!(playerQueue->empty()))
{
playerQueue->dequeue();
}
winner = "no winner";
player1->setPostion(0);
player2->setPostion(0);
playerQueue->enqueue(*player1);
playerQueue->enqueue(*player2);
}
// TO DO: implement this function properly
// Play the chutes and ladders until a player reaches the winning square 100
// - Each player takes turn to roll the die and moves to the new square by invoking rollDieAndMove.
// If the new square is outside of the board, the player stays put
// - Player's new position is checked against the game board's checkChutesLadders
// - checkChutesLadders returns a different square if player lands on a chute or a ladder
// - Player's position is then set to the new position as indicated by checkChutesLadders
// If player lands on a chute or a ladder, player slides down or climbs up
// - If player lands on the winning square 100, game is over
// - playGame returns after congratulating and printing the winner's name
void ChutesAndLaddersGame::playGame() {
while(getWinner() == "no winner")
{
Player currentPlayer = playerQueue->front();
currentPlayer.rollDieAndMove();
int newLocation = currentPlayer.getPostion();
newLocation = gameBoard.checkChutesLadders(newLocation);
currentPlayer.setPostion(newLocation);
if (currentPlayer.getPostion() == 100) winner = currentPlayer.getName();
playerQueue->dequeue();
playerQueue->enqueue(currentPlayer);
}
cout << getWinner() << " is the winner!" << endl;
return;
}
|
03ffc86553bd45065293416d6ea85595d67b82be | a33aac97878b2cb15677be26e308cbc46e2862d2 | /program_data/PKU_raw/103/875.c | 52fed267b7d1e498297eae7832e08ce826a27bda | [] | no_license | GabeOchieng/ggnn.tensorflow | f5d7d0bca52258336fc12c9de6ae38223f28f786 | 7c62c0e8427bea6c8bec2cebf157b6f1ea70a213 | refs/heads/master | 2022-05-30T11:17:42.278048 | 2020-05-02T11:33:31 | 2020-05-02T11:33:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 385 | c | 875.c |
char q[1200];
char lastQ;
int head,length;
char MT(char q)
{
if ((q>='a')&&(q<='z')) return q-'a'+'A';
}
int main()
{
cin>>q;
head=1;length=1;lastQ=q[0];
while (q[head]!='\0')
{
if (MT(q[head])==MT(lastQ)) length++;
else
{
cout<<'('<<MT(lastQ)<<','<<length<<')';
lastQ=q[head];length=1;
}
head++;
}
cout<<'('<<MT(lastQ)<<','<<length<<')'<<endl;
return 0;
} |
e3b52314bc40fa9eea60c897dc173a3f1f3ea853 | 95e5da8d91a213c69856db4f50ba95e12f4d6d98 | /cc/app/kitti_occ_grids/occ_grid_extractor.h | 2077369779f0726419d4eed059018f17847fecbc | [] | no_license | aushani/summer | 4f2ba146a9cafc8e0ed239e8d2ddecb30518bf11 | 01ef8e9fa05d13bd853f37d5d9f3aba2fe74d2fb | refs/heads/master | 2020-03-22T04:18:04.547751 | 2018-01-15T17:13:20 | 2018-01-15T17:13:20 | 137,923,798 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,502 | h | occ_grid_extractor.h | #pragma once
#include <iostream>
#include <sys/stat.h>
#include <unistd.h>
#include <fstream>
#include <random>
#include <chrono>
#include <boost/filesystem.hpp>
#include "library/kitti/camera_cal.h"
#include "library/kitti/tracklets.h"
#include "library/kitti/velodyne_scan.h"
#include "library/ray_tracing/occ_grid_builder.h"
namespace fs = boost::filesystem;
namespace kt = library::kitti;
namespace rt = library::ray_tracing;
namespace app {
namespace kitti_occ_grids {
class OccGridExtractor {
public:
OccGridExtractor(const std::string &save_base_fn);
void Run();
private:
const char* kKittiBaseFilename = "/home/aushani/data/kittidata/extracted/";
static constexpr double kPosRes_ = 0.20; // 50 cm
static constexpr int kAngleBins_ = 8; // 8 angle bins -> 45 degrees
static constexpr double kAngleRes_ = 2 * M_PI/kAngleBins_; // 45 degrees
static constexpr int kJittersPerObject_ = 3;
rt::OccGridBuilder og_builder_;
kt::CameraCal camera_cal_;
std::default_random_engine rand_engine;
fs::path save_base_path_;
void ProcessFrameObjects(kt::Tracklets *tracklets, const kt::VelodyneScan &scan, int log_num, int frame);
void ProcessFrameBackground(kt::Tracklets *tracklets, const kt::VelodyneScan &scan, int log_num, int frame);
bool ProcessFrame(kt::Tracklets *tracklets, int log_num, int frame);
bool ProcessLog(int log_num);
bool FileExists(const char* fn) const;
};
} // namespace kitti
} // namespace app
|
199916f2eb848145ff9d31a2e14591ad326f47dd | 33bf3509defd8b9962dfda155256f49e49793fbc | /CF/B. Chtholly's request.cpp | 1ab27ca54446eaca67ce278048272806e0e21140 | [] | no_license | restukartiko03/CP-Solution | 837dfae09c9e042d9ae5432d953f3d2b1ebc668c | 05f2a28858526944745e80277726ca441bdf86b3 | refs/heads/master | 2021-04-15T07:18:34.453465 | 2018-03-26T15:46:25 | 2018-03-26T15:46:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 786 | cpp | B. Chtholly's request.cpp | #include<bits/stdc++.h>
#define mp make_pair
#define pb push_back
#define ll long long
#define fi first
#define se second
#define pii pair< int , int >
#define pll pair< long , long >
#define pi acos(-1.0)
#define _FAST ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL);
#define MOD 10e9+7
#define line puts("")
using namespace std;
int banyak( int x){
int sum = 1;
while(x > 0){
sum *= 10;
x /= 10;
}
return sum;
}
int balik( int x){
int ans = 0;
while(x > 0){
ans *= 10;
ans += x%10;
x /= 10;
}
return ans;
}
long long sum,n,nn,p,idx,a[100010];
int main(){
n = 1;
idx = 1;
cin>>nn>>p;
while(idx <= nn){
a[idx] = n*banyak(n) + balik(n);
a[idx] %= p;
n++;
idx++;
}
for(int i=1;i<=nn;i++){
sum += a[i];
sum %= p;
}
cout<<sum<<endl;
}
|
51722fb86f4d4981babddeeaf4a965b053b8aff9 | 9e50de103d180250da9fa73d06fd650a0224f201 | /CheckersEngine/Engine/BoardUtilities.cpp | 210080283def917c643556f8d78e72b15e3c6e05 | [] | no_license | HubertBraun/CheckersEngine | 5740daadc1a117e0fc39c0fdb7a626439d450e22 | e734dc4b135df06237e85532ace4b0ab92a5c8c4 | refs/heads/master | 2020-04-26T12:49:44.963588 | 2019-03-09T12:35:50 | 2019-03-09T12:35:50 | 173,561,926 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,516 | cpp | BoardUtilities.cpp | #include"BoardUtilities.h"
#include<iostream>
#include<Windows.h>
using std::cout;
using std::endl;
namespace sboard
{
void gotoxy(int x, int y) //goes to the (X,Y) coordinates
{
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void copy(board out, board in) //copies the board
{
for (int i = 0; i < boardXY; i++)
for (int j = 0; j < boardXY; j++)
out[i][j] = in[i][j];
}
void clean() //cleanes the board
{
gotoxy(0, 0);
for (int i = 0; i < boardXY; i++)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 0);
for (int j = 0; j < boardXY / 2; j++)
{
if (i % 2)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), BACKGROUND_BLUE | BACKGROUND_RED | BACKGROUND_GREEN); //dark grey
cout << " ";
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), BACKGROUND_BLUE | BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_INTENSITY); //light grey
cout << " ";
}
else
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), BACKGROUND_BLUE | BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_INTENSITY);
cout << " ";
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), BACKGROUND_BLUE | BACKGROUND_RED | BACKGROUND_GREEN);
cout << " ";
}
}
cout << endl;
}
}
void print(board b) //displays the board
{
clean(); //cleans the screen
for (int i = 0; i < boardXY; i++)
{
for (int j = 0; j < boardXY; j++)
{
gotoxy(j*2, i); //only white fields
switch (b[i][j])
{
case 1: //black(on the top of the board)
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), BACKGROUND_BLUE);
cout << " ";
break;
case 2: //white
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), BACKGROUND_RED);
cout << " ";
break;
case 4: //black king
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), BACKGROUND_BLUE | BACKGROUND_INTENSITY);
cout << " ";
break;
case 5: //white king
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), BACKGROUND_RED | BACKGROUND_INTENSITY);
cout << " ";
break;
}
}
}
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),15); //returns to the standard colour
gotoxy(0, boardXY+2);
}
bool compare(board b1, board b2)
{
for (int y = 0; y < boardXY; y++)
{
for (int x = 0; x < boardXY; x++)
{
if (b1[y][x] != b2[y][x])
return false;
}
}
return true;
}
}
|
c2ec281b22e14ff95788f5b259537d42f3df245a | c0438cae3adfb762c87d2c43bc1095bc0c123627 | /String/Find the smallest window in a string containing all characters of another string.cpp | 3506175b0f3b0cfe6d9735ea6df7910c06e660c7 | [] | no_license | SubhradeepSS/dsa | 6705ae2c27e73dd8b9eb3557fa5c255b54e6c746 | 3d4cf60c298e1c93ce458690f3e01940232d5099 | refs/heads/master | 2023-08-14T18:14:09.254692 | 2021-10-06T18:13:13 | 2021-10-06T18:13:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,929 | cpp | Find the smallest window in a string containing all characters of another string.cpp | #include<bits/stdc++.h>
using namespace std;
string findSubString(string str,string pat){
int len1=str.length(),len2=pat.length();
int start_ind=-1,min_length=INT_MAX,count=0;
int hash_pat[256]={0},hash_str[256]={0};
for(int i=0;i<len2;i++)
hash_pat[pat[i]]++;
int start=0;
for(int i=0;i<len1;i++){
hash_str[str[i]]++;
if(hash_str[str[i]]<=hash_pat[str[i]]&&hash_pat[str[i]])
count++;
if(count==len2){
while(hash_str[str[start]]>hash_pat[str[start]]||hash_pat[str[start]]==0)
{
if(hash_str[str[start]]>hash_pat[str[start]])
hash_str[str[start]]-- ;
start++;
}
if(i-start+1<min_length){
start_ind=start;
min_length=i-start+1;
}
}
}
if(start_ind==-1)
return "";
return str.substr(start_ind,min_length);
}
int main()
{
string str = "this is a test string";
string pat = "tist";
cout << "Smallest window is : \n"
<< findSubString(str, pat);
return 0;
}
/*
class Solution(object):
def minWindow(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
di=Counter(t)
curr={}
req=len(di)
cl=0
ans=float('inf'),None,None
l,r=0,0
while r<len(s):
add=s[r]
curr[add]=curr.get(add,0)+1
if add in di and di[add]==curr[add]:
cl+=1
while l<=r and cl==req:
sub=s[l]
if r-l+1<ans[0]:
ans=r-l+1,l,r
curr[sub]-=1
if sub in di and curr[sub]<di[sub]:
cl-=1
l+=1
r+=1
return "" if ans[0]==float('inf') else s[ans[1]:ans[2]+1]
*/
|
d139e388ee15cff9830c9113ab7a0a1de02e3040 | 0ef072f73e074bb88cbe0e594281f23e64c9ff6b | /Grades/Grades/Gradebook.cpp | 7baf38a41945ceeaade0c1bf3c6db9138c7e9e8b | [] | no_license | ryanmalencia/CPlusPractice | 43f350c4b54d023bef2c290397b3b6e0eaac4cc1 | a5b10a648c51e0eeb230c0fc00787549169fd29f | refs/heads/master | 2021-04-12T03:21:34.029296 | 2018-03-30T01:25:34 | 2018-03-30T01:25:34 | 125,945,448 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,028 | cpp | Gradebook.cpp | #include "stdafx.h"
#include <stdlib.h>
#include <string>
#include <vector>
#include "Gradebook.h"
#include "GradeStatistics.h"
using namespace std;
Gradebook::Gradebook()
{
count = 0;
}
Gradebook::Gradebook(string name)
{
this->name = name;
count = 0;
}
int Gradebook::AddGrade(double grade)
{
if (grade >= 0)
{
grades.push_back(grade);
count++;
return count;
}
else
{
return 0;
}
}
GradeStatistics *Gradebook::ComputeStatistics()
{
GradeStatistics *stats = new GradeStatistics();
double sum = 0;
double average = 0;
double highest = 0;
double lowest = 200;
int i = 0;
double current = 0;
if (count > 0)
{
for (i = 0; i < count; i++)
{
current = grades.at(i);
sum += current;
if (current > highest)
{
highest = current;
}
if (current < lowest)
{
lowest = current;
}
average = sum / count;
stats->SetStats(average, highest, lowest);
}
}
return stats;
}
string Gradebook::GetName()
{
return name;
}
int Gradebook::GetCount()
{
return count;
}
|
1b618c4ba1dbd3597d611a53e29308bd6174b7f4 | d8c958433033517d62c118d8bbf0d3c70f17cf0c | /joindialog.h | 0f63d90fb97894d7126190d1f299ba11b54d9aad | [] | no_license | busoc/moncop | c516c51538f039a2d4bd887c2300e6feee4fbd84 | 860f26d6ede19199792be26e8cae3a918ec389a3 | refs/heads/master | 2022-12-02T19:14:37.644477 | 2020-08-21T08:37:29 | 2020-08-21T08:37:29 | 289,218,331 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 396 | h | joindialog.h | #ifndef JOINDIALOG_H
#define JOINDIALOG_H
#include <QDialog>
namespace Ui {
class JoinDialog;
}
class JoinDialog : public QDialog
{
Q_OBJECT
public:
explicit JoinDialog(QWidget *parent = nullptr);
~JoinDialog();
QString host() const;
QString interface() const;
quint16 port() const;
bool join() const;
private:
Ui::JoinDialog *ui;
};
#endif // JOINDIALOG_H
|
6d9ae4082cb222c4d97a1d0f53f1f9bcd3f1454b | dd9e33662af1ba9c35b165d322aa87143a9eadec | /1078.cpp | 060fa0bb6603dd1f83a569c28a3f7a2bcca3e165 | [] | no_license | novakoki/PAT | 001ea6d02fcef2b2cfb2188184c81a9bda75b24b | 4292fe1a9a354fd6b6e9afc6cf293d7cb419b5d0 | refs/heads/master | 2021-01-21T10:09:03.562899 | 2017-03-03T06:22:41 | 2017-03-03T06:22:41 | 83,386,173 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,316 | cpp | 1078.cpp | #include <iostream>
#include <sstream>
#include <vector>
#include <list>
#include <queue>
#include <algorithm>
#include <iomanip>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <string>
#include <set>
#include <stack>
#include <cstdio>
#include <cstring>
#include <climits>
#include <cstdlib>
using namespace std;
int main() {
/*freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);*/
int m, n, key, pos;
scanf("%d %d", &m, &n);
vector<bool> is_prime(2*m, true);
is_prime[0] = false;
is_prime[1] = false;
for (int i = 2; i * i < 2*m; i++) {
if (is_prime[i]) {
for (int j = i*i; j < 2*m; j+=i)
is_prime[j] = false;
}
}
while (!is_prime[m]) m++;
vector<bool> table(m, false);
vector<int> res;
while (n--) {
scanf("%d", &key);
int index = 0;
bool flag = false;
pos = key % m;
for (int step = 0; step < m; step++) {
index = (pos + step * step) % m;
if (!table[index]) {
table[index] = true;
res.push_back(index);
flag = true;
break;
}
}
if (!flag)
res.push_back(-1);
}
for (int i = 0; i < res.size(); i++) {
if (i != 0)
printf(" ");
if (res[i] == -1)
printf("-");
else
printf("%d", res[i]);
}
return 0;
} |
ece98be21b2b0e0ce2edfba55ee74e0d12630ae0 | ba1e90ae6ea9f8f74d9b542e159825341c717712 | /2014/cclunchsep4.cpp | b595eff7629ef572206bae5c65857408cc2ea6a9 | [] | no_license | sailesh2/CompetitiveCode | b384687a7caa8980ab9b9c9deef2488b0bfe9cd9 | 5671dac08216f4ce75d5992e6af8208fa2324d12 | refs/heads/master | 2021-06-24T22:39:11.396049 | 2020-11-27T05:22:17 | 2020-11-27T05:22:17 | 161,877,355 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 786 | cpp | cclunchsep4.cpp | #include<stdio.h>
#include<iostream>
using namespace std;
int main()
{
int i,t,j,ctr,n,m,a,b,c;
cin>>t;
for(i=0;i<t;i++)
{
cin>>n;
ctr=0;
int arr[n];
int sav[n];
sav[0]=0;
for(j=0;j<n;j++)
{
cin>>arr[j];
if(j!=0)
{
if(arr[j]!=arr[j-1])
{
ctr++;
//sav[i]=ctr;
}
sav[j]=ctr;
}
}
// for(i=0;i<n;i++)
// cout<<sav[i];
cin>>m;
for(j=0;j<m;j++)
{
cin>>a>>b>>c;
if(a==1)
cout<<sav[c-1]-sav[b-1]+1<<"\n";
}
}
return 0;
}
|
ec6e126dace52c38a9d95c5143424518bd7bc304 | 6b3a502518bb96c4202e1dbcb5d6ac8fb04449bd | /core/data/GP/Factory.h | e6cf498721923f9b85dd75611b52ff32c54349a3 | [
"MIT"
] | permissive | Mahdidaeidaei/Placenta-Morphometry | 631c6a7f3f210e775cafcb8f40222134d423e3e0 | dfc084d8b83acf0b67808cbf941d28856883a00e | refs/heads/master | 2020-06-01T02:01:47.172085 | 2019-06-03T16:27:44 | 2019-06-03T16:27:44 | 190,589,038 | 0 | 0 | null | 2019-06-06T13:46:31 | 2019-06-06T13:46:31 | null | UTF-8 | C++ | false | false | 7,023 | h | Factory.h | /******************************************************************************\
|* Population library for C++ X.X.X *|
|*----------------------------------------------------------------------------*|
The Population License is similar to the MIT license in adding this clause:
for any writing public or private that has resulted from the use of the
software population, the reference of this book "Population library, 2012,
Vincent Tariel" shall be included in it.
So, the terms of the Population License are:
Copyright © 2012, Tariel Vincent
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 and for any writing
public or private that has resulted from the use of the software population,
the reference of this book "Population library, 2012, Vincent Tariel" shall
be included in it.
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.
\***************************************************************************/
#ifndef FACTORY_H
#define FACTORY_H
#include<map>
#include<string>
#include<vector>
#include"core/data/utility/Exception.h"
#include"core/data/GP/NullType.h"
#include"core/data/GP/Typelist.h"
#include"core/data/GP/TypelistMacros.h"
#include"core/data/GP/TypeTraitsTemplateTemplate.h"
#include"core/data/GP/Type2Id.h"
namespace pop
{
namespace Details {
template<typename Product>
struct CreatorMemberClone
{
Product * createObject(Product * creator){
return creator->clone();
}
};
template<typename Product, typename Key>
struct RegisterInFactoryInInitiatilzation
{
std::vector<std::pair<Key,Product*> > Register(){
return std::vector<std::pair<Key,Product*> >();
}
};
}
template
<
class Product,
typename Key,
template <class> class CreatorMemberPolicy =Details::CreatorMemberClone,
template <class,class> class RegisterData = Details::RegisterInFactoryInInitiatilzation
>
class Factory : public CreatorMemberPolicy<Product>, RegisterData<Product,Key>
{
protected:
std::map<Key,Product *> _map;
public:
Factory()
{
std::vector<std::pair<Key,Product*> > vec= RegisterData<Product,Key>::Register();
for(unsigned int i=0;i<vec.size();i++){
Register(vec[i].first,vec[i].second);
}
}
virtual ~Factory()
{
typename std::map<Key,Product *>::iterator it;
for ( it=_map.begin() ; it != _map.end(); it++ )
delete it->second;
_map.clear();
}
bool Register(Key key, Product * productcreator)
{
_map[key]=productcreator;
return true;
}
void Unregister(Key key)
{
_map.erase (key);
}
Product * createObject(Key key) throw(pexception)
{
if(_map.find(key)!=_map.end()){
Product * p = _map[key];
return CreatorMemberPolicy<Product>::createObject(p);
}
else
{
throw(pexception("Factory: Unknown key\n"));
return CreatorMemberPolicy<Product>::createObject((_map.begin())->second);
}
}
template<typename Parm1>
Product * createObject(Key key,Parm1 parm1) throw(pexception)
{
if(_map.find(key)!=_map.end())
return CreatorMemberPolicy<Product>::createObject(_map[key],parm1);
else
{
throw(pexception("Factory: Unknown key\n"));
return CreatorMemberPolicy<Product>::createObject((_map.begin())->second,parm1);
}
}
template<typename Parm1, typename Parm2>
Product * createObject(Key key, Parm1 parm1, Parm2 parm2) throw(pexception)
{
if(_map.find(key)!=_map.end())
return CreatorMemberPolicy<Product>::createObject(_map[key],parm1,parm2);
else
{
throw(pexception("Factory: Unknown key\n"));
return CreatorMemberPolicy<Product>::createObject((_map.begin())->second,parm1,parm2);
}
}
// template<typename Parm1, typename Parm2, typename Parm3>
// virtual Product * createObject(Key key, Parm1 parm1, Parm2 parm2, Parm3 parm3)
// {
// if(_map.find(key)!=_map.end())
// return CreatorMemberPolicy<Product>::createObject(_map[key],parm1,parm2,parm3);
// else
// throw(pexception("Factory: Unknown key\n"));
// }
// template<typename Parm1, typename Parm2, typename Parm3, typename Parm4>
// virtual Product * createObject(Key key, Parm1 parm1, Parm2 parm2, Parm3 parm3, Parm4 parm4)
// {
// if(_map.find(key)!=_map.end())
// return CreatorMemberPolicy<Product>::createObject(_map[key],parm1,parm2,parm3,parm4);
// else
// throw(pexception("Factory: Unknown key\n"));
// }
// template<typename Parm1, typename Parm2, typename Parm3, typename Parm4, typename Parm5>
// virtual Product * createObject(Key key, Parm1 parm1, Parm2 parm2, Parm3 parm3, Parm4 parm4, Parm5 parm5)
// {
// if(_map.find(key)!=_map.end())
// return CreatorMemberPolicy<Product>::createObject(_map[key],parm1,parm2,parm3,parm4,parm5);
// else
// throw(pexception("Factory: Unknown key\n"));
// }
};
template<typename T>
struct GPFactoryRegister;
template <>
struct GPFactoryRegister<Loki::NullType>
{
template<typename Factory, typename SubClassBlank>
static bool Register( Factory & , Loki::Type2Type<SubClassBlank>)
{
return true;
}
};
template <class Head, class Tail>
struct GPFactoryRegister<Loki::Typelist< Head, Tail> >
{
template<typename Factory, typename SubClassBlank>
static bool Register(Factory & factory, Loki::Type2Type<SubClassBlank> t)
{
typedef typename SubstituteTemplateParameter<Head,SubClassBlank>::Result SubClass;
Type2Id<SubClass> type;
for(unsigned int i=0;i<type.id.size();i++)
{
SubClass * c = new SubClass();
factory.Register( type.id[i],c);
}
return GPFactoryRegister<Tail>::Register(factory,t);
}
};
}
#endif // FACTORY_H
|
e952f3a5fa2e6b7b843cf635a8645d1b071b9da0 | 29eccfcedc60468cd5ec69afc8e70f1792da9fc9 | /src/tft/wristband-tft.cpp | ab466df236d619c2ba3ee47ffc6e9fc14d77e42c | [
"MIT"
] | permissive | marf41/TTGO-T-Wristband | 29fad0be1654e40ff0f85318f29fd3a3da10886b | 5558dccddd17e35553c6aab08f47da9f5680567f | refs/heads/master | 2021-05-25T18:33:07.866156 | 2020-12-17T20:03:40 | 2020-12-17T20:03:40 | 253,871,001 | 1 | 0 | null | 2020-04-07T17:52:08 | 2020-04-07T17:52:08 | null | UTF-8 | C++ | false | false | 17,062 | cpp | wristband-tft.cpp | #include "wristband-tft.hpp"
TFT_eSPI tft = TFT_eSPI();
bool landscape = true;
void tftInit() {
tft.init();
tftPortrait();
tft.setSwapBytes(true);
tft.fillScreen(TFT_BLACK);
ledcSetup(0, 5000, 8);
ledcAttachPin(TFT_BL, 0);
ledcWrite(0, 185);
}
void wifiManagerAdvice(const char *ap_name) {
tft.fillScreen(TFT_BLACK);
tft.setTextColor(TFT_WHITE);
tft.drawString("Connect hotspot name ", 20, tft.height() / 2 - 20);
tft.drawString("configure wrist", 35, tft.height() / 2 + 20);
tft.setTextColor(TFT_GREEN);
tft.setTextDatum(MC_DATUM);
tft.drawString(ap_name, tft.width() / 2, tft.height() / 2);
}
void drawProgressBar(uint16_t x0, uint16_t y0, uint16_t w, uint16_t h,
uint8_t percentage, uint16_t frameColor,
uint16_t barColor) {
tft.setTextColor(TFT_WHITE, TFT_BLACK);
tft.setTextDatum(TC_DATUM);
tft.setTextPadding(tft.textWidth(" 888% "));
tft.drawString(String(percentage) + "%", 145, 35);
if (percentage == 0) {
tft.fillRoundRect(x0, y0, w, h, 3, TFT_BLACK);
}
uint8_t margin = 2;
uint16_t barHeight = h - 2 * margin;
uint16_t barWidth = w - 2 * margin;
tft.drawRoundRect(x0, y0, w, h, 3, frameColor);
tft.fillRect(x0 + margin, y0 + margin, barWidth * percentage / 100.0,
barHeight, barColor);
}
void updatingText() {
// tftLandscape();
tftPortrait();
tft.fillScreen(TFT_BLACK);
tft.setTextColor(TFT_WHITE, TFT_BLACK);
// tft.drawString("Updating...", tft.width() / 2 - 20, 55);
}
void drawOTA(int progress) {
// tftPortrait();
static int last = -1;
if (progress == last && progress > 0) {
return;
}
if (progress % 5 == 0) {
drawCommon(0, 0);
}
last = progress;
tft.setTextColor(TFT_WHITE, TFT_BLACK);
tft.setFreeFont(&Orbitron_Light_24);
tft.setTextDatum(TC_DATUM);
if (progress % 5 == 0) {
// tft.fillScreen(TFT_BLACK);
tft.drawRect(0, 60, tft.width(), tft.height() - 60, TFT_BLACK);
tft.drawString("OTA", tft.width() / 2, 70);
}
tft.setTextPadding(tft.textWidth(" 888% "));
tft.drawString(String(progress) + "%", tft.width() / 2, 100);
tft.drawLine(0, tft.height() - 2, tft.width(), tft.height() - 2, TFT_WHITE);
tft.drawLine(0, tft.height() - 1, tft.width() * progress / 100.0,
tft.height() - 1, TFT_CYAN);
tft.setFreeFont(NULL);
}
void msgBig(const char *message) {
tft.fillScreen(TFT_BLACK);
tft.setTextColor(TFT_CYAN);
tft.setTextDatum(MC_DATUM);
tft.drawString(message, tft.width() / 2, tft.height() / 2, 4);
}
void msgError(const char *message) { msg(message, TFT_RED); }
void msgWarning(const char *message) { msg(message, TFT_ORANGE); }
void msgSuccess(const char *message) { msg(message, TFT_GREEN); }
void msgInfo(const char *message) { msg(message, TFT_CYAN); }
void msgInfo2(const char *msgA, const char *msgB) {
msg2(msgA, msgB, TFT_CYAN);
}
void msg(const char *message, uint16_t color) {
tftLandscape();
tft.fillScreen(TFT_BLACK);
tft.setTextColor(color);
tft.setTextDatum(MC_DATUM);
tft.drawString(message, tft.width() / 2, tft.height() / 2, 2);
tftPortrait();
}
void msg2(const char *msgA, const char *msgB, uint16_t color) {
tftLandscape();
tft.fillScreen(TFT_BLACK);
tft.setTextColor(color);
tft.setTextDatum(MC_DATUM);
tft.drawString(msgA, tft.width() / 2, tft.height() / 3, 2);
tft.drawString(msgB, tft.width() / 2, tft.height() * 2 / 3, 2);
tftPortrait();
}
void tftSleep(bool showMsg) {
if (showMsg) {
tft.fillScreen(TFT_BLACK);
tft.setTextColor(TFT_GREEN, TFT_BLACK);
tft.setTextDatum(MC_DATUM);
tft.drawString("Press again to wake up", tft.width() / 2, tft.height() / 2);
delay(2000);
}
tft.fillScreen(TFT_BLACK);
tft.writecommand(ST7735_SWRESET);
delay(100);
tft.writecommand(ST7735_SLPIN);
delay(150);
tft.writecommand(ST7735_DISPOFF);
}
void clearScreen() {
tft.fillScreen(TFT_BLACK);
tft.setCursor(0, 0);
}
void displayDate(const uint8_t day, const uint8_t month, const uint16_t year,
bool utc) {
char date[11] = " ";
sprintf(date, "%02u.%02u.%u", day, month, year);
tft.setTextDatum(TL_DATUM);
// tft.setTextColor(TFT_GREEN, TFT_BLACK);
tft.setTextColor(0xFBE0, TFT_BLACK);
tft.setCursor(6, 108);
tft.print(date);
if (utc) {
tft.print("U");
}
}
uint16_t displayHour(const uint8_t hour, const uint8_t minute, bool utc) {
uint8_t xpos = 6;
uint8_t yposa = 6;
uint8_t yposb = 54;
uint16_t colonX = 0;
tft.setTextDatum(TL_DATUM);
tft.setTextColor(SEG7_BACKGROUND, TFT_BLACK);
tft.drawString("88", xpos, yposa, 7);
tft.drawString("88", xpos, yposb, 7);
tft.setTextColor(utc ? TFT_GREENYELLOW : 0xFBE0);
if (hour < 10) {
xpos += tft.drawChar('0', xpos, yposa, 7);
}
xpos += tft.drawNumber(hour, xpos, yposa, 7);
colonX = xpos;
xpos += displayColon(xpos, true, utc);
xpos = 6;
tft.setTextColor(utc ? TFT_GREENYELLOW : 0xFBE0);
if (minute < 10) {
xpos += tft.drawChar('0', xpos, yposb, 7);
}
tft.drawNumber(minute, xpos, yposb, 7);
return colonX;
}
uint16_t displayColon(uint16_t x, bool color, bool utc) {
if (color) {
tft.setTextColor(0x0821);
} else {
tft.setTextColor(utc ? TFT_GREENYELLOW : 0xFBE0);
}
return tft.drawChar(':', x, 6, 7);
}
void drawBattery(float voltage, uint8_t percentage, bool charging) {
char voltageString[5] = " ";
uint16_t originx = 70;
uint16_t originy = 20;
uint16_t width = 80;
uint16_t height = 40;
uint16_t tabheight = 15;
uint16_t tabwidth = 5;
uint8_t margin = 2;
uint16_t barHeight = height - 2 * margin;
uint16_t barWidth = width - 2 * margin;
sprintf(voltageString, "%2.2f", voltage);
tft.fillScreen(TFT_BLACK);
tftLandscape();
if (percentage == 0) {
tft.fillRoundRect(originx, originy, width, height, 3, TFT_BLACK);
}
tft.fillRoundRect(originx - tabwidth + 1, (height - tabheight) / 2 + originy,
tabwidth, tabheight, 1, TFT_WHITE);
tft.drawRoundRect(originx, originy, width, height, 3, TFT_WHITE);
uint8_t barFill = barWidth * percentage / 100.0;
tft.fillRect(originx + margin + (barWidth - barFill), originy + margin,
barFill, barHeight, TFT_DARKGREEN);
tft.setTextColor(TFT_WHITE);
tft.setTextDatum(MC_DATUM);
tft.setTextPadding(tft.textWidth(" 888% ", 2));
width = tft.width();
originx = 40;
height = 0;
originy = 40;
tft.drawString(String(percentage) + "%", width / 2 + originx,
height / 2 + originy, 2);
tftPortrait();
tft.setTextColor(TFT_WHITE, TFT_BLACK);
tft.setTextDatum(BC_DATUM);
String voltageInfo = String(voltageString) + "V";
if (charging) {
voltageInfo += " CHRG";
}
tft.drawString(voltageInfo, tft.width() / 2, tft.height());
}
void initDrawBearing() {
tft.fillScreen(TFT_BLACK);
tft.setTextDatum(MC_DATUM);
tft.setTextColor(TFT_ORANGE, TFT_BLACK);
tft.drawString("---", tft.width() / 2, 40, 4);
tft.drawCircle(40, 40, 35, TFT_WHITE);
}
void refreshDrawBearing(int16_t bearing) {
char bearingText[5] = "---\0";
if (bearing >= 0) {
sprintf(bearingText, "%03d", bearing);
}
tft.setTextDatum(MC_DATUM);
tft.setTextColor(TFT_ORANGE, TFT_BLACK);
tft.fillCircle(40, 40, 34, TFT_BLACK);
tft.drawString(bearingText, tft.width() / 2, 40, 4);
if (bearing >= 0) {
double bs = sin((360 - bearing) * PI / 180.0);
double bc = cos((360 - bearing) * PI / 180.0);
uint8_t iy = 40 + 30 * bs;
uint8_t ix = 40 + 30 * bc;
uint8_t oy = 40 + 34 * bs;
uint8_t ox = 40 + 34 * bc;
tft.drawLine(ix, iy, ox, oy, TFT_WHITE);
}
}
void initDrawTemperature() {
// tft.fillScreen(TFT_BLACK);
tft.setTextDatum(BR_DATUM);
tft.setTextColor(TFT_WHITE, TFT_BLACK);
tft.drawString("C", tft.width() - 5, tft.height(), 2);
tft.drawCircle(tft.width() - 18, tft.height() - 12, 2, TFT_WHITE);
}
void refreshDrawTemperature(float temperature) {
char temperatureText[8] = " ";
sprintf(temperatureText, "%.1f", temperature);
tft.setTextDatum(TC_DATUM);
tft.setTextColor(TFT_RED, TFT_BLACK);
tft.drawString(temperatureText, tft.width() / 2, 100, 4);
}
void drawBottomBar(uint8_t percent, uint16_t color) {
if (percent > 100) {
percent = 100;
}
if (color == 0) {
color = TFT_GREEN;
if (percent <= 50) {
color = TFT_YELLOW;
}
if (percent <= 10) {
color = TFT_ORANGE;
}
if (percent <= 5) {
color = TFT_RED;
}
}
uint8_t posx = landscape ? 159 : 79;
uint8_t posy = landscape ? 77 : 157;
uint16_t len = posx - 3;
len *= percent;
len /= 100;
tft.drawLine(1, posy, 1, posy + 2, TFT_WHITE);
tft.fillRect(2, posy, (posx - 3) + 2, 3, TFT_BLACK);
tft.fillRect(2, posy, len + 2, 3, color);
tft.drawLine(posx, posy, posx, posy + 2, TFT_WHITE);
}
void tftLandscape() {
tft.setRotation(1);
landscape = true;
}
void tftPortrait() {
tft.setRotation(0);
landscape = false;
}
void status(const char *msg, int state) {
tft.setFreeFont(&TomThumb);
tft.setTextDatum(TC_DATUM);
tft.setTextColor(TFT_WHITE, TFT_BLACK);
tft.setTextPadding(tft.width());
if (state < 0) {
tft.drawString(msg, tft.width() / 2, tft.height() - 6);
} else {
tft.drawString(String(msg) + " " + String(state) + " ", tft.width() / 2,
tft.height() - 6);
}
}
void displayBatteryValue(float voltage, uint8_t percent, bool charging) {
char str[14] = "";
sprintf(str, "%2.2fV %3d%% %s", voltage, percent, charging ? "+" : " ");
tft.setTextDatum(TL_DATUM);
tft.setTextColor(0xFBE0, TFT_BLACK);
tft.drawString(str, 6, 145);
}
void initDrawQuaternion() {
tft.fillScreen(TFT_BLACK);
tft.setTextDatum(TL_DATUM);
tft.setTextColor(TFT_ORANGE, TFT_BLACK);
tft.drawString("q0 = ", 6, 10, 2);
tft.drawString("qx = ", 6, 30, 2);
tft.drawString("qy = ", 6, 50, 2);
tft.drawString("qz = ", 6, 70, 2);
tft.drawString("Y = ", 6, 90, 2);
tft.drawString("P = ", 6, 110, 2);
tft.drawString("R = ", 6, 130, 2);
}
void refreshDrawQuaternion(const float *q) {
tft.setTextDatum(TL_DATUM);
tft.setTextColor(TFT_ORANGE, TFT_BLACK);
char q0[8] = "";
char qx[8] = "";
char qy[8] = "";
char qz[8] = "";
char syaw[8] = "";
char spitch[8] = "";
char sroll[8] = "";
sprintf(q0, "%6.3f", q[0]);
sprintf(qx, "%6.3f", q[1]);
sprintf(qy, "%6.3f", q[2]);
sprintf(qz, "%6.3f", q[3]);
float yaw = atan2(2.0f * (q[1] * q[2] + q[0] * q[3]),
q[0] * q[0] + q[1] * q[1] - q[2] * q[2] - q[3] * q[3]);
float pitch = -asin(2.0f * (q[1] * q[3] - q[0] * q[2]));
float roll = atan2(2.0f * (q[0] * q[1] + q[2] * q[3]),
q[0] * q[0] - q[1] * q[1] - q[2] * q[2] + q[3] * q[3]);
pitch *= 180.0f / PI;
yaw *= 180.0f / PI;
roll -= (4 + (40 / 60)); // Declination
roll *= 180.0f / PI;
sprintf(syaw, "%5.1f", yaw);
sprintf(spitch, "%5.1f", pitch);
sprintf(sroll, "%5.1f", roll);
tft.drawString(q0, 40, 10, 2);
tft.drawString(qx, 40, 30, 2);
tft.drawString(qy, 40, 50, 2);
tft.drawString(qz, 40, 70, 2);
tft.drawString(syaw, 40, 90, 2);
tft.drawString(spitch, 40, 110, 2);
tft.drawString(sroll, 40, 130, 2);
}
void displayAppointments() {
char status[16] = "- / - / -";
uint8_t today = 0;
uint8_t tomorrow = 0;
uint8_t week = 0;
if (false) {
sprintf(status, "%2u / %2u / %2u", today, tomorrow, week);
} // TODO
tft.setTextDatum(TC_DATUM);
// tft.setTextColor(TFT_GREEN, TFT_BLACK);
tft.setTextColor(today > 0 ? TFT_ORANGE : 0xFBE0, TFT_BLACK);
tft.drawString(status, tft.width() / 2, 120, 2);
}
uint8_t drawOptions(const char *options[]) {
tft.fillScreen(TFT_BLACK);
tft.setTextDatum(ML_DATUM);
tft.setFreeFont(&Orbitron_Light5pt7b);
tft.setTextColor(TFT_WHITE, TFT_BLACK);
uint8_t i = 0;
for (i = 0; options[i]; i++) {
if (options[i]) {
tft.drawString(options[i], 20, 55 + (i + 1) * 16);
}
}
return i + 1;
}
void drawMenuPointer(int8_t n, bool right) {
uint8_t width = 10;
uint8_t from = 3;
tft.fillRect(from, 65, width, 100, TFT_BLACK);
uint8_t y = (n + 1) * 16 + 55;
uint8_t x = width + from - 1;
if (right) {
tft.fillTriangle(from, y - 5, x, y, from, y + 5, TFT_WHITE);
} else {
tft.fillTriangle(x, y - 5, from, y, x, y + 5, TFT_WHITE);
}
}
void drawStatus(char symbol, bool status, uint8_t pos) {
char str[2];
str[0] = symbol;
str[1] = '\0';
tft.setTextDatum(TC_DATUM);
tft.setTextColor(status ? TFT_ORANGE : TFT_DARKGREY, TFT_BLACK);
tft.drawString(str, pos, 135, 1);
}
void displayCounter(float counter, float add, float percent) {
char str[24] = "0.00";
char per[24] = "0.00";
sprintf(str, "%.1f +%.1f", counter, add);
sprintf(per, "%.3f%%", percent);
tft.setTextDatum(TC_DATUM);
// tft.setTextColor(TFT_GREEN, TFT_BLACK);
tft.setTextColor(TFT_ORANGE, TFT_BLACK);
tft.drawString(str, tft.width() / 2, 120, 2);
tft.drawString(per, tft.width() / 2, 140, 2);
}
void readRect(uint32_t x, uint32_t y, uint32_t w, uint32_t h, uint8_t *data) {
tft.readRectRGB(x, y, w, h, data);
}
void drawAppointments() {
RTC_Date now = getClockTime();
uint8_t t = TPOS(now.hour, now.minute);
tft.drawLine(t, 65, t, tft.height(), 0x3186);
for (uint8_t n = 0; n <= 3; n++) {
Appointment ap = getAppointment(n);
if (ap.set) {
uint8_t y = 59 + n * 24;
if (n > 0) {
// tft.drawLine(0, y, tft.width(), y, TFT_WHITE);
}
tft.setFreeFont(&Orbitron_Light5pt7b);
tft.setTextColor(TFT_WHITE, TFT_BLACK);
tft.setTextDatum(TL_DATUM);
tft.drawString(ap.name, 0, y + 1);
tft.setFreeFont(&TomThumb);
tft.setTextDatum(TL_DATUM);
tft.drawString(ap.place, 0, y + 14);
tft.setTextDatum(TR_DATUM);
tft.drawString(String(ap.hfrom) + ":" + SPAD(ap.mfrom) + "-" +
String(ap.hto) + ":" + SPAD(ap.mto),
tft.width(), y + 14);
tft.drawLine(0, y + 21, tft.width(), y + 21, TFT_BLACK);
if (ap.hfrom == 0 && ap.hto == 0 && ap.mfrom == 0 && ap.mto && 0) {
tft.drawLine(TPOS(0, 0), y + 21, TPOS(23, 59), y + 21, TFT_WHITE);
} else {
uint8_t tf = TPOS(ap.hfrom, ap.mfrom);
uint8_t tt = TPOS(ap.hto, ap.mto);
tft.drawLine(tf, y + 21, tt, y + 21, TFT_WHITE);
tft.drawLine(t, y + 21, t, y + 23,
((t >= tf) && (t <= tt)) ? TFT_CYAN : 0x3186);
}
}
}
}
bool drawCommon(uint8_t page, uint8_t pages) {
bool cleared = false;
static int8_t oldMinute = -1;
RTC_Date current;
float voltage, bvoltage;
current = getClockTime();
if (current.minute != oldMinute) {
tft.fillScreen(TFT_BLACK);
cleared = true;
}
oldMinute = current.minute;
// current = getClockTime();
tft.setTextPadding(0);
tft.setFreeFont(&Orbitron_Light_24);
/*
if (!page) {
tft.setTextColor(TFT_RED, TFT_BLACK);
tft.setTextDatum(TC_DATUM);
tft.drawString(String(page).c_str(), tft.width() / 2, tft.height() - 50);
}
*/
tft.setTextColor(TFT_WHITE, TFT_BLACK);
tft.setTextDatum(TL_DATUM);
tft.drawString(
String(current.hour < 10 ? "0" : "") + String(current.hour) + ":", 0, 0);
tft.drawString(
String(current.minute < 10 ? "0" : "") + String(current.minute), 0, 25);
tft.setFreeFont(&orbitron_light7pt7b);
tft.setTextDatum(TR_DATUM);
tft.drawString(String(current.day) + ".", tft.width() - 1, 0);
tft.drawString(String(current.month < 10 ? "0" : "") + String(current.month) +
".",
tft.width() - 1, 14);
tft.drawString(getClockDayName(), tft.width() - 1, 28);
/* if (lastError[0] != 0) {
tft.setTextColor(TFT_RED, TFT_BLACK);
tft.setTextColor(TFT_WHITE, TFT_BLACK);
tft.setTextDatum(TC_DATUM);
tft.drawString(lastError, tft.width(), 100);
} */
tft.setFreeFont(&TomThumb);
tft.setTextDatum(TR_DATUM);
tft.drawString((WiFiConnected() ? "W " : "") + String(current.year),
tft.width(), 45);
tft.setTextDatum(TR_DATUM);
voltage = getVoltage();
bvoltage = getBusVoltage();
uint8_t percent = calcPercentage(voltage);
tft.drawString(String(percent) + "% " + String(bvoltage, 2) + "V " +
String(voltage, 2) + "V" + (isCharging() ? "+" : ""),
tft.width() + 3, 52);
tft.setTextDatum(TC_DATUM);
// tft.drawString(String(percent) + "%", tft.width() / 2, 52);
tft.setTextDatum(TL_DATUM);
tft.drawString(String(page) + "/" + String(pages), 0, 52);
tft.setFreeFont(NULL);
tft.drawLine(0, 58, tft.width(), 58, TFT_GREY);
uint16_t color = TFT_GREEN;
if (percent <= 50) {
color = TFT_YELLOW;
}
if (percent <= 10) {
color = TFT_ORANGE;
}
if (percent <= 5) {
color = TFT_RED;
}
tft.drawLine(0, 58, tft.width() * percent / 100.0, 58, color);
if (pages > 0) {
uint8_t pw = tft.width() / (pages + 1);
uint8_t pr = 0;
if (pages > 1) {
pr = (tft.width() - (pw * pages)) / (pages - 1);
}
for (uint8_t i = 0; i < pages; i++) {
uint8_t px = i * pw + i * pr;
tft.drawLine(px, 60, px + pw, 60, i == page ? TFT_CYAN : TFT_WHITE);
}
}
return cleared;
}
|
185e5ee84d828c3893f70656c20fc5a154ed9edc | 8b3aa26cec0f07dd1b226d74ea7f099597ac4783 | /src/States/StateRoundFailed.h | 46adc3cb0e5b3af04d53775d0d925f3266af10ea | [] | no_license | RyanSwann1/BomberMan | c79dc5b6a89e5615eca9a60278563a46a4df5b9e | 04a912865f6f72d822aac3f5b28ceea7d57884e0 | refs/heads/master | 2021-01-22T06:03:28.914959 | 2017-11-07T15:49:12 | 2017-11-07T15:49:12 | 92,521,498 | 0 | 0 | null | 2017-11-07T15:49:12 | 2017-05-26T14:59:07 | C++ | UTF-8 | C++ | false | false | 307 | h | StateRoundFailed.h | #pragma once
#include <States\StateBase.h>
#include <Game\Timer.h>
class StateRoundFailed : public StateBase
{
public:
StateRoundFailed(StateManager& stateManager, StateType stateType);
~StateRoundFailed();
private:
void activateButton(const std::string& name) override;
void onEnteringWinState();
}; |
24fb9ae76f9bb40ddae5679815e2ac7548ee0a38 | 26786ae41bd8032e668ea745c0481ddc013ff0b4 | /Push_Button_Led.ino | 131429c5147e0f73b1eb5aeddba7d5ae952ef867 | [] | no_license | IchalAlwiros/Learn-FreeRTOS_Control-Led | 8be354f26845bf2e35734908c24d21525074d45d | be6cef3fbbd2a1f93339aab45faaa8ed189c0ae0 | refs/heads/main | 2023-06-06T23:21:26.956069 | 2021-07-14T05:19:10 | 2021-07-14T05:19:10 | 385,821,790 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 979 | ino | Push_Button_Led.ino | #include <Arduino_FreeRTOS.h>
void Task_PSX(void *param);
void Task_Print2(void *param);
TaskHandle_t Task_Handle1;
TaskHandle_t Task_Handle2;
void setup() {
Serial.begin(9600);
pinMode(13, OUTPUT);
//Prioritas tertinggi, itu akan dijalankan terlebih dalu
xTaskCreate(Task_PSX,"Task1",100,NULL,1,&Task_Handle1);
xTaskCreate(Task_Print2,"Task2",100,NULL,2,&Task_Handle2);
}
void loop() {
//Dead Loop
}
void Task_PSX(void *param)
{
(void)param;
while(1)
{
if (Serial.available() > 0) {
char comdata = char(Serial.read());
if (comdata == 'W') {
Serial.println("LED ON");
digitalWrite(13, HIGH);
vTaskDelay(1000/portTICK_PERIOD_MS);
}
else if(comdata == 'A' ) {
Serial.println("LED LOW");
digitalWrite(13, LOW);
}
}
}
}
void Task_Print2(void *param)
{
(void)param;
while(1)
{
Serial.println("Hello My Name is Ichal");
vTaskDelay(1000/portTICK_PERIOD_MS);
}
}
|
42368eb0220be3c38d91f3daaca2d32c71c4c440 | b12984c4a27367db1ec155370d1271f029bdfc56 | /PEngine/Source/Runtime/Component/Private/SpriteComponent.cpp | 7d4da686d919b831ddeaa3a655f31767cf9cc3bd | [
"MIT"
] | permissive | DimaMuzychenko/PEngine | 312c6a54f4f02df51309f848c6bb661fec3c0067 | 18dc600f9bfa95520492a00b101ddaa4e62cf209 | refs/heads/main | 2023-04-10T03:02:25.727800 | 2021-04-20T15:08:09 | 2021-04-20T15:08:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 325 | cpp | SpriteComponent.cpp | #include "Component/Public/SpriteComponent.h"
#include "Object/Public/Level.h"
DEFINE_META(CSpriteComponent)
CSpriteComponent::CSpriteComponent(CObject* Owner) : Super(Owner)
{
}
#ifdef WITH_EDITOR
void CSpriteComponent::FillEditorFields()
{
Super::FillEditorFields();
}
#endif
void CSpriteComponent::Draw() const
{
}
|
a9225fa8ae615aecba5498b29e5d84347eb0852f | f0f7ca508461a376e4b07d95562afdaa1a8b75dc | /PGG_Lab7-8_v1 - V16 - Finished/PGG_ViewingMovingObjects/Cube.cpp | 92f93d440e652a47025950326b4baf3e433677df | [] | no_license | HiddenRealm/PGG | 7aac4249d3acaf8e6648ea9d4474a899b1829b6f | 8a919dbae1b4281e94f046b02c92e12e91c6dd63 | refs/heads/master | 2020-03-20T12:21:19.880352 | 2018-06-15T01:52:30 | 2018-06-15T01:52:30 | 137,427,441 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,891 | cpp | Cube.cpp |
#include "Cube.h"
//Constructer
Cube::Cube()
{
// Variable for storing our VAO
// OpenGL has its own defined datatypes - a 'GLuint' is basically an unsigned int
_VAO = 0;
// Creates one VAO
glGenVertexArrays( 1, &_VAO );
// 'Binding' something makes it the current one we are using
// This is like activating it, so that subsequent function calls will work on this item
glBindVertexArray( _VAO );
// Simple vertex data for a cube
// (actually this is only four sides of a cube, you will have to expand this code if you want a complete cube :P )
float vertices[] = {
-0.5f, 0.5f, 0.5f,
-0.5f,-0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
-0.5f,-0.5f, 0.5f,
0.5f,-0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
0.5f,-0.5f, 0.5f,
0.5f, 0.5f,-0.5f,
0.5f,-0.5f, 0.5f,
0.5f,-0.5f,-0.5f,
0.5f, 0.5f,-0.5f,
-0.5f, 0.5f, 0.5f,
-0.5f, 0.5f,-0.5f,
-0.5f,-0.5f, 0.5f,
-0.5f,-0.5f, 0.5f,
-0.5f, 0.5f,-0.5f,
-0.5f,-0.5f,-0.5f,
0.5f, 0.5f,-0.5f,
0.5f,-0.5f,-0.5f,
-0.5f, 0.5f,-0.5f,
-0.5f, 0.5f,-0.5f,
0.5f,-0.5f,-0.5f,
-0.5f,-0.5f,-0.5f,
-0.5f, 0.5f,-0.5f,
-0.5f, 0.5f, 0.5f,
0.5f, 0.5f,-0.5f,
0.5f, 0.5f,-0.5f,
-0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f
};
// Number of vertices in above data
_numVertices = 30;
// Variable for storing a VBO
GLuint buffer = 0;
// Create a generic 'buffer'
glGenBuffers(1, &buffer);
// Tell OpenGL that we want to activate the buffer and that it's a VBO
glBindBuffer(GL_ARRAY_BUFFER, buffer);
// With this buffer active, we can now send our data to OpenGL
// We need to tell it how much data to send
// We can also tell OpenGL how we intend to use this buffer - here we say GL_STATIC_DRAW because we're only writing it once
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * _numVertices * 3, vertices, GL_STATIC_DRAW);
// This tells OpenGL how we link the vertex data to the shader
// (We will look at this properly in the lectures)
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0 );
glEnableVertexAttribArray(0);
// Normal data for our incomplete cube
// Each entry is the normal for the corresponding vertex in the position data above
float normals[] = {
0.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
-1.0f, 0.0f, 0.0f,
-1.0f, 0.0f, 0.0f,
-1.0f, 0.0f, 0.0f,
-1.0f, 0.0f, 0.0f,
-1.0f, 0.0f, 0.0f,
-1.0f, 0.0f, 0.0f,
0.0f, 0.0f,-1.0f,
0.0f, 0.0f,-1.0f,
0.0f, 0.0f,-1.0f,
0.0f, 0.0f,-1.0f,
0.0f, 0.0f,-1.0f,
0.0f, 0.0f,-1.0f,
0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f
};
// Variable for storing a VBO
GLuint normalBuffer = 0;
// Create a generic 'buffer'
glGenBuffers(1, &normalBuffer);
// Tell OpenGL that we want to activate the buffer and that it's a VBO
glBindBuffer(GL_ARRAY_BUFFER, normalBuffer);
// With this buffer active, we can now send our data to OpenGL
// We need to tell it how much data to send
// We can also tell OpenGL how we intend to use this buffer - here we say GL_STATIC_DRAW because we're only writing it once
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * _numVertices * 3, normals, GL_STATIC_DRAW);
// This tells OpenGL how we link the vertex data to the shader
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0 );
glEnableVertexAttribArray(1);
// Unbind for neatness, it just makes life easier
// As a general tip, especially as you're still learning, for each function that needs to do something specific try to return OpenGL in the state you found it in
// This means you will need to set the states at the beginning of your function and set them back at the end
// If you don't do this, your function could rely on states being set elsewhere and it's easy to lose track of this as your project grows
// If you then change the code from elsewhere, your current code could mysteriously stop working properly!
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray( 0 );
// Technically we can do this, because the enabled / disabled state is stored in the VAO
glDisableVertexAttribArray(0);
}
//Deconstructer
Cube::~Cube()
{
glDeleteVertexArrays( 1, &_VAO );
// TODO: delete the VBOs as well!
}
void Cube::Draw()
{
// Activate the VAO
glBindVertexArray( _VAO );
// Tell OpenGL to draw it
// Must specify the type of geometry to draw and the number of vertices
glDrawArrays(GL_TRIANGLES, 0, _numVertices);
// Unbind VAO
glBindVertexArray( 0 );
}
|
d4be6ebc3aa07ed5f27f6613c3a171269aa73eaa | 23eeef629a7ea12b3374fab7492ad550e3ce1370 | /tutorial_08.cpp | 47f3f458aea8984cbb7a2c2242a7c2fe9da98f0c | [] | no_license | mpeven/opengl_tutorial | eb75712fd89925615860f27ac21170e7efbcea9d | affa9fb8df6c58f05a96c17f035a7973d3f9d86c | refs/heads/master | 2021-05-07T14:31:20.299658 | 2017-11-16T00:44:32 | 2017-11-16T00:44:32 | 109,893,298 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,077 | cpp | tutorial_08.cpp | //Tutorial 8: Shading
// Compilation: g++ -framework OpenGL -lGLUT -w tutorial_08.cpp -o tut8.out
#include <GL/freeglut.h>
#include <stdio.h>
const int window_height = 640;
const int window_width = 640;
void RenderLoop()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.f, 1.f, 0.01f, 30.f);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
GLfloat light_diffuse_color[4] = { 1.f, 1.f, 1.f, 1.f };
GLfloat light_position[4] = { 0.f, 0.f, 1.f, 0.f };
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse_color);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
GLfloat material_diffuse_color[4] = { 1.f, 1.f, 1.f, 1.f };
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, material_diffuse_color);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glTranslatef(0.f, 0.f, -10.f);
glScalef(4.f, 4.f, 4.f);
glEnable(GL_NORMALIZE);
glShadeModel(GL_SMOOTH);
// glShadeModel(GL_FLAT);
glBegin(GL_TRIANGLES);
glNormal3f(0.f, 0.f, -1.f);
glVertex3f(0.0f, 0.0f, 0.0f);
glNormal3f(1.f, -1.f, 1.f);
glVertex3f(1.0f, 0.0f, 0.0f);
glNormal3f(0.f, 0.f, 1.f);
glVertex3f(1.0f, 1.0f, 0.0f);
glEnd();
glPopMatrix();
glDisable(GL_LIGHTING);
// GLfloat m[16];
// glGetFloatv(GL_PROJECTION_MATRIX, m);
// printf("\n Projection Matrix : \n");
// for (int i = 0; i < 4; i++) printf(" %f %f %f %f \n", m[i], m[4 + i], m[8 + i], m[12 + i]);
// glGetFloatv(GL_MODELVIEW_MATRIX, m);
// printf("\n Model View Matrix : \n");
// for (int i = 0; i < 4; i++) printf(" %f %f %f %f \n", m[i], m[4 + i], m[8 + i], m[12 + i]);
glutSwapBuffers();
}
void InitializeGLUT(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("Shading");
glutReshapeWindow(window_width, window_height);
glutDisplayFunc(RenderLoop);
glClearColor(0.f, 0.f, 0.f, 1.0);
glutMainLoop();
}
int main(int argc, char* argv[])
{
InitializeGLUT(argc, argv);
return 0;
}
|
72631c7e9ba58008ee197aac29865686b74e19fd | 4e0e82e2f926bcd90d1c306d940afceb1d968d30 | /rover_imu_uart/src/uart_imu_receiver/ROS_UART_IMU_Rx.hpp | d6be8fc7adf8e945e5d2c7d7204b7521bb97d0c9 | [] | no_license | pwalczykk/phobos_rover | 944c836c80c3ee8e4602e301eaf74bf8c356d26c | 79639312e9091e2d0e7a9876bbe30e3bc25ae622 | refs/heads/master | 2021-03-27T13:43:59.321061 | 2017-03-13T12:26:23 | 2017-03-13T12:26:23 | 58,230,231 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,389 | hpp | ROS_UART_IMU_Rx.hpp | #ifndef ROS_UART_RX_IMU_HPP_
#define ROS_UART_RX_IMU_HPP_
#define ACCEL_SCALE_RANGE 2
#define GYRO_SCALE_RANGE 250
#define MAGNETOMETER_SCALE_RANGE 1.3
#define Z_ACCEL_OFFSET 1800
#define Y_ACCEL_OFFSET 130
#define X_ACCEL_OFFSET -800
#define Z_GYRO_OFFSET 0
#define Y_GYRO_OFFSET 0
#define X_GYRO_OFFSET 0
#include <ros/ros.h>
#include <std_msgs/String.h>
#include <sensor_msgs/Imu.h>
#include <sensor_msgs/MagneticField.h>
#include <iostream>
#include <string.h>
#include "UART_Rx.hpp"
class ROS_UART_Rx : public UART_Rx{
ros::NodeHandle *nh;
ros::Publisher pubimu, pubmag;
int error_counter;
sensor_msgs::Imu msgimu;
sensor_msgs::MagneticField msgmag;
std::stringstream dataStream;
float xlin, ylin, zlin, xang, yang, zang, xmag, ymag, zmag;
public:
ROS_UART_Rx(std::string device_addres, std::string topicimu, std::string topicmag, ros::NodeHandle* nh) : UART_Rx((const char*) device_addres.c_str()){
this->nh = nh;
pubimu = nh->advertise<sensor_msgs::Imu>(topicimu, 10);
pubmag = nh->advertise<sensor_msgs::MagneticField>(topicmag, 10);
msgimu.header.frame_id = "odom";
msgmag.header.frame_id = "odom";
msgimu.linear_acceleration_covariance = { 1e-6, 0 , 0,
0 , 1e-6, 0,
0 , 0 , 1e-6 };
msgimu.angular_velocity_covariance = { 1e-6, 0 , 0,
0 , 1e-6, 0,
0 , 0 , 1e-6 };
msgimu.orientation_covariance = { 1e-9, 0 , 0,
0 , 1e-9, 0,
0 , 0 , 1e-9 };
msgmag.magnetic_field_covariance = { 1e-6, 0 , 0,
0 , 1e-6, 0,
0 , 0 , 1e-6 };
error_counter = 0;
}
~ROS_UART_Rx(){}
void CheckReceiveBuffer(){
if(UART_Rx::ReadBuffer()){
//read data into stringstream
dataStream.str(std::string(UART_Rx::rx_buffer));
//extract data into numerical variables
dataStream >> xmag >> zmag >> ymag >> xlin >> ylin >> zlin >> xang >> yang >> zang;
/*
//compose mag message
msgmag.magnetic_field.x = xmag;//(xmag/2047)*MAGNETOMETER_SCALE_RANGE;
msgmag.magnetic_field.y = ymag;//(ymag/2047)*MAGNETOMETER_SCALE_RANGE;
msgmag.magnetic_field.z = zmag;//(zmag/2047)*MAGNETOMETER_SCALE_RANGE;
//compose IMU message
msgimu.linear_acceleration.x = xlin;//((xlin+(X_ACCEL_OFFSET))/32767)*ACCEL_SCALE_RANGE*9.81;
msgimu.linear_acceleration.y = ylin;//((ylin+(Y_ACCEL_OFFSET))/32767)*ACCEL_SCALE_RANGE*9.81;
msgimu.linear_acceleration.z = zlin;//((zlin+(Z_ACCEL_OFFSET))/32767)*ACCEL_SCALE_RANGE*9.81;
msgimu.angular_velocity.x = xang;//((xang+(X_GYRO_OFFSET))/32767)*(GYRO_SCALE_RANGE)*(2*3.14159/360);
msgimu.angular_velocity.y = yang;//((yang+(Y_GYRO_OFFSET))/32767)*(GYRO_SCALE_RANGE)*(2*3.14159/360);
msgimu.angular_velocity.z = zang;//((zang+(Z_GYRO_OFFSET))/32767)*(GYRO_SCALE_RANGE)*(2*3.14159/360);
*/
//compose mag message
msgmag.magnetic_field.x = (ymag/2047)*MAGNETOMETER_SCALE_RANGE;
msgmag.magnetic_field.y = (-xmag/2047)*MAGNETOMETER_SCALE_RANGE;
msgmag.magnetic_field.z = (zmag/2047)*MAGNETOMETER_SCALE_RANGE;
//compose IMU message
msgimu.linear_acceleration.x = ((xlin+(X_ACCEL_OFFSET))/32767)*ACCEL_SCALE_RANGE*9.81;
msgimu.linear_acceleration.y = ((ylin+(Y_ACCEL_OFFSET))/32767)*ACCEL_SCALE_RANGE*9.81;
msgimu.linear_acceleration.z = ((zlin+(Z_ACCEL_OFFSET))/32767)*ACCEL_SCALE_RANGE*9.81;
msgimu.angular_velocity.x = ((xang+(X_GYRO_OFFSET))/32767)*(GYRO_SCALE_RANGE)*(2*3.14159/360);
msgimu.angular_velocity.y = ((yang+(Y_GYRO_OFFSET))/32767)*(GYRO_SCALE_RANGE)*(2*3.14159/360);
msgimu.angular_velocity.z = ((zang+(Z_GYRO_OFFSET))/32767)*(GYRO_SCALE_RANGE)*(2*3.14159/360);
// printf("Publikuje\n");
//publish
pubimu.publish(msgimu);
pubmag.publish(msgmag);
//zero out the buffer, as we don't need the data anymore
bzero(UART_Rx::rx_buffer, sizeof(UART_Rx::rx_buffer));
}
else{
ROS_FATAL("IMU ERROR - Cant read buffer");
error_counter++;
if(error_counter > 5){
exit(-1);
}
}
}
};
#endif
|
9d676ca6f98edc1da0c3219c0c5893162ecacfc6 | 056a35a213f0f146e37394aba99109b93d16834b | /WT_Show/show/core/monitor/monitor_window.cpp | 231988f5515543d4281b3738aef51888b202c3ab | [] | no_license | wiali/video_record | 45e2e7e126448cd2408ac5dbae1703975cabbff6 | 5d2c9d3b3d6bca9d771b1b9bf434ae5369d3f501 | refs/heads/master | 2021-07-22T12:59:25.084905 | 2017-11-01T10:06:16 | 2017-11-01T10:06:16 | 103,298,379 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,446 | cpp | monitor_window.cpp | #include "monitor_window.h"
#include "ui_monitor_window.h"
#include <QGuiApplication>
#include <QScreen>
#include <QClipboard>
#include <QStyle>
#include <QDesktopWidget>
#include <stage_item_form.h>
#include <global_utilities.h>
#include "styled_message_box.h"
#include "event/stop_video_streaming_event.h"
#include "event/change_application_state_event.h"
#include "event/clean_event.h"
#include "common/utilities.h"
#include "monitor/camera_right_menu_form.h"
#include "monitor/export_progress_dialog.h"
namespace capture {
namespace monitor {
MonitorWindow::MonitorWindow(QSharedPointer<model::ApplicationStateModel> model,
QSharedPointer<components::LiveVideoStreamCompositor> compositor,
QWidget* parent)
: BaseWindow(model, parent)
, ui(new Ui::MonitorWindow)
, m_compositor(compositor)
, m_imageFilter(new image_filters::ImageFilter)
, m_worktoolsLauncher(new components::WorktoolsLauncher)
, m_matModeStateMachine(new components::MatModeStateMachine)
, m_cameraManager(new components::VideoSourceManager(model))
, m_segmentationEngine(new components::DocumentModeProcessor)
, m_stageProjectExporter(new components::StageProjectExporter(model->projectsExport()))
, m_cleanEnvironment(new components::CleanEnvironment)
, m_isMinimizing(false)
, m_shutterMask(nullptr) {
// have Qt setup the UI Form baed on the .UI file for us
ui->setupUi(this);
// set menus and main widget
setLeftMenu(ui->left_menu);
setRightMenu(ui->right_menu);
setMainView(ui->center_right_widget);
m_matModeStateMachine->setModel(model);
configureCameras();
m_exportImageProcessor.reset(new components::ExportImageProcessor(model->projectsExport()));
qRegisterMetaType<QList<QUrl>>();
connect(m_exportImageProcessor.data(), &components::ExportImageProcessor::clipboardUrlsReady, this, &MonitorWindow::onClipboardUrlsReady);
ui->videoWidget->setModel(model->liveCapture(), compositor);
ui->left_menu->setModel(model);
ui->right_menu->setModel(model);
ui->right_menu->setEditTargetWidget(ui->stageViewer);
ui->cameraInUseWidget->setModel(model);
ui->noCalibrationDataForm->setModel(model);
ui->zoomIndicator->setModel(model);
//ui->exportForm->setModel(model->projectsExport());
ui->clipboardExportFinishedNotificationWidget->setModel(model);
ui->colorCalibrationForm->setModel(model);
ui->keystoneCornersIndicatorWidget->setModel(model, compositor);
BaseWindow::init(ui->stageViewer);
connect(ui->right_menu, &SharedRightMenuForm::rolled, this, &MonitorWindow::onRightMenuRoll);
connect(ui->right_menu, &SharedRightMenuForm::unrolled, this, &MonitorWindow::onRightMenuRoll);
//used to notify crop stageViewer size changed
connect(ui->stageViewer, &StageViewer::sizeChanged, this, &MonitorWindow::onStageViewerSizeChanged);
connect(m_model.data(), &model::ApplicationStateModel::matModeStateChanged, this, &MonitorWindow::onMatModeStateChanged);
onMatModeStateChanged(m_model->matModeState());
connect(m_model.data(), &model::ApplicationStateModel::modeChanged, this, &MonitorWindow::onApplicationModeChanged);
onApplicationModeChanged(m_model->mode());
connect(model->projects().data(), &model::ObservableStageProjectCollection::added, this, &MonitorWindow::onProjectCountChanged);
connect(model->projects().data(), &model::ObservableStageProjectCollection::removed, this, &MonitorWindow::onProjectCountChanged);
connect(model->projectsExport().data(), &model::ProjectsExportModel::stateChanged, this, &MonitorWindow::onProjectsExportStateChanged);
connect(model->liveCapture().data(), &model::LiveCaptureModel::captureStateChanged, this, &MonitorWindow::onCaptureStateChanged);
connect(this, &MonitorWindow::monitorWindowResized, ui->right_menu, &CameraRightMenuForm::setupAnimation);
resizeElements(geometry().size());
restoreWindowSettings();
updateMainWindowLocation();
auto captureModeEvent = new event::ChangeMatModeEvent(model->mainWindowLocation() == model::ApplicationStateModel::MainWindowLocation::None ?
event::ChangeMatModeEvent::LampOff : event::ChangeMatModeEvent::Desktop);
captureModeEvent->dispatch();
connect(m_stageProjectExporter.data(), &components::StageProjectExporter::exportFailed, this, &MonitorWindow::onExportFailed);
connect(m_exportImageProcessor.data(), &components::ExportImageProcessor::exportFailed, this, &MonitorWindow::onExportFailed);
auto settings = GlobalUtilities::applicationSettings("clean");
if (settings->value("clean_dmp", false).toBool()) {
auto cleanEvent = new event::CleanEvent();
cleanEvent->dispatch();
}
m_shutterMask = new QWidget(this);
m_shutterMask->setStyleSheet("background-color: black");
m_shutterMask->hide();
}
StageViewer* MonitorWindow::stageViewer() const { return ui->stageViewer; }
common::InkLayerWidget* MonitorWindow::inkLayerWidget() { return m_inkLayerWidget.data(); }
MonitorWindow::~MonitorWindow() {
QClipboard* clipboard = QApplication::clipboard();
if(clipboard->ownsClipboard()) {
qInfo() << this << "The clipboard has capture data, clean it!";
clipboard->clear();
}
m_matModeStateMachine->abort();
m_frameCapture->abort();
auto stopStreamsEvent = new event::StopVideoStreamingEvent();
stopStreamsEvent->dispatch();
delete ui;
}
void MonitorWindow::onProjectsExportStateChanged(model::ProjectsExportModel::State state)
{
// Clipboard UI notification is handled by notification
auto projectsExport = model()->projectsExport();
if (state == model::ProjectsExportModel::State::PrepairingToExport &&
projectsExport->format() != model::ProjectsExportModel::Format::Clipboard) {
if(!common::Utilities::isStageWorkToolInstalled() &&
projectsExport->format() == model::ProjectsExportModel::Format::Stage) {
return;
}
ExportProgressDialog dialog(this);
// Make sure that dialog is centered
auto dialogCenter = dialog.mapToGlobal(dialog.rect().center());
auto parentWindowCenter = mapToGlobal(rect().center());
dialog.move(parentWindowCenter - dialogCenter);
dialog.setModel(projectsExport);
dialog.exec();
}
}
bool MonitorWindow::restoreWindowSettings() {
bool result = false;
auto settings = GlobalUtilities::applicationSettings("monitor_window");
auto geometry = settings->value("geometry");
auto state = settings->value("state");
result = !geometry.isNull();
if (result) {
restoreGeometry(geometry.toByteArray());
} else {
if (auto verticalScreen = GlobalUtilities::findScreen(GlobalUtilities::MonitorScreen)) {
qDebug() << this << "Available vertical screen geometry" << verticalScreen->availableGeometry();
auto geometry = QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, size(),
verticalScreen->availableGeometry());
qDebug() << this << "No settings detected, setting window position to" << geometry;
setGeometry(geometry);
} else {
qWarning() << this << "Cannot find vertical screen";
}
}
if (!state.isNull()) {
restoreState(state.toByteArray());
}
return result;
}
void MonitorWindow::saveWindowSettings() {
auto settings = GlobalUtilities::applicationSettings("monitor_window");
settings->setValue("geometry", saveGeometry());
settings->setValue("state", saveState());
}
void MonitorWindow::updateMainWindowLocation() {
auto monitor = monitorScreen();
auto mat = matScreen();
auto present = presentScreen();
if(monitor) {
QRect geometry = monitor->geometry().intersected(this->geometry());
float ratio = (float)geometry.width()*geometry.height() / width() / height();
if(ratio > 0.5)
m_model->setMainWindowLocation(model::ApplicationStateModel::MainWindowLocation::None);
}
if(mat) {
QRect geometry = mat->geometry().intersected(this->geometry());
float ratio = (float)geometry.width()*geometry.height() / width() / height();
if(ratio > 0.5)
m_model->setMainWindowLocation(model::ApplicationStateModel::MainWindowLocation::MonitorOnMat);
}
if(present) {
QRect geometry = present->geometry().intersected(this->geometry());
float ratio = (float)geometry.width()*geometry.height() / width() / height();
if(ratio > 0.5)
m_model->setMainWindowLocation(model::ApplicationStateModel::MainWindowLocation::MonitorOnExtend);
}
}
void MonitorWindow::onClipboardUrlsReady(QList<QUrl> urls) {
// Qt's Clipboard needs to be invoked on main UI thread so we need to do this roundtrip ...
auto clipboard = QApplication::clipboard();
QMimeData* mimeData = new QMimeData();
mimeData->setUrls(urls);
clipboard->clear();
clipboard->setMimeData(mimeData);
}
void MonitorWindow::resizeEvent(QResizeEvent* event) {
BaseWindow::resizeEvent(event);
QPoint zoomIndicatorTopLeft((m_mainView->width() - ui->zoomIndicator->width()) / 2, ui->zoomIndicator->pos().y());
ui->zoomIndicator->move(m_mainView->pos() + zoomIndicatorTopLeft);
QPoint clipboardExportFinishedTopLeft((ui->top_widget->width() - ui->clipboardExportFinishedNotificationWidget->width()) / 2,
(ui->top_widget->height() - ui->clipboardExportFinishedNotificationWidget->height()) / 2);
ui->clipboardExportFinishedNotificationWidget->move(clipboardExportFinishedTopLeft);
onRightMenuRoll();
if (m_shutterMask) {
m_shutterMask->setGeometry(ui->center_right_widget->geometry());
}
ui->keystoneCornersIndicatorWidget->setGeometry(ui->center_right_widget->geometry());
emit monitorWindowResized();
}
void MonitorWindow::onRightMenuRoll() {
QPoint presentationMonitorTopLeft((width() - ui->presentationMonitorNotificationWidget->width()) / 2, 30);
ui->presentationMonitorNotificationWidget->move(presentationMonitorTopLeft);
}
void MonitorWindow::onSingleInstanceReceivedArguments(const QStringList &arguments) {
const auto parameters = common::Utilities::parseCommandLine(arguments);
const QString stageGUID = "133D6F29-5F4E-4600-BBB0-2B11EFEA0148";
if(parameters.first == common::Utilities::Ok && parameters.second.launchedFrom == stageGUID) {
if(m_model->mode() == model::ApplicationStateModel::Mode::Preview ||
m_model->mode() == model::ApplicationStateModel::Mode::LiveCapture) {
m_model->setSendToStageMode(true);
m_model->liveCapture()->inkData()->clear();
m_model->setMode(model::ApplicationStateModel::Mode::LiveCapture);
auto captureModeEvent = new event::ChangeMatModeEvent(event::ChangeMatModeEvent::MatMode::LampOff);
captureModeEvent->dispatch();
}
}
common::Utilities::bringToTopmost(winId());
}
void MonitorWindow::onDisplayCountChanged(int screenCount) {
BaseWindow::onDisplayCountChanged(screenCount);
updateMainWindowLocation();
if(m_model->mainWindowLocation() == model::ApplicationStateModel::MainWindowLocation::MonitorOnExtend) {
QRect rect = QApplication::desktop()->availableGeometry();
int x = rect.x() + (rect.width() - width()) / 2;
int y = rect.y() + (rect.height() - height()) / 2;
x = x > rect.x() ? x : rect.x();
y = y > rect.y() ? y : rect.y();
showNormal();
move(x, y);
}
}
void MonitorWindow::changeEvent(QEvent* event) {
BaseWindow::changeEvent(event);
if (event->type() == QEvent::WindowStateChange) {
bool isMinimizing = windowState().testFlag(Qt::WindowMinimized);
// When minimizing and presentation mode is on then do nothing
// Otherwise switch to Desktop mode
if (isMinimizing && !m_model->presentationMode()) {
m_model->setMatModeState(model::ApplicationStateModel::MatModeState::Desktop);
auto event = new event::ChangeMatModeEvent(event::ChangeMatModeEvent::MatMode::Desktop);
event->dispatch();
}
if(m_isMinimizing && !isMinimizing) {
auto event = new event::ChangeMatModeEvent(common::Utilities::MatModeStateToMatMode(m_model->matModeState()));
event->dispatch();
}
if(m_model->liveCapture()->captureState() == model::LiveCaptureModel::CaptureState::NotCapturing) {
auto event = new event::ChangeApplicationStateEvent(isMinimizing);
event->dispatch();
}
m_isMinimizing = isMinimizing;
}
}
void MonitorWindow::onScreenGeometryChanged(const QRect& geometry) {
int x = (geometry.width() - frameSize().width()) / 2;
int y = (geometry.height() - frameSize().height()) / 2;
y = y < 40 ? 0 : y;
move(geometry.x() + x, geometry.y() + y);
}
void MonitorWindow::configureCameras() {
auto outputSinkConfig = m_compositor->videoPipeline()->outputSinkConfiguration();
// Don't stream to DirectShow virtual camera
outputSinkConfig.name = QString();
// Don't include compositor
outputSinkConfig.size = QSize();
m_compositor->videoPipeline()->setOutputSinkConfiguration(outputSinkConfig);
for(auto videoStreamSource : m_model->liveCapture()->videoStreamSources()) {
switch(videoStreamSource->videoSource().type) {
case common::VideoSourceInfo::SourceType::DownwardFacingCamera: {
auto settings = GlobalUtilities::applicationSettings("downward_facing_camera");
videoStreamSource->setSkipFrameCount(settings->value("skip_first_frames_count", 5).toInt());
videoStreamSource->setFrameFreezeDetectionTimeout(settings->value("video_freeze_detection_timeout", 3000).toInt());
break;
}
case common::VideoSourceInfo::SourceType::SproutCamera: {
auto settings = GlobalUtilities::applicationSettings("sprout_camera");
videoStreamSource->setFrameFreezeDetectionTimeout(settings->value("video_freeze_detection_timeout", 3000).toInt());
break;
}
}
}
m_videoSourceInput = QSharedPointer<components::VideoSourceInput>::create(m_compositor, m_imageFilter, model());
m_frameCapture.reset(new components::FrameCapture(m_compositor, model()));
connect(m_frameCapture.data(), &components::FrameCapture::captureFailed, this, &MonitorWindow::onCaptureFailed);
}
void MonitorWindow::onCaptureFailed() {
// SPROUT-19362
qWarning() << this << "Capture has failed, restarting the cameras";
auto messageBox = common::Utilities::createMessageBox();
messageBox->setText(tr("Capture failed"));
messageBox->setInformativeText(tr("Unable to capture frames from hardware devices, please try again."));
messageBox->addStyledButton(tr("OK"), QMessageBox::YesRole);
messageBox->exec();
m_model->setMode(model::ApplicationStateModel::Mode::None);
m_model->setMode(model::ApplicationStateModel::Mode::LiveCapture);
}
void MonitorWindow::onApplicationModeChanged(model::ApplicationStateModel::Mode mode) {
static QMap<model::ApplicationStateModel::Mode, int> tabIndexMap = {
{ model::ApplicationStateModel::Mode::None, -1 },
{ model::ApplicationStateModel::Mode::LiveCapture, 0 },
{ model::ApplicationStateModel::Mode::Preview, 1 },
{ model::ApplicationStateModel::Mode::CameraFailedToStart, 2 },
{ model::ApplicationStateModel::Mode::NoCalibrationData, 3 },
{ model::ApplicationStateModel::Mode::NoVideoSource, 4},
{ model::ApplicationStateModel::Mode::ColorCorrectionCalibration, 5 },
{ model::ApplicationStateModel::Mode::KeystoneCorrectionCalibration, 0},
};
const auto tabIndex = tabIndexMap[mode];
if (tabIndex >= 0) {
ui->centralAreaStackedWidget->setCurrentIndex(tabIndex);
// In case that window was minimized we want to bring it forward
if (windowState().testFlag(Qt::WindowMinimized)) {
setWindowState(Qt::WindowActive);
}
}
ui->videoWidget->setViewportManipulationEnabled(mode != model::ApplicationStateModel::Mode::KeystoneCorrectionCalibration);
ui->videoWidget->setViewportEnabled(mode != model::ApplicationStateModel::Mode::KeystoneCorrectionCalibration);
}
void MonitorWindow::moveEvent(QMoveEvent* event) {
updateMainWindowLocation();
BaseWindow::moveEvent(event);
}
void MonitorWindow::closeEvent(QCloseEvent* event) {
common::Utilities::processCloseEvent(event, model());
if (event->isAccepted()) {
saveWindowSettings();
emit closing();
BaseWindow::closeEvent(event);
}
}
void MonitorWindow::onMatModeStateChanged(model::ApplicationStateModel::MatModeState state) {
Q_UNUSED(state);
activateWindow();
raise();
}
QScreen* MonitorWindow::findOwnScreen() {
switch(m_model->mainWindowLocation()) {
case model::ApplicationStateModel::MainWindowLocation::None:
return GlobalUtilities::findScreen(GlobalUtilities::MonitorScreen);
case model::ApplicationStateModel::MainWindowLocation::MonitorOnMat:
return GlobalUtilities::findScreen(GlobalUtilities::MatScreen);
case model::ApplicationStateModel::MainWindowLocation::MonitorOnExtend:
return GlobalUtilities::findScreen(GlobalUtilities::PresentScreen);
}
Q_UNREACHABLE();
}
void MonitorWindow::onExportFailed(const QString& msg) {
qInfo() << this << "Export failed with reason" << msg;
auto messageBox = common::Utilities::createMessageBox();
messageBox->setText(tr("Failed to export"));
messageBox->setInformativeText(tr("Unable to export captures. Please check the disk space and try again."));
messageBox->addStyledButton(tr("OK"), QMessageBox::YesRole);
messageBox->exec();
}
void MonitorWindow::onProjectCountChanged() {
if (GlobalUtilities::applicationSettings("monitor_window")->value("show_debug_info", false).toBool()) {
const auto title = QString("Captures: %1, version: %2, %3")
.arg(m_model->projects()->count())
.arg(QApplication::instance()->applicationVersion())
.arg(m_model->singleScreenMode() ? "single screen mode" : "Sprout mode");
setWindowTitle(title);
}
}
void MonitorWindow::onCaptureStateChanged(model::LiveCaptureModel::CaptureState captureState) {
if (captureState == model::LiveCaptureModel::CaptureState::Capturing &&
// SPROUTSW-4652 - don't show shutter mask if we are capturing primary desktop
!m_model->liveCapture()->selectedVideoStreamSources().contains(common::VideoSourceInfo::PrimaryDesktop())) {
m_shutterMask->show();
// Make sure that shutter mask will be visible only for predefined duration
QTimer::singleShot(GlobalUtilities::applicationSettings("monitor_window")->value("shutter_mask_duration", 100).toInt(),
m_shutterMask, &QWidget::hide);
} else {
m_shutterMask->hide();
}
}
void MonitorWindow::onStageViewerSizeChanged(QSize size)
{
emit stageViewerSizeChanged(size);
}
} // namespace monitor
} // namespace capture
|
0bd56d7aa4cc426640c856ffa9ad49b18b574163 | 915b1b271c222273c9c914ea5bd7bf6fd3239d6f | /math_functions.h | 760e578c430aae1874ed5fa779ba6ce3925cb8aa | [] | no_license | bingxinhu/TensorRT-SSD-1 | f6015ec2ff88a8dd387e8b705f553b4e5c40394b | c0455174addcd76db9da98dc3738ca2d46c476be | refs/heads/master | 2021-09-22T22:30:19.134693 | 2018-09-18T02:44:38 | 2018-09-18T02:44:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 674 | h | math_functions.h | #ifndef __MATH_FUNCTINS_H__
#define __MATH_FUNCTINS_H__
#include <stdint.h>
#include <cmath> // for std::fabs and std::signbit
#include <cblas.h>
#include <cudnn.h>
#include <cublas_v2.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <curand.h>
#include <driver_types.h> // cuda driver types
#include <algorithm>
#include <glog/logging.h>
#define TENSORRT_BLOCK 512
inline int TENSORRT_GET_BLOCKS(const int N) {
return (N + TENSORRT_BLOCK - 1) / TENSORRT_BLOCK;
}
cudaError_t PReLUForward(const int count, const int channels, const int dim, const float* bottom_data,
float* top_data, void* mDeviceKernel, const int div_factor);
#endif |
2c6d805ac32728335a109a2d71114a35bd116447 | 8209a87ad129ec85e66e0e654b3c94cc1e840d4c | /estrutura-sequencial/exercicio-25.cpp | 2964fafa094d7ae631f59d489632f42d1a35ea64 | [] | no_license | fraterblack/exercicios-algoritimos | 85ef053d2007664dbe286b8bc2d93d17c15c1d15 | 561a492ff47deb039897831d1a66b82700b7426c | refs/heads/master | 2020-05-24T20:53:44.393913 | 2017-03-27T23:44:54 | 2017-03-27T23:44:54 | 84,879,955 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 761 | cpp | exercicio-25.cpp | #include<stdio.h>
#include<conio.h>
#include<locale.h>
#include<math.h>
main () {
setlocale(LC_ALL, "Portuguese");
float totalDespesa, totalGorjeta;
printf("Informe o total da despesa (R$): ");
scanf("%f", &totalDespesa);
totalGorjeta = totalDespesa * 0.1;
printf("********* Total do Pedido *********\nTotal despesas ................. %.2f \nGorjeta Garçom ................. %.2f \nTotal do Pedido ................ %.2f", totalDespesa, totalGorjeta, (totalDespesa + totalGorjeta));
getch();
}
/*
25. Todo restaurante, embora por lei não possa obrigar o cliente a pagar, cobra 10% para o garçom.
Elabore um algoritmo que leia o valor gasto com despesas realizadas em um restaurante, e imprima
o valor total com a gorjeta.
*/
|
7fc5c788533c019277f390b86fb20dbd831a33bd | a8804f93227e46fd41ac9c6c4ba7e91ee5bf6a93 | /uva/10401/10401.cpp | 852fdfd53c1316d77c19c0a32dfe754eaf2e2141 | [] | no_license | caioaao/cp-solutions | 9a2b3552a09fbc22ee8c3494d54ca1e7de7269a9 | 8a2941a394cf09913f9cae85ae7aedfafe76a43e | refs/heads/master | 2021-01-17T10:22:27.607305 | 2020-07-04T15:37:01 | 2020-07-04T15:37:01 | 35,003,033 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,253 | cpp | 10401.cpp | #include <iostream>
#include <algorithm>
#include <cstring>
#define MAX_N 16
using namespace std;
typedef long long ll;
int pos[MAX_N], N;
ll memo[MAX_N][MAX_N];
ll dp(int col, int lastCol){
if(col == N) return 1;
if(memo[col][lastCol] != -1) return memo[col][lastCol];
if(pos[col] != -1){
if(pos[col] >= lastCol -1 && pos[col] <= lastCol+1){
return memo[col][lastCol] = 0;
}
return memo[col][lastCol] = dp(col+1,pos[col]);
}
memo[col][lastCol] = 0;
for(int i = 0; i < N; i++){
if(i >= lastCol - 1 && i <= lastCol+1) continue;
memo[col][lastCol] += dp(col+1, i);
}
return memo[col][lastCol];
}
int main(){
string s;
while(cin >> s){
N = s.length();
memset(memo, -1, sizeof memo);
for(int i = 0; i < N; i++){
switch(s[i]){
case '?':
pos[i] = -1;
break;
case 'A':
pos[i] = 9;
break;
case 'B':
pos[i] = 10;
break;
case 'C':
pos[i] = 11;
break;
case 'D':
pos[i] = 12;
break;
case 'E':
pos[i] = 13;
break;
case 'F':
pos[i] = 14;
break;
default:
pos[i] = s[i]-'0'-1;
}
}
ll ans = 0;
if(pos[0] == -1){
for(int i = 0; i < N; i++)
ans += dp(1,i);
}
else
ans = dp(1,pos[0]);
cout << ans << '\n';
}
}
|
14b5bac50417ecd337568016b0083976485e869e | 0577a46d8d28e1fd8636893bbdd2b18270bb8eb8 | /notes/deprecated_note_attachment.cc | 4a0ba0354582c275d9d61e6a5553ae0cff267ece | [
"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 | 1,913 | cc | deprecated_note_attachment.cc | // Copyright (c) 2013-2015 Vivaldi Technologies AS. All rights reserved
#include <string>
#include "base/base64.h"
#include "base/guid.h"
#include "base/json/json_string_value_serializer.h"
#include "base/memory/ptr_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/values.h"
#include "crypto/sha2.h"
#include "notes/deprecated_note_attachment.h"
#include "notes/notes_codec.h"
namespace vivaldi {
DeprecatedNoteAttachment::~DeprecatedNoteAttachment() = default;
DeprecatedNoteAttachment::DeprecatedNoteAttachment(const std::string& content)
: content_(content) {
if (content.empty())
return;
base::Base64Encode(crypto::SHA256HashString(content), &checksum_);
checksum_ += "|" + base::NumberToString(content.size());
}
DeprecatedNoteAttachment::DeprecatedNoteAttachment(const std::string& checksum,
const std::string& content)
: checksum_(checksum), content_(content) {}
DeprecatedNoteAttachment::DeprecatedNoteAttachment(DeprecatedNoteAttachment&&) =
default;
DeprecatedNoteAttachment& DeprecatedNoteAttachment::operator=(
DeprecatedNoteAttachment&&) = default;
std::unique_ptr<DeprecatedNoteAttachment> DeprecatedNoteAttachment::Decode(
const base::Value& input,
NotesCodec* checksummer) {
DCHECK(input.is_dict());
DCHECK(checksummer);
const std::string* checksum = input.FindStringKey("checksum");
const std::string* content = input.FindStringKey("content");
if (!content)
return nullptr;
checksummer->UpdateChecksum(*content);
std::unique_ptr<DeprecatedNoteAttachment> attachment;
if (checksum) {
checksummer->UpdateChecksum(*checksum);
attachment =
std::make_unique<DeprecatedNoteAttachment>(*checksum, *content);
} else {
attachment = std::make_unique<DeprecatedNoteAttachment>(*content);
}
return attachment;
}
} // namespace vivaldi
|
73f449d996dda9c4b4b25a273df19dda93f03bb8 | 2f8a14f20718b2ecd2c1b6d7d2e9def877e48b1f | /leetcode/remove_duplicates_from_sorted_array/cpp/solution.cc | cb5765a27fe20a8fbdcd94877a631da8a1686d63 | [] | no_license | amazonsx/archives | 5aa9441aa7689b8af9d33a9a7fefd381c08a569b | e6618ad50ced9aa9e90e4d989b97a3377e92af9c | refs/heads/master | 2021-01-10T18:46:08.536119 | 2014-11-23T06:49:06 | 2014-11-23T06:49:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 782 | cc | solution.cc | #include <iostream>
#define DEBUG
using namespace std;
class Solution {
public:
int removeDuplicates(int A[], int n);
};
int Solution::removeDuplicates(int A[], int n) {
if (n <= 1) return n;
int j = 0;
for ( int i = 1; i < n; i ++) {
if (A[i] != A[j]) {
A[++j] = A[i];
}
}
return j+1;
}
int main(int argc, char *argv[]) {
//int A[] = { -3, -1, 0, 0, 1, 3, 3, 4, 4, 4, 4 };
int A[] = { -3, -1, 0, 0};
for ( int i = 0; i < (signed)(sizeof(A)/sizeof(int)); i ++)
cout << A[i] << " " ;
cout << endl;
Solution s;
int size = s.removeDuplicates(A, sizeof(A)/sizeof(int));
cout << size << endl;
for ( int i = 0; i < size; i ++)
cout << A[i] << " " ;
cout << endl;
return 1;
}
|
9dfd75a0e2920836d122886a263206a627cebee8 | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/base/efiutil/efilib/inc/basesys.hxx | c101533433166fe80d13f73ec79e3f9c5e008a8c | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 932 | hxx | basesys.hxx | /*++
Copyright (c) 1991 Microsoft Corporation
Module Name:
basesys.hxx
Abstract:
BASE_SYSTEM is the a base class for SYSTEM. It is created so
encapsulate the methods on SYSTEM that are used for AUTOCHK.
Environment:
ULIB, User Mode
--*/
#if !defined( _BASE_SYSTEM_DEFN_ )
#define _BASE_SYSTEM_DEFN_
#include "message.hxx"
class BASE_SYSTEM {
public:
STATIC
ULIB_EXPORT
BOOLEAN
QueryResourceString(
OUT PWSTRING ResourceString,
IN MSGID MsgId,
IN PCSTR Format ...
);
STATIC
ULIB_EXPORT
BOOLEAN
QueryResourceStringV(
OUT PWSTRING ResourceString,
IN MSGID MsgId,
IN PCSTR Format,
IN va_list VarPointer
);
};
#endif // _BASE_SYSTEM_DEFN_
|
8382f0253d25e8ba855bf4d8d2ef64bf09a66f92 | 4b902f7cc86c128793f555cd03e38349a28ac4c6 | /dataset/cpp/USBox.cpp | afb6f07539f2aa97278963f5f82353e5df3eac29 | [] | no_license | korhankonaray/FileTypeDetector | bf763ad20992978a54a1484035398fe69f6edd71 | 2ab29f9433781c74f35206c1ab2ecb6c6689e263 | refs/heads/master | 2021-06-29T20:14:47.062064 | 2021-02-28T18:54:07 | 2021-02-28T18:54:07 | 206,796,718 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 11,190 | cpp | USBox.cpp | // Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved.
// http://getmoai.com
#include "pch.h"
#include <uslscore/USBox.h>
#include <uslscore/USPrism.h>
//================================================================//
// USBox
//================================================================//
//----------------------------------------------------------------//
float USBox::Area () const {
return ( this->mMax.mX - this->mMin.mX ) * ( this->mMax.mY - this->mMin.mY ) * ( this->mMax.mZ - this->mMin.mZ );
}
//----------------------------------------------------------------//
void USBox::Bless () {
if ( this->mMin.mX > this->mMax.mX ) {
float temp = this->mMin.mX;
this->mMin.mX = this->mMax.mX;
this->mMax.mX = temp;
}
if ( this->mMin.mY > this->mMax.mY ) {
float temp = this->mMin.mY;
this->mMin.mY = this->mMax.mY;
this->mMax.mY = temp;
}
if ( this->mMin.mZ > this->mMax.mZ ) {
float temp = this->mMin.mZ;
this->mMin.mZ = this->mMax.mZ;
this->mMax.mZ = temp;
}
}
//----------------------------------------------------------------//
void USBox::Clip ( const USBox& box ) {
// Clamp XMin
if ( this->mMin.mX < box.mMin.mX ) this->mMin.mX = box.mMin.mX;
if ( this->mMin.mX > box.mMax.mX ) this->mMin.mX = box.mMax.mX;
// Clamp XMax
if ( this->mMax.mX < box.mMin.mX ) this->mMax.mX = box.mMin.mX;
if ( this->mMax.mX > box.mMax.mX ) {
this->mMax.mX = box.mMax.mX;
}
// Clamp YMin
if ( this->mMin.mY < box.mMin.mY ) this->mMin.mY = box.mMin.mY;
if ( this->mMin.mY > box.mMax.mY ) this->mMin.mY = box.mMax.mY;
// Clamp YMax
if ( this->mMax.mY < box.mMin.mY ) this->mMax.mY = box.mMin.mY;
if ( this->mMax.mY > box.mMax.mY ) this->mMax.mY = box.mMax.mY;
// Clamp ZMin
if ( this->mMin.mZ < box.mMin.mZ ) this->mMin.mZ = box.mMin.mZ;
if ( this->mMin.mZ > box.mMax.mZ ) this->mMin.mZ = box.mMax.mZ;
// Clamp ZMax
if ( this->mMax.mZ < box.mMin.mZ ) this->mMax.mZ = box.mMin.mZ;
if ( this->mMax.mZ > box.mMax.mZ ) this->mMax.mZ = box.mMax.mZ;
}
//----------------------------------------------------------------//
bool USBox::Contains ( const USVec3D& loc ) const {
if (( loc.mX < mMin.mX ) || ( loc.mX > mMax.mX )) return false;
if (( loc.mY < mMin.mY ) || ( loc.mY > mMax.mY )) return false;
if (( loc.mZ < mMin.mZ ) || ( loc.mZ > mMax.mZ )) return false;
return true;
}
//----------------------------------------------------------------//
bool USBox::Contains ( const USVec3D& loc, u32 plane ) const {
switch ( plane ) {
default:
case PLANE_XY:
if (( loc.mX < mMin.mX ) || ( loc.mX > mMax.mX )) return false;
if (( loc.mY < mMin.mY ) || ( loc.mY > mMax.mY )) return false;
break;
case PLANE_XZ:
if (( loc.mX < mMin.mX ) || ( loc.mX > mMax.mX )) return false;
if (( loc.mZ < mMin.mZ ) || ( loc.mZ > mMax.mZ )) return false;
break;
case PLANE_YZ:
if (( loc.mY < mMin.mY ) || ( loc.mY > mMax.mY )) return false;
if (( loc.mZ < mMin.mZ ) || ( loc.mZ > mMax.mZ )) return false;
break;
}
return true;
}
//----------------------------------------------------------------//
void USBox::GetCenter ( USVec3D& center ) const {
center.mX = this->mMin.mX + (( this->mMax.mX - this->mMin.mX ) * 0.5f );
center.mY = this->mMin.mY + (( this->mMax.mY - this->mMin.mY ) * 0.5f );
center.mZ = this->mMin.mZ + (( this->mMax.mZ - this->mMin.mZ ) * 0.5f );
}
//----------------------------------------------------------------//
void USBox::GetFitting ( const USBox& target, USVec3D& offset, USVec3D& scale ) const {
float w = this->Width ();
float h = this->Height ();
float d = this->Depth ();
float tw = target.Width ();
float th = target.Height ();
float td = target.Depth ();
scale.mX = ( w != 0.0f ) && ( tw != 0.0f ) ? tw / w : 1.0f;
scale.mY = ( h != 0.0f ) && ( th != 0.0f ) ? th / h : 1.0f;
scale.mZ = ( d != 0.0f ) && ( td != 0.0f ) ? td / d : 1.0f;
offset.mX = target.mMin.mX - ( this->mMin.mX * scale.mX );
offset.mY = target.mMin.mY - ( this->mMin.mY * scale.mY );
offset.mZ = target.mMin.mZ - ( this->mMin.mZ * scale.mZ );
}
//----------------------------------------------------------------//
float USBox::GetMaxExtent () const {
float max = 0.0f;
float comp;
comp = ABS ( this->mMin.mX );
if ( max < comp ) max = comp;
comp = ABS ( this->mMin.mY );
if ( max < comp ) max = comp;
comp = ABS ( this->mMin.mZ );
if ( max < comp ) max = comp;
comp = ABS ( this->mMax.mX );
if ( max < comp ) max = comp;
comp = ABS ( this->mMax.mY );
if ( max < comp ) max = comp;
comp = ABS ( this->mMax.mZ );
if ( max < comp ) max = comp;
return max;
}
//----------------------------------------------------------------//
float USBox::GetRadius () const {
USVec3D spans = mMax;
spans.Sub ( mMin );
spans.Scale ( 0.5f );
return spans.Length ();
}
//----------------------------------------------------------------//
USRect USBox::GetRect ( u32 plane ) const {
USRect rect;
switch ( plane ) {
default:
case PLANE_XY:
rect.mXMin = this->mMin.mX;
rect.mXMax = this->mMax.mX;
rect.mYMin = this->mMin.mY;
rect.mYMax = this->mMax.mY;
break;
case PLANE_XZ:
rect.mXMin = this->mMin.mX;
rect.mXMax = this->mMax.mX;
rect.mYMin = this->mMin.mZ;
rect.mYMax = this->mMax.mZ;
break;
case PLANE_YZ:
rect.mXMin = this->mMin.mZ;
rect.mXMax = this->mMax.mZ;
rect.mYMin = this->mMin.mY;
rect.mYMax = this->mMax.mY;
break;
}
return rect;
}
//----------------------------------------------------------------//
void USBox::Grow ( const USBox& box ) {
if ( mMin.mX > box.mMin.mX ) mMin.mX = box.mMin.mX;
if ( mMax.mX < box.mMax.mX ) mMax.mX = box.mMax.mX;
if ( mMin.mY > box.mMin.mY ) mMin.mY = box.mMin.mY;
if ( mMax.mY < box.mMax.mY ) mMax.mY = box.mMax.mY;
if ( mMin.mZ > box.mMin.mZ ) mMin.mZ = box.mMin.mZ;
if ( mMax.mZ < box.mMax.mZ ) mMax.mZ = box.mMax.mZ;
}
//----------------------------------------------------------------//
void USBox::Grow ( const USVec3D& vec ) {
if ( mMin.mX > vec.mX ) mMin.mX = vec.mX;
else if ( mMax.mX < vec.mX ) mMax.mX = vec.mX;
if ( mMin.mY > vec.mY ) mMin.mY = vec.mY;
else if ( mMax.mY < vec.mY ) mMax.mY = vec.mY;
if ( mMin.mZ > vec.mZ ) mMin.mZ = vec.mZ;
else if ( mMax.mZ < vec.mZ ) mMax.mZ = vec.mZ;
}
//----------------------------------------------------------------//
void USBox::Inflate ( float size ) {
this->mMin.mX -= size;
this->mMin.mY -= size;
this->mMin.mZ -= size;
this->mMax.mX += size;
this->mMax.mY += size;
this->mMax.mZ += size;
}
//----------------------------------------------------------------//
void USBox::Init ( const USBox& box ) {
*this = box;
}
//----------------------------------------------------------------//
void USBox::Init ( const USPrism& prism ) {
this->mMin = prism.mLoc;
this->mMax = prism.mLoc;
// X Axis
if ( prism.mXAxis.mX < 0.0f ) this->mMin.mX += prism.mXAxis.mX;
else this->mMax.mX += prism.mXAxis.mX;
if ( prism.mYAxis.mX < 0.0f ) this->mMin.mX += prism.mYAxis.mX;
else this->mMax.mX += prism.mYAxis.mX;
if ( prism.mZAxis.mX < 0.0f ) this->mMin.mX += prism.mZAxis.mX;
else this->mMax.mX += prism.mZAxis.mX;
// Y Axis
if ( prism.mXAxis.mY < 0.0f ) this->mMin.mY += prism.mXAxis.mY;
else this->mMax.mY += prism.mXAxis.mY;
if ( prism.mYAxis.mY < 0.0f ) this->mMin.mY += prism.mYAxis.mY;
else this->mMax.mY += prism.mYAxis.mY;
if ( prism.mZAxis.mY < 0.0f ) this->mMin.mY += prism.mZAxis.mY;
else this->mMax.mY += prism.mZAxis.mY;
// Z Axis
if ( prism.mXAxis.mZ < 0.0f ) this->mMin.mZ += prism.mXAxis.mZ;
else this->mMax.mZ += prism.mXAxis.mZ;
if ( prism.mYAxis.mZ < 0.0f ) this->mMin.mZ += prism.mYAxis.mZ;
else this->mMax.mZ += prism.mYAxis.mZ;
if ( prism.mZAxis.mZ < 0.0f ) this->mMin.mZ += prism.mZAxis.mZ;
else this->mMax.mZ += prism.mZAxis.mZ;
}
//----------------------------------------------------------------//
void USBox::Init ( const USVec3D& vec ) {
mMin.mX = mMax.mX = vec.mX;
mMin.mY = mMax.mY = vec.mY;
mMin.mZ = mMax.mZ = vec.mZ;
}
//----------------------------------------------------------------//
void USBox::Init ( float left, float top, float right, float bottom, float back, float front ) {
this->mMin.mX = left;
this->mMax.mX = right;
this->mMax.mY = top;
this->mMin.mY = bottom;
this->mMin.mZ = back;
this->mMax.mZ = front;
}
//----------------------------------------------------------------//
bool USBox::IsPoint () {
if ( this->mMin.mX != this->mMax.mX ) return false;
if ( this->mMin.mY != this->mMax.mY ) return false;
if ( this->mMin.mZ != this->mMax.mZ ) return false;
return true;
}
//----------------------------------------------------------------//
void USBox::Offset ( const USVec3D& offset ) {
mMin.mX += offset.mX;
mMax.mX += offset.mX;
mMin.mY += offset.mY;
mMax.mY += offset.mY;
mMin.mZ += offset.mZ;
mMax.mZ += offset.mZ;
}
//----------------------------------------------------------------//
bool USBox::Overlap ( const USBox& box ) const {
if (( mMin.mX > box.mMax.mX ) || ( mMax.mX < box.mMin.mX )) return false;
if (( mMin.mY > box.mMax.mY ) || ( mMax.mY < box.mMin.mY )) return false;
if (( mMin.mZ > box.mMax.mZ ) || ( mMax.mZ < box.mMin.mZ )) return false;
return true;
}
//----------------------------------------------------------------//
bool USBox::Overlap ( const USBox& box, u32 plane ) const {
switch ( plane ) {
default:
case PLANE_XY:
if (( mMin.mX > box.mMax.mX ) || ( mMax.mX < box.mMin.mX )) return false;
if (( mMin.mY > box.mMax.mY ) || ( mMax.mY < box.mMin.mY )) return false;
break;
case PLANE_XZ:
if (( mMin.mX > box.mMax.mX ) || ( mMax.mX < box.mMin.mX )) return false;
if (( mMin.mZ > box.mMax.mZ ) || ( mMax.mZ < box.mMin.mZ )) return false;
break;
case PLANE_YZ:
if (( mMin.mY > box.mMax.mY ) || ( mMax.mY < box.mMin.mY )) return false;
if (( mMin.mZ > box.mMax.mZ ) || ( mMax.mZ < box.mMin.mZ )) return false;
break;
}
return true;
}
//----------------------------------------------------------------//
void USBox::Pad ( float pad ) {
this->mMin.mX -= pad;
this->mMin.mY -= pad;
this->mMin.mZ -= pad;
this->mMax.mX += pad;
this->mMax.mY += pad;
this->mMax.mZ += pad;
}
//----------------------------------------------------------------//
void USBox::Scale ( float scale ) {
mMin.mX *= scale;
mMax.mX *= scale;
mMin.mY *= scale;
mMax.mY *= scale;
mMin.mZ *= scale;
mMax.mZ *= scale;
}
//----------------------------------------------------------------//
void USBox::Scale ( const USVec3D& scale ) {
mMin.mX *= scale.mX;
mMax.mX *= scale.mX;
mMin.mY *= scale.mY;
mMax.mY *= scale.mY;
mMin.mZ *= scale.mZ;
mMax.mZ *= scale.mZ;
}
//----------------------------------------------------------------//
void USBox::Transform ( const USAffine3D& mtx ) {
USPrism prism;
prism.Init ( *this );
prism.Transform ( mtx );
this->Init ( prism );
}
//----------------------------------------------------------------//
void USBox::Transform ( const USMatrix4x4& mtx ) {
USPrism prism;
prism.Init ( *this );
prism.Transform ( mtx );
this->Init ( prism );
}
|
b4f7be739fb88f4a930f963dcaff274d2edcf89a | 3bbf11ba7a189cc6d1456908b5da8b2c902236c4 | /Test_Sketches/Test-LightSensor/Test-LightSensor.ino | c7a3c9205687fbadc22d71576243b705698f8ae8 | [] | no_license | growboxguy/Gbox420 | 6c5442642f2856a7c7ce1efcbc3cfec307ab569f | 2a69969146716a3bda25439ec05e00256f2de619 | refs/heads/master | 2023-07-20T17:28:35.953560 | 2021-07-05T10:36:11 | 2021-07-05T10:36:11 | 157,996,952 | 40 | 18 | null | 2020-02-16T21:54:50 | 2018-11-17T15:20:11 | C++ | UTF-8 | C++ | false | false | 849 | ino | Test-LightSensor.ino | //GrowBoxGuy - http://sites.google.com/site/growboxguy/
//Sketch for testing: Light sensor with analog and digital outputs
//Pins
const int DigitalPin = 4; // D0 digital input - LM393 light sensor
const int AnalogPin = A0; // A0 analog input - LM393 light sensor
void setup()
{
Serial.begin(115200);
Serial.println(F("Sketch for testing: Light sensor with analog and digital outputs"));
pinMode(DigitalPin, INPUT);
pinMode(AnalogPin, INPUT);
}
void loop()
{
bool isLightOn = !digitalRead(DigitalPin); // read the input pin: 1- light detected , light detected. Had to invert(!) signal from the sensor to make more sense.
if (isLightOn)
Serial.println(F("Light detected"));
else
Serial.println(F("Light not detected"));
Serial.print(F("Light intensity - "));
Serial.println(1023 - analogRead(AnalogPin));
delay(2000);
}
|
3788e078dd7505828f7d436dced4331d6c76fe41 | 9b9982d1089504b88cdd0b61861fe25ce071bea9 | /bst/bst1/bst1/sortedArrToBST.cpp | 9ab7daaec069d0b4bf2dfe10a8701b049a9557c0 | [] | no_license | swk333/recursion | 416d3634e136121d63b1fce479555614aad566cb | 2cfc09c41084e7a21cdb95e3ae96c3bfdc90643f | refs/heads/main | 2023-04-10T20:25:43.606057 | 2021-04-30T03:32:13 | 2021-04-30T03:32:13 | 328,837,269 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,293 | cpp | sortedArrToBST.cpp | #include <iostream>
#include <string>
#include <cmath>
#include <deque>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
class BinaryTree{
public:
int data;
BinaryTree* left;
BinaryTree* right;
BinaryTree(int value){ this->data = value;};
BinaryTree(int value, BinaryTree* left, BinaryTree* right){
this->data = value;
this->left = left;
this->right = right;
};
};
BinaryTree* sortedArrToBSTHelper(vector<int> numberList, int start, int end){
int mid = start + (end - start) / 2;
if(start>end){
return NULL;
}
BinaryTree* root = new BinaryTree(numberList[mid]);
root->left = sortedArrToBSTHelper(numberList, start, mid - 1);
root->right = sortedArrToBSTHelper(numberList, mid + 1, end);
return root;
}
BinaryTree* sortedArrToBST(vector<int> numberList){
//ここから書きましょう
BinaryTree* root = sortedArrToBSTHelper(numberList, 0, numberList.size()-1);
return root;
}
//異なる整数値で構成されるソート済みのリスト numberList が与えられるので、平衡二分探索木を作成し、その根ノードを返す、sortedArrToBST という関数を作成してください。
|
00f876a641e8c190d7d961b47757f03d7899b636 | d3bc4da66fcf059cbd3d05c2817f6d94bc0cf9d4 | /PoCTask/PoCTask/Window.h | 619dac5c7a17040a692a1e27bb629f0d72535c9f | [] | no_license | stanimir/ABirds | 9535d8aaa56fc8ddb6939d9d635d4998eedf40c1 | b0ec8a06246286617769184ead41fa0d9656d798 | refs/heads/master | 2023-06-25T01:43:31.294793 | 2023-06-18T15:18:49 | 2023-06-18T15:37:48 | 107,548,727 | 0 | 1 | null | 2023-06-18T15:37:49 | 2017-10-19T13:18:06 | C | UTF-8 | C++ | false | false | 510 | h | Window.h | #pragma once
#include <string>
#include <SDL.h>
using namespace std;
class Window
{
public:
Window(const string &title, int width, int height);
Window();
~Window();
inline bool isClosed() const {
return _closed;
}
// Detect and Do Something that was detect
void pollEvents();
void clear() const;
private:
bool init();
private:
string _title;
int _width = 900;
int _height = 563;
bool _closed = false;
SDL_Window *_window = nullptr;
protected:
SDL_Renderer *_renderer = nullptr;
};
|
7a3b4611ab97b700fa01a28de842277f3808125b | 8b9229ba6d43c5ae3cc9816003f99d8efe3d50a4 | /dp/util/StridedIterator.h | 1ad188a7f26f910df7ab8cd19fda153033782fe5 | [] | no_license | JamesLinus/pipeline | 02aef690636f1d215a135b971fa34a9e09a6b901 | 27322a5527deb69c14bd70dd99374b52709ae157 | refs/heads/master | 2021-01-16T22:14:56.899613 | 2016-03-22T10:39:59 | 2016-03-22T10:39:59 | 56,539,375 | 1 | 0 | null | 2016-04-18T20:22:33 | 2016-04-18T20:22:32 | null | UTF-8 | C++ | false | false | 10,163 | h | StridedIterator.h | // Copyright NVIDIA Corporation 2010
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#pragma once
#include <iterator>
namespace dp
{
namespace util
{
struct DummyPayload {};
/*******************/
/* StridedIterator */
/*******************/
template <typename ValueType, typename Payload = DummyPayload>
class StridedIterator : public std::iterator< std::input_iterator_tag, ValueType >
{
public:
StridedIterator();
StridedIterator( ValueType *basePtr, size_t strideInBytes, Payload = Payload() );
StridedIterator( const StridedIterator &rhs );
StridedIterator &operator=( const StridedIterator &rhs );
virtual ~StridedIterator() {}
ValueType &operator*();
ValueType &operator[](size_t index);
bool operator==(const StridedIterator &rhs) const; // compares only ptr!
bool operator!=(const StridedIterator &rhs) const; // compares only ptr!
StridedIterator operator+(int offset) const;
StridedIterator &operator++(); // pre-increment
StridedIterator operator++(int); //post-increment
typedef std::input_iterator_tag iterator_category;
typedef ValueType value_type;
protected:
ValueType *m_basePtr;
size_t m_strideInBytes;
Payload m_payload;
};
template <typename ValueType, typename Payload>
inline StridedIterator<ValueType, Payload>::StridedIterator( )
: m_basePtr(0)
, m_strideInBytes(0)
{
}
template <typename ValueType, typename Payload>
inline StridedIterator<ValueType, Payload>::StridedIterator( ValueType *basePtr, size_t strideInBytes, Payload payload )
: m_basePtr( basePtr )
, m_strideInBytes( strideInBytes )
, m_payload( payload )
{
}
template <typename ValueType, typename Payload>
inline StridedIterator<ValueType,Payload>::StridedIterator( const StridedIterator &rhs )
: m_basePtr( rhs.m_basePtr )
, m_strideInBytes( rhs.m_strideInBytes )
, m_payload( rhs.m_payload )
{
}
template <typename ValueType, typename Payload>
inline StridedIterator<ValueType,Payload> &StridedIterator<ValueType,Payload>::operator=( const StridedIterator &rhs )
{
m_basePtr = rhs.m_basePtr;
m_strideInBytes = rhs.m_strideInBytes;
m_payload = rhs.m_payload;
return *this;
}
template <typename ValueType, typename Payload>
ValueType &StridedIterator<ValueType,Payload>::operator*()
{
return *reinterpret_cast<ValueType *>(m_basePtr);
}
template <typename ValueType, typename Payload>
ValueType &StridedIterator<ValueType,Payload>::operator[](size_t index)
{
char *ptr = reinterpret_cast<char *>(m_basePtr);
ptr += m_strideInBytes * index;
return *reinterpret_cast<ValueType *>(ptr);
}
template <typename ValueType, typename Payload>
StridedIterator<ValueType,Payload> StridedIterator<ValueType,Payload>::operator+(int offset) const
{
char *ptr = reinterpret_cast<char *>(m_basePtr);
ptr += offset * m_strideInBytes;
return StridedIterator<ValueType, Payload>( ptr, m_strideInBytes, m_payload );
}
template <typename ValueType, typename Payload>
StridedIterator<ValueType,Payload> &StridedIterator<ValueType,Payload>::operator++()
{
char *ptr = reinterpret_cast<char *>(m_basePtr);
ptr += m_strideInBytes;
m_basePtr = reinterpret_cast<ValueType *>(ptr);
return *this;
}
template <typename ValueType, typename Payload>
StridedIterator<ValueType,Payload> StridedIterator<ValueType,Payload>::operator++(int)
{
StridedIterator copy(*this);
++(*this);
return copy;
}
template <typename ValueType, typename Payload>
bool StridedIterator<ValueType,Payload>::operator==( const StridedIterator<ValueType, Payload> &rhs ) const
{
return m_basePtr == rhs.m_basePtr;
}
template <typename ValueType, typename Payload>
bool StridedIterator<ValueType,Payload>::operator!=( const StridedIterator<ValueType, Payload> &rhs ) const
{
return m_basePtr != rhs.m_basePtr;
}
/************************/
/* StridedConstIterator */
/************************/
template <typename ValueType, typename Payload = DummyPayload>
class StridedConstIterator : public std::iterator< std::input_iterator_tag, ValueType >
{
public:
StridedConstIterator( );
StridedConstIterator( const ValueType *basePtr, size_t strideInBytes, Payload = Payload() );
StridedConstIterator( const StridedConstIterator &rhs );
StridedConstIterator &operator=( const StridedConstIterator &rhs );
virtual ~StridedConstIterator() {}
const ValueType &operator*() const;
const ValueType &operator[](size_t index) const;
bool operator==(const StridedConstIterator &rhs) const; // compares only ptr!
bool operator!=(const StridedConstIterator &rhs) const; // compares only ptr!
StridedConstIterator operator+(size_t offset) const;
StridedConstIterator &operator++(); // pre-increment
StridedConstIterator operator++(int); //post-increment
protected:
const ValueType *m_basePtr;
size_t m_strideInBytes;
Payload m_payload;
};
template <typename ValueType, typename Payload>
inline StridedConstIterator<ValueType, Payload>::StridedConstIterator( )
: m_basePtr(0)
, m_strideInBytes(0)
{
}
template <typename ValueType, typename Payload>
inline StridedConstIterator<ValueType, Payload>::StridedConstIterator( const ValueType *basePtr, size_t strideInBytes, Payload payload )
: m_basePtr( basePtr )
, m_strideInBytes( strideInBytes )
, m_payload( payload )
{
}
template <typename ValueType, typename Payload>
inline StridedConstIterator<ValueType,Payload>::StridedConstIterator( const StridedConstIterator &rhs )
: m_basePtr( rhs.m_basePtr )
, m_strideInBytes( rhs.m_strideInBytes )
, m_payload( rhs.m_payload )
{
}
template <typename ValueType, typename Payload>
inline StridedConstIterator<ValueType,Payload> &StridedConstIterator<ValueType,Payload>::operator=( const StridedConstIterator &rhs )
{
m_basePtr = rhs.m_basePtr;
m_strideInBytes = rhs.m_strideInBytes;
m_payload = rhs.m_payload;
return *this;
}
template <typename ValueType, typename Payload>
const ValueType &StridedConstIterator<ValueType,Payload>::operator*() const
{
return *reinterpret_cast<const ValueType *>(m_basePtr);
}
template <typename ValueType, typename Payload>
const ValueType &StridedConstIterator<ValueType,Payload>::operator[](size_t index) const
{
const char *ptr = reinterpret_cast<const char *>(m_basePtr);
ptr += m_strideInBytes * index;
return *reinterpret_cast<const ValueType *>(ptr);
}
template <typename ValueType, typename Payload>
StridedConstIterator<ValueType,Payload> StridedConstIterator<ValueType,Payload>::operator+( size_t offset ) const
{
const char *ptr = reinterpret_cast<const char *>(m_basePtr);
ptr += offset * m_strideInBytes;
return StridedConstIterator<ValueType, Payload>( reinterpret_cast<const ValueType *>(ptr), m_strideInBytes, m_payload );
}
template <typename ValueType, typename Payload>
StridedConstIterator<ValueType,Payload> &StridedConstIterator<ValueType,Payload>::operator++()
{
const char *ptr = reinterpret_cast<const char *>(m_basePtr);
ptr += m_strideInBytes;
m_basePtr = reinterpret_cast<const ValueType *>(ptr);
return *this;
}
template <typename ValueType, typename Payload>
StridedConstIterator<ValueType,Payload> StridedConstIterator<ValueType,Payload>::operator++(int)
{
StridedConstIterator copy(*this);
++(*this);
return copy;
}
template <typename ValueType, typename Payload>
bool StridedConstIterator<ValueType,Payload>::operator==( const StridedConstIterator<ValueType, Payload> &rhs ) const
{
return m_basePtr == rhs.m_basePtr;
}
template <typename ValueType, typename Payload>
bool StridedConstIterator<ValueType,Payload>::operator!=( const StridedConstIterator<ValueType, Payload> &rhs ) const
{
return m_basePtr != rhs.m_basePtr;
}
} //namespace util
} // namespace dp
|
ed1d4e6a813eaba8e7ce394e9a7590548294ca9a | dc83eeee7ff5312f432c2167f600e98136b50e1e | /nihtiu_alarm/defs.cpp | 4a3f35202d6ffc6ed9b426e69d9c27d00aa6f1ed | [
"MIT"
] | permissive | malvcr/nihtiu | 3dc4ad54ae2d5282dde89b83c2478ead7f1fc981 | f8e527f3dd8f5f9584336aeb71aa52b63ebb33d4 | refs/heads/master | 2021-04-03T20:34:47.298029 | 2020-05-11T05:12:04 | 2020-05-11T05:12:04 | 248,394,179 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 134 | cpp | defs.cpp | /**
* Nihtiu
*
* (c) 2020 Marco Alvarado
*
* This project has the MIT Licensing. Check the accompaining LICENSE file.
*
*/
|
a997c5cee6263d45365a2da19934cdd00d66a7c8 | b2c01a105dc1bbc2f1535ea6d781836ff9523d3b | /HW 05/BoardVector.h | 19b46c27778ebeaa1d3eacd59bf299b91641a5b6 | [
"MIT"
] | permissive | BerkP/CSE241-Object-Oriented-Programming | 748abe368647dae279dd2c564968f0a3b123ee6f | 4d9952a8257fd653bee46aa9fcbea57195137553 | refs/heads/main | 2023-03-16T02:55:19.130015 | 2021-03-11T12:21:13 | 2021-03-11T12:21:13 | 346,681,859 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 450 | h | BoardVector.h | #ifndef BOARDVECTOR_H
#define BOARDVECTOR_H
#include <vector>
#include "AbstractBoard.h"
using namespace std;
namespace GTU_PKGZ{
class BoardVector:public AbstractBoard{
public:
BoardVector();
/* Default constr */
BoardVector(int ,int);
void setSize(int rowInput,int columnInput) override;
virtual int& operator()(int ,int );
virtual const int& operator()(int ,int )const;
private:
vector<vector<int>> boardVec;
};
};
#endif |
a0ab36e7cddab588b67c55d817152afe7f0c86a3 | ecbf5821fdd3d108632c4fb7adf56844045479ec | /TransshipmentProject/NoTransshipmentApp_Solver.h | 68f6636e2c107df8b9409194b99f181bd5841036 | [] | no_license | OlgaRusyaeva/Transshipment | 339c338fc5f8280d7ef00a57f07eba230aa6f356 | 95964b0c756d5718c95b602bc205644bb6729682 | refs/heads/master | 2021-01-02T09:41:35.355276 | 2017-08-03T23:11:42 | 2017-08-03T23:11:42 | 99,280,382 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 656 | h | NoTransshipmentApp_Solver.h | //
// NoTransshipmentApp_Solver.h
// TransshipmentProject
//
// Created by Olga on 23/02/15.
//
//
#ifndef TransshipmentProject_NoTransshipmentApp_Solver_h
#define TransshipmentProject_NoTransshipmentApp_Solver_h
#include "NoTransshipment_Solver.h"
class State;
class Cost;
class Demand;
class NoTransshipmentApp_Solver: public NoTransshipment_Solver
{
public:
NoTransshipmentApp_Solver(const int& iterationNumber){N=iterationNumber;}
void constructValueFunctionForRestPeriods(const int& time, const int& location, const Cost& cost, const State& currentState, Demand& demand,const matrixInt_t& identical);
private:
int N;
};
#endif
|
6e4770291cec4c9373984fce0c3d1db20c775ba2 | 897c335fc8280e90b9f7867f1e0a95f345262f0f | /c_linux/ubuntu_c/thread/ext5-2.cpp | a98a4dc39dc828674617d1c10858c752398759e3 | [] | no_license | jiangqianghua/workspace | da504ab68a18948c6d8b2609d9513e3d509af995 | fd5d5dfc44bf080dfeddd097575ab937db8a79d4 | refs/heads/master | 2021-01-18T22:29:58.224055 | 2016-12-04T03:52:45 | 2016-12-04T03:52:45 | 29,686,942 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 526 | cpp | ext5-2.cpp | #include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SIZE 1024 ;
#define KEY 99 ;
int shmid ;
int j = 5;
int main()
{
int i , *pint ;
pid_t pid ;
char *addr ;
i = 10 ;
shmid = shmget(1024,99,IPC_CREAT|0777);
pint =(int *)shmat(shmid,0,0);
*pint = 100 ;
printf("Start of fork testing \n");
pid = fork();
i++ ;
j++ ;
*pint += 1 ;
printf("Return of fork success:pi=%d\n",pid);
printf("i=%d,j=%d\n",i,j);
printf("*pint=%d\n",*pint);
return 0 ;
}
|
06132645beac8d52b62eb91b1d61a04f83f3c374 | 9c400e7e3a84f4657af32d1fbaf7da0572ccca5b | /applications/modem/src/demodulator.cpp | 649553e742541a855b4bfcd1f1cc2c72149c6e27 | [] | no_license | xtuml/models | 1986868b6a12f92017588c3a38f894a1bc7c00bb | 34dc3e28318207e17a0e532bc81f88fef8b011d5 | refs/heads/master | 2023-07-20T14:38:42.048389 | 2023-07-06T14:14:44 | 2023-07-06T14:14:44 | 6,943,299 | 14 | 98 | null | 2023-07-06T14:14:45 | 2012-11-30T17:59:41 | C | UTF-8 | C++ | false | false | 1,190 | cpp | demodulator.cpp | /*----------------------------------------------------------------------------
* File: demodulator.cpp
*
* UML Component as a SystemC Module
* Component/Module Name: demodulator
*
* your copyright statement can go here (from te_copyright.body)
*--------------------------------------------------------------------------*/
#include "demodulator.h"
/*
* Interface: flow
* Provided Port: Port1
* To Provider Message: sample
*/
void
demodulator::flow_sample( const i_t A00portindex, const r_t p_sample_value)
{
demodulator * thismodule = this;
switch ( A00portindex ) {
/* Provided Port: Port1 */
case ( 0 ): {
} break;
default:
break;
}
}
/*
* Interface: feedback
* Provided Port: Port3
* To Provider Message: offset
*/
void
demodulator::feedback_offset()
{
demodulator * thismodule = this;
/* Provided Port: Port3 */
}
#if demodulator_MAX_CLASS_NUMBERS > 0
/* xtUML class info (collections, sizes, etc.) */
sys_sets::Escher_Extent_t * const demodulator::demodulator_class_info[ demodulator_MAX_CLASS_NUMBERS ] = {
};
#endif
/*
* UML Domain Functions (Synchronous Services)
*/
|
8aad73bbe94489380366336c39b20afa9d3edeed | 27651c3f5f829bff0720d7f835cfaadf366ee8fa | /QBluetooth/BTTypes/Impl/QBtService.cpp | f9d63107f957ae4c8d1305a371c89761265bca0a | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | cpscotti/Push-Snowboarding | 8883907e7ee2ddb9a013faf97f2d9673b9d0fad5 | cc3cc940292d6d728865fe38018d34b596943153 | refs/heads/master | 2021-05-27T16:35:49.846278 | 2011-07-08T10:25:17 | 2011-07-08T10:25:17 | 1,395,155 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,178 | cpp | QBtService.cpp | /*
* QBtService.cpp
*
*
* Author: Ftylitakis Nikolaos
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "../QBtService.h"
QBtService::QBtService()
: classUUID(QBtConstants::UndefinedClass),
name("Undefined"),
description("Undefined"),
handle(0),
port(0)
{
protocolUUID.clear();
}
/*
QBtService::QBtService(const QBtService& service) :
name(service.getName()), classUUID(service.getClass()),
port(service.getPort()), handle(service.getHandle()),
description(service.getDescription())
{
protocolUUID = service.getProtocols();
}
*/
//////////////////////////////////////////////
// Accessors //
//////////////////////////////////////////////
QBtService::ProtocolList QBtService::getProtocols() const
{
return protocolUUID;
}
QBtConstants::ServiceClass QBtService::getClass() const
{
return classUUID;
}
QString QBtService::getName() const
{
return name;
}
QString QBtService::getDescription() const
{
return description;
}
unsigned int QBtService::getPort() const
{
return port;
}
unsigned int QBtService::getHandle() const
{
return handle;
}
//////////////////////////////////////////////
// Mutators //
//////////////////////////////////////////////
void QBtService::setClass(QBtConstants::ServiceClass newClass)
{
classUUID = newClass;
}
void QBtService::setName(const QString& newName)
{
name = newName;
}
void QBtService::setDescription(const QString& newDescription)
{
description = newDescription;
}
void QBtService::setPort(unsigned int newPort)
{
port = newPort;
}
void QBtService::setHandle(unsigned int newHandle)
{
handle = newHandle;
}
void QBtService::setProtocols(const QBtService::ProtocolList & newUUIDs)
{
protocolUUID = newUUIDs;
}
void QBtService::addProtocol(QBtConstants::ServiceProtocol uuid)
{
if(protocolUUID.indexOf(uuid) == -1) // if not on list
protocolUUID.append(uuid);
}
/**
* Returns false if uuid not found in the protocol list
*/
bool QBtService::removeProtocol(QBtConstants::ServiceProtocol uuid)
{
return protocolUUID.removeOne(uuid);
}
//////////////////////////////////////////
// Operators //
//////////////////////////////////////////
/*
QBtService& QBtService::operator= (const QBtService& service)
{
if ( this == &service )
return *this;
name = service.getName();
port = service.getPort();
classUUID = service.getClass();
protocolUUID = service.getProtocols();
handle = service.getHandle();
description = service.getDescription();
return *this;
}
*/
|
137a93a2bf700ac8085f7f1d4bd65362cbad62ad | bc3c03ae7a16786f6c99fb93622cd4eecda83c64 | /SheepHerdChallenge/Source/SheepHerdChallenge/Scenery/EdgeTriggerBox.h | bfc889121e69cba7eb78d1ee950b7888db386952 | [] | no_license | lizzye414/SheepHerdingChallenge | b7a47159d69c8321ba9d7bbea0e911f5705262a6 | 0f1bbbe9dc04483a3e646fd3d9ec94afc8221de2 | refs/heads/master | 2022-12-17T14:36:25.556803 | 2020-09-15T15:28:22 | 2020-09-15T15:28:22 | 295,770,877 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 603 | h | EdgeTriggerBox.h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Engine/TriggerBox.h"
#include "EdgeTriggerBox.generated.h"
/**
*
*/
UCLASS()
class SHEEPHERDCHALLENGE_API AEdgeTriggerBox : public ATriggerBox
{
GENERATED_BODY()
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// constructor sets default values for this actor's properties
AEdgeTriggerBox();
// declare overlap begin function
UFUNCTION()
void OnOverlap(AActor* OverlappedActor, AActor* OtherActor);
};
|
70d21540bcf263ff79205dd86e8368f932684191 | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /chrome/browser/history/history_tab_helper_unittest.cc | 0c69d7ee26ad47638dcb682ae90a69700c10c785 | [
"BSD-3-Clause"
] | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 4,042 | cc | history_tab_helper_unittest.cc | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/history/history_tab_helper.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/cancelable_task_tracker.h"
#include "base/test/bind_test_util.h"
#include "chrome/browser/history/history_service_factory.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "chrome/test/base/testing_profile.h"
#include "components/history/core/browser/history_constants.h"
#include "components/history/core/browser/history_service.h"
#include "components/history/core/browser/history_types.h"
#include "components/history/core/browser/url_row.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/web_contents_tester.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
class HistoryTabHelperTest : public ChromeRenderViewHostTestHarness {
protected:
HistoryTabHelperTest() {}
// ChromeRenderViewHostTestHarness:
void SetUp() override {
ChromeRenderViewHostTestHarness::SetUp();
ASSERT_TRUE(profile()->CreateHistoryService(/*delete_file=*/false,
/*no_db=*/false));
history_service_ = HistoryServiceFactory::GetForProfile(
profile(), ServiceAccessType::IMPLICIT_ACCESS);
ASSERT_TRUE(history_service_);
history_service_->AddPage(
page_url_, base::Time::Now(), /*context_id=*/nullptr,
/*nav_entry_id=*/0,
/*referrer=*/GURL(), history::RedirectList(), ui::PAGE_TRANSITION_TYPED,
history::SOURCE_BROWSED, /*did_replace_entry=*/false);
HistoryTabHelper::CreateForWebContents(web_contents());
}
HistoryTabHelper* history_tab_helper() {
return HistoryTabHelper::FromWebContents(web_contents());
}
content::WebContentsTester* web_contents_tester() {
return content::WebContentsTester::For(web_contents());
}
std::string QueryPageTitleFromHistory(const GURL& url) {
std::string title;
base::RunLoop loop;
history_service_->QueryURL(
url, /*want_visits=*/false,
base::BindLambdaForTesting([&](history::QueryURLResult result) {
EXPECT_TRUE(result.success);
title = base::UTF16ToUTF8(result.row.title());
loop.Quit();
}),
&tracker_);
loop.Run();
return title;
}
const GURL page_url_ = GURL("http://foo.com");
private:
base::CancelableTaskTracker tracker_;
history::HistoryService* history_service_;
DISALLOW_COPY_AND_ASSIGN(HistoryTabHelperTest);
};
TEST_F(HistoryTabHelperTest, ShouldUpdateTitleInHistory) {
web_contents_tester()->NavigateAndCommit(page_url_);
content::NavigationEntry* entry =
web_contents()->GetController().GetLastCommittedEntry();
ASSERT_NE(nullptr, entry);
ASSERT_TRUE(web_contents()->IsLoading());
web_contents()->UpdateTitleForEntry(entry, base::UTF8ToUTF16("title1"));
EXPECT_EQ("title1", QueryPageTitleFromHistory(page_url_));
}
TEST_F(HistoryTabHelperTest, ShouldLimitTitleUpdatesPerPage) {
web_contents_tester()->NavigateAndCommit(page_url_);
content::NavigationEntry* entry =
web_contents()->GetController().GetLastCommittedEntry();
ASSERT_NE(nullptr, entry);
ASSERT_TRUE(web_contents()->IsLoading());
// The first 10 title updates are accepted and update history, as per
// history::kMaxTitleChanges.
for (int i = 1; i <= history::kMaxTitleChanges; ++i) {
const std::string title = base::StringPrintf("title%d", i);
web_contents()->UpdateTitleForEntry(entry, base::UTF8ToUTF16(title));
}
ASSERT_EQ("title10", QueryPageTitleFromHistory(page_url_));
// Furhter updates should be ignored.
web_contents()->UpdateTitleForEntry(entry, base::UTF8ToUTF16("title11"));
EXPECT_EQ("title10", QueryPageTitleFromHistory(page_url_));
}
} // namespace
|
16d2d20f9402c0c5974c8ad3fe3e337beadcf869 | 1404f3e204455aacd602c46bdfa2a05c2ac4fb46 | /Source/TS_Arena/TS_ArenaCharacter_MP.h | c6db3f0120d6f5a64c475a1ca19d70e90112dc33 | [] | no_license | lmlr/TS_Arena | 555fecb2878f2ae8ac3f8a15a10e9987e8a8002f | 3138d174ace049176aa610a38e15578aa1ac41cc | refs/heads/master | 2021-07-03T23:06:43.815993 | 2017-09-27T08:09:23 | 2017-09-27T08:09:23 | 104,262,403 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,191 | h | TS_ArenaCharacter_MP.h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "TS_ArenaCharacter.h"
#include "TS_ArenaCharacter_MP.generated.h"
/**
*
*/
UCLASS()
class TS_ARENA_API ATS_ArenaCharacter_MP : public ATS_ArenaCharacter
{
GENERATED_BODY()
public:
ATS_ArenaCharacter_MP();
virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const;
class USphereComponent* GetPickupSphere() const { return PickupSphere; }
UFUNCTION()
void OnOverlapBegin(UPrimitiveComponent* OverlappedComp,
AActor* OtherActor, UPrimitiveComponent* OtherComp,
int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult);
UFUNCTION(BlueprintCallable, Category = "Pickup")
void ClientCollectItem();
UFUNCTION(BlueprintCallable, Category = "Pickup")
void ClientDropItem();
UFUNCTION(Server, Reliable, WithValidation, Category = "Pickup")
void ServerCollectItem();
UFUNCTION(Server, Reliable, WithValidation, Category = "Pickup")
void ServerDropItem();
UFUNCTION(BlueprintCallable, Category = "Stats")
float GetMaxHealth() { return MaxHealth; };
UFUNCTION(BlueprintCallable, Category = "Stats")
float GetCurrentHealth() { return CurrentHealth; };
UFUNCTION(Server, Reliable, WithValidation, Category = "Stats")
void ServerDeltaHealthEvent(float DeltaHealth, AController* DamageDealer);
class ABaseWeapon_Pickup* GetEquipedWeapon() { return EquipedWeapon; };
UFUNCTION(NetMulticast, Reliable, WithValidation, Category = "Pickup")
void SetEquipedWeapon(class ABaseWeapon_Pickup* Weapon);
void Fire() override;
void StopFiring() override;
UFUNCTION(Server, Reliable, WithValidation, Category = "Pickup")
void ServerIssueFireCommand();
UFUNCTION(Server, Reliable, WithValidation, Category = "Pickup")
void ServerIssueStopFireCommand();
UFUNCTION(Server, Reliable, WithValidation)
void ServerOnDeath(AController* Killer);
UFUNCTION(Client, Reliable)
void ClientDeactivateInput();
FTimerHandle RespawnTimer;
UFUNCTION(NetMulticast, Reliable)
void ClientDespawn();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
private:
UPROPERTY(Replicated, EditAnywhere, Category = "Pickup",
meta = (AllowPrivateAccess = "true"))
float PickupSphereRadius;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Pickup",
meta = (AllowPrivateAccess = "true"))
class USphereComponent* PickupSphere;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Pickup",
meta = (AllowPrivateAccess = "true"))
class UBoxComponent* InteractionBox;
UPROPERTY(Replicated, EditAnywhere, Category = "Stats",
meta = (AllowPrivateAccess = "true"))
float MaxHealth;
UPROPERTY(Replicated, EditAnywhere, Category = "Stats",
meta = (AllowPrivateAccess = "true"))
float CurrentHealth;
UPROPERTY(Replicated, VisibleAnywhere, BlueprintReadOnly, Category = "Pickup",
meta = (AllowPrivateAccess = "true"))
class ABaseWeapon_Pickup* EquipedWeapon;
// TODO Might not need replication
UPROPERTY(Replicated, VisibleAnywhere, BlueprintReadOnly, Category = "Stats",
meta = (AllowPrivateAccess = "true"))
bool bIsDead;
};
|
fa07e166d4709beac18831a39bcc3fc7a6509128 | b15e0aa36c90d33a8e76448a82915acfb1e16f50 | /268/lab10/Lammers-2124909-Lab-10/MazeCreationException.cpp | 895f25d78f82b18570de015b27afb04a6bb68a86 | [] | no_license | lcoblamm/EECS | 8f422c40d5b7ce5c8d3081fc7b3e2a6879e3675e | a04f4a05715b567e8aaf606b6484e33d3728caee | refs/heads/master | 2021-05-03T09:11:05.794206 | 2016-04-10T23:37:39 | 2016-04-10T23:37:39 | 30,848,029 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 279 | cpp | MazeCreationException.cpp | /*
@file: MazeCreationException.cpp
@author: Lynne Lammers
@date: 2014.04.30
Purpose: Implementation of MazeCreationException class
*/
#include "MazeCreationException.h"
MazeCreationException::MazeCreationException(const char* message): std::runtime_error(message)
{
}
|
c80240ae0304a1cc2bad76e8900463eb17e214db | fb9b42c9d01d55eb46b4e51d2184a41caffa5ac1 | /Recursion/nthtriangle.cc | 1333229a1e9ce2af97316111d823b757b1325ce7 | [] | no_license | Priyadarshanvijay/Codingblocks-2018 | d60ca31b050b4c5bdced1fe8b26d2e57497ae44e | 963b722d0d665f241b359edd4e9cb4c1f5b19458 | refs/heads/master | 2020-05-25T06:40:55.695887 | 2020-01-30T11:39:59 | 2020-01-30T11:39:59 | 187,669,993 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 222 | cc | nthtriangle.cc | #include <iostream>
using namespace std;
int triangle(int n)
{
if(n<=0) return 0;
int sum = 0;
sum = n+triangle(n-1);
return sum;
}
int main()
{
int n;
cin >> n;
int ans = triangle(n);
cout<<ans<<endl;
return 0;
} |
b134f4509f2dc6ae0e91f9226fb3bb424adcf9ad | 977cbb4a577243fec3fafa6958bd44661382dfa3 | /Credit.cpp | f27d272510ea53d24f44390c3346e7f271e1d154 | [] | no_license | simoneliu94/BankingSystem | 764815f3859bde5bc7b8397c31442e54c2c1e97c | a64f1f250869b6f93af5a99188fc293ab8705ce0 | refs/heads/master | 2021-08-23T00:42:55.581558 | 2017-12-01T23:49:30 | 2017-12-01T23:49:30 | 112,308,470 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,913 | cpp | Credit.cpp | #include "Credit.h"
using namespace std;
Credit::Credit()
{
}
//Create a credit account with parameters id, balance, date and customer and pass them to Account class
Credit::Credit(string a_id, double a_bal, double lim, string a_date, Customer &a_cus):Account(a_id, a_bal, a_date, a_cus)
{
limit = lim;
credit_score = 650;
}
//Set credit limit
void Credit::set_limit(double lim)
{
limit = lim;
}
//Get credit limit
double Credit::get_limit()
{
return limit;
}
//Set credit limit
void Credit::set_score(int sc)
{
credit_score = sc;
}
//Get credit limit
int Credit::get_score()
{
return credit_score;
}
int Credit::get_credit_score()
{
return credit_score;
}
//Override deposit function from Account class
//Pay off the balance, charge fee to this transaction
void Credit::deposit(double amt, string des)
{
balance = balance - amt;
trans_charge();
string trans = "Account " + acc_id + ". Deposited $"+ to_string(amt)+". Current balance $"+to_string(balance) + ". Note: " + des;
keep_transaction(trans);
}
//Override withdraw function from Account class
//Withdraw money from account, charge fee to this transaction
void Credit::withdraw(double amt, string des)
{
//Checking if the limit has been reached yet
if(amt <= limit)
{
balance = balance + amt;
trans_charge();
string trans = "Account " + acc_id + ". Withdrew $"+ to_string(amt)+". Current balance $"+to_string(balance) + ". Note: " + des;
keep_transaction(trans);
}
else
{
cout <<"Account "<< acc_id<< ". Insufficient funds to withdraw" << endl;
cout << "-------------------------------------------" << endl;
}
}
//Override the
//Charges 8% interest compounded daily
void Credit::daily_interest()
{
interest_rate = 0.08/365;
balance = balance + interest_rate;
string trans = "Account " + acc_id + ". Daily charge rate $" + to_string(interest_rate)+". Current balance: $"+to_string(balance);
keep_transaction(trans);
}
//Charge fees to transactions
void Credit::trans_charge()
{
trans_fee = 0.3;
balance = balance + trans_fee;
}
//Charges a fee of $25/mo if balance is $0.00.
void Credit::zeroBal_charge()
{
if(balance==0)
{
balance = balance + 25;
}
}
//Charge minimum due monthly at rate 0.25% of the current balance
//Call track_credit_score() function
void Credit::monthly_fee()
{
min_due = balance * 0.0025;
balance = balance + min_due;
track_credit_score();
string trans = "Account " + acc_id + ". Minimum due this month $" + to_string(min_due)+". Current balance: $"+to_string(balance);
keep_transaction(trans);
}
//Keep track of the credit score each month
//If customer spend less than 30% of the limit each month, then add 5 points to their credit score
//Else, deduct 1 points
void Credit::track_credit_score()
{
if (balance <= limit*0.3)
{
credit_score = credit_score + 5;
}
else
{
credit_score = credit_score - 1;
}
}
//Print out the status based on credit score
void Credit::credit_status()
{
if(credit_score>=800)
{
cout << "Credit score range: Excellent" << endl;
}
if((750<=credit_score) & (credit_score<=799))
{
cout << "Credit score range: Very good" << endl;
}
if((700<=credit_score) & (credit_score<=749))
{
cout << "Credit score range: Good" << endl;
}
if((650<=credit_score) & (credit_score<=699))
{
cout << "Credit score range: Fair" << endl;
}
if((600<=credit_score) & (credit_score<=649))
{
cout << "Credit score range: Poor" << endl;
}
if(credit_score<=599)
{
cout << "Credit score range: Very bad" << endl;
}
}
|
bca04258b7675249e48400f6a7cdcfe21b9e5fc5 | 09e2375e0b8b9645d6eafffe8e1428bd9469d056 | /MakeLimitInputs/table.h | 552280f8d157ec68c1c9f852f7c937cc679a69aa | [] | no_license | susy2015/StatisticalTools | e59d9cb6a31e166c2508da98d73d442cdf390790 | fa6a2d2b9d126051881910ed1ca9f43670314468 | refs/heads/master | 2021-01-18T23:07:46.771607 | 2017-03-02T18:59:14 | 2017-03-02T18:59:14 | 37,553,718 | 0 | 3 | null | 2017-03-02T18:59:44 | 2015-06-16T20:17:14 | C++ | MacCentralEurope | C++ | false | false | 4,715 | h | table.h | //class table for formatted output
//Christian Autermann, Universitšt Hamburg
#ifndef TABLE_H
#define TABLE_H
/* ----------------------------------------------------------------------------------------------
Usage:
------
using Table::TTable;
TTable table("Particle mass table");
table.AddColumn<string>("particle");
table.AddColumn<double>("mass [GeV]");
table.AddColumn<int>("number");
table << "top" << 172. << 2;
table << "W" << 80. << 13;
cout << table << endl;
----------------------------------------------------------------------------------------------*/
#include <iostream>
#include <string>
#include <vector>
#include "column.h"
namespace Table {
///Different Styles, default is Plain
enum TableStyle {Empty, Plain, TeX};
class TTable {
public:
///Constructor & Destructor allowing to directly set the table header, the delimiter between columns and the caption
TTable():header_(""),delimiter_(" "),caption_(""),style_(Plain),idx_(0){};
TTable(std::string h):header_(h),delimiter_(" "),caption_(""),style_(Plain),idx_(0){};
TTable(std::string h, std::string d):header_(h),delimiter_(d),caption_(""),style_(Plain),idx_(0){};
TTable(std::string h,std::string d,std::string c):header_(h),delimiter_(d),caption_(c),style_(Plain),idx_(0){};
virtual ~TTable(){ for (std::vector<TColumnBase*>::iterator it=table_.begin();it!=table_.end();++it) delete *it; table_.clear(); };
///Method to specify the columns in this table. To be called once per column
template <class T> void AddColumn(const std::string& header){table_.push_back(new TColumn<T>(header));};
///Methods to set the contents of a cell in the table
///One argument: The active cell is set, and the next cell (left to right, top down) becomes active
template <class T> void Set(T value){table_.at(idx_++)->Add( new T(value) );if(idx_>=table_.size())idx_=0;};
/*spezialize for char*/ void Set(const char* value){table_.at(idx_++)->Add( new std::string(value)); if(idx_>=table_.size())idx_=0;};
///Two arguments: New cells are appended at the bottom of the table; idx specifies the column. Column (idx+1) modulo n_columns is set active.
template <class T> void Set(unsigned idx,T value){table_.at(idx)->Add( new T(value) );idx_=(idx==table_.size()?0:idx+1);};
/*spezialize for char*/ void Set(unsigned idx,const char* value){table_.at(idx)->Add( new std::string(value) );idx_=(idx==table_.size()?0:idx+1);};
///Three arguments: This method can be used to overwrite the contents of cell (x,y) with value.
template <class T> void Set(unsigned x, unsigned y, const T& value){static_cast<TColumn<T> >(table_.at(x))->Set(y,value);};
///Number of lines of this table; header and caption are not counted.
unsigned Length() const {
unsigned length=0;
for (std::vector<TColumnBase*>::const_iterator it=table_.begin();it!=table_.end();++it)
if ((*it)->Size()>length) length = (*it)->Size();
return length;
};
///Methods to get and set Header, Delimiter between columns, caption, style of the table
std::string GetHeader() const{return header_;};
std::string GetDelimiter() const{return delimiter_;};
std::string GetCaption() const{return caption_;};
void SetHeader(const std::string& s){header_=s;};
void SetDelimiter(const std::string& s){delimiter_=s;};
void SetCaption(const std::string& s){caption_=s;};
void SetStyle(TableStyle s){style_=s;};
TableStyle GetStyle() const {return style_;};
void SetMinumumWidth(unsigned w){table_.at(idx_)->SetMinumumWidth(w);}
void SetMinumumWidth(unsigned w,unsigned idx){table_.at(idx)->SetMinumumWidth(w);}
unsigned GetWidth(){return table_.at(idx_)->GetCurrentWidth();}
unsigned GetWidth(unsigned idx){return table_.at(idx)->GetCurrentWidth();}
///Method to set the precision of column i. To be used e.g for <double> columns. Default is 1.
void SetPrecision(unsigned i, unsigned p){table_[i]->SetPrecision(p);};
///Set all columns to one precision, default precision is 1
void SetPrecision(unsigned p){ for (std::vector<TColumnBase*>::const_iterator it=table_.begin();it!=table_.end();++it) (*it)->SetPrecision(p);};
const std::vector<TColumnBase*> * GetTable() const {return &table_;};
private:
std::string header_, delimiter_, caption_;
std::vector<TColumnBase*> table_;
TableStyle style_;
unsigned idx_;
};
template <class T> TTable& operator<<(TTable& tab, T t){
tab.Set(t);
return tab;
}
///Overloading the std::ostream operator for output.
std::ostream& operator<<( std::ostream& os, const TTable& tab );
}
#endif
|
e5c4b8455207e2d8ea3938f486cf35679d7d203c | e97676049537a10187f4fc5f9781a37c13179f20 | /RooRarFit/RooFlatte.cc | b81885999317636acb82d975c42bcd0148035e1b | [] | no_license | Abd-zak/rich | e61714c9939c9898a4339b26e90a0331b6799ea2 | 603e0f7afed7c45f92deb15e6706fec2b5a52583 | refs/heads/main | 2023-06-21T12:57:10.727379 | 2021-07-26T07:54:09 | 2021-07-26T07:54:09 | 384,119,990 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,284 | cc | RooFlatte.cc | /*****************************************************************************
* Project: BaBar detector at the SLAC PEP-II B-factory
* Package: RooRarFit
* File: $Id: RooFlatte.cc,v 1.5 2014/09/14 17:33:47 fwilson Exp $
* Authors: Fergus Wilson
* History:
*
* Copyright (C) 2005-2012, RAL
*****************************************************************************/
// -- CLASS DESCRIPTION [PDF] --
// This is an implementation of the BES parameterisation of the Flatte
// distribution
//
// Reference : S.M.Flatte Phys. Rev. B63, 224 (1976);
// B.S.Zou and D.V.Bugg Phys Rev. D48, R3948 (1993);
// M.Ablikim wt al (BES collaboration), Phys. Rev. D70, 092002, (2004)
//
//////////////////////////////////////////////////////
//
// BEGIN_HTML
// This is an implementation of the BES parameterisation of the Flatte
// distribution
//
// Reference : S.M.Flatte Phys. Rev. B63, 224 (1976);
// B.S.Zou and D.V.Bugg Phys Rev. D48, R3948 (1993);
// M.Ablikim wt al (BES collaboration), Phys. Rev. D70, 092002, (2004)
//
// END_HTML
//
#include "rarVersion.hh"
#include "Riostream.h"
#include "RooFlatte.hh"
#include "RooAbsReal.h"
#include "RooRealVar.h"
#include <complex>
typedef std::complex<Double_t> dcmplx;
ClassImp(RooFlatte)
//------------------------------------------------------------------
RooFlatte::RooFlatte(const char *name, const char *title,
RooAbsReal& _x, RooAbsReal& _mean,
RooAbsReal& _g0, RooAbsReal& _m0a, RooAbsReal& _m0b,
RooAbsReal& _g1, RooAbsReal& _m1a, RooAbsReal& _m1b) :
RooAbsPdf(name,title),
x("x","Dependent",this,_x),
mean("mean","Mean",this,_mean),
g0("g0","Channel 1 coupling",this,_g0),
m0a("m0a","Mass of particle 1 in channel 1",this,_m0a),
m0b("m0b","Mass of particle 2 in channel 1",this,_m0b),
g1("g1","Channel 2 coupling",this,_g1),
m1a("m1a","Mass of particle 1 in channel 2",this,_m1a),
m1b("m1b","Mass of particle 2 in channel 2",this,_m1b)
{
}
//------------------------------------------------------------------
RooFlatte::RooFlatte(const RooFlatte& other,
const char* name) :
RooAbsPdf(other,name),
x("x",this,other.x),
mean("mean",this,other.mean),
g0("g0",this,other.g0),
m0a("m0a",this,other.m0a),
m0b("m0b",this,other.m0b),
g1("g1",this,other.g1),
m1a("m1a",this,other.m1a),
m1b("m1b",this,other.m1b)
{
}
//------------------------------------------------------------------
Double_t RooFlatte::evaluate() const
{
// calculate Flatte amplitude
if (g0<0 || g1<0) {return(0);}
Double_t s = x*x;
// Energy, centre of mass p^2 of first channel
Double_t E0a = 0.5 * (s + m0a*m0a - m0b*m0b) / x;
Double_t qSq0 = E0a*E0a - m0a*m0a;
// Energy, centre of mass p^2 of second channel
Double_t E1a = 0.5 * (s + m1a*m1a - m1b*m1b) / x;
Double_t qSq1 = E1a*E1a - m1a*m1a;
dcmplx gamma0 = (qSq0 > 0) ? dcmplx(g0*sqrt(qSq0),0) : dcmplx(0, g0*sqrt(-qSq0));
dcmplx gamma1 = (qSq1 > 0) ? dcmplx(g1*sqrt(qSq1),0) : dcmplx(0, g1*sqrt(-qSq1));
dcmplx gamma = gamma0 + gamma1;
dcmplx partB = dcmplx(0.0, 2*mean/x) * gamma;
dcmplx partA(mean*mean - s, 0);
dcmplx denom = partA - partB;
//dcmplx T(mean*sqrt(g0*g1),0);
dcmplx T(1,0);
T = T / denom;
return(std::abs(T) * std::abs(T)); // Amplitude (arbitrary scale)
}
|
06ada1f66d7bce91465e6f50689dc84ac52dd2e3 | 1b4a1a66173d85be9745d192c427ed975c19c18f | /simple_calculator/Formula.cpp | 3d038b95a85744f274885aaa33884f8c65637fcb | [
"Apache-2.0"
] | permissive | shianchin/mini_projects | d10a6aef24ac482507dc7fd01965454941bc5797 | c4559e564c05ae5abfd844cb43691867f01f3ff2 | refs/heads/master | 2021-01-17T03:07:43.233442 | 2017-08-27T15:51:55 | 2017-08-27T15:51:55 | 46,563,110 | 0 | 0 | null | 2016-08-07T12:54:15 | 2015-11-20T13:20:27 | Python | UTF-8 | C++ | false | false | 2,169 | cpp | Formula.cpp | //----------------------------------------------------------------------
// Project : Customizable Scientific Calculator
//
// File name : Formula.cpp
//
// Author : Cheang Shian Chin
//
// Date created : 15 October 2016
//
// Purpose : Handles read & write formulae to file.
//
//----------------------------------------------------------------------
#include "Formula.h"
#include <string.h>
#include <iostream>
#include <fstream>
using namespace std;
Formula::Formula()
{
}
Formula::~Formula()
{
}
void Formula::writeToFile(string fName, string equation)
{
ofstream myfile("formula.txt", ofstream::app); //append to file
if (myfile.is_open())
{
myfile << fName << "\n" << equation << "\n";
myfile.close();
cout << "> Formula written successful!\n";
}
else
{
cout << "Unable to open file.\n";
}
}
bool Formula::loadFromFile(void)
{
bool isFileExist = false;
string s_FormulaExpr;
ifstream myfile("formula.txt");
if (myfile.is_open())
{
int i = 0;
int lineNum = 0;
string fName;
char* comma = 0;
while ( getline(myfile, s_FormulaExpr) )
{
if (lineNum%2 == 0) // first line is formula name
{
m_formulae[i].fName = s_FormulaExpr;
}
else // second line is formula equation
{
m_formulae[i].equation = s_FormulaExpr;
i++;
}
lineNum++;
}
myfile.close();
isFileExist = true;
}
else
{
cout << "File does not exist.\n";
isFileExist = false;
}
return isFileExist;
}
string Formula::getName(int index)
{
return m_formulae[index].fName;
}
string Formula::getEquation(int index)
{
return m_formulae[index].equation;
}
//----------------------------------------------------------------------
// Revision History :
//
// Date Author Ref Revision
// 15-Oct-2016 shianchin 1 Initial creation.
//
//----------------------------------------------------------------------
|
b89c1775e7008ecee92ff3342b244b3d21911f24 | f3986aae0e60ffd9395968a7dcb639eb55f07dd7 | /c++/cpp_primer/9/size.cpp | 7d7df72b06f5491151d6c6b983103a3e3d7c86d4 | [] | no_license | czisimba/playground | 764dba458088e0c80e2b75850c1fb36e73dace4d | 7a892add3e233eec41233f9555ebf5f704998179 | refs/heads/master | 2020-05-22T04:01:49.504407 | 2017-03-13T09:25:11 | 2017-03-13T09:25:11 | 47,691,357 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 393 | cpp | size.cpp | #include <iostream>
#include <vector>
#include <list>
using namespace::std;
int main()
{
vector<int> ivec;
cout << "vector size:" << ivec.size() << endl;
cout << "vector max size:" << ivec.max_size() << endl;
ivec.resize(100);
cout << "vector size(after resize to 100):" << ivec.size() << endl;
cout << "vector max size:" << ivec.max_size() << endl;
return 0;
}
|
edee97e25ecc9b4b5fc548d8a433a57cf5baf91e | 844fc17b4b94fcc455e56b1e8fa87da8be537d23 | /applications/convergence_plots/spectral_transfer_matrix.hpp | b0f7913988b58d44a20f0fd333536d62c0d692db | [] | no_license | simonpintarelli/2dBoltzmann | be6426564ffd74cd084787fbe1c6590b27a53dcc | bc6b7bbeffa242ce80937947444383b416ba3fc9 | refs/heads/master | 2021-04-12T10:21:50.167296 | 2018-12-16T16:16:43 | 2018-12-16T16:16:43 | 126,182,914 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 609 | hpp | spectral_transfer_matrix.hpp | #pragma once
#include <Eigen/Sparse>
#include <algorithm>
namespace boltzmann {
template <typename SPECTRAL_BASIS>
Eigen::SparseMatrix<double>
spectral_transfer_matrix(const SPECTRAL_BASIS& dst, const SPECTRAL_BASIS& src)
{
unsigned int m = dst.n_dofs();
unsigned int n = src.n_dofs();
Eigen::SparseMatrix<double> T(m, n);
for (unsigned int i = 0; i < m; ++i) {
const auto& dst_elem = dst.get_elem(i);
unsigned int j;
try {
j = src.get_dof_index(dst_elem.id());
} catch (...) {
continue;
}
T.insert(i, j) = 1;
}
return T;
}
} // end namespace boltzmann
|
2ccf0b432a3794380ccf5d23e94ae68c0b289289 | a77e5d9bfbf0e6c6943534cf53a4f913cdbede6f | /source/Thread.cpp | 34a726cdd37d17df32b7929fb7771fb890b8d6ca | [] | no_license | xiaowenmu/mynet | ea41ad693c50137120be74b56357bffd0fd42e16 | 37d368437c404129025d88882ece553c5d9f413e | refs/heads/master | 2020-05-19T16:37:55.647733 | 2019-06-08T13:32:55 | 2019-06-08T13:32:55 | 185,115,452 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,463 | cpp | Thread.cpp | #include"include/Thread.h"
#include"include/MacroDefine.h"
namespace mynet{
struct ThreadData{
typedef std::function<void()> ThreadFun;
ThreadFun fun;
Condition *condPtr;
pid_t *tid;
ThreadData(ThreadFun f,Condition *cond,pid_t *t):fun(std::move(f)),condPtr(cond),tid(t){};
void runInThread(){
try{
condPtr->notify();
fun();
}
catch (...){
fprintf(stderr, "unknown exception caught in Thread %s\n", "cuowu");
throw;
}
}
};
void *StartThread(void *dat){
//started = true;
ThreadData *data = static_cast<ThreadData*>(dat);
*(data->tid) = mynet::Thread::gettid();
//condition->notify();
//started = true;
data->runInThread();
delete data;
return NULL;
}
Thread::Thread(ThreadFun f,int i):func(f),threadMutex(),condition(threadMutex),started(false),joined(false){
char buf[20];
snprintf(buf,sizeof(buf),"Thread %d",i);
name = buf;
};
void Thread::run(){
assert(started == false);
started = true;
ThreadData *data = new ThreadData(func,&condition,&tid);
if(pthread_create(&threadId,nullptr,StartThread,data)){
delete data;
started = false;
ERRRET(-1);
}
else{
//pthread_detach(threadId);
condition.wait();
}
return;
}
Thread::~Thread(){
if (started && !joined){
pthread_detach(threadId);
}
}
int Thread::join(){
if(started && !joined){
joined = true;
return pthread_join(threadId,NULL);
}
else
ERRRET(-1);
}
}
|
38382f7503f810e5fc4f4b04fee0e0d58e6a2c58 | 04243c8686210ee2f16e85d79c15f60bf3949588 | /CLanClient/CLanClient.cpp | d59538614f44bfcea6f720d675a64eda80e7d467 | [] | no_license | Goomni/MOProject | 4745e5ec19ab313ad6e90547ee5a7a91750d0472 | aa0ae7bd974eb6250f70d3bd2b0949a6e0c0d29c | refs/heads/master | 2023-08-10T11:49:54.451702 | 2021-09-02T22:55:32 | 2021-09-02T22:55:32 | 402,583,012 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 28,458 | cpp | CLanClient.cpp | #include "CLanClient.h"
#include "Logger\Logger.h"
#include "Define\GGM_CONSTANTS.h"
#include "Define\GGM_ERROR.h"
ULONGLONG ReconnectCount = 0;
namespace GGM
{
bool GGM::CLanClient::Start(
TCHAR * ConnectIP,
USHORT port,
DWORD ConcurrentThreads,
DWORD MaxThreads,
bool IsNoDelay,
bool IsReconnect,
int ReconnectDelay
)
{
bool IsSuccess = WSAInit(ConnectIP, port, IsNoDelay);
if (IsSuccess == false)
return false;
m_MySession.SendQ.InitLockFreeQueue(0, MAX_LOCK_FREE_Q_SIZE);
IsSuccess = CPacket::CreatePacketPool(0);
if (IsSuccess == false)
return false;
IsSuccess = ConnectToLanServer(IsReconnect, ReconnectDelay, ConcurrentThreads);
if (IsSuccess == false)
return false;
IsSuccess = ThreadInit(ConcurrentThreads, MaxThreads);
if (IsSuccess == false)
return false;
return true;
}
void GGM::CLanClient::Stop()
{
// 재접속 off
m_IsReconnect = false;
// 워커 스레드 IOCP 핸들을 닫는다. 이 시점에 워커스레드가 모두 종료된다.
CloseHandle(m_hWorkerIOCP);
// 워커스레드가 모두 종료될 때까지 대기한다.
WaitForMultipleObjects(m_IOCPThreadsCount, m_ThreadHandleArr, TRUE, INFINITE);
for (DWORD i = 0; i < m_IOCPThreadsCount; i++)
CloseHandle(m_ThreadHandleArr[i]);
if (m_MySession.socket != INVALID_SOCKET)
{
closesocket(m_MySession.socket);
m_MySession.socket = INVALID_SOCKET;
}
// 기타 리소스 정리
delete[] m_ThreadHandleArr;
delete[] m_ThreadIDArr;
//
WSACleanup();
}
bool GGM::CLanClient::Connect()
{
// 아직 소켓이 생성되지 않았거나, 이전에 끊겨서 리소스가 정리된 후 재연결 하는 것이라면 하나 생성해줌
if (m_MySession.socket == INVALID_SOCKET)
{
if (CreateSocket() == false)
return false;
}
// Connect를 논블락으로 처리하고 그 결과를 확인하기 위해서 select를 활용한다.
// Connect 두번 호출하는 이유
// 만약에 두번째 connect 호출 했을 때 Error 값이 WSAEISCONN 떠 주면 Select 안해도 되기 때문이다.
SOCKET sock = m_MySession.socket;
connect(sock, (SOCKADDR*)&m_ServerAddr, sizeof(m_ServerAddr));
connect(sock, (SOCKADDR*)&m_ServerAddr, sizeof(m_ServerAddr));
// 논블락 소켓일 경우 connect를 호출하면 나올 수 있는 에러의 경우의 수는 다음과 같다.
// 1. 최초 호출시 바로 WSAEWOULDBLOCK
// 2. 아직 연결이 완료되지 않았는데 다시 connect 호출하면 WSAEALREADY
// 3. 이미 연결이 완료된 소켓에 대해서 다시 connect 호출하면 WSAEISCONN
// 4. 그 이외의 경우는 WSAECONNREFUSED, WSAENETUNREACH, WSAETIMEDOUT
DWORD dwError = WSAGetLastError();
if (dwError == WSAEWOULDBLOCK || dwError == WSAEALREADY)
{
// 쓰기셋에 소켓 넣는다.
FD_SET WriteSet;
WriteSet.fd_count = 0;
WriteSet.fd_array[0] = sock;
WriteSet.fd_count++;
// 예외셋에 소켓 넣는다.
FD_SET ExceptionSet;
ExceptionSet.fd_count = 0;
ExceptionSet.fd_array[0] = sock;
ExceptionSet.fd_count++;
timeval TimeVal = { 0, 500000 };
// select로 timeval 값만큼만 연결을 기다린다.
int iResult = select(0, nullptr, &WriteSet, &ExceptionSet, &TimeVal);
if (iResult == 0 || ExceptionSet.fd_count == 1)
return false;
}
// 서버와 연결에 성공한 소켓과 워커스레드의 IOCP를 연결한다.
HANDLE hRet = CreateIoCompletionPort((HANDLE)sock, m_hWorkerIOCP, 0, 0);
if (hRet != m_hWorkerIOCP)
{
OnError(GetLastError(), _T("Associate Session Socket with Worker IOCP failed %d"));
return false;
}
// 연결 성공했으면 세션 초기화
InterlockedIncrement(&m_MySession.IoCount);
m_MySession.SessionID++;
m_MySession.SentPacketCount = 0;
m_MySession.RecvQ.ClearRingBuffer();
m_MySession.SendQ.ClearLockFreeQueue();
m_MySession.IsSending = FALSE;
m_MySession.IsReleased = FALSE;
// 최초 RecvPost 등록
RecvPost(&m_MySession.RecvQ, &m_MySession.RecvOverlapped, &m_MySession.IoCount, sock);
SessionReleaseLock();
// 연결 성공했을때 무언가 해야 할일이 있다면 여기서 함
OnConnect();
return true;
}
bool CLanClient::WSAInit(TCHAR * ConnectIP, USHORT port, bool IsNoDelay)
{
// WSADATA 구조체 초기화
WSADATA wsa;
if (int SocketError = WSAStartup(MAKEWORD(2, 2), &wsa))
{
OnError(SocketError, _T("WSAStartup Failed"));
return false;
}
ZeroMemory(&m_ServerAddr, sizeof(m_ServerAddr));
m_ServerAddr.sin_port = htons(port);
m_ServerAddr.sin_family = AF_INET;
if (ConnectIP == nullptr)
{
OnError(GGM_ERROR::INVALID_SERVER_IP, _T("Invalid Server IP"));
return false;
}
if (InetPton(AF_INET, ConnectIP, &(m_ServerAddr.sin_addr)) != TRUE)
{
OnError(WSAGetLastError(), _T("InetPton Failed"));
return false;
}
m_IsNoDelay = IsNoDelay;
if (CreateSocket() == false)
return false;
return true;
}
bool CLanClient::ConnectToLanServer(bool IsReconnect, int ReconnectDelay, DWORD ConcurrentThreads)
{
// 워커스레드와 연동될 IOCP 생성
m_hWorkerIOCP = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, NULL, ConcurrentThreads);
if (m_hWorkerIOCP == NULL)
{
OnError(GetLastError(), _T("CreateIoCompletionPort Failed"));
return false;
}
// 랜서버와 연결이 끊길시 재접속 여부와 딜레이 설정
m_IsReconnect = IsReconnect;
m_ReconnectDelay = ReconnectDelay;
// LanServer와 연결 성공할 때까지 연결시도
do
{
if (Connect() == true)
break;
Sleep(ReconnectDelay);
} while (IsReconnect);
return true;
}
bool CLanClient::ThreadInit(DWORD ConcurrentThreads, DWORD MaxThreads)
{
// 생성된 스레드의 핸들을 저장할 배열
m_ThreadHandleArr = new HANDLE[MaxThreads];
if (m_ThreadHandleArr == nullptr)
{
OnError(GetLastError(), _T("MEM Alloc Failed"));
return false;
}
// 생성된 스레드의 아이디를 저장할 배열
m_ThreadIDArr = new DWORD[MaxThreads];
if (m_ThreadIDArr == nullptr)
{
OnError(GetLastError(), _T("MEM Alloc Failed"));
return false;
}
/////////////////// WorkerThread 생성 //////////////////////////////
// 사용자가 요청한 개수의 워커 스레드(동시실행 개수 아님) 생성
for (DWORD i = 0; i < MaxThreads; i++)
{
m_ThreadHandleArr[i] = (HANDLE)_beginthreadex(
nullptr,
0,
CLanClient::WorkerThread, // 워커 스레드 함수 클래스 내부에 private static으로 선언되어있음
this, // 워커스레드 함수가 static으로 선언되어있으므로 다른 멤버 변수나 함수에 접근하기 위해서 해당 인스턴스의 this 포인터가 필요함
0,
(unsigned int*)&m_ThreadIDArr[i]
);
if (m_ThreadHandleArr[i] == NULL)
{
OnError(GetLastError(), _T("_beginthreadex Failed"));
return false;
}
}
/////////////////// WorkerThread 생성 //////////////////////////////
return true;
}
bool GGM::CLanClient::Disconnect()
{
// 단순 연결을 끊는 것과 세션을 릴리즈 하는 것은 다른 것이다.
// 여기서는 shutdown을 통해 연결만 끊는다.
// shutdown을 통해 연결이 끊은 후 자연스럽게 I/O Count가 0이 되도록 유도하여 세션을 릴리즈한다.
do
{
// 세션에 접근을 시도한다.
// 세션 접근에 실패하면 그냥 나간다.
if (SessionAcquireLock(m_MySession.SessionID) == false)
break;
shutdown(m_MySession.socket, SD_BOTH);
} while (0);
// 세션에 접근을 완료했음을 알림
SessionReleaseLock();
return true;
}
bool GGM::CLanClient::SendPacket(CPacket * pPacket)
{
bool Result;
do
{
// 세션에 접근을 시도한다.
// 세션 접근에 실패하면 (이미 스레드가 릴리즈 중이라면) 그냥 나간다.
if (SessionAcquireLock(m_MySession.SessionID) == false)
{
Result = true;
break;
}
// 네트워크 레벨에서는 직렬화 버퍼의 제일 앞에 네트워크 계층의 헤더를 붙인다.
LAN_HEADER Header;
Header.size = pPacket->GetCurrentUsage() - LAN_HEADER_LENGTH;
pPacket->EnqueueHeader((char*)&Header);
// SendQ에 네트워크 패킷의 포인터를 담는다.
pPacket->AddRefCnt();
Result = m_MySession.SendQ.Enqueue(pPacket);
if (Result == false)
{
OnError(GGM_ERROR::BUFFER_WRITE_FAILED, _T("SESSION BUFFER WRITE FAILED"));
break;
}
// SendFlag를 확인해보고 Send중이 아니라면 PQCS로 WSASend 요청
// 이렇게 함으로써, 컨텐츠에서 WSASend를 호출하여 업데이트가 느려지는 것을 막을 수 있다.
// 그러나 패킷 응답성은 떨어짐
if (InterlockedOr(&m_MySession.IsSending, 0) == TRUE)
break;
PostQueuedCompletionStatus(m_hWorkerIOCP, 0, 0, &m_DummyOverlapped);
// PQCS를 하고나서는 IOCount를 바로 깍지 않고 완료통지에서 깎는다.
return true;
} while (0);
// 세션에 접근을 완료했음을 알림
SessionReleaseLock();
return true;
}
unsigned int __stdcall GGM::CLanClient::WorkerThread(LPVOID Param)
{
// Worker 스레드 함수가 static이기 때문에 멤버변수에 접근하거나 멤버함수를 호출하기 위해
// this 포인터를 인자로 받아온다.
CLanClient *pThis = (CLanClient*)Param;
// IOCP 핸들
HANDLE hIOCP = pThis->m_hWorkerIOCP;
// LanClient의 워커스레드가 접근하는 세션 구조체의 주소는 매번 동일하므로 필요한 변수의 주소를 모두 로컬로 받아둔다.
LONG *pIoCount = &(pThis->m_MySession.IoCount);
LONG *pIsSending = &(pThis->m_MySession.IsSending);
OVERLAPPED *pRecvOverlapped = &(pThis->m_MySession.RecvOverlapped);
OVERLAPPED *pSendOverlapped = &(pThis->m_MySession.SendOverlapped);
OVERLAPPED *pDummyOverlapped = &pThis->m_DummyOverlapped;
ULONG *pSentPacketCount = &(pThis->m_MySession.SentPacketCount);
CPacket **PacketArray = pThis->m_MySession.PacketArray;
CRingBuffer *pRecvQ = &(pThis->m_MySession.RecvQ);
CLockFreeQueue<CPacket*> *pSendQ = &(pThis->m_MySession.SendQ);
SOCKET *pSocket = &(pThis->m_MySession.socket);
// 루프 돌면서 작업 한다.
while (true)
{
// 완료통지 후 결과를 받을 변수들을 초기화 한다.
DWORD BytesTransferred; // 송수신 바이트 수
Session *pSession; // 컴플리션 키로 전달한 세션 구조체 포인터
OVERLAPPED *pOverlapped; // Overlapped 구조체 포인터의 포인터
// GQCS를 호출해서 일감이 오기를 대기한다.
bool bOk = GetQueuedCompletionStatus(hIOCP, &BytesTransferred, (PULONG_PTR)&pSession, (LPOVERLAPPED*)&pOverlapped, INFINITE);
// 워커 스레드 일 시작했음.
//pThis->OnWorkerThreadBegin();
// SendPacket함수 내부에서 PQCS로 SendPost요청 했다면 이 곳에서 처리
if (pOverlapped == pDummyOverlapped)
{
if (pSendQ->size() > 0)
pThis->SendPost(
pIsSending,
pSendQ,
pSendOverlapped,
PacketArray,
pSentPacketCount,
pIoCount,
*pSocket
);
// 세션 동기화를 위해 IOCount올렸던 것을 이 곳에서 차감
pThis->SessionReleaseLock();
continue;
}
// Overlapped 구조체가 nullptr이면 문제가 발생한 것이다.
if (pOverlapped == nullptr)
{
DWORD Error = WSAGetLastError();
if (bOk == FALSE && Error == ERROR_ABANDONED_WAIT_0)
{
// 오버랩드 구조체가 널인데 에러코드가 ERROR_ABANDONED_WAIT_0라면 외부에서 현재 사용중인 IOCP 핸들을 닫은 것이다.
// 스레드 종료처리 로직이므로 종료 해주면 된다.
// 테스트용 콘솔 출력 나중에 지워야 함
_tprintf_s(_T("[SERVER] SERVER OFF! WORKER THREAD EXIT [ID %d]\n"), GetCurrentThreadId());
return 0;
}
pThis->OnError(WSAGetLastError(), _T("GQCS FAILED / OVERLAPPED NULL"));
continue;
}
// pOverlapped가 nullptr가 아니라면 송수신바이트 수가 0인지 검사해야 한다.
// IOCP에서 송수신 바이트수는 (0 이나 요청한 바이트 수) 이외의 다른 값이 나올 수 없다.
// 따라서 송수신 바이트 수가 0이 아니라면 요청한 비동기 I/O가 정상적으로 처리되었음을 의미한다.
if (BytesTransferred == 0)
{
//0이 나오면 저쪽에서 FIN을 보냈거나 에러가 난 경우이다.
//I/O Count를 0으로 유도해서 세션이 자연스럽게 정리될 수 있도록 한다.
pThis->SessionReleaseLock();
continue;
}
// 완료된 I/O가 RECV인지 SEND인지 판단한다.
// 오버랩드 구조체 포인터 비교
if (pOverlapped == pRecvOverlapped)
{
// 완료통지로 받은 바이트 수만큼 Rear를 옮겨준다.
pRecvQ->RelocateWrite(BytesTransferred);
// 네트워크 클래스 계층의 완성된 패킷이 있는지 확인
// CheckPacket 내부에서 모든 완료된 패킷을 OnRecv로 전달
pThis->CheckPacket(pRecvQ);
// RecvPost 호출해서 WSARecv 재등록
pThis->RecvPost(pRecvQ, pRecvOverlapped, pIoCount, *pSocket);
}
else
{
// 완료된 I/O가 SEND라면 OnSend 호출
//pThis->OnSend(pSession->SessionID, BytesTransferred);
// OnSend후에는 송신완료 작업을 해주어야 함
// 1. 비동기 I/O로 요청시 보관해 둔 직렬화 버퍼를 정리해준다.
ULONG PacketCount = *pSentPacketCount;
for (ULONG i = 0; i < PacketCount; i++)
{
CPacket::Free(PacketArray[i]);
}
*pSentPacketCount = 0;
// 2. 요청한 비동기 Send가 완료되었으므로 이제 해당 세션에 대해 Send할 수 있게 되었음
*pIsSending = FALSE;
// 3. 아직 보내지 못한 것이 있는지 확인해서 있다면 보냄
if (pSendQ->size() > 0)
pThis->SendPost(pIsSending, pSendQ, pSendOverlapped, PacketArray, pSentPacketCount, pIoCount, *pSocket);
}
// I/O Count는 일반적으로 이곳에서 감소시킨다. ( 오류가 났을 경우는 오류가 발생한 곳에서 감소 시킴 )
// 감소결과 I/O COUNT가 0이 되면 세션을 릴리즈한다.
// 0으로 만든 스레드가 그 세션을 릴리즈 해야 한다.
pThis->SessionReleaseLock();
// 워커 스레드 일 끝났음
//pThis->OnWorkerThreadEnd();
}
return 0;
}
void GGM::CLanClient::CheckPacket(CRingBuffer *pRecvQ)
{
// 현재 RECV 링버퍼 사용량 체크
int CurrentUsage = pRecvQ->GetCurrentUsage();
int Result;
CPacket Packet(0);
char *pPacketbuf = (char*)Packet.GetBufferPtr();
LAN_HEADER Header;
// 링버퍼에 최소한 헤더길이 이상이 있는지 먼저확인한다.
// 헤더길이 이상이 있으면 루프돌면서 존재하는 완성된 패킷 다 뽑아서 OnRecv에 전달
while (CurrentUsage >= LAN_HEADER_LENGTH)
{
char *pPacket = pPacketbuf;
// 해당 세션 링버퍼에서 헤더만큼 PEEK
Result = pRecvQ->Peek((char*)&Header, LAN_HEADER_LENGTH);
if (Result != LAN_HEADER_LENGTH)
{
// 이것은 서버가 더 이상 진행하면 안되는 상황 덤프를 남겨서 문제를 확인하자
CCrashDump::ForceCrash();
break;
}
CurrentUsage -= LAN_HEADER_LENGTH;
// 현재 링버퍼에 완성된 패킷만큼 없으면 반복문 탈출
if (CurrentUsage < Header.size)
break;
// 완성된 패킷이 있다면 HEADER는 RecvQ에서 지워준다.
pRecvQ->EraseData(LAN_HEADER_LENGTH);
// 완성된 패킷을 뽑아서 직렬화 버퍼에 담는다.
Result = pRecvQ->Dequeue(pPacket, Header.size);
if (Result != Header.size)
{
// 이것은 서버가 더 이상 진행하면 안되는 상황 덤프를 남겨서 문제를 확인하자
CCrashDump::ForceCrash();
break;
}
Packet.RelocateWrite(Header.size);
// 완성된 패킷이 존재하므로 OnRecv에 완성 패킷을 전달한다.
OnRecv(&Packet);
// 현재 링버퍼의 사용 사이즈를 패킷 사이즈만큼 감소
CurrentUsage -= Header.size;
// 직렬화 버퍼를 재활용하기 위해 Rear와 Front 초기화
Packet.InitBuffer();
}
}
bool GGM::CLanClient::SendPost(
LONG *pIsSending,
CLockFreeQueue<CPacket*> *pSendQ,
LPOVERLAPPED pOverlapped,
CPacket **PacketArray,
ULONG *pSentPacketCount,
LONG *pIoCount,
SOCKET sock
)
{
///////////////////////////////////////////////////////////////////
// 0. Send 가능 플래그 체크
///////////////////////////////////////////////////////////////////
while (InterlockedExchange(pIsSending, TRUE) == FALSE)
{
// 현재 SendQ 사용량을 확인해서 보낼 것이 있는지 다시 한번 확인해본다.
// 보낼 것이 있는줄 알고 들어왔는데 보낼 것이 없을 수도 있다.
ULONG CurrentUsage = pSendQ->size();
// 보낼것이 없다면 Send 플래그 다시 바꾸어 주고 리턴
if (CurrentUsage == 0)
{
// 만약 이 부분에서 플래그를 바꾸기전에 컨텍스트 스위칭이 일어난다면 문제가 된다.
// 다른 스레드가 보낼 것이 있었는데 플래그가 잠겨있어서 못 보냈을 수도 있다.
//InterlockedBitTestAndReset(pIsSending, 0);
*pIsSending = FALSE;
// 만약 위에서 문제가 발생했다면 이 쪽에서 보내야 한다.
// 그렇지 않으면 아무도 보내지 않는 상황이 발생한다.
if (pSendQ->size() > 0)
continue;
return true;
}
///////////////////////////////////////////////////////////////////
// 1. WSASend용 Overlapped 구조체 초기화
///////////////////////////////////////////////////////////////////
ZeroMemory(pOverlapped, sizeof(OVERLAPPED));
///////////////////////////////////////////////////////////////////
//2. WSABUF 구조체 초기화
///////////////////////////////////////////////////////////////////
// SendQ에는 패킷단위의 직렬화버퍼 포인터가 저장되어 있다.
// 포인터를 SendQ에서 디큐해서 해당 직렬화 버퍼가 가지고 있는 패킷의 포인터를 WSABUF에 전달하고, 모아서 보낸다.
// 혼란방지용 [SendQ : 직렬화 버퍼의 포인터 (CPacket*)] [ WSABUF : 직렬화버퍼내의 버퍼포인터 (char*)]
// WSABUF에 한번에 모아 보낼 패킷의 개수는 정적으로 100 ~ 500개 사이로 정한다.
// WSABUF의 개수를 너무 많이 잡으면 시스템이 해당 메모리를 락 걸기 때문에 메모리가 이슈가 발생할 수 있다.
// 직렬화버퍼의 포인터와 송신한 개수를 보관했다가 완료통지가 뜨면 메모리 해제
// 직렬화 버퍼내의 패킷 메모리 포인터(char*)를 담을 WSABUF 구조체 배열
WSABUF wsabuf[MAX_PACKET_COUNT];
// SendQ에서 한번에 송신 가능한 패킷외 최대 개수만큼 직렬화 버퍼의 포인터를 Dequeue한다.
// 세션별로 가지고 있는 직렬화 버퍼 포인터 배열에 그것을 복사한다.
// Peek을 한 후 완료통지 이후에 Dequeue를 하면 memcpy가 추가적으로 일어나므로 메모리를 희생해서 횟수를 줄였다.
// 현재 큐에 들어있는 포인터의 개수가 최대치를 초과했다면 보정해준다.
if (CurrentUsage > MAX_PACKET_COUNT)
CurrentUsage = MAX_PACKET_COUNT;
for (ULONG i = 0; i < CurrentUsage; i++)
pSendQ->Dequeue(&PacketArray[i]);
// 보낸 패킷의 개수를 기억했다가 나중에 완료통지가 오면 메모리를 해제해야 한다.
DWORD PacketCount = *pSentPacketCount = CurrentUsage;
// 패킷 개수만큼 반복문 돌면서 실제 직렬화 버퍼 내의 패킷 버퍼 포인터를 WSABUF구조체에 저장
for (DWORD i = 0; i < PacketCount; i++)
{
wsabuf[i].buf = (char*)PacketArray[i]->GetBufferPtr();
wsabuf[i].len = PacketArray[i]->GetCurrentUsage();
}
///////////////////////////////////////////////////////////////////
// 3. WSASend 등록하기 전에 I/O 카운트 증가
///////////////////////////////////////////////////////////////////
InterlockedIncrement(pIoCount);
///////////////////////////////////////////////////////////////////
// 4. WSASend 요청
///////////////////////////////////////////////////////////////////
DWORD bytesSent = 0;
int Result = WSASend(sock, wsabuf, PacketCount, &bytesSent, 0, pOverlapped, nullptr);
///////////////////////////////////////////////////////////////////
// 5. WSASend 요청에 대한 예외처리
///////////////////////////////////////////////////////////////////
DWORD Error = WSAGetLastError();
if (Result == SOCKET_ERROR)
{
if (Error != WSA_IO_PENDING)
{
// Error 코드가 WSAENOBUFS라면 에러 전달
if (Error == WSAENOBUFS)
OnError(WSAENOBUFS, _T("WSAENOBUFS"));
// WSASend가 WSA_IO_PENDING 이외의 에러를 내면 함수 호출이 실패한것이다.
// I/O Count 감소시킨다.
SessionReleaseLock();
}
}
return true;
}
return true;
}
bool GGM::CLanClient::RecvPost(
CRingBuffer *pRecvQ,
LPOVERLAPPED pOverlapped,
LONG *pIoCount,
SOCKET sock
)
{
///////////////////////////////////////////////////////////////////
// 0. I/O 요청을 하기 전에 현재 링버퍼의 여유공간을 검사한다.
///////////////////////////////////////////////////////////////////
int CurrentSpare = pRecvQ->GetCurrentSpare();
///////////////////////////////////////////////////////////////////
// 1. WSARecv용 Overlapped 구조체 초기화
///////////////////////////////////////////////////////////////////
ZeroMemory(pOverlapped, sizeof(OVERLAPPED));
///////////////////////////////////////////////////////////////////
//2. WSABUF 구조체 초기화
///////////////////////////////////////////////////////////////////
// WSABUF를 두개 사용하는 이유는 링버퍼가 중간에 단절되었을 때에도 한번에 다 받기 위함이다.
WSABUF wsabuf[2];
int RecvBufCount = 1;
int RecvSize = pRecvQ->GetSizeWritableAtOnce();
// 첫번째 버퍼에 대한 정보를 구조체에 등록한다.
wsabuf[0].buf = pRecvQ->GetWritePtr();
wsabuf[0].len = RecvSize;
// 만약 링버퍼가 잘린 상태라면 두개의 버퍼에 나눠서 받는다.
if (CurrentSpare > RecvSize)
{
RecvBufCount = 2;
wsabuf[1].buf = pRecvQ->GetBufferPtr();
wsabuf[1].len = CurrentSpare - RecvSize;
}
//////////////////////////////////////////////////////////////////////
// 3. WSARecv 등록전에 I/O 카운트 증가, 다른 스레드에서도 접근하는 멤버이므로 락이 필요하다.
//////////////////////////////////////////////////////////////////////
InterlockedIncrement(pIoCount);
///////////////////////////////////////////////////////////////////
// 4. I/O 요청
///////////////////////////////////////////////////////////////////
DWORD BytesRead = 0;
DWORD Flags = 0;
int Result = WSARecv(sock, wsabuf, RecvBufCount, &BytesRead, &Flags, pOverlapped, nullptr);
///////////////////////////////////////////////////////////////////
// 5. I/O 요청에 대한 예외 처리
///////////////////////////////////////////////////////////////////
if (Result == SOCKET_ERROR)
{
DWORD Error = WSAGetLastError();
if (Error != WSA_IO_PENDING)
{
// 에러코드가 WSAENOBUFS라면 에러전달
if (Error == WSAENOBUFS)
OnError(WSAENOBUFS, _T("WSAENOBUFS"));
// WSARecv가 WSA_IO_PENDING 이외의 에러를 내면 함수 호출이 실패한것이다.
// I/O Count 감소시킨다.
SessionReleaseLock();
}
}
return true;
}
void GGM::CLanClient::ReleaseSession()
{
// ReleaseFlag 가 TRUE가 되면 어떤 스레드도 이 세션에 접근하거나 릴리즈 시도를 해서는 안된다.
// IoCount와 ReleaseFlag가 4바이트씩 연달아서 위치해 있으므로 아래와 같이 인터락함수 호출한다.
// IoCount(LONG) == 0 ReleaseFlag(LONG) == 0 >> 인터락 성공시 >>IoCount(LONG) == 0 ReleaseFlag(LONG) == 1
Session *pSession = &m_MySession;
if (InterlockedCompareExchange64((volatile LONG64*)&(pSession->IoCount), 0x0000000100000000, FALSE) != FALSE)
return;
ULONGLONG SessionID = pSession->SessionID++;
// 만약 직렬화 버퍼를 동적할당 후 Send하는 도중에 오류가나서 Release를 해야한다면
// 메모리를 해제해 주어야 한다.
ULONG PacketCount = pSession->SentPacketCount;
CPacket **PacketArray = pSession->PacketArray;
for (WORD i = 0; i < PacketCount; i++)
CPacket::Free(PacketArray[i]);
// 링버퍼 내에 남은 찌꺼기 제거
ULONG GarbagePacketCount = pSession->SendQ.size();
for (ULONG i = 0; i < GarbagePacketCount; i++)
{
CPacket *pGarbagePacket;
pSession->SendQ.Dequeue(&pGarbagePacket);
CPacket::Free(pGarbagePacket);
}
// 소켓 리소스 정리
closesocket(pSession->socket);
pSession->socket = INVALID_SOCKET;
// 해당 세션에 대한 모든 리소스가 정리되었으므로 이벤트 핸들링 함수 호출
OnDisconnect();
// 연결 끊겼을 때 재접속 옵션이 켜져있다면 재접속 시도
while (m_IsReconnect)
{
if (Connect() == true)
{
InterlockedIncrement(&ReconnectCount);
break;
}
Sleep(m_ReconnectDelay);
}
}
bool GGM::CLanClient::SessionAcquireLock(ULONGLONG LocalSessionID)
{
// 이 함수를 호출했다는 것은 이후 로직에서 해당 세션을 사용하겠다는 의미이다.
// 이 세션이 현재 어떤 상태인지는 모르지만 세션에 접근한다는 의미로, I/O Count를 증가시킨다.
// I/O Count를 먼저 증가시켰다면 릴리즈 되는 것을 막을 수 있다.
// 만약 I/O Count를 증가시켰는데 1이라면 더 이상의 세션 접근은 무의미하다.
ULONGLONG RetIOCount = InterlockedIncrement(&(m_MySession.IoCount));
if (RetIOCount == 1 || m_MySession.IsReleased == TRUE || m_MySession.SessionID != LocalSessionID)
return false;
return true;
}
void GGM::CLanClient::SessionReleaseLock()
{
// 세션에 대한 접근이 모두 끝났으므로 이전에 올린 I/O 카운트를 감소 시킨다.
LONG IoCount = InterlockedDecrement(&(m_MySession.IoCount));
if (IoCount <= 0)
{
if (IoCount < 0)
{
OnError(GGM_ERROR::NEGATIVE_IO_COUNT, _T("[CNetServer] SessionReleaseLock() IoCount Negative"));
CCrashDump::ForceCrash();
}
ReleaseSession();
}
}
bool CLanClient::CreateSocket()
{
// 소켓 생성
m_MySession.socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (m_MySession.socket == INVALID_SOCKET)
{
OnError(WSAGetLastError(), _T("Connect socket Creation Failed"));
return false;
}
// connect 할 때 논블락 소켓을 이용한다.
u_long NonBlockOn = 1;
int iResult = ioctlsocket(m_MySession.socket, FIONBIO, &NonBlockOn);
if (iResult == SOCKET_ERROR)
{
OnError(WSAGetLastError(), _T("ioctlsocket Failed"));
return false;
}
// TCP_NODELAY 플래그 확인해서 켜주기
if (m_IsNoDelay == true)
{
int iResult = setsockopt(
m_MySession.socket,
IPPROTO_TCP,
TCP_NODELAY,
(const char*)&m_IsNoDelay,
sizeof(m_IsNoDelay)
);
if (iResult == SOCKET_ERROR)
{
OnError(WSAGetLastError(), _T("setsockopt [TCP_NODELAY] Failed"));
return false;
}
}
// LINGER옵션 설정
LINGER linger = { 1,0 };
int Result = setsockopt(m_MySession.socket, SOL_SOCKET, SO_LINGER, (const char*)&linger, sizeof(linger));
if (Result == SOCKET_ERROR)
{
OnError(WSAGetLastError(), _T("setsockopt [SO_LINGER] Failed"));
return false;
}
// WSASend를 항상 비동기 I/O로 만들기 위해 소켓 송신 버퍼의 사이즈를 0으로 만든다.
/* int BufSize = 0;
Result = setsockopt(m_MySession.socket, SOL_SOCKET, SO_SNDBUF, (const char*)&BufSize, sizeof(BufSize));
if (Result == SOCKET_ERROR)
{
OnError(WSAGetLastError(), _T("setsockopt [SO_SNDBUF] Failed"));
return false;
}*/
return true;
}
}
|
21d253bbe057b495c6af41d2b3dd7fb55e409b20 | 891c4614ad009d25fea684cdd94f5d47f310941c | /leetcode/01. Two Sum.cpp | 19f418dc2ff04d4b2cb631bf27f29ef58f974196 | [] | no_license | parkcl/algorithm-practice | 28a70ddee3792dfa1c27fd255ec0bac5f4078f2b | 3dc94e387ec08d5eec6ecd4b1776e6c95304265f | refs/heads/master | 2021-06-21T12:42:55.801665 | 2017-06-01T16:17:19 | 2017-06-01T16:17:19 | 88,552,948 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,211 | cpp | 01. Two Sum.cpp | /**
Problem statement: given input vector, nums, return indices
of the two numbers such that they add up to a specific target.
*/
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> intLookupTable;
int index = -1;
for (vector<int>::const_iterator i = nums.begin(); i != nums.end(); ++i)
intLookupTable[*i] = ++index;
index = 0;
for (vector<int>::const_iterator i = nums.begin(); i != nums.end(); ++i) {
int diffTarg = target - *i;
// if there exists a B such that B = target - nums[i]
if (intLookupTable.find(diffTarg) == intLookupTable.end()) {
} else if (intLookupTable.at(diffTarg) != index){
int otherIndex = intLookupTable.at(diffTarg);
vector<int> result;
if (otherIndex < index) {
result = {otherIndex, index};
} else {
result = {index, otherIndex};
}
return result;
}
++index;
}
vector<int> empty;
return empty;
}
};
|
988a0432df75eb4e82fa62d554bd32f6a85e75f7 | 0c441322e08aa622c06433cbeef476d0e14ef679 | /Dec1_2019/const_pointers.cpp | 426c8840b98be07888e7c7ca228954fdf7a9a41d | [] | no_license | Shreya-Shetty2019/Sample | 64936059450f02875d837b1b82a36336b2d9efe2 | 7fdfec4926d0b9bb18f3f49e98c9b1415851d436 | refs/heads/master | 2020-09-16T13:55:14.473481 | 2019-12-01T18:46:49 | 2019-12-01T18:46:49 | 223,789,933 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 876 | cpp | const_pointers.cpp | #include<iostream>
int main()
{
int val=20;
int count=56;
const int *ptr=&val;
//pointers to integer constants
std::cout<<"value of val is "<<val<<std::endl;
std::cout<<"value of ptr is "<<*ptr<<std::endl;
//*ptr=90; //ERROR
//-------------------------constant pointers-------------------------------------------------------//
int *const const_ptr=&count;
std::cout<<"value of count is "<<count<<std::endl;
std::cout<<"value of const_ptr is "<<*const_ptr<<std::endl;
count=89;
*const_ptr=79;
std::cout<<"value of const_ptr is "<<count<<std::endl;
//const_ptr=&val; //ERROR
//-----------------constant pointers to constants----------------//
int j_value=90;
const int *const j_ptr=&j_value;
std::cout<<"j_value = "<<j_value<<std::endl<<"j_ptr = "<<*j_ptr<<std::endl;
j_value=45;
*j_ptr=456;
std::cout<<"j_value "<<j_value;
return 0;
} |
5671f4f671a6ca861297ffb5a5ae4c87e1a21b12 | ff98cec1bc75685c346795259f9083880dee0ba8 | /bank.cpp | 90212bfb0dd4de95932f5ae545c26e31b0b1653a | [] | no_license | ralfleistad/Kattis | cb8560708db3be2beb29e5ec17fbd88f435201d8 | 55e2719c1bbfb0c5f7f2cc7ea0e0edce4cebddc7 | refs/heads/master | 2021-06-27T10:50:47.032372 | 2020-12-18T10:30:24 | 2020-12-18T10:30:24 | 187,688,568 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,221 | cpp | bank.cpp | #include <cmath>
#include <iomanip>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <map>
#include <string>
#include <bitset>
#include <climits>
#include <queue>
#include <cstring>
using namespace std;
struct Person {
int cash;
int leave;
};
bool CMP(const Person a, const Person b) {
return a.cash >= b.cash;
}
void enqueue(vector<int> &vec, Person p) {
int time = p.leave;
while(time >= 0) {
if(vec[time] == 0) {
vec[time] = p.cash;
return;
}
time--;
}
}
int main() {
int n, t;
cin >> n >> t;
vector< int > queue (t, 0);
vector< Person > line;
for(int i = 0; i < n; i++) {
Person p;
cin >> p.cash;
cin >> p.leave;
line.push_back(p);
}
sort(line.begin(), line.end(), CMP);
for(int i = 0; i < line.size(); i++) {
enqueue(queue, line[i]);
}
int total = 0;
for(int i = 0; i < queue.size(); i++) {
total += queue[i];
}
cout << total << endl;
return 0;
} |
44163dc44d0f675599792c9fcc856752d972b861 | c10650383e9bb52ef8b0c49e21c10d9867cb033c | /c++/MFC_Broadcast_Server/MFC_Broadcast_ServerDlg.cpp | ce0f095ca26726db0c66444acfac8fc828707676 | [] | no_license | tangyiyong/Practise-project | f1ac50e8c7502a24f226257995e0457f43c45032 | 4a1d874d8e3cf572b68d56518a2496513ce5cb27 | refs/heads/master | 2020-08-11T16:28:11.670852 | 2016-03-05T04:24:41 | 2016-03-05T04:24:41 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 16,437 | cpp | MFC_Broadcast_ServerDlg.cpp | // MFC_Broadcast_ServerDlg.cpp : implementation file
//
#include "stdafx.h"
#include "MFC_Broadcast_Server.h"
#include "MFC_Broadcast_ServerDlg.h"
#include "DialogSendMSG.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CMFC_Broadcast_ServerDlg dialog
CMFC_Broadcast_ServerDlg::CMFC_Broadcast_ServerDlg(CWnd* pParent /*=NULL*/)
: CDialog(CMFC_Broadcast_ServerDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CMFC_Broadcast_ServerDlg)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CMFC_Broadcast_ServerDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CMFC_Broadcast_ServerDlg)
DDX_Control(pDX, IDC_LIST, m_list);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CMFC_Broadcast_ServerDlg, CDialog)
//{{AFX_MSG_MAP(CMFC_Broadcast_ServerDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BTB_START, OnBtbStart)
ON_BN_CLICKED(IDC_BTB_STOP, OnBtbStop)
ON_WM_DESTROY()
ON_BN_CLICKED(IDC_BTN_FLUSH, OnBtnFlush)
ON_NOTIFY(NM_RCLICK, IDC_LIST, OnRclickList)
ON_COMMAND(IDC_MENU_SENDMSG, OnMenuSendmsg)
ON_COMMAND(IDC_MENU_SEESCREEN, OnMenuSeescreen)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CMFC_Broadcast_ServerDlg message handlers
BOOL CMFC_Broadcast_ServerDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
//检测程序是否多开
HANDLE hMutex = CreateMutex(NULL, FALSE, "SERVER"); //创建互斥体
if(GetLastError() == ERROR_ALREADY_EXISTS)
{
// 如果已有互斥量存在则释放句柄并复位互斥量
CloseHandle(hMutex);
hMutex = NULL;
AfxMessageBox("程序已经启动!");
// 程序退出
exit(0);
ExitProcess(0);
PostQuitMessage(0);//会启动然后再关闭
}
//加载菜单
m_LRMenu.LoadMenu(IDR_MENU_LIST);
//初始化List
m_list.SetExtendedStyle(LVS_EX_FULLROWSELECT|LVS_EX_GRIDLINES);
m_list.InsertColumn(0, "主机名", LVCFMT_LEFT, 75);
m_list.InsertColumn(1, "IP地址", LVCFMT_LEFT, 110);
//初始化套接字
m_hSocket=::socket(AF_INET,SOCK_DGRAM,0);
SOCKADDR_IN in={0};
in.sin_addr.S_un.S_addr=0;
in.sin_family=AF_INET;
in.sin_port=htons(7788);
::bind(m_hSocket,(SOCKADDR *)&in,16);
bool opt=true; //设置该套接字为广播类型,
setsockopt(m_hSocket,SOL_SOCKET,SO_BROADCAST,(char FAR *)&opt,sizeof(opt));
int nSendBuf=PACKSIZE*10;//设置为80K
setsockopt(m_hSocket,SOL_SOCKET,SO_SNDBUF,(const char*)&nSendBuf,sizeof(int));
setsockopt(m_hSocket,SOL_SOCKET,SO_RCVBUF,(const char*)&nSendBuf,sizeof(int));
//获取屏幕大小(px)
m_hDcScreen=CDC::FromHandle(::GetDC(NULL));
m_Screenw=m_hDcScreen->GetDeviceCaps(HORZRES);
m_Screenh=m_hDcScreen->GetDeviceCaps(VERTRES);
//初始化位图信息头
DWORD nImageSize = m_Screenw * m_Screenh * 2;
memset(&m_biScreen,0,sizeof(m_biScreen));
m_biScreen.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
m_biScreen.bmiHeader.biWidth = m_Screenw;
m_biScreen.bmiHeader.biHeight = m_Screenh;
m_biScreen.bmiHeader.biBitCount = 16;
m_biScreen.bmiHeader.biCompression = BI_RGB;
m_biScreen.bmiHeader.biPlanes = 1;
m_biScreen.bmiHeader.biSizeImage = nImageSize;
//获取屏幕描述表
m_bmpMemNow.CreateCompatibleBitmap(m_hDcScreen, m_Screenw, m_Screenh);
m_dcMemNow.CreateCompatibleDC(m_hDcScreen);
m_dcMemNow.SelectObject(&m_bmpMemNow);
m_bmpMemOld.CreateCompatibleBitmap(m_hDcScreen, m_Screenw, m_Screenh);
m_dcMemOld.CreateCompatibleDC(m_hDcScreen);
m_dcMemOld.SelectObject(&m_bmpMemOld);
m_pBufScreen=new BYTE[nImageSize];
memset(m_pBufScreen, 0,m_biScreen.bmiHeader.biSizeImage);
m_pBufEncode1 = new BYTE[m_biScreen.bmiHeader.biSizeImage];
memset(m_pBufEncode1, 0, m_biScreen.bmiHeader.biSizeImage);
m_pBufEncode2 = new BYTE[m_biScreen.bmiHeader.biSizeImage];
memset(m_pBufEncode2, 0,m_biScreen.bmiHeader.biSizeImage);
memset(&m_addrTo, 0, sizeof(SOCKADDR_IN));
m_addrTo.sin_family = AF_INET;
m_addrTo.sin_addr.S_un.S_addr = inet_addr("255.255.255.255");//htonl(INADDR_BROADCAST); //设置ip为广播地址 即: 192.168.0.255
m_addrTo.sin_port = htons(UDP_PORT);
m_hThread=NULL;
m_hThreadRev=::CreateThread(NULL,0,ReceiveThread,this,0,NULL); //创建接收线程
return TRUE; // return TRUE unless you set the focus to a control
}
void CMFC_Broadcast_ServerDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CMFC_Broadcast_ServerDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CMFC_Broadcast_ServerDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
void CMFC_Broadcast_ServerDlg::OnBtbStart()
{
// 通知学生端打开窗口,准备开始接收
PACKHEAD head = {0};
head.nFlag = PH_START_BROADCAST; //1开始广播
head.biScreen = m_biScreen;
memset(m_bufSend, 0, PACKSIZE);
memcpy(m_bufSend, &head, sizeof(PACKHEAD));
int nSent = ::sendto(m_hSocket, (char *)m_bufSend, PACKSIZE, 0, (SOCKADDR *)&m_addrTo, sizeof(SOCKADDR));
if (nSent == SOCKET_ERROR)
{
CString sMsg;
sMsg.Format("不能开始广播, 错误代码为: %d", GetLastError());
this->MessageBox(sMsg);
return;
}
::Sleep(100);
if(m_hThread==NULL)
{
m_hThread=::CreateThread(NULL,0,SendThread,this,0,NULL);
IsThreadRuning=TRUE;
}
else
{
if(IsThreadRuning==FALSE)
{
::ResumeThread(m_hThread);
IsThreadRuning=TRUE;
}
}
}
DWORD WINAPI CMFC_Broadcast_ServerDlg::SendThread(LPVOID p)
{
CMFC_Broadcast_ServerDlg *pDlg=(CMFC_Broadcast_ServerDlg *)p;
while(1)
{
pDlg->DoSend();
}
::Sleep(10);
return 0;
}
void CMFC_Broadcast_ServerDlg::DoSend()
{
SYSTEMTIME tm0, tm1;
::GetLocalTime(&tm0);
//获取屏幕
m_dcMemNow.BitBlt(0, 0, m_Screenw, m_Screenh, m_hDcScreen, 0, 0, SRCCOPY);//获取屏幕位图
//绘制鼠标
CURSORINFO ci = {0};
ci.cbSize = sizeof(CURSORINFO);
GetCursorInfo(&ci);
ICONINFO ii = {0};
GetIconInfo(ci.hCursor, &ii);
m_dcMemNow.DrawIcon(ci.ptScreenPos.x-ii.xHotspot, ci.ptScreenPos.y-ii.yHotspot, ci.hCursor);
::DeleteObject(ii.hbmColor);
::DeleteObject(ii.hbmMask);
//每30帧发完整帧
static UINT nFrame = -1;
nFrame++;
if (nFrame % 60 == 0) //每隔30帧就传一个完整帧给学生端
{
m_dcMemOld.FillSolidRect(0, 0,m_Screenw,m_Screenh, 0x00000000); //黑色
}
//将 当前屏 和 上一屏 进行异或, 结果存入m_dcMemOld的m_bmpMemOld中
// 此时的m_dcMemOld中保留的是当前图和上幅图不同的部分, 相同部分全部是0
//m_dcMemOld.BitBlt(0, 0,m_Screenw,m_Screenh, &m_dcMemNow, 0, 0, SRCCOPY);
m_dcMemOld.BitBlt(0, 0,m_Screenw,m_Screenh, &m_dcMemNow, 0, 0,SRCINVERT);
//将异或之后的位图数据保存到屏幕缓冲m_pBufScreen
GetDIBits(m_dcMemOld,m_bmpMemOld,0,m_Screenh,m_pBufScreen,(LPBITMAPINFO)&m_biScreen,DIB_RGB_COLORS);
//保存当前屏于m_pDCMemOld
m_dcMemOld.BitBlt(0, 0,m_Screenw,m_Screenh, &m_dcMemNow, 0, 0, SRCCOPY);
//压缩数据
//1次压缩 m_pBufNow --> m_pBufEncode1
qlz_state_compress *qsc = NULL;
memset(m_pBufEncode1, 0,m_biScreen.bmiHeader.biSizeImage);
qsc = (qlz_state_compress *)malloc(sizeof(qlz_state_compress));
DWORD dwEncodedSize1 = qlz_compress((char*)m_pBufScreen, (char*)m_pBufEncode1,m_biScreen.bmiHeader.biSizeImage, qsc);
free(qsc);
//2次压缩 m_pBufEncode1 --> m_pBufEncode2
memset(m_pBufEncode2, 0, m_biScreen.bmiHeader.biSizeImage);
qsc = (qlz_state_compress *)malloc(sizeof(qlz_state_compress));
DWORD dwEncodedSize2 = qlz_compress((char*)m_pBufEncode1, (char*)m_pBufEncode2,dwEncodedSize1, qsc);
free(qsc);
//生成信息头
PACKHEAD head = {0}; //3发送帧PACKSIZE =32768
head.nFlag = PH_SEND_FRAMEPART;
head.nFrame = nFrame;
head.nPartCnt = WORD((dwEncodedSize2 + PACKSIZE - sizeof(PACKHEAD) - 1) / (PACKSIZE - sizeof(PACKHEAD)));
head.biScreen = m_biScreen;
DWORD nSentSum = 0;
while (nSentSum < dwEncodedSize2)
{
DWORD nWill = dwEncodedSize2 - nSentSum;
nWill = min(nWill, PACKSIZE - sizeof(PACKHEAD));
head.nPartID++;
memcpy(m_bufSend, &head, sizeof(PACKHEAD));
memcpy(m_bufSend + sizeof(PACKHEAD), m_pBufEncode2 + nSentSum, nWill);
DWORD nSent = ::sendto(m_hSocket, (char *)m_bufSend,
nWill + sizeof(PACKHEAD), 0, (SOCKADDR *)&m_addrTo, sizeof(SOCKADDR));
::Sleep(5);
if (nSent > 0)
{
nSentSum += (nSent - sizeof(PACKHEAD));
}
else
{
TRACE("发送第 %d 帧 的 第 %d of %d 部分时出错, 错误代码为: %d",
head.nFrame, head.nPartID, head.nPartCnt, GetLastError());
break;
}
TRACE("Frame %d : Part %d of %d\r\n", head.nFrame, head.nPartID, head.nPartCnt);
}
//8. 延时(最多10帧/s = 1000 / 100)
::GetLocalTime(&tm1);
int ms = 1000 * (tm1.wSecond - tm0.wSecond) + (tm1.wMilliseconds - tm0.wMilliseconds);
if (ms < 100 && ms > 0) //重大bug修正: 要加上 && ms > 0, 否则当ms < 0时, 延时会非常久,用户感觉是死机了
::Sleep(100 - ms);
}
void CMFC_Broadcast_ServerDlg::OnBtbStop()
{
// 通知学生端隐藏窗口
PACKHEAD head = {0};
head.nFlag = PH_STOP_BROADCAST; //停止广播
memset(m_bufSend, 0, PACKSIZE);
memcpy(m_bufSend, &head, sizeof(PACKHEAD));
int nSent = ::sendto(m_hSocket, (char *)m_bufSend, PACKSIZE, 0, (SOCKADDR *)&m_addrTo, sizeof(SOCKADDR));
if (nSent == SOCKET_ERROR)
{
CString sMsg;
sMsg.Format("不能开始广播, 错误代码为: %d", GetLastError());
this->MessageBox(sMsg);
return;
}
::Sleep(10);
if(IsThreadRuning==TRUE)
{
::SuspendThread(m_hThread);
IsThreadRuning=FALSE;
}
}
DWORD WINAPI CMFC_Broadcast_ServerDlg::ReceiveThread(LPVOID p)
{
CMFC_Broadcast_ServerDlg *pDlg=(CMFC_Broadcast_ServerDlg *)p;
while(1)
{
pDlg->DoReceive();
}
return 0;
}
void CMFC_Broadcast_ServerDlg::DoReceive()
{
memset(m_bufRecv, 0, PACKSIZE);
SOCKADDR_IN addrFrom = {0};
int nLen = sizeof(SOCKADDR);
int nRecv = ::recvfrom(m_hSocket, (char *)m_bufRecv,sizeof(PACKHEAD),MSG_PEEK, (SOCKADDR *)&addrFrom, &nLen);
int err=::WSAGetLastError(); //10022 WSANOTINITIALISED
PACKHEAD *pHead = (PACKHEAD *)m_bufRecv;
switch(pHead->nFlag)
{
case PH_USER_ONLINE:
DoUserOnline();
break;
case PH_USER_OFFLINE:
DoUserOffline();
break;
case PH_USER_OLTEST:
::recvfrom(m_hSocket, (char *)m_bufRecv,sizeof(PACKHEAD),0, (SOCKADDR *)&addrFrom, &nLen);
break;
case PH_USER_OLREPLY:
DoUserOLReply();
break;
default:
::recvfrom(m_hSocket, (char *)m_bufRecv,PACKSIZE,0, (SOCKADDR *)&addrFrom, &nLen);
break;
}
}
void CMFC_Broadcast_ServerDlg::DoUserOnline()
{
SOCKADDR_IN addrFrom = {0};
int nLen = sizeof(SOCKADDR);
int nRecv = ::recvfrom(m_hSocket, (char *)m_bufRecv,PACKSIZE,0, (SOCKADDR *)&addrFrom, &nLen);
HOSTENT pHost;
in_addr ina;
ina.S_un.S_addr = addrFrom.sin_addr.S_un.S_addr;
pHost=*::gethostbyaddr((char *)&ina.S_un.S_addr,4,AF_INET);
CString sIP;
sIP.Format("%s",inet_ntoa(ina));
int n=m_list.GetItemCount();
for(int i=0;i<n;i++)
if(m_list.GetItemText(i,1)==sIP)
return;
m_list.InsertItem(n,pHost.h_name);
m_list.SetItemText(n,1,inet_ntoa(ina));
UpdateListNOH();
}
void CMFC_Broadcast_ServerDlg::OnDestroy()
{
CDialog::OnDestroy();
::TerminateThread(m_hThreadRev,0);
m_dcMemNow.DeleteDC();
m_dcMemOld.DeleteDC();
m_bmpMemNow.DeleteObject();
m_bmpMemOld.DeleteObject();
delete[] m_pBufScreen;
delete[] m_pBufEncode1;
delete[] m_pBufEncode2;
::closesocket(m_hSocket);
}
void CMFC_Broadcast_ServerDlg::DoUserOffline()
{
SOCKADDR_IN addrFrom = {0};
int nLen = sizeof(SOCKADDR);
int nRecv = ::recvfrom(m_hSocket, (char *)m_bufRecv,PACKSIZE,0, (SOCKADDR *)&addrFrom, &nLen);
CString sIP;
sIP.Format("%s",inet_ntoa(addrFrom.sin_addr));
int n=m_list.GetItemCount();
for(int i=0;i<n;i++)
if(m_list.GetItemText(i,1)==sIP)
{
m_list.DeleteItem(i);
UpdateListNOH();
}
}
void CMFC_Broadcast_ServerDlg::OnBtnFlush()
{
m_list.DeleteAllItems();
//发送在线测试
PACKHEAD ph={0};
ph.nFlag=PH_USER_OLTEST;
SOCKADDR_IN m_addrTo={0};
m_addrTo.sin_family = AF_INET;
m_addrTo.sin_addr.S_un.S_addr = inet_addr("255.255.255.255");//htonl(INADDR_BROADCAST); //设置ip为广播地址 即: 192.168.0.255
m_addrTo.sin_port = htons(UDP_PORT);
int n=::sendto(m_hSocket, (char *)&ph,sizeof(PACKHEAD), 0, (SOCKADDR *)&m_addrTo, sizeof(SOCKADDR));
}
void CMFC_Broadcast_ServerDlg::DoUserOLReply()
{
::Sleep(100);
//实际接收
SOCKADDR_IN addrFrom = {0};
int nLen = sizeof(SOCKADDR);
int nRecv = ::recvfrom(m_hSocket, (char *)m_bufRecv, sizeof(PACKHEAD), 0, (SOCKADDR *)&addrFrom, &nLen);
if (nRecv == SOCKET_ERROR)
{
TRACE("接收错误, 错误代码为: %d\r\n", GetLastError());
return;
}
HOSTENT pHost;
in_addr ina;
ina.S_un.S_addr = addrFrom.sin_addr.S_un.S_addr;
pHost=*::gethostbyaddr((char *)&ina.S_un.S_addr,4,AF_INET);
CString sIP;
sIP.Format("%s",inet_ntoa(ina));
int n=m_list.GetItemCount();
for(int i=0;i<n;i++)
if(m_list.GetItemText(i,1)==sIP)
return;
m_list.InsertItem(n,pHost.h_name);
m_list.SetItemText(n,1,inet_ntoa(ina));
UpdateListNOH();
}
void CMFC_Broadcast_ServerDlg::UpdateListNOH()
{
CString s;
s.Format("在线主机数:%d",m_list.GetItemCount());
//this->MessageBox(s);
this->SetDlgItemText(IDC_STATIC_NOH,s);
}
void CMFC_Broadcast_ServerDlg::OnRclickList(NMHDR* pNMHDR, LRESULT* pResult)
{
NMLISTVIEW * pNMListView = (NMLISTVIEW*)pNMHDR;
int nItem = pNMListView->iItem;
if (nItem == -1) return;
sRClckHost=m_list.GetItemText(nItem,0);
sRClckIP=m_list.GetItemText(nItem,1);
CPoint point;
::GetCursorPos(&point);
this->SetForegroundWindow();
this->m_LRMenu.GetSubMenu(0)->TrackPopupMenu(TPM_LEFTALIGN|TPM_RIGHTBUTTON,point.x,point.y,this);
*pResult = 0;
}
void CMFC_Broadcast_ServerDlg::OnMenuSendmsg()
{
CDialogSendMSG DlgMsg;
DlgMsg.m_sIP=sRClckIP;
DlgMsg.m_sHost=sRClckHost;
DlgMsg.m_hSocket=m_hSocket;
DlgMsg.DoModal();
}
void CMFC_Broadcast_ServerDlg::OnMenuSeescreen()
{
}
|
c62024feaa651e8ff0c4a46b9c62dbf666edb150 | cb71095aa80406ee7c9a02ed37d0f616b7d1cdcc | /Kurs7_Alla_and_Yulya/class_player.cpp | 18ba3de4b92cc42494454dadea99a911122bc448 | [] | no_license | TokiSeven/university_course2_informatics_coursework_forYulyaAndAlla | 7b73aa4a79ac70b2db522e5021b06d15cd0bcef8 | 7ad236946248f36110ebce70d78bb1cbc3b50c7a | refs/heads/master | 2021-01-15T09:02:40.094609 | 2016-01-14T21:33:57 | 2016-01-14T21:33:57 | null | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 1,367 | cpp | class_player.cpp | #include "class_player.h"
CLASS_PLAYER::CLASS_PLAYER(float x, float y, Texture &image) : CLASS_UNIT(x, y, image)
{
score = 0;
lifeCount = 3;
maxLifeCount = 3;
rect.width = rect.width / 2;
sprite.setTextureRect(IntRect(0, 0, 64, 63));
}
CLASS_PLAYER::~CLASS_PLAYER()
{
delete this;
}
void CLASS_PLAYER::jump()
{
if (this->onGround)
{
dy = -0.7;
this->state = Jump;
}
}
void CLASS_PLAYER::right()
{
dx = 0.3;
this->state = Right;
}
void CLASS_PLAYER::left()
{
dx = -0.3;
this->state = Left;
}
void CLASS_PLAYER::animation(float time)
{
// загрузим анимацию
// скорость анимации 0.005
currentFrame += 0.005 * time;
if (currentFrame > 2)
currentFrame -= 2; // два кадров
if (dx > 0)
sprite.setTextureRect(IntRect(64 * (int)currentFrame, 0, 64, 63));
if (dx < 0)
sprite.setTextureRect(IntRect(64 * (int)currentFrame + 64, 0, -64, 63));
}
void CLASS_PLAYER::AI(TYPE_OF_TILE colTileX, TYPE_OF_TILE colTileY)
{
if (lifeCount <= 0)
die();
if (lifeCount > 3)
lifeCount = 3;
}
void CLASS_PLAYER::damage(int count)
{
if (lifeCount > 0)
lifeCount -= count;
}
void CLASS_PLAYER::heal(int count)
{
if (lifeCount > 0 && lifeCount <= maxLifeCount)
lifeCount += count;
}
|
d8a8de8e44fa2ace1b014e27d359ba3cc9c09773 | f4b844363d692373d80d1340ddd98ced9a6cd47d | /Barbarian.hpp | c4b4296c22b01884a73bc6448de2e9aaeef0bc43 | [] | no_license | bpoore/162_Fantasy_Game | e7024861835fed3c010e7cc9bfeb20bf211106e1 | 35008665f2861860e355b147ac2fb50685a593b9 | refs/heads/master | 2020-12-24T19:28:24.208863 | 2016-04-29T06:13:50 | 2016-04-29T06:13:50 | 57,358,387 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 457 | hpp | Barbarian.hpp | /*********************************************************************
** Author: Elizabeth Poore
** Date: May 5, 2015
** Description: Barbarian.hpp is the Barbarian class specification file
*********************************************************************/
#ifndef BARBARIAN_HPP
#define BARBARIAN_HPP
class Barbarian : public Character
{
public:
Barbarian(std::string n);
~Barbarian();
virtual Damage attack();
virtual int defense();
};
#endif
|
fe8de7cdee05ff66003fcdffe33cf47438b880e3 | 73935c1814a8fe260167d4aa1b01d39de72f5c0f | /src/server/game/Entities/Unit/UnitMovement.h | 1a62210e9de35bb5fefe911e166b8b20f9eea606 | [] | no_license | planee/Mop-548 | e794ed978237f355efa813c2be8f8fb14d1907dc | a852cc0be53fcc2951b51452e3ebaa9f1d7d7397 | refs/heads/master | 2022-12-23T01:08:51.566255 | 2020-09-25T03:55:52 | 2020-09-25T03:55:52 | 298,549,776 | 1 | 7 | null | 2020-09-25T11:10:28 | 2020-09-25T11:10:27 | null | UTF-8 | C++ | false | false | 1,521 | h | UnitMovement.h | /*
* Copyright (C) 2012 - 2016 WoWSource
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#ifndef _UNIT_MOVEMENT_H
#define _UNIT_MOVEMENT_H
#include "DBCStructure.h"
#include "EventProcessor.h"
#include "FollowerReference.h"
#include "FollowerRefManager.h"
#include "HostileRefManager.h"
#include "MotionMaster.h"
#include "Object.h"
#include "ObjectMovement.h"
#include "SpellAuraDefines.h"
#include "ThreatManager.h"
namespace Movement
{
class ExtraMovementStatusElement;
class MoveSpline;
}
enum UnitMoveType
{
MOVE_WALK = 0,
MOVE_RUN = 1,
MOVE_RUN_BACK = 2,
MOVE_SWIM = 3,
MOVE_SWIM_BACK = 4,
MOVE_TURN_RATE = 5,
MOVE_FLIGHT = 6,
MOVE_FLIGHT_BACK = 7,
MOVE_PITCH_RATE = 8
};
#define MAX_MOVE_TYPE 9
extern float baseMoveSpeed[MAX_MOVE_TYPE];
extern float playerBaseMoveSpeed[MAX_MOVE_TYPE];
#endif
|
c5108cc1dc8b935aadd72ea4cb949d9456d56a81 | 40da32f08e1fbe68f6a17036fba7f5fc11c05a59 | /types/address.h | f45f7c392e1272cf70f60be362375439360bbd10 | [] | no_license | rjhayortega/auction | d18439157a55f3ac55b420eadddcd92588fc55da | 4a5dd3c96ecabe01ccd387381b03ae5712ef4001 | refs/heads/master | 2020-04-17T13:10:49.982631 | 2019-01-19T23:32:57 | 2019-01-19T23:32:57 | 166,604,493 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 928 | h | address.h |
#ifndef _ADDRESS_H_
#define _ADDRESS_H_
/******************************************************************************
-
- class Address
-
- purpose: Encapsulates an address
-
- Notes:
-
- Todo:
-
*****************************************************************************/
#include <string>
using namespace std;
class Address
{
public:
Address(string="",string="", string="", string="", string="", string="", string="");
void setAddress1(string);
void setAddress2(string);
void setCity(string);
void setState(string);
void setZip(string);
void setUnit(string);
void setCounty(string);
string getAddress1();
string getAddress2();
string getCity();
string getState();
string getZip();
string getUnit();
string getCounty();
string cityStateZipStr();
private:
string address1;
string address2;
string city;
string state;
string zip;
string unit;
string county;
};
#endif
|
d6bfb2e919334922b7458a4c3a93d2294ccf8dee | e85c74e0c08a8e8497bae3d6cec788e811249b73 | /test_model.cpp | f09cbc6d75831bf902d59f6c31668199fe36f60e | [] | no_license | ykerit/daal_case | 80b4a806d2d497725f36c4f940899db36a24f7c1 | 303911d95b720a5b7002077c323b7ab730eb6500 | refs/heads/master | 2023-06-12T18:38:56.658865 | 2021-07-01T04:53:18 | 2021-07-01T04:53:18 | 381,904,147 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,616 | cpp | test_model.cpp | #include "daal.h"
#include "service.h"
#include <fstream>
#include <iostream>
#include <assert.h>
using namespace daal;
using namespace daal::algorithms;
using namespace daal::data_management;
using namespace daal::algorithms::gbt::regression;
void load_data(NumericTablePtr& test_data) {
float data[27 * 2] = {1.0};
test_data = HomogenNumericTable<>::create(data, 27, 2);
}
void test_model() {
NumericTablePtr testData;
load_data(testData);
prediction::Batch<float> algorithm;
auto model_path = "./bst_wf_test.txt";
std::ifstream file(model_path, std::ios::in|std::ios::binary|std::ios::ate);
if(!file) {
std::cout << "loading model error" <<std::endl;
assert(false);
}
size_t length = file.tellg();
file.seekg(0, std::ios::beg);
byte* buffer = new byte[length];
file.read((char*)buffer, length);
file.close();
OutputDataArchive out_dataArch(buffer, length);
delete[] buffer;
daal::algorithms::gbt::regression::ModelPtr deserialized_model = daal::algorithms::gbt::regression::Model::create(27);
deserialized_model->deserialize(out_dataArch);
std::cout << deserialized_model->numberOfTrees() << std::endl;
std::cout << deserialized_model->getNumberOfFeatures() << std::endl;
algorithm.input.set(prediction::data, testData);
algorithm.input.set(prediction::model, deserialized_model);
algorithm.compute();
prediction::ResultPtr predictionResult = algorithm.getResult();
printNumericTable(predictionResult->get(prediction::prediction), "Gragient boosted trees prediction results (first 10 rows):", 10);
}
int main()
{
test_model();
return 0;
}
|
c46e0d7def2e5a4586fb574ea34c4d330ec3a166 | 74a0046ec32d45942144b1526d9d7f580f154bbf | /vendor/snarkv/include/snark/stransaction.h | 55844ef1377151411dbafde7e3c2df5af52f2a5b | [
"MIT",
"Apache-2.0"
] | permissive | chain2future-os/future-core | e93c7d166392902862717d555044cd223efc295f | 030a2be7be92f205439334bd9a848843b0922cb0 | refs/heads/master | 2022-12-15T08:01:28.507126 | 2020-08-25T03:38:34 | 2020-08-25T03:38:34 | 290,100,867 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,291 | h | stransaction.h | #ifndef _S_TRANSACTION_H_
#define _S_TRANSACTION_H_
#include <fc/reflect/reflect.hpp>
#include "snark/uint256.h"
#include "snark/note_encryption.h"
#include "snark/serialize.h"
#include "snark/util_str_encodings.h"
typedef int64_t CAmount;
typedef std::array<unsigned char, 64> spend_auth_sig_t;
typedef std::array<unsigned char, 64> binding_sig_t;
static constexpr size_t GROTH_PROOF_SIZE = (
48 + // π_A
96 + // π_B
48); // π_C
typedef std::array<unsigned char, GROTH_PROOF_SIZE> GrothProof;
class SpendDescription
{
public:
zero::uint256 cv; //!< A value commitment to the value of the input note.
zero::uint256 anchor; //!< A Merkle root of the Sapling note commitment tree at some block height in the past.
zero::uint256 nullifier; //!< The nullifier of the input note.
zero::uint256 rk; //!< The randomized public key for spendAuthSig.
GrothProof zkproof; //!< A zero-knowledge proof using the spend circuit.
spend_auth_sig_t spendAuthSig; //!< A signature authorizing this spend.
SpendDescription() { }
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(cv);
READWRITE(anchor);
READWRITE(nullifier);
READWRITE(rk);
READWRITE(zkproof);
READWRITE(spendAuthSig);
}
friend bool operator==(const SpendDescription& a, const SpendDescription& b)
{
return (
a.cv == b.cv &&
a.anchor == b.anchor &&
a.nullifier == b.nullifier &&
a.rk == b.rk &&
a.zkproof == b.zkproof &&
a.spendAuthSig == b.spendAuthSig
);
}
friend bool operator!=(const SpendDescription& a, const SpendDescription& b)
{
return !(a == b);
}
};
class OutputDescription
{
public:
zero::uint256 cv; //!< A value commitment to the value of the output note.
zero::uint256 cm; //!< The note commitment for the output note.
zero::uint256 ephemeralKey; //!< A Jubjub public key.
zero::uint256 outEphemeralKey; //!< A Jubjub public key for outCiphertext.
//libzcash::SaplingEncCiphertext encCiphertext; //!< A ciphertext component for the encrypted output note.
libzcash::DynamicEncCiphertext encCiphertext; //!< A ciphertext component for the encrypted output note.
//libzcash::SaplingOutCiphertext outCiphertext; //!< A ciphertext component for the encrypted output note.
libzcash::DynamicOutCiphertext outCiphertext; //!< A ciphertext component for the encrypted output note.
GrothProof zkproof; //!< A zero-knowledge proof using the output circuit.
OutputDescription() { }
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(cv);
READWRITE(cm);
READWRITE(ephemeralKey);
READWRITE(outEphemeralKey);
READWRITE(encCiphertext);
READWRITE(outCiphertext);
READWRITE(zkproof);
}
friend bool operator==(const OutputDescription& a, const OutputDescription& b)
{
return (
a.cv == b.cv &&
a.cm == b.cm &&
a.ephemeralKey == b.ephemeralKey &&
a.outEphemeralKey == b.outEphemeralKey &&
a.encCiphertext == b.encCiphertext &&
a.outCiphertext == b.outCiphertext &&
a.zkproof == b.zkproof
);
}
friend bool operator!=(const OutputDescription& a, const OutputDescription& b)
{
return !(a == b);
}
};
class BaseOutPoint
{
public:
zero::uint256 hash;
uint32_t n;
BaseOutPoint() { SetNull(); }
BaseOutPoint(zero::uint256 hashIn, uint32_t nIn) { hash = hashIn; n = nIn; }
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(hash);
READWRITE(n);
}
void SetNull() { hash.SetNull(); n = (uint32_t) -1; }
bool IsNull() const { return (hash.IsNull() && n == (uint32_t) -1); }
friend bool operator<(const BaseOutPoint& a, const BaseOutPoint& b)
{
return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
}
friend bool operator==(const BaseOutPoint& a, const BaseOutPoint& b)
{
return (a.hash == b.hash && a.n == b.n);
}
friend bool operator!=(const BaseOutPoint& a, const BaseOutPoint& b)
{
return !(a == b);
}
};
/** An outpoint - a combination of a transaction hash and an index n into its vout */
class COutPoint : public BaseOutPoint
{
public:
COutPoint() : BaseOutPoint() {};
COutPoint(zero::uint256 hashIn, uint32_t nIn) : BaseOutPoint(hashIn, nIn) {};
std::string ToString() const
{
char buffer[64] = {0};
snprintf(buffer, sizeof(buffer), "COutPoint(%s, %u)", hash.ToString().substr(0,10).c_str(), n);
return buffer;
}
};
struct CTxIn {
COutPoint prevout;
uint32_t nSequence;
};
struct CTxOut {
CAmount nValue;
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(nValue);
}
};
struct shielded_transaction {
std::vector<CTxIn> vin;
std::vector<CTxOut> vout;
CAmount valueBalance;
std::vector<SpendDescription> vShieldedSpend;
std::vector<OutputDescription> vShieldedOutput;
binding_sig_t bindingSig;
};
struct ShieldedSpendPack {
std::string cv;
std::string anchor;
std::string nullifier;
std::string rk;
std::string zkproof;
std::string spendAuthSig;
//GrothProof zkproof;
//spend_auth_sig_t spendAuthSig;
ShieldedSpendPack() {
}
ShieldedSpendPack(const SpendDescription& spend) {
cv = spend.cv.GetHex();
anchor = spend.anchor.GetHex();
nullifier = spend.nullifier.GetHex();
rk = spend.rk.GetHex();
zkproof = HexStr(spend.zkproof);
spendAuthSig = HexStr(spend.spendAuthSig);
}
SpendDescription toShieldedSpendDesc() const {
SpendDescription spend;
spend.cv.SetHex(cv);
spend.anchor.SetHex(anchor);
spend.nullifier.SetHex(nullifier);
spend.rk.SetHex(rk);
std::vector<unsigned char> bytes = ParseHex(zkproof);
for (size_t i = 0; i < bytes.size() && i < spend.zkproof.size(); i++) {
spend.zkproof[i] = bytes[i];
}
bytes = ParseHex(spendAuthSig);
for (size_t i = 0; i < bytes.size() && i < spend.spendAuthSig.size(); i++) {
spend.spendAuthSig[i] = bytes[i];
}
return spend;
}
};
struct ShieldedOutputPack {
std::string cv;
std::string cm;
std::string ephemeralKey;
std::string outEphemeralKey;
std::string encCiphertext;
std::string outCiphertext;
std::string zkproof;
//libzcash::SaplingEncCiphertext encCiphertext;
//libzcash::SaplingOutCiphertext outCiphertext;
//GrothProof zkproof;
ShieldedOutputPack() {
}
ShieldedOutputPack(const OutputDescription& output) {
cv = output.cv.GetHex();
cm = output.cm.GetHex();
ephemeralKey = output.ephemeralKey.GetHex();
outEphemeralKey = output.outEphemeralKey.GetHex();
encCiphertext = HexStr(output.encCiphertext);
outCiphertext = HexStr(output.outCiphertext);
zkproof = HexStr(output.zkproof);
}
OutputDescription toShieldedOutputDesc() const {
OutputDescription output;
output.cv.SetHex(cv);
output.cm.SetHex(cm);
output.ephemeralKey.SetHex(ephemeralKey);
output.outEphemeralKey.SetHex(outEphemeralKey);
std::vector<unsigned char> bytes = ParseHex(encCiphertext);
output.encCiphertext.resize(bytes.size());
for (size_t i = 0; i < bytes.size(); i++) {
output.encCiphertext[i] = bytes[i];
}
bytes = ParseHex(outCiphertext);
output.outCiphertext.resize(bytes.size());
for (size_t i = 0; i < bytes.size(); i++) {
output.outCiphertext[i] = bytes[i];
}
bytes = ParseHex(zkproof);
for (size_t i = 0; i < bytes.size() && output.zkproof.size(); i++) {
output.zkproof[i] = bytes[i];
}
return output;
}
};
struct OutPointPack {
std::string hash;
uint32_t n;
OutPointPack() {
}
OutPointPack(const COutPoint& point) {
hash = point.hash.GetHex();
n = point.n;
}
COutPoint toOutPoint() const {
COutPoint point;
point.hash.SetHex(hash);
point.n = n;
return point;
}
};
struct TxInPack {
OutPointPack prevout;
uint32_t nSequence;
TxInPack() {
}
TxInPack(const CTxIn& in) : prevout(in.prevout) {
nSequence = in.nSequence;
}
CTxIn toTxIn() const {
CTxIn in;
in.prevout = prevout.toOutPoint();
in.nSequence = nSequence;
return in;
}
};
struct ShieldedTrxPack {
std::vector<TxInPack> vin;
std::vector<CAmount> vout;
CAmount valueBalance;
std::vector<ShieldedSpendPack> vShieldedSpend;
std::vector<ShieldedOutputPack> vShieldedOutput;
//binding_sig_t bindingSig;
std::string bindingSig;
ShieldedTrxPack() {
}
ShieldedTrxPack(const shielded_transaction& trx) {
for (auto& in : trx.vin) {
vin.emplace_back(in);
}
for (auto& out : trx.vout) {
vout.emplace_back(out.nValue);
}
valueBalance = trx.valueBalance;
for (auto& spend : trx.vShieldedSpend) {
vShieldedSpend.emplace_back(spend);
}
for (auto& output: trx.vShieldedOutput) {
vShieldedOutput.emplace_back(output);
}
bindingSig = HexStr(trx.bindingSig);
}
shielded_transaction toShieldedTrx() const {
shielded_transaction trx;
for (auto& in : vin) {
trx.vin.push_back(in.toTxIn());
}
for (auto& out : vout) {
CTxOut txOut;
txOut.nValue = out;
trx.vout.push_back(txOut);
}
trx.valueBalance = valueBalance;
for (auto& spend : vShieldedSpend) {
trx.vShieldedSpend.push_back(spend.toShieldedSpendDesc());
}
for (auto& output : vShieldedOutput) {
trx.vShieldedOutput.push_back(output.toShieldedOutputDesc());
}
std::vector<unsigned char> bytes = ParseHex(bindingSig);
for (size_t i = 0; i < bytes.size() && i < trx.bindingSig.size(); i++) {
trx.bindingSig[i] = bytes[i];
}
return trx;
}
};
FC_REFLECT( OutPointPack, (hash)(n))
FC_REFLECT( TxInPack, (prevout)(nSequence))
FC_REFLECT( ShieldedSpendPack, (cv)(anchor)(nullifier)(rk)(zkproof)(spendAuthSig))
FC_REFLECT( ShieldedOutputPack, (cv)(cm)(ephemeralKey)(outEphemeralKey)(encCiphertext)(outCiphertext)(zkproof))
FC_REFLECT( ShieldedTrxPack, (vin)(vout)(valueBalance)(vShieldedSpend)(vShieldedOutput)(bindingSig))
#endif
|
92a4f1d7e74a7fbb198e1ebfa47089ad391981f6 | d32b6eb7c8ca73704a38fef90b5fdca305184da6 | /AAudioTrack2/src/main/cpp/smallville7123/plugins/ChannelRack.h | aba24365c851b794267d17468ef765483a607e32 | [] | no_license | qiguixuJamesTsui/AAudioTrack | e629c1a3ada913596c1adc893e17d4ee4fca69b8 | 368864da0a5198e7839c207772a3bacea33747f3 | refs/heads/master | 2023-02-02T01:28:41.734185 | 2020-12-20T11:54:43 | 2020-12-20T11:54:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,633 | h | ChannelRack.h | //
// Created by matthew good on 28/11/20.
//
#ifndef AAUDIOTRACK_CHANNELRACK_H
#define AAUDIOTRACK_CHANNELRACK_H
#include "../../ardour/Backends/PortUtils2.h"
#include "Mixer.h"
#include "Sampler.h"
#include "Delay.h"
#include "../HostInfo.h"
#include "../Rack.h"
#include "../Channel_Generator.h"
#include "../PianoRoll.h"
#include "../Pattern.h"
#include "../PatternList.h"
#include "../PatternGroup.h"
class ChannelRack : Plugin_Base {
public:
Rack<Channel_Generator> rack;
Channel_Generator *newChannel() {
return rack.newType();
}
void removeChannel(Channel_Generator * channel) {
rack.removeType(channel);
}
public:
bool requires_sample_count() override {
return true;
}
bool requires_mixer() override {
return true;
}
PortUtils2 * silencePort = nullptr;
ChannelRack() {
silencePort = new PortUtils2();
// i dont think a ring buffer can be used, eg assuming the ring buffer IS the buffer, then it would need to re-push all notes in the new order each time it is modified, which would involve shifting and inserting notes, which could result in invalid playback of incorrect notes
// for example if you have 0,0,1,0 and you want to set 1,0,1,0 then it would need to be 0,0,1,0 > 1,0,0,1 > 0,1,0,0 > 1,0,1,0
// in which the audio thread CAN play any of the notes during the modification of the ring buffer
// lock-free and wait-free data structures are REQUIRED for communication
// between the audio thread and low priority threads such as the UI thread
//00:21 AndroidDAW: https://en.wikipedia.org/wiki/Non-blocking_algorithm#Wait-freedom *
//00:21 falktx: well anyway, for dsp->ui you very likely want to post data to some ringbuffer, then signal that there is data to read from it on the UI side5~
//00:21 falktx: the UI side basically just polls at regular intervals to check if there is data or not
//00:21 falktx: the usual stuff
//
//00:24 AndroidDAW: and could i do the same to manipulate for example, arrays which are shared between the RT thread and other non RT threads? for example a piano roll's note data
//00:24 AndroidDAW: in which the note data can be manipulated by the UI thread, and read by the RT thread
//00:24 niceplace has joined (~nplace@45.83.91.136)
//00:25 AndroidDAW: or would a different lock-free structure be required for this?
//00:27 AndroidDAW: for example, for manipulating channel racks and patterns (eg pattern 1, pattern 2, ect) and so on
//00:27 AndroidDAW: channel/effect racks*
//00:28 AndroidDAW: where a ring buffer would not be suitible as the data must be persistant for the duration of the programs runtime
//00:29 AndroidDAW: eg the channel/effect racks and patterns should not generally impose any limits on how many the user can create
//00:30 AndroidDAW: (tho i think its common to have something like a 999 limit but even that could be exceeded, especially in a playlist view)
//00:31 fundamental: If the audio thread goes to execute, the audio thread cannot be blocked by anything, it cannot allocate memory on the heap, nor free it to the heap, and if data is unavailable due to another thread it must be able to continue without it
//00:31 AndroidDAW: yea
//00:32 AndroidDAW: fundamental: eg the allocation could be done by the UI thread instead of the RT thread, however the RT thread would need to be capable of handling this
//00:33 AndroidDAW: eg it must be able to handle non allocated data and partially allocated data (assuming that is possible)
//00:34 AndroidDAW: tho partially allocated data is basically just non allocated data, or incomplete data, such as the data being allocated but its size not yet set when the RT thread reads it
//00:36 AndroidDAW: anyway, a ring buffer would not be a suitible structure for data which must not be recycled/size limited right?
//00:37 AndroidDAW: for example if you have a ring buffer with a capacity of 5, you cannot give it 7 pieces of data and except it to be able to store, and access, all 7 pieces of data
}
~ChannelRack() {
silencePort->deallocatePorts<ENGINE_FORMAT>();
delete silencePort;
}
void writePlugin(Plugin_Base * plugin, HostInfo *hostInfo, PortUtils2 *in, Plugin_Base *mixer,
PortUtils2 *out, unsigned int samples) {
plugin->is_writing = plugin->write(hostInfo, in, mixer,
out, samples);
}
void writeEffectRack(EffectRack * effectRack, HostInfo *hostInfo, PortUtils2 *in, Plugin_Base *mixer,
PortUtils2 *out, unsigned int samples) {
effectRack->is_writing = effectRack->write(hostInfo, in, mixer,
out, samples);
}
void writeChannels(HostInfo *hostInfo, PortUtils2 *in, Plugin_Base *mixer, PortUtils2 *out,
unsigned int samples) {
// LOGE("writing channels");
for (int i = 0; i < PatternGroup::cast(hostInfo->patternGroup)->rack.typeList.size(); ++i) {
PatternList *patternList = PatternGroup::cast(hostInfo->patternGroup)->rack.typeList[i];
if (patternList != nullptr) {
for (int i = 0; i < patternList->rack.typeList.size(); ++i) {
Pattern *pattern = patternList->rack.typeList[i];
if (pattern != nullptr) {
Channel_Generator *channel = pattern->channelReference;
if (channel != nullptr) {
channel->out->allocatePorts<ENGINE_FORMAT>(out);
channel->out->fillPortBuffer<ENGINE_FORMAT>(0);
if (channel->plugin != nullptr) {
if (channel->plugin->is_writing == PLUGIN_CONTINUE) {
writePlugin(channel->plugin, hostInfo, in, mixer,
channel->out, samples);
}
}
if (channel->effectRack != nullptr) {
if (channel->effectRack->is_writing == PLUGIN_CONTINUE) {
writeEffectRack(channel->effectRack, hostInfo, in,
mixer,
channel->out, samples);
}
}
}
}
}
}
}
for (int32_t i = 0; i < samples; i ++) {
for (int i = 0; i < PatternGroup::cast(hostInfo->patternGroup)->rack.typeList.size(); ++i) {
PatternList *patternList = PatternGroup::cast(hostInfo->patternGroup)->rack.typeList[i];
if (patternList != nullptr) {
for (int i = 0; i < patternList->rack.typeList.size(); ++i) {
Pattern *pattern = patternList->rack.typeList[i];
if (pattern != nullptr) {
if (pattern->hasNote(hostInfo->engineFrame)) {
Channel_Generator * channel = pattern->channelReference;
if (channel != nullptr) {
channel->out->allocatePorts<ENGINE_FORMAT>(out);
channel->out->fillPortBuffer<ENGINE_FORMAT>(0);
if (channel->plugin != nullptr) {
channel->plugin->stopPlayback();
writePlugin(channel->plugin, hostInfo, in, mixer,
channel->out, samples);
}
if (channel->effectRack != nullptr) {
writeEffectRack(channel->effectRack, hostInfo, in, mixer,
channel->out, samples);
}
}
}
}
}
}
}
hostInfo->engineFrame++;
// return from the audio loop
}
// LOGE("wrote channels");
}
void prepareMixer(HostInfo * hostInfo, Plugin_Type_Mixer * mixer_, PortUtils2 * out) {
// LOGE("preparing mixer");
for (int i = 0; i < PatternGroup::cast(hostInfo->patternGroup)->rack.typeList.size(); ++i) {
PatternList *patternList = PatternGroup::cast(hostInfo->patternGroup)->rack.typeList[i];
if (patternList != nullptr) {
for (int i = 0; i < patternList->rack.typeList.size(); ++i) {
Pattern *pattern = patternList->rack.typeList[i];
if (pattern != nullptr) {
if (pattern->channelReference != nullptr) {
if (pattern->channelReference->out->allocated) {
mixer_->addPort(pattern->channelReference->out);
}
}
}
}
}
}
silencePort->allocatePorts<ENGINE_FORMAT>(out);
mixer_->addPort(silencePort);
silencePort->fillPortBuffer<ENGINE_FORMAT>(0);
// LOGE("prepared mixer");
}
void mix(HostInfo *hostInfo, PortUtils2 *in, Plugin_Type_Mixer * mixer, PortUtils2 *out,
unsigned int samples) {
// LOGE("mixing");
mixer->write(hostInfo, in, mixer, out, samples);
// LOGE("mixed");
}
void finalizeMixer(HostInfo * hostInfo, Plugin_Type_Mixer * mixer_) {
// LOGE("finalizing mixer");
mixer_->removePort(silencePort);
silencePort->deallocatePorts<ENGINE_FORMAT>();
for (int i = 0; i < PatternGroup::cast(hostInfo->patternGroup)->rack.typeList.size(); ++i) {
PatternList *patternList = PatternGroup::cast(hostInfo->patternGroup)->rack.typeList[i];
if (patternList != nullptr) {
for (int i = 0; i < patternList->rack.typeList.size(); ++i) {
Pattern *pattern = patternList->rack.typeList[i];
if (pattern != nullptr) {
if (pattern->channelReference != nullptr) {
if (pattern->channelReference->out->allocated) {
mixer_->removePort(pattern->channelReference->out);
pattern->channelReference->out->deallocatePorts<ENGINE_FORMAT>();
}
}
}
}
}
}
// LOGE("finalized mixer");
}
void mixChannels(HostInfo *hostInfo, PortUtils2 *in, Plugin_Type_Mixer * mixer, PortUtils2 *out,
unsigned int samples) {
prepareMixer(hostInfo, mixer, out);
mix(hostInfo, in, mixer, out, samples);
finalizeMixer(hostInfo, mixer);
}
int write(HostInfo *hostInfo, PortUtils2 *in, Plugin_Base *mixer, PortUtils2 *out,
unsigned int samples) override {
writeChannels(hostInfo, in, mixer, out, samples);
mixChannels(hostInfo, in, reinterpret_cast<Plugin_Type_Mixer*>(mixer), out, samples);
return PLUGIN_CONTINUE;
}
void bindChannelToPattern(void *nativeChannel, void *nativePattern) {
static_cast<Pattern*>(nativePattern)->channelReference = static_cast<Channel_Generator *>(nativeChannel);
}
void setPlugin(void *nativeChannel, void *nativePlugin) {
static_cast<Channel_Generator *>(nativeChannel)->plugin = static_cast<Plugin_Type_Generator *>(nativePlugin);
}
PatternList * newPatternList(HostInfo * hostInfo) {
return PatternGroup::cast(hostInfo->patternGroup)->newPatternList();
}
void deletePatternList(HostInfo * hostInfo, PatternList * patternList) {
return PatternGroup::cast(hostInfo->patternGroup)->removePatternList(patternList);
}
Pattern * newPattern(PatternList * patternList) {
return patternList->newPattern();
}
void deletePattern(PatternList * patternList, Pattern * pattern) {
return patternList->removePattern(pattern);
}
};
#endif //AAUDIOTRACK_CHANNELRACK_H
|
a05e42eac20aaa4e5bc7233c08b29f18bd3bd9e4 | 4dd695fdfe07b70522880cf27d6925f37dc41f58 | /Project9/Human.cpp | fd5ae55c2d13d86969c7a94648c1cc61f95b46fe | [] | no_license | MarinaKim/Inheritance_Lab2105 | 206ee8e265ec1aca31e0f530a93109cf6b7b2b97 | 47c60ec1a765e7f77c5f95018e3bdfda11f9eb16 | refs/heads/master | 2020-03-18T04:15:13.869043 | 2018-05-21T14:11:15 | 2018-05-21T14:11:15 | 134,278,385 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 525 | cpp | Human.cpp | #include "Human.h"
Human::Human(string name, string sname, int age, string address)
{
this->name = name;
this->sname = sname;
this->age = age;
this->address = address;
}
istream & operator >> (istream & is, Human&obj)
{
string s;
getline(is, obj.name, '/');
getline(is, obj.sname, '/');
is >> obj.age;
getline(is, s, ' ');
getline(is, obj.address);
return is;
}
ostream & operator << (ostream & os, Human obj)
{
os << obj.name <<"\t"<<obj.sname<< "\t" << obj.age << "\t" << obj.address << endl;
return os;
}
|
c0cf1a2d436297822f1c8688cbec2d52b9b43ea8 | 288f4a54a27ad6548595c6eba76a39d86a3c1968 | /svn/F270/ghl/.svn/text-base/main.cpp.svn-base | d1e6d315e57da277ddf2acadca347001bebb8d96 | [] | no_license | chrismayo/ONLIGHT | b6c3dc4378c2b37332aa035e2d32920238af567c | 105317a8d55468b7cddb81e2ad7fd02b51132a84 | refs/heads/master | 2021-01-01T17:28:43.915528 | 2015-09-01T10:58:30 | 2015-09-01T10:58:30 | 39,361,481 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,615 | main.cpp.svn-base | #include <QApplication>
#include <QLabel>
#include <QSharedMemory>
#include <QTableView>
#include <QDebug>
#include <QDateTime>
#include "./Common/slidingscreen.h"
#include "./Common/softkeypad.h"
#include "./GlobalData/cfgGlobalDef.h"
#include "./GlobalData/dataGlobalDef_ModbusReg.h"
#include "./DataModel/modeldigitalgroupchannel.h"
#include "./WorkWin/winmainframe.h"
#include "./WorkWin/winroot.h"
#include "./GlobalData/sqlBlock_RecordChanInfo.h"
#include "./Threads/threaddataprocess.h"
#include "./Threads/threaddatarecord.h"
#include "./Threads/threaddatasync.h"
#include "./WorkWin/wintrendgroup.h"
#include <qsqldatabase.h>
#include <qsqlquery.h>
#include <qsqlrecord.h>
#include <qsqlerror.h>
#include <QDateTime>
DEVICE_CONFIG testConfigStruct;
DEVICE_CONFIG *p_gDeviceCfg=&testConfigStruct; //全局变量指针,指向LPSRAM中的设备配置结构
QSharedMemory g_sharedDataTable;
quint64 gTmep;
//线程初始化:信号槽链接 && 启动线程
void threadInit()
{
QObject::connect(ThreadDataProcess::instance(), SIGNAL(sigMathProcessFinished()), \
ThreadDataSync::instance(), SIGNAL(sigSyncData()));
ThreadDataProcess::instance()->changeMeasurePeriod();
ThreadDataRecord::instance()->start();
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
threadInit();
WinMainFrame *pMainWin = WinMainFrame::instance();
pMainWin->addWorkWin(new WinRoot());
pMainWin->showFullScreen();
WinTrendGroup *pTrend = new WinTrendGroup;
pTrend->showFullScreen();
return a.exec();
}
| |
79c11adcefab3f6c5be1b7eeb49690be56d57a74 | 83a65eebfe51fde8c052096d788596410b6a7b8f | /src/CTrail-all.cpp | 3a67db8e19617111590dbee85e0a511c742e332a | [] | no_license | mikekazakov/ctrail | 21b8fa8a02923e8ab138508f3e6140bf00d37daa | 5447e16216f1f8804d4545b2dccfffe37e939c24 | refs/heads/master | 2020-09-07T12:23:12.326158 | 2019-12-01T16:58:09 | 2019-12-01T16:58:09 | 220,779,563 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 358 | cpp | CTrail-all.cpp | #include "ChromeTraceExporter.cpp"
#include "CSVExporter.cpp"
#include "CyclicValuesStorage.cpp"
#include "Dashboard.cpp"
#include "DashboardImpl.cpp"
#include "MonotonicValuesStorage.cpp"
#include "OneShotMonitor.cpp"
#include "Ports.cpp"
#include "Registry.cpp"
#include "RegistryImpl.cpp"
#include "ValuesStorage.cpp"
#include "ValuesStorageExporter.cpp"
|
608006be474c9b8dbb9de4b26ad1e3688fc5c016 | 086a72a391984a14feab432e484a66359925715b | /pscore/core/any_ptr.cc | 7f3edf098e096a38eb75b694c330dfa45728a9b2 | [] | no_license | Superjomn/pscore | 966e8dd25b098cf9d2e2b36ebb0c182494454463 | 0cbe6d3caab30ba73646d0af0e61dfed1ea9f333 | refs/heads/master | 2023-06-02T21:24:13.582567 | 2021-06-28T07:28:20 | 2021-06-28T07:28:20 | 377,822,009 | 0 | 0 | null | 2021-06-28T07:28:20 | 2021-06-17T12:24:44 | C++ | UTF-8 | C++ | false | false | 74 | cc | any_ptr.cc | #include "pscore/core/any_ptr.h"
namespace pscore {} // namespace pscore |
7876292102d3937a53d927056b81ab4b8161fe0a | cb4674d804d1d0b28004e651b3a16cf15dc3545f | /tests/fake_support/opencascade/gp_Pnt.hxx | be4ce4f9e9214dfd69458f5291c3a9f10c1e480a | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | GridEyes-2010/gmio | 7a493aae2704c88baf5ac8eb1aadbccf36349895 | 6deb4fabb47b4aaf31073e23adf2c4f1d1bc290e | refs/heads/master | 2022-01-01T21:58:54.750029 | 2017-04-14T09:14:50 | 2017-04-14T09:14:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 361 | hxx | gp_Pnt.hxx | #ifndef _gp_Pnt_HeaderFile
#define _gp_Pnt_HeaderFile
#include <Standard_TypeDef.hxx>
#include <gp_XYZ.hxx>
#include <gp_Trsf.hxx>
class gp_Pnt
{
public:
gp_Pnt() {}
gp_Pnt(const gp_XYZ& /*coords*/) {}
const gp_XYZ& XYZ() const { return coord; }
void Transform(const gp_Trsf&) {}
private:
gp_XYZ coord;
};
#endif // _gp_Pnt_HeaderFile
|
f8663fee7dbbe705cdaff7d3e96d911a746a26e2 | f95a3c26ff14fbc10876da8d404aca11ececb1b7 | /ExampleCode/ExampleCode/Lib/Header/Graphics/Textures/TextureFactory/OpenGLTextureFactory.h | 7ff02c04b2c822f0195651afd893a7c9d0397f36 | [] | no_license | PBenkoApplication/CodeSample | 574e4e2d7f7e4300136c72dc921e66fcd372cd15 | 68174a37cc6ddecba64794dc16042406493b654c | refs/heads/master | 2021-01-01T16:53:11.795981 | 2017-07-21T12:47:09 | 2017-07-21T12:47:09 | 97,941,723 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 952 | h | OpenGLTextureFactory.h | #ifndef OPENGLTEXTUREFACTORY_H
#define OPENGLTEXTUREFACTORY_H
#include "ITextureFactory.h"
#include "../OpenGL/OpenGLTexture.h"
namespace BAME
{
class OpenGLTextureFactory : public ITextureFactory
{
public:
OpenGLTextureFactory();
~OpenGLTextureFactory();
protected:
void AddNewTextureToPool(std::string const& texturePath, bool isSRGB) override;
void AddNewDDSCubeMapTextureToPool(std::string const& texturePath, bool isSRGB) override;
/*std::unique_ptr<ITexture> CreateUnique_Texture(Texture const& texture) override;
std::unique_ptr<ITexture> CreateUnique_DDSCubeTexture(Texture const& texture) override;
*/ //std::unique_ptr<ITexture> CreateSkyboxUnique_Texture(std::string const& front, std::string const& back, std::string const& left, std::string const& right, std::string const& top) override;
/*private:
std::map<std::string, OpenGLTexture*> mOpenGLTextureMap;
std::list<std::string> mTexturePathList;*/
};
}
#endif
|
6342c9c621b3774fcb69c752760b7a51718c9bb5 | 19194c2f2c07ab3537f994acfbf6b34ea9b55ae7 | /android-33/android/graphics/RectF.def.hpp | 88fc67686fb270477512090fa45c354d8a4b8f50 | [
"GPL-3.0-only"
] | permissive | YJBeetle/QtAndroidAPI | e372609e9db0f96602da31b8417c9f5972315cae | ace3f0ea2678967393b5eb8e4edba7fa2ca6a50c | refs/heads/Qt6 | 2023-08-05T03:14:11.842336 | 2023-07-24T08:35:31 | 2023-07-24T08:35:31 | 249,539,770 | 19 | 4 | Apache-2.0 | 2022-03-14T12:15:32 | 2020-03-23T20:42:54 | C++ | UTF-8 | C++ | false | false | 2,418 | hpp | RectF.def.hpp | #pragma once
#include "../../JObject.hpp"
namespace android::graphics
{
class Rect;
}
namespace android::os
{
class Parcel;
}
class JObject;
class JString;
namespace android::graphics
{
class RectF : public JObject
{
public:
// Fields
static JObject CREATOR();
jfloat bottom();
jfloat left();
jfloat right();
jfloat top();
// QJniObject forward
template<typename ...Ts> explicit RectF(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {}
RectF(QJniObject obj) : JObject(obj) {}
// Constructors
RectF();
RectF(android::graphics::Rect arg0);
RectF(android::graphics::RectF &arg0);
RectF(jfloat arg0, jfloat arg1, jfloat arg2, jfloat arg3);
// Methods
static jboolean intersects(android::graphics::RectF arg0, android::graphics::RectF arg1);
jfloat centerX() const;
jfloat centerY() const;
jboolean contains(android::graphics::RectF arg0) const;
jboolean contains(jfloat arg0, jfloat arg1) const;
jboolean contains(jfloat arg0, jfloat arg1, jfloat arg2, jfloat arg3) const;
jint describeContents() const;
jboolean equals(JObject arg0) const;
jint hashCode() const;
jfloat height() const;
void inset(jfloat arg0, jfloat arg1) const;
jboolean intersect(android::graphics::RectF arg0) const;
jboolean intersect(jfloat arg0, jfloat arg1, jfloat arg2, jfloat arg3) const;
jboolean intersects(jfloat arg0, jfloat arg1, jfloat arg2, jfloat arg3) const;
jboolean isEmpty() const;
void offset(jfloat arg0, jfloat arg1) const;
void offsetTo(jfloat arg0, jfloat arg1) const;
void readFromParcel(android::os::Parcel arg0) const;
void round(android::graphics::Rect arg0) const;
void roundOut(android::graphics::Rect arg0) const;
void set(android::graphics::Rect arg0) const;
void set(android::graphics::RectF arg0) const;
void set(jfloat arg0, jfloat arg1, jfloat arg2, jfloat arg3) const;
void setEmpty() const;
jboolean setIntersect(android::graphics::RectF arg0, android::graphics::RectF arg1) const;
void sort() const;
JString toShortString() const;
JString toString() const;
void union_(android::graphics::RectF arg0) const;
void union_(jfloat arg0, jfloat arg1) const;
void union_(jfloat arg0, jfloat arg1, jfloat arg2, jfloat arg3) const;
jfloat width() const;
void writeToParcel(android::os::Parcel arg0, jint arg1) const;
};
} // namespace android::graphics
|
6b2e17a90231d507a543ec1bbc98e672e7ae5c0b | 44289ecb892b6f3df043bab40142cf8530ac2ba4 | /Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/app/CActivityOptionsAnimationStartedListener.cpp | 2aa6f21654b0cc2455f8457d8efa6d6b8bc2ff66 | [
"Apache-2.0"
] | permissive | warrenween/Elastos | a6ef68d8fb699fd67234f376b171c1b57235ed02 | 5618eede26d464bdf739f9244344e3e87118d7fe | refs/heads/master | 2021-01-01T04:07:12.833674 | 2017-06-17T15:34:33 | 2017-06-17T15:34:33 | 97,120,576 | 2 | 1 | null | 2017-07-13T12:33:20 | 2017-07-13T12:33:20 | null | UTF-8 | C++ | false | false | 2,021 | cpp | CActivityOptionsAnimationStartedListener.cpp | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include "elastos/droid/app/CActivityOptionsAnimationStartedListener.h"
#include "elastos/droid/app/CActivityOptions.h"
#include "elastos/droid/os/Handler.h"
using Elastos::Droid::Os::EIID_IIRemoteCallback;
using Elastos::Droid::Os::EIID_IBinder;
namespace Elastos {
namespace Droid {
namespace App {
CAR_INTERFACE_IMPL_2(CActivityOptionsAnimationStartedListener, Object, IIRemoteCallback, IBinder)
CAR_OBJECT_IMPL(CActivityOptionsAnimationStartedListener)
ECode CActivityOptionsAnimationStartedListener::constructor(
/* [in] */ IHandler* handler,
/* [in] */ IActivityOptionsOnAnimationStartedListener* listener)
{
mHandler = handler;
mListener = listener;
return NOERROR;
}
ECode CActivityOptionsAnimationStartedListener::SendResult(
/* [in] */ IBundle* data)
{
if (mHandler != NULL) {
Boolean result;
AutoPtr<IRunnable> r = new AnimationStartedListenerRunnable(mListener);
mHandler->Post(r, &result);
}
return NOERROR;
}
ECode CActivityOptionsAnimationStartedListener::ToString(
/* [out]*/ String* str)
{
VALIDATE_NOT_NULL(str);
*str = String("CActivityOptionsAnimationStartedListener");
return NOERROR;
}
} // namespace App
} // namespace Droid
} // namespace Elastos
|
5b109ba232633c33e97ff7eec2a4e6a88a915e00 | 0de02af56408b50495a999c1af9e714015be8364 | /inc/Bot.hh | 8654389a9061d1c2046ff791b2f4456fed0a96b9 | [] | no_license | Christopher-Steel/Bomberman | 4345ec42e27506ea66b7b8c56da32211c975949e | 04b6445be01f1bdbf6e2faf09d87096277af787f | refs/heads/master | 2020-03-14T08:04:14.232840 | 2018-04-29T17:58:42 | 2018-04-29T17:58:42 | 131,517,029 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,395 | hh | Bot.hh | //
// Bot.hh for bomberman in /home/dubour_f//projects/Bomberman/bomberman-2016-dubdub/inc
//
// Made by frederic dubourg
// Login <dubour_f@epitech.net>
//
// Started on Wed May 22 13:46:58 2013 frederic dubourg
// Last update Wed Jun 5 23:14:45 2013 frederic dubourg
//
#ifndef BOT_HH_
# define BOT_HH_
#include <ABomber.hh>
namespace Model
{
class Bot : public ABomber
{
enum eDirection
{
STAND,
RIGHT,
LEFT,
UP,
DOWN
};
public:
enum eDifficulty
{
EASY,
MEDIUM,
HARD,
GODLIKE
};
public:
Bot(const Vector3f&, const eDifficulty);
~Bot();
void update(gdl::GameClock const&, gdl::Input &);
private:
// bool isInDanger_;
std::list<Vector3f> collisions_;
std::list<Vector3f> danger_;
// std::list<Vector3f> escape_[4];
eDirection goal_;
eDifficulty level_;
// void findAnEscape();
void seekCollisions();
void seekDanger();
bool isDangerous(Vector3f);
void toSafePath(gdl::GameClock const&);
void toGoal(gdl::GameClock const&);
void setNewGoal(gdl::GameClock const&);
void moveTileRight(Vector3f*, gdl::GameClock const&);
void moveTileLeft(Vector3f*, gdl::GameClock const&);
void moveTileUp(Vector3f*, gdl::GameClock const&);
void moveTileDown(Vector3f*, gdl::GameClock const&);
void tryBomb();
};
}
#endif
|
c3ab062d8e54e32cda28b51756e12b82c117a39c | 2378938f301116c10e33f52f9bc857853ce10b4d | /codeforces/accepted/915a.cc | ce4c454ffa793e6e7219802a8d538d2c8d092604 | [] | no_license | ckebabo/problem_solving | e25fafd606edeeb9dd99de9339044dbfe8838fbb | f62ec8800457339ac0c0529344f4d4e852e3560f | refs/heads/master | 2018-07-29T06:23:22.379461 | 2018-06-02T15:07:54 | 2018-06-02T15:07:54 | 117,555,079 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 233 | cc | 915a.cc | #include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n,k;
cin >> n >> k;
int v = 0;
for(int i=0;i<n;i++) {
int t;
cin >> t;
if(k % t == 0) v = max(v, t);
}
cout << k/v << endl;
return 0;
}
|
832f7f797e142376125eb6badf3a51d00f0f1066 | f7d06ecbaf75e0cf246c08217fc73f4745bd0287 | /PoseCalculator.h | 80e1a54fdb9ec3bc6550f2b0e794f78b5b365a37 | [] | no_license | 4ndr3w/omnibot | 1b7f841b11e9e9b13186711e7e8b1d59bf9594e0 | a2aa51cb44ac3402e735d70607e9ff47b44b52dd | refs/heads/master | 2021-01-19T04:12:40.869179 | 2017-05-19T01:47:59 | 2017-05-19T01:47:59 | 87,358,336 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 444 | h | PoseCalculator.h | #include <WPILib/WPILib.h>
#include "hardware/Drivetrain.h"
#include "OmniBotComm.h"
#ifndef POSE_CALC_H
#define POSE_CALC_H
class PoseCalculator {
private:
SEM_ID lock;
double x,y,theta;
double vx,vy,vth;
Drivetrain *drive;
PoseCalculator();
public:
static PoseCalculator* getInstance();
RobotPose getPose();
RobotVelocity getVelocity();
void reset();
void update();
};
#endif |
a401c9aa32d602bfb5734e77b9c546023c78b882 | 8a6c98a052cef2c9d49680bdd4d4517e477e25d3 | /SharedLib/PSPApp/PSPUSBStorage.cpp | 88f5d743c2e49f08ba7abfbd58ba031d5f64abe3 | [] | no_license | PSP-Archive/PSPRadio | d4bc2a43e7a2f79ba5090d8d84bb9de25aa367e6 | dfeb55b359cc125379f7f97282e9058c2c79b485 | refs/heads/master | 2023-02-05T18:17:26.980200 | 2020-12-31T06:45:53 | 2020-12-31T06:45:53 | 325,731,433 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,125 | cpp | PSPUSBStorage.cpp | /*
PSPApp C++ OO Application Framework. (Initial Release: Sept. 2005)
Copyright (C) 2005 Rafael Cabezas a.k.a. Raf
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <stdio.h>
#include <pspsdk.h>
#include <pspkernel.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <stdarg.h>
#include <pspusb.h>
#include <pspusbstor.h>
#include <kubridge.h>
#include "PSPApp.h"
#include "PSPUSBStorage.h"
#include "PSPThread.h"
#undef ReportError
//helper function to make things easier
int LoadStartModule(char *path)
{
u32 loadResult;
u32 startResult;
int status;
loadResult = kuKernelLoadModule(path, 0, NULL);
if (loadResult & 0x80000000)
return -1;
else
startResult =
sceKernelStartModule(loadResult, 0, NULL, &status, NULL);
if (loadResult != startResult)
return -2;
return 0;
}
CPSPUSBStorage::CPSPUSBStorage(CPSPApp *pspapp)
{
m_PSPApp = pspapp;
m_USBEnabled = false;
LoadStartModule("flash0:/kd/semawm.prx");
LoadStartModule("flash0:/kd/usbstor.prx");
LoadStartModule("flash0:/kd/usbstormgr.prx");
LoadStartModule("flash0:/kd/usbstorms.prx");
//LoadStartModule("flash0:/kd/usbstorboot.prx");
}
CPSPUSBStorage::~CPSPUSBStorage()
{
if (true == IsUSBEnabled())
{
Log(LOG_VERYLOW, "~CPSPUSBStorage(): Disabling USB.");
DisableUSB();
}
}
int CPSPUSBStorage::EnableUSB()
{
int retVal = 0;
int state = 0;
if (false == m_USBEnabled)
{
Log(LOG_INFO, "Starting USB...");
/** setup USB drivers */
retVal = sceUsbStart(PSP_USBBUS_DRIVERNAME, 0, 0);
if (retVal == 0)
{
retVal = sceUsbStart(PSP_USBSTOR_DRIVERNAME, 0, 0);
if (retVal == 0)
{
//retVal = sceUsbstorBootSetCapacity(0x800000);
if (retVal == 0)
{
retVal = sceUsbActivate(0x1c8);
state = sceUsbGetState();
if (state & PSP_USB_ACTIVATED != 0)
{
Log(LOG_INFO, "USB Activated.");
m_USBEnabled = true;
retVal = 0;
}
else
{
Log(LOG_ERROR, "Error Activating USB\n", retVal);
retVal = -1;
}
}
else
{
Log(LOG_ERROR, "Error setting capacity with USB Mass Storage driver (0x%08X)\n", retVal);
retVal = -1;
}
}
else
{
Log(LOG_ERROR, "Error starting USB Mass Storage driver (0x%08X)\n", retVal);
retVal = -1;
}
}
else
{
Log(LOG_ERROR, "Error starting USB Bus driver (0x%08X)\n", retVal);
retVal = -1;
}
}
if (retVal == 0)
{
pPSPApp->SendEvent(MID_USB_ENABLE);
}
return retVal;
}
int CPSPUSBStorage::DisableUSB()
{
int retVal = 0;
int state = 0;
if (true == m_USBEnabled)
{
Log(LOG_INFO, "Stopping USB...");
state = sceUsbGetState();
if (state & 0x8) /** Busy */
{
Log(LOG_ERROR, "USB Busy, cannot disable right now...\n", retVal);
retVal = -1; //./BUSY
}
else
{
retVal = sceUsbDeactivate(0x1c8);
if (retVal != 0)
{
Log(LOG_ERROR, "Error calling sceUsbDeactivate (0x%08X)\n", retVal);
}
retVal = sceUsbStop(PSP_USBSTOR_DRIVERNAME, 0, 0);
if (retVal != 0)
{
Log(LOG_ERROR, "Error stopping USB Mass Storage driver (0x%08X)\n", retVal);
}
retVal = sceUsbStop(PSP_USBBUS_DRIVERNAME, 0, 0);
if (retVal != 0)
{
Log(LOG_ERROR, "Error stopping USB BUS driver (0x%08X)\n", retVal);
}
}
if (retVal >= 0)
{
m_USBEnabled = false;
}
}
if (retVal == 0)
{
pPSPApp->SendEvent(MID_USB_DISABLE);
}
return retVal;
}
|
642a8c2960c695f2cdc5573a23707bd8a273f64a | f0d59af3f73b91bba39f956aff50e206b549630c | /visualcenter.h | 29d26c93bcf8d42a4f9ae20c89ec5fe5eb279042 | [] | no_license | MrSiz/LogV | 405133b106651116dfe13db025872e9d30f7d01a | d8f9add14067aa7532721a9307e4ceb43151d788 | refs/heads/master | 2020-03-10T20:28:51.415330 | 2018-06-18T05:58:20 | 2018-06-18T05:58:20 | 129,571,518 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,496 | h | visualcenter.h | #ifndef VISUALCENTER_H
#define VISUALCENTER_H
#include "threadpool.h"
#include <QWidget>
#include <QtCharts>
#include <QtCharts/QChartView>
#include <QList>
namespace Ui {
class VisualCenter;
}
class VisualCenter : public QWidget
{
Q_OBJECT
public:
explicit VisualCenter(int numThread = 2, QWidget *parent = 0);
~VisualCenter();
void init(int num);
public slots:
void drawpieChart(QList<int> data, QStringList xnames, QString title, int g_pos);
void drawbarChart(QList<int> data, QStringList xnames, QString title, int g_pos);
void drawlineChart(QList<int> data, QStringList xnames, QString title, int g_pos);
void drawhttpMethodAndTimeChart(QMap<int, int> get, QMap<int, int> head, QMap<int, int> post, QMap<int, int> put,
QMap<int, int> del, QMap<int, int> trace);
void drawipAndHttpReq(QMap<QString, QMap<QString, int>> store);
void drawbrowserIpStatus(QHash<QString, int>, QHash<QString, QHash<QString, int>>,
QHash<QString, QHash<QString, QHash<QString, int>>>);
void drawipAndOs(QMap<QString, int> visitors, QMap<QString, int> hits, QStringList head);
void recevieSeries( QList<QPair<QString, qreal>> s0, QList<QPair<QString, qreal>> s1, QList<QPair<QString, qreal>> s2);
private:
Ui::VisualCenter *ui;
QChartView *chartView;
QList<QChart*> chartList;
QList<QAbstractSeries*> series;
QList<QBarSet*> barSet;
ThreadPool pool;
};
#endif // VISUALCENTER_H
|
8397d4e7baa9262e992962c863bba6c0cc0af7db | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /ckafka/include/tencentcloud/ckafka/v20190819/model/FailureParam.h | 4feff8048b46d8a391fd602e0b83011a387aac4f | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp | 9f5df8220eaaf72f7eaee07b2ede94f89313651f | 42a76b812b81d1b52ec6a217fafc8faa135e06ca | refs/heads/master | 2023-08-30T03:22:45.269556 | 2023-08-30T00:45:39 | 2023-08-30T00:45:39 | 188,991,963 | 55 | 37 | Apache-2.0 | 2023-08-17T03:13:20 | 2019-05-28T08:56:08 | C++ | UTF-8 | C++ | false | false | 8,397 | h | FailureParam.h | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_CKAFKA_V20190819_MODEL_FAILUREPARAM_H_
#define TENCENTCLOUD_CKAFKA_V20190819_MODEL_FAILUREPARAM_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
#include <tencentcloud/core/AbstractModel.h>
#include <tencentcloud/ckafka/v20190819/model/KafkaParam.h>
#include <tencentcloud/ckafka/v20190819/model/TopicParam.h>
namespace TencentCloud
{
namespace Ckafka
{
namespace V20190819
{
namespace Model
{
/**
* 数据处理规则失败处理
*/
class FailureParam : public AbstractModel
{
public:
FailureParam();
~FailureParam() = default;
void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const;
CoreInternalOutcome Deserialize(const rapidjson::Value &value);
/**
* 获取类型,DLQ死信队列,IGNORE_ERROR保留,DROP废弃
* @return Type 类型,DLQ死信队列,IGNORE_ERROR保留,DROP废弃
*
*/
std::string GetType() const;
/**
* 设置类型,DLQ死信队列,IGNORE_ERROR保留,DROP废弃
* @param _type 类型,DLQ死信队列,IGNORE_ERROR保留,DROP废弃
*
*/
void SetType(const std::string& _type);
/**
* 判断参数 Type 是否已赋值
* @return Type 是否已赋值
*
*/
bool TypeHasBeenSet() const;
/**
* 获取Ckafka类型死信队列
* @return KafkaParam Ckafka类型死信队列
*
*/
KafkaParam GetKafkaParam() const;
/**
* 设置Ckafka类型死信队列
* @param _kafkaParam Ckafka类型死信队列
*
*/
void SetKafkaParam(const KafkaParam& _kafkaParam);
/**
* 判断参数 KafkaParam 是否已赋值
* @return KafkaParam 是否已赋值
*
*/
bool KafkaParamHasBeenSet() const;
/**
* 获取重试间隔
* @return RetryInterval 重试间隔
*
*/
uint64_t GetRetryInterval() const;
/**
* 设置重试间隔
* @param _retryInterval 重试间隔
*
*/
void SetRetryInterval(const uint64_t& _retryInterval);
/**
* 判断参数 RetryInterval 是否已赋值
* @return RetryInterval 是否已赋值
*
*/
bool RetryIntervalHasBeenSet() const;
/**
* 获取重试次数
* @return MaxRetryAttempts 重试次数
*
*/
uint64_t GetMaxRetryAttempts() const;
/**
* 设置重试次数
* @param _maxRetryAttempts 重试次数
*
*/
void SetMaxRetryAttempts(const uint64_t& _maxRetryAttempts);
/**
* 判断参数 MaxRetryAttempts 是否已赋值
* @return MaxRetryAttempts 是否已赋值
*
*/
bool MaxRetryAttemptsHasBeenSet() const;
/**
* 获取DIP Topic类型死信队列
注意:此字段可能返回 null,表示取不到有效值。
* @return TopicParam DIP Topic类型死信队列
注意:此字段可能返回 null,表示取不到有效值。
*
*/
TopicParam GetTopicParam() const;
/**
* 设置DIP Topic类型死信队列
注意:此字段可能返回 null,表示取不到有效值。
* @param _topicParam DIP Topic类型死信队列
注意:此字段可能返回 null,表示取不到有效值。
*
*/
void SetTopicParam(const TopicParam& _topicParam);
/**
* 判断参数 TopicParam 是否已赋值
* @return TopicParam 是否已赋值
*
*/
bool TopicParamHasBeenSet() const;
/**
* 获取死信队列类型,CKAFKA,TOPIC
注意:此字段可能返回 null,表示取不到有效值。
* @return DlqType 死信队列类型,CKAFKA,TOPIC
注意:此字段可能返回 null,表示取不到有效值。
*
*/
std::string GetDlqType() const;
/**
* 设置死信队列类型,CKAFKA,TOPIC
注意:此字段可能返回 null,表示取不到有效值。
* @param _dlqType 死信队列类型,CKAFKA,TOPIC
注意:此字段可能返回 null,表示取不到有效值。
*
*/
void SetDlqType(const std::string& _dlqType);
/**
* 判断参数 DlqType 是否已赋值
* @return DlqType 是否已赋值
*
*/
bool DlqTypeHasBeenSet() const;
private:
/**
* 类型,DLQ死信队列,IGNORE_ERROR保留,DROP废弃
*/
std::string m_type;
bool m_typeHasBeenSet;
/**
* Ckafka类型死信队列
*/
KafkaParam m_kafkaParam;
bool m_kafkaParamHasBeenSet;
/**
* 重试间隔
*/
uint64_t m_retryInterval;
bool m_retryIntervalHasBeenSet;
/**
* 重试次数
*/
uint64_t m_maxRetryAttempts;
bool m_maxRetryAttemptsHasBeenSet;
/**
* DIP Topic类型死信队列
注意:此字段可能返回 null,表示取不到有效值。
*/
TopicParam m_topicParam;
bool m_topicParamHasBeenSet;
/**
* 死信队列类型,CKAFKA,TOPIC
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_dlqType;
bool m_dlqTypeHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_CKAFKA_V20190819_MODEL_FAILUREPARAM_H_
|
14c36301b395004dc03913eab38ab4a7b094f5d7 | e542e955e45277ca014430019a0188f6e85a0d3c | /HkfyCrypt/HDSerial.cpp | 8c139d7f8066cb2771a2bb8d9559ffdb9cadc57a | [] | no_license | langyastudio/sentinel-crypto | fb3eb34270dc22cb42255b8beeee3340510bf096 | 86f98f7f2149e1ff10cb3657f01144ce386b6570 | refs/heads/master | 2020-03-22T10:51:21.039366 | 2019-10-31T03:21:46 | 2019-10-31T03:21:46 | 139,931,467 | 4 | 1 | null | null | null | null | GB18030 | C++ | false | false | 2,406 | cpp | HDSerial.cpp | #include "stdafx.h"
#include "HDSerial.h"
void ChangeByteOrder(PCHAR szString, USHORT uscStrSize)
{
USHORT i = 0;
CHAR temp= '\0';
for (i = 0; i < uscStrSize; i+=2)
{
temp = szString[i];
szString[i] = szString[i+1];
szString[i+1] = temp;
}
}
//--------------------------------------------------------------
// 硬盘序列号
//--------------------------------------------------------------
BOOL GetHDSerial(char *lpszHD, int len/*=128*/)
{
BOOL bRtn = FALSE;
DWORD bytesRtn = 0;
char szhd[80] = {0};
PIDSECTOR phdinfo;
HANDLE hDrive = NULL;
GETVERSIONOUTPARAMS vers;
SENDCMDINPARAMS in;
SENDCMDOUTPARAMS out;
ZeroMemory(&vers, sizeof(vers));
ZeroMemory(&in , sizeof(in));
ZeroMemory(&out , sizeof(out));
//搜索四个物理硬盘,取第一个有数据的物理硬盘
for (int j=0; j<4; j++)
{
sprintf(szhd, "\\\\.\\PhysicalDrive%d", j);
hDrive = CreateFileA(szhd,
GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_READ|FILE_SHARE_WRITE,
0,
OPEN_EXISTING,
0,
0);
if (NULL == hDrive)
{
continue;
}
if (!DeviceIoControl(hDrive, DFP_GET_VERSION, 0, 0, &vers, sizeof(vers), &bytesRtn,0))
{
goto FOREND;
}
//If IDE identify command not supported, fails
if (!(vers.fCapabilities&1))
{
goto FOREND;
}
//Identify the IDE drives
if (j&1)
{
in.irDriveRegs.bDriveHeadReg = 0xb0;
}
else
{
in.irDriveRegs.bDriveHeadReg = 0xa0;
}
if (vers.fCapabilities&(16>>j))
{
//We don't detect a ATAPI device.
goto FOREND;
}
else
{
in.irDriveRegs.bCommandReg = 0xec;
}
in.bDriveNumber = j;
in.irDriveRegs.bSectorCountReg = 1;
in.irDriveRegs.bSectorNumberReg = 1;
in.cBufferSize = 512;
if (!DeviceIoControl(hDrive, DFP_RECEIVE_DRIVE_DATA, &in, sizeof(in), &out, sizeof(out), &bytesRtn,0))
{
//"DeviceIoControl failed:DFP_RECEIVE_DRIVE_DATA"<<endl;
goto FOREND;
}
phdinfo=(PIDSECTOR)out.bBuffer;
char s[21] = {0};
memcpy(s, phdinfo->sSerialNumber, 20);
s[20] = 0;
ChangeByteOrder(s, 20);
//删除空格字符
int ix = 0;
for (ix=0; ix<20; ix++)
{
if (s[ix] == ' ')
{
continue;
}
break;
}
memcpy(lpszHD, s+ix, 20);
bRtn = TRUE;
break;
FOREND:
CloseHandle(hDrive);
hDrive = NULL;
}
CloseHandle(hDrive);
hDrive = NULL;
return(bRtn);
} |
a168cd469e06c25fb9243a65f8cdd3af38f2d7ce | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5769900270288896_1/C++/JaNo/B.cpp | 61d876da45c2dba6f78984bc517c59c302d9274f | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,732 | cpp | B.cpp | //Fruit of Light
//FoL CC
//Apple Strawberry
#include<cstdio>
#include<algorithm>
#include<vector>
#include<iostream>
#include<set>
#include<map>
#include<queue>
#include<cmath>
#include<cstring>
using namespace std;
#define For(i, n) for(int i = 0; i<(n); ++i)
#define INF 1023456789
#define eps 1e-9
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
int oneway(int r, int c, int n){
int sq = r*c;
int zero = sq-sq/2;
int one = 0;
int two = 0;
if (sq%2==0) two = 2;
if (min(r,c)==1) {
two = sq/2;
if (sq%2==0) {two--; one++;}
}
int inside = max(0,((r-2)*(c-2))/2);
int bound = sq/2 - inside;
int three = bound-two-one;
int four = inside;
int bad = 0;
n -= zero;
bad += max(0, min(n, one)); n-=one;
bad += max(0, min(n, two))*2; n-=two;
bad += max(0, min(n, three))*3; n-=three;
bad += max(0, min(n, four))*4;
return bad;
}
int secondway(int r, int c, int n){
if (min(r,c)==1) return INF;
int sq = r*c;
int zero = sq/2;
int one = 0;
int two = 0;
if (sq%2==0) two = 2;
else two = 4;
int inside = max(0,(r-2)*(c-2) - ((r-2)*(c-2))/2);
int bound = (sq - sq/2) - inside;
int three = bound-two-one;
int four = inside;
int bad = 0;
n -= zero;
bad += max(0, min(n, one)); n-=one;
bad += max(0, min(n, two))*2; n-=two;
bad += max(0, min(n, three))*3; n-=three;
bad += max(0, min(n, four))*4;
return bad;
}
int extra(){
int r,c,n;
scanf("%d%d%d", &r,&c,&n);
printf("%d\n", min(oneway(r,c,n), secondway(r,c,n)));
}
int main(){
int T;
scanf("%d",&T);
For(i,T){
printf("Case #%d: ",i+1);
extra();
}
}
|
79181d05956e3bd243d9dc31cb113f2b93500107 | c30e2a0dc71db5fcdd459db52e012f116c4a726e | /LearnC++ForProgramingDevelopement/TextAdventure/Chapter26-TextAdventure/EvaluateVisitor.cpp | 8b5a9811cc8620b802f51db4fafd5bf68fd8c3bf | [
"MIT"
] | permissive | Gabroide/Learning-C- | 9bcfc09fb826ea78affca118572fa7ac7c7b786b | d2fc9b2ef21d66a17b9b716975087093c592abbc | refs/heads/master | 2021-07-21T08:41:40.602975 | 2020-05-10T20:16:47 | 2020-05-10T20:16:47 | 161,846,077 | 0 | 0 | MIT | 2019-06-12T07:45:47 | 2018-12-14T22:15:43 | C++ | UTF-8 | C++ | false | false | 297 | cpp | EvaluateVisitor.cpp | #include "EvaluateVisitor.h"
#include "Option.h"
EvaluateVisitor::EvaluateVisitor(Player& player)
: m_player{ player }
{
}
void EvaluateVisitor::OnVisit(Visitable& visitable)
{
Option* pOption = dynamic_cast<Option*>(&visitable);
if (pOption != nullptr)
{
pOption->Evaluate(m_player);
}
} |
0bedc3d037b141593e5d2c639d9063cf7f89194f | 59c4a6fe9c686654922e1f365a5098a18ec9eef5 | /src/parameterised/api/module.cc | 20a6f719ed2ea2ec966cd96afd6f30a52165965e | [
"MIT"
] | permissive | pabble-lang/libscribble | c002f622ccf05e1c84b9e274dc9d921fd530fcfa | df25fb8a88257fa3249e9faaa3e6fe69a10f0082 | refs/heads/master | 2020-06-19T05:25:24.946495 | 2015-08-07T02:27:37 | 2015-08-07T02:27:37 | 74,918,949 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,220 | cc | module.cc | #include <scribble/parameterised/const.h>
#include <scribble/parameterised/ext_type.h>
#include <scribble/parameterised/import.h>
#include <scribble/parameterised/module.h>
#include <scribble/parameterised/protocol.h>
#include <scribble/parameterised/range.h>
namespace scribble {
namespace parameterised {
pbl_module *pbl_mk_module_init()
{
return new Module();
}
pbl_module *pbl_mk_module(char *name)
{
return new Module(name);
}
pbl_module *pbl_module_add_protocol(pbl_module *module, pbl_protocol *protocol)
{
module->add_session(protocol);
return module;
}
pbl_module *pbl_module_add_import(pbl_module *module, pbl_import *import)
{
module->add_import(import);
return module;
}
pbl_module *pbl_module_add_const(pbl_module *module, pbl_const *constant)
{
module->add_constant(constant);
return module;
}
pbl_module *pbl_module_add_exttype(pbl_module *module, pbl_exttype *exttype)
{
module->add_datatype(exttype);
return module;
}
pbl_module *pbl_module_add_range(pbl_module *module, pbl_rng *rng)
{
module->add_range(rng);
return module;
}
void pbl_module_free(pbl_module *module)
{
delete module;
}
} // namespace parameterised
} // namesapce scribble
|
644adaca3f2d5a80f43a6b608fb644efeebbea64 | 630db4ba2ef42eb3a81972da808881b9dfa707e6 | /2021-05-31-baekjoon1037.cpp | 589afd6eb9e7a05dda6533f7557606ad0266c8e7 | [] | no_license | Byeongchan99/Algorithm_Study | 90283d97767df5b5e5075a3a9c1250d0a7765e91 | ad913b72c95582fbb4a99e4fef4219be6f25a19d | refs/heads/main | 2023-07-02T09:58:09.302871 | 2021-08-01T10:38:30 | 2021-08-01T10:38:30 | 313,072,328 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 857 | cpp | 2021-05-31-baekjoon1037.cpp | 1037 약수
양수 A가 N의 진짜 약수가 되려면, N이 A의 배수이고, A가 1과 N이 아니어야 한다. 어떤 수 N의 진짜 약수가 모두 주어질 때, N을 구하는 프로그램을 작성하시오.
#define _CRT_SECURE_NO_WARNINGS
#include <numeric>
#include <cstdio>
#include <stdlib.h>
#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <climits> // 최댓값, 최솟값
#include <cmath> // 수학 - min, max 등
#include <cassert> // assert - 오류 검출용
#include <queue>
#include <stack>
#include <deque>
#include <map>
#include <set>
using namespace std;
int main() {
int n, min_A = 987654321, max_A = 0, A;
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
scanf("%d", &A);
min_A = min(min_A, A);
max_A = max(max_A, A);
}
printf("%d", min_A * max_A);
}
|
50efb1519f1c44339c701b5e7f7565a44d6b2c25 | 461619a84c6617ceaf2b7913ef58c99ff32c0fb5 | /twitter/statuses/user_timeline/src/statuses/statuses/main.cpp | 5e5a18a90a193f9b5d6f1fe5566d223cbf441c40 | [
"MIT"
] | permissive | bg1bgst333/Sample | cf066e48facac8ecd203c56665251fa1aa103844 | 298a4253dd8123b29bc90a3569f2117d7f6858f8 | refs/heads/master | 2023-09-02T00:46:31.139148 | 2023-09-01T02:41:42 | 2023-09-01T02:41:42 | 27,908,184 | 9 | 10 | MIT | 2023-09-06T20:49:55 | 2014-12-12T06:22:49 | Java | SHIFT_JIS | C++ | false | false | 8,089 | cpp | main.cpp | // ヘッダのインクルード
// 既定のヘッダ
#include <tchar.h> // TCHAR型
#include <iostream> // C++標準入出力
#include <string> // std::string
#include <winsock2.h> // Windowsソケット
#include <ws2tcpip.h> // WinSock2 TCP/IP
#include <openssl/bio.h> // BIO
#include <openssl/ssl.h> // SSL
#include <openssl/err.h> // エラー
// 独自のヘッダ
#include "credentials.h" // 認証情報
// マクロの定義
// UNICODE切り替え
#ifdef UNICODE
#define tstring std::wstring
#else
#define tstring std::string
#endif
// _tmain関数の定義
int _tmain() {
// 変数の宣言と初期化.
WSADATA wsaData; // WSADATA型wsaData.
int iRet; // int型iRet.
struct addrinfo hint = { 0 }; // addrinfo構造体hintを0で初期化.
struct addrinfo *ai; // addrinfo構造体ポインタai.
int soc = -1; // ソケットファイルディスクリプタsocを-1に初期化.
SSL_CTX *ctx = NULL; // SSL_CTX構造体へのポインタctxをNULLに初期化.
SSL *ssl = NULL; // SSL接続情報を持つSSL構造体へのポインタsslをNULLに初期化.
tstring request_tstr; // リクエスト文字列request_tstr.
int len; // 文字コード変換後の長さlen.
char request_str[4096]; // 文字コード変換後のリクエスト文字列request_str.
int written = 0; // SSL_writeでの書き込みに成功した長さwritten.
char response_buf[1024] = { 0 }; // char型配列response_buf(要素数1024)を0で初期化.
int response_len = 0; // SSL_readで読み込んだ長さを格納するresponse_lenを0で初期化.
// WinSockの初期化.
iRet = WSAStartup(MAKEWORD(2, 2), &wsaData); // WSAStartupでWinSockの初期化.
if (iRet) { // 0でない場合.
// エラー処理.
_tprintf(_T("Error!(iRet = %d.)\n"), iRet); // _tprintfでiRetを出力.
WSACleanup(); // WSACleanupで終了処理.
return -1; // -1を返す.
}
// 初期化成功メッセージ.
_tprintf(_T("WSAStartup success!\n")); // "WSAStartup success!"と出力.
// ファミリーとソケットタイプのセット.
hint.ai_family = AF_INET; // ファミリーはAF_INET.
hint.ai_socktype = SOCK_STREAM; // ソケットタイプはSOCK_STREAM.
// addrinfo構造体の取得.
iRet = getaddrinfo("api.twitter.com", "https", &hint, &ai); // getaddrinfoでホスト情報取得.
if (iRet) { // 0以外はエラー.
// エラー処理.
_tprintf(_T("Error!(iRet = %d.)\n"), iRet); // _tprintfでiRetを出力.
WSACleanup(); // WSACleanupで終了処理.
return -2; // -2を返す.
}
// ソケットの生成.
soc = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); // socketでaiのメンバを渡してsocを生成.
if (soc == -1) { // -1でエラー.
// エラー処理.
_tprintf(_T("Error!(soc = %d.)\n"), soc); // _tprintfでsocを出力.
freeaddrinfo(ai); // freeaddrinfoでaiを解放.
WSACleanup(); // WSACleanupで終了処理.
return -3; // -3を返す.
}
// socを出力.
_tprintf(_T("soc = %d\n"), soc); // _tprintfでsocを出力.
// 接続
iRet = connect(soc, ai->ai_addr, ai->ai_addrlen); // connectで接続.
if (iRet == -1) { // -1だとエラー.
// エラー処理.
closesocket(soc); // closesocketでsocを閉じる.
freeaddrinfo(ai); // freeaddrinfoでaiを解放.
WSACleanup(); // WSACleanupで終了処理.
return -4; // -4を返す.
}
// 接続成功.
_tprintf(_T("connect success!\n")); // _tprintfで"connect success!"を出力.
// SSLライブラリの初期化.
SSL_library_init(); // SSL_library_initでSSLライブラリの初期化.
SSL_load_error_strings(); // SSL_load_error_stringsでエラー文字列をロード.
// SSLコンテキストの作成.
ctx = SSL_CTX_new(SSLv23_client_method()); // SSL_CTX_newでSSLコンテキストを作成し, SSL_CTX型ポインタとしてctxに格納.
// ctxの指すアドレスを出力.
_tprintf(_T("ctx = %08x\n"), (unsigned int)ctx); // _tprintfでctxの指すアドレスを出力.
// SSL接続情報の作成.
ssl = SSL_new(ctx); // SSL_newでctxからSSL接続情報を作成し, ポインタをsslに格納.
// sslの指すアドレスを出力.
_tprintf(_T("ssl = %08x\n"), (unsigned int)ssl); // _tprintfでsslの指すアドレスを出力.
// SSL接続情報にソケットファイルディスクリプタをセット.
if (SSL_set_fd(ssl, soc) == 0) { // SSL_set_fdでsslにsocをセット.(戻り値が0なら失敗, 1なら成功.)
// エラー処理
_tprintf(_T("SSL_set_fd error!\n")); // "SSL_set_fd error!"と出力.
ERR_print_errors_fp(stderr); // ERR_print_errors_fpにstderrを渡して標準エラー出力にエラーメッセージを出力.
SSL_free(ssl); // SSL_freeでsslを解放.
SSL_CTX_free(ctx); // SSL_CTX_freeでctxを解放.
closesocket(soc); // closesocketでsocを閉じる.
freeaddrinfo(ai); // freeaddrinfoでaiを解放.
WSACleanup(); // WSACleanupで終了処理.
return -5; // -5を返す.
}
// 成功
_tprintf(_T("SSL_set_fd success!\n")); // "SSL_set_fd success!"と出力.
// SSL接続
iRet = SSL_connect(ssl); // SSL_connectにsslを渡してSSLハンドシェイクを行う.
if (iRet == 1) { // 成功
_tprintf(_T("SSL_connect success!\n")); // "SSL_connect success!"と出力.
}
else { // エラー
// エラー処理
_tprintf(_T("SSL_connect error!\n")); // "SSL_connect error!"と出力.
SSL_free(ssl); // SSL_freeでsslを解放.
SSL_CTX_free(ctx); // SSL_CTX_freeでctxを解放.
closesocket(soc); // closesocketでsocを閉じる.
freeaddrinfo(ai); // freeaddrinfoでaiを解放.
WSACleanup(); // WSACleanupで終了処理.
return -6; // -6を返す.
}
// GETリクエスト文字列の作成.
request_tstr = _T("GET /1.1/statuses/user_timeline.json?screen_name=bgst1tw1test1&count=1 HTTP/1.1"); // request_tstrに"GET /1.1/statuses/user_timeline.json?screen_name=bgst1tw1test1&count=1 HTTP/1.1"を格納.
request_tstr = request_tstr + _T("\r\n"); // 改行
request_tstr = request_tstr + _T("Authorization: Bearer "); // request_tstrに"Authorization: Bearer "を連結.
request_tstr = request_tstr + BEARER_TOKEN; // request_tstrにBEARER_TOKENを連結.
request_tstr = request_tstr + _T("\r\n"); // 改行
request_tstr = request_tstr + _T("Host: api.twitter.com"); // request_tstrに"Host: api.twitter.com"を連結.
request_tstr = request_tstr + _T("\r\n"); // 改行
request_tstr = request_tstr + _T("User-Agent: bgst1tw1test1"); // request_tstrに"User-Agent: bgst1tw1test1"を連結.
request_tstr = request_tstr + _T("\r\n\r\n"); // 空行
// request_tstrの文字コード変換(Unicode => utf-8)
len = WideCharToMultiByte(CP_UTF8, 0, request_tstr.c_str(), -1, NULL, 0, NULL, NULL); // マルチバイトに変換するためのサイズを取得.
WideCharToMultiByte(CP_UTF8, 0, request_tstr.c_str(), -1, request_str, len, NULL, NULL); // マルチバイトに変換.
// リクエストの書き込み.
written = SSL_write(ssl, request_str, len); // SSL_writeでrequest_strを書き込む.
printf("SSL_write written = %d\n", written); // SSL_writeで書き込み成功した文字数を出力.
// レスポンスの読み込み.
while ((response_len = SSL_read(ssl, response_buf, 1024 - 1)) > 0) { // SSL_readで読み込んだレスポンスをresponse_bufに格納.(1バイト以上なら続ける.)
// response_bufの内容を出力.
printf("%s", response_buf); // printfでresponse_bufを出力.
memset(response_buf, 0, sizeof(char) * 1024); // memsetでresponse_bufをクリア.
}
// 改行
printf("\n"); // printfで改行.
// SSL切断.
SSL_shutdown(ssl); // SSL_shutdownでSSL切断する.
// SSL接続情報の破棄.
SSL_free(ssl); // SSL_freeでsslを解放.
// SSLコンテキストの解放.
SSL_CTX_free(ctx); // SSL_CTX_freeでctxを解放.
// socを閉じる.
closesocket(soc); // closesocketでsocを閉じる.
// aiを解放.
freeaddrinfo(ai); // freeaddrinfoでaiを解放.
// WinSockの終了処理.
WSACleanup(); // WSACleanupで終了処理.
// プログラムの終了
return 0; // 0を返す.
} |
a64199d694eca98218b9a2263811eb5432153a8d | e1c2a102e85c37f0e99b931e3a70b5f2c0682a31 | /src/heranca/main.cpp | e81570bddf54d697b62ef724c01dee46700e7508 | [
"MIT"
] | permissive | coleandro/programacao-avancada | cc370755b7f85bb44644e326fd36f30361d1a7ea | 0de06243432fb799b1dc6707b24f2b3f6f23f76d | refs/heads/master | 2020-05-04T13:37:51.327385 | 2019-04-16T23:57:04 | 2019-04-16T23:57:04 | 131,093,863 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 880 | cpp | main.cpp | #include <iostream>
#include "Veiculo.h"
#include "Carro.h"
#include "Caminhao.h"
#include "Caminhonete.h"
int main() {
// Veiculos
Veiculo vei1("ABC-1234", 1000.0, 180.0, 63000.0);
Veiculo vei2("BCD-2345", 1280.0, 220.0, 84900.0);
// Carros
Carro car1("DEF-3456", 1080.0, 220.0, 62500.0, "VW UP CROSS TSI", "BRANCO");
Carro car2("FGH-4567", 1250.0, 240.0, 125000.0, "VW GOLF GTI", "PRATA");
// Caminhoes
Caminhao cam1("HIJ-7890", 26000.0, 120.0, 384000.0, 80.0, 6.8, 3.7);
Caminhao cam2("JKL-0123", 28000.0, 120.0, 410000.0, 70.0, 6.7, 3.5);
// Caminhonetes
Caminhonete cat1("MNO-4567", 2185.0, 190.0, 191990.0, "VW AMAROK HIGHLINE 3.0 V6 4X4 AT CD", "AZUL", 1105.0, 5254.0, 1834.0);
Caminhonete cat2("PQR-8901", 2582.0, 160.0, 490000.0, "FORD F-150 RAPTOR 3.5 V6 TURBO CD", "AZUL", 549.0, 5890.0, 1994.0);
return 0;
} |
1f82b11423cea53cef6f3d26cfa62b896aaf90f2 | d7b9c777e467afff96f0807a30f96390380e1183 | /Particle.cpp/main.cpp | 83861e05d0fe73a82d00eb476775b6890712ba9d | [] | no_license | htafer/cppStuff | bf6bc8b6451663754463417d09ab69c92efcd7c9 | dce5547d3de05093b7394d94bf9a4f0a3e37524b | refs/heads/master | 2020-04-14T13:57:01.240681 | 2019-02-22T14:49:32 | 2019-02-22T14:49:32 | 163,883,441 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,964 | cpp | main.cpp | #include <iostream>
#include <iomanip>
#include <math.h>
#include <random>
#include "SDL.h"
#include "Screen.h"
#include "Particle.h"
#include "Swarm.h"
#include <stdlib.h>
#include <time.h>
#include <cstdlib>
#include <ctime>
using namespace std;
using namespace caveofprogramming;
int main () {
srand((unsigned)time(NULL));
std::srand(std::time(nullptr));
int elapsed;
Screen screen1;
//Check if initialisation went fine
if (!screen1.init()) {
screen1.close();
};
Swarm swarm;
swarm.init();
//swarm.init_explosion(0.1, Screen::SCREEN_WIDTH/2, Screen::SCREEN_HEIGHT/2);
//Init random number generator
/* std::random_device rd; // only used once to initialise (seed) engine
std::mt19937 rng(rd()); // random-number engine used (Mersenne-Twister in this case)
//random number generator for
std::uniform_int_distribution<int> horizontal(0,Screen::SCREEN_WIDTH-1); // guaranteed unbiased
std::uniform_int_distribution<int> vertical(0,Screen::SCREEN_HEIGHT-1); // guaranteed unbiased
Particle *particles = new Particle[max_particle];
for(int i=0; i<max_particle; i++){
particles[i].init(horizontal(rng), vertical(rng), 0,0,0,255,0,0,0);
}
*/
while (true) {
//screen1.clear();
elapsed=SDL_GetTicks();
swarm.update(elapsed);
const Particle * const pParticles = swarm.getParticles();
unsigned char green = (unsigned char) ((1 + sin(elapsed * 0.0001)) * 128);
unsigned char red = (unsigned char) ((1 + sin(elapsed * 0.0002)) * 128);
unsigned char blue = (unsigned char) ((1 + sin(elapsed * 0.0003)) * 128);
for(int i=0; i<Swarm::NPARTICLE; i++){
int x = (int) ((pParticles[i].m_x +1)/2 *Screen::SCREEN_WIDTH);
int y = (int) ((pParticles[i].m_y +1)/2 *Screen::SCREEN_HEIGHT);
//cout << x << ":" << y << endl;
screen1.setPixel(x,y, red,green,blue);
//screen1.setPixel(0,0,255,0,0);
}
/*elapsed = SDL_GetTicks();
unsigned char green = (unsigned char) ((1+sin(elapsed*0.001))*128);
for(int i=0; i<max_particle; i++){
screen1.setPixel(particles[i].m_x, particles[i].m_y, particles[i].m_r, particles[i].m_g, particles[i].m_b);
}
*/
if (!screen1.processEvents()) {
break;
}
screen1.boxBlur();
screen1.update();
}
screen1.close();
return 0;
}
/*
// Allocate pixel buffer;
Uint32 *buffer = new Uint32[SCREEN_WIDTH*SCREEN_HEIGHT];
//Write pixel information in the buffer.
//Set everything to white
memset(buffer, 0xFF0000FF, SCREEN_WIDTH*SCREEN_HEIGHT*sizeof(Uint32));
memset(buffer, 0xFF0000FF, SCREEN_WIDTH*SCREEN_HEIGHT*sizeof(Uint32));
//for(int i=0; i< SCREEN_HEIGHT*SCREEN_WIDTH; i++){
// buffer[i]=0xFF0000FF;
//}
SDL_Quit();
return 0;
}
*/ |
12dd5cb205692638fdbd8a5a92f36e52b94f98ec | 0e2ee1cd50a6ba70f34dd6a570a0652b5a17ee33 | /parse_file.h | c819edb6079d25defc3059f497e2d9d66b16ab99 | [] | no_license | pzoxiuv/biostuff | e694356c824c0cdcbb107cb07d88cdb95a306531 | 6d32de235da49a7ce8c7b5b08b257a3ab031d5d7 | refs/heads/master | 2021-01-10T04:47:40.028539 | 2016-01-03T02:11:28 | 2016-01-03T02:11:28 | 48,925,803 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 124 | h | parse_file.h | #ifndef PARSE_FILE_H
#define PARSE_FILE_H
#include "main.h"
std::vector<gene_t> parse_file(const char *filename);
#endif
|
0f05608922df8d1fde7e9562894dd2acf172bd49 | f780917ad11ebb6f38ac989ad391d8c26effbe79 | /RandomForest/BeyondRandomForest/Tree.h | 1fbe444f0e1ac9a2db2d75b50e6b4b41ae4f6db3 | [] | no_license | cool-cola/Random-Forests | 349a3c9f8593fbe4a43f4253b19ab3e5d7b78e7f | 968bd395727ee8448077dee3392a0776961c1b34 | refs/heads/master | 2021-01-21T06:49:09.693608 | 2017-03-08T02:09:02 | 2017-03-08T02:09:02 | 83,287,612 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 353 | h | Tree.h | #pragma once
#include "DataTable.h"
#include "bootstrapDataset.h"
namespace BeyondRandomForest
{
class CTree
{
public:
CTree(void);
virtual ~CTree(void);
void buildTree(const CDataTable& vDataTable, const CBootstrapDataset& vBoostrapDataset, const int vCandidateVariables, const std::vector<std::string>& vResponseVariables);
private:
};
} |
3b2bea2877116dfd93ff27350243067d0efbf898 | 8755fe466d934b336bea57550c048859c3b00ae3 | /blocklist.h | 8537656f163b1cdb2a43d592a383024a7dabe657 | [] | no_license | paperplane03/BookStore_SiriusNEO | 887af9e18a8a555c63624316c4cd37415655024e | 16447e454d68ddefb34a91a26379e3287256b2d2 | refs/heads/master | 2023-03-12T05:41:18.437520 | 2021-02-20T08:42:49 | 2021-02-20T08:42:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,371 | h | blocklist.h | //
// Created by PaperL on 2020/11/9.
//
#ifndef BOOKSTORE_SIRIUSNEO_BLOCKLIST_H
#define BOOKSTORE_SIRIUSNEO_BLOCKLIST_H
#include <cstdio>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <string>
#include <string.h>
#define BLOCK_SIZE 320
#define BLOCK_SPLIT_THRESHOLD 300
#define BLOCK_SPLIT_LEFT 150
#define BLOCK_MERGE_THRESHOLD 30
//#define PaperL_Debug
using namespace std;
class Node {
public:
int offset;
char str[64];
bool operator<(const Node &x) const;
Node();
Node(const int &arg1, const string &arg2);
Node &operator=(const Node &right);
};
class Block {
public:
int nxt;
int pre;
int num;
Node array[BLOCK_SIZE];
Block();
Block &operator=(const Block &right);
};
class blocklist {
private:
const string fname;
fstream fi, fo, fi2, fo2, fip, fip2, fop, fop2;
inline int nextBlock(const int &offset);
inline void delBlock(const int &offset);
void mergeBlock(const int &offset1, const int &offset2);
void splitBlock(const int &offset);
public:
blocklist(const string &arg);
~blocklist();
void findNode(const string &key, vector<int> &array);
void addNode(const Node &node);
int deleteNode(const Node &node);
#ifdef PaperL_Debug
void debugPrint();
#endif
};
#endif //BOOKSTORE_SIRIUSNEO_BLOCKLIST_H
|
cda07f64161ee0f2cabf0bdc4f7f05bb1cbfd16b | ba7c50c6898069aa53bca4328f0f91bebdc6b5f4 | /libraries/MenuManager/MenuManager.cpp | 6d3191f167fe4e231e14c0f028646a89e89104f1 | [] | no_license | martinzk/sw5 | ea691e2185a3ed3250bc5ba301b4c7b8acc3adab | 575db6012f06c2b3483316f51d3998ff4ec4b425 | refs/heads/master | 2020-11-30T00:33:45.568496 | 2015-09-16T12:16:14 | 2015-09-16T12:16:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,261 | cpp | MenuManager.cpp | #include <MenuManager.h>
bool MenuManager::instanceFlag = false;
MenuManager* MenuManager::menuManager = NULL;
MenuManager* MenuManager::GetMenuManager()
{
if(!instanceFlag)
{
menuManager = new MenuManager();
instanceFlag = true;
return menuManager;
}
return menuManager;
}
MenuManager::MenuManager()
{
keypad.SetInPin(AD_KEYPAD_PIN);
keypad.AddButton(1, 0, 40);
keypad.AddButton(2, 141, 40);
keypad.AddButton(3, 328, 40);
keypad.AddButton(4, 503, 40);
keypad.AddButton(5, 740, 40);
}
void MenuManager::AddRootMenu(Menu* rootMenu)
{
this->currentMenu = rootMenu;
this->rootMenu = rootMenu;
this->currentMenu->Select();
}
void MenuManager::SelectPush()
{
int buttonPress = 0;
buttonPress = keypad.RegisterPush();
switch (buttonPress)
{
case 1:
this->back();
break;
case 2:
this->up();
break;
case 3:
this->down();
break;
case 4:
this->execute();
break;
case 5:
this->home();
default:
break;
}
}
void MenuManager::up()
{
int row = this->currentMenu->index - this->currentMenu->menuRowCounter;
if(this->currentMenu->index != 0)
{
if(row == 0)
{
this->currentMenu->menuRowCounter--;
}
this->currentMenu->index--;
this->currentMenu->Select();
}
}
void MenuManager::down()
{
int row = this->currentMenu->index - this->currentMenu->menuRowCounter;
if(this->currentMenu->index +1 < this->currentMenu->GetMenuSize())
{
if(row == 3)
{
this->currentMenu->menuRowCounter++;
}
this->currentMenu->index++;
this->currentMenu->Select();
}
}
void MenuManager::execute()
{
if(this->currentMenu->GetMenuSize() >0)
{
IMenuItem* child = this->currentMenu->GetMenuChild();
if(child->GetType() == currentMenu->GetType())
{
this->currentMenu = static_cast<Menu*>(child);
}
child->Select();
}
}
void MenuManager::back()
{
this->currentMenu->index = 0;
this->currentMenu->menuRowCounter = 0;
if(this->currentMenu != this->rootMenu)
{
this->currentMenu = static_cast<Menu*>(this->currentMenu->GetParent());
}
this->currentMenu->Select();
}
void MenuManager::home()
{
this->rootMenu->index = 0;
this->rootMenu->menuRowCounter = 0;
this->currentMenu = this->rootMenu;
this->currentMenu->Select();
} |
2cc73532885eeb7cac71f8aa1ed24475e66b8d3f | 172a04c22139983d2a093292b709eb15045dbe7f | /ctripui/roomsuserui.cpp | 99977231223c1875514328dabdcf1a5185491d15 | [] | no_license | inhzus/hotelManage | a080d8d6c48454ffa7d28bb3bf2886e3980dfb23 | 2e0cef0cd019d19cae9ce7ae076c48be9a2b8df8 | refs/heads/master | 2021-06-14T23:32:15.936229 | 2017-04-05T00:10:46 | 2017-04-05T00:10:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,404 | cpp | roomsuserui.cpp | #include "roomsuserui.h"
RoomsUserui::RoomsUserui(QWidget *parent) :
QDialog(parent),
ui(new Ui::RoomsUserui)
{
this->setWindowFlags(Qt::WindowCloseButtonHint | Qt::MSWindowsFixedSizeDialogHint);
ui->setupUi(this);
this->setFixedSize(640, 450);
uRow = getVecRow(uRow);
connect(ui->tableWidget, SIGNAL(itemDoubleClicked(QTableWidgetItem*)), this, SLOT(orderRoom(QTableWidgetItem*)));
buildTable();
}
RoomsUserui::~RoomsUserui()
{
delete ui;
}
void RoomsUserui::buildTable(){
auto *table = ui->tableWidget;
table->verticalHeader()->setVisible(false);
table->horizontalHeader()->setHighlightSections(false);
table->horizontalHeader()->setStretchLastSection(true);
table->setSelectionBehavior(QAbstractItemView::SelectRows);
table->setEditTriggers(QAbstractItemView::NoEditTriggers);//编辑
table->horizontalHeader()->setFixedHeight(35);
QFont font("等线", 10, 20);
table->setFont(font);
table->setStyleSheet(
//"color:grey;"
//"selection-background-color:lightblue;"
"selection-background-color:rgb(34, 175, 75);"
);
table->horizontalScrollBar()->setStyleSheet("QScrollBar{background:transparent; height:10px;}"
"QScrollBar::handle{background:lightgray; border:2px solid transparent; border-radius:5px;}"
"QScrollBar::handle:hover{background:gray;}"
"QScrollBar::sub-line{background:transparent;}"
"QScrollBar::add-line{background:transparent;}");
table->verticalScrollBar()->setStyleSheet("QScrollBar{background:transparent; width: 10px;}"
"QScrollBar::handle{background:lightgray; border:2px solid transparent; border-radius:5px;}"
"QScrollBar::handle:hover{background:gray;}"
"QScrollBar::sub-line{background:transparent;}"
"QScrollBar::add-line{background:transparent;}");
showGrid();
}
void RoomsUserui::showGrid(){
auto *table = ui->tableWidget;
int i = uRow;
string name = vhotels[i].name;
ui->tableWidget->clear();
QStringList header;
table->setColumnCount(4);
table->setRowCount((int)vrooms[i].size() - 1);
header << "name" << "key" << "price" << "type";
table->setHorizontalHeaderLabels(header);
for(int j = 1; j < vrooms[i].size(); ++j){
table->setItem(j - 1, 0, new QTableWidgetItem(QString::fromStdString(name)));
stringstream ss; string s;
ss << vrooms[i][j].numR;
ss >> s;
table->setItem(j - 1, 1, new QTableWidgetItem(QString::fromStdString(s)));
ss.clear();
ss << vrooms[i][j].price;
ss >> s;
table->setItem(j - 1, 2, new QTableWidgetItem(QString::fromStdString(s))); ss.clear();
table->setItem(j - 1, 3, new QTableWidgetItem(QString::fromStdString(vrooms[i][j].type)));
for(int k = 0; k < 4; ++k) table->item(j - 1,k)->setTextAlignment(Qt::AlignCenter);
}
table->resizeColumnToContents(0);
}
void RoomsUserui::orderRoom(QTableWidgetItem *item){
uColumn = item->row() + 1;
Ordering oding;
oding.exec();
}
|
1ed3bbd5b46439ef14f8f6cd55b3899cf0080500 | e0a762aed8e0639d9760060f847e0e9185bbfde1 | /src/renderer/scenegraph/LightNode.h | 4fcb3a194bddd986d9a2242e98a3b7149cffc198 | [] | no_license | sondrex76/-imt2531-2019-exam-sondrewr | 219764173d18201c8cc328ac330fbb208bc6dd94 | c21c7d84005912f1c0a854c80be14852ca0fc505 | refs/heads/master | 2020-05-19T00:29:16.999310 | 2019-05-06T09:13:50 | 2019-05-06T09:13:50 | 184,736,182 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,014 | h | LightNode.h | #pragma once
#include "Node.h"
#include "../defines.h"
namespace Scenegraph {
template<class TLight>
class LightNode final : public Node {
public:
LightNode(const TLight &light, glm::mat4x4 transform) : Node(transform), m_light(&light) {}
bool bindActiveCamera(const glm::mat4x4 &parentAbsTransform, Renderer::CameraData &buffer) const override {
// Lights don't have a camera
return false;
}
void renderGeometry(const glm::mat4x4 &parentAbsTransform) const override {
#ifdef RENDER_LIGHT_DEBUG
m_light->renderDebug(absoluteTransform(parentAbsTransform));
#endif
}
void renderLights(const glm::mat4x4 &parentAbsTransform, const Renderer::GBuffer &gbuffer, Renderer::ColorTexture &target, Renderer::RenderLightGeometryCb &geometryCb) const override {
m_light->render(gbuffer, target, absoluteTransform(parentAbsTransform), geometryCb);
}
private:
const TLight *m_light;
};
}
|
1b5734edac2aee2208b83e18366f286b37047185 | a8a31b178932adc882da490b89d3d2a44cca9999 | /trajectory_publisher/src/polynomialtrajectory.cpp | d736a9f62791368da18a598d47c12b73be30ea64 | [
"BSD-3-Clause"
] | permissive | Jaeyoung-Lim/mavros_controllers | 2a4e352b73a04fcdefd15a05a308326d67c6f67e | 8b3fff0327b56c415aa24708bea5f37d76307404 | refs/heads/master | 2022-09-26T16:00:55.140038 | 2022-08-22T10:33:47 | 2022-08-23T07:36:52 | 140,596,755 | 360 | 162 | BSD-3-Clause | 2022-08-23T07:36:52 | 2018-07-11T15:43:22 | C++ | UTF-8 | C++ | false | false | 6,343 | cpp | polynomialtrajectory.cpp | /****************************************************************************
*
* Copyright (c) 2018-2021 Jaeyoung Lim. 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 PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @brief Polynomial Trajectory
*
* @author Jaeyoung Lim <jalim@ethz.ch>
*/
#include "trajectory_publisher/polynomialtrajectory.h"
polynomialtrajectory::polynomialtrajectory() : N(0), dt_(0.1), T_(1.0) {
c_x_ << 0.0, 0.0, 0.0, 0.0;
c_y_ << 0.0, 0.0, 0.0, 0.0;
c_z_ << 0.0, 0.0, 0.0, 0.0;
};
polynomialtrajectory::~polynomialtrajectory() {}
void polynomialtrajectory::setCoefficients(Eigen::VectorXd &x_coefficients, Eigen::VectorXd &y_coefficients,
Eigen::VectorXd &z_coefficients) {
c_x_ = x_coefficients;
c_y_ = y_coefficients;
c_z_ = z_coefficients;
}
void polynomialtrajectory::initPrimitives(Eigen::Vector3d pos, Eigen::Vector3d axis, double omega) {
// Generate primitives based on current state for smooth trajectory
c_x_(0) = pos(0);
c_y_(0) = pos(1);
c_z_(0) = pos(2);
}
void polynomialtrajectory::generatePrimitives(Eigen::Vector3d pos) {
// Generate primitives based on current state for smooth trajectory
c_x_(0) = pos(0);
c_y_(0) = pos(1);
c_z_(0) = pos(2);
}
void polynomialtrajectory::generatePrimitives(Eigen::Vector3d pos, Eigen::Vector3d vel) {
// Generate primitives based on current state for smooth trajectory
c_x_(0) = pos(0);
c_y_(0) = pos(1);
c_z_(0) = pos(2);
c_x_(1) = vel(0);
c_y_(1) = vel(1);
c_z_(1) = vel(2);
}
void polynomialtrajectory::generatePrimitives(Eigen::Vector3d pos, Eigen::Vector3d vel, Eigen::Vector3d jerk) {
// Generate primitives based on current state for smooth trajectory
c_x_(0) = pos(0);
c_y_(0) = pos(1);
c_z_(0) = pos(2);
c_x_(1) = vel(0);
c_y_(1) = vel(1);
c_z_(1) = vel(2);
c_x_(2) = 0.0; // Acceleration is neglected
c_y_(2) = 0.0;
c_z_(2) = 0.0;
c_x_(3) = jerk(0);
c_y_(3) = jerk(1);
c_z_(3) = jerk(2);
}
void polynomialtrajectory::generatePrimitives(Eigen::Vector3d pos, Eigen::Vector3d vel, Eigen::Vector3d acc,
Eigen::Vector3d jerk) {
// Generate primitives based on current state for smooth trajectory
c_x_(0) = pos(0);
c_y_(0) = pos(1);
c_z_(0) = pos(2);
c_x_(1) = vel(0);
c_y_(1) = vel(1);
c_z_(1) = vel(2);
c_x_(2) = acc(0);
c_y_(2) = acc(1);
c_z_(2) = acc(2);
c_x_(3) = jerk(0);
c_y_(3) = jerk(1);
c_z_(3) = jerk(2);
}
Eigen::VectorXd polynomialtrajectory::getCoefficients(int dim) {
switch (dim) {
case 0:
return c_x_;
case 1:
return c_y_;
case 2:
return c_z_;
}
}
Eigen::Vector3d polynomialtrajectory::getPosition(double time) {
Eigen::Vector3d position;
position << c_x_(0) + c_x_(1) * time + c_x_(2) * pow(time, 2) + c_x_(3) * pow(time, 3),
c_y_(0) + c_y_(1) * time + c_y_(2) * pow(time, 2) + c_y_(3) * pow(time, 3),
c_z_(0) + c_z_(1) * time + c_z_(2) * pow(time, 2) + c_z_(3) * pow(time, 3);
return position;
}
Eigen::Vector3d polynomialtrajectory::getVelocity(double time) {
Eigen::Vector3d velocity;
velocity << c_x_(1) + c_x_(2) * time * 2 + c_x_(3) * pow(time, 2) * 3,
c_y_(1) + c_y_(2) * time * 2 + c_y_(3) * pow(time, 2) * 3,
c_z_(1) + c_z_(2) * time * 2 + c_z_(3) * pow(time, 2) * 3;
return velocity;
}
Eigen::Vector3d polynomialtrajectory::getAcceleration(double time) {
Eigen::Vector3d acceleration;
acceleration << c_x_(2) * 2 + c_x_(3) * time * 6, c_y_(2) * 2 + c_y_(3) * time * 6, c_z_(2) * 2 + c_z_(3) * time * 6;
return acceleration;
}
nav_msgs::Path polynomialtrajectory::getSegment() {
Eigen::Vector3d targetPosition;
Eigen::Vector4d targetOrientation;
nav_msgs::Path segment;
targetOrientation << 1.0, 0.0, 0.0, 0.0;
geometry_msgs::PoseStamped targetPoseStamped;
for (double t = 0; t < this->getDuration(); t += this->getsamplingTime()) {
targetPosition = this->getPosition(t);
targetPoseStamped = vector3d2PoseStampedMsg(targetPosition, targetOrientation);
segment.poses.push_back(targetPoseStamped);
}
return segment;
}
geometry_msgs::PoseStamped polynomialtrajectory::vector3d2PoseStampedMsg(Eigen::Vector3d position,
Eigen::Vector4d orientation) {
geometry_msgs::PoseStamped encode_msg;
encode_msg.header.stamp = ros::Time::now();
encode_msg.header.frame_id = "map";
encode_msg.pose.orientation.w = orientation(0);
encode_msg.pose.orientation.x = orientation(1);
encode_msg.pose.orientation.y = orientation(2);
encode_msg.pose.orientation.z = orientation(3);
encode_msg.pose.position.x = position(0);
encode_msg.pose.position.y = position(1);
encode_msg.pose.position.z = position(2);
return encode_msg;
} |
7071cd454e7cb47c0c3158b5c5065737cbdc3ac4 | b45a48e484b04c2c095a8202a2532058fb8a1e52 | /TC3045/Parcial uno/Entregas/CesarTest/Cesar.h | cfcd8f970a097cb832ba40ea7532a3da5ee4400a | [] | no_license | Biller17/PruebasYCalidadSoftware | d412335dbb2fbe850cc419553673691ea80d8821 | 215dcbf3ab5ef4dc204114126b400705d29f4d2d | refs/heads/master | 2021-01-11T23:01:51.169654 | 2017-05-19T04:00:30 | 2017-05-19T04:00:30 | 78,536,484 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,086 | h | Cesar.h | #pragma once
#include <iostream>
#include <fstream>
#include <string>
class Cesar {
public:
Cesar(){}
std::string read (){
std::ifstream file;
std::string word;
std::string decriptedWord;
bool decripted = false;
file.open("encriptado.txt");
word.clear();
char x;
while(file >> word){
x = file.get();
while(x != ' '){
word = word + x;
x = file.get();
}
int i = 1;
for(; i < 27; i++); {
word = decrypt(word,i);
if(search(word)){
break;
}
}
word.clear();
}
file.close();
}
std::string decrypt(std::string encrypted, int offset){
for(int i = 0; i < encrypted.size(); i++){
encrypted[i]+=offset;
}
return encrypted;
}
bool search(std::string word){
std::ifstream file;
std::string line;
file.open("diccionario.txt");
while(file.is_open()){
getline(file, line);
if(word.compare(line) == 0)
return true;
if(file.eof()){
file.close();
return false;
}
}
}
};
|
3f6b35d0c28f11b5a7e6adfffe92a8c8035e1572 | f9a3f11ee028cdb73b22b7fa18648c0abb5f425d | /zcode/DSA01005.cpp | 3dd2455bf7ed6a7daee0d8e0870896203d799de1 | [] | no_license | pearldarkk/C-Cplusplus | 431e17343ca6a1859aca1dc1b8a353afa7d23a87 | 43b5f656c9e7dd0a7866f50c69a0c49ad115c2f1 | refs/heads/main | 2023-08-22T05:43:32.770939 | 2021-10-26T13:36:18 | 2021-10-26T13:36:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 820 | cpp | DSA01005.cpp | #include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<int> v;
vector<bool> used;
int n;
void gen(int x) {
for (int i = 1; i <= n; ++i)
if (!used[i]) {
v[x] = i;
used[i] = 1;
if (x == n) {
for (int i = 1; i <= n; ++i)
cout << v[i];
cout << ' ';
} else
gen(x + 1);
used[i] = 0;
}
}
int main() {
//freopen("text.inp", "r", stdin);
// freopen("text.out", "w", stdout);
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
while (t--) {
cin >> n;
used.resize(0);
used.resize(n + 1);
v.resize(n + 1);
gen(1);
cout << endl;
}
return 0;
} |
4b3cbe64de00011db26ce58ba0b05e7d2d674953 | d01e649cacedffbe3bef656dd6f4e29986e3bad0 | /includes/myroom/node/node.hpp | ab98bf397b346847c8990984aeab6427b90b8250 | [] | no_license | mazlani/my-room-virtual-reality | c4e6b7fb0fa869e41403dc1c9336d5c248f509df | c8014b48263aea6a9e47df0dc085e58dba5714db | refs/heads/master | 2021-07-24T22:38:29.937887 | 2017-11-03T16:55:08 | 2017-11-03T16:55:08 | 108,431,897 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,012 | hpp | node.hpp | #ifndef MYROOM_NODE_NODE_HPP
#define MYROOM_NODE_NODE_HPP
#include <iterator>
#include <OpenSG/OSGBaseTypes.h>
#include <OpenSG/OSGComponentTransform.h>
#include <OpenSG/OSGGroup.h>
#include <OpenSG/OSGNode.h>
#include <OpenSG/OSGMaterial.h>
#include <myroom/util/color.hpp>
namespace myroom { namespace node {
OSG::NodeTransitPtr
pointNode(const OSG::Vec3f &pos,
const OSG::Real32 size = 1,
const OSG::MaterialRecPtr material = myroom::util::defaultMaterialColor());
OSG::NodeTransitPtr
lineNode(const OSG::Vec3f &start,
const OSG::Vec3f &end,
const OSG::Real32 size = 1,
const OSG::MaterialRecPtr material = myroom::util::defaultMaterialColor());
OSG::NodeTransitPtr
segmentNode(const OSG::Vec3f &start,
const OSG::Vec3f &end,
const OSG::Real32 size = 1,
const OSG::MaterialRecPtr material = myroom::util::defaultMaterialColor());
}}
#endif //MYROOM_NODE_NODE_HPP
|
25760c43a495f8fc005f126db5d1f633b3106df5 | 0d653408de7c08f1bef4dfba5c43431897097a4a | /cmajor/wing/ImageList.cpp | 0691eb122678b820b0918558cfcaee8a97b175fd | [] | no_license | slaakko/cmajorm | 948268634b8dd3e00f86a5b5415bee894867b17c | 1f123fc367d14d3ef793eefab56ad98849ee0f25 | refs/heads/master | 2023-08-31T14:05:46.897333 | 2023-08-11T11:40:44 | 2023-08-11T11:40:44 | 166,633,055 | 7 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,843 | cpp | ImageList.cpp | // =================================
// Copyright (c) 2022 Seppo Laakko
// Distributed under the MIT license
// =================================
#include <wing/ImageList.hpp>
#include <wing/Control.hpp>
#include <soulng/util/Unicode.hpp>
namespace cmajor { namespace wing {
using namespace soulng::unicode;
ImageList::ImageList()
{
}
void ImageList::AddImage(const std::string& imageName)
{
std::u16string bitmapName = ToUtf16(imageName);
Bitmap* bitmap = Bitmap::FromResource(Instance(), (const WCHAR*)bitmapName.c_str());
AddImage(imageName, bitmap);
}
void ImageList::AddDisabledImage(const std::string& imageName)
{
int imageIndex = GetImageIndex(imageName);
if (imageIndex != -1)
{
Bitmap* bitmap = images[imageIndex].get();
std::unique_ptr<Bitmap> disabledBitmap = ToGrayBitmap(bitmap, DefaultBitmapTransparentColor());
AddImage(imageName + ".disabled", disabledBitmap.release());
}
else
{
throw std::runtime_error("image '" + imageName + "' not found");
}
}
void ImageList::AddImage(const std::string& imageName, Bitmap* bitmap)
{
int imageIndex = images.size();
images.push_back(std::unique_ptr<Bitmap>(bitmap));
imageIndexMap[imageName] = imageIndex;
}
int ImageList::GetImageIndex(const std::string& imageName) const
{
auto it = imageIndexMap.find(imageName);
if (it != imageIndexMap.cend())
{
return it->second;
}
else
{
return -1;
}
}
int ImageList::GetDisabledImageIndex(const std::string& imageName) const
{
return GetImageIndex(imageName + ".disabled");
}
Bitmap* ImageList::GetImage(int imageIndex) const
{
if (imageIndex >= 0 && imageIndex < images.size())
{
return images[imageIndex].get();
}
else
{
return nullptr;
}
}
} } // cmajor::wing
|
52c7178ad406faddc04e1a781e6abea042a69b90 | 2192a47fe996c3364266c43ca850763b478b4d5e | /Module_01.8_BitwiseOperators/Driver.cpp | ee6b2260e637bfb1cb16f88efb679e9d939232c6 | [] | no_license | lorenarms/SNHU_CS_260_Practice_Projects | 9ab49376dc23cfe568d906bacb7c32f189fd4f28 | d3f8e94afbde25c68876842fcfd21dd296bc2dec | refs/heads/master | 2023-09-05T10:10:30.134210 | 2021-11-06T16:33:56 | 2021-11-06T16:33:56 | 402,142,088 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,490 | cpp | Driver.cpp | #include "Driver.h"
#include <iostream>
using namespace std;
// swap two variables without using a temporary variable
void Swap(int &a, int &b)
{
a = a + b;
b = a - b;
a = a - b;
}
// checks a variable using bitwise operator
void CheckIfOddOrEven(int a)
{
if (!(a&1))
{
cout << " is even." << endl;
}
else
{
cout << " is odd." << endl;
}
}
void SwapWithBitwise(int &a, int &b)
{
a ^= b;
b ^= a;
a ^= b;
}
void ConvertCaseBitwise()
{
char word[8] = "sREedEv";
char* wordptr = &word[0];
cout << "Word: " << word << endl;
while (wordptr < &word[7])
{
cout << "UPPERCASE: " << (*wordptr & '_') << endl;
cout << "lowercase: " << (*wordptr | ' ') << endl;
wordptr++;
}
cout << "Word: " << word << endl;
}
void main()
{
int x = 5, y = 6;
cout << "x & y: " << (x & y) << endl; // prints '4'
/*cout << "Before swap: x = " << x << " and y = " << y << endl;
Swap(x, y);
cout << "After swap: x = " << x << " and y = " << y << endl;*/
cout << "x | y: " << (x | y) << endl; // prints '7'
cout << "x ^ y: " << (x ^ y) << endl; // prints '3'
cout << "~x: " << (~x) << endl;
y = 2;
cout << "x << y: " << (x << y) << endl; // prints '20'
cout << "x >> y: " << (x >> y) << endl; // prints '1'
cout << "x";
CheckIfOddOrEven(x);
cout << "y";
CheckIfOddOrEven(y);
cout << "Before swap: x = " << x << " and y = " << y << endl;
SwapWithBitwise(x, y);
cout << "After swap: x = " << x << " and y = " << y << endl;
ConvertCaseBitwise();
}
|
b064923c00e47e2a3176a39c6386c6e145fae9ef | e21dece7e20f1c69f8f9985e308591021ad5ae6a | /country.cpp | 67a76ebde71cc9bceae30e8e831f7ac598d4aa77 | [] | no_license | Damien90154/ProjetLockerControl | 51a41a0f27e488579e2ed2f0a5e650b55128f414 | 753941bd41c25c02b6d90d1bb6f13d98288878ab | refs/heads/master | 2020-05-17T00:21:00.331769 | 2015-05-03T15:32:37 | 2015-05-03T15:32:37 | 34,989,580 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 792 | cpp | country.cpp | #include "country.h"
#include <QApplication>
Country::Country()
{
m_Linguist = new QTranslator();
SetFrench();
}
Country::~Country()
{
delete m_Linguist;
}
void Country::SetFrench()
{
qApp->removeTranslator(m_Linguist);
m_Linguist->load(":/Linguist/french");
qApp->installTranslator(m_Linguist);
}
void Country::SetEnglish()
{
qApp->removeTranslator(m_Linguist);
m_Linguist->load(":/Linguist/english");
qApp->installTranslator(m_Linguist);
}
void Country::SetDeutsch()
{
qApp->removeTranslator(m_Linguist);
m_Linguist->load(":/Linguist/german");
qApp->installTranslator(m_Linguist);
}
void Country::SetEspanol()
{
qApp->removeTranslator(m_Linguist);
m_Linguist->load(":/Linguist/spain");
qApp->installTranslator(m_Linguist);
}
|
0392bc7d10263d280f11f55fc82f89222d3afa3a | 24bdd2e863ab9835240b4014c6b91426f4759876 | /Single_Phase_3D/SINGLE_PHASE_MPI_Software_Spars_2dDrag_force.cpp | 7b64eb9ae666a5d681b02915f8561094c5a68b44 | [] | no_license | DarkOfTheMoon/jianhui-lbm | aaaee6abc03ca38237cc44b9447698c5ce2c4017 | 76d831352c5aa1600389dbdee6a4659c01eb2c65 | refs/heads/master | 2020-05-17T16:40:59.862938 | 2013-11-12T10:00:23 | 2013-11-12T10:00:23 | 42,917,907 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 71,175 | cpp | SINGLE_PHASE_MPI_Software_Spars_2dDrag_force.cpp | #include<iostream>
#include<cmath>
#include<cstdlib>
#include<iomanip>
#include<fstream>
#include<sstream>
#include<string>
#include<math.h>
# include "mpi.h"
#define MAXN 100
#define eps 1e-12
#define zero(x) (fabs(x)<eps)
struct mat{
int n,m;
double data[MAXN][MAXN];
};
//D3Q19 STANDARD LATTICE MRT LATTICE BOLTZMANN METHOD
//UNIFORM MESH, LATTICE VELOCITY 1
using namespace std;
const int Q=19;
double u_max,u_ave,gx,gy,gz,porosity;
//----------
double s_e;
double s_eps;
double s_q;
//----------
double s_v;
double q_p;
int cl,cr;
int EI;
int Count,NX,NY,NZ;
int mirX=0;
int mirY=0;
int mirZ=0;
int mir=0;
double M[19][19]=
{{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{-30,-11,-11,-11,-11,-11,-11,8,8,8,8,8,8,8,8,8,8,8,8},
{12,-4,-4,-4,-4,-4,-4,1,1,1,1,1,1,1,1,1,1,1,1},
{0,1,-1,0,0,0,0,1,-1,1,-1,0,0,0,0,1,-1,1,-1},
{0,-4,4,0,0,0,0,1,-1,1,-1,0,0,0,0,1,-1,1,-1},
{0,0,0,1,-1,0,0,1,1,-1,-1,1,-1,1,-1,0,0,0,0},
{0,0,0,-4,4,0,0,1,1,-1,-1,1,-1,1,-1,0,0,0,0},
{0,0,0,0,0,1,-1,0,0,0,0,1,1,-1,-1,1,1,-1,-1},
{0,0,0,0,0,-4,4,0,0,0,0,1,1,-1,-1,1,1,-1,-1},
{0,2,2,-1,-1,-1,-1,1,1,1,1,-2,-2,-2,-2,1,1,1,1},
{0,-4,-4,2,2,2,2,1,1,1,1,-2,-2,-2,-2,1,1,1,1},
{0,0,0,1,1,-1,-1,1,1,1,1,0,0,0,0,-1,-1,-1,-1},
{0,0,0,-2,-2,2,2,1,1,1,1,0,0,0,0,-1,-1,-1,-1},
{0,0,0,0,0,0,0,1,-1,-1,1,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,1,-1,-1,1,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,-1,-1,1},
{0,0,0,0,0,0,0,1,-1,1,-1,0,0,0,0,-1,1,-1,1},
{0,0,0,0,0,0,0,-1,-1,1,1,1,-1,1,-1,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,-1,-1,1,1,1,1,-1,-1}};
double MI[19][19];
double m[19];
double meq[19];
double uMax,c,Re,dx,dy,Lx,Ly,dt,rho0,P0,tau_f,niu,error,SFx,SFy,reso;
void Read_Rock(int***,double*,char[128]);
void tests();
void init_Sparse(int***,int***,int*, int*);
void init(double*, double**, double**,double*, double*, double*);
void periodic_streaming(double** ,double** ,int* ,int***,int*, int*,double*, double**);
void periodic_streaming_MR(double** ,double** ,int* ,int*** ,int* ,int* ,double* ,double** );
void standard_bounceback_boundary(int,double**);
void collision(double*,double** ,double** ,double*, double* ,double* , int* ,int***);
void comput_macro_variables( double* ,double**,double** ,double** ,double** ,double* , double* , double* ,int* ,int***);
void comput_macro_variables_IMR( double* ,double** ,double** ,double**,double** ,int*,int*** , double* , double*, double*, int ,double ,double* ,double* , double* );
double Error(double** ,double** ,double*, double*);
void boundary_velocity(int,double,int , double ,int ,double ,int ,double ,int ,double ,int ,double ,double** ,double* ,double** ,int*** );
void boundary_pressure(int ,double ,int , double ,int ,double ,int ,double ,int ,double ,int ,double ,double** ,double** ,double* ,int*** );
void output_velocity(int ,double* ,double** ,int ,int ,int ,int ,int*** );
void output_density(int ,double* ,int ,int ,int ,int ,int*** );
void Geometry(int*** );
double Comput_Perm(double** u,double*,int);
double S[19];
void Comput_MI(double[19][19], double[19][19]);
int inverse(mat &a);
double feq(int,double, double[3]);
void Suppliment(int*,int***);
int e[19][3]=
{{0,0,0},{1,0,0,},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1},{1,1,0},{-1,1,0},{1,-1,0},{-1,-1,0},{0,1,1},
{0,-1,1},{0,1,-1},{0,-1,-1},{1,0,1},{-1,0,1},{1,0,-1},{-1,0,-1}};
double w[19]={1.0/3.0,1.0/18.0,1.0/18.0,1.0/18.0,1.0/18.0,1.0/18.0,1.0/18.0,1.0/36.0,1.0/36.0,1.0/36.0,1.0/36.0,1.0/36.0,1.0/36.0,1.0/36.0,1.0/36.0,1.0/36.0,1.0/36.0,1.0/36.0,1.0/36.0};
int LR[19]={0,2,1,4,3,6,5,10,9,8,7,14,13,12,11,18,17,16,15};
int n,nx_l,n_max,in_IMR,PerDir,freRe,freDe,freVe,Par_Geo,Par_nx,Par_ny,Par_nz;
int Zoom;
int wr_per,pre_xp,pre_xn,pre_yp,pre_yn,pre_zp,pre_zn;
int vel_xp,vel_xn,vel_yp,vel_yn,vel_zp,vel_zn;
double in_vis,p_xp,p_xn,p_yp,p_yn,p_zp,p_zn;
double inivx,inivy,inivz,v_xp,v_xn,v_yp,v_yn,v_zp,v_zn;
double error_perm;
char outputfile[128]="./";
int main(int argc , char *argv [])
{
MPI :: Init (argc , argv );
MPI_Status status ;
double start , finish;
int rank = MPI :: COMM_WORLD . Get_rank ();
int para_size=MPI :: COMM_WORLD . Get_size ();
int dif;
MPI_Barrier(MPI_COMM_WORLD);
start = MPI_Wtime();
int NCHAR=128;
char filename[128], dummy[128+1];
int dummyInt;
if (rank==0)
{
ifstream fin(argv[1]);
fin >> filename; fin.getline(dummy, NCHAR);
fin >> NX >> NY >> NZ; fin.getline(dummy, NCHAR);
fin >> n_max; fin.getline(dummy, NCHAR);
fin >> reso; fin.getline(dummy, NCHAR);
fin >> in_IMR; fin.getline(dummy, NCHAR);
fin >> mirX >> mirY >> mirZ; fin.getline(dummy, NCHAR);
fin >> gx >> gy >> gz; fin.getline(dummy, NCHAR);
fin >> pre_xp >> p_xp >> pre_xn >> p_xn; fin.getline(dummy, NCHAR);
fin >> pre_yp >> p_yp >> pre_yn >> p_yn; fin.getline(dummy, NCHAR);
fin >> pre_zp >> p_zp >> pre_zn >> p_zn; fin.getline(dummy, NCHAR);
fin >> vel_xp >> v_xp >> vel_xn >> v_xn; fin.getline(dummy, NCHAR);
fin >> vel_yp >> v_yp >> vel_yn >> v_yn; fin.getline(dummy, NCHAR);
fin >> vel_zp >> v_zp >> vel_zn >> v_zn; fin.getline(dummy, NCHAR);
fin >> in_vis; fin.getline(dummy, NCHAR);
fin >> inivx >> inivy >> inivz; fin.getline(dummy, NCHAR);
fin.getline(dummy, NCHAR);
fin >> wr_per; fin.getline(dummy, NCHAR);
fin >> PerDir; fin.getline(dummy, NCHAR);
fin >> freRe; fin.getline(dummy, NCHAR);
fin >> freVe; fin.getline(dummy, NCHAR);
fin >> freDe; fin.getline(dummy, NCHAR);
fin >> mir; fin.getline(dummy, NCHAR);
fin.getline(dummy, NCHAR);
fin >> Par_Geo >> Par_nx >> Par_ny >> Par_nz; fin.getline(dummy, NCHAR);
fin >> Zoom; fin.getline(dummy, NCHAR);
fin >> outputfile; fin.getline(dummy, NCHAR);
fin >> EI; fin.getline(dummy, NCHAR);
fin >> q_p; fin.getline(dummy, NCHAR);
fin.close();
//cout<<NX<<" asdfa "<<endl;
NX=NX-1;NY=NY-1;NZ=NZ-1;
}
MPI_Bcast(&filename,128,MPI_CHAR,0,MPI_COMM_WORLD);
MPI_Bcast(&mirX,1,MPI_INT,0,MPI_COMM_WORLD);MPI_Bcast(&NX,1,MPI_INT,0,MPI_COMM_WORLD);
MPI_Bcast(&mirY,1,MPI_INT,0,MPI_COMM_WORLD);MPI_Bcast(&NY,1,MPI_INT,0,MPI_COMM_WORLD);
MPI_Bcast(&mirZ,1,MPI_INT,0,MPI_COMM_WORLD);MPI_Bcast(&NZ,1,MPI_INT,0,MPI_COMM_WORLD);
MPI_Bcast(&n_max,1,MPI_INT,0,MPI_COMM_WORLD);MPI_Bcast(&reso,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
MPI_Bcast(&in_IMR,1,MPI_INT,0,MPI_COMM_WORLD);MPI_Bcast(&gx,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
MPI_Bcast(&gy,1,MPI_DOUBLE,0,MPI_COMM_WORLD);MPI_Bcast(&gz,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
MPI_Bcast(&pre_xp,1,MPI_INT,0,MPI_COMM_WORLD);MPI_Bcast(&p_xp,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
MPI_Bcast(&pre_xn,1,MPI_INT,0,MPI_COMM_WORLD);MPI_Bcast(&p_xn,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
MPI_Bcast(&pre_yp,1,MPI_INT,0,MPI_COMM_WORLD);MPI_Bcast(&p_yp,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
MPI_Bcast(&pre_yn,1,MPI_INT,0,MPI_COMM_WORLD);MPI_Bcast(&p_yn,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
MPI_Bcast(&pre_zp,1,MPI_INT,0,MPI_COMM_WORLD);MPI_Bcast(&p_zp,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
MPI_Bcast(&pre_zn,1,MPI_INT,0,MPI_COMM_WORLD);MPI_Bcast(&p_zn,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
MPI_Bcast(&vel_xp,1,MPI_INT,0,MPI_COMM_WORLD);MPI_Bcast(&v_xp,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
MPI_Bcast(&vel_xn,1,MPI_INT,0,MPI_COMM_WORLD);MPI_Bcast(&v_xn,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
MPI_Bcast(&vel_yp,1,MPI_INT,0,MPI_COMM_WORLD);MPI_Bcast(&v_yp,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
MPI_Bcast(&vel_yn,1,MPI_INT,0,MPI_COMM_WORLD);MPI_Bcast(&v_yn,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
MPI_Bcast(&vel_zp,1,MPI_INT,0,MPI_COMM_WORLD);MPI_Bcast(&v_zp,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
MPI_Bcast(&vel_zn,1,MPI_INT,0,MPI_COMM_WORLD);MPI_Bcast(&v_zn,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
MPI_Bcast(&inivx,1,MPI_DOUBLE,0,MPI_COMM_WORLD);MPI_Bcast(&inivy,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
MPI_Bcast(&inivz,1,MPI_DOUBLE,0,MPI_COMM_WORLD);MPI_Bcast(&wr_per,1,MPI_INT,0,MPI_COMM_WORLD);
MPI_Bcast(&PerDir,1,MPI_INT,0,MPI_COMM_WORLD);MPI_Bcast(&freRe,1,MPI_INT,0,MPI_COMM_WORLD);
MPI_Bcast(&freVe,1,MPI_INT,0,MPI_COMM_WORLD);MPI_Bcast(&freDe,1,MPI_INT,0,MPI_COMM_WORLD);
MPI_Bcast(&mir,1,MPI_INT,0,MPI_COMM_WORLD);MPI_Bcast(&in_vis,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
MPI_Bcast(&Zoom,1,MPI_INT,0,MPI_COMM_WORLD);MPI_Bcast(&outputfile,128,MPI_CHAR,0,MPI_COMM_WORLD);
MPI_Bcast(&EI,1,MPI_INT,0,MPI_COMM_WORLD);MPI_Bcast(&q_p,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
int U_max_ref=0;
if (mirX==1)
NX=NX*2+1;
if (mirY==1)
NY=NY*2+1;
if (mirZ==1)
NZ=NZ*2+1;
/*
//*************THIN SOLID BOUNDARY MESH REFINEDMENT**************
if (Zoom>1)
{
NX=(NX)*Zoom;
NY=(NY)*Zoom;
NZ=(NZ)*Zoom;
}
//***************************************************************
*/
if (Zoom>1)
{
NX=(NX+1)*Zoom-1;
NY=(NY+1)*Zoom-1;
NZ=(NZ+1)*Zoom-1;
}
//if (Zoom>1)
// reso=reso/Zoom;
nx_l=(int)((NX+1)/para_size);
dif=(NX+1)-nx_l*para_size;
if (rank>para_size-1-dif)
nx_l+=1;
// if (rank==para_size-1)
// nx_l+=(NX+1)%para_size;
double* Permia;
double* rho;
double** u;
double**f;
double**F;
double**u0;
int* SupInv;
double* forcex;
double* forcey;
double* forcez;
int*** Solids;
int*** Solid;
int* Sl;
int* Sr;
Solid = new int**[nx_l];
Sl = new int[(NY+1)*(NZ+1)];
Sr = new int[(NY+1)*(NZ+1)];
Solids = new int**[(NX+1)/Zoom];
for (int i=0;i<(NX+1)/Zoom;i++)
{
Solids[i] = new int*[(NY+1)/Zoom];
for (int j=0;j<(NY+1)/Zoom;j++)
{
Solids[i][j]= new int[(NZ+1)/Zoom];
}
}
for (int i=0;i<nx_l;i++)
{
Solid[i] = new int*[NY+1];
for (int j=0;j<=NY;j++)
Solid[i][j]= new int[NZ+1];
}
// Count = new int[rank];
// if (!(filename=="NOSOLID"))
Read_Rock(Solids,&porosity,filename);
// else
// {
// for(int i=0;i<=NX;i++)
// for(int j=0;j<=NY;j++)
// for(int k=0;k<=NZ;k++)
// Solids[i][j][k]=0;
// }
init_Sparse(Solids,Solid,Sl,Sr);
for (int i=0;i<(NX+1)/Zoom;i++)
{
for (int j=0;j<(NY+1)/Zoom;j++)
delete [] Solids[i][j];
delete [] Solids[i];
}
delete [] Solids;
//***************************************************
//WARRING: SPARSE MATRIX STARTS FROM INDEX 1 NOT 0!!!
//***************************************************
Permia = new double[3];
rho = new double[Count+1];
forcex = new double[Count+1];
forcey = new double[Count+1];
forcez = new double[Count+1];
u = new double*[Count+1];
f = new double*[Count+1];
F = new double*[Count+1];
u0 = new double*[Count+1];
SupInv = new int[Count+1];
for (int i=0;i<=Count;i++)
{
u[i] = new double[3];
f[i] = new double[19];
u0[i] = new double[3];
F[i] = new double[19];
}
Comput_MI(M,MI);
Suppliment(SupInv,Solid);
MPI_Barrier(MPI_COMM_WORLD);
Geometry(Solid);
init(rho,u,f,forcex,forcey,forcez);
if (rank==0)
cout<<"Porosity= "<<porosity<<endl;
/*
char FileName[128]="Results.txt";
char FileName2[128]="Permeability.txt";
char FileName3[128]="bodyforce.txt";
*/
//========================================================
char FileName[128];strcpy(FileName,outputfile);
char FileName2[128];strcpy(FileName2,outputfile);
char FileName3[128];strcpy(FileName3,outputfile);
strcat(FileName,"Results.txt");
strcat(FileName2,"Permeability.txt");
strcat(FileName3,"bodyforce.txt");
//========================================================
ofstream fins;
fins.open(FileName,ios::trunc);
fins.close();
if (wr_per==1)
{
fins.open(FileName2,ios::trunc);
fins.close();
}
fins.open(FileName3,ios::out);
fins.close();
for(n=0;n<=n_max;n++)
{
//cout<<"@@@@@@@@@@@ "<<n<<endl;
collision(rho,u,f,forcex,forcey,forcez,SupInv,Solid);//cout<<"markcollision"<<endl;
if (EI==0)
{periodic_streaming(f,F,SupInv,Solid,Sl,Sr,rho,u);}//cout<<"mark"<<endl;}
else
periodic_streaming_MR(f,F,SupInv,Solid,Sl,Sr,rho,u);
// if ((1-pre_xp)*(1-pre_xn)*(1-pre_yp)*(1-pre_yn)*(1-pre_zp)*(1-pre_zn)==0)
// boundary_pressure(pre_xp,p_xp,pre_xn,p_xn,pre_yp,p_yp,pre_yn,p_yn,pre_zp,p_zp,pre_zn,p_zn,f,u,rho,Solid);
// if ((1-vel_xp)*(1-vel_xn)*(1-vel_yp)*(1-vel_yn)*(1-vel_zp)*(1-vel_zn)==0)
// boundary_velocity(vel_xp,v_xp,vel_xn,v_xn,vel_yp,v_yp,vel_yn,v_yn,vel_zp,v_zp,vel_zn,v_zn,f,rho,u,Solid);
if (in_IMR==1)
comput_macro_variables_IMR(rho,u,u0,f,F,SupInv,Solid,forcex,forcey,forcez,n,porosity,&gx,&gy,&gz);
else
comput_macro_variables(rho,u,u0,f,F,forcex,forcey,forcez,SupInv,Solid);
if ((1-pre_xp)*(1-pre_xn)*(1-pre_yp)*(1-pre_yn)*(1-pre_zp)*(1-pre_zn)==0)
boundary_pressure(pre_xp,p_xp,pre_xn,p_xn,pre_yp,p_yp,pre_yn,p_yn,pre_zp,p_zp,pre_zn,p_zn,f,u,rho,Solid);
if ((1-vel_xp)*(1-vel_xn)*(1-vel_yp)*(1-vel_yn)*(1-vel_zp)*(1-vel_zn)==0)
boundary_velocity(vel_xp,v_xp,vel_xn,v_xn,vel_yp,v_yp,vel_yn,v_yn,vel_zp,v_zp,vel_zn,v_zn,f,rho,u,Solid);
if(n%freRe==0)
{
error=Error(u,u0,&u_max,&u_ave);if (u_max>=10.0) U_max_ref+=1;
error_perm=Comput_Perm(u,Permia,PerDir);
if (rank==0)
{
finish = MPI_Wtime();
ofstream fin(FileName,ios::app);
fin<<"The"<<n<<"th computation result:"<<endl;
//=============================================================================================
fin<<"The permiability is: "<<Permia[0]*reso*reso*1000<<", "<<Permia[1]*reso*reso*1000<<", "<<Permia[2]*reso*reso*1000<<endl;
fin<<"The relative error of permiability computing is: "<<error_perm<<endl;
//==============================================================================================
//==============================================================================================
Re=u_ave*(NY+1)/(1.0/3.0*(1/s_v-0.5));
fin<<"The Maximum velocity is: "<<setprecision(6)<<u_max<<" Re="<<Re<<endl;
//===============================================================================================
fin<<"The max relative error of velocity is: "
<<setiosflags(ios::scientific)<<error<<endl;
fin<<"Elapsed time is "<< finish-start <<" seconds"<<endl;
fin<<endl;
fin.close();
if (wr_per==1)
{
ofstream finfs(FileName2,ios::app);
switch(PerDir)
{
case 1:
finfs<<Permia[0]*reso*reso*1000<<endl;break;
case 2:
finfs<<Permia[1]*reso*reso*1000<<endl;break;
case 3:
finfs<<Permia[2]*reso*reso*1000<<endl;break;
default:
finfs<<Permia[0]*reso*reso*1000<<endl;break;
}
finfs.close();
}
ofstream finf3(FileName3,ios::app);
finf3<<gx<<endl;
finf3.close();
cout<<"The"<<n<<"th computation result:"<<endl;
//=============================================================================================
cout<<"The permiability is: "<<Permia[0]*reso*reso*1000<<", "<<Permia[1]*reso*reso*1000<<", "<<Permia[2]*reso*reso*1000<<endl;
cout<<"The relative error of permiability computing is: "<<error_perm<<endl;
//==============================================================================================
//==============================================================================================
Re=u_ave*(NY+1)/(1.0/3.0*(1/s_v-0.5));
cout<<"The Maximum velocity is: "<<setprecision(6)<<u_max<<" Re="<<Re<<endl;
//===============================================================================================
cout<<"The max relative error of uv is: "
<<setiosflags(ios::scientific)<<error<<endl;
cout<<"Elapsed time is "<< finish-start <<" seconds"<<endl;
cout<<endl;
}
if ((freDe>=0) and (n%freDe==0))
output_density(n,rho,mirX,mirY,mirZ,mir,Solid);
if ((freVe>=0) and (n%freVe==0))
output_velocity(n,rho,u,mirX,mirY,mirZ,mir,Solid);
if(error!=error) {cout<<"PROGRAM STOP"<<endl;break;};
if(U_max_ref>=5) {cout<<"PROGRAM STOP DUE TO HIGH VELOCITY"<<endl;break;}
}
}
for (int i=0;i<=Count;i++)
{
delete [] u[i];
delete [] u0[i];
delete [] f[i];
delete [] F[i];
}
delete [] f;
delete [] u;
delete [] F;
delete [] u0;
delete [] rho;
delete [] forcex;
delete [] forcey;
delete [] forcez;
delete [] SupInv;
delete [] Sl;
delete [] Sr;
delete [] Permia;
// delete [] Count;
finish = MPI_Wtime();
MPI_Barrier(MPI_COMM_WORLD);
if(rank==0)
{
cout<<"Elapsed time is "<< finish-start <<" seconds"<<endl;
cout<<"Accuracy: "<<MPI_Wtick()<<" Second"<<endl;
ofstream fin(FileName,ios::app);
fin<<"Elapsed time is "<< finish-start <<" seconds"<<endl;
fin<<"Accuracy: "<<MPI_Wtick()<<" Second"<<endl;
}
MPI :: Finalize ();
}
int inverse(mat &a){
double t;
int i,j,k,is[MAXN],js[MAXN];
if(a.n!=a.m) return 0;
for(k=0;k<a.n;k++){
for(t=0,i=k;i<a.n;i++)
for(j=k;j<a.n;j++)
if(fabs(a.data[i][j])>t)
t=fabs(a.data[is[k]=i][js[k]=j]);
if(zero(t)) return 0;
if(is[k]!=k)
for(j=0;j<a.n;j++)
t=a.data[k][j],a.data[k][j]=a.data[is[k]][j],a.data[is[k]][j]=t;
if(js[k]!=k)
for(i=0;i<a.n;i++)
t=a.data[i][k],a.data[i][k]=a.data[i][js[k]],a.data[i][js[k]]=t;
a.data[k][k]=1/a.data[k][k];
for(j=0;j<a.n;j++)
if(j!=k)
a.data[k][j]*=a.data[k][k];
for(i=0;i<a.n;i++)
if(i!=k)
for(j=0;j<a.n;j++)
if(j!=k)
a.data[i][j]-=a.data[i][k]*a.data[k][j];
for(i=0;i<a.n;i++)
if(i!=k)
a.data[i][k]*=-a.data[k][k];
}
for(k=a.n-1;k>=0;k--){
for(j=0;j<a.n;j++)
if(js[k]!=k)
t=a.data[k][j],a.data[k][j]=a.data[js[k]][j],a.data[js[k]][j]=t;
for(i=0;i<a.n;i++)
if(is[k]!=k)
t=a.data[i][k],a.data[i][k]=a.data[i][is[k]],a.data[i][is[k]]=t;
}
return 1;
}
void Comput_MI(double M[19][19], double MI[19][19])
{
double mim[19][19];
mat a;
int i,j;
int n_s=19;
for(int i=0;i<n_s;i++)
for(int j=0;j<n_s;j++)
a.data[i][j]=M[i][j];
a.m=a.n=n_s;
if(inverse(a))
for(int i=0;i<n_s;i++)
for(int j=0;j<n_s;j++)
MI[i][j]=a.data[i][j];
else
puts("NO");
}
void init_Sparse(int*** Solids, int*** Solid,int* Sl,int* Sr)
{
MPI_Status status[4] ;
MPI_Request request[4];
int rank = MPI :: COMM_WORLD . Get_rank ();
int mpi_size=MPI :: COMM_WORLD . Get_size ();
bool mark;
int kk,ip,jp,kp,mean_l,mpi_test,s_c;
mean_l=(int)((NX+1)/mpi_size);
s_c=0;
for (int i=0;i<rank;i++)
if (i<mpi_size-((NX+1)-mean_l*mpi_size))
s_c+=mean_l;
else
s_c+=mean_l+1;
int* Sl_send;
int* Sr_send;
Sl_send = new int[(NY+1)*(NZ+1)];
Sr_send = new int[(NY+1)*(NZ+1)];
Count=1;
//cout<<Solids[3][4][5]<<" @@@@@@@@@@@@@@@@@@"<<endl;
//for(int i=0;i<nx_l;i++)
// for(int j=0;j<=NY;j++)
// for(int k=0;k<=NZ;k++)
// cout<<Solids[int((s_c+i-(s_c+i)%Zoom)/Zoom)][int((j-j%Zoom)/Zoom)][int((k-k%Zoom)/Zoom)]<<endl;
for(int i=0;i<nx_l;i++)
for(int j=0;j<=NY;j++)
for(int k=0;k<=NZ;k++)
{
//cout<<(s_c+i-(s_c+i)%Zoom)/Zoom<<" "<<(j-j%Zoom)/Zoom<<" "<<(k-k%Zoom)/Zoom<<endl;
if (Solids[int((s_c+i-(s_c+i)%Zoom)/Zoom)][int((j-j%Zoom)/Zoom)][int((k-k%Zoom)/Zoom)]==0)
{
Solid[i][j][k]=Count;
Count++;
}
else
Solid[i][j][k]=0;
}
Count-=1;
cl=0;cr=0;
for (int j=0;j<=NY;j++)
for (int k=0;k<=NZ;k++)
{
if (Solid[0][j][k]>0)
{
cl++;
Sl_send[j*(NZ+1)+k]=cl;
}
else
Sl_send[j*(NZ+1)+k]=0;
if (Solid[nx_l-1][j][k]>0)
{
cr++;
Sr_send[j*(NZ+1)+k]=cr;
}
else
Sr_send[j*(NZ+1)+k]=0;
}
if (rank==0)
{
MPI_Isend(Sr_send, (NY+1)*(NZ+1), MPI_INT, rank+1, rank*2+1, MPI_COMM_WORLD,&request[0]);
MPI_Isend(Sl_send, (NY+1)*(NZ+1), MPI_INT, mpi_size-1, rank*2, MPI_COMM_WORLD,&request[1]);
MPI_Irecv(Sr , (NY+1)*(NZ+1), MPI_INT, rank+1, (rank+1)*2, MPI_COMM_WORLD,&request[2]);
MPI_Irecv(Sl, (NY+1)*(NZ+1), MPI_INT, mpi_size-1, (mpi_size-1)*2+1, MPI_COMM_WORLD,&request[3] );
}
else
if (rank==mpi_size-1)
{
MPI_Isend(Sl_send, (NY+1)*(NZ+1), MPI_INT, rank-1, rank*2, MPI_COMM_WORLD,&request[0]);
MPI_Isend(Sr_send, (NY+1)*(NZ+1), MPI_INT, 0, rank*2+1, MPI_COMM_WORLD,&request[1]);
MPI_Irecv(Sl, (NY+1)*(NZ+1), MPI_INT, rank-1, (rank-1)*2+1, MPI_COMM_WORLD,&request[2] );
MPI_Irecv(Sr, (NY+1)*(NZ+1), MPI_INT, 0, 0, MPI_COMM_WORLD,&request[3]);
}
else
{
MPI_Isend(Sl_send, (NY+1)*(NZ+1), MPI_INT, rank-1, rank*2, MPI_COMM_WORLD,&request[0]);
MPI_Isend(Sr_send, (NY+1)*(NZ+1), MPI_INT, rank+1, rank*2+1, MPI_COMM_WORLD,&request[1]);
MPI_Irecv(Sl, (NY+1)*(NZ+1), MPI_INT, rank-1, (rank-1)*2+1, MPI_COMM_WORLD,&request[2]);
MPI_Irecv(Sr, (NY+1)*(NZ+1), MPI_INT, rank+1, (rank+1)*2, MPI_COMM_WORLD,&request[3]);
};
MPI_Waitall(4,request, status);
MPI_Testall(4,request,&mpi_test,status);
delete [] Sl_send;
delete [] Sr_send;
}
void Suppliment(int* SupInv,int*** Solid)
{
int rank = MPI :: COMM_WORLD . Get_rank ();
int mpi_size=MPI :: COMM_WORLD . Get_size ();
for(int i=0;i<nx_l;i++)
for(int j=0;j<=NY;j++)
for(int k=0;k<=NZ;k++)
if (Solid[i][j][k]>0)
SupInv[abs(Solid[i][j][k])]=i*(NY+1)*(NZ+1)+j*(NZ+1)+k;
}
void Read_Rock(int*** Solids,double* porosity,char poreFileName[128])
{
int rank = MPI :: COMM_WORLD . Get_rank ();
int mpi_size=MPI :: COMM_WORLD . Get_size ();
int nx0=NX+1;
int ny0=NY+1;
int nz0=NZ+1;
int nx=NX+1;
int ny=NY+1;
int nz=NZ+1;
int* Solid_Int;
int nx_a,ny_a,nz_a;
if (Zoom>1)
{
nx0=(nx0)/Zoom;
ny0=(ny0)/Zoom;
nz0=(nz0)/Zoom;
nx=(nx)/Zoom;
ny=(ny)/Zoom;
nz=(nz)/Zoom;
}
if (mirX==1)
nx0=(nx0)/2;
if (mirY==1)
ny0=(ny0)/2;
if (mirZ==1)
nz0=(nz0)/2;
double pore;
int i, j, k,ir,jr,kr;
Solid_Int = new int[nx*ny*nz];
if (rank==0)
{
if (Par_Geo==0)
{
nx_a=nx0;
ny_a=ny0;
nz_a=nz0;
}
else
{
nx_a=Par_nx;
ny_a=Par_ny;
nz_a=Par_nz;
}
FILE *ftest;
ifstream fin;
ftest = fopen(poreFileName, "r");
if(ftest == NULL)
{
cout << "\n The pore geometry file (" << poreFileName <<
") does not exist!!!!\n";
cout << " Please check the file\n\n";
exit(0);
}
fclose(ftest);
fin.open(poreFileName);
// Reading pore geometry
for(k=0 ; k<nz_a ; k++)
for(j=0 ; j<ny_a ; j++)
for(i=0 ; i<nx_a ; i++)
{
while(true)
{
fin >> pore;
if( pore == 0.0 || pore == 1.0) break;
}
if ((pore == 0.0) && (i<nx0) && (j<ny0) && (k<nz0)) Solid_Int[i*ny*nz+j*nz+k] = 0;
//else Solid_Int[i][j][k] = 1;
if ((pore == 1.0) && (i<nx0) && (j<ny0) && (k<nz0)) Solid_Int[i*ny*nz+j*nz+k] = 1;
}
fin.close();
// Mirroring the rock
if(mirX==1){
for(i=nx0 ; i<nx ; i++)
for(j=0 ; j<ny ; j++)
for(k=0 ; k<nz ; k++)
Solid_Int[i*ny*nz+j*nz+k] = Solid_Int[(nx-i-1)*ny*nz+j*nz+k];
}
if(mirY==1){
for(j=ny0 ; j<ny ; j++)
for(i=0 ; i<nx ; i++)
for(k=0 ; k<nz ; k++)
Solid_Int[i*ny*nz+j*nz+k] = Solid_Int[i*ny*nz+(ny-j-1)*nz+k];
}
if(mirZ==1){
for(k=nz0 ; k<nz ; k++)
for(j=0 ; j<ny ; j++)
for(i=0 ; i<nx ; i++)
Solid_Int[i*ny*nz+j*nz+k] = Solid_Int[i*ny*nz+j*nz+nz-k-1];
}
//MESH REFINEMENT
//double porosity;
// Calculate Porosity
int nNodes = 0;
for(i=0 ; i<nx*ny*nz ; i++)
if(Solid_Int[i] == 0) nNodes++;
*porosity = (double)nNodes / (nx*ny*nz);
}
MPI_Bcast(Solid_Int,nx*ny*nz,MPI_INT,0,MPI_COMM_WORLD);
cout<<"INPUT FILE READING COMPLETE. THE POROSITY IS: "<<*porosity<<endl;
//cout<<nx<<" "<<ny<<" "<<nz<<" zoom "<<Zoom<<endl;
for (i=0;i<nx;i++)
for (j=0;j<ny;j++)
for (k=0;k<nz;k++)
Solids[i][j][k]=Solid_Int[i*(ny)*(nz)+j*(nz)+k];
//cout<<"asdfasdfasdfasdfa"<<endl;
MPI_Barrier(MPI_COMM_WORLD);
/*
//*************THIN SOLID BOUNDARY MESH REFINEDMENT**************
for (i=0;i<nx;i++)
for (j=0;j<ny;j++)
for (k=0;k<nz;k++)
Solids[i*2][j*2][k*2]=Solid_Int[i*(ny)*(nz)+j*(nz)+k];
cout<<nx<<" "<<ny<<" "<<nz<<endl;
for (k=0;k<nz;k++) //k==2*k
{
for (j=0;j<ny;j++) //j=2*j
for(i=0;i<nx-1;i++)
{
ir=2*i+1;jr=2*j;kr=2*k;
if ((Solids[ir-1][jr][kr]==1) and (Solids[ir+1][jr][kr]==1))
Solids[ir][jr][kr]=1;
else
Solids[ir][jr][kr]=0;
}
for (i=0;i<nx;i++)
for (j=0;j<ny-1;j++)
{
ir=2*i;jr=2*j+1;kr=k*2;
if ((Solids[ir][jr-1][kr]==1) and (Solids[ir][jr+1][kr]==1))
Solids[ir][jr][kr]=1;
else
Solids[ir][jr][kr]=0;
}
}
//cout<<"@@@@@@@@@@@@@"<<endl;
for (k=0;k<nz-1;k++)
{
for (i=0;i<=NX;i++)
for (j=0;j<=NY;j++)
{
kr=2*k+1;
if ((Solids[i][j][kr-1]==1) and (Solids[i][j][kr+1]==1))
Solids[i][j][kr]=1;
else
Solids[i][j][kr]=0;
}
}
//******************************************************************************
*/
/*
for (i=0;i<nx;i++)
for (j=0;j<(ny);j++)
for (k=0;k<(nz);k++)
for (int iz=0;iz<=Zoom-1;iz++)
for (int jz=0;jz<=Zoom-1;jz++)
for (int kz=0;kz<=Zoom-1;kz++)
Solids[Zoom*i+iz][Zoom*j+jz][Zoom*k+kz]=Solid_Int[i*(ny)*(nz)+j*(nz)+k];
}
*/
delete [] Solid_Int;
}
void init(double* rho, double** u, double** f,double* forcex,double* forcey, double* forcez)
{
double Cylinder_r=7;
double usqr,vsqr;
rho0=1.0;dt=1.0/Zoom;dx=1.0/Zoom;
uMax=0.0;
Re=50.0;
//forcex=gx;forcey=gy;
//niu=U*Lx/Re;
niu=uMax*Cylinder_r*2/Re;
niu=in_vis;
tau_f=3.0*niu/dt+0.5;
//gx=3*uMax*niu/((NY/2)*(NY/2));
//tau_f=1.0;
s_v=1/tau_f;
//tau_f=1.0;
//cout<<"tau_f= "<<tau_f<<endl;
double pr; //raduis of the obstacles
//if (Zoom>1)
//s_v=1.0/((1.0/s_v-0.5)/Zoom+0.5);
//srand(time(0)); //RANDOM NUMBER GENERATION SEED
//cylinder_creation(50,103,Cylinder_r);
double s_other=8*(2-s_v)/(8-s_v);
double u_tmp[3];
/*
S[0]=s_v;
S[1]=s_v;
S[2]=s_v;
S[3]=s_v;
S[4]=s_v;
S[5]=s_v;
S[6]=s_v;
S[7]=s_v;
S[8]=s_v;
S[9]=s_v;
S[10]=s_v;
S[11]=s_v;
S[12]=s_v;
S[13]=s_v;
S[14]=s_v;
S[15]=s_v;
S[16]=1;
S[17]=1;
S[18]=1;
*/
S[0]=0;
S[1]=s_v;
S[2]=s_v;
S[3]=0;
S[4]=s_other;
S[5]=0;
S[6]=s_other;
S[7]=0;
S[8]=s_other;
S[9]=s_v;
S[10]=s_v;
S[11]=s_v;
S[12]=s_v;
S[13]=s_v;
S[14]=s_v;
S[15]=s_v;
S[16]=s_other;
S[17]=s_other;
S[18]=s_other;
// for(int i=0;i<=NX;i++)
// for(int j=0;j<=NY;j++)
// for(int k=0;k<=NZ;k++)
//
// Solid[i][j][k]=0;
for (int i=1;i<=Count;i++)
{
u[i][0]=inivx;
u[i][1]=inivy;
u[i][2]=inivz;
u_tmp[0]=u[i][0];
u_tmp[1]=u[i][1];
u_tmp[2]=u[i][2];
rho[i]=1.0;
//***********************************************************************
forcex[i]=gx;
forcey[i]=gy;
forcez[i]=gz;
//***********************************************************************
//INITIALIZATION OF m and f
for (int lm=0;lm<19;lm++)
//if (Solid[(int)(SupInv[i]/((NY+1)*(NZ+1)))][(int)((SupInv[i]%((NY+1)*(NZ+1)))/(NZ+1))][SupInv[i]%(NZ+1)]<0)
// f[i][lm]=0.0;
//else
f[i][lm]=feq(lm,rho[i],u_tmp);
}
}
double feq(int k,double rho, double u[3])
{
double eu,uv,feq;
double c2,c4;
double c=1;
c2=c*c;c4=c2*c2;
eu=(e[k][0]*u[0]+e[k][1]*u[1]+e[k][2]*u[2]);
uv=(u[0]*u[0]+u[1]*u[1]+u[2]*u[2]);// WITH FORCE TERM:GRAVITY IN X DIRECTION
feq=w[k]*rho*(1.0+3.0*eu/c2+4.5*eu*eu/c4-1.5*uv/c2);
return feq;
}
void periodic_streaming_MR(double** f,double** F,int* SupInv,int*** Solid,int* Sl,int* Sr,double* rho,double** u)
{
MPI_Status status[4] ;
MPI_Request request[4];
int rank = MPI :: COMM_WORLD . Get_rank ();
int mpi_size=MPI :: COMM_WORLD . Get_size ();
int ip,jp,kp,in,jn,kn,i,j,k,mpi_test;
double rho_ls,v_ls[3],v_ls2[3];
double qprim=(1-2*q_p)*1.2;
int* Gcl = new int[mpi_size];
int* Gcr = new int[mpi_size];
MPI_Gather(&cl,1,MPI_INT,Gcl,1,MPI_INT,0,MPI_COMM_WORLD);
MPI_Bcast(Gcl,mpi_size,MPI_INT,0,MPI_COMM_WORLD);
MPI_Gather(&cr,1,MPI_INT,Gcr,1,MPI_INT,0,MPI_COMM_WORLD);
MPI_Bcast(Gcr,mpi_size,MPI_INT,0,MPI_COMM_WORLD);
double* recvl,*recvl_rho,*recvl_u,*sendl_rho,*sendl_u;
double* recvr,*recvr_rho,*recvr_u,*sendr_rho,*sendr_u;
double* sendl = new double[Gcl[rank]*19];
double* sendr = new double[Gcr[rank]*19];
for(k=0;k<19;k++)
{
for(i=1;i<=Gcl[rank];i++)
sendl[(i-1)*19+k]=f[i][k];
for(j=Count-Gcr[rank]+1;j<=Count;j++)
sendr[(j-(Count-Gcr[rank]+1))*19+k]=f[j][k];
}
if (rank==0)
{
recvl = new double[Gcr[mpi_size-1]*19];
recvr = new double[Gcl[rank+1]*19];
}
else
if (rank==mpi_size-1)
{
recvl = new double[Gcr[rank-1]*19];
recvr = new double[Gcl[0]*19];
}
else
{
recvl = new double[Gcr[rank-1]*19];
recvr = new double[Gcl[rank+1]*19];
}
if (q_p<0.5)
{
sendl_rho = new double[Gcl[rank]];
sendr_rho = new double[Gcr[rank]];
sendl_u = new double[Gcl[rank]*3];
sendr_u = new double[Gcr[rank]*3];
for(k=0;k<3;k++)
{
for(i=1;i<=Gcl[rank];i++)
sendl_u[(i-1)*3+k]=u[i][k];
for(j=Count-Gcr[rank]+1;j<=Count;j++)
sendr_u[(j-(Count-Gcr[rank]+1))*3+k]=u[j][k];
}
for(i=1;i<=Gcl[rank];i++)
sendl_rho[(i-1)]=rho[i];
for(j=Count-Gcr[rank]+1;j<=Count;j++)
sendr_rho[(j-(Count-Gcr[rank]+1))]=rho[j];
if (rank==0)
{
recvl_rho = new double[Gcr[mpi_size-1]];
recvr_rho = new double[Gcl[rank+1]];
recvl_u = new double[Gcr[mpi_size-1]*3];
recvr_u = new double[Gcl[rank+1]*3];
}
else
if (rank==mpi_size-1)
{
recvl_rho = new double[Gcr[rank-1]];
recvr_rho = new double[Gcl[0]];
recvl_u = new double[Gcr[rank-1]*3];
recvr_u = new double[Gcl[0]*3];
}
else
{
recvl_rho = new double[Gcr[rank-1]];
recvr_rho = new double[Gcl[rank+1]];
recvl_u = new double[Gcr[rank-1]*3];
recvr_u = new double[Gcl[rank+1]*3];
}
}
MPI_Barrier(MPI_COMM_WORLD);
if (rank==0)
{
MPI_Isend(sendr, Gcr[0]*19, MPI_DOUBLE, rank+1, rank*2+1, MPI_COMM_WORLD,&request[0]);
MPI_Isend(sendl, Gcl[0]*19, MPI_DOUBLE, mpi_size-1, rank*2, MPI_COMM_WORLD,&request[1]);
MPI_Irecv(recvr , Gcl[1]*19, MPI_DOUBLE, rank+1, (rank+1)*2, MPI_COMM_WORLD,&request[2]);
MPI_Irecv(recvl, Gcr[mpi_size-1]*19, MPI_DOUBLE, mpi_size-1, (mpi_size-1)*2+1, MPI_COMM_WORLD,&request[3] );
}
else
if (rank==mpi_size-1)
{
MPI_Isend(sendl, Gcl[rank]*19, MPI_DOUBLE, rank-1, rank*2, MPI_COMM_WORLD,&request[0]);
MPI_Isend(sendr, Gcr[rank]*19, MPI_DOUBLE, 0, rank*2+1, MPI_COMM_WORLD,&request[1]);
MPI_Irecv(recvl, Gcr[rank-1]*19, MPI_DOUBLE, rank-1, (rank-1)*2+1, MPI_COMM_WORLD,&request[2] );
MPI_Irecv(recvr, Gcl[0]*19, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD,&request[3]);
}
else
{
MPI_Isend(sendl, Gcl[rank]*19, MPI_DOUBLE, rank-1, rank*2, MPI_COMM_WORLD,&request[0]);
MPI_Isend(sendr, Gcr[rank]*19, MPI_DOUBLE, rank+1, rank*2+1, MPI_COMM_WORLD,&request[1]);
MPI_Irecv(recvl, Gcr[rank-1]*19, MPI_DOUBLE, rank-1, (rank-1)*2+1, MPI_COMM_WORLD,&request[2]);
MPI_Irecv(recvr, Gcl[rank+1]*19, MPI_DOUBLE, rank+1, (rank+1)*2, MPI_COMM_WORLD,&request[3]);
};
MPI_Waitall(4,request, status);
MPI_Testall(4,request,&mpi_test,status);
delete [] sendl;
delete [] sendr;
if (q_p<0.5)
{
if (rank==0)
{
MPI_Isend(sendr_rho, Gcr[0], MPI_DOUBLE, rank+1, rank*2+1, MPI_COMM_WORLD,&request[0]);
MPI_Isend(sendl_rho, Gcl[0], MPI_DOUBLE, mpi_size-1, rank*2, MPI_COMM_WORLD,&request[1]);
MPI_Irecv(recvr_rho , Gcl[1], MPI_DOUBLE, rank+1, (rank+1)*2, MPI_COMM_WORLD,&request[2]);
MPI_Irecv(recvl_rho, Gcr[mpi_size-1], MPI_DOUBLE, mpi_size-1, (mpi_size-1)*2+1, MPI_COMM_WORLD,&request[3] );
}
else
if (rank==mpi_size-1)
{
MPI_Isend(sendl_rho, Gcl[rank], MPI_DOUBLE, rank-1, rank*2, MPI_COMM_WORLD,&request[0]);
MPI_Isend(sendr_rho, Gcr[rank], MPI_DOUBLE, 0, rank*2+1, MPI_COMM_WORLD,&request[1]);
MPI_Irecv(recvl_rho, Gcr[rank-1], MPI_DOUBLE, rank-1, (rank-1)*2+1, MPI_COMM_WORLD,&request[2] );
MPI_Irecv(recvr_rho, Gcl[0], MPI_DOUBLE, 0, 0, MPI_COMM_WORLD,&request[3]);
}
else
{
MPI_Isend(sendl_rho, Gcl[rank], MPI_DOUBLE, rank-1, rank*2, MPI_COMM_WORLD,&request[0]);
MPI_Isend(sendr_rho, Gcr[rank], MPI_DOUBLE, rank+1, rank*2+1, MPI_COMM_WORLD,&request[1]);
MPI_Irecv(recvl_rho, Gcr[rank-1], MPI_DOUBLE, rank-1, (rank-1)*2+1, MPI_COMM_WORLD,&request[2]);
MPI_Irecv(recvr_rho, Gcl[rank+1], MPI_DOUBLE, rank+1, (rank+1)*2, MPI_COMM_WORLD,&request[3]);
};
MPI_Waitall(4,request, status);
MPI_Testall(4,request,&mpi_test,status);
delete [] sendl_rho;
delete [] sendr_rho;
if (rank==0)
{
MPI_Isend(sendr_u, Gcr[0]*3, MPI_DOUBLE, rank+1, rank*2+1, MPI_COMM_WORLD,&request[0]);
MPI_Isend(sendl_u, Gcl[0]*3, MPI_DOUBLE, mpi_size-1, rank*2, MPI_COMM_WORLD,&request[1]);
MPI_Irecv(recvr_u , Gcl[1]*3, MPI_DOUBLE, rank+1, (rank+1)*2, MPI_COMM_WORLD,&request[2]);
MPI_Irecv(recvl_u, Gcr[mpi_size-1]*3, MPI_DOUBLE, mpi_size-1, (mpi_size-1)*2+1, MPI_COMM_WORLD,&request[3] );
}
else
if (rank==mpi_size-1)
{
MPI_Isend(sendl_u, Gcl[rank]*3, MPI_DOUBLE, rank-1, rank*2, MPI_COMM_WORLD,&request[0]);
MPI_Isend(sendr_u, Gcr[rank]*3, MPI_DOUBLE, 0, rank*2+1, MPI_COMM_WORLD,&request[1]);
MPI_Irecv(recvl_u, Gcr[rank-1]*3, MPI_DOUBLE, rank-1, (rank-1)*2+1, MPI_COMM_WORLD,&request[2] );
MPI_Irecv(recvr_u, Gcl[0]*3, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD,&request[3]);
}
else
{
MPI_Isend(sendl_u, Gcl[rank]*3, MPI_DOUBLE, rank-1, rank*2, MPI_COMM_WORLD,&request[0]);
MPI_Isend(sendr_u, Gcr[rank]*3, MPI_DOUBLE, rank+1, rank*2+1, MPI_COMM_WORLD,&request[1]);
MPI_Irecv(recvl_u, Gcr[rank-1]*3, MPI_DOUBLE, rank-1, (rank-1)*2+1, MPI_COMM_WORLD,&request[2]);
MPI_Irecv(recvr_u, Gcl[rank+1]*3, MPI_DOUBLE, rank+1, (rank+1)*2, MPI_COMM_WORLD,&request[3]);
};
MPI_Waitall(4,request, status);
MPI_Testall(4,request,&mpi_test,status);
delete [] sendl_u;
delete [] sendr_u;
}
if (q_p>=0.5)
{
for(int ci=1;ci<=Count;ci++)
{
i=(int)(SupInv[ci]/((NY+1)*(NZ+1)));
j=(int)((SupInv[ci]%((NY+1)*(NZ+1)))/(NZ+1));
k=(int)(SupInv[ci]%(NZ+1));
for(int lm=0;lm<19;lm++)
{
ip=i-e[lm][0];
jp=j-e[lm][1];if (jp<0) {jp=NY;}; if (jp>NY) {jp=0;};
kp=k-e[lm][2];if (kp<0) {kp=NZ;}; if (kp>NZ) {kp=0;};
if (ip<0)
{
if (Sl[jp*(NZ+1)+kp]>0)
F[ci][lm]=recvl[(Sl[jp*(NZ+1)+kp]-1)*19+lm];
else
{
v_ls[0]=u[ci][0];
v_ls[1]=u[ci][1];
v_ls[2]=u[ci][2];
F[ci][lm]=f[ci][LR[lm]]-feq(LR[lm],rho[ci],v_ls)+(2*q_p-1)/q_p*w[LR[lm]]+(1-q_p)/q_p*feq(LR[lm],rho[ci],v_ls);
//F[ci][lm]=f[ci][LR[lm]];
//cout<<i<<" "<<j<<" "<<k<<endl;
}
}
if (ip>=nx_l)
{
if (Sr[jp*(NZ+1)+kp]>0)
F[ci][lm]=recvr[(Sr[jp*(NZ+1)+kp]-1)*19+lm];
else
{
v_ls[0]=u[ci][0];
v_ls[1]=u[ci][1];
v_ls[2]=u[ci][2];
F[ci][lm]=f[ci][LR[lm]]-feq(LR[lm],rho[ci],v_ls)+(2*q_p-1)/q_p*w[LR[lm]]+(1-q_p)/q_p*feq(LR[lm],rho[ci],v_ls);
//F[ci][lm]=f[ci][LR[lm]];
}
}
if ((ip>=0) and (ip<nx_l))
{
if (Solid[ip][jp][kp]>0)
F[ci][lm]=f[abs(Solid[ip][jp][kp])][lm];
else
{
v_ls[0]=u[ci][0];
v_ls[1]=u[ci][1];
v_ls[2]=u[ci][2];
F[ci][lm]=f[ci][LR[lm]]-feq(LR[lm],rho[ci],v_ls)+(2*q_p-1)/q_p*w[LR[lm]]+(1-q_p)/q_p*feq(LR[lm],rho[ci],v_ls);
//F[ci][lm]=f[ci][LR[lm]];
}
}
}
}
}
else
for(int ci=1;ci<=Count;ci++)
{
i=(int)(SupInv[ci]/((NY+1)*(NZ+1)));
j=(int)((SupInv[ci]%((NY+1)*(NZ+1)))/(NZ+1));
k=(int)(SupInv[ci]%(NZ+1));
if ((i>=1) and (i<nx_l-1))
{
for(int lm=0;lm<19;lm++)
{
ip=i-e[lm][0];
jp=j-e[lm][1];if (jp<0) {jp=NY;}; if (jp>NY) {jp=0;};
kp=k-e[lm][2];if (kp<0) {kp=NZ;}; if (kp>NZ) {kp=0;};
in=i+e[lm][0];
jn=j+e[lm][1];if (jn<0) {jn=NY;}; if (jn>NY) {jn=0;};
kn=k+e[lm][2];if (kn<0) {kn=NZ;}; if (kn>NZ) {kn=0;};
if (Solid[ip][jp][kp]>0)
F[ci][lm]=f[abs(Solid[ip][jp][kp])][lm];
else
{
v_ls[0]=u[ci][0];
v_ls[1]=u[ci][1];
v_ls[2]=u[ci][2];
if (Solid[in][jn][kn]>0)
F[ci][lm]=f[ci][LR[lm]]-feq(LR[lm],rho[ci],v_ls)+(1-2*q_p)*feq(LR[lm],rho[Solid[in][jn][kn]],u[Solid[in][jn][kn]])+2*q_p*feq(LR[lm],rho[ci],v_ls);
else
F[ci][lm]=(qprim+2*q_p-1)/qprim*(feq(LR[lm],rho[ci],v_ls))+(1-2*q_p)/qprim*w[LR[lm]];
}
}
}
else
for(int lm=0;lm<19;lm++)
{
ip=i-e[lm][0];
jp=j-e[lm][1];if (jp<0) {jp=NY;}; if (jp>NY) {jp=0;};
kp=k-e[lm][2];if (kp<0) {kp=NZ;}; if (kp>NZ) {kp=0;};
in=i+e[lm][0];
jn=j+e[lm][1];if (jn<0) {jn=NY;}; if (jn>NY) {jn=0;};
kn=k+e[lm][2];if (kn<0) {kn=NZ;}; if (kn>NZ) {kn=0;};
if (i==0)
{
if (ip<0)
{
if (Sl[jp*(NZ+1)+kp]>0)
F[ci][lm]=recvl[(Sl[jp*(NZ+1)+kp]-1)*19+lm];
else
{
v_ls[0]=u[ci][0];v_ls2[0]=u[Solid[in][jn][kn]][0];
v_ls[1]=u[ci][1];v_ls2[1]=u[Solid[in][jn][kn]][1];
v_ls[2]=u[ci][2];v_ls2[2]=u[Solid[in][jn][kn]][2];
if (Solid[in][jn][kn]>0)
F[ci][lm]=f[ci][LR[lm]]-feq(LR[lm],rho[ci],v_ls)+(1-2*q_p)*feq(LR[lm],rho[Solid[in][jn][kn]],v_ls2)+2*q_p*feq(LR[lm],rho[ci],v_ls);
else
F[ci][lm]=(qprim+2*q_p-1)/qprim*(feq(LR[lm],rho[ci],v_ls))+(1-2*q_p)/qprim*w[LR[lm]];
}
}
if (in<0)
{
if (Solid[ip][jp][kp]>0)
F[ci][lm]=f[abs(Solid[ip][jp][kp])][lm];
else
{
v_ls[0]=u[ci][0];v_ls2[0]=recvl_u[(Sl[jn*(NZ+1)+kn]-1)*3];
v_ls[1]=u[ci][1];v_ls2[1]=recvl_u[(Sl[jn*(NZ+1)+kn]-1)*3+1];
v_ls[2]=u[ci][2];v_ls2[2]=recvl_u[(Sl[jn*(NZ+1)+kn]-1)*3+2];
if (Sl[jn*(NZ+1)+kn]>0)
F[ci][lm]=f[ci][LR[lm]]-feq(LR[lm],rho[ci],v_ls)+(1-2*q_p)*feq(LR[lm],recvl_rho[Sl[jn*(NZ+1)+kn]-1],v_ls2)+2*q_p*feq(LR[lm],rho[ci],v_ls);
else
F[ci][lm]=(qprim+2*q_p-1)/qprim*(feq(LR[lm],rho[ci],v_ls))+(1-2*q_p)/qprim*w[LR[lm]];
}
}
if ((ip>=0) and (in>=0))
{
if (Solid[ip][jp][kp]>0)
F[ci][lm]=f[abs(Solid[ip][jp][kp])][lm];
else
{
v_ls[0]=u[ci][0];v_ls2[0]=u[Solid[in][jn][kn]][0];
v_ls[1]=u[ci][1];v_ls2[1]=u[Solid[in][jn][kn]][1];
v_ls[2]=u[ci][2];v_ls2[2]=u[Solid[in][jn][kn]][2];
if (Solid[in][jn][kn]>0)
F[ci][lm]=f[ci][LR[lm]]-feq(LR[lm],rho[ci],v_ls)+(1-2*q_p)*feq(LR[lm],rho[Solid[in][jn][kn]],v_ls2)+2*q_p*feq(LR[lm],rho[ci],v_ls);
else
F[ci][lm]=(qprim+2*q_p-1)/qprim*(feq(LR[lm],rho[ci],v_ls))+(1-2*q_p)/qprim*w[LR[lm]];
}
}
}
if (i==nx_l-1)
{
if (ip>=nx_l)
{
if (Sr[jp*(NZ+1)+kp]>0)
F[ci][lm]=recvr[(Sr[jp*(NZ+1)+kp]-1)*19+lm];
else
{
v_ls[0]=u[ci][0];v_ls2[0]=u[Solid[in][jn][kn]][0];
v_ls[1]=u[ci][1];v_ls2[1]=u[Solid[in][jn][kn]][1];
v_ls[2]=u[ci][2];v_ls2[2]=u[Solid[in][jn][kn]][2];
if (Solid[in][jn][kn]>0)
F[ci][lm]=f[ci][LR[lm]]-feq(LR[lm],rho[ci],v_ls)+(1-2*q_p)*feq(LR[lm],rho[Solid[in][jn][kn]],v_ls2)+2*q_p*feq(LR[lm],rho[ci],v_ls);
else
F[ci][lm]=(qprim+2*q_p-1)/qprim*(feq(LR[lm],rho[ci],v_ls))+(1-2*q_p)/qprim*w[LR[lm]];
}
}
if (in>=nx_l)
{
if (Solid[ip][jp][kp]>0)
F[ci][lm]=f[abs(Solid[ip][jp][kp])][lm];
else
{
v_ls[0]=u[ci][0];v_ls2[0]=recvr_u[(Sr[jn*(NZ+1)+kn]-1)*3];
v_ls[1]=u[ci][1];v_ls2[1]=recvr_u[(Sr[jn*(NZ+1)+kn]-1)*3+1];
v_ls[2]=u[ci][2];v_ls2[2]=recvr_u[(Sr[jn*(NZ+1)+kn]-1)*3+2];
if (Sr[jn*(NZ+1)+kn]>0)
F[ci][lm]=f[ci][LR[lm]]-feq(LR[lm],rho[ci],v_ls)+(1-2*q_p)*feq(LR[lm],recvr_rho[Sr[jn*(NZ+1)+kn]-1],v_ls2)+2*q_p*feq(LR[lm],rho[ci],v_ls);
else
F[ci][lm]=(qprim+2*q_p-1)/qprim*(feq(LR[lm],rho[ci],v_ls))+(1-2*q_p)/qprim*w[LR[lm]];
}
}
if ((ip<nx_l) and (in<nx_l))
{
if (Solid[ip][jp][kp]>0)
F[ci][lm]=f[abs(Solid[ip][jp][kp])][lm];
else
{
v_ls[0]=u[ci][0];v_ls2[0]=u[Solid[in][jn][kn]][0];
v_ls[1]=u[ci][1];v_ls2[1]=u[Solid[in][jn][kn]][1];
v_ls[2]=u[ci][2];v_ls2[2]=u[Solid[in][jn][kn]][2];
if (Solid[in][jn][kn]>0)
F[ci][lm]=f[ci][LR[lm]]-feq(LR[lm],rho[ci],v_ls)+(1-2*q_p)*feq(LR[lm],rho[Solid[in][jn][kn]],v_ls2)+2*q_p*feq(LR[lm],rho[ci],v_ls);
else
F[ci][lm]=(qprim+2*q_p-1)/qprim*(feq(LR[lm],rho[ci],v_ls))+(1-2*q_p)/qprim*w[LR[lm]];
}
}
}
}
}
//for(int ci=1;ci<=Count;ci++)
// for(int lm=0;lm<19;lm++)
// f[ci][lm]=F[ci][lm];
delete [] Gcl;
delete [] Gcr;
delete [] recvl;
delete [] recvr;
if (q_p<0.5)
{
delete [] recvl_rho;
delete [] recvl_u;
delete [] recvr_rho;
delete [] recvr_u;
}
}
void periodic_streaming(double** f,double** F,int* SupInv,int*** Solid,int* Sl,int* Sr,double* rho,double** u)
{
MPI_Status status[4] ;
MPI_Request request[4];
//cout<<"@@@@@@@@@@@ "<<n<<endl;
int rank = MPI :: COMM_WORLD . Get_rank ();
int mpi_size=MPI :: COMM_WORLD . Get_size ();
int ip,jp,kp,i,j,k,mpi_test;
double rho_ls,v_ls[3];
int* Gcl = new int[mpi_size];
int* Gcr = new int[mpi_size];
MPI_Gather(&cl,1,MPI_INT,Gcl,1,MPI_INT,0,MPI_COMM_WORLD);
MPI_Bcast(Gcl,mpi_size,MPI_INT,0,MPI_COMM_WORLD);
MPI_Gather(&cr,1,MPI_INT,Gcr,1,MPI_INT,0,MPI_COMM_WORLD);
MPI_Bcast(Gcr,mpi_size,MPI_INT,0,MPI_COMM_WORLD);
double* recvl;
double* recvr;
double* sendl = new double[Gcl[rank]*19];
double* sendr = new double[Gcr[rank]*19];
for(k=0;k<19;k++)
{
for(i=1;i<=Gcl[rank];i++)
sendl[(i-1)*19+k]=f[i][k];
for(j=Count-Gcr[rank]+1;j<=Count;j++)
sendr[(j-(Count-Gcr[rank]+1))*19+k]=f[j][k];
}
if (rank==0)
{
recvl = new double[Gcr[mpi_size-1]*19];
recvr = new double[Gcl[rank+1]*19];
}
else
if (rank==mpi_size-1)
{
recvl = new double[Gcr[rank-1]*19];
recvr = new double[Gcl[0]*19];
}
else
{
recvl = new double[Gcr[rank-1]*19];
recvr = new double[Gcl[rank+1]*19];
}
MPI_Barrier(MPI_COMM_WORLD);
//cout<<"@@@@@@@@@@@ "<<n<<endl;
if (rank==0)
{
MPI_Isend(sendr, Gcr[0]*19, MPI_DOUBLE, rank+1, rank*2+1, MPI_COMM_WORLD,&request[0]);
MPI_Isend(sendl, Gcl[0]*19, MPI_DOUBLE, mpi_size-1, rank*2, MPI_COMM_WORLD,&request[1]);
MPI_Irecv(recvr , Gcl[1]*19, MPI_DOUBLE, rank+1, (rank+1)*2, MPI_COMM_WORLD,&request[2]);
MPI_Irecv(recvl, Gcr[mpi_size-1]*19, MPI_DOUBLE, mpi_size-1, (mpi_size-1)*2+1, MPI_COMM_WORLD,&request[3] );
}
else
if (rank==mpi_size-1)
{
MPI_Isend(sendl, Gcl[rank]*19, MPI_DOUBLE, rank-1, rank*2, MPI_COMM_WORLD,&request[0]);
MPI_Isend(sendr, Gcr[rank]*19, MPI_DOUBLE, 0, rank*2+1, MPI_COMM_WORLD,&request[1]);
MPI_Irecv(recvl, Gcr[rank-1]*19, MPI_DOUBLE, rank-1, (rank-1)*2+1, MPI_COMM_WORLD,&request[2] );
MPI_Irecv(recvr, Gcl[0]*19, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD,&request[3]);
}
else
{
MPI_Isend(sendl, Gcl[rank]*19, MPI_DOUBLE, rank-1, rank*2, MPI_COMM_WORLD,&request[0]);
MPI_Isend(sendr, Gcr[rank]*19, MPI_DOUBLE, rank+1, rank*2+1, MPI_COMM_WORLD,&request[1]);
MPI_Irecv(recvl, Gcr[rank-1]*19, MPI_DOUBLE, rank-1, (rank-1)*2+1, MPI_COMM_WORLD,&request[2]);
MPI_Irecv(recvr, Gcl[rank+1]*19, MPI_DOUBLE, rank+1, (rank+1)*2, MPI_COMM_WORLD,&request[3]);
};
MPI_Waitall(4,request, status);
MPI_Testall(4,request,&mpi_test,status);
//cout<<"@@@@@@@@@@@ "<<n<<endl;
for(int ci=1;ci<=Count;ci++)
{
i=(int)(SupInv[ci]/((NY+1)*(NZ+1)));
j=(int)((SupInv[ci]%((NY+1)*(NZ+1)))/(NZ+1));
k=(int)(SupInv[ci]%(NZ+1));
for(int lm=0;lm<19;lm++)
{
ip=i-e[lm][0];
jp=j-e[lm][1];if (jp<0) {jp=NY;}; if (jp>NY) {jp=0;};
kp=k-e[lm][2];if (kp<0) {kp=NZ;}; if (kp>NZ) {kp=0;};
if (ip<0)
if (Sl[jp*(NZ+1)+kp]>0)
F[ci][lm]=recvl[(Sl[jp*(NZ+1)+kp]-1)*19+lm];
else
F[ci][lm]=f[ci][LR[lm]];
if (ip>=nx_l)
if (Sr[jp*(NZ+1)+kp]>0)
F[ci][lm]=recvr[(Sr[jp*(NZ+1)+kp]-1)*19+lm];
else
F[ci][lm]=f[ci][LR[lm]];
if ((ip>=0) and (ip<nx_l))
if (Solid[ip][jp][kp]>0)
F[ci][lm]=f[Solid[ip][jp][kp]][lm];
else
F[ci][lm]=f[ci][LR[lm]];
}
}
/*
double sum=0;
for(int ci=1;ci<=Count;ci++)
{
for(int lm=0;lm<19;lm++)
{f[ci][lm]=F[ci][lm];sum+=F[ci][lm];}
cout<<sum<<endl;sum=0;
}
*/
delete [] Gcl;
delete [] Gcr;
delete [] sendl;
delete [] sendr;
delete [] recvl;
delete [] recvr;
}
void collision(double* rho,double** u,double** f,double* forcex, double* forcey, double* forcez, int* SupInv,int*** Solid)
{
double lm0,lm1;
double usqr,vsqr;
double F_hat[19],GuoF[19],f_eq[19],u_tmp[3];
double m_l[19];
for(int i=1;i<=Count;i++)
{
forcex[i]=gx-(8*niu/(10*10))*u[i][0];
forcey[i]=gy-(8*niu/(10*10))*u[i][1];
forcez[i]=gz-(8*niu/(10*10))*u[i][2];
//=================FORCE TERM_GUO=========================================
for (int k=0;k<19;k++)
{
lm0=((e[k][0]-u[i][0])*forcex[i]+(e[k][1]-u[i][1])*forcey[i]+(e[k][2]-u[i][2])*forcez[i])*3;
lm1=(e[k][0]*u[i][0]+e[k][1]*u[i][1]+e[k][2]*u[i][2])*(e[k][0]*forcex[i]+e[k][1]*forcey[i]+e[k][2]*forcez[i])*9;
GuoF[k]=w[k]*(lm0+lm1);
//GuoF[k]=0.0;
}
//=====================equilibrium of moment=================================
u_tmp[0]=u[i][0];
u_tmp[1]=u[i][1];
u_tmp[2]=u[i][2];
for(int k=0;k<19;k++)
{
f_eq[k]=feq(k,rho[i],u_tmp);
}
for (int l=0;l<19;l++)
{
meq[l]=0;
for(int lm=0;lm<19;lm++)
meq[l]+=M[l][lm]*f_eq[lm];
}
//============================================================================
// ================== m=Mf matrix calculation =============================
// ================== F_hat=(I-.5*S)MGuoF =====================================
for (int mi=0; mi<19; mi++)
{m_l[mi]=0;F_hat[mi]=0;
for (int mj=0; mj<19; mj++)
{
m_l[mi]+=M[mi][mj]*f[i][mj];
F_hat[mi]+=M[mi][mj]*GuoF[mj];
}
F_hat[mi]*=(1-0.5*S[mi]);
}
//============================================================================
// if (i==20)
// {
// cout<<"Collison"<<endl;
// for(int lm=0;lm<19;lm++)
// cout<<f[20][lm]<<", ";
// cout<<endl;
// }
for (int sk=0;sk<19;sk++)
//m[sk]=m[sk]-S[sk]*(m[sk]-meq[sk]);
//m[sk]=m[sk]-S[sk]*(m[sk]-meq[sk])+(1-S[sk]*F_hat[sk]/2);
m_l[sk]=m_l[sk]-S[sk]*(m_l[sk]-meq[sk])+dt*F_hat[sk];
//}
// ================== f=M_-1m matrix calculation =============================
for (int mi=0; mi<19; mi++)
{f[i][mi]=0;
for (int mj=0; mj<19; mj++)
f[i][mi]+=MI[mi][mj]*m_l[mj];
}
//============================================================================
}
/*
double sum=0;
for(int ci=1;ci<=Count;ci++)
{
for(int lm=0;lm<19;lm++)
{sum+=f[ci][lm];}
cout<<sum<<endl;sum=0;
}
*/
}
void standard_bounceback_boundary(int it,double** f)
{
double tmp;
tmp = f[it][1];f[it][1] = f[it][2];f[it][2] = tmp;
tmp = f[it][3];f[it][3] = f[it][4];f[it][4] = tmp;
tmp = f[it][5];f[it][5] = f[it][6];f[it][6] = tmp;
tmp = f[it][7];f[it][7] = f[it][10];f[it][10] = tmp;
tmp = f[it][8];f[it][8] = f[it][9];f[it][9] = tmp;
tmp = f[it][11];f[it][11] = f[it][14];f[it][14] = tmp;
tmp = f[it][12];f[it][12] = f[it][13];f[it][13] = tmp;
tmp = f[it][15];f[it][15] = f[it][18];f[it][18] = tmp;
tmp = f[it][16];f[it][16] = f[it][17];f[it][17] = tmp;
}
void comput_macro_variables_IMR( double* rho,double** u,double** u0,double** f,double** F,int* SupInv,int*** Solid, double* forcex, double* forcey, double* forcez, int n,double porosity,double* gx,double* gy, double* gz)
{
int rank = MPI :: COMM_WORLD . Get_rank ();
int mpi_size=MPI :: COMM_WORLD . Get_size ();
double rho0=1.0;
double dp[3],rhok;
double *rbuf;
rbuf=new double[mpi_size*3];
for(int i=1;i<=Count;i++)
{
rhok=rho[i];
u0[i][0]=u[i][0];
u0[i][1]=u[i][1];
u0[i][2]=u[i][2];
rho[i]=0;
u[i][0]=0;
u[i][1]=0;
u[i][2]=0;
for(int k=0;k<19;k++)
{
f[i][k]=F[i][k];
rho[i]+=f[i][k];
u[i][0]+=e[k][0]*f[i][k];
u[i][1]+=e[k][1]*f[i][k];
u[i][2]+=e[k][2]*f[i][k];
}
u[i][0]=(u[i][0]+dt*forcex[i]/2)/rho[i];
u[i][1]=(u[i][1]+dt*forcey[i]/2)/rho[i];
u[i][2]=(u[i][2]+dt*forcez[i]/2)/rho[i];
dp[0]+=forcex[i]-(u[i][0]-u0[i][0])*rhok;
dp[1]+=forcey[i]-(u[i][1]-u0[i][1])*rhok;
dp[2]+=forcez[i]-(u[i][2]-u0[i][2])*rhok;
}
if ((n%1000==0) and (n>100))
{
MPI_Barrier(MPI_COMM_WORLD);
MPI_Gather(dp,3,MPI_DOUBLE,rbuf,3,MPI_DOUBLE,0,MPI_COMM_WORLD);
if (rank==0)
{
dp[0]=0;dp[1]=0;dp[2]=0;
for (int i=0;i<mpi_size;i++)
{
dp[0]+=rbuf[i*3+0];
dp[1]+=rbuf[i*3+1];
dp[2]+=rbuf[i*3+2];
}
dp[0]/=(NX+1)*(NY+1)*(NZ+1)*porosity;
dp[1]/=(NX+1)*(NY+1)*(NZ+1)*porosity;
dp[2]/=(NX+1)*(NY+1)*(NZ+1)*porosity;
}
MPI_Bcast(dp,3,MPI_DOUBLE,0,MPI_COMM_WORLD);
for (int i=1;i<=Count;i++)
{
switch(PerDir)
{
case 1:
forcex[i]=dp[0];break;
case 2:
forcey[i]=dp[1];break;
case 3:
forcez[i]=dp[2];break;
default:
forcex[i]=dp[0];
}
}
*gx=dp[0];
*gy=dp[1];
*gz=dp[2];
}
delete [] rbuf;
}
void comput_macro_variables( double* rho,double** u,double** u0,double** f,double** F,double* forcex, double* forcey, double* forcez,int* SupInv,int*** Solid)
{
// int rank = MPI :: COMM_WORLD . Get_rank ();
// int mpi_size=MPI :: COMM_WORLD . Get_size ();
for(int i=1;i<=Count;i++)
{
u0[i][0]=u[i][0];
u0[i][1]=u[i][1];
u0[i][2]=u[i][2];
rho[i]=0;
u[i][0]=0;
u[i][1]=0;
u[i][2]=0;
for(int k=0;k<19;k++)
{
f[i][k]=F[i][k];
rho[i]+=f[i][k];
u[i][0]+=e[k][0]*f[i][k];
u[i][1]+=e[k][1]*f[i][k];
u[i][2]+=e[k][2]*f[i][k];
}
//cout<<f[i][2]<<endl;
u[i][0]=(u[i][0]+dt*forcex[i]/2)/rho[i];
u[i][1]=(u[i][1]+dt*forcey[i]/2)/rho[i];
u[i][2]=(u[i][2]+dt*forcez[i]/2)/rho[i];
//=============================DEBUG=======================================
/*
if ((n%10==0) and (n<=1000))
{
forcex[i]=gx*0.01*n/10;
forcey[i]=gy*0.01*n/10;
forcez[i]=gz*0.01*n/10;
}
*/
//===========================================================================
}
//MPI_Barrier(MPI_COMM_WORLD);
}
void boundary_velocity(int xp,double v_xp,int xn, double v_xn,int yp,double v_yp,int yn,double v_yn,int zp,double v_zp,int zn,double v_zn,double** f,double* rho,double** u,int*** Solid)
// PLEASE SPECIFY THE BOUNDARY LOCATION BEFORE USE
// FOR EXAMPLE: IF SOUTH BOUNDARY IS INCLUDE, THEN THE BOOL VARIABLE SOUTH=1, AND ALSO SPECIFY THE LOCAL RHO
// IF THIS BOUNDARY CONDITION IS NOT GOING TO BE USED, PLEASE SET THE CORRESPONDING BOOL VARIABLE AS 0
// FORMAT:
// (NORTH BOUNDARY MARK,LOCAL RHO VALUE,SOUTH BOUNDARY MARK, LOCAL RHO VALUE,EAST BOUNDARY MARK, LOCAL RHO VALUE
// WEST BOUNDARY MARK, LOCAL RHO VALUE)
{
int Q=19;
//double ux0,uy0,uz0;
double u_xp[3]={v_xp,0,0};
double u_xn[3]={v_xn,0,0};
double u_yp[3]={0,v_yp,0};
double u_yn[3]={0,v_yn,0};
double u_zp[3]={0,0,v_zp};
double u_zn[3]={0,0,v_zn};
int rank = MPI :: COMM_WORLD . Get_rank ();
int mpi_size=MPI :: COMM_WORLD . Get_size ();
if (yp==1)
for (int i=0;i<nx_l;i++)
for(int k=0;k<=NZ;k++)
for (int ks=0;ks<Q;ks++)
{
if (Solid[i][NY][k]>0)
if (Solid[i][NY-1][k]>0)
f[Solid[i][NY][k]][ks]=feq(ks,1.0,u_yp)+f[Solid[i][NY-1][k]][ks]-feq(ks,1.0,u[Solid[i][NY-1][k]]);
else
f[Solid[i][NY][k]][ks]=feq(ks,1.0,u_yp);
f[Solid[i][NY][k]][ks]=feq(ks,1.0,u_yp);
}
if (yn==1)
for (int i=0;i<nx_l;i++)
for(int k=0;k<=NZ;k++)
for (int ks=0;ks<Q;ks++)
{
if (Solid[i][0][k]>0)
if (Solid[i][1][k]>0)
f[Solid[i][0][k]][ks]=feq(ks,1.0,u_yn)+f[Solid[i][1][k]][ks]-feq(ks,1.0,u[Solid[i][1][k]]);
else
f[Solid[i][0][k]][ks]=feq(ks,1.0,u_yn);
f[Solid[i][0][k]][ks]=feq(ks,1.0,u_yn);
}
if (zp==1)
for (int i=0;i<nx_l;i++)
for(int j=0;j<=NY;j++)
for (int ks=0;ks<Q;ks++)
{
if (Solid[i][j][NZ]>0)
if (Solid[i][j][NZ-1]>0)
f[Solid[i][j][NZ]][ks]=feq(ks,1.0,u_zp)+f[Solid[i][j][NZ-1]][ks]-feq(ks,1.0,u[Solid[i][j][NZ-1]]);
else
f[Solid[i][j][NZ]][ks]=feq(ks,1.0,u_zp);
f[Solid[i][j][NZ]][ks]=feq(ks,rho[abs(Solid[i][j][NZ-1])],u_zp);
}
if (zn==1)
for (int i=0;i<nx_l;i++)
for(int j=0;j<=NY;j++)
for (int ks=0;ks<Q;ks++)
{
if (Solid[i][j][0]>0)
if (Solid[i][j][1]>0)
f[Solid[i][j][0]][ks]=feq(ks,1.0,u_zn)+f[Solid[i][j][1]][ks]-feq(ks,1.0,u[Solid[i][j][1]]);
else
f[Solid[i][j][0]][ks]=feq(ks,1.0,u_zn);
f[Solid[i][j][0]][ks]=feq(ks,rho[abs(Solid[i][j][1])],u_zn);
}
if ((xp==1) && (rank==mpi_size-1))
for (int j=0;j<=NY;j++)
for (int k=0;k<=NZ;k++)
for (int ks=0;ks<Q;ks++)
{
if (Solid[nx_l-1][k][j]>0)
if (Solid[nx_l-2][j][k]>0)
f[Solid[nx_l-1][j][k]][ks]=feq(ks,1.0,u_xp)+f[Solid[nx_l-2][j][k]][ks]-feq(ks,1.0,u[Solid[nx_l-2][j][k]]);
else
f[Solid[nx_l-1][j][k]][ks]=feq(ks,1.0,u_xp);
f[Solid[nx_l-1][j][k]][ks]=feq(ks,rho[abs(Solid[nx_l-2][j][k])],u_xp);
}
if ((xn==1) && (rank==0))
for (int j=0;j<=NY;j++)
for(int k=0;k<=NZ;k++)
for (int ks=0;ks<Q;ks++)
{
if (Solid[0][j][k]>0)
if (Solid[1][j][k]>0)
f[Solid[0][j][k]][ks]=feq(ks,1.0,u_xn)+f[Solid[1][j][k]][ks]-feq(ks,1.0,u[Solid[1][j][k]]);
else
f[Solid[0][j][k]][ks]=feq(ks,1.0,u_xn);
f[Solid[0][j][k]][ks]=feq(ks,rho[abs(Solid[1][j][k])],u_xn);
}
}
void boundary_pressure(int xp,double rho_xp,int xn, double rho_xn,int yp,double rho_yp,int yn,double rho_yn,int zp,double rho_zp,int zn,double rho_zn,double** f,double** u,double* rho,int*** Solid)
// PLEASE SPECIFY THE BOUNDARY LOCATION BEFORE USE
// FOR EXAMPLE: IF SOUTH BOUNDARY IS INCLUDE, THEN THE BOOL VARIABLE SOUTH=1, AND ALSO SPECIFY THE LOCAL RHO
// IF THIS BOUNDARY CONDITION IS NOT GOING TO BE USED, PLEASE SET THE CORRESPONDING BOOL VARIABLE AS 0
// FORMAT:
// (NORTH BOUNDARY MARK,LOCAL RHO VALUE,SOUTH BOUNDARY MARK, LOCAL RHO VALUE,EAST BOUNDARY MARK, LOCAL RHO VALUE
// WEST BOUNDARY MARK, LOCAL RHO VALUE)
{
int Q=19;
//double ux0,uy0,uz0;
double u_ls[3]={0,0,0};
int rank = MPI :: COMM_WORLD . Get_rank ();
int mpi_size=MPI :: COMM_WORLD . Get_size ();
if (yp==1)
for (int i=0;i<nx_l;i++)
for(int k=0;k<=NZ;k++)
{
for (int ks=0;ks<Q;ks++)
if (Solid[i][NY][k]>0)
{
if (Solid[i][NY-1][k]>0)
{
u_ls[0]=u[Solid[i][NY-1][k]][0];
u_ls[1]=u[Solid[i][NY-1][k]][1];
u_ls[2]=u[Solid[i][NY-1][k]][2];
//f[Solid[i][NY][k]][ks]=feq(ks,rho_yp,u_ls)+f[Solid[i][NY-1][k]][ks]-feq(ks,rho[Solid[i][NY-1][k]],u[Solid[i][NY-1][k]]);
}
else
{
u_ls[0]=0.0;
u_ls[1]=0.0;u_ls[2]=0.0;
//f[Solid[i][NY][k]][ks]=feq(ks,rho_yp,u_ls);
}
f[Solid[i][0][k]][ks]=feq(ks,rho_yn,u_ls);
}
}
if (yn==1)
for (int i=0;i<nx_l;i++)
for(int k=0;k<=NZ;k++)
{
for (int ks=0;ks<Q;ks++)
if (Solid[i][0][k]>0)
{
if (Solid[i][1][k]>0)
{
u_ls[0]=u[Solid[i][1][k]][0];
u_ls[1]=u[Solid[i][1][k]][1];
u_ls[2]=u[Solid[i][1][k]][2];
//f[Solid[i][0][k]][ks]=feq(ks,rho_yn,u_ls)+f[Solid[i][1][k]][ks]-feq(ks,rho[Solid[i][1][k]],u[Solid[i][1][k]]);
}
else
{
u_ls[0]=0.0;
u_ls[1]=0.0;u_ls[2]=0.0;
//f[Solid[i][0][k]][ks]=feq(ks,rho_yn,u_ls);
}
f[Solid[i][0][k]][ks]=feq(ks,rho_yn,u_ls);
}
}
if (zp==1)
for (int i=0;i<nx_l;i++)
for(int j=0;j<=NY;j++)
{
for (int ks=0;ks<Q;ks++)
if (Solid[i][j][NZ]>0)
{
if (Solid[i][j][NZ-1]>0)
{
u_ls[0]=u[Solid[i][j][NZ-1]][0];
u_ls[1]=u[Solid[i][j][NZ-1]][1];
u_ls[2]=u[Solid[i][j][NZ-1]][2];
//f[Solid[i][j][NZ]][ks]=feq(ks,rho_zp,u_ls)+f[Solid[i][j][NZ-1]][ks]-feq(ks,rho[Solid[i][j][NZ-1]],u[Solid[i][j][NZ-1]]);
}
else
{
u_ls[0]=0.0;
u_ls[1]=0.0;u_ls[2]=0.0;
//f[Solid[i][j][NZ]][ks]=feq(ks,rho_zp,u_ls);
}
f[Solid[i][j][NZ]][ks]=feq(ks,rho_zp,u_ls);
}
}
if (zn==1)
for (int i=0;i<nx_l;i++)
for(int j=0;j<=NY;j++)
{
for (int ks=0;ks<Q;ks++)
if (Solid[i][j][0]>0)
{
if (Solid[i][j][1]>0)
{
u_ls[0]=u[Solid[i][j][1]][0];
u_ls[1]=u[Solid[i][j][1]][1];
u_ls[2]=u[Solid[i][j][1]][2];
//f[Solid[i][j][0]][ks]=feq(ks,rho_zn,u_ls)+f[Solid[i][j][1]][ks]-feq(ks,rho[Solid[i][j][1]],u[Solid[i][j][1]]);
}
else
{
u_ls[0]=0.0;
u_ls[1]=0.0;u_ls[2]=0.0;//f[Solid[i][j][0]][ks]=feq(ks,rho_zn,u_ls);
}
f[Solid[i][j][0]][ks]=feq(ks,rho_zn,u_ls);
}
}
if ((xp==1) && (rank==mpi_size-1))
for (int j=0;j<=NY;j++)
for (int k=0;k<=NZ;k++)
{
for (int ks=0;ks<Q;ks++)
if (Solid[nx_l-1][j][k]>0)
{
if (Solid[nx_l-2][j][k]>0)
{
u_ls[0]=u[Solid[nx_l-2][j][k]][0];
u_ls[1]=u[Solid[nx_l-2][j][k]][1];
u_ls[2]=u[Solid[nx_l-2][j][k]][2];
//f[Solid[nx_l-1][j][k]][ks]=feq(ks,rho_xp,u_ls)+f[Solid[nx_l-2][j][k]][ks]-feq(ks,rho[Solid[nx_l-2][j][k]],u[Solid[nx_l-2][j][k]]);
//f[Solid[nx_l-1][j][k]][ks]=feq(ks,rho_xp,u_ls);
}
else
{
u_ls[0]=0.0;
u_ls[1]=0.0;
u_ls[2]=0.0;
//f[Solid[nx_l-1][j][k]][ks]=feq(ks,rho_xp,u_ls);
}
f[Solid[nx_l-1][j][k]][ks]=feq(ks,rho_xp,u_ls);
}
}
if ((xn==1) && (rank==0))
for (int j=0;j<=NY;j++)
for(int k=0;k<=NZ;k++)
{
//cout<<"@@@@@@@@@@@"<<endl;
for (int ks=0;ks<Q;ks++)
if (Solid[0][j][k]>0)
{
if(Solid[1][j][k]>0)
{
u_ls[0]=u[Solid[1][j][k]][0];
u_ls[1]=u[Solid[1][j][k]][1];
u_ls[2]=u[Solid[1][j][k]][1];
//f[Solid[0][j][k]][ks]=feq(ks,rho_xn,u_ls)+f[Solid[1][j][k]][ks]-feq(ks,rho[Solid[1][j][k]],u[Solid[1][j][k]]);
//f[Solid[0][j][k]][ks]=feq(ks,rho_xn,u_ls);
}
else
{
u_ls[0]=0.0;
u_ls[1]=0.0;
u_ls[2]=0.0;
//f[Solid[0][j][k]][ks]=feq(ks,rho_xn,u_ls);
}
f[Solid[0][j][k]][ks]=feq(ks,rho_xn,u_ls);
}
//f[0][j][k][ks]=feq(ks,rho[1][j][k],u_ls,w,e);
}
}
double Error(double** u,double** u0,double *v_max,double* u_average)
{
int rank = MPI :: COMM_WORLD . Get_rank ();
int mpi_size=MPI :: COMM_WORLD . Get_size ();
double *rbuf,*um,*uave,u_compt;
double temp1,temp2,temp3;
temp1=0;
temp2=0;
temp3=0;
double error_in;
double u_max;
rbuf=new double[mpi_size];
um = new double[mpi_size];
uave = new double[mpi_size];
u_max=0;
*v_max=0;
//MPI_Barrier(MPI_COMM_WORLD);
for(int i=1; i<Count; i++)
{
temp1+=(u[i][0]-u0[i][0])*(u[i][0]-u0[i][0])+(u[i][1]-u0[i][1])*(u[i][1]-u0[i][1])+(u[i][2]-u0[i][2])*(u[i][2]-u0[i][2]);
temp2 += u[i][0]*u[i][0]+u[i][1]*u[i][1]+u[i][2]*u[i][2];
temp3+=sqrt(u[i][0]*u[i][0]+u[i][1]*u[i][1]+u[i][2]*u[i][2]);
if (u[i][0]*u[i][0]+u[i][1]*u[i][1]+u[i][2]*u[i][2]>u_max)
u_max=u[i][0]*u[i][0]+u[i][1]*u[i][1]+u[i][2]*u[i][2];
}
temp1=sqrt(temp1);
temp2=sqrt(temp2);
error_in=temp1/(temp2+1e-30);
u_max=sqrt(u_max);
MPI_Barrier(MPI_COMM_WORLD);
MPI_Gather(&error_in,1,MPI_DOUBLE,rbuf,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
MPI_Gather(&u_max,1,MPI_DOUBLE,um,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
MPI_Gather(&temp3,1,MPI_DOUBLE,uave,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
u_compt=0;
if (rank==0)
for (int i=0;i<mpi_size;i++)
{
if (rbuf[i]>error_in)
error_in=rbuf[i];
if (um[i]>*v_max)
*v_max=um[i];
u_compt+=uave[i];
}
u_compt/=(NX+1)*(NY+1)*(NZ+1);
*u_average=u_compt;
delete [] rbuf;
delete [] um;
delete [] uave;
//MPI_Barrier(MPI_COMM_WORLD);
return(error_in);
}
/*
void Geometry(int*** Solid)
{
int rank = MPI :: COMM_WORLD . Get_rank ();
int mpi_size=MPI :: COMM_WORLD . Get_size ();
const int root_rank=0;
int* nx_g = new int[mpi_size];
int* disp = new int[mpi_size];
MPI_Gather(&nx_l,1,MPI_INT,nx_g,1,MPI_INT,root_rank,MPI_COMM_WORLD);
if (rank==root_rank)
{
disp[0]=0;
for (int i=0;i<mpi_size;i++)
nx_g[i]*=(NY+1)*(NZ+1);
for (int i=1;i<mpi_size;i++)
disp[i]=disp[i-1]+nx_g[i-1];
}
int* Solid_storage= new int[nx_l*(NY+1)*(NZ+1)];
int* rbuf;
for(int i=0;i<nx_l;i++)
for(int j=0;j<=NY;j++)
for(int k=0;k<=NZ;k++)
if (Solid[i][j][k]<=0)
Solid_storage[i*(NY+1)*(NZ+1)+j*(NZ+1)+k]=1;
else
Solid_storage[i*(NY+1)*(NZ+1)+j*(NZ+1)+k]=0;
if (rank==root_rank)
rbuf= new int[(NX+1)*(NY+1)*(NZ+1)];
//MPI_Barrier(MPI_COMM_WORLD);
MPI_Gatherv(Solid_storage,nx_l*(NY+1)*(NZ+1),MPI_INT,rbuf,nx_g,disp,MPI_INT,root_rank,MPI_COMM_WORLD);
int NX0=NX+1;
int NY0=NY+1;
int NZ0=NZ+1;
if (mir==0)
{
if (mirX==1)
NX0=NX0/2;
if (mirY==1)
NY0=NY0/2;
if (mirZ==1)
NZ0=NZ0/2;
}
if (rank==root_rank)
{
ostringstream name;
name<<outputfile<<"LBM_Geometry"<<".vtk";
ofstream out;
out.open(name.str().c_str());
out<<"# vtk DataFile Version 2.0"<<endl;
out<<"J.Yang Lattice Boltzmann Simulation 3D Single Phase-Solid-Geometry"<<endl;
out<<"ASCII"<<endl;
out<<"DATASET STRUCTURED_POINTS"<<endl;
out<<"DIMENSIONS "<<NX0<<" "<<NY0<<" "<<NZ0<<endl;
out<<"ORIGIN 0 0 0"<<endl;
out<<"SPACING 1 1 1"<<endl;
out<<"POINT_DATA "<<NX0*NY0*NZ0<<endl;
out<<"SCALARS sample_scalars float"<<endl;
out<<"LOOKUP_TABLE default"<<endl;
for(int k=0;k<NZ0;k++)
for(int j=0; j<NY0; j++)
for(int i=0;i<NX0;i++)
//for(int k=0;k<=NZ;k++)
out<<" "<<rbuf[i*(NY+1)*(NZ+1)+j*(NZ+1)+k]<<endl;
out.close();
}
delete [] Solid_storage;
if (rank==root_rank)
delete [] rbuf;
delete [] nx_g;
delete [] disp;
}
*/
void Geometry(int*** Solid)
{
int rank = MPI :: COMM_WORLD . Get_rank ();
int mpi_size=MPI :: COMM_WORLD . Get_size ();
const int root_rank=0;
int nx_g[mpi_size];
int disp[mpi_size];
MPI_Gather(&nx_l,1,MPI_INT,nx_g,1,MPI_INT,root_rank,MPI_COMM_WORLD);
if (rank==root_rank)
{
disp[0]=0;
for (int i=1;i<mpi_size;i++)
disp[i]=disp[i-1]+nx_g[i-1];
}
MPI_Bcast(&disp,mpi_size,MPI_INT,0,MPI_COMM_WORLD);
int NX0=NX+1;
int NY0=NY+1;
int NZ0=NZ+1;
if (mir==0)
{
if (mirX==1)
NX0=NX0/2;
if (mirY==1)
NY0=NY0/2;
if (mirZ==1)
NZ0=NZ0/2;
}
ostringstream name;
name<<outputfile<<"LBM_Geometry"<<".vtk";
if (rank==root_rank)
{
ofstream out;
out.open(name.str().c_str());
out<<"# vtk DataFile Version 2.0"<<endl;
out<<"J.Yang Lattice Boltzmann Simulation 3D Single Phase-Solid-Geometry"<<endl;
out<<"ASCII"<<endl;
out<<"DATASET STRUCTURED_POINTS"<<endl;
out<<"DIMENSIONS "<<NZ0<<" "<<NY0<<" "<<NX0<<endl;
out<<"ORIGIN 0 0 0"<<endl;
out<<"SPACING 1 1 1"<<endl;
out<<"POINT_DATA "<<NX0*NY0*NZ0<<endl;
out<<"SCALARS sample_scalars float"<<endl;
out<<"LOOKUP_TABLE default"<<endl;
out.close();
}
for (int processor=0;processor<mpi_size;processor++)
{
if (rank==processor)
{
ofstream out(name.str().c_str(),ios::app);
for(int i=0;i<nx_l;i++)
if (i+disp[rank]<NX0)
for(int j=0; j<NY0; j++)
for(int k=0;k<NZ0;k++)
// out<<1<<endl;
if (Solid[i][j][k]<=0)
out<<1<<endl;
else
out<<0<<endl;
out.close();
}
MPI_Barrier(MPI_COMM_WORLD);
}
}
void output_velocity(int m,double* rho,double** u,int MirX,int MirY,int MirZ,int mir,int*** Solid)
{
int rank = MPI :: COMM_WORLD . Get_rank ();
const int mpi_size=MPI :: COMM_WORLD . Get_size ();
const int root_rank=0;
int nx_g[mpi_size];
int disp[mpi_size];
MPI_Gather(&nx_l,1,MPI_INT,nx_g,1,MPI_INT,root_rank,MPI_COMM_WORLD);
if (rank==root_rank)
{
disp[0]=0;
for (int i=1;i<mpi_size;i++)
disp[i]=disp[i-1]+nx_g[i-1];
}
int NX0=NX+1;
int NY0=NY+1;
int NZ0=NZ+1;
if (mir==0)
{
if (MirX==1)
NX0=NX0/2;
if (MirY==1)
NY0=NY0/2;
if (MirZ==1)
NZ0=NZ0/2;
}
ostringstream name;
name<<outputfile<<"LBM_velocity_Vector_"<<m<<".vtk";
if (rank==root_rank)
{
ofstream out;
out.open(name.str().c_str());
out<<"# vtk DataFile Version 2.0"<<endl;
out<<"J.Yang Lattice Boltzmann Simulation 3D Single Phase-Velocity"<<endl;
out<<"ASCII"<<endl;
out<<"DATASET STRUCTURED_POINTS"<<endl;
out<<"DIMENSIONS "<<NZ0<<" "<<NY0<<" "<<NX0<<endl;
out<<"ORIGIN 0 0 0"<<endl;
out<<"SPACING 1 1 1"<<endl;
out<<"POINT_DATA "<<NX0*NY0*NZ0<<endl;
out<<"VECTORS sample_vectors double"<<endl;
out<<endl;
out.close();
}
for (int processor=0;processor<mpi_size;processor++)
{
if (rank==processor)
{
ofstream out(name.str().c_str(),ios::app);
for(int i=0;i<nx_l;i++)
if (i+disp[rank]<NX0)
for(int j=0; j<NY0; j++)
for(int k=0;k<NZ0;k++)
if (Solid[i][j][k]>0)
out<<u[Solid[i][j][k]][2]<<" "<<u[Solid[i][j][k]][1]<<" "<<u[Solid[i][j][k]][0]<<endl;
else
out<<0.0<<" "<<0.0<<" "<<0.0<<endl;
out.close();
}
MPI_Barrier(MPI_COMM_WORLD);
}
/* ostringstream name2;
name2<<"LBM_velocity_"<<m<<".out";
ofstream out2(name2.str().c_str());
for (int j=0;j<=NY;j++)
{
if (Solid[1][j][1]>0)
out2<<u[Solid[2][j][1]][0]<<endl;
else
out2<<0.0<<endl;
}
*/
}
void output_density(int m,double* rho,int MirX,int MirY,int MirZ,int mir,int*** Solid)
{
int rank = MPI :: COMM_WORLD . Get_rank ();
const int mpi_size=MPI :: COMM_WORLD . Get_size ();
const int root_rank=0;
int nx_g[mpi_size];
int disp[mpi_size];
MPI_Gather(&nx_l,1,MPI_INT,nx_g,1,MPI_INT,root_rank,MPI_COMM_WORLD);
if (rank==root_rank)
{
disp[0]=0;
for (int i=1;i<mpi_size;i++)
disp[i]=disp[i-1]+nx_g[i-1];
}
int NX0=NX+1;
int NY0=NY+1;
int NZ0=NZ+1;
if (mir==0)
{
if (MirX==1)
NX0=NX0/2;
if (MirY==1)
NY0=NY0/2;
if (MirZ==1)
NZ0=NZ0/2;
}
ostringstream name;
name<<outputfile<<"LBM_Density_"<<m<<".vtk";
if (rank==root_rank)
{
ofstream out;
out.open(name.str().c_str());
out<<"# vtk DataFile Version 2.0"<<endl;
out<<"J.Yang Lattice Boltzmann Simulation 3D Single Phase-Solid-Density"<<endl;
out<<"ASCII"<<endl;
out<<"DATASET STRUCTURED_POINTS"<<endl;
out<<"DIMENSIONS "<<NZ0<<" "<<NY0<<" "<<NX0<<endl;
out<<"ORIGIN 0 0 0"<<endl;
out<<"SPACING 1 1 1"<<endl;
out<<"POINT_DATA "<<NX0*NY0*NZ0<<endl;
out<<"SCALARS sample_scalars float"<<endl;
out<<"LOOKUP_TABLE default"<<endl;
out.close();
}
for (int processor=0;processor<mpi_size;processor++)
{
if (rank==processor)
{
ofstream out(name.str().c_str(),ios::app);
for(int i=0;i<nx_l;i++)
if (i+disp[rank]<NX0)
for(int j=0; j<NY0; j++)
for(int k=0;k<NZ0;k++)
if (Solid[i][j][k]>0)
out<<rho[Solid[i][j][k]]<<endl;
else
out<<1.0<<endl;
out.close();
}
MPI_Barrier(MPI_COMM_WORLD);
}
}
double Comput_Perm(double** u,double* Permia,int PerDIr)
{
int rank = MPI :: COMM_WORLD . Get_rank ();
int mpi_size=MPI :: COMM_WORLD . Get_size ();
double *rbuf;
rbuf=new double[mpi_size*3];
double Perm[3];
double error;
double Q[3]={0.0,0.0,0.0};
for (int i=1;i<=Count;i++)
{
Q[0]+=u[i][0];
Q[1]+=u[i][1];
Q[2]+=u[i][2];
}
MPI_Barrier(MPI_COMM_WORLD);
//Qx/=(NX+1)/mpi_size*(NY+1)*(NZ+1);
//Qy/=(NX+1)/mpi_size*(NY+1)*(NZ+1);
//Qz/=(NX+1)/mpi_size*(NY+1)*(NZ+1);
MPI_Gather(&Q,3,MPI_DOUBLE,rbuf,3,MPI_DOUBLE,0,MPI_COMM_WORLD);
if (rank==0)
{
Q[0]=0;Q[1]=0;Q[2]=0;
for (int i=0;i<mpi_size;i++)
{
Q[0]+=rbuf[i*3+0];
Q[1]+=rbuf[i*3+1];
Q[2]+=rbuf[i*3+2];
}
//Perm[0]=Q[0]*(1.0/Zoom)*(1.0/Zoom)/((NX+1)/Zoom*(NY+1)/Zoom*(NZ+1)/Zoom)*(in_vis)/gx;
//Perm[1]=Q[1]*(1.0/Zoom)*(1.0/Zoom)/((NX+1)/Zoom*(NY+1)/Zoom*(NZ+1)/Zoom)*(in_vis)/gy;
//Perm[2]=Q[2]*(1.0/Zoom)*(1.0/Zoom)/((NX+1)/Zoom*(NY+1)/Zoom*(NZ+1)/Zoom)*(in_vis)/gz;
Perm[0]=Q[0]/((NX+1)*(NY+1)*(NZ+1))*(in_vis)/gx;
Perm[1]=Q[1]/((NX+1)*(NY+1)*(NZ+1))*(in_vis)/gy;
Perm[2]=Q[2]/((NX+1)*(NY+1)*(NZ+1))*(in_vis)/gz;
switch(PerDIr)
{
case 1:
error=(Perm[0]-Permia[0])/Permia[0];break;
case 2:
error=(Perm[1]-Permia[1])/Permia[1];break;
case 3:
error=(Perm[2]-Permia[2])/Permia[2];break;
default:
error=(Perm[0]-Permia[0])/Permia[0];
}
Permia[0]=Perm[0];
Permia[1]=Perm[1];
Permia[2]=Perm[2];
}
delete [] rbuf;
return (error);
}
|
9636d11f189b28f77d7c629376ff3480fd6f25fd | 267e979fee386aedfde7dd48f5bb88cb7a86095a | /CG/Scene.cpp | d1eefd8643e9a3f91aa17b2c52c77ed544cb894c | [] | no_license | wb-finalking/Path_Tracing | 6c84da19c618cac5035b2ee63187095f48166589 | 4de934eee355f8a6e41460a87a81c2387a4c1ffb | refs/heads/master | 2021-04-27T03:48:01.977737 | 2018-04-13T14:16:18 | 2018-04-13T14:16:18 | 122,720,435 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,589 | cpp | Scene.cpp | #include <Scene.h>
std::atomic_int Scene::computed_row{0};
Scene::Scene() : viewport_width(8), viewport_height(5), max_depth(14),
sample_num(64), light_intensity(35), near_plane(10),cam_pos(Vector3f(0, 4, 30)),
cam_view(Vector3f(0, 0, -1)), cam_up(Vector3f(0, 1, 0)), cam_right(Vector3f(1, 0, 0)),
environment_color(Vector3f(0, 0, 0)), img_width(801), img_height(531), thread_num(2)
{
buffer = new Vector3f[img_height*img_width];
}
Scene::~Scene()
{
for (Object* obj : m_objects)
delete obj;
m_objects.clear();
if (buffer)
{
delete[] buffer;
buffer = NULL;
}
}
void Scene::render(RayTracingType raytracing_type)
{
computed_row = 0;
multithread(raytracing_type);
for (int i = 0; i < (int)m_thread_list.size(); i++)
m_thread_list[i].join();
}
void Scene::multithread(RayTracingType raytracing_type)
{
m_thread_list.clear();
int stride = img_height / thread_num;
int start_row = 0, end_row = 0;
for (int i = 0; i < thread_num; i++)
{
end_row = ((i == thread_num - 1) ? img_height : start_row + stride);
m_thread_list.push_back(std::thread(&Scene::subRender, this, start_row, end_row, raytracing_type));
start_row = end_row;
}
m_thread_list.push_back(std::thread(&Scene::emitStatus, this));
}
void Scene::subRender(int start_row, int end_row, RayTracingType raytracing_type)
{
Vector3f view_center_pos = cam_pos + near_plane*cam_view;
Vector3f start_pos = view_center_pos - (1.0*viewport_width / 2.0)*cam_right + (1.0*viewport_height / 2.0)*cam_up;
Vector3f color(0, 0, 0);
for (int row = start_row; row < end_row; row++)
{
for (int col = 0; col < img_width; col++)
{
float r = 1.0*row*viewport_height / img_height;
float c = 1.0*col*viewport_width / img_width;
Vector3f org = start_pos + c*cam_right - r*cam_up;
Vector3f dir = (org - cam_pos).normalized();
color = Vector3f(0, 0, 0);
if (raytracing_type == Ordinary)
{
//ordinay raytracing
color = RayTracer(org, dir);
color *= 255;
//std::cout <<"color : "<< color << std::endl;
}
else if (raytracing_type == MCSD)
{
//MCSD raytracing
int valid_num = 0;
for (int sample_index = 0; sample_index < sample_num; sample_index++)
{
float x_noise = noise(viewport_width, img_width);
float y_noise = noise(viewport_height, img_height);
Vector3f org_noise = org + x_noise*cam_right - y_noise*cam_up;
Vector3f dir_noise = (org_noise - cam_pos).normalized();
Vector3f color_tmp(0, 0, 0);
std::vector<InterPoint> path;
path.reserve(max_depth+2);
//color_tmp = MCSDRayTracer(org_noise, dir_noise, max_depth);
//if (color_tmp[0] > 0 || color_tmp[1] > 0 || color_tmp[2] > 0)
//{
// color += color_tmp;
// valid_num++;
//}
color += MCSDRayTracer(org_noise, dir_noise, max_depth, path);
}
//if (valid_num > 0)
// color /= valid_num;
color /= sample_num;
clip(color);
for (int i = 0; i < 3; i++)
{
int c = int(pow(color[i], 0.4545f)*255.0f + 0.5f);
//int c = int(pColor[i] + 0.5f);
c = (c > 255) ? 255 : c;
color[i] = c;
}
}
else if (raytracing_type == MCBD)
{
//MCBD raytracing
int valid_num = 0;
for (int sample_index = 0; sample_index < sample_num; sample_index++)
{
float x_noise = noise(viewport_width, img_width);
float y_noise = noise(viewport_height, img_height);
Vector3f org_noise = org + x_noise*cam_right - y_noise*cam_up;
Vector3f dir_noise = (org_noise - cam_pos).normalized();
Vector3f color_tmp(0, 0, 0);
color_tmp = MCBDRayTracer(org_noise, dir_noise, max_depth);
if (color_tmp[0] >= 0 && color_tmp[1] >= 0 && color_tmp[2] >= 0)
{
clip2(color_tmp);
color += color_tmp;
valid_num++;
}
//color += MCBDRayTracer(org_noise, dir_noise, max_depth);
}
if (valid_num > 0)
color /= valid_num;
//color /= sample_num;
clip(color);
for (int i = 0; i < 3; i++)
{
int c = int(pow(color[i], 0.4545f)*255.0f + 0.5f);
//int c = int(color[i]*255 + 0.5f);
c = (c > 255) ? 255 : c;
color[i] = c;
}
}
buffer[row*img_width + col] = color;
//if (color[0]>0||color[1]>0||color[2]>0)
//std::cout << color[0] << " " << color[1] << " " << color[2] << std::endl;
//std::cout << "col : " << col << " row : " << row << std::endl;
}
std::cout << "row : " << row << std::endl;
computed_row++;
emit statusChange(int(computed_row));
//std::cout << "computed_row : " << computed_row << std::endl;
}
}
void Scene::loadScene(std::vector<std::string>&obj_files)
{
for (Object* obj : m_objects)
delete obj;
m_objects.clear();
for (std::string filename : obj_files)
{
m_objects.push_back(new Object_Mesh(filename));
}
}
void Scene::loadObj(std::string filename)
{
m_objects.push_back(new Object_Mesh(filename));
}
void Scene::loadSphere(const Vector3f center, const float r)
{
m_objects.push_back(new Object_Sphere(center, r));
}
void Scene::appendMaterial(Material* m)
{
int obj_id = m_objects.size()-1;
if (m_objects[obj_id]->material == NULL)
m_objects[obj_id]->material = m;
else
delete m;
}
void Scene::clearObjs()
{
for (Object* obj : m_objects)
delete obj;
m_objects.clear();
}
Vector3f Scene::RayTracer(const Vector3f& org, const Vector3f& dir)
{
float min_t;
bool intersected=false;
InterPoint tmp_inter_p;
InterPoint inter_p;
for (int i = 0; i < m_objects.size(); i++)
{
if (m_objects[i]->intersection(org, dir, tmp_inter_p))
{
//std::cout <<" tmp_inter_pt "<< tmp_inter_p.t << std::endl;
if (!intersected || min_t > tmp_inter_p.t)
{
intersected = true;
min_t = tmp_inter_p.t;
inter_p = tmp_inter_p;
}
}
}
if (intersected)
//return Vector3f(0.25,0.25,0.75);
return inter_p.normal;
else
return environment_color;
}
bool Scene::sceneIntersecting(const Vector3f& org, const Vector3f& dir, InterPoint& inter_p, bool is_out)
{
float min_t;
bool intersected = false;
InterPoint tmp_inter_p;
for (int i = 0; i < m_objects.size(); i++)
{
if (m_objects[i]->intersection(org, dir, tmp_inter_p, is_out))
{
if (!intersected || min_t > tmp_inter_p.t)
{
intersected = true;
min_t = tmp_inter_p.t;
inter_p = tmp_inter_p;
}
}
}
if (intersected)
return true;
else
return false;
}
Vector3f Scene::MCSDRayTracer(const Vector3f& org, const Vector3f& dir, int depth, std::vector<InterPoint>& path,bool refrac, bool is_out)
{
if (depth < 0)
return environment_color;
InterPoint inter_p;
Vector3f color(0,0,0);
if (!sceneIntersecting(org, dir, inter_p,is_out))
return environment_color;
inter_p.is_empty = false;
if (refrac)
path[max_depth - depth+1] = inter_p;
//*************self iteration**************//
//generating dir according material
//dir=...
//color_tmp=MCSDRayTracer(inter_p.point , dir , depth-1);
//computing color according to material
//color=.../p(dir)
//*************radiate iteration**************//
if (inter_p.material!=NULL)
color = inter_p.material->radiate(inter_p, dir, depth, this,path, refrac, is_out);
return color;
}
Vector3f Scene::pathLinker(std::vector<InterPoint>&view_path, std::vector<InterPoint>&light_path)
{
Vector3f color(0, 0, 0);
int view_point = 0;//contain lightsource
for (int i = 0; i < max_depth + 2; i++)
{
if (!view_path[i].is_empty)
view_point++;
else
break;
}
int light_point = 0;//contain viewpoint
for (int i = 0; i < max_depth + 2; i++)
{
if (!light_path[i].is_empty)
light_point++;
else
break;
}
//modify is_out but will also modify when checking
for (int i = 0; i < light_point - 1; i++)
{
if (!(light_path[i].is_out&&light_path[i + 1].is_out))
light_path[i].is_out = !light_path[i].is_out;
}
int valid_num = 0;
int check_num = 0;
float total_p = 0;
for (int i = 1; i < view_point; i++)
{
for (int j = 0; j < light_point; j++)
{
Vector3f color_tmp(0, 0, 0);
float path_p;
if (pathCheck(view_path, i, light_path, j, color_tmp, path_p))
{
color += path_p*path_p*color_tmp;
valid_num++;
total_p += path_p*path_p;
}
//color += color_tmp;
check_num++;
}
}
if (valid_num>0)
color /= total_p;
//color /= valid_num;
//color /= check_num;
//float num = 0;
//for (int k = 0; k < view_point + light_point-1; k++)
//{
// int valid_num = 0;
// float total_p = 0;
// Vector3f color_sum(0,0,0);
// for (int i = 0; i <= k; i++)
// {
// int j = k - i;
// if (i < (view_point - 1) && j < light_point)
// {
// Vector3f color_tmp(0, 0, 0);
// float path_p;
// if (pathCheck(view_path, i+1, light_path, j, color_tmp, path_p))
// {
// color_sum += path_p*path_p*color_tmp;
// valid_num++;
// total_p += path_p*path_p;
// }
// }
// }
// if (valid_num > 0)
// {
// color_sum /= total_p;
// color += color_sum;
// num++;
// }
//}
//color /= num;
return color;
}
bool Scene::pathCheck(std::vector<InterPoint>&view_path, int indexLinked_view, std::vector<InterPoint>&light_path, int indexLinked_light, Vector3f &color, float &path_p)
{
//******************checking block*********************//
bool blocked = true;
bool is_out_linked = true;//need modifing
bool intersected;
Vector3f org = view_path[indexLinked_view].point;
Vector3f dir = (light_path[indexLinked_light].point - view_path[indexLinked_view].point).normalized();
InterPoint inter_p;
intersected=sceneIntersecting( org, dir, inter_p, true);
if (intersected)
{
Vector3f v1 = (light_path[indexLinked_light].point - view_path[indexLinked_view].point);
Vector3f v2 = (inter_p.point - view_path[indexLinked_view].point);
float t1 = v1.dot(v1);
float t2 = v2.dot(v2);
if (std::abs(t1 - t2) < 0.001)
{
blocked = false;
is_out_linked = true;
}
}
if (blocked && sceneIntersecting(org, dir, inter_p, false))
{
Vector3f v1 = (light_path[indexLinked_light].point - view_path[indexLinked_view].point);
Vector3f v2 = (inter_p.point - view_path[indexLinked_view].point);
float t1 = v1.dot(v1);
float t2 = v2.dot(v2);
if (std::abs(t1 - t2) < 0.001)
{
blocked = false;
is_out_linked = false;
}
}
if (blocked)
return false;
//******************computing probability at the linked node*********************//
float P1 = -1;
float P2 = -1;
if (indexLinked_light <= 0)
{
P1 = 1 / (2 * PI);
Vector3f dir_in = (view_path[indexLinked_view].point - view_path[indexLinked_view - 1].point).normalized();
Vector3f dir_out = (light_path[indexLinked_light].point - view_path[indexLinked_view].point).normalized();
P2 = view_path[indexLinked_view].material->fixedProbability(view_path[indexLinked_view].normal, dir_in, dir_out, view_path[indexLinked_view].is_out);
}
else
{
//Vector3f dir_in = (view_path[indexLinked_view].point - path_node[end_id].point).normalized();
Vector3f dir_out = (view_path[indexLinked_view].point - light_path[indexLinked_light].point).normalized();
Vector3f dir_in = (light_path[indexLinked_light].point - light_path[indexLinked_light - 1].point).normalized();
P1 = light_path[indexLinked_light].material->fixedProbability(light_path[indexLinked_light].normal, dir_in, dir_out, light_path[indexLinked_light].is_out);
dir_in = (view_path[indexLinked_view].point - view_path[indexLinked_view - 1].point).normalized();
dir_out = (light_path[indexLinked_light].point - view_path[indexLinked_view].point).normalized();
P2 = view_path[indexLinked_view].material->fixedProbability(view_path[indexLinked_view].normal, dir_in, dir_out, view_path[indexLinked_view].is_out);
}
if (std::fabs(P1) < 0.001&&std::fabs(P2) < 0.001)
return false;
//******************path computing*********************//
std::vector<InterPoint> path_node;
//path_node.push_back(light_path[0]);
for (int i = 0; i < indexLinked_light+1; i++)
{
path_node.push_back(light_path[i]);
}
for (int i = indexLinked_view; i >=0; i--)
{
path_node.push_back(view_path[i]);
}
path_node[indexLinked_light + 1].P = P1;//assign probability at the linked node
//path_node.push_back(view_path[0]);
//******************modify is_out*********************//
path_node[indexLinked_light].is_out = is_out_linked;
//first node is light source
//final node is viewpoint
Vector3f color_tmp(0,0,0);
Vector3f normal(0, 1, 0);
Vector3f dir_in(0,1,0);
Vector3f dir_out(0,1,0);
bool is_out = true;
for (int i=0; i < path_node.size()-1; i++)
{
normal = path_node[i].normal;
is_out = path_node[i].is_out;
dir_in = (path_node[i].point - path_node[i+1].point).normalized();
color_tmp = path_node[i].material->fixedRadiate(color_tmp, normal, dir_in, dir_out, is_out, path_node[i].P);
dir_out = (path_node[i].point - path_node[i + 1].point).normalized();
}
color = color_tmp;
//******************MC path computing*********************//
path_p = 1;
if (indexLinked_view > 1)
{
for (int i = 1; i <indexLinked_view - 1; i++)
{
dir_in = (view_path[i].point - view_path[i - 1].point).normalized();
dir_out = (view_path[i + 1].point - view_path[i].point).normalized();
float p = view_path[i].material->fixedProbability(view_path[i].normal, dir_in, dir_out, view_path[i].is_out);
color /= p;
path_p *= p;
}
}
//color /= (P1 + P2) / 2;
//path_p *= (P1 + P2) / 2;
if (indexLinked_light > 1)
{
for (int i = 1; i < indexLinked_light - 1; i++)
{
dir_in = (light_path[i].point - light_path[i - 1].point).normalized();
dir_out = (light_path[i + 1].point - light_path[i].point).normalized();
float p = light_path[i].material->fixedProbability(light_path[i].normal, dir_in, dir_out, light_path[i].is_out);
color /= p;
path_p *= p;
}
color /= 1 / (2 * PI);
path_p *= 1 / (2 * PI);
//color /= (P1 + P2) / 2;
//path_p *= (P1 + P2) / 2;
}
else if (indexLinked_light == 1)
{
color /= 1 / (2 * PI);
path_p *= 1 / (2 * PI);
//color /= (P1 + P2) / 2;
//path_p *= (P1 + P2) / 2;
}
return true;
}
Vector3f Scene::MCBDRayTracer(const Vector3f& org, const Vector3f& dir, int depth, bool is_out)
{
Vector3f color(0,0,0);
std::vector<InterPoint> view_path;
view_path.resize(max_depth + 2);
InterPoint view_point;
view_point.is_empty = false;
view_point.emit_dir = dir;
view_point.point = org;
view_path[0] = view_point;
color = MCSDRayTracer(org, dir, depth, view_path, is_out );
//if single direction MCRayTracer get the lightsource
if (color[0] > 0 || color[1] > 0 || color[2] > 0)
return color;
if (view_path[1].is_empty)
return color;
// emit the path from lightsource
std::vector<InterPoint> emit_pos;
for (int obj_id = 0; obj_id < m_objects.size(); obj_id++)
{
if (m_objects[obj_id]->material->material_type == LIGHT)
{
m_objects[obj_id]->getEmitPos(emit_pos);
}
}
//int source_num = emit_pos.size();
//int valid_num=0;
//color = Vector3f(0,0,0);
//for (int source_id = 0; source_id < source_num; source_id++)
//{
// std::vector<InterPoint> light_path;
// light_path.resize(max_depth + 2);
// light_path[0] = emit_pos[source_id];
// MCSDRayTracer(emit_pos[source_id].point, emit_pos[source_id].emit_dir, depth, light_path, is_out );
// //Vector3f color_tmp = pathLinker(view_path,light_path);
// //if (color_tmp[0] > 0 || color_tmp[1]>0 || color_tmp[2] > 0)
// //{
// // color += color_tmp;
// // valid_num++;
// //}
// color += pathLinker(view_path, light_path);
//}
////if (valid_num>0)
//// color /= valid_num;
//color /= source_num;
int source_num = emit_pos.size();
int valid_num=0;
color = Vector3f(0,0,0);
int source_id = rand() % source_num;
std::vector<InterPoint> light_path;
light_path.resize(max_depth + 2);
light_path[0] = emit_pos[source_id];
MCSDRayTracer(emit_pos[source_id].point, emit_pos[source_id].emit_dir, depth, light_path, is_out );
color = pathLinker(view_path, light_path);
return color;
}
void Scene::renderViewport(QImage& img_scene)
{
for (int i = 0; i<img_height; i++)
{
int row_ind = i*img_width;
for (int j = 0; j<img_width; j++)
{
int index = row_ind + j;
uint color = 0;
Vector3f tmp_color = buffer[index];
//img_scene.setPixel(j, i, qRgb((int)tmp_color[0], (int)tmp_color[1], (int)tmp_color[2]));
img_scene.setPixel(j, i, qRgb((int)std::fabs(tmp_color[0]), (int)std::fabs(tmp_color[1]), (int)std::fabs(tmp_color[2])));
}
}
}
void Scene::clip(Vector3f& color)
{
for (int i = 0; i<3; i++)
{
if (color(i)<0)
color(i) = 0;
else if (color(i)>1.f)
color(i) = 1;
}
}
void Scene::clip2(Vector3f& color)
{
for (int i = 0; i<3; i++)
{
if (color(i)>10.f)
color(i) = 10;
}
}
float Scene::noise(float viewport_scale, float img_scale)
{
float r = rand() % 10000;
r = r / 10000;
return r*viewport_scale / img_scale;
}
void Scene::emitStatus()
{
//while (computed_row<img_height)
// emit statusChange(int(computed_row));
while (computed_row<img_height)
pProgressBar->setValue(100.0*computed_row / img_height);
}
//******************set parameters*************************//
void Scene::setViewport(int width, int height)
{
viewport_height = height;
viewport_width = width;
}
void Scene::setThreadNum(int num)
{
thread_num = num;
}
void Scene::setNearplane(int z)
{
near_plane = z;
}
void Scene::setLightIntensity(int indensity)
{
light_intensity = indensity;
}
void Scene::setSampleNum(int num)
{
sample_num = num;
}
void Scene::setMaxDepth(int depth)
{
max_depth = depth;
}
void Scene::setCameraPos(Vector3f pos)
{
cam_pos = pos;
}
void Scene::setCameraView(Vector3f view)
{
cam_view = view.normalized();
}
void Scene::setImgSize(int width, int height)
{
if (buffer != NULL)
delete buffer;
img_width = width;
img_height = height;
buffer = new Vector3f[img_height*img_width];
}
void Scene::setMaterial()
{
m_objects[0]->setMaterial(new Light(light_intensity));
m_objects[1]->setMaterial(new Diffuse(Vector3f(0.75, 0.25, 0.25)));
m_objects[2]->setMaterial(new Diffuse(Vector3f(0.25, 0.25, 0.25)));
m_objects[3]->setMaterial(new Diffuse(Vector3f(0.25, 0.25, 0.25)));
m_objects[4]->setMaterial(new Diffuse(Vector3f(0.25, 0.25, 0.75)));
m_objects[5]->setMaterial(new Diffuse(Vector3f(0.25, 0.25, 0.25)));
m_objects[6]->setMaterial(new Mirror());
m_objects[7]->setMaterial(new Glass());
}
void Scene::setObjMaterial(int obj_index, Material *m)
{
if (obj_index<m_objects.size() && obj_index >= 0)
m_objects[obj_index]->setMaterial(m);
}
//******************get parameters*************************//
int Scene::getCompletedRows()
{
int num = computed_row;
return num;
}
int Scene::getTotalRows()
{
return img_height;
}
float Scene::getLightIntensity()
{
return light_intensity;
} |
c51c8653f233992031ff50ad45eb5c038d6e5a11 | 06d2386ced7e6c82eab0243541de0d8d258e812c | /ct_sensor.ino | ef4dff2a52029afd523fff93fa6f3b89b13ae22e | [] | no_license | iowasparrow/homeEnergy | 1aecf91f43dd46ef666133f7f9d40e1b4694b43b | 53dbb49014cd1de0898f6a14786e5a02642faf3f | refs/heads/main | 2023-03-17T13:36:01.682636 | 2021-03-16T17:33:19 | 2021-03-16T17:33:19 | 348,436,696 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,312 | ino | ct_sensor.ino | #include <PubSubClient.h>
#include <ESP8266WiFi.h>
#include <Adafruit_ADS1015.h>
Adafruit_ADS1115 ads; /* Use this for the 16-bit version */
//this sketch is working for a 50 amp ct
//const float FACTOR = 20; //20A/1V from the CT
const float FACTOR = 30;
const float multiplier = 0.0000633;
#ifndef STASSID
#define STASSID "makersmark"
#define STAPSK "sieshell"
#endif
WiFiClient client;
PubSubClient mqttClient(client);
const char* ssid = STASSID;
const char* password = STAPSK;
int i = 0;
void printMeasure(String prefix, float value, String postfix)
{
Serial.print(prefix);
Serial.print(value, 3);
Serial.println(postfix);
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
void setup() {
Serial.begin(115200);
ads.setGain(GAIN_FOUR); // 4x gain +/- 1.024V 1 bit = 0.5mV 0.03125mV
ads.begin();
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
/* Explicitly set the ESP8266 to be a WiFi-client, otherwise, it by default,
would try to act as both a client and an access-point and could cause
network-issues with your other WiFi-devices on your WiFi-network. */
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
delay(1500);
//mqttClient.setServer(server, 1883);
mqttClient.setServer("192.168.1.97", 1883);
mqttClient.setCallback(callback);
if (mqttClient.connect("arduino-1")) {
// connection succeeded
Serial.println("Connected to mqtt ");
//boolean r= mqttClient.subscribe("madison/apc/linevoltage");
//Serial.println("subscribe ");
//Serial.println(r);
}
else {
// connection failed
// mqttClient.state() will provide more information
// on why it failed.
Serial.println("Connection failed for mqtt ");
}
}
void reconnect_mqtt()
{
delay(1500);
if (mqttClient.connect("arduino-1")) {
// connection succeeded
Serial.println("Connected to mqtt ");
}
}
void reconnect_wifi()
{
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("reconnecting wifi");
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
//begin old function
float voltageL1, voltageL2, voltageGenL1, voltageGenL2 = 0; //maybe change this datatype to int16_t instead of float
float currentL1, currentL2, currentGenL1, currentGenL2 = 0;
int16_t raw_readingL1, raw_readingL2, raw_readingGenL1, raw_readingGenL2 = 0;
float sumL1, sumL2, sumGenL1, sumGenL2 = 0;
long time_check = millis();
int counter = 0;
while (millis() - time_check < 1000)
{
raw_readingGenL1 = ads.readADC_SingleEnded(0);
raw_readingGenL2 = ads.readADC_SingleEnded(1);
raw_readingL1 = ads.readADC_SingleEnded(2);
raw_readingL2 = ads.readADC_SingleEnded(3);
voltageL1 = raw_readingL1 * multiplier;
voltageL2 = raw_readingL2 * multiplier;
voltageGenL1 = raw_readingGenL1 * multiplier;
voltageGenL2 = raw_readingGenL2 * multiplier;
currentL1 = voltageL1 * FACTOR;
currentL2 = voltageL2 * FACTOR;
currentGenL1 = voltageGenL1 * FACTOR;
currentGenL2 = voltageGenL2 * FACTOR;
sumL1 += sq(currentL1);
sumL2 += sq(currentL2);
sumGenL1 += sq(currentGenL1);
sumGenL2 += sq(currentGenL2);
counter = counter + 1;
}
currentL1 = sqrt(sumL1 / counter);
currentL2 = sqrt(sumL2 / counter);
currentGenL1 = sqrt(sumGenL1 / counter);
currentGenL2 = sqrt(sumGenL2 / counter);
char resultL1[8]; //buffer for my number
dtostrf(currentL1, 5, 3, resultL1);
char resultL2[8]; //buffer for my number
dtostrf(currentL2, 5, 3, resultL2);
char resultGenL1[8]; //buffer for my number
dtostrf(currentGenL1, 5, 3, resultGenL1);
char resultGenL2[8]; //buffer for my number
dtostrf(currentGenL2, 5, 3, resultGenL2);
printMeasure("Irms: ", currentL1, "pin2");
printMeasure("Irms2: ", currentL2, "pin3");
printMeasure("GenL1: ", currentGenL1, "pin0");
printMeasure("GenL2: ", currentGenL2, "pin1");
if (WiFi.status() != WL_CONNECTED) {
Serial.println("not connected");
reconnect_wifi();
}
if (mqttClient.state() != 0) {
Serial.println(mqttClient.state());
reconnect_mqtt();
}
Serial.println("publishing to mqtt broker");
mqttClient.publish("madison/arduinocurrent", resultL1);
mqttClient.publish("madison/arduinocurrent2", resultL2);
mqttClient.publish("madison/generatorL1", resultGenL1);
mqttClient.publish("madison/generatorL2", resultGenL2);
//boolean rc = mqttClient.publish("test", "test message");
//byte outmsg[]={0xff,0xfe};
//Serial.println("publishing bytes");
//rc = mqttClient.publish("testbyte", outmsg,2);
delay(1000);
// Serial.println(WiFi.status()); // 3 is connected
mqttClient.loop();
} //end loop
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.