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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6ed15bb7f142b292a9bb46195295046abc7bc858 | bcb1fdd350b7b904cf5fa9d71fff131066c5069d | /benchmark/runtime/float/list.cpp | 321fa7e7cbc696ce5ab0818404fb1179a35d12d3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Cr4shOv3rrid3/scnlib | 97679caa63dbcb73e47da55080a4f649310f5323 | 72a4bab9e32f2b44593137fba40c54710e20a623 | refs/heads/master | 2022-08-13T07:15:35.474495 | 2022-04-26T18:31:41 | 2022-04-26T18:31:41 | 281,186,906 | 0 | 0 | Apache-2.0 | 2020-07-20T17:46:15 | 2020-07-20T17:46:14 | null | UTF-8 | C++ | false | false | 5,181 | cpp | list.cpp | // Copyright 2017 Elias Kosunen
//
// 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
//
// https://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.
//
// This file is a part of scnlib:
// https://github.com/eliaskosunen/scnlib
#include "bench_float.h"
static void scan_float_list_scn(benchmark::State& state)
{
const auto n = static_cast<size_t>(state.range(0));
auto data = stringified_float_list<float>(n);
std::vector<float> read;
read.reserve(n);
for (auto _ : state) {
auto result = scn::make_result(data);
while (true) {
float i{};
result = scn::scan(result.range(), "{}", i);
if (!result) {
if (result.error() != scn::error::end_of_range) {
state.SkipWithError("Benchmark errored");
}
break;
}
read.push_back(i);
}
}
state.SetBytesProcessed(
static_cast<int64_t>(state.iterations() * n * sizeof(float)));
}
BENCHMARK(scan_float_list_scn)->Arg(16)->Arg(64)->Arg(256);
static void scan_float_list_scn_default(benchmark::State& state)
{
const auto n = static_cast<size_t>(state.range(0));
auto data = stringified_float_list<float>(n);
std::vector<float> read;
read.reserve(n);
for (auto _ : state) {
auto result = scn::make_result(data);
while (true) {
float i{};
result = scn::scan_default(result.range(), i);
if (!result) {
if (result.error() != scn::error::end_of_range) {
state.SkipWithError("Benchmark errored");
}
break;
}
read.push_back(i);
}
}
state.SetBytesProcessed(
static_cast<int64_t>(state.iterations() * n * sizeof(float)));
}
BENCHMARK(scan_float_list_scn_default)->Arg(16)->Arg(64)->Arg(256);
static void scan_float_list_scn_value(benchmark::State& state)
{
const auto n = static_cast<size_t>(state.range(0));
auto data = stringified_float_list<float>(n);
std::vector<float> read;
read.reserve(n);
for (auto _ : state) {
auto result = scn::make_result<scn::expected<float>>(data);
while (true) {
result = scn::scan_value<float>(result.range());
if (!result) {
if (result.error() != scn::error::end_of_range) {
state.SkipWithError("Benchmark errored");
}
break;
}
read.push_back(result.value());
}
}
state.SetBytesProcessed(
static_cast<int64_t>(state.iterations() * n * sizeof(float)));
}
BENCHMARK(scan_float_list_scn_value)->Arg(16)->Arg(64)->Arg(256);
static void scan_float_list_scn_list(benchmark::State& state)
{
const auto n = static_cast<size_t>(state.range(0));
auto data = stringified_float_list<float>(n);
std::vector<float> read;
read.reserve(n);
for (auto _ : state) {
auto result = scn::scan_list(data, read);
if (!result) {
state.SkipWithError("Benchmark errored");
break;
}
}
state.SetBytesProcessed(
static_cast<int64_t>(state.iterations() * n * sizeof(float)));
}
BENCHMARK(scan_float_list_scn_list)->Arg(16)->Arg(64)->Arg(256);
static void scan_float_list_sstream(benchmark::State& state)
{
const auto n = static_cast<size_t>(state.range(0));
auto data = stringified_float_list<float>(n);
std::vector<float> read;
read.reserve(n);
for (auto _ : state) {
std::istringstream iss{data};
float i;
while (iss >> i) {
read.push_back(i);
}
if (iss.fail() && !iss.eof()) {
state.SkipWithError("Benchmark errored");
break;
}
}
state.SetBytesProcessed(
static_cast<int64_t>(state.iterations() * n * sizeof(float)));
}
BENCHMARK(scan_float_list_sstream)->Arg(16)->Arg(64)->Arg(256);
static void scan_float_list_scanf(benchmark::State& state)
{
const auto n = static_cast<size_t>(state.range(0));
auto data = stringified_float_list<float>(n);
std::vector<float> read;
read.reserve(n);
for (auto _ : state) {
auto ptr = &data[0];
while (true) {
float i;
auto ret = scanf_float_n(ptr, i);
if (ret != 1) {
if (ret != EOF) {
state.SkipWithError("Benchmark errored");
}
break;
}
read.push_back(i);
}
}
state.SetBytesProcessed(
static_cast<int64_t>(state.iterations() * n * sizeof(float)));
}
BENCHMARK(scan_float_list_scanf)->Arg(16)->Arg(64)->Arg(256);
|
4d3d2ed7ef824e677f386f1556fee34626bec81e | a6806e3642faddb0fc257142728988e82ba85f82 | /slist.h | 412c0aeedda28b4f289fade4cb0b4078c34a741b | [] | no_license | JaremKaas/dl-list | fde593b7aedf163c43db5eba604f6e9dee82c7ab | caeb12854991e0e5caa780711ebe934a89783d56 | refs/heads/main | 2023-04-17T09:40:06.793955 | 2021-05-09T14:33:41 | 2021-05-09T14:33:41 | 347,627,683 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,219 | h | slist.h | #ifndef SLIST_H_INCLUDED
#define SLIST_H_INCLUDED
#include <iostream>
using std::cout;
using std::endl;
//------- Class List-------//
template <typename Key,typename Info>
class List
{
struct Node
{
Key key; //TO DO: unique data
Info info;
Node* previous;
Node* next;
Node(const Key& newkey,const Info& newinfo)
{
key = newkey;
info = newinfo;
previous = next = nullptr;
}
};
int length;// number of nodes in th list
Node *head; // pointer to the first node
Node *tail; // pointer to the last element
void deleteNode(const Key& key); //USED BY: erase(const Key& key)
//Function to delete element from the list
//length is decremented by 1
Node* findNode(const Key& key); //USED BY: erase(const Key& key)
//Return pointer to Node with given Key or if it does not exists nullptr
public:
List() : head(nullptr), tail(nullptr) , length(0){ } //constructor
List(const List<Key, Info> &scdList); //copy constructor
~List() //destructor
{ clear(); }
bool isListEmpty() const //returns true if list is nonempty otherwise false
{ return !head; }
bool doesNodeExist(const Key& key) //returns true if node exists otherwise false
{ return findNode(key); } // USES: findNode(const Key& key)
void erase(const Key& key) //delete node with given key
{ deleteNode(key); } //USES: findNode(const Key& key), deleteNode(Node* n)
int refLength() const //access length
{ return length;}
Info getInfo(const Key& key)
{
Node* current = findNode(key);
if (current)
return current->info;
}
void clear(); // delete all nodes from the list
// change length to 0
void print() const; //output the list
//inserting
void insert(const Key& newKey, const Info& newInfo);
void join(const List<Key, Info>& fst, const List<Key, Info>& snd);
// select <Key, Info> pair from fst or snd
// where Key value is lower and add this to the result
};
template <typename Key,typename Info>
List<Key, Info>::List(const List<Key, Info> &scdList)
{
head=nullptr;
tail=nullptr;
length=0;
if(scdList.head)
{
Node *current=scdList.head; // traversal node
length=scdList.length; //copy length
Node *newHead=new Node(current->key,current->info); //creation of a new node which head and tail
head=newHead;
tail=newHead;
current=current->next;
while(current) // duplication of the remainings nodes
{
Node *newNode=new Node(current->key,current->info);
tail->next()=newNode;
tail=newNode;
current=current->next;
}
}
}
template <typename Key,typename Info>
void List<Key, Info>::print() const{
if(!head)
cout<<"List is empty."<<endl;
else
{
Node *temp=head;
while (temp)
{
cout << "Key: " << temp->key << " Info: " << temp->info << endl;
temp=temp->next;
}
}
}
template <typename Key, typename Info>
typename List<Key, Info>::Node* List<Key, Info>::findNode(const Key& key){
Node* current = head;
while (current)
{
if (current->key == key)
return current;
current = current->next;
}
return nullptr;
}
template <typename Key, typename Info>
void List<Key, Info>::deleteNode(const Key& key)
{
Node* current = findNode(key);
if (current)
{
if(head == tail) //Case 1 - one element list
{
delete current;
head = nullptr;
tail = nullptr;
length = 0;
}
else //Case 2
{
current->previous->next = current->next;
current->next->previous = current->previous;
if (current == head)
head = current->next;
else if(current == tail)
tail = current->previous;
delete current;
length--;
}
}
}
template <typename Key,typename Info>
void List<Key, Info>::clear()
{
Node *current=head;
while(head)
{
current=head;
head=head->next;
delete current;
length--;
}
}
template <typename Key, typename Info>
void List<Key, Info>::insert(const Key& newKey, const Info& newInfo){
if (doesNodeExist(newKey)) //no duplicates
return;
Node* newNode = new Node(newKey, newInfo); //create new node
if (!head) //Case 1 - list is empty
{
head = newNode;
tail = newNode;
length++;
}
else
{
Node* current = head;//pointer to traverse the list
Node* prevCurrent = nullptr; //pointer just before current
bool found = false;
while (current && !found) //search the list
{ //newNode will be inserted before current
if (current->key > newKey)
found = true;
else
{
prevCurrent = current;
current = current->next;
}
}
newNode->previous = prevCurrent;
newNode->next = current;
if (prevCurrent)
prevCurrent->next = newNode;
if (current)
current->previous = newNode;
if (!current)
tail = newNode;
if (current == head)
head = newNode;
length++;
}
}
template <typename Key,typename Info>
void List<Key, Info>::join(const List<Key, Info>& fst,const List<Key, Info>& snd)
{
if(isListEmpty()==false)
clear();
Node *fstptr=fst.refHead();
Node *sndptr=snd.refHead();
while(fstptr!=nullptr && sndptr!=nullptr )
{
if (fstptr->key < sndptr->key()) // node from fst is added
{
insertElement(fstptr->info, fstptr->key);
fstptr = fstptr->next;
}
else if (fstptr->key==sndptr->key) // since I decide that key is not uniqe both elements are added
{
insertElement(fstptr->info(),fstptr->key);
insertElement(sndptr->info(),sndptr->key);
fstptr = fstptr->next;
sndptr = sndptr->next;
}
else if(fstptr->key>sndptr->key) // node from snd is added
{
insertElement(sndptr->info,sndptr->key);
sndptr=sndptr->next;
}
else
break;
}
if(fstptr!=nullptr && sndptr==nullptr) // the remaining nodes from fst are added
{
while(fstptr!=nullptr)
{
insertElement(fstptr->info,fstptr->key);
fstptr=fstptr->next;
}
}
if(fstptr==nullptr && sndptr!=nullptr) // the remaining nodes from snd are added
{
while(sndptr!=nullptr)
{
insertElement(sndptr->info, sndptr->key);
sndptr=sndptr->next;
}
}
}
#endif // SLIST_H_INCLUDED
|
0a9df00097b24903f82454375c53ad5f911dcf6f | 7375b16527b2a52290f3d0e4a7c01064e5cb2291 | /Game/Game/main.cpp | 338b298d31676f9154d34aecdcf5fc6fed3be96a | [] | no_license | pardovot/cpp | a70cc2b859ee2caaee03a653f0c44af01aec1f7b | bda4795a553ca6e2bb63898e9c9ab97ac0937628 | refs/heads/master | 2020-04-06T12:16:39.388022 | 2018-11-13T21:27:39 | 2018-11-13T21:27:39 | 157,449,119 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 181 | cpp | main.cpp | #include "Game.h"
#include <random>
#include <time.h>
#include <chrono>
int main() {
sf::RenderWindow window(sf::VideoMode(800, 600), "My Game");
Game game(window);
return 0;
}
|
ae0b87543a7e2f7241fb3c61376af3ce2bea1626 | 7579107b4bc53472e9a98d0dfdcc40979687a096 | /apps/exercices/cv13_FaceTracking/cv13_FaceTracking.cpp | 9e99aa68c27285a41cd1b70e3318b44c4b4f0f2a | [] | no_license | cpvrlab/SLProject | d29ef6f62c7e044c0718dd6a1186272108607a2a | f624fbeb7fb69f3904c73ab73810734cac6962ce | refs/heads/master | 2023-06-09T17:25:02.193744 | 2023-05-12T16:27:36 | 2023-05-12T16:27:36 | 30,246,579 | 58 | 30 | null | 2021-01-20T09:56:08 | 2015-02-03T14:26:56 | C++ | UTF-8 | C++ | false | false | 3,742 | cpp | cv13_FaceTracking.cpp | //#############################################################################
// File: cv13_FaceTracking.cpp
// Purpose: Minimal OpenCV application for face Tracking in video
// Source: https://docs.opencv.org/3.0-beta/doc/tutorials/objdetect/cascade_classifier/cascade_classifier.html
// Date: Authumn 2017
//#############################################################################
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/objdetect.hpp>
#include <iostream>
#include <stdio.h>
using namespace std;
using namespace cv;
//----------------------------------------------------------------------------
// Globals
// Note for Visual Studio: You must set the Working Directory to $(TargetDir)
// with: Right Click on Project > Properties > Debugging
static String projectRoot = String(SL_PROJECT_ROOT);
static String face_cascade_name = projectRoot + "/data/opencv/haarcascades/haarcascade_frontalface_alt.xml";
static String eyes_cascade_name = projectRoot + "/data/opencv/haarcascades/haarcascade_eye_tree_eyeglasses.xml";
static CascadeClassifier face_cascade;
static CascadeClassifier eyes_cascade;
static String window_name = "Capture - Face detection";
//-----------------------------------------------------------------------------
void detectFaceAndDisplay(Mat frame)
{
std::vector<Rect> faces;
Mat frame_gray;
cvtColor(frame, frame_gray, COLOR_BGR2GRAY);
equalizeHist(frame_gray, frame_gray);
// Detect faces
face_cascade.detectMultiScale(frame_gray,
faces,
1.1,
2,
0 | CASCADE_SCALE_IMAGE,
Size(30, 30));
for (size_t i = 0; i < faces.size(); i++)
{
rectangle(frame, faces[i], Scalar(255, 0, 255), 2);
Mat faceROI = frame_gray(faces[i]);
std::vector<Rect> eyes;
// In each face, detect eyes
eyes_cascade.detectMultiScale(faceROI,
eyes,
1.1,
2,
0 | CASCADE_SCALE_IMAGE,
Size(30, 30));
for (size_t j = 0; j < eyes.size(); j++)
{
eyes[j].x += faces[i].x;
eyes[j].y += faces[i].y;
rectangle(frame, eyes[j], Scalar(255, 0, 0), 2);
}
}
imshow(window_name, frame);
}
//-----------------------------------------------------------------------------
int main()
{
// Be aware that on Windows not more than one process can access the camera at the time.
// Be aware that on many OS you have to grant access rights to the camera system
VideoCapture capture;
Mat frame;
// 1. Load the cascades
if (!face_cascade.load(face_cascade_name))
{
printf("Error loading face cascade\n");
return -1;
};
if (!eyes_cascade.load(eyes_cascade_name))
{
printf("Error loading eyes cascade\n");
return -1;
};
// 2. Read the video stream
capture.open(0);
if (!capture.isOpened())
{
printf("Error opening video capture\n");
return -1;
}
while (capture.read(frame))
{
if (frame.empty())
{
printf("No captured frame -- Break!");
break;
}
detectFaceAndDisplay(frame);
// Wait for key to exit loop
if (waitKey(10) != -1)
return 0;
}
return 0;
}
//-----------------------------------------------------------------------------
|
2c518718081d7913b61ac496fbb3ab8c3d7fe3bc | 9362688c32682b1fbdb103497ac7a127a98a6e36 | /DAA(Maximum Leaf Spanning Tree/mlstp.cpp | 5aeb1216759673e0ec8f0622910146e96f41f53c | [] | no_license | Lingamaneni-Divya/Maximum-Leaf-Spanning-Tree | d4810640d6258efad307a351331102f89e3f97ba | 1e2a5885634d7159ef43505e2c34e9d9c07e955f | refs/heads/master | 2020-11-30T19:30:56.449085 | 2019-12-30T18:21:34 | 2019-12-30T18:21:34 | 230,463,477 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,545 | cpp | mlstp.cpp | #include<bits/stdc++.h>
using namespace std;
//max leafy forest
int parent[100005]={0};
int d[100005]={0};
int size[100005]={0};
int findparent(int v)
{
if(v==parent[v])
return v;
return parent[v]= findparent(parent[v]);
}
void unionbyrank(int u,int v)
{
int a=findparent(u);
int b=findparent(v);
if(a!=b)
{
if(size[a]>size[b])
{
parent[b]=a;
size[a]=size[a]+size[b];
}
else
{
parent[a]=b;
size[b]=size[a]+size[b];
}
}
}
set<pair<int,int>> buildMaximallyLeafyForest(int noofvertices,vector<int> G[])
{
set<pair<int,int>> F;
int i,j;
for(i =0;i<noofvertices;i++)
{
d[i]=0;
parent[i]=i;
size[i]=1;
}
for(i=0;i<noofvertices;i++)
{
set<pair<int,int> > s1;
int d1=0;
int v=i;
for(j=0;j<G[i].size();j++)
{
int u=G[i][j];
if(findparent(u)!=findparent(v) and s1.find( make_pair(u,findparent(u)) )==s1.end())
{
d1=d1+1;
s1.insert(make_pair(u,findparent(u)) );
}
}
if(d[v]+d1>=3)
{
for(auto it=s1.begin();it!=s1.end();it++)
{
pair<int,int> u=*it;
F.insert(make_pair(v,u.first));
F.insert(make_pair(u.first,v));
unionbyrank(v,u.second);
d[u.first]=d[u.first]+1;
d[v]=d[v]+1;
}
}
}
return F;
}
//kruskal
int parent1[100005]={0};
int size1[100005]={0};
int findparent1(int x)
{
if(parent1[x]==x)
return x;
return parent1[x]=findparent1(parent1[x]);
}
void unionbyrank1(int u,int v)
{
int a=findparent1(u);
int b=findparent1(v);
if(a!=b)
{
if(size1[a]>size1[b])
{
parent1[b]=a;
size1[a]=size1[a]+size1[b];
}
else
{
parent1[a]=b;
size1[b]=size1[a]+size1[b];
}
}
}
set<pair<int,int>> kruskal(int noofvertices,set<pair<int,int>> F)
{
int i;
set<pair<int,int>> spanningtree;
for(i=0;i<noofvertices;i++)
parent1[i]=i;
for(auto it=F.begin();it!=F.end();it++)
{
pair<int,int> p=*it;
int x=p.first;
int y=p.second;
if(findparent1(x)!=findparent1(y))
{
spanningtree.insert(make_pair(x,y));
unionbyrank1(x,y);
}
}
return spanningtree;
}
int main()
{
cout<<"enter no of vertices"<<endl;
int noofvertices;
cin>>noofvertices;
int noofedges;
cin>>noofedges;
vector<pair<int,int>> inputedges;
int i,j;
for(i=0;i<noofedges;i++)
{
int x,y;
cin>>x>>y;
inputedges.push_back(make_pair(x,y));
}
vector<int> G[100005];
for(i=0;i<noofedges;i++)
{
pair<int,int> x=inputedges[i];
int u=x.first;
int v=x.second;
G[u].push_back(v);
G[v].push_back(u);
}
set<pair<int,int> > F;
/*for(i=0;i<noofvertices;i++)
{
for(j=0;j<G[i].size();j++)
{
F.insert(make_pair(i,G[i][j]));
F.insert(make_pair(G[i][j],i));
}
}*/
F=buildMaximallyLeafyForest(noofvertices,G);
set<int> verticesinF;
for(auto it=F.begin();it!=F.end();it++)
{
pair<int,int> x=*it;
verticesinF.insert(x.first);
verticesinF.insert(x.second);
}
for(i=0;i<noofvertices;i++)
{
for(j=0;j<G[i].size();j++)
{
int u=i;
int v=G[i][j];
if(verticesinF.find(u)==verticesinF.end() and verticesinF.find(v)==verticesinF.end())
{
F.insert(make_pair(u,v));
F.insert(make_pair(v,u));
}
else if(findparent(u)!=findparent(v))
{
F.insert(make_pair(u,v));
F.insert(make_pair(v,u));
}
}
}
/*cout<< "result"<<endl;
for(auto it=F.begin();it!=F.end();it++)
{
cout << (*it).first << " "<<(*it).second <<endl;
}*/
set<pair<int,int>> result = kruskal(noofvertices,F);
cout<< "result"<<endl;
for(auto it=result.begin();it!=result.end();it++)
{
cout << (*it).first << " "<<(*it).second <<endl;
}
return 0;
}
|
38ef68442af0e9b75df8a6e1318a94edeeca3128 | f21d8ab6d204b6df1beefdeb10b1090ab279bb10 | /AppleAD741x.cpp | 7c5fcd51e748b3165ca1dbda5739808d264021b1 | [] | no_license | Quantum-Platinum-Cloud/AppleHWSensor | 498af947edfe181fcd61776f59b2b4cbe52021fc | f0b6963c137069c195947949b6f420f5dcf4ffbb | refs/heads/main | 2023-08-02T02:53:26.568112 | 2010-03-29T18:15:13 | 2021-10-06T04:39:46 | 589,308,259 | 1 | 0 | null | 2023-01-15T18:50:55 | 2023-01-15T18:50:55 | null | UTF-8 | C++ | false | false | 31,661 | cpp | AppleAD741x.cpp | /*
* Copyright (c) 2003 Apple Computer, Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* The contents of this file constitute Original Code as defined in and
* are subject to the Apple Public Source License Version 1.1 (the
* "License"). You may not use this file except in compliance with the
* License. Please obtain a copy of the License at
* http://www.apple.com/publicsource and read it before using this file.
*
* This Original Code and all software distributed under the License are
* distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
* License for the specific language governing rights and limitations
* under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
/*
* Copyright (c) 2003 Apple Computer, Inc. All rights reserved.
*
* File: $Id: AppleAD741x.cpp,v 1.9 2005/04/26 23:20:22 mpontil Exp $
*
* DRI: Eric Muehlhausen
*
* $Log: AppleAD741x.cpp,v $
* Revision 1.9 2005/04/26 23:20:22 mpontil
* Fixed a build problem when logging was enabled.
*
* Revision 1.8 2005/04/11 23:38:44 dirty
* [4078743] Properly handle negative temperatures.
*
* Revision 1.7 2004/01/30 23:52:00 eem
* [3542678] IOHWSensor/IOHWControl should use "reg" with version 2 thermal parameters
* Remove AppleSMUSensor/AppleSMUFan since that code will be in AppleSMUDevice class.
* Fix IOHWMonitor, AppleMaxim6690, AppleAD741x to use setPowerState() API instead of
* unsynchronized powerStateWIllChangeTo() API.
*
* Revision 1.6 2003/08/15 23:34:55 eem
* Merged performFunction-leak branch for 3379113, 3379339 and bumped
* version to 1.0.4b1.
*
* Revision 1.5.4.1 2003/08/15 02:26:50 eem
* 3379113, 3379339: leaking objects in performFunction()
*
* Revision 1.5 2003/07/02 22:54:47 dirty
* Add CVS log and id keywords.
*
*/
#include "AppleAD741x.h"
#define super IOService
OSDefineMetaClassAndStructors(AppleAD741x, IOService)
bool AppleAD741x::init( OSDictionary *dict )
{
if (!super::init(dict)) return(false);
fGetSensorValueSym = NULL;
pmRootDomain = NULL;
fPlatformFuncArray = NULL;
fI2CReadBufferSize = 0;
fSleep = false;
return(true);
}
void AppleAD741x::free( void )
{
super::free();
}
bool AppleAD741x::start( IOService *nub )
{
IOService *parentDev, *childNub;
UInt32 fullAddr;
OSData * regprop;
OSArray * nubArray;
const char * drvName;
const OSSymbol *instantiatePFuncs = OSSymbol::withCString("InstantiatePlatformFunctions");
IOReturn retval;
DLOG("AppleAD741x::start - entered\n");
if (!super::start(nub)) return(false);
if (!fGetSensorValueSym)
fGetSensorValueSym = OSSymbol::withCString("getSensorValue");
// Extract bus number and address from reg property
if ((regprop = OSDynamicCast(OSData, nub->getProperty("reg"))) == NULL)
{
DLOG("AppleAD741x::start no reg property!\n");
return(false);
}
else
{
fullAddr = *((UInt32 *)regprop->getBytesNoCopy());
fI2CBus = (UInt8)((fullAddr >> 8) & 0x000000ff);
fI2CAddress = (UInt8)(fullAddr & 0x000000fe);
DLOG("AppleAD741x::start fI2CBus = %02x fI2CAddress = %02x\n",
fI2CBus, fI2CAddress);
}
// Find the i2c driver
if ((parentDev = OSDynamicCast(IOService, nub->getParentEntry(gIODTPlane))) != NULL)
{
DLOG("AppleAD741x::start got parentDev %s\n", parentDev->getName());
}
else
{
DLOG("AppleAD741x::start failed to get parentDev\n");
return(false);
}
drvName = parentDev->getName();
if (strcmp(drvName, "i2c") != 0)
{
DLOG("AppleAD741x::start warning: unexpected i2c device name %s\n", drvName);
}
if ((fI2C_iface = OSDynamicCast(IOService, parentDev->getChildEntry(gIOServicePlane))) != NULL &&
(fI2C_iface->metaCast("PPCI2CInterface") != NULL))
{
DLOG("AppleAD741x::start got fI2C_iface %s\n", fI2C_iface->getName());
}
else
{
DLOG("AppleAD741x::start failed to get fI2C_iface\n");
return(false);
}
// soft-reset the device -- failure could mean that the device is not present or not
// responding
if (softReset() != kIOReturnSuccess)
{
IOLog("AppleAD741x::start failed to soft-reset device at bus %x addr %x\n", fI2CBus, fI2CAddress);
return(false);
}
// parse thermal sensor properties and create nubs
nubArray = parseSensorParamsAndCreateNubs( nub );
if (nubArray == NULL || nubArray->getCount() == 0)
{
DLOG("AppleAD741x::start no thermal sensors found\n");
if (nubArray) nubArray->release();
return(false);
}
// Scan for platform-do-xxx functions
fPlatformFuncArray = NULL;
DLOG("AppleAD741x::start(%x) calling InstantiatePlatformFunctions\n", fI2CAddress);
retval = nub->getPlatform()->callPlatformFunction(instantiatePFuncs, false,
(void *)nub, (void *)&fPlatformFuncArray, (void *)0, (void *)0);
instantiatePFuncs->release();
DLOG("AppleAD741x::start(%x) InstantiatePlatformFunctions returned %ld, pfArray %sNULL\n",
fI2CAddress, retval, fPlatformFuncArray ? "NOT " : "");
if (retval == kIOReturnSuccess && (fPlatformFuncArray != NULL))
{
int i, funcCount;
UInt32 flags;
IOPlatformFunction *func;
bool doSleepWake = false;
funcCount = fPlatformFuncArray->getCount();
DLOG("AppleAD741x::start(%x) iterating platformFunc array, count = %ld\n",
fI2CAddress, funcCount);
for (i = 0; i < funcCount; i++)
{
if (func = OSDynamicCast(IOPlatformFunction, fPlatformFuncArray->getObject(i)))
{
flags = func->getCommandFlags();
DLOG("AppleAD741x::start(%x) got function, flags 0x%08lx, pHandle 0x%08lx\n",
fI2CAddress, flags, func->getCommandPHandle());
// If this function is flagged to be performed at initialization, do it
if (flags & kIOPFFlagOnInit)
performFunction(func, (void *)1, (void *)0, (void *)0, (void *)0);
// If we need to do anything at sleep/wake time, we'll need to set this
// flag so we know to register for notifications
if (flags & (kIOPFFlagOnSleep | kIOPFFlagOnWake))
doSleepWake = true;
}
else
{
// This function won't be used -- generate a warning
DLOG("AppleAD741x::start(%x) not an IOPlatformFunction object\n",
fI2CAddress);
}
}
// Register sleep and wake notifications
if (doSleepWake)
{
mach_timespec_t waitTimeout;
waitTimeout.tv_sec = 30;
waitTimeout.tv_nsec = 0;
pmRootDomain = OSDynamicCast(IOPMrootDomain,
waitForService(serviceMatching("IOPMrootDomain"), &waitTimeout));
if (pmRootDomain != NULL)
{
DLOG("AppleAD741x::start to acknowledge power changes\n");
pmRootDomain->registerInterestedDriver(this);
}
else
{
DLOG("AppleAD741x::start(%x) failed to register PM interest\n",
fI2CAddress);
}
}
}
// tell the world i'm here
registerService();
// tell the world my sensor nubs are here
for (unsigned int index = 0; index < nubArray->getCount(); index++)
{
childNub = OSDynamicCast(IOService, nubArray->getObject(index));
if (childNub) childNub->registerService();
}
nubArray->release();
return(true);
}
void AppleAD741x::stop( IOService *nub )
{
UInt32 flags, i;
IOPlatformFunction *func;
DLOG("AppleAD741x::stop - entered\n");
// Execute any functions flagged as "on termination"
for (i = 0; i < fPlatformFuncArray->getCount(); i++)
{
if (func = OSDynamicCast(IOPlatformFunction, fPlatformFuncArray->getObject(i)))
{
flags = func->getCommandFlags();
if (flags & kIOPFFlagOnTerm)
performFunction(func, (void *)1, (void *)0, (void *)0, (void *)0);
}
}
if (fGetSensorValueSym) { fGetSensorValueSym->release(); fGetSensorValueSym = NULL; }
if (fPlatformFuncArray) { fPlatformFuncArray->release(); fPlatformFuncArray = NULL; }
super::stop( nub );
}
/*******************************************************************************
* Execute a platform function - performFunction()
*******************************************************************************/
bool AppleAD741x::performFunction(IOPlatformFunction *func, void *pfParam1 = 0,
void *pfParam2 = 0, void *pfParam3 = 0, void *pfParam4 = 0)
{
bool success = true; // initialize to success
IOPlatformFunctionIterator *iter;
UInt8 scratchBuffer[READ_BUFFER_LEN], mode = kI2CUnspecifiedMode;
UInt8 *maskBytes, *valueBytes;
unsigned delayMS;
UInt32 cmd, cmdLen, result, param1, param2, param3, param4, param5,
param6, param7, param8, param9, param10;
DLOG ("AppleAD741x::performFunction(%x) - entered\n", fI2CAddress);
if (!func)
return false;
if (!(iter = func->getCommandIterator()))
return false;
while (iter->getNextCommand (&cmd, &cmdLen, ¶m1, ¶m2, ¶m3, ¶m4,
¶m5, ¶m6, ¶m7, ¶m8, ¶m9, ¶m10, &result)) {
if (result != kIOPFNoError) {
DLOG("AppleAD741x::performFunction(%x) error parsing platform function\n", fI2CAddress);
success = false;
goto PERFORM_FUNCTION_EXIT;
}
DLOG ("AppleAD741x::performFunction(%x) - 1)0x%lx, 2)0x%lx, 3)0x%lx, 4)0x%lx, 5)0x%lx,"
"6)0x%lx, 7)0x%lx, 8)0x%lx, 9)0x%lx, 10)0x%lx\n", fI2CAddress, param1, param2, param3,
param4, param5, param6, param7, param8, param9, param10);
switch (cmd)
{
// kCommandReadI2C, kCommandWriteI2C and kCommandRMWI2C are not supported
// because they don't specify the command/subaddress for the max6690
// communication.
case kCommandDelay:
// param1 is in microseconds, but we are going to sleep so use
// milliseconds
delayMS = param1 / 1000;
if (delayMS != 0) IOSleep(delayMS);
DLOG("AppleAD741x::performFunction(%x) delay %u\n", fI2CAddress, delayMS);
break;
case kCommandReadI2CSubAddr:
if (param2 > READ_BUFFER_LEN)
{
IOLog("AppleAD741x::performFunction(%x) r-sub operation too big!\n", fI2CAddress);
success = false;
goto PERFORM_FUNCTION_EXIT;
}
// open the bus
if (!openI2C())
{
IOLog("AppleAD741x::performFunction(%x) r-sub failed to open I2C\n", fI2CAddress);
success = false;
goto PERFORM_FUNCTION_EXIT;
}
else
{
// set the bus mode
if (mode == kI2CUnspecifiedMode || mode == kI2CCombinedMode)
setI2CCombinedMode();
else if (mode == kI2CDumbMode)
setI2CDumbMode();
else if (mode == kI2CStandardMode)
setI2CStandardMode();
else if (mode == kI2CStandardSubMode)
setI2CStandardSubMode();
// do the read
fI2CReadBufferSize = (UInt16) param2;
success = readI2C( (UInt8) param1, fI2CReadBuffer, fI2CReadBufferSize );
DLOG("AppleAD741x::performFunction(%x) r-sub %x len %x, got data", fI2CAddress, param1, param2);
#ifdef MAX6690_DEBUG
char bufDump[256], byteDump[8];
bufDump[0] = '\0';
for (UInt32 i = 0; i < param2; i++)
{
sprintf(byteDump, " %02X", fI2CReadBuffer[i]);
strcat(bufDump, byteDump);
}
DLOG("%s\n", bufDump);
#endif
// close the bus
closeI2C();
}
if (!success) goto PERFORM_FUNCTION_EXIT;
break;
case kCommandWriteI2CSubAddr:
// open the bus
if (!openI2C())
{
IOLog("AppleAD741x::performFunction(%x) w-sub failed to open I2C\n", fI2CAddress);
success = false;
goto PERFORM_FUNCTION_EXIT;
}
else
{
// set the bus mode
if (mode == kI2CUnspecifiedMode || mode == kI2CStandardSubMode)
setI2CStandardSubMode();
else if (mode == kI2CDumbMode)
setI2CDumbMode();
else if (mode == kI2CStandardMode)
setI2CStandardMode();
else if (mode == kI2CCombinedMode)
setI2CCombinedMode();
DLOG("AppleAD741x::performFunction(%x) w-sub %x len %x data", fI2CAddress, param1, param2);
#ifdef MAX6690_DEBUG
char bufDump[256], byteDump[8];
bufDump[0] = '\0';
for (UInt32 i = 0; i < param2; i++)
{
sprintf(byteDump, " %02X", ((UInt8 *)param3)[i]);
strcat(bufDump, byteDump);
}
DLOG("%s\n", bufDump);
#endif
// perform the write
success = writeI2C( (UInt8) param1, (UInt8 *) param3, (UInt16) param2 );
// close the bus
closeI2C();
}
if (!success) goto PERFORM_FUNCTION_EXIT;
break;
case kCommandI2CMode:
// the "mode" variable only persists for the duration of a single
// function, because it is intended to be used as a part of a
// command list.
if ((param1 == kI2CDumbMode) ||
(param1 == kI2CStandardMode) ||
(param1 == kI2CStandardSubMode) ||
(param1 == kI2CCombinedMode))
mode = (UInt8) param1;
DLOG("AppleAD741x::performFunction(%x) mode %x\n", fI2CAddress, mode);
break;
case kCommandRMWI2CSubAddr:
// check parameters
if ((param2 > fI2CReadBufferSize) || // number of mask bytes
(param3 > fI2CReadBufferSize) || // number of value bytes
(param4 > fI2CReadBufferSize) || // number of transfer bytes
(param3 > param2)) // param3 is not actually used, we assume that
// any byte that is masked also gets a value
// OR'ed in
{
IOLog("AppleAD741x::performFunction(%x) invalid mw-sub cycle\n", fI2CAddress);
success = false;
goto PERFORM_FUNCTION_EXIT;
}
// set up buffers
maskBytes = (UInt8 *) param5;
valueBytes = (UInt8 *) param6;
// apply mask and OR in value -- follow reference implementation in
// AppleHWClock driver
for (unsigned int index = 0; index < param2; index++)
{
scratchBuffer[index] = (valueBytes[index] & maskBytes[index]);
scratchBuffer[index] |= (fI2CReadBuffer[index] & ~maskBytes[index]);
}
// open the bus
if (!openI2C())
{
IOLog("AppleAD741x::performFunction(%x) mw-sub failed to open I2C\n", fI2CAddress);
success = false;
goto PERFORM_FUNCTION_EXIT;
}
else
{
// set the bus mode
if (mode == kI2CUnspecifiedMode || mode == kI2CCombinedMode)
setI2CCombinedMode();
else if (mode == kI2CDumbMode)
setI2CDumbMode();
else if (mode == kI2CStandardMode)
setI2CStandardMode();
else if (mode == kI2CStandardSubMode)
setI2CStandardSubMode();
DLOG("AppleAD741x::performFunction(%x) mw-sub %x len %x data", fI2CAddress, param1, param4);
#ifdef MAX6690_DEBUG
char bufDump[256], byteDump[8];
bufDump[0] = '\0';
for (UInt32 i = 0; i < param4; i++)
{
sprintf(byteDump, " %02X", scratchBuffer[i]);
strcat(bufDump, byteDump);
}
DLOG("%s\n", bufDump);
#endif
// write out data
success = writeI2C( (UInt8) param1, scratchBuffer, (UInt16) param4 );
// close the bus
closeI2C();
}
if (!success) goto PERFORM_FUNCTION_EXIT;
break;
default:
DLOG ("AppleAD741x::performFunction - bad command %ld\n", cmd);
success = false;
goto PERFORM_FUNCTION_EXIT;
}
}
PERFORM_FUNCTION_EXIT:
iter->release();
DLOG ("AppleAD741x::performFunction - done - returning %s\n", success ? "TRUE" : "FALSE");
return(success);
}
/*******************************************************************************
* IOHWSensor entry point - callPlatformFunction()
*******************************************************************************/
IOReturn AppleAD741x::callPlatformFunction(const OSSymbol *functionName,
bool waitForFunction, void *param1, void *param2,
void *param3, void *param4)
{
UInt32 id = (UInt32)param1;
UInt32 *value_buf = (UInt32 *)param2;
SInt32 *temp_buf = (SInt32 *)param2;
bool found = false;
UInt8 i;
DLOG("AppleAD741x::callPlatformFunction %s %s %08lx %08lx %08lx %08lx\n",
functionName->getCStringNoCopy(), waitForFunction ? "TRUE" : "FALSE",
(UInt32) param1, (UInt32) param2, (UInt32) param3, (UInt32) param4);
if (functionName->isEqualTo(fGetSensorValueSym) == true)
{
if (fSleep == true)
return(kIOReturnOffline);
if (temp_buf == NULL)
return(kIOReturnBadArgument);
for (i=0; i<5; i++)
{
if (id == fHWSensorIDMap[i])
{
found = true;
break;
}
}
if (found)
{
if (i == 0)
return(getTemperature(temp_buf));
else
return(getADC(i, value_buf));
}
}
return(super::callPlatformFunction(functionName, waitForFunction,
param1, param2, param3, param4));
}
/*******************************************************************************
* Create and set up sensor nubs - parseSensorParamsAndCreateNubs()
*******************************************************************************/
OSArray *AppleAD741x::parseSensorParamsAndCreateNubs(IOService *nub)
{
IOService *childNub;
OSData *tmp_osdata, *tempNubName, *adcNubName;
OSArray *nubArray = NULL;
unsigned i, n_sensors = 0;
UInt32 version, *id = NULL, *zone = NULL, *polling_period = NULL;
const char *type = NULL, *location = NULL;
char work[32];
// Get the version
tmp_osdata = OSDynamicCast(OSData,
nub->getProperty(kDTSensorParamsVersionKey));
if (tmp_osdata == NULL)
{
DLOG("AppleAD741x::parseSensorParamsAndCreateNubs no param version\n");
return(NULL);
}
version = *((UInt32 *)tmp_osdata->getBytesNoCopy());
// Get pointers inside the libkern containers for all properties
tmp_osdata = OSDynamicCast(OSData,
nub->getProperty(kDTSensorIDKey));
if (tmp_osdata == NULL)
{
DLOG("AppleAD741x::parseSensorParamsAndCreateNubs no ids\n");
return(NULL);
}
n_sensors = tmp_osdata->getLength() / sizeof(UInt32);
// the AD7417 has one temp channel and four ADC channels. If there are more
// sensors than this indicated, something is wacky.
if (n_sensors > 5)
{
DLOG("AppleAD741x::parseSensorParamsAndCreateNubs too many sensors %u\n", n_sensors);
return(NULL);
}
id = (UInt32 *)tmp_osdata->getBytesNoCopy();
tmp_osdata = OSDynamicCast(OSData,
nub->getProperty(kDTSensorZoneKey));
if (tmp_osdata == NULL)
{
DLOG("AppleAD741x::parseSensorParamsAndCreateNubs no zones\n");
return(NULL);
}
zone = (UInt32 *)tmp_osdata->getBytesNoCopy();
tmp_osdata = OSDynamicCast(OSData,
nub->getProperty(kDTSensorTypeKey));
if (tmp_osdata == NULL)
{
DLOG("AppleAD741x::parseSensorParamsAndCreateNubs no types\n");
return(NULL);
}
type = (const char *)tmp_osdata->getBytesNoCopy();
tmp_osdata = OSDynamicCast(OSData,
nub->getProperty(kDTSensorLocationKey));
if (tmp_osdata == NULL)
{
DLOG("AppleAD741x::parseSensorParamsAndCreateNubs no locations\n");
return(NULL);
}
location = (const char *)tmp_osdata->getBytesNoCopy();
// Polling Period key is not required
tmp_osdata = OSDynamicCast(OSData,
nub->getProperty(kDTSensorPollingPeriodKey));
if (tmp_osdata != NULL)
{
polling_period = (UInt32 *)tmp_osdata->getBytesNoCopy();
DLOG("AppleAD741x::parseSensorParamsAndCreateNubs polling period %lx\n", polling_period);
}
// Create an OSData representation of the sensor nub name string
strcpy(work, kHWTempSensorNubName);
tempNubName = OSData::withBytes(work, strlen(work) + 1);
if (tempNubName == NULL) return(0);
strcpy(work, kHWADCSensorNubName);
adcNubName = OSData::withBytes(work, strlen(work) + 1);
if (adcNubName == NULL) return(0);
// Iterate through the sensors and create their nubs
for (i=0; i<n_sensors; i++)
{
DLOG("AppleAD741x::parseSensorParamsAndCreateNubs child nub %u\n", i);
childNub = OSDynamicCast(IOService,
OSMetaClass::allocClassWithName("IOService"));
if (!childNub || !childNub->init())
continue;
childNub->attach(this);
// Make the mapping for this sensor-id
fHWSensorIDMap[i] = id[i];
// set name, device_type and compatible
if (strcmp(type, "adc") == 0)
{
childNub->setName(kHWADCSensorNubName);
childNub->setProperty("name", adcNubName);
childNub->setProperty("compatible", adcNubName);
childNub->setProperty("device_type", adcNubName);
}
else //if (strcmp(type, "temperature") == 0 || strcmp(type, "temp") == 0)
{
childNub->setName(kHWTempSensorNubName);
childNub->setProperty("name", tempNubName);
childNub->setProperty("compatible", tempNubName);
childNub->setProperty("device_type", tempNubName);
}
// set the sensor properties
childNub->setProperty(kHWSensorParamsVersionKey, &version, sizeof(UInt32));
childNub->setProperty(kHWSensorIDKey, &id[i], sizeof(UInt32));
childNub->setProperty(kHWSensorZoneKey, &zone[i], sizeof(UInt32));
childNub->setProperty(kHWSensorTypeKey, type);
type += strlen(type) + 1;
childNub->setProperty(kHWSensorLocationKey, location);
location += strlen(location) + 1;
if (polling_period && polling_period[i] != kHWSensorPollingPeriodNULL)
childNub->setProperty(kHWSensorPollingPeriodKey, &polling_period[i],
sizeof(UInt32));
// add this nub to the array
if (nubArray == NULL)
{
nubArray = OSArray::withObjects((const OSObject **) &childNub, 1);
}
else
{
nubArray->setObject( childNub );
}
}
tempNubName->release();
adcNubName->release();
return(nubArray);
}
#pragma mark -
#pragma mark *** Software Reset ***
#pragma mark -
/*******************************************************************************
* Read sensor channels from the device
*******************************************************************************/
IOReturn AppleAD741x::softReset( void )
{
UInt8 val;
/* According to the data sheet, software can simulate a reset by writing default
values to the config, config2, t_oti and t_hyst registers. In practice, it
has been enough to only set config and config2, and this has the added
advantage of not clobbering the overtemp and hysteresis values if we have
to reset in the middle of operation. */
if (!openI2C())
{
DLOG("AppleAD741x::softReset failed to open bus\n");
goto failNoClose;
}
// Set the config1 and config2 registers
if (!setI2CStandardSubMode())
{
DLOG("AppleAD741x::softReset failed to set bus mode\n");
goto failClose;
}
val = 0;
if (!writeI2C( kConfig1Reg, &val, 1 ))
{
DLOG("AppleAD741x::softReset failed to write cfg1 reg\n");
goto failClose;
}
val = 0;
if (!writeI2C( kConfig2Reg, &val, 1 ))
{
DLOG("AppleAD741x::softReset failed to write cfg2 reg\n");
goto failClose;
}
// Read back the config1 register (read operations clear fault conditions)
if (!setI2CCombinedMode())
{
DLOG("AppleAD741x::softReset failed to set bus mode\n");
goto failClose;
}
// don't care what the value is, just want to make sure the read succeeds
if (!readI2C( kConfig1Reg, &val, 1 ))
{
DLOG("AppleAD741x::softReset failed to read back cfg1 reg\n");
goto failClose;
}
closeI2C();
return(kIOReturnSuccess);
failClose:
closeI2C();
failNoClose:
return(kIOReturnError);
}
#pragma mark -
#pragma mark *** Read Sensor Channels ***
#pragma mark -
/*******************************************************************************
* Read sensor channels from the device
*******************************************************************************/
IOReturn AppleAD741x::getTemperature( SInt32 * temp )
{
UInt8 bytes[2];
SInt16 reading;
bool success = false;
// Open the bus - this grabs a mutex in the I2C driver so it's thread-safe
if (!openI2C())
{
DLOG("AppleAD741x::getTemperature error opening bus!\n");
}
else
{
do
{
// reads should be performed in combined mode
if (!setI2CCombinedMode())
{
DLOG("AppleAD741x::getTemperature failed to set bus mode!\n");
break;
}
if (!readI2C( kTempValueReg, bytes, 2 ))
{
DLOG("AppleAD741x::getTemperature read temp failed!\n");
break;
}
success = true;
} while (false);
closeI2C();
}
if (success)
{
DLOG("AppleAD741x::getTemperature got bytes 0x%02X 0x%02X\n", bytes[0], bytes[1]);
reading = *((SInt16 *) bytes);
// temperature is fixed point 8.2 in most significant 10 bits of the two bytes that were read
*temp = ( ( ( SInt16 ) ( reading & 0xFFC0 ) ) << 8 );
return(kIOReturnSuccess);
}
else
{
*temp = -1;
return(kIOReturnError);
}
}
IOReturn AppleAD741x::getADC( UInt8 channel, UInt32 * sample )
{
UInt8 cfg1, tmpByte, bytes[2];
UInt16 rawSample;
bool success = false;
if (channel < kAD1Channel || channel > kAD4Channel)
{
DLOG("AppleAD741x::getADC invalid channel\n");
return(kIOReturnBadArgument);
}
DLOG("AppleAD741x::getADC reading channel %u\n", channel);
// Open the bus - this grabs a mutex in the I2C driver so it's thread-safe
if (!openI2C())
{
DLOG("AppleAD741x::getADC error opening bus!\n");
}
else
{
do
{
// reads should be performed in combined mode
if (!setI2CCombinedMode())
{
DLOG("AppleAD741x::getADC failed to set bus mode for read!\n");
break;
}
if (!readI2C( kConfig1Reg, &cfg1, 1 ))
{
DLOG("AppleAD741x::getADC read cfg1 failed!\n");
break;
}
// set the channel selection bits
tmpByte = channel << kCfg1ChannelShift;
DLOG("AppleAD741x::getADC read cfg1 0x%02X\n", cfg1);
cfg1 = (cfg1 & ~kCfg1ChannelMask) | (tmpByte & kCfg1ChannelMask);
DLOG("AppleAD741x::getADC new cfg1 0x%02X\n", cfg1);
// write it back out to the cfg register
if (!setI2CStandardSubMode())
{
DLOG("AppleAD741x::getADC failed to set bus mode for write!\n");
break;
}
if (!writeI2C( kConfig1Reg, &cfg1, 1 ))
{
DLOG("AppleAD741x::getADC write cfg1 failed!\n");
break;
}
// now read the adc register to get the sample
if (!setI2CCombinedMode())
{
DLOG("AppleAD741x::getADC failed to set bus mode for read!\n");
break;
}
if (!readI2C( kADCReg, bytes, 2 ))
{
DLOG("AppleAD741x::getADC read adc reg failed!\n");
break;
}
success = true;
} while (false);
closeI2C();
}
if (success)
{
DLOG("AppleAD741x::getADC got bytes 0x%02X 0x%02X\n", bytes[0], bytes[1]);
rawSample = *((UInt16 *) bytes);
*sample = ((UInt32)rawSample) >> 6; // shift out bits [5:0] which are unused
return(kIOReturnSuccess);
}
else
{
*sample = 0xFFFFFFFF;
return(kIOReturnError);
}
}
#pragma mark -
#pragma mark *** Power Management ***
#pragma mark -
/*******************************************************************************
* Power Management callbacks and handlers
*******************************************************************************/
IOReturn AppleAD741x::powerStateWillChangeTo (IOPMPowerFlags theFlags, unsigned long, IOService*)
{
if ( ! (theFlags & IOPMPowerOn) ) {
// Sleep sequence:
DLOG("AppleAD741x::powerStateWillChangeTo - sleep\n");
doSleep();
} else {
// Wake sequence:
DLOG("AppleAD741x::powerStateWillChangeTo - wake\n");
doWake();
}
return IOPMAckImplied;
}
void AppleAD741x::doSleep(void)
{
UInt32 flags, i;
IOPlatformFunction *func;
fSleep = true;
// Execute any functions flagged as "on sleep"
for (i = 0; i < fPlatformFuncArray->getCount(); i++)
{
if (func = OSDynamicCast(IOPlatformFunction, fPlatformFuncArray->getObject(i)))
{
flags = func->getCommandFlags();
if (flags & kIOPFFlagOnSleep)
performFunction(func, (void *)1, (void *)0, (void *)0, (void *)0);
}
}
}
void AppleAD741x::doWake(void)
{
UInt32 flags, i;
IOPlatformFunction *func;
// Execute any functions flagged as "on wake"
for (i = 0; i < fPlatformFuncArray->getCount(); i++)
{
if (func = OSDynamicCast(IOPlatformFunction, fPlatformFuncArray->getObject(i)))
{
flags = func->getCommandFlags();
if (flags & kIOPFFlagOnWake)
performFunction(func, (void *)1, (void *)0, (void *)0, (void *)0);
}
}
fSleep = false;
}
#pragma mark -
#pragma mark *** I2C Helpers ***
#pragma mark -
/*******************************************************************************
* I2C Helpers
*******************************************************************************/
bool AppleAD741x::openI2C( void )
{
UInt32 passBus;
IOReturn status;
DLOG("AppleAD741x::openI2C - entered\n");
if (fI2C_iface == NULL)
return false;
// Open the interface
passBus = (UInt32) fI2CBus; // cast from 8-bit to machine long word length
if ((status = (fI2C_iface->callPlatformFunction(kOpenI2Cbus, false, (void *) passBus, NULL, NULL, NULL)))
!= kIOReturnSuccess)
{
DLOG("AppleAD741x::openI2C failed, status = %08lx\n", (UInt32) status);
return(false);
}
return(true);
}
void AppleAD741x::closeI2C( void )
{
IOReturn status;
DLOG("AppleAD741x::closeI2C - entered\n");
if (fI2C_iface == NULL) return;
if ((status = (fI2C_iface->callPlatformFunction(kCloseI2Cbus, false, NULL, NULL, NULL, NULL)))
!= kIOReturnSuccess)
{
DLOG("AppleAD741x::closeI2C failed, status = %08lx\n", (UInt32) status);
}
}
bool AppleAD741x::setI2CDumbMode( void )
{
IOReturn status;
DLOG("AppleAD741x::setI2CDumbMode - entered\n");
if ((fI2C_iface == NULL) ||
(status = (fI2C_iface->callPlatformFunction(kSetDumbMode, false, NULL, NULL, NULL, NULL)))
!= kIOReturnSuccess)
{
DLOG("AppleAD741x::setI2CDumbMode failed, status = %08lx\n", (UInt32) status);
return(false);
}
return(true);
}
bool AppleAD741x::setI2CStandardMode( void )
{
IOReturn status;
DLOG("AppleAD741x::setI2CStandardMode - entered\n");
if ((fI2C_iface == NULL) ||
(status = (fI2C_iface->callPlatformFunction(kSetStandardMode, false, NULL, NULL, NULL, NULL)))
!= kIOReturnSuccess)
{
DLOG("AppleAD741x::setI2CStandardMode failed, status = %08lx\n", (UInt32) status);
return(false);
}
return(true);
}
bool AppleAD741x::setI2CStandardSubMode( void )
{
IOReturn status;
DLOG("AppleAD741x::setI2CStandardSubMode - entered\n");
if ((fI2C_iface == NULL) ||
(status = (fI2C_iface->callPlatformFunction(kSetStandardSubMode, false, NULL, NULL, NULL, NULL)))
!= kIOReturnSuccess)
{
DLOG("AppleAD741x::setI2CStandardSubMode failed, status = %08lx\n", (UInt32) status);
return(false);
}
return(true);
}
bool AppleAD741x::setI2CCombinedMode( void )
{
IOReturn status;
DLOG("AppleAD741x::setI2CCombinedMode - entered\n");
if ((fI2C_iface == NULL) ||
(status = (fI2C_iface->callPlatformFunction(kSetCombinedMode, false, NULL, NULL, NULL, NULL)))
!= kIOReturnSuccess)
{
DLOG("AppleAD741x::setI2CCombinedMode failed, status = %08lx\n", (UInt32) status);
return(false);
}
return(true);
}
bool AppleAD741x::writeI2C(UInt8 subAddr, UInt8 *data, UInt16 size)
{
UInt32 passAddr, passSubAddr, passSize;
unsigned int retries = 0;
IOReturn status;
DLOG("AppleAD741x::writeI2C - entered\n");
if (fI2C_iface == NULL || data == NULL || size == 0)
return false;
passAddr = (UInt32) (fI2CAddress >> 1);
passSubAddr = (UInt32) subAddr;
passSize = (UInt32) size;
while ((retries < kNumRetries) &&
((status = (fI2C_iface->callPlatformFunction(kWriteI2Cbus, false, (void *) passAddr,
(void *) passSubAddr, (void *) data, (void *) passSize))) != kIOReturnSuccess))
{
DLOG("AppleAD741x::writeI2C transaction failed, status = %08lx\n", (UInt32) status);
retries++;
}
if (retries >= kNumRetries)
return(false);
else
return(true);
}
bool AppleAD741x::readI2C(UInt8 subAddr, UInt8 *data, UInt16 size)
{
UInt32 passAddr, passSubAddr, passSize;
unsigned int retries = 0;
IOReturn status;
DLOG("AppleAD741x::readI2C \n");
if (fI2C_iface == NULL || data == NULL || size == 0)
return false;
passAddr = (UInt32) (fI2CAddress >> 1);
passSubAddr = (UInt32) subAddr;
passSize = (UInt32) size;
while ((retries < kNumRetries) &&
((status = (fI2C_iface->callPlatformFunction(kReadI2Cbus, false, (void *) passAddr,
(void *) passSubAddr, (void *) data, (void *) passSize))) != kIOReturnSuccess))
{
DLOG("AppleAD741x::readI2C transaction failed, status = %08lx\n", (UInt32) status);
retries++;
}
if (retries >= kNumRetries)
return(false);
else
return(true);
}
|
ad8883cdb14768f1d72013e9298a66948b5461ba | a07d3a2e13df59bb9b47e0e789b11fa72a2197db | /LRUCache/CPP/LRUCache.cpp | 78202790333ec516f4f794f60ea9d0e3a09fbabd | [] | no_license | wcsanders1/LeetCode | 38647965fd58927f59d375b72bbf38e4c901c3c8 | b569d6cca85e7b2bdb567e3db7422e9b0aa72aa3 | refs/heads/master | 2023-08-27T23:54:48.139831 | 2023-08-22T09:47:16 | 2023-08-22T09:47:16 | 253,105,355 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,582 | cpp | LRUCache.cpp | // https://leetcode.com/problems/lru-cache/
#include <vector>
#include <unordered_set>
#include <unordered_map>
#include <queue>
using namespace std;
class Node
{
public:
Node *prev;
Node *next;
int value;
int key;
};
class LRUCache
{
public:
LRUCache(int capacity)
{
this->capacity = capacity;
count = 0;
start = nullptr;
end = nullptr;
}
int get(int key)
{
if (m.count(key) == 0)
{
return -1;
}
resetStart(key);
return m[key]->value;
}
void put(int key, int value)
{
if (m.count(key) == 0)
{
auto t = start;
start = new Node();
start->value = value;
start->key = key;
start->next = t;
if (t != nullptr)
{
t->prev = start;
}
m[key] = start;
count++;
}
else
{
m[key]->value = value;
resetStart(key);
}
if (count == 1)
{
end = start;
}
if (count > capacity)
{
auto t = end;
int k = end->key;
end = end->prev;
end->next = nullptr;
m.erase(t->key);
delete t;
count--;
}
}
Node *start;
Node *end;
int capacity;
int count;
unordered_map<int, Node *> m;
private:
void resetStart(int key)
{
if (key == this->start->key)
{
return;
}
auto t = m[key];
t->prev->next = t->next;
if (t->next != nullptr)
{
t->next->prev = t->prev;
}
auto s = start;
start = t;
s->prev = t;
t->next = s;
if (end->key == t->key)
{
end = t->prev;
}
t->prev = nullptr;
}
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache* obj = new LRUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/
int main()
{
auto cache = new LRUCache(2);
cache->put(1, 1);
cache->put(2, 2);
int result1 = cache->get(1);
cache->put(3, 3);
int result2 = cache->get(2);
cache->put(4, 4);
int result3 = cache->get(1);
int result4 = cache->get(3);
int result5 = cache->get(4);
auto cache2 = new LRUCache(1);
cache2->put(2, 1);
int result2_1 = cache2->get(2);
auto cache3 = new LRUCache(3);
cache3->put(1, 1);
cache3->put(2, 2);
cache3->put(3, 3);
cache3->put(4, 4);
int result3_1 = cache3->get(4);
int result3_2 = cache3->get(3);
int result3_3 = cache3->get(2);
int result3_4 = cache3->get(1);
cache3->put(5, 5);
int result3_5 = cache3->get(1);
int result3_6 = cache3->get(2);
int result3_7 = cache3->get(3);
int result3_8 = cache3->get(4);
int result3_9 = cache3->get(5);
} |
9d8944b5709d1ca3ee3957d0950fa8e7b63c1dae | 877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a | /app/src/main/cpp/dir7941/dir29315/dir29712/dir29713/dir30015/file30089.cpp | 582c5fa3a29fba8b33b70f4fa582dad45471611f | [] | no_license | tgeng/HugeProject | 829c3bdfb7cbaf57727c41263212d4a67e3eb93d | 4488d3b765e8827636ce5e878baacdf388710ef2 | refs/heads/master | 2022-08-21T16:58:54.161627 | 2020-05-28T01:54:03 | 2020-05-28T01:54:03 | 267,468,475 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 115 | cpp | file30089.cpp | #ifndef file30089
#error "macro file30089 must be defined"
#endif
static const char* file30089String = "file30089"; |
628366ded23b09c4a178775487ce84039088083c | 08025500a6be10833b54fc3b5ba26af8cd156ecc | /4. Graph/Minimum Spanning Tree/Variants/00534.cpp | fdcff8aa27d4350adcf03634bcbcfeb1142f2aee | [] | no_license | silvercobraa/competitive-programming | 6d597f6e67108e0eb40af8d15d7a6c9007edd884 | da09e2aa4796681a01cc5d3fed71e6f9beac57eb | refs/heads/master | 2022-05-09T01:17:14.010457 | 2020-11-27T15:19:50 | 2020-11-27T15:19:50 | 143,571,603 | 0 | 0 | null | 2020-11-27T15:19:51 | 2018-08-05T00:13:27 | C++ | UTF-8 | C++ | false | false | 1,960 | cpp | 00534.cpp | #include <iostream>
#include <vector>
#include <set>
#include <cmath>
using namespace std;
class UF {
private:
vector<int> parent;
vector<int> size;
public:
UF (int n) {
parent = vector<int>(n);
size = vector<int>(n);
for (size_t i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
}
int find(int x) {
return parent[x] = parent[x] == x ? x : find(parent[x]);
}
void merge(int x, int y) {
int px = find(x);
int py = find(y);
if (size[px] > size[py]) {
parent[py] = px;
size[px] += size[py];
}
else {
parent[px] = py;
size[py] += size[px];
}
}
};
int dfs(vector<vector<pair<int,int>>>& tree, int parent, int weight, int node) {
if (node == 1) {
// cout << weight << endl;
return weight;
}
for (auto par: tree[node]) {
if (par.second != parent) {
int rec = dfs(tree, node, par.first, par.second);
if (rec != 0) {
// cout << par.first << endl;
return max(weight, rec);
}
}
}
return 0;
}
int main(int argc, char const *argv[]) {
int n;
int scenario = 1;
for (cin >> n; n != 0; cin >> n) {
vector<pair<int, int>> V(n);
for (int i = 0; i < n; i++) {
int a, b;
cin >> a >> b;
V[i] = {a, b};
}
set<pair<int, pair<int,int>>> E;
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
int dx = V[i].first - V[j].first;
int dy = V[i].second - V[j].second;
int dist = dx*dx + dy*dy;
E.insert({dist, {i, j}});
}
}
UF uf(n);
vector<vector<pair<int,int>>> tree(n);
while (not E.empty()) {
auto e = E.begin();
int w = e->first;
int a = e->second.first;
int b = e->second.second;
if (uf.find(a) != uf.find(b)) {
tree[a].push_back({w, b});
tree[b].push_back({w, a});
uf.merge(uf.find(a), uf.find(b));
}
E.erase(e);
}
int ans = dfs(tree, -1, 0, 0);
// cout << "ANS:" << ans << endl;
printf("Scenario #%d\n", scenario);
printf("Frog Distance = %.3lf\n\n", sqrt(ans));
scenario++;
}
return 0;
}
|
59d44ab3698a321165e5bf4b5e64a71e966cd2f1 | 2d0bada349646b801a69c542407279cc7bc25013 | /src/vai_library/medicalsegmentation/test/test_medicalsegmentation.cpp | 8fdf16625f10ae0d41b64892cabe7930d9f8b190 | [
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"BSD-3-Clause-Open-MPI",
"LicenseRef-scancode-free-unknown",
"Libtool-exception",
"GCC-exception-3.1",
"LicenseRef-scancode-mit-old-style",
"OFL-1.1",
"JSON",
"LGPL-2.1-only",
"LGPL-2.0-or-later",
"ICU",
"LicenseRef-scancode-other-permissive",
"GPL-2.0-or-later",
"GPL-3.0-only",
"LicenseRef-scancode-issl-2018",
"MIT",
"LGPL-2.1-or-later",
"LicenseRef-scancode-unicode",
"LGPL-3.0-only",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-3.0-or-later",
"Zlib",
"BSD-Source-Code",
"ClArtistic",
"LicenseRef-scancode-unknown-license-reference",
"ISC",
"NCSA",
"LicenseRef-scancode-proprietary-license",
"GPL-2.0-only",
"CC-BY-4.0",
"FSFULLR",
"Minpack",
"Unlicense",
"BSL-1.0",
"NAIST-2003",
"Apache-2.0",
"LicenseRef-scancode-protobuf",
"LicenseRef-scancode-public-domain",
"Libpng",
"Spencer-94",
"BSD-2-Clause",
"Intel",
"GPL-1.0-or-later",
"MPL-2.0"
] | permissive | Xilinx/Vitis-AI | 31e664f7adff0958bb7d149883ab9c231efb3541 | f74ddc6ed086ba949b791626638717e21505dba2 | refs/heads/master | 2023-08-31T02:44:51.029166 | 2023-07-27T06:50:28 | 2023-07-27T06:50:28 | 215,649,623 | 1,283 | 683 | Apache-2.0 | 2023-08-17T09:24:55 | 2019-10-16T21:41:54 | Python | UTF-8 | C++ | false | false | 3,608 | cpp | test_medicalsegmentation.cpp | /*
* Copyright 2022-2023 Advanced Micro Devices Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <sys/stat.h>
#include <iostream>
#include <opencv2/opencv.hpp>
#include <sstream>
#include <vector>
#include <vitis/ai/medicalsegmentation.hpp>
using namespace cv;
using namespace std;
Scalar colors[] = {Scalar(255, 0, 0), Scalar(0, 255, 0), Scalar(0, 0, 255),
Scalar(255, 0, 255), Scalar(0, 255, 255)};
std::vector<string> classTypes = {"BE", "cancer", "HGD", "polyp", "suspicious"};
int main(int argc, char *argv[]) {
if (argc < 2) {
std::cout << " usage: " << argv[0] << " <img_url>" << std::endl; //
abort();
}
Mat img = cv::imread(argv[1]);
if (img.empty()) {
cerr << "cannot load " << argv[1] << endl;
abort();
}
std::string name(argv[1]);
std::string filenamepart1 = name.substr(name.find_last_of('/') + 1);
filenamepart1 = filenamepart1.substr(0, filenamepart1.find_last_of('.'));
auto seg =
vitis::ai::MedicalSegmentation::create("FPN_Res18_Medical_segmentation");
if (!seg) { // supress coverity complain
std::cerr <<"create error\n";
abort();
}
cv::Size size_orig = img.size();
cv::Mat img_save;
auto result = seg->run(img);
/* simple version
for(int i=0; i<5; i++) {
for (auto y = 0; y < result.segmentation[i].rows; y++) {
for (auto x = 0; x < result.segmentation[i].cols; x++) {
result.segmentation[i].at<uchar>(y, x) *= 100;
}
}
std::stringstream ss; ss << "segres_" << i << ".jpg" ;
cv::imwrite(ss.str(), result.segmentation[i]); // Save the result as an
image;
}
*/
// if dir doesn't exist, create it.
for (int i = 0; i < 6; i++) {
std::string path = "results";
if (i != 0) {
path = path + "/" + classTypes[i - 1];
}
auto ret = mkdir(path.c_str(), 0777);
if (!(ret == 0 || (ret == -1 && EEXIST == errno))) {
std::cout << "error occured when mkdir " << path << std::endl;
return -1;
}
}
for (int i = 0; i < 5; i++) {
std::string fname("results/" + classTypes[i] + "/" + filenamepart1 +
".png");
cv::resize(result.segmentation[i], img_save, size_orig, 0, 0,
cv::INTER_LINEAR);
cv::imwrite(fname, img_save); // Save the result as an image;
auto img_true = cv::imread(fname, 0); // gray
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
cv::findContours(img_true, contours, hierarchy, cv::RETR_TREE,
cv::CHAIN_APPROX_SIMPLE);
if (contours.size()) {
cv::drawContours(img, contours, -1, colors[i], 3);
auto midVal = int(contours[0].size()/2);
cv::putText(img,
classTypes[i],
cv::Point(contours[0][midVal].x, contours[0][midVal].y),
cv::FONT_HERSHEY_SIMPLEX,
1,
cv::Scalar(255,255,255),
2,
cv::LINE_AA);
}
}
std::string fname("results/" + filenamepart1 + "_overlayer.png");
cv::imwrite(fname, img);
return 0;
}
|
631ea3686daaa603471e4901cc76acabba478cfb | 32aac3f245804748bceba053f0da2838fe7c36de | /bfss_sn/bfss_node.h | aba3329f37053f0bb7a618cd0f06476d8c538698 | [] | no_license | bfss-storage/bfss_server | 68408d547fcb4adc6574c3ace6ec5baa33589d79 | fd3e55e24efe3e788c1d2be7bf35f1481d86db35 | refs/heads/master | 2023-01-07T13:05:12.698807 | 2019-05-28T08:03:58 | 2019-05-28T08:03:58 | 188,982,645 | 2 | 1 | null | 2023-01-03T22:50:51 | 2019-05-28T08:02:14 | C++ | UTF-8 | C++ | false | false | 6,622 | h | bfss_node.h | //
// Created by root on 19-2-8.
//
#ifndef BFSS__SN__NODE__H
#define BFSS__SN__NODE__H
#include <mutex>
#include <shared_mutex>
#include <iostream>
#include <queue>
#include <boost/atomic.hpp>
#include <boost/thread/thread.hpp>
#include <boost/lockfree/spsc_queue.hpp>
#include <openssl/sha.h>
#include <openssl/evp.h>
#include <libconfig.h++>
#include <log4cxx/logger.h>
#include <log4cxx/basicconfigurator.h>
#include <log4cxx/helpers/exception.h>
#include <BFSS_SND.h>
#include <BFSS_REGMD.h>
#include <BFSS_APID.h>
#include <bfss_regm_types.h>
#include <bfss_base.h>
#include <bfss_exception.h>
#include "blkdev.h"
#include "bfss_keys.h"
using namespace bfss;
namespace BFSS_SN {
class cache_node;
class cache_node {
enum _node_status {
NS_UNINITED = 0,
NS_INITED = 1,
NS_UPDATED = 2,
NS_FLUSHED = NS_INITED
};
keys_manager & key_mgr;
int32_t cache_index;
int32_t blk_index;
char blk_data[blk_size];
boost::shared_mutex blk_mutex; /* [缓存读写过程] 不能和 [块设备读写过程 或 加解密过程] 相冲突*/
cache_node * encrypted; /*为明文缓存记录密文缓存的指针,密文缓存该指针为nullptr*/
uint16_t status;
int64_t mtime;
public:
cache_node * prev;
cache_node * next;
explicit cache_node(keys_manager &_key_mgr, int32_t _index) : key_mgr(_key_mgr) {
cache_index = _index;
blk_index = -1;
memset(blk_data, 0, blk_size);
status = NS_UNINITED;
mtime = INT64_MAX;
encrypted = nullptr;
prev = this;
next = this;
};
int32_t write(const int32_t index, const int32_t offset, const int32_t size, const char *data);
int32_t read(const int32_t index, const int32_t offset, const int32_t size, std::string &data, bool decrypt);
bool blk2cache();
bool cache2blk();
bool encrypt();
bool decrypt();
void reset_index(int32_t index, cache_node *encrypted_node);
inline void flush() {
if (is_decrypted()) {
encrypt(); // 明文cache 只加密
} else {
cache2blk(); // 密文cache 则落盘
}
}
inline bool is_decrypted() {
boost::shared_lock<boost::shared_mutex> read_lock(blk_mutex);
return (encrypted != nullptr);
}
inline bool is_uninited() {
boost::shared_lock<boost::shared_mutex> read_lock(blk_mutex);
return (status == NS_UNINITED);
}
inline bool is_updated() {
boost::shared_lock<boost::shared_mutex> read_lock(blk_mutex);
return (status == NS_UPDATED);
}
inline bool is_timeout(int64_t _now, int32_t _timeout) {
boost::shared_lock<boost::shared_mutex> read_lock(blk_mutex);
return (mtime + (int64_t) _timeout) < _now;
}
inline bool is_me(int32_t index) {
boost::shared_lock<boost::shared_mutex> read_lock(blk_mutex);
return (blk_index == index);
}
inline int32_t get_blk_index() {
boost::shared_lock<boost::shared_mutex> read_lock(blk_mutex);
return blk_index;
}
inline std::string to_string() {
std::ostringstream oss;
oss << ((encrypted != nullptr) ? " D[" : " E[" ) << cache_index
<< "](" << blk_index << ")" << ((status == NS_UPDATED) ? "U" : " ");
return oss.str();
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////////
/*LRU - LeastRecentlyUsed*/
class lru_indexable_list {
struct lru_index {
cache_node *encrypt;
cache_node *decrypt;
};
public:
lru_indexable_list() {
_latest = nullptr;
_cache_index = nullptr;
}
~lru_indexable_list() {
_latest = nullptr;
delete [] _cache_index;
_cache_index = nullptr;
}
void init(int32_t _blk_count, int64_t max_cache_size, keys_manager &_key_mgr);
template<typename _func_t>
void access(int32_t _index, bool decrypt, _func_t &&_do_action) {
boost::upgrade_lock<boost::shared_mutex> cache_shared_lock(_cache_mutex);
cache_node *node = get_node(_index, decrypt, cache_shared_lock);
_do_action(node);
}
template<typename _func_t>
void traverse(_func_t &&_do_action, bool _direction=false) {
boost::shared_lock<boost::shared_mutex> list_shared_lock(_list_mutex);
if (_latest == nullptr) {
return;
}
auto *node = _latest;
do {
bool _go_on = _do_action(node);
if (!_go_on) {
return;
}
node = (_direction ? node->next :node->prev);
} while (node != _latest);
}
private:
void update_list(cache_node *node, boost::upgrade_lock<boost::shared_mutex>& list_shared_lock);
cache_node *get_node(int32_t index, bool decrypt,
boost::upgrade_lock<boost::shared_mutex> &cache_shared_lock);
void get_cache_index(lru_index &_pair, int blk_index, bool decrypt,
boost::upgrade_lock<boost::shared_mutex> &cache_shared_lock,
boost::upgrade_lock<boost::shared_mutex> &index_shared_lock);
inline std::string to_string() {
int x = 5;
std::string str_next;
traverse([&](cache_node *node) {
x--;
str_next += " -> " + node->to_string();
return (x > 0);
}, true);
x = 5;
std::string str_prev;
traverse([&](cache_node *node) {
x--;
str_prev = " -> " + node->to_string() + str_prev;
return (x > 0);
});
return str_next + " ... " + str_prev;
}
std::shared_ptr<blk_cache_info> _cache_ptr;
boost::shared_mutex _cache_mutex;
cache_node *_latest;
boost::shared_mutex _list_mutex;
lru_index *_cache_index;
boost::shared_mutex _index_mutex;
};
}
#endif //BFSS__SN__NODE__H
|
c4040076e0f2e9561502f0150cdef4e77f9cfdd5 | c9b5a2cd00764ee4a0b889b5b602eb28fd08e989 | /cpp/198. House Robber.cpp | bacfc9748d777981c228d41faacfdd78f183526f | [] | no_license | cwza/leetcode | 39799a6730185fa06913e3beebebd3e7b2e5d31a | 72136e3487d239f5b37e2d6393e034262a6bf599 | refs/heads/master | 2023-04-05T16:19:08.243139 | 2021-04-22T04:46:45 | 2021-04-22T04:46:45 | 344,026,209 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,251 | cpp | 198. House Robber.cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef vector<vector<int>> vvi;
typedef pair<int, int> pi;
/*
dp[i] = max(nums[i] + dp[i+2], dp[i+1])
dp[n] = 0
dp[n-1] = nums[n-1]
ans = dp[0]
*/
class Solution {
public:
// int rob(vector<int>& nums) {
// int n = nums.size();
// if(n==0) return 0;
// int dp[n+1]; dp[n] = 0, dp[n-1] = nums[n-1];
// for(int i = n - 2; i >= 0; i--) {
// dp[i] = max(nums[i] + dp[i+2], dp[i+1]);
// }
// return dp[0];
// }
int rob(vector<int>& nums) {
// 1D Space of above
// Time: O(n), Space: O(1)
int n = nums.size();
if(n==0) return 0;
int prev = 0, cur = nums[n-1];
for(int i = n - 2; i >= 0; i--) {
int cur_tmp = cur;
cur = max(nums[i] + prev, cur);
prev = cur_tmp;
}
return cur;
}
};
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
Solution solution; vi nums; int ans;
solution = Solution();
nums = {1,2,3,1};
ans = solution.rob(nums);
assert(ans==4);
solution = Solution();
nums = {2,7,9,3,1};
ans = solution.rob(nums);
assert(ans==12);
} |
b5cb822beaa695c5c239b9fa96a41f8ed51a5411 | a47f63007ed57518cbe4d3234139f4902a760beb | /Items.h | cf5018d9ae662f071f0941bc5d495df4c74f07b5 | [] | no_license | nhansilva/GameRar | 1f41a6d85d2c989cb00875583229c7f0c9f9c5f6 | d4a71394d0dd1450385939f068bf4987b71d8abf | refs/heads/master | 2020-04-07T05:59:22.694897 | 2018-11-22T03:11:22 | 2018-11-22T03:11:22 | 158,117,831 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 894 | h | Items.h | #include "GCamera.h"
#include "ILHeart.h"
#include "ISHeart.h"
#include "IFood.h"
#include "IDagger.h"
#include "IWhip.h"
#include "400Coin.h"
#include "600Coin.h"
#include "IFire.h"
#include "2Up.h"
#pragma once
class CItems
{
private:
int whichItem; //Phân biệt items
CLHeart *lheart;
CSHeart *sheart;
CFood *food;
CIDagger *dagger;
CIWhip *whip;
C400Coin *_400coin;
C600Coin *_600coin;
CIFire *fire;
C2Up *_2up;
int timeDie = 0;
public:
int getwhichObj() { return whichItem; }
void setwhichObj(int x1) { whichItem = x1; }
void Draw(GCamera * cam);
Box GetBox(GCamera *camera);
void Update(int t);
void StopFall();
void Fall();
void setFireDie(int a);
void setXFire(int a);
void setYFire(int a);
CItems(int io, int x1, int y1);
int getIsDie();
void setIsDie(bool a);
void setX(int a);
void setY(int a);
void setCountTime();
~CItems();
};
|
22d3089ba4fac325ba207cbacd898aef12b0e2c6 | e0d8f27f590a0b7b2330b5a391319b07ba823635 | /source/main.cpp | 1716d21df234c089cd75274f0eab848fd146f3dc | [] | no_license | FiskNi/Project-Kiddo | 0c2a74b6989ac6236f88d94aa3004d40c5debd50 | 516ef59ea503ccca211d231aa4d2eb14d929e2cc | refs/heads/master | 2021-07-10T02:56:42.479967 | 2020-08-24T13:17:41 | 2020-08-24T13:17:41 | 180,403,595 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 408 | cpp | main.cpp | #include "GameEngine.h"
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow)
{
// Debug console
AllocConsole();
AttachConsole(GetCurrentProcessId());
freopen("CON", "w", stdout); //Redirects the string stream to the debug console
cout << "Welcome to the debug console!" << endl;
// The Game
GameEngine gProjectKiddo;
gProjectKiddo.Run();
return 0;
}
|
9fccbd1811f10a303d4874d52374ff315c441132 | 5acf0552159f9f6d1eab49302c535b1bc853a505 | /ejemplos/funciones/lambda/foreach/main.cpp | 58833bda6163c27d08a007cd6cf4c39dc4bf5c8d | [
"MIT"
] | permissive | Nebrija-Programacion/Programacion-I | b01f04936aded62b5843c6a48a55552d32a6ecb6 | f14996251eb44df420d361e0628628e35fb442a8 | refs/heads/master | 2022-07-23T04:48:24.023017 | 2022-06-21T14:19:18 | 2022-06-21T14:19:18 | 147,667,722 | 21 | 23 | MIT | 2020-10-09T08:44:46 | 2018-09-06T12:07:33 | C++ | UTF-8 | C++ | false | false | 1,619 | cpp | main.cpp | /*
* This file is part of the course "Programacion I" taught at Universidad Nebrija
* https://github.com/Nebrija-Programacion/Programacion-I
*
* Copyright (c) 2019 Alberto Valero - https://github.com/avalero
*
* 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, version 3.
*
* See <http://www.gnu.org/licenses/>.
*/
/******************************************************************************************
In this program we are creating a function that loops over a vector of integer and performs
an action over each elemnt.
This action is performed using a lambda function. The lambda functions receives a reference
to a vector of integers, that will manipulate.
*******************************************************************************************/
#include <iostream>
#include <vector>
#include <functional>
using namespace std;
/**
* @brief forEach Loops over each elemnt of v and performs fp
* @param v the vector to loop
* @param fp the actions that must be performed over each elemnt
*/
void forEach(vector<int> v, std::function<void(int elem)> fp){
for(auto elem: v){
fp(elem);
}
}
int main()
{
vector<int> v{{1,2,3,4,5,6}};
vector<int> odds;
// loop over each element of v and add odd elements to "odds" vector.
forEach(v, [&odds](int e){
if(e % 2 != 0) odds.push_back(e);
});
// loop over each elemnt of v and print it
forEach(odds, [](int e){
cout << e << endl;
});
return 0;
}
|
82764889040fa9a9732d69d205e4291b254bd2d4 | 51130a8ca581cf523e6109f2caef2672d33ba635 | /QtApp/mainwindow.h | a140856dce78b5f4e5e733be29f86950c7df93c0 | [] | no_license | dulangaweerakoon/FYP_Qt_App | 7feaf50a8eec5f864b9125bef6e4ad188c4298e0 | 646b96422fc8484b34c512f518c1f68cdd49245f | refs/heads/master | 2021-09-03T03:45:52.399509 | 2018-01-05T09:07:28 | 2018-01-05T09:07:28 | 115,726,623 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 780 | h | mainwindow.h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QGraphicsScene>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void update_graphicView(cv::Mat img);
void update_globalTrack(int x, int y);
void update_heatmap(int x, int y);
private slots:
void on_pushButton_clicked();
private:
Ui::MainWindow *ui;
QGraphicsScene *imageScene;
QGraphicsScene *globalScene;
QGraphicsScene *heatmapScene;
cv::Mat floormap;
int count;
cv::Mat map;
cv::Mat pallete;
};
#endif // MAINWINDOW_H
|
76fcd17345597284b96d70e234455f2e8bbbbd4a | 991a4d0729e563387c58de8736d4b7c8c8001f19 | /arduino_codes/drs_neo/drs_neo.ino | 8d67a71b9353181c91b5c2d4d54fdb4b8052fd9e | [] | no_license | itachiuchiha97/dr18_telemetry | 4370d8cfb6403830a7e83f595db785a265729ee4 | e103c7e49c0b066da394addeefbcb661f3f86ba4 | refs/heads/master | 2021-01-07T02:18:00.537988 | 2019-01-06T13:39:47 | 2019-01-06T13:39:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,367 | ino | drs_neo.ino | // Components: NeoPixel , DRS Actuation Button
#include <Servo.h>
#include <Adafruit_NeoPixel.h>
int PIN = 6 ;
int NUMPIXELS = 10 ;
Servo myservo;
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
int str[2] ;
String data = "0000 22\n" ;
int Button_Pin = 2;
int state = HIGH;
int reading;
int previous = LOW;
unsigned long time = 0 ;
unsigned long debounce = 200;
void setup() {
Serial.begin(9600) ;
myservo.attach(9); // attaches the servo on pin 9 to the servo object
pinMode(Button_Pin, INPUT) ;
pixels.begin(); // This initializes the NeoPixel library.
for(int i = 0 ; i < 9 ; i++) {
pixels.setPixelColor(i, pixels.Color(255, 0, 127)) ;
pixels.show() ;
delay(30) ;
}
for(int i = 0 ; i < 9 ; i++) {
pixels.setPixelColor(i, pixels.Color(0, 0, 0)) ;
pixels.show() ;
delay(18) ;
}
for(int i = 0 ; i < 9 ; i++) {
pixels.setPixelColor(i, pixels.Color(255, 255, 51)) ;
pixels.show() ;
delay(30) ;
}
for(int i = 0 ; i < 9 ; i++) {
pixels.setPixelColor(i, pixels.Color(0, 0, 0)) ;
pixels.show() ;
delay(18) ;
}
for(int i = 0 ; i < 9 ; i++) {
pixels.setPixelColor(i, pixels.Color(0, 255, 0)) ;
pixels.show() ;
delay(30) ;
}
for(int i = 0 ; i < 9 ; i++) {
pixels.setPixelColor(i, pixels.Color(0, 0, 0)) ;
pixels.show() ;
delay(18) ;
}
}
void loop() {
if (Serial.available() > 0 ) {
data = Serial.readStringUntil('\n') ;
//data = Serial.readString() ;
//data = Serial.read() ;
}
/////////////////CONVERTING DATA INTO AN ARRAY////////////////////////////////////////////////
int j = 0 ;
int last = 0 ;
for (int i = 0 ; i < data.length() ; i++) {
//Serial.println(data.charAt(i)) ;
if (data.charAt(i) != ' ') {
j++ ;
} else {
str[0] = data.substring(last , j).toInt() ;
last = j + 1 ;
j++ ;
}
}
str[1] = data.substring(last , data.length() - 1 ).toInt() ;
Serial.print(str[0]) ;
Serial.print(' ') ;
Serial.println(str[1]) ;
//////////////////////NEOPIXEL///////////////////////////////////////
// map the number of pixels according to the RPM stored in str[0] .
if (str[0] < 1250) {
for (int a = 0 ; a < 1 ; a++) {
pixels.setPixelColor(a, pixels.Color(0, 150, 0)) ; // Moderately bright green color.
pixels.show() ;
}
} else if (str[0] >= 1250 && str[0] < 2500 ) {
for (int a = 0 ; a < 2 ; a++) {
pixels.setPixelColor(a, pixels.Color(0, 150, 0)) ;
pixels.show() ;
}
} else if (str[0] >= 2500 && str[0] < 3750 ) {
for (int a = 0 ; a < 3 ; a++) {
pixels.setPixelColor(a, pixels.Color(0, 150, 0)) ;
pixels.show() ;
}
} else if (str[0] > 3750 && str[0] < 5000 ) {
for (int a = 0 ; a < 4 ; a++) {
pixels.setPixelColor(a, pixels.Color(255, 255, 0)) ; // Moderately yellow color.
pixels.show() ;
}
} else if (str[0] >= 5000 && str[0] < 6250 ) {
for (int a = 0 ; a < 5 ; a++) {
pixels.setPixelColor(a, pixels.Color(255, 255, 0)) ;
pixels.show() ;
}
} else if (str[0] >= 6250 && str[0] < 7500 ) {
for (int a = 0 ; a < 6 ; a++) {
pixels.setPixelColor(a, pixels.Color(255, 255, 0)) ;
pixels.show() ;
}
} else if (str[0] >= 7500 && str[0] < 8750 ) {
for (int a = 0 ; a < 7 ; a++) {
pixels.setPixelColor(a, pixels.Color(255, 255, 0)) ;
pixels.show() ;
}
} else if (str[0] >= 8750 && str[0] < 10000 ) {
for (int a = 0 ; a < 8 ; a++) {
pixels.setPixelColor(a, pixels.Color(255, 0, 0)) ; // Bright red color.
pixels.show() ;
}
}
//////////////////SERVO AND OVER RIDE SWITCH/////////////////////////////////////////////////
reading = digitalRead(Button_Pin);
if (reading == HIGH && previous == LOW && millis() - time > debounce) {
state = !state ;
time = millis();
}
if (state) {
pixels.setPixelColor(10, pixels.Color(0, 150, 0)); // Moderately bright green color.
pixels.show();
myservo.write(0) ;
}
else {
pixels.setPixelColor(10, pixels.Color(0, 0, 0)); // Moderately bright green color.
pixels.show();
myservo.write(22) ;
}
previous = reading;
////////////////////////////////////////////////////////////////////////////////////
for ( int i = 0 ; i < 10 ; i++) {
pixels.setPixelColor(i, pixels.Color(0, 0, 0));
}
}
|
ffaad5903eacce12e8dfab0b489d0d48e7d1a7ed | d3b612483b4151b9ed3ab6c61e66760ff7cc7ad4 | /TinyWebServer/src/httpresponse.cpp | b3c1fa3813efaf49de2d37947ee86106103cfc2d | [
"MIT"
] | permissive | Qazwar/Network-Learn | 4aa848f1ffc377fc3ef8cb0edb815276cb818eac | f88a5e2593a307d877d185d2b7ca5759fa508e30 | refs/heads/main | 2023-07-10T00:41:36.388532 | 2021-08-12T14:27:03 | 2021-08-12T14:27:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,311 | cpp | httpresponse.cpp | /**
* @author Ho 229
* @date 2021/7/26
*/
#include "httpresponse.h"
#include "until.h"
#ifdef _WIN32
# if _MSC_VER >= 1600
# pragma execution_character_set("utf-8")
# endif
#endif
HttpResponse::HttpResponse()
{
this->initializatHeaders();
}
void HttpResponse::setFilePath(const fs::path &path)
{
const fs::directory_entry entry(path);
if(entry.is_regular_file())
{
m_filePath = path;
m_type = File;
}
}
void HttpResponse::reset()
{
m_text.clear();
m_filePath.clear();
m_headers.clear();
this->initializatHeaders();
}
void HttpResponse::setHttpState(const HttpState &state)
{
if(state.second.empty())
return;
m_httpState = state;
}
void HttpResponse::toRawData(std::string &response)
{
response.clear();
if(m_type == Normal)
m_headers["Content-Length"] = std::to_string(m_text.size());
else
m_headers["Content-Length"] = std::to_string(fs::directory_entry(m_filePath).file_size());
// Response line
response.append("HTTP/1.1 " + std::to_string(m_httpState.first) + ' '
+ m_httpState.second + "\r\n");
// Headers
for(const auto &[key, value] : m_headers)
response.append(key + ": " + value + "\r\n");
if(m_type == Normal)
response.append("\r\n" + m_text);
else
response.append("\r\n");
}
void HttpResponse::buildErrorResponse(int state, const std::string &message)
{
this->setRawHeader("Content-Type", "text/html; charset=utf-8");
this->setHttpState({404, "Not found"});
m_text = "<h2>Tiny Web Server</h2><h1>" + std::to_string(state)
+ " " + message + "<br>∑(っ°Д°;)っ<h1>\n";
}
void HttpResponse::buildFileResponse(const fs::path &filePath)
{
const auto it = PermissibleStaticType.find(filePath.extension().string());
if(it != PermissibleStaticType.end())
this->setRawHeader("Content-Type", it->second);
//this->setRawHeader("Transfer-Encoding", "chunked");
this->setFilePath(filePath);
}
inline void HttpResponse::initializatHeaders()
{
m_headers["Server"] = "Tiny Web Server";
//m_headers["Connection"] = "keep-alive";
m_headers["Connection"] = "close";
m_headers["Accept-Ranges"] = "bytes";
m_headers["Date"] = Until::currentDateString();
}
|
1621d00c5d973efee5b68fd27ae417d48243d9cf | 36693e75f03a3b08038e5850b632496193a73222 | /G5_Lab4/datatypes/headers/DtHora.h | 202e2fca5b534e597d33f0f35ed40c3e60bfb0c4 | [] | no_license | Drolegc/lab4 | fb9b5eea1805d21b6ef382c54b4803f60379cd0c | 2b31c6764681215b823d2a83749526ee72b72ca6 | refs/heads/master | 2020-06-06T00:00:28.113919 | 2019-07-03T15:52:06 | 2019-07-03T15:52:06 | 192,580,213 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 391 | h | DtHora.h | #ifndef DTHORA_H
#define DTHORA_H
#include <stdexcept>
class DtHora {
private:
int hora;
int minutos;
bool isValid();
public:
DtHora(int hora, int minutos);
int getHora();
int getMinutos();
void setHora(int hora);
void setMinutos(int minutos);
~DtHora();
};
#endif /* DTHORA_H */
|
6d3c774f109ade79655338a2b4238196a8fb89dd | 1ef7a9f94a0d206eaa5ce32a9f245119acad0cdb | /Hypercube/MpiLab/Dijkstra/DijkstraMPI/DijkstraMPI.cpp | d0dda723dc96942a31ba7d9f8fb3cd105731b96d | [] | no_license | Andu98/Hypercube-Dijkstra | c69abc2c76caf5df36e0e7e027fb03edc705b452 | d4c6c2f14a294b8a1d0963ad845bdebe0030daab | refs/heads/main | 2023-02-25T14:56:12.846188 | 2021-02-01T15:28:51 | 2021-02-01T15:28:51 | 334,992,667 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,122 | cpp | DijkstraMPI.cpp | #include "DijkstraMPI.h"
#include "../DijkstraCommon/VertexData.h"
pair<const vector<double>, const vector<int>> DijkstraMPI::run(MPI_Comm& communicator) {
// cat timp nu au fost gasite toate varfurile
while (!m_dijkstraBackend.verificaDacaToateVarfurileAuFostProcesate()) {
//varf care apartine nodului curent si este cel mai apropiat de grupul deja procesat de varfuri
VertexData localMin = m_dijkstraBackend.gasesteVarfCuDistantaMinima();
//aduna toate varfurile locale cele mai apropiate si construieste un minim global
VertexData globalMin = creazaInstantaVarf();
MPI_Allreduce(&localMin, &globalMin, 1, MPI_DOUBLE_INT, MPI_MINLOC, communicator);
//daca nu exista un minim global opreste (imposibil pentru cazul hipercubului)
if (globalMin.varfNr == -1) {
break;
}
// marcheaza varful ca fiind procesat
m_dijkstraBackend.marcheazaVarfulProcesat(globalMin.varfNr);
// calculeaza noua distanta
m_dijkstraBackend.executaLoopDijkstra(globalMin, m_graphData);
}
return make_pair(m_dijkstraBackend.getDistances(), m_dijkstraBackend.getPredecessors());
} |
9bd483425710d1666d82990f6a5d0ab145324717 | c14832c08e325ea3b61b5af5c19be783e767bbaa | /widget.cpp | 92bb61ad9b55894d053e78756e9673fc00183cfe | [] | no_license | cstwhh/Sierpinski | 9b42d4219c0dcd663b1da706f73793cd34cd8c7d | 998649b7852d718d4abae691d381681d8b9036ab | refs/heads/master | 2021-01-10T13:16:00.997907 | 2015-12-16T16:10:23 | 2015-12-16T16:10:23 | 48,119,816 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,304 | cpp | widget.cpp | #include "widget.h"
#include "ui_widget.h"
#include<QtCore/qmath.h>
#include<QPainter>
#include<QtDebug>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
//设置界面
ui->setupUi(this);
this->setWindowTitle("Sierpinski");
//初始值设置
length=600;
n=0;
color=Qt::yellow;
//计算初始面积
double area=5000*qCos(M_PI/6)*pow(0.75,n);
//更新面积显示区的数值
ui->areaEdit->setText(QString::number(area));
//初始化triangles
triangles=new QQueue<QPolygonF>();
triangles->clear();
updateTriangles(0);
}
Widget::~Widget()
{
delete ui;
}
void Widget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
//设置画笔
QPen pen;
pen.setColor(Qt::black);
pen.setStyle(Qt::SolidLine);
pen.setWidth(1);
painter.setPen(pen);
//设置画刷
QBrush brush(Qt::SolidPattern); // 画刷
brush.setColor(color);
painter.setBrush(brush); // 设置画刷
//将triangles里面的所有分形三角形画出来
for(int i=0;i<triangles->size();++i)
painter.drawPolygon(triangles->at(i));
}
void Widget::updateTriangles(int n) {
//初始化只含有最大的三角形
triangles->clear();
QPolygonF singleTriangle;
singleTriangle << QPointF(160+length*qSin(M_PI/6),30)
<< QPointF(160,30+length*qCos(M_PI/6))
<< QPointF(160+length,30+length*qCos(M_PI/6));
triangles->append(singleTriangle);
//1-n级分形三角形的位置坐标,并且更新到triangles里面
for(int i=0;i<n;++i) {
long long needOut=pow(3,i);
for(long long j=1;j<=needOut;++j) {
QPolygonF singleTriangle=triangles->dequeue();
QPointF A,B,C;
//singleTriangle>>A>>B>>C;
A=singleTriangle.at(0);
B=singleTriangle.at(1);
C=singleTriangle.at(2);
QPointF AB=QPointF((A.x()+B.x())/2,(A.y()+B.y())/2);
QPointF BC=QPointF((B.x()+C.x())/2,(B.y()+C.y())/2);
QPointF CA=QPointF((C.x()+A.x())/2,(C.y()+A.y())/2);
QPolygonF A_AB_CA,B_AB_BC,C_BC_CA;
A_AB_CA <<A<<AB<<CA;
B_AB_BC <<B<<AB<<BC;
C_BC_CA <<C<<BC<<CA;
triangles->append(A_AB_CA);
triangles->append(B_AB_BC);
triangles->append(C_BC_CA);
}
}
//triangles被更新,所以应该调用update()函数,重新绘制
update();
}
void Widget::on_valueRange_sliderMoved(int position)
{
//n值显示区的数值更新
ui->nLabel->setText(QString::number(position));
//n大于maxVisiableValue时,更多的分形在已有屏幕上体现不出来,没有深入绘制的必要
int maxVisiableValue=8;
if(position>maxVisiableValue) {
if(n<maxVisiableValue) updateTriangles(maxVisiableValue);
}
//否则,绘制n级分形三角形
else {
updateTriangles(position);
}
//更新n以及面积
n=position;
double area=5000*qCos(M_PI/6)*pow(0.75,n);
ui->areaEdit->setText(QString::number(area));
}
void Widget::on_valueRange_valueChanged(int value)
{
//直接调用以上函数即可
on_valueRange_sliderMoved(value);
}
|
c06bcc0ed6511da995d0c3e64f03d5bd7c5bce60 | 9e3e04dfe1d0f5e1994611eb04e290bf9f8a18c0 | /ep1/ep1.cpp | a9bf18d51d373353965b5adb3135b25df4b65141 | [
"MIT"
] | permissive | codingdojotw/CppMiniTutorial | 1e99fcfa47a5e4700381faddcb7f9889d004d29d | dab961768ecc94288daad2db201f59ca71349b18 | refs/heads/master | 2021-01-19T07:42:41.741024 | 2013-11-08T10:08:52 | 2013-11-08T10:08:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 685 | cpp | ep1.cpp | // ep1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <memory>
#include <gtest\gtest.h>
using namespace std;
struct Foo {
virtual int Plus(int left, int right)
{
return 2;
}
};
struct Bar : public Foo {
virtual int Plus(int left, short right)
{
return 4;
}
};
TEST(Episode1, OverrideTest_CallParent)
{
unique_ptr<Foo> op(new Foo());
EXPECT_EQ(2, op->Plus(1, 1));
}
TEST(Episode1, OverrideTest_CallDerived)
{
unique_ptr<Foo> op(new Bar());
EXPECT_EQ(4, op->Plus(1, 1));
}
int _tmain(int argc, _TCHAR* argv[])
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
eb18f49b68a76a9fb1ea40e0073665ad5f98b5c9 | 693ec5c4afc3644e1e8559283eab5cee24f58fb6 | /codeforces/1257A.cpp | 61f81a7b5fb54e7c13cbab6ca0e29001bd8dd144 | [] | no_license | AnupamDas054/competitve-programming | 89e72cc8ccf9e738cc9e7d1aec1b0bfb6e696b9d | 9a50b10b9ccdff58c31548eace21e5fced2c5f3c | refs/heads/master | 2023-02-20T12:00:37.680952 | 2021-01-22T18:50:34 | 2021-01-22T18:50:34 | 231,796,604 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 502 | cpp | 1257A.cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
int n,s,a,b;
cin>>n>>s>>a>>b;
if(a>b)
swap(a,b);
if(a-1<=s)
{
s=s-(a-1);
a=1;
}
else
{
a=a-s;
s=0;
}
if(n-b<=s)
{
b=n;
}
else
{
b=b+(s);
}
cout<<abs(a-b)<<endl;
}
return 0;
}
|
bd7e6366b8198fb8bcf3bc487953b86bd7ea9d6c | 58fa1a4852233ae7133cf191ab6ea8b7f8d2408f | /include/ceres/jet.h | 7f9f5bea66d6ad972355d5c40c451156f29cf454 | [
"Apache-2.0",
"MIT",
"BSD-3-Clause"
] | permissive | ceres-solver/ceres-solver | 0c4fcbe4f20e6b62bf6c929dc8775ebd9c206780 | ed9921fc2417faeca52ceb4b35287bc9611454eb | refs/heads/master | 2023-08-30T17:25:16.021682 | 2023-08-29T02:53:36 | 2023-08-29T02:53:36 | 15,667,250 | 3,401 | 1,157 | NOASSERTION | 2023-04-30T12:08:50 | 2014-01-06T06:44:59 | C++ | UTF-8 | C++ | false | false | 50,849 | h | jet.h | // Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2022 Google Inc. All rights reserved.
// http://ceres-solver.org/
//
// 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 Google Inc. 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.
//
// Author: keir@google.com (Keir Mierle)
//
// A simple implementation of N-dimensional dual numbers, for automatically
// computing exact derivatives of functions.
//
// While a complete treatment of the mechanics of automatic differentiation is
// beyond the scope of this header (see
// http://en.wikipedia.org/wiki/Automatic_differentiation for details), the
// basic idea is to extend normal arithmetic with an extra element, "e," often
// denoted with the greek symbol epsilon, such that e != 0 but e^2 = 0. Dual
// numbers are extensions of the real numbers analogous to complex numbers:
// whereas complex numbers augment the reals by introducing an imaginary unit i
// such that i^2 = -1, dual numbers introduce an "infinitesimal" unit e such
// that e^2 = 0. Dual numbers have two components: the "real" component and the
// "infinitesimal" component, generally written as x + y*e. Surprisingly, this
// leads to a convenient method for computing exact derivatives without needing
// to manipulate complicated symbolic expressions.
//
// For example, consider the function
//
// f(x) = x^2 ,
//
// evaluated at 10. Using normal arithmetic, f(10) = 100, and df/dx(10) = 20.
// Next, argument 10 with an infinitesimal to get:
//
// f(10 + e) = (10 + e)^2
// = 100 + 2 * 10 * e + e^2
// = 100 + 20 * e -+-
// -- |
// | +--- This is zero, since e^2 = 0
// |
// +----------------- This is df/dx!
//
// Note that the derivative of f with respect to x is simply the infinitesimal
// component of the value of f(x + e). So, in order to take the derivative of
// any function, it is only necessary to replace the numeric "object" used in
// the function with one extended with infinitesimals. The class Jet, defined in
// this header, is one such example of this, where substitution is done with
// templates.
//
// To handle derivatives of functions taking multiple arguments, different
// infinitesimals are used, one for each variable to take the derivative of. For
// example, consider a scalar function of two scalar parameters x and y:
//
// f(x, y) = x^2 + x * y
//
// Following the technique above, to compute the derivatives df/dx and df/dy for
// f(1, 3) involves doing two evaluations of f, the first time replacing x with
// x + e, the second time replacing y with y + e.
//
// For df/dx:
//
// f(1 + e, y) = (1 + e)^2 + (1 + e) * 3
// = 1 + 2 * e + 3 + 3 * e
// = 4 + 5 * e
//
// --> df/dx = 5
//
// For df/dy:
//
// f(1, 3 + e) = 1^2 + 1 * (3 + e)
// = 1 + 3 + e
// = 4 + e
//
// --> df/dy = 1
//
// To take the gradient of f with the implementation of dual numbers ("jets") in
// this file, it is necessary to create a single jet type which has components
// for the derivative in x and y, and passing them to a templated version of f:
//
// template<typename T>
// T f(const T &x, const T &y) {
// return x * x + x * y;
// }
//
// // The "2" means there should be 2 dual number components.
// // It computes the partial derivative at x=10, y=20.
// Jet<double, 2> x(10, 0); // Pick the 0th dual number for x.
// Jet<double, 2> y(20, 1); // Pick the 1st dual number for y.
// Jet<double, 2> z = f(x, y);
//
// LOG(INFO) << "df/dx = " << z.v[0]
// << "df/dy = " << z.v[1];
//
// Most users should not use Jet objects directly; a wrapper around Jet objects,
// which makes computing the derivative, gradient, or jacobian of templated
// functors simple, is in autodiff.h. Even autodiff.h should not be used
// directly; instead autodiff_cost_function.h is typically the file of interest.
//
// For the more mathematically inclined, this file implements first-order
// "jets". A 1st order jet is an element of the ring
//
// T[N] = T[t_1, ..., t_N] / (t_1, ..., t_N)^2
//
// which essentially means that each jet consists of a "scalar" value 'a' from T
// and a 1st order perturbation vector 'v' of length N:
//
// x = a + \sum_i v[i] t_i
//
// A shorthand is to write an element as x = a + u, where u is the perturbation.
// Then, the main point about the arithmetic of jets is that the product of
// perturbations is zero:
//
// (a + u) * (b + v) = ab + av + bu + uv
// = ab + (av + bu) + 0
//
// which is what operator* implements below. Addition is simpler:
//
// (a + u) + (b + v) = (a + b) + (u + v).
//
// The only remaining question is how to evaluate the function of a jet, for
// which we use the chain rule:
//
// f(a + u) = f(a) + f'(a) u
//
// where f'(a) is the (scalar) derivative of f at a.
//
// By pushing these things through sufficiently and suitably templated
// functions, we can do automatic differentiation. Just be sure to turn on
// function inlining and common-subexpression elimination, or it will be very
// slow!
//
// WARNING: Most Ceres users should not directly include this file or know the
// details of how jets work. Instead the suggested method for automatic
// derivatives is to use autodiff_cost_function.h, which is a wrapper around
// both jets.h and autodiff.h to make taking derivatives of cost functions for
// use in Ceres easier.
#ifndef CERES_PUBLIC_JET_H_
#define CERES_PUBLIC_JET_H_
#include <cmath>
#include <complex>
#include <iosfwd>
#include <iostream> // NOLINT
#include <limits>
#include <numeric>
#include <string>
#include <type_traits>
#include "Eigen/Core"
#include "ceres/internal/jet_traits.h"
#include "ceres/internal/port.h"
#include "ceres/jet_fwd.h"
// Here we provide partial specializations of std::common_type for the Jet class
// to allow determining a Jet type with a common underlying arithmetic type.
// Such an arithmetic type can be either a scalar or an another Jet. An example
// for a common type, say, between a float and a Jet<double, N> is a Jet<double,
// N> (i.e., std::common_type_t<float, ceres::Jet<double, N>> and
// ceres::Jet<double, N> refer to the same type.)
//
// The partial specialization are also used for determining compatible types by
// means of SFINAE and thus allow such types to be expressed as operands of
// logical comparison operators. Missing (partial) specialization of
// std::common_type for a particular (custom) type will therefore disable the
// use of comparison operators defined by Ceres.
//
// Since these partial specializations are used as SFINAE constraints, they
// enable standard promotion rules between various scalar types and consequently
// their use in comparison against a Jet without providing implicit
// conversions from a scalar, such as an int, to a Jet (see the implementation
// of logical comparison operators below).
template <typename T, int N, typename U>
struct std::common_type<T, ceres::Jet<U, N>> {
using type = ceres::Jet<common_type_t<T, U>, N>;
};
template <typename T, int N, typename U>
struct std::common_type<ceres::Jet<T, N>, U> {
using type = ceres::Jet<common_type_t<T, U>, N>;
};
template <typename T, int N, typename U>
struct std::common_type<ceres::Jet<T, N>, ceres::Jet<U, N>> {
using type = ceres::Jet<common_type_t<T, U>, N>;
};
namespace ceres {
template <typename T, int N>
struct Jet {
enum { DIMENSION = N };
using Scalar = T;
// Default-construct "a" because otherwise this can lead to false errors about
// uninitialized uses when other classes relying on default constructed T
// (where T is a Jet<T, N>). This usually only happens in opt mode. Note that
// the C++ standard mandates that e.g. default constructed doubles are
// initialized to 0.0; see sections 8.5 of the C++03 standard.
Jet() : a() { v.setConstant(Scalar()); }
// Constructor from scalar: a + 0.
explicit Jet(const T& value) {
a = value;
v.setConstant(Scalar());
}
// Constructor from scalar plus variable: a + t_i.
Jet(const T& value, int k) {
a = value;
v.setConstant(Scalar());
v[k] = T(1.0);
}
// Constructor from scalar and vector part
// The use of Eigen::DenseBase allows Eigen expressions
// to be passed in without being fully evaluated until
// they are assigned to v
template <typename Derived>
EIGEN_STRONG_INLINE Jet(const T& a, const Eigen::DenseBase<Derived>& v)
: a(a), v(v) {}
// Compound operators
Jet<T, N>& operator+=(const Jet<T, N>& y) {
*this = *this + y;
return *this;
}
Jet<T, N>& operator-=(const Jet<T, N>& y) {
*this = *this - y;
return *this;
}
Jet<T, N>& operator*=(const Jet<T, N>& y) {
*this = *this * y;
return *this;
}
Jet<T, N>& operator/=(const Jet<T, N>& y) {
*this = *this / y;
return *this;
}
// Compound with scalar operators.
Jet<T, N>& operator+=(const T& s) {
*this = *this + s;
return *this;
}
Jet<T, N>& operator-=(const T& s) {
*this = *this - s;
return *this;
}
Jet<T, N>& operator*=(const T& s) {
*this = *this * s;
return *this;
}
Jet<T, N>& operator/=(const T& s) {
*this = *this / s;
return *this;
}
// The scalar part.
T a;
// The infinitesimal part.
Eigen::Matrix<T, N, 1> v;
// This struct needs to have an Eigen aligned operator new as it contains
// fixed-size Eigen types.
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
// Unary +
template <typename T, int N>
inline Jet<T, N> const& operator+(const Jet<T, N>& f) {
return f;
}
// TODO(keir): Try adding __attribute__((always_inline)) to these functions to
// see if it causes a performance increase.
// Unary -
template <typename T, int N>
inline Jet<T, N> operator-(const Jet<T, N>& f) {
return Jet<T, N>(-f.a, -f.v);
}
// Binary +
template <typename T, int N>
inline Jet<T, N> operator+(const Jet<T, N>& f, const Jet<T, N>& g) {
return Jet<T, N>(f.a + g.a, f.v + g.v);
}
// Binary + with a scalar: x + s
template <typename T, int N>
inline Jet<T, N> operator+(const Jet<T, N>& f, T s) {
return Jet<T, N>(f.a + s, f.v);
}
// Binary + with a scalar: s + x
template <typename T, int N>
inline Jet<T, N> operator+(T s, const Jet<T, N>& f) {
return Jet<T, N>(f.a + s, f.v);
}
// Binary -
template <typename T, int N>
inline Jet<T, N> operator-(const Jet<T, N>& f, const Jet<T, N>& g) {
return Jet<T, N>(f.a - g.a, f.v - g.v);
}
// Binary - with a scalar: x - s
template <typename T, int N>
inline Jet<T, N> operator-(const Jet<T, N>& f, T s) {
return Jet<T, N>(f.a - s, f.v);
}
// Binary - with a scalar: s - x
template <typename T, int N>
inline Jet<T, N> operator-(T s, const Jet<T, N>& f) {
return Jet<T, N>(s - f.a, -f.v);
}
// Binary *
template <typename T, int N>
inline Jet<T, N> operator*(const Jet<T, N>& f, const Jet<T, N>& g) {
return Jet<T, N>(f.a * g.a, f.a * g.v + f.v * g.a);
}
// Binary * with a scalar: x * s
template <typename T, int N>
inline Jet<T, N> operator*(const Jet<T, N>& f, T s) {
return Jet<T, N>(f.a * s, f.v * s);
}
// Binary * with a scalar: s * x
template <typename T, int N>
inline Jet<T, N> operator*(T s, const Jet<T, N>& f) {
return Jet<T, N>(f.a * s, f.v * s);
}
// Binary /
template <typename T, int N>
inline Jet<T, N> operator/(const Jet<T, N>& f, const Jet<T, N>& g) {
// This uses:
//
// a + u (a + u)(b - v) (a + u)(b - v)
// ----- = -------------- = --------------
// b + v (b + v)(b - v) b^2
//
// which holds because v*v = 0.
const T g_a_inverse = T(1.0) / g.a;
const T f_a_by_g_a = f.a * g_a_inverse;
return Jet<T, N>(f_a_by_g_a, (f.v - f_a_by_g_a * g.v) * g_a_inverse);
}
// Binary / with a scalar: s / x
template <typename T, int N>
inline Jet<T, N> operator/(T s, const Jet<T, N>& g) {
const T minus_s_g_a_inverse2 = -s / (g.a * g.a);
return Jet<T, N>(s / g.a, g.v * minus_s_g_a_inverse2);
}
// Binary / with a scalar: x / s
template <typename T, int N>
inline Jet<T, N> operator/(const Jet<T, N>& f, T s) {
const T s_inverse = T(1.0) / s;
return Jet<T, N>(f.a * s_inverse, f.v * s_inverse);
}
// Binary comparison operators for both scalars and jets. At least one of the
// operands must be a Jet. Promotable scalars (e.g., int, float, double etc.)
// can appear on either side of the operator. std::common_type_t is used as an
// SFINAE constraint to selectively enable compatible operand types. This allows
// comparison, for instance, against int literals without implicit conversion.
// In case the Jet arithmetic type is a Jet itself, a recursive expansion of Jet
// value is performed.
#define CERES_DEFINE_JET_COMPARISON_OPERATOR(op) \
template <typename Lhs, \
typename Rhs, \
std::enable_if_t<PromotableJetOperands_v<Lhs, Rhs>>* = nullptr> \
constexpr bool operator op(const Lhs& f, const Rhs& g) noexcept( \
noexcept(internal::AsScalar(f) op internal::AsScalar(g))) { \
using internal::AsScalar; \
return AsScalar(f) op AsScalar(g); \
}
CERES_DEFINE_JET_COMPARISON_OPERATOR(<) // NOLINT
CERES_DEFINE_JET_COMPARISON_OPERATOR(<=) // NOLINT
CERES_DEFINE_JET_COMPARISON_OPERATOR(>) // NOLINT
CERES_DEFINE_JET_COMPARISON_OPERATOR(>=) // NOLINT
CERES_DEFINE_JET_COMPARISON_OPERATOR(==) // NOLINT
CERES_DEFINE_JET_COMPARISON_OPERATOR(!=) // NOLINT
#undef CERES_DEFINE_JET_COMPARISON_OPERATOR
// Pull some functions from namespace std.
//
// This is necessary because we want to use the same name (e.g. 'sqrt') for
// double-valued and Jet-valued functions, but we are not allowed to put
// Jet-valued functions inside namespace std.
using std::abs;
using std::acos;
using std::asin;
using std::atan;
using std::atan2;
using std::cbrt;
using std::ceil;
using std::copysign;
using std::cos;
using std::cosh;
using std::erf;
using std::erfc;
using std::exp;
using std::exp2;
using std::expm1;
using std::fdim;
using std::floor;
using std::fma;
using std::fmax;
using std::fmin;
using std::fpclassify;
using std::hypot;
using std::isfinite;
using std::isinf;
using std::isnan;
using std::isnormal;
using std::log;
using std::log10;
using std::log1p;
using std::log2;
using std::norm;
using std::pow;
using std::signbit;
using std::sin;
using std::sinh;
using std::sqrt;
using std::tan;
using std::tanh;
// MSVC (up to 1930) defines quiet comparison functions as template functions
// which causes compilation errors due to ambiguity in the template parameter
// type resolution for using declarations in the ceres namespace. Workaround the
// issue by defining specific overload and bypass MSVC standard library
// definitions.
#if defined(_MSC_VER)
inline bool isgreater(double lhs,
double rhs) noexcept(noexcept(std::isgreater(lhs, rhs))) {
return std::isgreater(lhs, rhs);
}
inline bool isless(double lhs,
double rhs) noexcept(noexcept(std::isless(lhs, rhs))) {
return std::isless(lhs, rhs);
}
inline bool islessequal(double lhs,
double rhs) noexcept(noexcept(std::islessequal(lhs,
rhs))) {
return std::islessequal(lhs, rhs);
}
inline bool isgreaterequal(double lhs, double rhs) noexcept(
noexcept(std::isgreaterequal(lhs, rhs))) {
return std::isgreaterequal(lhs, rhs);
}
inline bool islessgreater(double lhs, double rhs) noexcept(
noexcept(std::islessgreater(lhs, rhs))) {
return std::islessgreater(lhs, rhs);
}
inline bool isunordered(double lhs,
double rhs) noexcept(noexcept(std::isunordered(lhs,
rhs))) {
return std::isunordered(lhs, rhs);
}
#else
using std::isgreater;
using std::isgreaterequal;
using std::isless;
using std::islessequal;
using std::islessgreater;
using std::isunordered;
#endif
#ifdef CERES_HAS_CPP20
using std::lerp;
using std::midpoint;
#endif // defined(CERES_HAS_CPP20)
// Legacy names from pre-C++11 days.
// clang-format off
CERES_DEPRECATED_WITH_MSG("ceres::IsFinite will be removed in a future Ceres Solver release. Please use ceres::isfinite.")
inline bool IsFinite(double x) { return std::isfinite(x); }
CERES_DEPRECATED_WITH_MSG("ceres::IsInfinite will be removed in a future Ceres Solver release. Please use ceres::isinf.")
inline bool IsInfinite(double x) { return std::isinf(x); }
CERES_DEPRECATED_WITH_MSG("ceres::IsNaN will be removed in a future Ceres Solver release. Please use ceres::isnan.")
inline bool IsNaN(double x) { return std::isnan(x); }
CERES_DEPRECATED_WITH_MSG("ceres::IsNormal will be removed in a future Ceres Solver release. Please use ceres::isnormal.")
inline bool IsNormal(double x) { return std::isnormal(x); }
// clang-format on
// In general, f(a + h) ~= f(a) + f'(a) h, via the chain rule.
// abs(x + h) ~= abs(x) + sgn(x)h
template <typename T, int N>
inline Jet<T, N> abs(const Jet<T, N>& f) {
return Jet<T, N>(abs(f.a), copysign(T(1), f.a) * f.v);
}
// copysign(a, b) composes a float with the magnitude of a and the sign of b.
// Therefore, the function can be formally defined as
//
// copysign(a, b) = sgn(b)|a|
//
// where
//
// d/dx |x| = sgn(x)
// d/dx sgn(x) = 2δ(x)
//
// sgn(x) being the signum function. Differentiating copysign(a, b) with respect
// to a and b gives:
//
// d/da sgn(b)|a| = sgn(a) sgn(b)
// d/db sgn(b)|a| = 2|a|δ(b)
//
// with the dual representation given by
//
// copysign(a + da, b + db) ~= sgn(b)|a| + (sgn(a)sgn(b) da + 2|a|δ(b) db)
//
// where δ(b) is the Dirac delta function.
template <typename T, int N>
inline Jet<T, N> copysign(const Jet<T, N>& f, const Jet<T, N> g) {
// The Dirac delta function δ(b) is undefined at b=0 (here it's
// infinite) and 0 everywhere else.
T d = fpclassify(g) == FP_ZERO ? std::numeric_limits<T>::infinity() : T(0);
T sa = copysign(T(1), f.a); // sgn(a)
T sb = copysign(T(1), g.a); // sgn(b)
// The second part of the infinitesimal is 2|a|δ(b) which is either infinity
// or 0 unless a or any of the values of the b infinitesimal are 0. In the
// latter case, the corresponding values become NaNs (multiplying 0 by
// infinity gives NaN). We drop the constant factor 2 since it does not change
// the result (its values will still be either 0, infinity or NaN).
return Jet<T, N>(copysign(f.a, g.a), sa * sb * f.v + abs(f.a) * d * g.v);
}
// log(a + h) ~= log(a) + h / a
template <typename T, int N>
inline Jet<T, N> log(const Jet<T, N>& f) {
const T a_inverse = T(1.0) / f.a;
return Jet<T, N>(log(f.a), f.v * a_inverse);
}
// log10(a + h) ~= log10(a) + h / (a log(10))
template <typename T, int N>
inline Jet<T, N> log10(const Jet<T, N>& f) {
// Most compilers will expand log(10) to a constant.
const T a_inverse = T(1.0) / (f.a * log(T(10.0)));
return Jet<T, N>(log10(f.a), f.v * a_inverse);
}
// log1p(a + h) ~= log1p(a) + h / (1 + a)
template <typename T, int N>
inline Jet<T, N> log1p(const Jet<T, N>& f) {
const T a_inverse = T(1.0) / (T(1.0) + f.a);
return Jet<T, N>(log1p(f.a), f.v * a_inverse);
}
// exp(a + h) ~= exp(a) + exp(a) h
template <typename T, int N>
inline Jet<T, N> exp(const Jet<T, N>& f) {
const T tmp = exp(f.a);
return Jet<T, N>(tmp, tmp * f.v);
}
// expm1(a + h) ~= expm1(a) + exp(a) h
template <typename T, int N>
inline Jet<T, N> expm1(const Jet<T, N>& f) {
const T tmp = expm1(f.a);
const T expa = tmp + T(1.0); // exp(a) = expm1(a) + 1
return Jet<T, N>(tmp, expa * f.v);
}
// sqrt(a + h) ~= sqrt(a) + h / (2 sqrt(a))
template <typename T, int N>
inline Jet<T, N> sqrt(const Jet<T, N>& f) {
const T tmp = sqrt(f.a);
const T two_a_inverse = T(1.0) / (T(2.0) * tmp);
return Jet<T, N>(tmp, f.v * two_a_inverse);
}
// cos(a + h) ~= cos(a) - sin(a) h
template <typename T, int N>
inline Jet<T, N> cos(const Jet<T, N>& f) {
return Jet<T, N>(cos(f.a), -sin(f.a) * f.v);
}
// acos(a + h) ~= acos(a) - 1 / sqrt(1 - a^2) h
template <typename T, int N>
inline Jet<T, N> acos(const Jet<T, N>& f) {
const T tmp = -T(1.0) / sqrt(T(1.0) - f.a * f.a);
return Jet<T, N>(acos(f.a), tmp * f.v);
}
// sin(a + h) ~= sin(a) + cos(a) h
template <typename T, int N>
inline Jet<T, N> sin(const Jet<T, N>& f) {
return Jet<T, N>(sin(f.a), cos(f.a) * f.v);
}
// asin(a + h) ~= asin(a) + 1 / sqrt(1 - a^2) h
template <typename T, int N>
inline Jet<T, N> asin(const Jet<T, N>& f) {
const T tmp = T(1.0) / sqrt(T(1.0) - f.a * f.a);
return Jet<T, N>(asin(f.a), tmp * f.v);
}
// tan(a + h) ~= tan(a) + (1 + tan(a)^2) h
template <typename T, int N>
inline Jet<T, N> tan(const Jet<T, N>& f) {
const T tan_a = tan(f.a);
const T tmp = T(1.0) + tan_a * tan_a;
return Jet<T, N>(tan_a, tmp * f.v);
}
// atan(a + h) ~= atan(a) + 1 / (1 + a^2) h
template <typename T, int N>
inline Jet<T, N> atan(const Jet<T, N>& f) {
const T tmp = T(1.0) / (T(1.0) + f.a * f.a);
return Jet<T, N>(atan(f.a), tmp * f.v);
}
// sinh(a + h) ~= sinh(a) + cosh(a) h
template <typename T, int N>
inline Jet<T, N> sinh(const Jet<T, N>& f) {
return Jet<T, N>(sinh(f.a), cosh(f.a) * f.v);
}
// cosh(a + h) ~= cosh(a) + sinh(a) h
template <typename T, int N>
inline Jet<T, N> cosh(const Jet<T, N>& f) {
return Jet<T, N>(cosh(f.a), sinh(f.a) * f.v);
}
// tanh(a + h) ~= tanh(a) + (1 - tanh(a)^2) h
template <typename T, int N>
inline Jet<T, N> tanh(const Jet<T, N>& f) {
const T tanh_a = tanh(f.a);
const T tmp = T(1.0) - tanh_a * tanh_a;
return Jet<T, N>(tanh_a, tmp * f.v);
}
// The floor function should be used with extreme care as this operation will
// result in a zero derivative which provides no information to the solver.
//
// floor(a + h) ~= floor(a) + 0
template <typename T, int N>
inline Jet<T, N> floor(const Jet<T, N>& f) {
return Jet<T, N>(floor(f.a));
}
// The ceil function should be used with extreme care as this operation will
// result in a zero derivative which provides no information to the solver.
//
// ceil(a + h) ~= ceil(a) + 0
template <typename T, int N>
inline Jet<T, N> ceil(const Jet<T, N>& f) {
return Jet<T, N>(ceil(f.a));
}
// Some new additions to C++11:
// cbrt(a + h) ~= cbrt(a) + h / (3 a ^ (2/3))
template <typename T, int N>
inline Jet<T, N> cbrt(const Jet<T, N>& f) {
const T derivative = T(1.0) / (T(3.0) * cbrt(f.a * f.a));
return Jet<T, N>(cbrt(f.a), f.v * derivative);
}
// exp2(x + h) = 2^(x+h) ~= 2^x + h*2^x*log(2)
template <typename T, int N>
inline Jet<T, N> exp2(const Jet<T, N>& f) {
const T tmp = exp2(f.a);
const T derivative = tmp * log(T(2));
return Jet<T, N>(tmp, f.v * derivative);
}
// log2(x + h) ~= log2(x) + h / (x * log(2))
template <typename T, int N>
inline Jet<T, N> log2(const Jet<T, N>& f) {
const T derivative = T(1.0) / (f.a * log(T(2)));
return Jet<T, N>(log2(f.a), f.v * derivative);
}
// Like sqrt(x^2 + y^2),
// but acts to prevent underflow/overflow for small/large x/y.
// Note that the function is non-smooth at x=y=0,
// so the derivative is undefined there.
template <typename T, int N>
inline Jet<T, N> hypot(const Jet<T, N>& x, const Jet<T, N>& y) {
// d/da sqrt(a) = 0.5 / sqrt(a)
// d/dx x^2 + y^2 = 2x
// So by the chain rule:
// d/dx sqrt(x^2 + y^2) = 0.5 / sqrt(x^2 + y^2) * 2x = x / sqrt(x^2 + y^2)
// d/dy sqrt(x^2 + y^2) = y / sqrt(x^2 + y^2)
const T tmp = hypot(x.a, y.a);
return Jet<T, N>(tmp, x.a / tmp * x.v + y.a / tmp * y.v);
}
// Like sqrt(x^2 + y^2 + z^2),
// but acts to prevent underflow/overflow for small/large x/y/z.
// Note that the function is non-smooth at x=y=z=0,
// so the derivative is undefined there.
template <typename T, int N>
inline Jet<T, N> hypot(const Jet<T, N>& x,
const Jet<T, N>& y,
const Jet<T, N>& z) {
// d/da sqrt(a) = 0.5 / sqrt(a)
// d/dx x^2 + y^2 + z^2 = 2x
// So by the chain rule:
// d/dx sqrt(x^2 + y^2 + z^2)
// = 0.5 / sqrt(x^2 + y^2 + z^2) * 2x
// = x / sqrt(x^2 + y^2 + z^2)
// d/dy sqrt(x^2 + y^2 + z^2) = y / sqrt(x^2 + y^2 + z^2)
// d/dz sqrt(x^2 + y^2 + z^2) = z / sqrt(x^2 + y^2 + z^2)
const T tmp = hypot(x.a, y.a, z.a);
return Jet<T, N>(tmp, x.a / tmp * x.v + y.a / tmp * y.v + z.a / tmp * z.v);
}
// Like x * y + z but rounded only once.
template <typename T, int N>
inline Jet<T, N> fma(const Jet<T, N>& x,
const Jet<T, N>& y,
const Jet<T, N>& z) {
// d/dx fma(x, y, z) = y
// d/dy fma(x, y, z) = x
// d/dz fma(x, y, z) = 1
return Jet<T, N>(fma(x.a, y.a, z.a), y.a * x.v + x.a * y.v + z.v);
}
// Return value of fmax() and fmin() on equality
// ---------------------------------------------
//
// There is arguably no good answer to what fmax() & fmin() should return on
// equality, which for Jets by definition ONLY compares the scalar parts. We
// choose what we think is the least worst option (averaging as Jets) which
// minimises undesirable/unexpected behaviour as used, and also supports client
// code written against Ceres versions prior to type promotion being supported
// in Jet comparisons (< v2.1).
//
// The std::max() convention of returning the first argument on equality is
// problematic, as it means that the derivative component may or may not be
// preserved (when comparing a Jet with a scalar) depending upon the ordering.
//
// Always returning the Jet in {Jet, scalar} cases on equality is problematic
// as it is inconsistent with the behaviour that would be obtained if the scalar
// was first cast to Jet and the {Jet, Jet} case was used. Prior to type
// promotion (Ceres v2.1) client code would typically cast constants to Jets
// e.g: fmax(x, T(2.0)) which means the {Jet, Jet} case predominates, and we
// still want the result to be order independent.
//
// Our intuition is that preserving a non-zero derivative is best, even if
// its value does not match either of the inputs. Averaging achieves this
// whilst ensuring argument ordering independence. This is also the approach
// used by the Jax library, and TensorFlow's reduce_max().
// Returns the larger of the two arguments, with Jet averaging on equality.
// NaNs are treated as missing data.
//
// NOTE: This function is NOT subject to any of the error conditions specified
// in `math_errhandling`.
template <typename Lhs,
typename Rhs,
std::enable_if_t<CompatibleJetOperands_v<Lhs, Rhs>>* = nullptr>
inline decltype(auto) fmax(const Lhs& x, const Rhs& y) {
using J = std::common_type_t<Lhs, Rhs>;
// As x == y may set FP exceptions in the presence of NaNs when used with
// non-default compiler options so we avoid its use here.
if (isnan(x) || isnan(y) || islessgreater(x, y)) {
return isnan(x) || isless(x, y) ? J{y} : J{x};
}
// x == y (scalar parts) return the average of their Jet representations.
#if defined(CERES_HAS_CPP20)
return midpoint(J{x}, J{y});
#else
return (J{x} + J{y}) * typename J::Scalar(0.5);
#endif // defined(CERES_HAS_CPP20)
}
// Returns the smaller of the two arguments, with Jet averaging on equality.
// NaNs are treated as missing data.
//
// NOTE: This function is NOT subject to any of the error conditions specified
// in `math_errhandling`.
template <typename Lhs,
typename Rhs,
std::enable_if_t<CompatibleJetOperands_v<Lhs, Rhs>>* = nullptr>
inline decltype(auto) fmin(const Lhs& x, const Rhs& y) {
using J = std::common_type_t<Lhs, Rhs>;
// As x == y may set FP exceptions in the presence of NaNs when used with
// non-default compiler options so we avoid its use here.
if (isnan(x) || isnan(y) || islessgreater(x, y)) {
return isnan(x) || isgreater(x, y) ? J{y} : J{x};
}
// x == y (scalar parts) return the average of their Jet representations.
#if defined(CERES_HAS_CPP20)
return midpoint(J{x}, J{y});
#else
return (J{x} + J{y}) * typename J::Scalar(0.5);
#endif // defined(CERES_HAS_CPP20)
}
// Returns the positive difference (f - g) of two arguments and zero if f <= g.
// If at least one argument is NaN, a NaN is return.
//
// NOTE At least one of the argument types must be a Jet, the other one can be a
// scalar. In case both arguments are Jets, their dimensionality must match.
template <typename Lhs,
typename Rhs,
std::enable_if_t<CompatibleJetOperands_v<Lhs, Rhs>>* = nullptr>
inline decltype(auto) fdim(const Lhs& f, const Rhs& g) {
using J = std::common_type_t<Lhs, Rhs>;
if (isnan(f) || isnan(g)) {
return std::numeric_limits<J>::quiet_NaN();
}
return isgreater(f, g) ? J{f - g} : J{};
}
// erf is defined as an integral that cannot be expressed analytically
// however, the derivative is trivial to compute
// erf(x + h) = erf(x) + h * 2*exp(-x^2)/sqrt(pi)
template <typename T, int N>
inline Jet<T, N> erf(const Jet<T, N>& x) {
// We evaluate the constant as follows:
// 2 / sqrt(pi) = 1 / sqrt(atan(1.))
// On POSIX systems it is defined as M_2_SQRTPI, but this is not
// portable and the type may not be T. The above expression
// evaluates to full precision with IEEE arithmetic and, since it's
// constant, the compiler can generate exactly the same code. gcc
// does so even at -O0.
return Jet<T, N>(erf(x.a), x.v * exp(-x.a * x.a) * (T(1) / sqrt(atan(T(1)))));
}
// erfc(x) = 1-erf(x)
// erfc(x + h) = erfc(x) + h * (-2*exp(-x^2)/sqrt(pi))
template <typename T, int N>
inline Jet<T, N> erfc(const Jet<T, N>& x) {
// See in erf() above for the evaluation of the constant in the derivative.
return Jet<T, N>(erfc(x.a),
-x.v * exp(-x.a * x.a) * (T(1) / sqrt(atan(T(1)))));
}
// Bessel functions of the first kind with integer order equal to 0, 1, n.
//
// Microsoft has deprecated the j[0,1,n]() POSIX Bessel functions in favour of
// _j[0,1,n](). Where available on MSVC, use _j[0,1,n]() to avoid deprecated
// function errors in client code (the specific warning is suppressed when
// Ceres itself is built).
inline double BesselJ0(double x) {
#if defined(CERES_MSVC_USE_UNDERSCORE_PREFIXED_BESSEL_FUNCTIONS)
return _j0(x);
#else
return j0(x);
#endif
}
inline double BesselJ1(double x) {
#if defined(CERES_MSVC_USE_UNDERSCORE_PREFIXED_BESSEL_FUNCTIONS)
return _j1(x);
#else
return j1(x);
#endif
}
inline double BesselJn(int n, double x) {
#if defined(CERES_MSVC_USE_UNDERSCORE_PREFIXED_BESSEL_FUNCTIONS)
return _jn(n, x);
#else
return jn(n, x);
#endif
}
// For the formulae of the derivatives of the Bessel functions see the book:
// Olver, Lozier, Boisvert, Clark, NIST Handbook of Mathematical Functions,
// Cambridge University Press 2010.
//
// Formulae are also available at http://dlmf.nist.gov
// See formula http://dlmf.nist.gov/10.6#E3
// j0(a + h) ~= j0(a) - j1(a) h
template <typename T, int N>
inline Jet<T, N> BesselJ0(const Jet<T, N>& f) {
return Jet<T, N>(BesselJ0(f.a), -BesselJ1(f.a) * f.v);
}
// See formula http://dlmf.nist.gov/10.6#E1
// j1(a + h) ~= j1(a) + 0.5 ( j0(a) - j2(a) ) h
template <typename T, int N>
inline Jet<T, N> BesselJ1(const Jet<T, N>& f) {
return Jet<T, N>(BesselJ1(f.a),
T(0.5) * (BesselJ0(f.a) - BesselJn(2, f.a)) * f.v);
}
// See formula http://dlmf.nist.gov/10.6#E1
// j_n(a + h) ~= j_n(a) + 0.5 ( j_{n-1}(a) - j_{n+1}(a) ) h
template <typename T, int N>
inline Jet<T, N> BesselJn(int n, const Jet<T, N>& f) {
return Jet<T, N>(
BesselJn(n, f.a),
T(0.5) * (BesselJn(n - 1, f.a) - BesselJn(n + 1, f.a)) * f.v);
}
// Classification and comparison functionality referencing only the scalar part
// of a Jet. To classify the derivatives (e.g., for sanity checks), the dual
// part should be referenced explicitly. For instance, to check whether the
// derivatives of a Jet 'f' are reasonable, one can use
//
// isfinite(f.v.array()).all()
// !isnan(f.v.array()).any()
//
// etc., depending on the desired semantics.
//
// NOTE: Floating-point classification and comparison functions and operators
// should be used with care as no derivatives can be propagated by such
// functions directly but only by expressions resulting from corresponding
// conditional statements. At the same time, conditional statements can possibly
// introduce a discontinuity in the cost function making it impossible to
// evaluate its derivative and thus the optimization problem intractable.
// Determines whether the scalar part of the Jet is finite.
template <typename T, int N>
inline bool isfinite(const Jet<T, N>& f) {
return isfinite(f.a);
}
// Determines whether the scalar part of the Jet is infinite.
template <typename T, int N>
inline bool isinf(const Jet<T, N>& f) {
return isinf(f.a);
}
// Determines whether the scalar part of the Jet is NaN.
template <typename T, int N>
inline bool isnan(const Jet<T, N>& f) {
return isnan(f.a);
}
// Determines whether the scalar part of the Jet is neither zero, subnormal,
// infinite, nor NaN.
template <typename T, int N>
inline bool isnormal(const Jet<T, N>& f) {
return isnormal(f.a);
}
// Determines whether the scalar part of the Jet f is less than the scalar
// part of g.
//
// NOTE: This function does NOT set any floating-point exceptions.
template <typename Lhs,
typename Rhs,
std::enable_if_t<CompatibleJetOperands_v<Lhs, Rhs>>* = nullptr>
inline bool isless(const Lhs& f, const Rhs& g) {
using internal::AsScalar;
return isless(AsScalar(f), AsScalar(g));
}
// Determines whether the scalar part of the Jet f is greater than the scalar
// part of g.
//
// NOTE: This function does NOT set any floating-point exceptions.
template <typename Lhs,
typename Rhs,
std::enable_if_t<CompatibleJetOperands_v<Lhs, Rhs>>* = nullptr>
inline bool isgreater(const Lhs& f, const Rhs& g) {
using internal::AsScalar;
return isgreater(AsScalar(f), AsScalar(g));
}
// Determines whether the scalar part of the Jet f is less than or equal to the
// scalar part of g.
//
// NOTE: This function does NOT set any floating-point exceptions.
template <typename Lhs,
typename Rhs,
std::enable_if_t<CompatibleJetOperands_v<Lhs, Rhs>>* = nullptr>
inline bool islessequal(const Lhs& f, const Rhs& g) {
using internal::AsScalar;
return islessequal(AsScalar(f), AsScalar(g));
}
// Determines whether the scalar part of the Jet f is less than or greater than
// (f < g || f > g) the scalar part of g.
//
// NOTE: This function does NOT set any floating-point exceptions.
template <typename Lhs,
typename Rhs,
std::enable_if_t<CompatibleJetOperands_v<Lhs, Rhs>>* = nullptr>
inline bool islessgreater(const Lhs& f, const Rhs& g) {
using internal::AsScalar;
return islessgreater(AsScalar(f), AsScalar(g));
}
// Determines whether the scalar part of the Jet f is greater than or equal to
// the scalar part of g.
//
// NOTE: This function does NOT set any floating-point exceptions.
template <typename Lhs,
typename Rhs,
std::enable_if_t<CompatibleJetOperands_v<Lhs, Rhs>>* = nullptr>
inline bool isgreaterequal(const Lhs& f, const Rhs& g) {
using internal::AsScalar;
return isgreaterequal(AsScalar(f), AsScalar(g));
}
// Determines if either of the scalar parts of the arguments are NaN and
// thus cannot be ordered with respect to each other.
template <typename Lhs,
typename Rhs,
std::enable_if_t<CompatibleJetOperands_v<Lhs, Rhs>>* = nullptr>
inline bool isunordered(const Lhs& f, const Rhs& g) {
using internal::AsScalar;
return isunordered(AsScalar(f), AsScalar(g));
}
// Categorize scalar part as zero, subnormal, normal, infinite, NaN, or
// implementation-defined.
template <typename T, int N>
inline int fpclassify(const Jet<T, N>& f) {
return fpclassify(f.a);
}
// Determines whether the scalar part of the argument is negative.
template <typename T, int N>
inline bool signbit(const Jet<T, N>& f) {
return signbit(f.a);
}
// Legacy functions from the pre-C++11 days.
template <typename T, int N>
CERES_DEPRECATED_WITH_MSG(
"ceres::IsFinite will be removed in a future Ceres Solver release. Please "
"use ceres::isfinite.")
inline bool IsFinite(const Jet<T, N>& f) {
return isfinite(f);
}
template <typename T, int N>
CERES_DEPRECATED_WITH_MSG(
"ceres::IsNaN will be removed in a future Ceres Solver release. Please use "
"ceres::isnan.")
inline bool IsNaN(const Jet<T, N>& f) {
return isnan(f);
}
template <typename T, int N>
CERES_DEPRECATED_WITH_MSG(
"ceres::IsNormal will be removed in a future Ceres Solver release. Please "
"use ceres::isnormal.")
inline bool IsNormal(const Jet<T, N>& f) {
return isnormal(f);
}
// The jet is infinite if any part of the jet is infinite.
template <typename T, int N>
CERES_DEPRECATED_WITH_MSG(
"ceres::IsInfinite will be removed in a future Ceres Solver release. "
"Please use ceres::isinf.")
inline bool IsInfinite(const Jet<T, N>& f) {
return isinf(f);
}
#ifdef CERES_HAS_CPP20
// Computes the linear interpolation a + t(b - a) between a and b at the value
// t. For arguments outside of the range 0 <= t <= 1, the values are
// extrapolated.
//
// Differentiating lerp(a, b, t) with respect to a, b, and t gives:
//
// d/da lerp(a, b, t) = 1 - t
// d/db lerp(a, b, t) = t
// d/dt lerp(a, b, t) = b - a
//
// with the dual representation given by
//
// lerp(a + da, b + db, t + dt)
// ~= lerp(a, b, t) + (1 - t) da + t db + (b - a) dt .
template <typename T, int N>
inline Jet<T, N> lerp(const Jet<T, N>& a,
const Jet<T, N>& b,
const Jet<T, N>& t) {
return Jet<T, N>{lerp(a.a, b.a, t.a),
(T(1) - t.a) * a.v + t.a * b.v + (b.a - a.a) * t.v};
}
// Computes the midpoint a + (b - a) / 2.
//
// Differentiating midpoint(a, b) with respect to a and b gives:
//
// d/da midpoint(a, b) = 1/2
// d/db midpoint(a, b) = 1/2
//
// with the dual representation given by
//
// midpoint(a + da, b + db) ~= midpoint(a, b) + (da + db) / 2 .
template <typename T, int N>
inline Jet<T, N> midpoint(const Jet<T, N>& a, const Jet<T, N>& b) {
Jet<T, N> result{midpoint(a.a, b.a)};
// To avoid overflow in the differential, compute
// (da + db) / 2 using midpoint.
for (int i = 0; i < N; ++i) {
result.v[i] = midpoint(a.v[i], b.v[i]);
}
return result;
}
#endif // defined(CERES_HAS_CPP20)
// atan2(b + db, a + da) ~= atan2(b, a) + (- b da + a db) / (a^2 + b^2)
//
// In words: the rate of change of theta is 1/r times the rate of
// change of (x, y) in the positive angular direction.
template <typename T, int N>
inline Jet<T, N> atan2(const Jet<T, N>& g, const Jet<T, N>& f) {
// Note order of arguments:
//
// f = a + da
// g = b + db
T const tmp = T(1.0) / (f.a * f.a + g.a * g.a);
return Jet<T, N>(atan2(g.a, f.a), tmp * (-g.a * f.v + f.a * g.v));
}
// Computes the square x^2 of a real number x (not the Euclidean L^2 norm as
// the name might suggest).
//
// NOTE: While std::norm is primarily intended for computing the squared
// magnitude of a std::complex<> number, the current Jet implementation does not
// support mixing a scalar T in its real part and std::complex<T> and in the
// infinitesimal. Mixed Jet support is necessary for the type decay from
// std::complex<T> to T (the squared magnitude of a complex number is always
// real) performed by std::norm.
//
// norm(x + h) ~= norm(x) + 2x h
template <typename T, int N>
inline Jet<T, N> norm(const Jet<T, N>& f) {
return Jet<T, N>(norm(f.a), T(2) * f.a * f.v);
}
// pow -- base is a differentiable function, exponent is a constant.
// (a+da)^p ~= a^p + p*a^(p-1) da
template <typename T, int N>
inline Jet<T, N> pow(const Jet<T, N>& f, double g) {
T const tmp = g * pow(f.a, g - T(1.0));
return Jet<T, N>(pow(f.a, g), tmp * f.v);
}
// pow -- base is a constant, exponent is a differentiable function.
// We have various special cases, see the comment for pow(Jet, Jet) for
// analysis:
//
// 1. For f > 0 we have: (f)^(g + dg) ~= f^g + f^g log(f) dg
//
// 2. For f == 0 and g > 0 we have: (f)^(g + dg) ~= f^g
//
// 3. For f < 0 and integer g we have: (f)^(g + dg) ~= f^g but if dg
// != 0, the derivatives are not defined and we return NaN.
template <typename T, int N>
inline Jet<T, N> pow(T f, const Jet<T, N>& g) {
Jet<T, N> result;
if (fpclassify(f) == FP_ZERO && g > 0) {
// Handle case 2.
result = Jet<T, N>(T(0.0));
} else {
if (f < 0 && g == floor(g.a)) { // Handle case 3.
result = Jet<T, N>(pow(f, g.a));
for (int i = 0; i < N; i++) {
if (fpclassify(g.v[i]) != FP_ZERO) {
// Return a NaN when g.v != 0.
result.v[i] = std::numeric_limits<T>::quiet_NaN();
}
}
} else {
// Handle case 1.
T const tmp = pow(f, g.a);
result = Jet<T, N>(tmp, log(f) * tmp * g.v);
}
}
return result;
}
// pow -- both base and exponent are differentiable functions. This has a
// variety of special cases that require careful handling.
//
// 1. For f > 0:
// (f + df)^(g + dg) ~= f^g + f^(g - 1) * (g * df + f * log(f) * dg)
// The numerical evaluation of f * log(f) for f > 0 is well behaved, even for
// extremely small values (e.g. 1e-99).
//
// 2. For f == 0 and g > 1: (f + df)^(g + dg) ~= 0
// This cases is needed because log(0) can not be evaluated in the f > 0
// expression. However the function f*log(f) is well behaved around f == 0
// and its limit as f-->0 is zero.
//
// 3. For f == 0 and g == 1: (f + df)^(g + dg) ~= 0 + df
//
// 4. For f == 0 and 0 < g < 1: The value is finite but the derivatives are not.
//
// 5. For f == 0 and g < 0: The value and derivatives of f^g are not finite.
//
// 6. For f == 0 and g == 0: The C standard incorrectly defines 0^0 to be 1
// "because there are applications that can exploit this definition". We
// (arbitrarily) decree that derivatives here will be nonfinite, since that
// is consistent with the behavior for f == 0, g < 0 and 0 < g < 1.
// Practically any definition could have been justified because mathematical
// consistency has been lost at this point.
//
// 7. For f < 0, g integer, dg == 0: (f + df)^(g + dg) ~= f^g + g * f^(g - 1) df
// This is equivalent to the case where f is a differentiable function and g
// is a constant (to first order).
//
// 8. For f < 0, g integer, dg != 0: The value is finite but the derivatives are
// not, because any change in the value of g moves us away from the point
// with a real-valued answer into the region with complex-valued answers.
//
// 9. For f < 0, g noninteger: The value and derivatives of f^g are not finite.
template <typename T, int N>
inline Jet<T, N> pow(const Jet<T, N>& f, const Jet<T, N>& g) {
Jet<T, N> result;
if (fpclassify(f) == FP_ZERO && g >= 1) {
// Handle cases 2 and 3.
if (g > 1) {
result = Jet<T, N>(T(0.0));
} else {
result = f;
}
} else {
if (f < 0 && g == floor(g.a)) {
// Handle cases 7 and 8.
T const tmp = g.a * pow(f.a, g.a - T(1.0));
result = Jet<T, N>(pow(f.a, g.a), tmp * f.v);
for (int i = 0; i < N; i++) {
if (fpclassify(g.v[i]) != FP_ZERO) {
// Return a NaN when g.v != 0.
result.v[i] = T(std::numeric_limits<double>::quiet_NaN());
}
}
} else {
// Handle the remaining cases. For cases 4,5,6,9 we allow the log()
// function to generate -HUGE_VAL or NaN, since those cases result in a
// nonfinite derivative.
T const tmp1 = pow(f.a, g.a);
T const tmp2 = g.a * pow(f.a, g.a - T(1.0));
T const tmp3 = tmp1 * log(f.a);
result = Jet<T, N>(tmp1, tmp2 * f.v + tmp3 * g.v);
}
}
return result;
}
// Note: This has to be in the ceres namespace for argument dependent lookup to
// function correctly. Otherwise statements like CHECK_LE(x, 2.0) fail with
// strange compile errors.
template <typename T, int N>
inline std::ostream& operator<<(std::ostream& s, const Jet<T, N>& z) {
s << "[" << z.a << " ; ";
for (int i = 0; i < N; ++i) {
s << z.v[i];
if (i != N - 1) {
s << ", ";
}
}
s << "]";
return s;
}
} // namespace ceres
namespace std {
template <typename T, int N>
struct numeric_limits<ceres::Jet<T, N>> {
static constexpr bool is_specialized = true;
static constexpr bool is_signed = std::numeric_limits<T>::is_signed;
static constexpr bool is_integer = std::numeric_limits<T>::is_integer;
static constexpr bool is_exact = std::numeric_limits<T>::is_exact;
static constexpr bool has_infinity = std::numeric_limits<T>::has_infinity;
static constexpr bool has_quiet_NaN = std::numeric_limits<T>::has_quiet_NaN;
static constexpr bool has_signaling_NaN =
std::numeric_limits<T>::has_signaling_NaN;
static constexpr bool is_iec559 = std::numeric_limits<T>::is_iec559;
static constexpr bool is_bounded = std::numeric_limits<T>::is_bounded;
static constexpr bool is_modulo = std::numeric_limits<T>::is_modulo;
static constexpr std::float_denorm_style has_denorm =
std::numeric_limits<T>::has_denorm;
static constexpr std::float_round_style round_style =
std::numeric_limits<T>::round_style;
static constexpr int digits = std::numeric_limits<T>::digits;
static constexpr int digits10 = std::numeric_limits<T>::digits10;
static constexpr int max_digits10 = std::numeric_limits<T>::max_digits10;
static constexpr int radix = std::numeric_limits<T>::radix;
static constexpr int min_exponent = std::numeric_limits<T>::min_exponent;
static constexpr int min_exponent10 = std::numeric_limits<T>::max_exponent10;
static constexpr int max_exponent = std::numeric_limits<T>::max_exponent;
static constexpr int max_exponent10 = std::numeric_limits<T>::max_exponent10;
static constexpr bool traps = std::numeric_limits<T>::traps;
static constexpr bool tinyness_before =
std::numeric_limits<T>::tinyness_before;
static constexpr ceres::Jet<T, N> min
CERES_PREVENT_MACRO_SUBSTITUTION() noexcept {
return ceres::Jet<T, N>((std::numeric_limits<T>::min)());
}
static constexpr ceres::Jet<T, N> lowest() noexcept {
return ceres::Jet<T, N>(std::numeric_limits<T>::lowest());
}
static constexpr ceres::Jet<T, N> epsilon() noexcept {
return ceres::Jet<T, N>(std::numeric_limits<T>::epsilon());
}
static constexpr ceres::Jet<T, N> round_error() noexcept {
return ceres::Jet<T, N>(std::numeric_limits<T>::round_error());
}
static constexpr ceres::Jet<T, N> infinity() noexcept {
return ceres::Jet<T, N>(std::numeric_limits<T>::infinity());
}
static constexpr ceres::Jet<T, N> quiet_NaN() noexcept {
return ceres::Jet<T, N>(std::numeric_limits<T>::quiet_NaN());
}
static constexpr ceres::Jet<T, N> signaling_NaN() noexcept {
return ceres::Jet<T, N>(std::numeric_limits<T>::signaling_NaN());
}
static constexpr ceres::Jet<T, N> denorm_min() noexcept {
return ceres::Jet<T, N>(std::numeric_limits<T>::denorm_min());
}
static constexpr ceres::Jet<T, N> max
CERES_PREVENT_MACRO_SUBSTITUTION() noexcept {
return ceres::Jet<T, N>((std::numeric_limits<T>::max)());
}
};
} // namespace std
namespace Eigen {
// Creating a specialization of NumTraits enables placing Jet objects inside
// Eigen arrays, getting all the goodness of Eigen combined with autodiff.
template <typename T, int N>
struct NumTraits<ceres::Jet<T, N>> {
using Real = ceres::Jet<T, N>;
using NonInteger = ceres::Jet<T, N>;
using Nested = ceres::Jet<T, N>;
using Literal = ceres::Jet<T, N>;
static typename ceres::Jet<T, N> dummy_precision() {
return ceres::Jet<T, N>(1e-12);
}
static inline Real epsilon() {
return Real(std::numeric_limits<T>::epsilon());
}
static inline int digits10() { return NumTraits<T>::digits10(); }
static inline int max_digits10() { return NumTraits<T>::max_digits10(); }
enum {
IsComplex = 0,
IsInteger = 0,
IsSigned,
ReadCost = 1,
AddCost = 1,
// For Jet types, multiplication is more expensive than addition.
MulCost = 3,
HasFloatingPoint = 1,
RequireInitialization = 1
};
template <bool Vectorized>
struct Div {
enum {
#if defined(EIGEN_VECTORIZE_AVX)
AVX = true,
#else
AVX = false,
#endif
// Assuming that for Jets, division is as expensive as
// multiplication.
Cost = 3
};
};
static inline Real highest() { return Real((std::numeric_limits<T>::max)()); }
static inline Real lowest() { return Real(-(std::numeric_limits<T>::max)()); }
};
// Specifying the return type of binary operations between Jets and scalar types
// allows you to perform matrix/array operations with Eigen matrices and arrays
// such as addition, subtraction, multiplication, and division where one Eigen
// matrix/array is of type Jet and the other is a scalar type. This improves
// performance by using the optimized scalar-to-Jet binary operations but
// is only available on Eigen versions >= 3.3
template <typename BinaryOp, typename T, int N>
struct ScalarBinaryOpTraits<ceres::Jet<T, N>, T, BinaryOp> {
using ReturnType = ceres::Jet<T, N>;
};
template <typename BinaryOp, typename T, int N>
struct ScalarBinaryOpTraits<T, ceres::Jet<T, N>, BinaryOp> {
using ReturnType = ceres::Jet<T, N>;
};
} // namespace Eigen
#endif // CERES_PUBLIC_JET_H_
|
8012c12dd7a5901ac5f976baa0a77f984086c951 | bfdb98cdb95ce47f55157141f4de77cbdb388df4 | /PWSMJ/CpuUsage.h | e4acd7a492391c62cceaa70ec1defc1a0f9fdfd6 | [] | no_license | ruanzx/PSMJ | dda70c1eb935aa7e4e0d745a73d94ad8da714e3b | e621e309ef51c190e13b220e6b871896c8b0e0e7 | refs/heads/master | 2021-01-20T11:23:01.480753 | 2015-07-07T06:52:28 | 2015-07-07T06:52:28 | 38,668,767 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,045 | h | CpuUsage.h | /////////////////////////////////////////////////////////////////////////////////////////////////
// Determine CPU usage of current process
// http://www.philosophicalgeek.com/2009/01/03/determine-cpu-usage-of-current-process-c-and-c/
// Add GetCpuTime function
/////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <windows.h>
class CpuUsage
{
public:
CpuUsage(void);
void Calculate();
double GetCpuTime();
double GetTotalCpuTime();
short GetCpuUsage();
private:
ULONGLONG SubtractTimes(const FILETIME& ftA, const FILETIME& ftB);
bool EnoughTimePassed();
inline bool IsFirstRun() const { return (m_dwLastRun == 0); }
//system total times
FILETIME m_ftPrevSysKernel;
FILETIME m_ftPrevSysUser;
//process times
FILETIME m_ftPrevProcKernel;
FILETIME m_ftPrevProcUser;
short m_nCpuUsage;
double m_nCpuTimeTotal;
double m_nCpuTimeDiff;
double m_nCpuTime[2]; // struct for prev and current cpu time
ULONGLONG m_dwLastRun;
volatile LONG m_lRunCount;
};
|
0e2b4a4bf2477b05070f0b6bc4ee50d81127c426 | 534f1bb6a4cc2ac5d337ea0be7b8f00017b8169c | /motors/ESC.cpp | 92ecabaac6a6b3a903deaf426f0802b0e49dafbe | [] | no_license | KLINKBOT/arduino | 96c99cfd5d121fafe66638e1c957b54d56fea2eb | 129535e10a8aa05a5b2da6ce7b8a4aee4a635864 | refs/heads/master | 2021-01-22T14:46:50.881190 | 2012-03-29T06:57:13 | 2012-03-29T06:57:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,958 | cpp | ESC.cpp | #include "ESC.h"
#include "MotorController.h"
ESC::ESC(PlatformMotionController &platform, byte pinA, byte pinB) : platform(&platform), previous(0), state(Running) {
memzero(&motorA, sizeof(motor_t));
memzero(&motorB, sizeof(motor_t));
motorA.pin = pinA;
motorB.pin = pinB;
}
void ESC::begin() {
}
void ESC::configure(uint16_t a, uint16_t b) {
motorA.target = a;
motorB.target = b;
}
void ESC::service() {
if (motorA.target == 0 && motorB.target == 0) {
return;
}
uint32_t now = micros();
switch (state) {
case Running:
if (!platform->isMoving()) {
return;
}
if (now - previous > 100000) {
platform->fill(&command);
platform->stop();
state = Draining;
previous = now;
}
break;
case Draining:
if (now - previous > 2000) {
state = Measuring;
motorA.accumulator = 0;
motorB.accumulator = 0;
samples = 0;
previous = now;
}
break;
case Measuring:
motorA.accumulator += analogRead(motorA.pin);
motorB.accumulator += analogRead(motorB.pin);
samples++;
if (now - previous > 2000) {
adjust();
previous = now;
}
break;
}
}
void ESC::adjust() {
uint16_t leftRate = (int16_t)(motorA.accumulator / samples);
int16_t leftDifference = motorA.target - leftRate;
byte newLeftSpeed = constrain(command.l.speed + leftDifference / 2, 0, 255);
uint16_t rightRate = (int16_t)(motorB.accumulator / samples);
int16_t rightDifference = motorB.target - rightRate;
byte newRightSpeed = constrain(command.r.speed + rightDifference / 2, 0, 255);
command.l.speed = newLeftSpeed;
command.r.speed = newRightSpeed;
platform->execute(&command);
#ifdef ESC_LOGGING
DPRINTF("%3d %3d %3d, %3d %3d %3d, %2d\r\n",
leftRate, leftDifference, newLeftSpeed,
rightRate, rightDifference, newRightSpeed,
newRightSpeed - newLeftSpeed
);
#endif
platform->execute(&command);
state = Running;
}
|
b2fd221e551f8043672fee371d954f0fc40b0947 | 7650416e9539e1383ce2882107299f0d3f7d40fb | /eng/wrappers/mbed/platform/plat_oride.h | e03b9c08d9f33ab12402e77300acd099f40c3de5 | [
"Apache-2.0"
] | permissive | OpenNuvoton/NuMaker-mbed-Aliyun-IoT-CSDK | 42737cb7ea900fd0638c0121727653a70d29a266 | 0565717f5b793a6ed6bb633191912ad91a457d31 | refs/heads/master | 2020-11-30T10:33:08.432854 | 2019-12-27T06:41:30 | 2019-12-27T06:41:30 | 230,378,587 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,111 | h | plat_oride.h | /*
* Copyright (c) 2019-2020, Nuvoton Technology Corporation
*
* SPDX-License-Identifier: Apache-2.0
*
* 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 PLAT_ORIDE_H
#define PLAT_ORIDE_H
#include "mbed.h"
namespace aliyun_iotkit { namespace plat_fs
{
/* Prepare default file system in mbed */
FileSystem *fs_prepare(void);
}}
namespace aliyun_iotkit { namespace plat_net
{
/* Prepare default network interface in mbed */
NetworkInterface *net_prepare(void);
}}
using namespace aliyun_iotkit::plat_fs;
using namespace aliyun_iotkit::plat_net;
#endif /* plat_oride.h */
|
ef6f8b8d044229ebee30a0020f85bbe8753fdb8d | b21bcc5c2203ce4a7d5ceb9bcf0d72cf79db6abc | /thread_study/socket_stream/srv/src/srv.cpp | c9ae33215a4840be1f9ad6e87f8472731e4fa4bd | [] | no_license | zhaoyunfuture/study | 81ad69a4abfedb3d14efa1080a2bcf091ab2e1a8 | ebed9809c84c31ff67b988b3bb3c3289b2b818d7 | refs/heads/master | 2022-01-18T21:33:06.613463 | 2022-01-09T13:19:58 | 2022-01-09T13:19:58 | 47,873,321 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,261 | cpp | srv.cpp | #include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include "my.pb.h"
#include "data.h"
using namespace std;
int my_read(int fd,char *buffer,int length){
int bytes_left;
int bytes_read;
char *ptr;
ptr = buffer;
bytes_left=length;
while(bytes_left>0){
bytes_read = read(fd, ptr,bytes_read);
cout << "read bytes: " << bytes_read << endl;
if(bytes_read<0) {
if(errno==EINTR)
bytes_read=0;
else
return(-1);
}else if(bytes_read==0)
break;
bytes_left-=bytes_read;
ptr+=bytes_read;
}
return(length-bytes_left);
}
void addressinfo(const tutorial::AddressBook& address_book)
{
cout <<"people size: " << address_book.people_size() << endl;
for (int i = 0; i < address_book.people_size(); i++) {
const tutorial::Person& person = address_book.people(i);
cout << "people ID: " << person.id() << endl;
cout << " Name: " << person.name() << endl;
if (person.email() != "") {
cout << " E-mail address: " << person.email() << endl;
}
}
}
int main()
{
int server_sockfd = -1;
int client_sockfd = -1;
socklen_t client_len = 0;
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
//创建流套接字
server_sockfd = socket(AF_INET, SOCK_STREAM, 0);
//设置服务器接收的连接地址和监听的端口
server_addr.sin_family = AF_INET;//指定网络套接字
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);//接受所有IP地址的连接
server_addr.sin_port = htons(9736);//绑定到9736端口
//绑定(命名)套接字
bind(server_sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr));
//创建套接字队列,监听套接字
listen(server_sockfd, 5);
//忽略子进程停止或退出信号
signal(SIGCHLD, SIG_IGN);
while(1)
{
//char ch = '\0';
client_len = sizeof(client_addr);
printf("Server waiting\n");
client_sockfd = accept(server_sockfd, (struct sockaddr*)&client_addr, &client_len);
if(fork() == 0)
{
//read(client_sockfd, &ch , 1);
char buf[sizeof(data)];
int readlen=0;
//readlen = my_read(client_sockfd,buf,IPC_MAX_LEN);
readlen = read(client_sockfd,buf,sizeof(data));
cout << "readlen: " << readlen << endl;
#if 0
data* d;
d = (data*) buf;
cout << "d.a: " << d->a << endl;
cout << "d.b: " << d->b << endl;
cout << "d.len: " << d->len << endl;
cout << "d.c: " << d->c << endl;
#endif
data* d = (data*) buf;
cout << "d->len: " <<d->len << endl;
tutorial::AddressBook address_book;
if (!address_book.ParseFromArray(d->c,d->len)) {
cerr << "Failed to parse address book." << endl;
return -1;
}
addressinfo(address_book);
close(client_sockfd);
exit(0);
}
else
{
//父进程中,关闭套接字
close(client_sockfd);
}
}
return 0;
}
|
d4726a35211acc49ef40ddbcdaca8423b0494608 | cbedce64d34da490d4abe1da40a85952aaeb32b5 | /Camera.h | a50835b58f003967cb3fea7f87a8d2ea7739f76e | [
"MIT"
] | permissive | manueme/the-island | 1a8942d8724bdd53cc39aecf60cdc46675daeb53 | f5100ae45dae48c357926f9df86d35b0b8602677 | refs/heads/master | 2020-08-05T14:40:25.792957 | 2019-10-03T12:47:36 | 2019-10-03T12:47:36 | 212,576,286 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 986 | h | Camera.h | #pragma once
#include "Component.h"
#include <glm/glm.hpp>
class GameObject;
class Transform;
class Camera final : public Component {
public:
explicit Camera(const shared_ptr<GameObject>& parent);
~Camera();
void updateVectors();
ComponentKey getComponentKey() override;
void setLookAt(float x, float y, float z);
void setCameraFront(float x, float y, float z);
void setCameraUp(float x, float y, float z);
void setCameraRight(float x, float y, float z);
glm::vec3 getPos() const;
glm::vec3 getLookAt() const;
glm::vec3 getCameraUp() const;
glm::vec3 getCameraRight() const;
glm::vec3 getCameraFront() const;
glm::mat4 getViewMatrix() const;
void objectMounted() override;
bool mainCamera;
float horizontalFOV;
float screenWidth;
float screenHeight;
private:
glm::vec3 lookAt;
glm::vec3 cameraUp;
glm::vec3 cameraFront;
glm::vec3 cameraRight;
shared_ptr<Transform> parentTransform;
};
|
1d63f7e4c9cbb164cac91dd4f9a68f6effdcea6f | 0e650fb278b137e0842817248270e6c7d07606ab | /nemux-test/Cpu-test-loadstore.cpp | cf54304811bae62e704bd8d451c1248ce9fffacb | [
"MIT"
] | permissive | svenzin/nemux | fb83c7f01790c34d4559a071e25fb871dc3157c4 | 087972503c490c8e26f24ff1b39284a4666dc7b7 | refs/heads/master | 2021-12-19T00:03:35.938910 | 2021-12-11T15:53:01 | 2021-12-11T15:53:01 | 10,719,054 | 0 | 0 | MIT | 2021-11-24T18:20:06 | 2013-06-16T11:21:00 | C++ | UTF-8 | C++ | false | false | 13,524 | cpp | Cpu-test-loadstore.cpp | /*
* Cpu-test-loadstore.cpp
*
* Created on: 07 Jul 2013
* Author: scorder
*/
#include "gtest/gtest.h"
#include "Cpu.h"
#include <vector>
#include <map>
#include <array>
#include <functional>
using namespace std;
using namespace Instructions;
using namespace Addressing;
class CpuTestLoadStore : public ::testing::Test {
public:
static const Word BASE_PC = 10;
static const int BASE_TICKS = 10;
CpuTestLoadStore() : cpu("6502", &memory) {
cpu.PC = BASE_PC;
cpu.Ticks = BASE_TICKS;
}
MemoryBlock<0x10000> memory;
Cpu cpu;
template<typename Getter, typename Setter>
void Test_Set(Getter get, Setter set, Opcode op) {
set(0x80);
cpu.Execute(op);
EXPECT_EQ(BASE_PC + op.Bytes, cpu.PC);
EXPECT_EQ(BASE_TICKS + op.Cycles, cpu.Ticks);
EXPECT_EQ(0x80, get());
}
template<typename Getter, typename Setter>
void Test_Load(Getter get, Setter set, Opcode op, int extra) {
auto tester = [&] (Byte m, Flag expZ, Flag expN) {
set(m);
cpu.PC = BASE_PC;
cpu.Ticks = BASE_TICKS;
cpu.Execute(op);
EXPECT_EQ(BASE_PC + op.Bytes, cpu.PC);
EXPECT_EQ(BASE_TICKS + op.Cycles + extra, cpu.Ticks);
EXPECT_EQ(m, get());
EXPECT_EQ(expZ, cpu.Z);
EXPECT_EQ(expN, cpu.N);
};
tester(0x20, 0, 0);
tester(0x00, 1, 0);
tester(0x80, 0, 1);
}
function<void (Byte)> Setter(Byte & a) {
return [&] (Byte value) { a = value; };
}
function<void (Byte)> Setter(Word a) {
return [=] (Byte value) { cpu.WriteByteAt(a, value); };
}
function<Byte ()> Getter(Byte & b) {
return [&] () { return b; };
}
function<Byte ()> Getter(Word a) {
return [=] () { return cpu.ReadByteAt(a); };
}
};
TEST_F(CpuTestLoadStore, LDX_Immediate) {
cpu.WriteByteAt(BASE_PC, 0xFF);
Test_Load(Getter(cpu.X), Setter(BASE_PC + 1),
Opcode(LDX, Immediate, 2, 2), 0);
}
TEST_F(CpuTestLoadStore, LDX_ZeroPage) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteByteAt(BASE_PC + 1, 0x20);
Test_Load(Getter(cpu.X), Setter(0x0020),
Opcode(LDX, ZeroPage, 2, 3), 0);
}
TEST_F(CpuTestLoadStore, LDX_ZeroPageY) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteByteAt(BASE_PC + 1, 0x20);
cpu.Y = 0x08;
Test_Load(Getter(cpu.X), Setter(0x0028),
Opcode(LDX, ZeroPageY, 2, 4), 0);
}
TEST_F(CpuTestLoadStore, LDX_ZeroPageY_Wraparound) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteByteAt(BASE_PC + 1, 0xF0);
cpu.Y = 0x10;
Test_Load(Getter(cpu.X), Setter(0x0000),
Opcode(LDX, ZeroPageY, 2, 4), 0);
}
TEST_F(CpuTestLoadStore, LDX_Absolute) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteWordAt(BASE_PC + 1, 0x0120);
Test_Load(Getter(cpu.X), Setter(0x0120),
Opcode(LDX, Absolute, 3, 4), 0);
}
TEST_F(CpuTestLoadStore, LDX_AbsoluteY) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteWordAt(BASE_PC + 1, 0x0120);
cpu.Y = 0x08;
Test_Load(Getter(cpu.X), Setter(0x0128),
Opcode(LDX, AbsoluteY, 3, 4), 0);
}
TEST_F(CpuTestLoadStore, LDX_AbsoluteY_CrossingPage) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteWordAt(BASE_PC + 1, 0x0120);
cpu.Y = 0xF0;
Test_Load(Getter(cpu.X), Setter(0x0210),
Opcode(LDX, AbsoluteY, 3, 4), 1);
}
TEST_F(CpuTestLoadStore, LDY_Immediate) {
cpu.WriteByteAt(BASE_PC, 0xFF);
Test_Load(Getter(cpu.Y), Setter(BASE_PC + 1),
Opcode(LDY, Immediate, 2, 2), 0);
}
TEST_F(CpuTestLoadStore, LDY_ZeroPage) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteByteAt(BASE_PC + 1, 0x20);
Test_Load(Getter(cpu.Y), Setter(0x0020),
Opcode(LDY, ZeroPage, 2, 3), 0);
}
TEST_F(CpuTestLoadStore, LDY_ZeroPageX) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteByteAt(BASE_PC + 1, 0x20);
cpu.X = 0x08;
Test_Load(Getter(cpu.Y), Setter(0x0028),
Opcode(LDY, ZeroPageX, 2, 4), 0);
}
TEST_F(CpuTestLoadStore, LDY_ZeroPageX_Wraparound) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteByteAt(BASE_PC + 1, 0xF0);
cpu.X = 0x10;
Test_Load(Getter(cpu.Y), Setter(0x0000),
Opcode(LDY, ZeroPageX, 2, 4), 0);
}
TEST_F(CpuTestLoadStore, LDY_Absolute) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteWordAt(BASE_PC + 1, 0x0120);
Test_Load(Getter(cpu.Y), Setter(0x0120),
Opcode(LDY, Absolute, 3, 4), 0);
}
TEST_F(CpuTestLoadStore, LDY_AbsoluteX) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteWordAt(BASE_PC + 1, 0x0120);
cpu.X = 0x08;
Test_Load(Getter(cpu.Y), Setter(0x0128),
Opcode(LDY, AbsoluteX, 3, 4), 0);
}
TEST_F(CpuTestLoadStore, LDY_AbsoluteX_CrossingPage) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteWordAt(BASE_PC + 1, 0x0120);
cpu.X = 0xF0;
Test_Load(Getter(cpu.Y), Setter(0x0210),
Opcode(LDY, AbsoluteX, 3, 4), 1);
}
TEST_F(CpuTestLoadStore, LDA_Immediate) {
cpu.WriteByteAt(BASE_PC, 0xFF);
Test_Load(Getter(cpu.A), Setter(BASE_PC + 1),
Opcode(LDA, Immediate, 2, 2), 0);
}
TEST_F(CpuTestLoadStore, LDA_ZeroPage) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteByteAt(BASE_PC + 1, 0x20);
Test_Load(Getter(cpu.A), Setter(0x0020),
Opcode(LDA, ZeroPage, 2, 3), 0);
}
TEST_F(CpuTestLoadStore, LDA_ZeroPageX) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteByteAt(BASE_PC + 1, 0x20);
cpu.X = 0x08;
Test_Load(Getter(cpu.A), Setter(0x0028),
Opcode(LDA, ZeroPageX, 2, 4), 0);
}
TEST_F(CpuTestLoadStore, LDA_ZeroPageX_Wraparound) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteByteAt(BASE_PC + 1, 0xF0);
cpu.X = 0x10;
Test_Load(Getter(cpu.A), Setter(0x0000),
Opcode(LDA, ZeroPageX, 2, 4), 0);
}
TEST_F(CpuTestLoadStore, LDA_Absolute) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteWordAt(BASE_PC + 1, 0x0120);
Test_Load(Getter(cpu.A), Setter(0x0120),
Opcode(LDA, Absolute, 3, 4), 0);
}
TEST_F(CpuTestLoadStore, LDA_AbsoluteX) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteWordAt(BASE_PC + 1, 0x0120);
cpu.X = 0x08;
Test_Load(Getter(cpu.A), Setter(0x0128),
Opcode(LDA, AbsoluteX, 3, 4), 0);
}
TEST_F(CpuTestLoadStore, LDA_AbsoluteX_CrossingPage) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteWordAt(BASE_PC + 1, 0x0120);
cpu.X = 0xF0;
Test_Load(Getter(cpu.A), Setter(0x0210),
Opcode(LDA, AbsoluteX, 3, 4), 1);
}
TEST_F(CpuTestLoadStore, LDA_AbsoluteY) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteWordAt(BASE_PC + 1, 0x0120);
cpu.Y = 0x08;
Test_Load(Getter(cpu.A), Setter(0x0128),
Opcode(LDA, AbsoluteY, 3, 4), 0);
}
TEST_F(CpuTestLoadStore, LDA_AbsoluteY_CrossingPage) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteWordAt(BASE_PC + 1, 0x0120);
cpu.Y = 0xF0;
Test_Load(Getter(cpu.A), Setter(0x0210),
Opcode(LDA, AbsoluteY, 3, 4), 1);
}
TEST_F(CpuTestLoadStore, LDA_IndexedIndirect) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteByteAt(BASE_PC + 1, 0x20);
cpu.X = 0x08;
cpu.WriteWordAt(0x28, 0x0120);
Test_Load(Getter(cpu.A), Setter(0x0120),
Opcode(LDA, IndexedIndirect, 2, 6), 0);
}
TEST_F(CpuTestLoadStore, LDA_IndexedIndirect_Wraparound) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteByteAt(BASE_PC + 1, 0xF0);
cpu.X = 0x0F;
cpu.WriteByteAt(0xFF, 0x20);
cpu.WriteByteAt(0x00, 0x01);
Test_Load(Getter(cpu.A), Setter(0x0120),
Opcode(LDA, IndexedIndirect, 2, 6), 0);
}
TEST_F(CpuTestLoadStore, LDA_IndirectIndexed) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteByteAt(BASE_PC + 1, 0x20);
cpu.WriteWordAt(0x20, 0x0120);
cpu.Y = 0x08;
Test_Load(Getter(cpu.A), Setter(0x0128),
Opcode(LDA, IndirectIndexed, 2, 5), 0);
}
TEST_F(CpuTestLoadStore, LDA_IndirectIndexed_CrossingPage) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteByteAt(BASE_PC + 1, 0x20);
cpu.WriteWordAt(0x20, 0x0120);
cpu.Y = 0xF0;
Test_Load(Getter(cpu.A), Setter(0x0210),
Opcode(LDA, IndirectIndexed, 2, 5), 1);
}
TEST_F(CpuTestLoadStore, LDA_IndirectIndexed_CrossingWordsize) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteByteAt(BASE_PC + 1, 0x20);
cpu.WriteWordAt(0x20, 0xFFFF);
cpu.Y = 0x10;
Test_Load(Getter(cpu.A), Setter(0x000F),
Opcode(LDA, IndirectIndexed, 2, 5), 1);
}
TEST_F(CpuTestLoadStore, LDA_IndirectIndexed_BaseFromZeroPage) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteByteAt(BASE_PC + 1, 0xFF);
cpu.WriteByteAt(0xFF, 0x20);
cpu.WriteByteAt(0x00, 0x01);
cpu.Y = 0x10;
Test_Load(Getter(cpu.A), Setter(0x0130),
Opcode(LDA, IndirectIndexed, 2, 5), 0);
}
TEST_F(CpuTestLoadStore, STX_ZeroPage) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteByteAt(BASE_PC + 1, 0x20);
Test_Set(Getter(0x0020), Setter(cpu.X),
Opcode(STX, ZeroPage, 2, 3));
}
TEST_F(CpuTestLoadStore, STX_ZeroPageY) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteByteAt(BASE_PC + 1, 0x20);
cpu.Y = 0x08;
Test_Set(Getter(0x0028), Setter(cpu.X),
Opcode(STX, ZeroPageY, 2, 4));
}
TEST_F(CpuTestLoadStore, STX_ZeroPageY_Wraparound) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteByteAt(BASE_PC + 1, 0xF0);
cpu.Y = 0x10;
Test_Set(Getter(0x0000), Setter(cpu.X),
Opcode(STX, ZeroPageY, 2, 4));
}
TEST_F(CpuTestLoadStore, STX_Absolute) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteWordAt(BASE_PC + 1, 0x0120);
Test_Set(Getter(0x0120), Setter(cpu.X),
Opcode(STX, Absolute, 3, 4));
}
TEST_F(CpuTestLoadStore, STY_ZeroPage) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteByteAt(BASE_PC + 1, 0x20);
Test_Set(Getter(0x0020), Setter(cpu.Y),
Opcode(STY, ZeroPage, 2, 3));
}
TEST_F(CpuTestLoadStore, STY_ZeroPageX) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteByteAt(BASE_PC + 1, 0x20);
cpu.X = 0x08;
Test_Set(Getter(0x0028), Setter(cpu.Y),
Opcode(STY, ZeroPageX, 2, 4));
}
TEST_F(CpuTestLoadStore, STY_ZeroPageX_Wraparound) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteByteAt(BASE_PC + 1, 0xF0);
cpu.X = 0x10;
Test_Set(Getter(0x0000), Setter(cpu.Y),
Opcode(STY, ZeroPageX, 2, 4));
}
TEST_F(CpuTestLoadStore, STY_Absolute) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteWordAt(BASE_PC + 1, 0x0120);
Test_Set(Getter(0x0120), Setter(cpu.Y),
Opcode(STY, Absolute, 3, 4));
}
TEST_F(CpuTestLoadStore, STA_ZeroPage) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteByteAt(BASE_PC + 1, 0x20);
Test_Set(Getter(0x0020), Setter(cpu.A),
Opcode(STA, ZeroPage, 2, 3));
}
TEST_F(CpuTestLoadStore, STA_ZeroPageX) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteByteAt(BASE_PC + 1, 0x20);
cpu.X = 0x08;
Test_Set(Getter(0x0028), Setter(cpu.A),
Opcode(STA, ZeroPageX, 2, 4));
}
TEST_F(CpuTestLoadStore, STA_ZeroPageX_Wraparound) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteByteAt(BASE_PC + 1, 0xF0);
cpu.X = 0x10;
Test_Set(Getter(0x0000), Setter(cpu.A),
Opcode(STA, ZeroPageX, 2, 4));
}
TEST_F(CpuTestLoadStore, STA_Absolute) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteWordAt(BASE_PC + 1, 0x0120);
Test_Set(Getter(0x0120), Setter(cpu.A),
Opcode(STA, Absolute, 3, 4));
}
TEST_F(CpuTestLoadStore, STA_AbsoluteX) {
// Same page
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteWordAt(BASE_PC + 1, 0x0120);
cpu.X = 0x08;
Test_Set(Getter(0x0128), Setter(cpu.A),
Opcode(STA, AbsoluteX, 3, 5));
}
TEST_F(CpuTestLoadStore, STA_AbsoluteY) {
// Same page
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteWordAt(BASE_PC + 1, 0x0120);
cpu.Y = 0x08;
Test_Set(Getter(0x0128), Setter(cpu.A),
Opcode(STA, AbsoluteY, 3, 5));
}
TEST_F(CpuTestLoadStore, STA_IndexedIndirect) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteByteAt(BASE_PC + 1, 0x20);
cpu.X = 0x08;
cpu.WriteWordAt(0x28, 0x0120);
Test_Set(Getter(0x0120), Setter(cpu.A),
Opcode(STA, IndexedIndirect, 2, 6));
}
TEST_F(CpuTestLoadStore, STA_IndexedIndirect_Wraparound) {
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteByteAt(BASE_PC + 1, 0xF0);
cpu.X = 0x0F;
cpu.WriteByteAt(0xFF, 0x20);
cpu.WriteByteAt(0x00, 0x01);
cpu.WriteByteAt(0x120, 0x00);
Test_Set(Getter(0x0120), Setter(cpu.A),
Opcode(STA, IndexedIndirect, 2, 6));
}
TEST_F(CpuTestLoadStore, STA_IndirectIndexed) {
// Same page
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteByteAt(BASE_PC + 1, 0x20);
cpu.WriteWordAt(0x20, 0x120);
cpu.Y = 0x08;
Test_Set(Getter(0x0128), Setter(cpu.A),
Opcode(STA, IndirectIndexed, 2, 6));
}
TEST_F(CpuTestLoadStore, STA_IndirectIndexed_CrossingWordsize) {
// Same page
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteByteAt(BASE_PC + 1, 0x20);
cpu.WriteWordAt(0x20, 0xFFFF);
cpu.Y = 0x10;
Test_Set(Getter(0x000F), Setter(cpu.A),
Opcode(STA, IndirectIndexed, 2, 6));
}
TEST_F(CpuTestLoadStore, STA_IndirectIndexed_BaseFromZeroPage) {
// Same page
cpu.WriteByteAt(BASE_PC, 0xFF);
cpu.WriteByteAt(BASE_PC + 1, 0xFF);
cpu.WriteByteAt(0xFF, 0x20);
cpu.WriteByteAt(0x00, 0x01);
cpu.Y = 0x10;
Test_Set(Getter(0x0130), Setter(cpu.A),
Opcode(STA, IndirectIndexed, 2, 6));
}
|
b01bf9d4d6130686cce46550396725ff1d7f2cc7 | 20339f9a40bc6d0a8f474496d04cabf56891daa1 | /include/GameRoom.hpp | 22a0677a92f67a4989a6e1bea06ce638be810d10 | [] | no_license | narongdejsrn/makhos | 1daecfd0946de7084203ad5197f0a2952d99f4d9 | 6514fed5d86e3b922a1290a907f0c7b8016ba663 | refs/heads/master | 2022-11-18T12:09:45.312411 | 2020-06-25T14:52:30 | 2020-06-25T14:52:30 | 270,681,951 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,356 | hpp | GameRoom.hpp | //
// GameRoom.hpp
// makhos
//
// Created by Narongdej Sarnsuwan on 10/6/20.
// Copyright © 2020 Narongdej Sarnsuwan. All rights reserved.
//
#ifndef GameRoom_hpp
#define GameRoom_hpp
#include <stdio.h>
#include <vector>
#include <memory>
#include "Checker.hpp"
#include "Scene.hpp"
#include "ZTexture.hpp"
#include "PawnObject.hpp"
#include "Primitive.hpp"
#include "../src/later.cpp"
#include "GridObject.hpp"
#include "TextButton.hpp"
#include "SimpleAI.hpp"
namespace makhos {
struct EatLocation {
int eater;
int moveToCol;
int moveToRow;
int kill;
};
class GameRoom: public Scene {
public:
GameRoom(SDL_Window* window, GameLoop *gameLoop);
~GameRoom();
void draw();
private:
// Textures
ZTexture *darkGrid;
ZTexture *checkerPawns;
ZTexture *textTexture;
SDL_Rect checkerClip[8];
std::shared_ptr<Checker> checker;
// GameObject
std::vector<PawnObject *> pawns;
std::vector<GridObject *> gameGrids;
BoardPosition *forceEating;
// Buttons
TextButton *resetButton;
TextButton *gameStateButton;
// Fonts
TTF_Font *boardPositionFont = nullptr;
// Pawns
int redPawnLeft;
int bluePawnLeft;
int gameState[64];
Uint32 lastClicked;
// AI
SimpleAI *simpleAI;
bool gameOver;
bool eatingMove;
bool holdingAPawn;
bool redTurn; // we use this to keep track of player turn
PawnObject *pawnInHand;
void drawBoard();
void drawPawns();
void createBoard();
void resetPlayerPositions();
void createPawns();
void holdAPawn(PawnObject *pawnObj, bool force = false);
void moveToPosition(GridObject *gameObject);
std::vector<BoardPosition> eatingPossibility();
BoardPosition findPosition(PawnObject *pawnObject);
bool isFree(TempBoardPosition boardPosition);
PawnObject *locatePawn(TempBoardPosition boardPosition);
PawnObject *locatePawn(BoardPosition boardPosition);
GridObject *locateGridObj(TempBoardPosition boardPosition);
GridObject *locateGridObj(BoardPosition boardPosition);
void checkKings();
void setActionableGrid();
Blocker getBlocker(PawnObject *pawnObj);
void checkGameOver();
void updateGameState();
void printGameState();
void botMove();
};
}
#endif /* GameRoom_hpp */
|
50f18af1f6fcb322fca180b6509e4b5167eccbb3 | 9df4cce1240c298e899ca836e36cf7419d9256bb | /parking Management.cpp | ed3cc2f4b2660ee753d2923a25b8aa8f466f116b | [] | no_license | anshulshakya/PracticeRepo | 4753525ca7e6dffa2321d3b659e9166167c04f50 | 75201c7c11109325645a5f89db06fa552b07ffa3 | refs/heads/master | 2023-03-06T16:55:36.214710 | 2021-02-02T20:09:34 | 2021-02-02T20:09:34 | 259,899,074 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,303 | cpp | parking Management.cpp | #include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int nob=0,nos=0,noc=0,amount=0,count=0;
void bus();
void scooter();
void car();
void status();
void delet();
int menu();
int main()
{
while(1)
{
switch(menu())
{
case 1:
bus();
break;
case 2:
scooter();
break;
case 3:
car();
break;
case 4:
status();
break;
case 5:
delet();
break;
case 6:
//goto ans;
//break;
exit(0);
default :
printf("invalid choice");
}
getch();
system("cls");
}
//ans:
// printf("end");
}
int menu()
{
int ch;
printf("\n1:Bus Entery \n2:Scooter Entery \n3:Car Entery \n4:Status \n5:Delete \n6:Exit");
printf("\n\nEnter your choice");
scanf("%d",&ch);
return(ch);
}
void bus()
{
nob++;
count++;
amount=amount+20;
printf("Entry successful");
}
void scooter()
{
nos++;
count++;
amount=amount+5;
printf("Entry successful");
}
void car()
{
noc++;
count++;
amount=amount+10;
printf("Entry successful");
}
void status()
{
printf("\nNo of bus=%d",nob);
printf("\nNo of scooter=%d",nos);
printf("\nNo of car=%d",noc);
printf("\nTotal no of vehicles=%d",count);
printf("\n Total amount=%d",amount);
}
void delet()
{
count=0;
nos=0;
nob=0;
noc=0;
amount=0;
}
|
71e55632a94b5a265d4994bad9195265eaeadbaa | ebe36eba494b9ab9bb658686e69c9253c43cb524 | /Practice/a2oj/DIV_B/Slightly_Decreasing_Permutation.cpp | e6a6fde7d75551e8e492478d1db33c36da3189e3 | [] | no_license | Dutta-SD/CC_Codes | 4840d938de2adc5a2051a32b48c49390e6ef877f | ec3652ec92d0d371fd3ce200f393f3f69ed27a68 | refs/heads/main | 2023-07-03T11:46:30.868559 | 2021-08-19T12:03:56 | 2021-08-19T12:03:56 | 316,813,717 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 439 | cpp | Slightly_Decreasing_Permutation.cpp | #include <bits/stdc++.h>
# define print(arr) for(auto i : arr){cout << i <<" ";}
using namespace std;
int main()
{
int n, k;
cin >> n >> k;
int perm[n];
for (int i = 0; i < n; ++i)
{
perm[i] = n-i;
}
// print(perm)
for (int i = 0; i < n-k-1; ++i)
{
for (int j = 1; j < n - i; ++j)
{
swap(perm[j], perm[j - 1]);
}
}
print(perm);
return 0;
} |
a5192181aa7e9dd25553cd8f4718106bbf86daec | bf41e4c5c97bcf416b52cc3d6c77daa1c9d0f0b2 | /util.h | d7ca0e7b98c83fd8bce1caf936ac31e39fc4ec7e | [] | no_license | xptree/grouppp | 2c70c2953a51b88de568a0c3acd3450c3f8747e4 | 7225f67320f384bed753bcd43010b00762be01a9 | refs/heads/master | 2021-01-16T22:37:04.524814 | 2015-08-11T16:25:33 | 2015-08-11T16:25:33 | 39,917,452 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 371 | h | util.h | #ifndef UTIL_H
#define UTIL_H
#include <vector>
#include <string>
using namespace std;
class Util
{
public:
static vector<string> split(const char* s, char delim);
static vector<long long> string_to_ll(vector<string>& elems);
static bool cmpTime(pair<int, int> first, pair<int, int> second);
static long long getFileSize(const char* fileName);
};
#endif //UTIL_H
|
65bc0350583aeeafc2310b5264a04093d62d832b | 28bdc0bf546582d2488a0fed6f88de488dc792e6 | /strategy/IStrategy.h | 1e1b9127bcf2f614f224c3ba52807bcba92d9cbd | [] | no_license | yiluohan1234/designPattern | a6a13d41fff65813acde62fdf271f5d4ef6cccb7 | ffc9e62ecd40a60d16202004787af9e05fb328e7 | refs/heads/master | 2020-04-06T06:57:50.408571 | 2018-11-28T08:55:43 | 2018-11-28T08:55:43 | 60,152,031 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 536 | h | IStrategy.h | /*************************************************************************
> File Name: IStrategy.h
> Author: cyf
> Mail: XXX@qq.com
> Created Time: 2016年05月30日 星期一 09时45分13秒
************************************************************************/
#ifndef _ISTRATEGY_H
#define _ISTRATEGY_H
/*
首先定一个策略接口,这是诸葛亮老人家给赵云的三个锦囊妙计的接口
*/
class IStrategy
{
public:
IStrategy(void){};
virtual ~IStrategy(void){};
virtual void Operate(void)=0;
};
#endif
|
726931df7fa2aa4e0a6ee5584a2635e7df18fb41 | 8f19b63873145658bcc8066723cbb78323ce75c8 | /src/mruntime/ApplicationTaskBlock.h | fd59b5469ca3e974b26135222bb1e59268cd86e8 | [
"Apache-2.0"
] | permissive | 0of/WebOS-Magna | c9dfcd310b3e16c4b4e19f34244d4413a3bf3c89 | a0fe2c9708fd4dd07928c11fcb03fb29fdd2d511 | refs/heads/master | 2021-01-13T13:00:29.907133 | 2016-02-01T07:48:41 | 2016-02-01T07:48:41 | 50,822,587 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,204 | h | ApplicationTaskBlock.h | #ifndef APPLICATIONTASKBLOCK_H
#define APPLICATIONTASKBLOCK_H
#include "basedef/Uncopyable.h"
#include "basedef/Thread.h"
using namespace Magna::Core;
#include "application/Application.h"
#include <QLibrary>
namespace Magna{
namespace Application{
typedef void(MAGNA_CDECL *app_entry)();
typedef QLibrary AppInstance;
class ApplicationTaskBlock : public Thread
, Uncopyable{
public:
ApplicationTaskBlock() ;
explicit ApplicationTaskBlock(app_entry entry,AppInstance* instance);
~ApplicationTaskBlock();
public:
void assignBlockId( uint32 id );
void assignRunningApplication( MagnaApplication * app );
inline MagnaApplication *getApplication(){ return m_appObj; }
bool isValid(){ return m_id != 0; }
bool operator == ( const ApplicationTaskBlock& block ) ;
bool operator != ( const ApplicationTaskBlock& block ) ;
private:
uint32 m_id;
AppInstance *m_instance;
MagnaApplication *m_appObj;
};
}//namespace Application
}//namespace Magna
#endif /* APPLICATIONTASKBLOCK_H */ |
e7f38aac411b84653d29ee4052b9b523eb5b5719 | 491b67c1b3cc8f1963189f28a2582f6f76804b79 | /src/include/parser.h | 9355de27056bb9a452b9a80e7c245438bad6801d | [] | no_license | sschellhoff/s3l | 134719e9197d1198a3973b481c92f56413824dca | 0124c57e023ed3f2cf412233d844cfdb5b7b3dd9 | refs/heads/master | 2021-01-17T22:56:19.816582 | 2016-04-16T17:35:06 | 2016-04-16T17:35:06 | 54,187,124 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,434 | h | parser.h | #pragma once
#include <iostream>
#include <memory>
#include <string>
#include <map>
#include <vector>
#include <stack>
#include "environment.h"
#include "operators.h"
#include "token.h"
#include "lexer.h"
#include "function_prototype.h"
#include "ast.h"
#include "function_definition_ast.h"
using ENV = Environment<Variable>;
using ENVSTACK = std::stack<ENV>;
using ASTPTR = std::unique_ptr<AST>;
using FUNCVECPTR = std::unique_ptr<std::vector<std::unique_ptr<FunctionDefinitionAST>>>;
class Parser {
private:
std::map<Operator, int> operatorPrecedences;
Token currentToken;
ENVSTACK environments;
Type currentFunctionsResultType;
Lexer lexer;
std::ostream &errorStream;
std::vector<FunctionPrototype> functionDefinitions;
std::vector<FunctionPrototype> functionDeclarations;
std::unique_ptr<std::vector<std::unique_ptr<FunctionDefinitionAST>>> functionASTs;
Type stringToType(const std::string &typeString)const;
bool isValidOperator(const Operator op, const Type t1, const Type t2)const;
Type determineOperatorResult(const Operator op, const Type t1, const Type t2)const;
Type getFunctionResultType(const std::string &name, std::vector<Type> &types);
bool isValidOperator(const UnaryOperator op, const Type t1)const;
void makeError(const std::string &msg);
void consumeToken();
bool isIdentifier(const std::string &name);
bool tryConsumeIdentifier(const std::string &name);
bool isFunctionDefined(const std::string &name, Type resultType, std::vector<Type> &types);
bool isFunctionDefined(const std::string &name, std::vector<Type> &types);
bool isFunctionDeclared(const std::string &name, Type resultType, std::vector<Type> &types);
bool isFunctionDeclared(const std::string &name, std::vector<Type> &types);
bool removeDeclarationIfNeeded(const std::string &name, Type resultType, std::vector<Type> &types);
std::vector<Type> argumentsToTypes(std::vector<Variable> &arguments)const;
ASTPTR parsePrimeExpression();
ASTPTR parseNumberConst();
ASTPTR parseBoolConst();
ASTPTR parseIdentifierExpression();
ASTPTR parseExpression();
ASTPTR parseBinaryExpressionRHS(int operatorPrecedence, ASTPTR lhs);
ASTPTR parseReturn();
ASTPTR parseBlock();
ASTPTR parseIf();
ASTPTR parseLoop();
ASTPTR parseIdentifierStatement();
bool parseFunctionDefinition();
public:
Parser(std::ostream &errorStream);
FUNCVECPTR parse(const std::string &program);
FUNCVECPTR parseFile(const std::string &filename);
}; |
cdd9713aa79b872519c175058656cb0c98be89c6 | 62d0e23e9ec6cc6b3400131f51c33d775e3e8357 | /Mantle/Source/Layers/ImGuiLayer.cpp | 11b5b467c31896887fa9cec6dccaac048bb6e316 | [
"Apache-2.0"
] | permissive | AiManti1/Graphics | 659c578b9d29098aa15167a40ee23e56d410af93 | 050816bf16202b09440412314338373a4d0d6c04 | refs/heads/master | 2023-02-15T19:51:25.341735 | 2021-01-14T10:41:05 | 2021-01-14T10:41:05 | 329,582,298 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,671 | cpp | ImGuiLayer.cpp | #include "mtlpch.h"
#include "MEngine.h"
#include "imgui.h"
#include "ImGuiLayer.h"
#include "OpenGL/ImGuiRenderer.h"
// TEMPORARY
#include <GLFW/glfw3.h>
#include <glad/glad.h>
namespace mtl {
ImGuiLayer::ImGuiLayer()
: Layer("ImGuiLayer")
{
}
ImGuiLayer::~ImGuiLayer()
{
}
void ImGuiLayer::OnAttach()
{
ImGui::CreateContext();
ImGui::StyleColorsDark();
ImGuiIO& io = ImGui::GetIO();
io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors;
io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos;
// TODO: should be key codes from 'KeyCodes.h'.
io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB;
io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;
io.KeyMap[ImGuiKey_PageUp] = GLFW_KEY_PAGE_UP;
io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN;
io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
io.KeyMap[ImGuiKey_Insert] = GLFW_KEY_INSERT;
io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
io.KeyMap[ImGuiKey_Space] = GLFW_KEY_SPACE;
io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;
io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;
io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;
io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;
io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
ImGui_ImplOpenGL3_Init("#version 430");
}
void ImGuiLayer::OnDetach()
{
}
void ImGuiLayer::OnUpdate()
{
ImGuiIO& io = ImGui::GetIO();
MEngine& engine = MEngine::Get(); // from being the singleton class
io.DisplaySize = ImVec2(engine.GetWindow().GetWidth(), engine.GetWindow().GetHeight());
float time = (float)glfwGetTime();
io.DeltaTime = m_Time > 0.0f ? (time - m_Time) : (1.0f / 60.0f); // seconds since last frame
m_Time = time;
ImGui_ImplOpenGL3_NewFrame();
ImGui::NewFrame();
static bool show = true;
ImGui::ShowDemoWindow(&show);
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
}
// When an event comes in to the layer, we check its type and then
// forward this event to one of the functions below (OnMouseButtonPressedEvent() etc.)
// (std::bind(&ImGuiLayer::OnMouseButtonPressedEvent, this, std::placeholders::1)) -> &fn
#define MTL_BIND_EVENT_FN(fn) std::bind(&fn, this, std::placeholders::_1)
void ImGuiLayer::OnEvent(Event& event)
{
EventDispatcher dispatcher(event);
// If 'event' of dispatcher matches MouseButtonPressedEvent type (dispatcher checks for this),
// then it will call (be propagated to) the specified function:
// Binding because it is of ImGui layer.
dispatcher.Dispatch<MouseButtonPressedEvent>(MTL_BIND_EVENT_FN(ImGuiLayer::OnMouseButtonPressedEvent));
dispatcher.Dispatch<MouseButtonReleasedEvent>(MTL_BIND_EVENT_FN(ImGuiLayer::OnMouseButtonReleasedEvent));
dispatcher.Dispatch<MouseMovedEvent>(MTL_BIND_EVENT_FN(ImGuiLayer::OnMouseMovedEvent));
dispatcher.Dispatch<MouseScrolledEvent>(MTL_BIND_EVENT_FN(ImGuiLayer::OnMouseScrolledEvent));
dispatcher.Dispatch<KeyPressedEvent>(MTL_BIND_EVENT_FN(ImGuiLayer::OnKeyPressedEvent));
dispatcher.Dispatch<KeyTypedEvent>(MTL_BIND_EVENT_FN(ImGuiLayer::OnKeyTypedEvent));
dispatcher.Dispatch<KeyReleasedEvent>(MTL_BIND_EVENT_FN(ImGuiLayer::OnKeyReleasedEvent));
dispatcher.Dispatch<WindowResizeEvent>(MTL_BIND_EVENT_FN(ImGuiLayer::OnWindowResizeEvent));
}
bool ImGuiLayer::OnMouseButtonPressedEvent(MouseButtonPressedEvent& e)
{
ImGuiIO& io = ImGui::GetIO();
io.MouseDown[e.GetMouseButton()] = true;
// false means we haven't handled this. And want other layer to handle this.
return false;
}
bool ImGuiLayer::OnMouseButtonReleasedEvent(MouseButtonReleasedEvent& e)
{
ImGuiIO& io = ImGui::GetIO();
io.MouseDown[e.GetMouseButton()] = false;
return false;
}
bool ImGuiLayer::OnMouseMovedEvent(MouseMovedEvent& e)
{
ImGuiIO& io = ImGui::GetIO();
io.MousePos = ImVec2(e.GetX(), e.GetY());
return false;
}
bool ImGuiLayer::OnMouseScrolledEvent(MouseScrolledEvent& e)
{
ImGuiIO& io = ImGui::GetIO();
io.MouseWheelH += e.GetXOffset(); // horisontal
io.MouseWheel += e.GetYOffset(); // vertical
return false;
}
bool ImGuiLayer::OnKeyPressedEvent(KeyPressedEvent& e)
{
ImGuiIO& io = ImGui::GetIO();
io.KeysDown[e.GetKeyCode()] = true;
// For modifying keys.
// TODO: should be replaced with the Engine's key codes.
io.KeyCtrl = io.KeysDown[GLFW_KEY_LEFT_CONTROL] || io.KeysDown[GLFW_KEY_RIGHT_CONTROL];
io.KeyShift = io.KeysDown[GLFW_KEY_LEFT_SHIFT] || io.KeysDown[GLFW_KEY_RIGHT_SHIFT];
io.KeyAlt = io.KeysDown[GLFW_KEY_LEFT_ALT] || io.KeysDown[GLFW_KEY_RIGHT_ALT];
io.KeySuper = io.KeysDown[GLFW_KEY_LEFT_SUPER] || io.KeysDown[GLFW_KEY_RIGHT_SUPER];
return false;
}
bool ImGuiLayer::OnKeyReleasedEvent(KeyReleasedEvent& e)
{
ImGuiIO& io = ImGui::GetIO();
io.KeysDown[e.GetKeyCode()] = false;
return false;
}
// Char callback (used for typing in a text box).
bool ImGuiLayer::OnKeyTypedEvent(KeyTypedEvent& e)
{
ImGuiIO& io = ImGui::GetIO();
int keycode = e.GetKeyCode();
if (keycode > 0 && keycode < 0x10000)
io.AddInputCharacter((unsigned short)keycode);
return false;
}
bool ImGuiLayer::OnWindowResizeEvent(WindowResizeEvent& e)
{
ImGuiIO& io = ImGui::GetIO();
io.DisplaySize = ImVec2(e.GetWidth(), e.GetHeight());
io.DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
// TODO: Temporary! Remove.
glViewport(0, 0, e.GetWidth(), e.GetHeight());
return false;
}
} |
d6b159a9798504d779b8f8c23523e0b3a8f72629 | 493ac26ce835200f4844e78d8319156eae5b21f4 | /flow_simulation/ideal_flow/processor0/0.31/phi | 8fca2e57798ee7509f2918100d5a718d429e8110 | [] | no_license | mohan-padmanabha/worm_project | 46f65090b06a2659a49b77cbde3844410c978954 | 7a39f9384034e381d5f71191122457a740de3ff0 | refs/heads/master | 2022-12-14T14:41:21.237400 | 2020-08-21T13:33:10 | 2020-08-21T13:33:10 | 289,277,792 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 36,118 | phi | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: v1912 |
| \\ / A nd | Website: www.openfoam.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class surfaceScalarField;
location "0.31";
object phi;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 3 -1 0 0 0 0];
oriented oriented;
internalField nonuniform List<scalar>
2708
(
-6.43108e-05
1.93165e-05
3.0837e-05
1.41574e-05
-8.25401e-05
0.000101859
7.95514e-07
-2.01144e-05
0.00125987
0.00024694
-0.000863898
-0.00064291
-0.000321987
0.000171497
5.27226e-05
9.77669e-05
-2.88458e-05
2.41555e-05
0.000134901
-0.000130211
0.000511777
0.000433996
-0.000376
-0.000569773
-0.00014264
3.90459e-05
0.000595293
-0.000823576
0.00100344
-0.00077516
0.000340754
0.000222062
-0.000279757
-0.000283059
-0.000429785
-6.58824e-05
2.94634e-05
0.000466204
-0.000223565
3.03438e-05
-2.65027e-05
0.000219724
-5.32923e-05
-1.50612e-05
6.83535e-05
-0.000125867
0.000186197
-2.81867e-05
-3.21438e-05
0.00085993
-0.000871821
3.57665e-05
-2.38759e-05
8.17223e-05
-5.40262e-05
1.68234e-05
-4.45196e-05
5.69198e-05
-9.26368e-05
3.57171e-05
-0.000120343
0.000124795
7.72701e-05
9.36955e-05
-0.000219469
0.000132461
-6.68745e-06
0.00014135
2.3553e-06
-0.000143705
-0.000216631
-2.17328e-06
-4.76056e-06
-8.63836e-06
3.67616e-05
-6.59971e-06
-2.15235e-05
0.000536301
8.14923e-05
6.51619e-06
7.98987e-05
0.000304298
-0.000390713
0.000833749
5.22464e-05
-2.60645e-05
0.000394876
7.30183e-05
-0.000416239
-5.16554e-05
-0.000195195
1.40362e-05
-3.54727e-05
-0.000413124
0.000338313
-0.000181546
0.000256357
2.96928e-05
-1.65857e-05
-0.000884928
-0.0010366
8.94173e-05
0.000957754
-1.0572e-05
0.000193329
-0.000373165
2.51314e-05
0.000154705
-0.000450439
0.0010114
-0.000581771
2.08062e-05
0.00093055
0.000451043
-0.000615188
-0.000766405
0.000212246
0.000195818
-0.000408063
0.000219791
-0.00018067
-3.91206e-05
-0.000309145
0.000312388
-3.24337e-06
-0.000830447
0.000872262
0.00058039
-0.000622204
-8.9875e-05
2.50465e-05
0.000183545
-0.000118716
-0.00117716
0.00113424
-5.26026e-05
9.55192e-05
0.000172391
-0.000308006
-0.000554377
-0.00139002
-3.54219e-05
0.000248287
-0.000390871
-0.000277058
4.86725e-05
0.000619257
-4.46337e-05
1.91312e-06
4.27206e-05
-3.16976e-05
0.00013359
3.45468e-05
-0.000136439
5.74349e-05
-6.94876e-05
0.000132553
-0.0001205
0.000129678
-3.12139e-05
-0.000218508
0.000120044
-4.86668e-07
-0.000146461
9.14025e-06
0.000137808
5.24664e-05
0.000605249
-0.000331907
-0.000325808
-2.24387e-05
3.32917e-05
-0.00096128
0.000950427
-0.000654847
0.00116627
-0.000868248
0.000356824
3.04455e-05
-0.00107263
0.00109927
-5.70851e-05
-0.000232272
-2.04543e-05
0.000227512
2.52149e-05
-1.60649e-05
-3.61303e-05
-0.00037759
-0.000249919
0.000165446
0.000425228
0.000425449
-0.000290243
-6.52229e-06
-0.000128684
-0.000100481
4.27004e-05
2.66812e-05
3.10997e-05
-0.000972277
0.000103427
0.000957195
-8.83449e-05
0.000149668
-1.68083e-05
-0.000136258
3.39916e-06
-0.000389311
0.000264208
0.000577454
-0.000452351
-0.000581296
0.000563048
9.44061e-06
3.61522e-05
-5.42311e-05
0.000258322
-0.000213915
8.05935e-06
-0.000113542
-0.000183181
0.000157394
0.000139328
0.000396978
-0.000678211
-0.000549215
-0.000425507
0.000471195
0.0010095
-0.00105519
0.000847443
-0.00017018
-4.86541e-05
-0.000628609
-3.15357e-06
1.40825e-05
0.000196737
-0.000207666
0.000220012
-3.54125e-05
-0.00032818
0.000154591
-0.000109004
0.000282593
-0.000622738
0.00102647
-0.000732971
0.000329237
0.000188093
-0.00025171
-0.00019347
7.42348e-05
0.000192681
-7.34455e-05
0.000106738
0.000152406
-0.000110128
-0.000149016
6.80301e-05
0.000144215
-5.41804e-05
-0.000129091
0.000166695
1.65765e-05
4.13206e-05
0.000759943
-0.000554324
0.000963904
6.43973e-05
-0.00101179
-1.65152e-05
0.00013347
-0.000262895
-7.43882e-05
0.000203814
-0.000951195
0.000923311
-0.000397623
-5.3017e-05
-0.000219389
5.52744e-05
0.000217132
0.000170721
-0.000188476
0.000163386
-0.000145631
1.42019e-05
-0.000109908
0.000155474
-5.97679e-05
-0.000265876
-5.42716e-05
0.000193919
0.000126229
-7.96986e-05
9.31956e-05
-4.86904e-05
3.51935e-05
-5.04949e-05
-2.51976e-05
8.33383e-05
-7.64576e-06
-0.000179201
1.81563e-05
0.000143209
1.78355e-05
0.000797688
7.10475e-05
-3.49867e-05
6.18839e-05
-0.000100671
0.000187266
-0.000148479
-0.000119036
-9.76825e-05
8.52535e-05
0.000131465
-0.000321036
0.000198239
-5.64037e-05
-2.03928e-05
1.00965e-05
-4.01986e-05
0.00112139
-1.82494e-05
3.10979e-05
3.2415e-05
-4.99526e-05
0.000138555
-0.000121017
6.59159e-05
-6.73688e-05
1.08936e-05
0.000197883
1.85233e-05
-0.000109668
-6.12646e-05
-0.000999927
0.00102764
3.35522e-05
8.13266e-05
-1.38126e-05
-6.90708e-05
1.55676e-06
-0.000814914
-0.000290372
-7.1731e-05
-0.000423906
0.000167457
2.8468e-05
-0.00108014
0.00108024
-2.85695e-05
3.48386e-05
-2.44324e-05
-0.00012601
0.000115604
0.000167479
-2.73274e-05
1.60625e-05
-0.000156214
0.00021173
-1.15995e-05
6.38706e-05
-0.000264001
-0.000354787
0.000307819
1.95361e-05
2.74319e-05
0.00103658
-0.00145949
0.000184376
0.000238541
0.000519428
9.75215e-06
1.18376e-05
-0.000541017
9.14019e-05
9.08194e-05
-0.00100585
-4.58814e-05
-0.000107002
0.000153535
-6.52258e-07
1.44948e-05
0.000173155
-0.000230298
4.26479e-05
5.91074e-06
0.000167891
-0.000176955
0.000841038
-0.000577422
4.53308e-05
-0.000308947
0.000150983
-9.32459e-05
-0.000171279
9.57281e-05
-6.45857e-05
0.000180587
-2.54777e-06
-8.06507e-06
0.000178092
0.00011454
8.03527e-05
-0.000101197
3.00019e-05
5.02355e-05
-5.05026e-05
-2.97348e-05
0.000747892
9.26735e-05
-4.28774e-05
0.000160494
0.000165002
-0.00112984
0.00113167
9.33545e-05
-9.51889e-05
-0.000478436
-0.000160794
0.00022154
-8.79374e-05
0.000794356
0.000171708
-0.000839646
-0.000126419
-0.000990211
-0.000636943
0.00105312
0.00057403
8.16566e-05
-0.000138555
-1.79308e-05
7.48294e-05
0.000111671
-4.29105e-05
0.000679131
0.000263392
2.83993e-05
-0.000139386
5.54998e-05
-3.83884e-05
5.21054e-05
-6.92168e-05
0.00082136
-0.00103912
0.000355374
-0.000137617
0.000155808
-0.000143076
-2.49054e-05
1.21735e-05
-0.000389953
2.18207e-05
-0.000105386
-0.000743584
0.00084897
4.25662e-05
0.000137111
-0.000144839
-3.9623e-05
1.64646e-05
2.76555e-06
-5.69624e-05
2.40156e-05
-0.000288089
-0.000191879
3.17988e-05
-3.33903e-05
2.02817e-05
2.83269e-05
-0.000237535
0.000188927
0.000135117
-0.000139317
2.01658e-05
-1.59657e-05
-0.000366962
-9.09359e-05
6.79454e-05
-0.000136
9.2736e-05
0.000133805
-9.05416e-05
-4.18143e-06
-8.05806e-05
4.5139e-05
0.000896831
-2.32926e-05
-0.000764383
-0.000109156
-0.000102456
0.00111799
0.00015074
-0.00111908
9.136e-05
0.000858572
-0.00102592
-0.000262054
0.000429399
-0.000229295
-0.000984876
0.00118571
2.84622e-05
0.000167869
-1.54035e-05
8.12341e-06
-9.3102e-06
-0.000190692
-0.000915441
0.000882984
-0.000269245
0.000301702
0.00126714
7.6445e-05
-0.000315038
-0.00102855
-4.84138e-05
0.000906953
-1.1096e-05
0.000143616
-0.000196375
0.000231515
-0.000178755
0.000120556
5.0165e-05
-4.5862e-05
-0.000137319
0.000104072
0.000357203
-0.000928103
-0.000376578
0.000353485
0.000161107
4.7271e-05
-0.000165812
0.000905021
0.000108682
-0.000172665
-0.00017816
0.000896683
-0.000882119
0.000163597
-0.000215856
-1.14217e-05
7.8089e-06
0.000214695
-0.000208745
0.000106589
-7.7684e-06
-0.000123253
6.65555e-05
0.000116083
-8.69102e-05
1.49091e-05
-0.000100957
-4.88776e-05
-5.91845e-06
6.92909e-05
7.51316e-05
-5.50971e-05
2.00255e-05
-0.000163435
0.000124492
6.96853e-05
-7.01867e-05
0.000137612
-0.000955742
0.000173533
0.00089388
0.000137139
4.20414e-05
-0.000122261
0.000369544
-0.000594765
-0.000569154
0.000794376
1.38283e-05
0.00023805
-0.000874616
-3.39947e-05
0.000916181
1.4645e-05
-0.000121091
5.34653e-06
0.000115744
7.32114e-05
-0.000130174
0.00107166
-0.00124754
-0.000160525
0.000336412
0.000136177
-0.000347152
-0.000162191
-0.000821664
-0.000338646
0.000851667
0.000308643
-7.98717e-05
0.00104243
-0.00094747
-1.50885e-05
-1.75247e-05
3.34213e-05
-1.3549e-05
-2.34755e-06
0.000113625
-0.000978391
0.000947076
-8.23094e-05
-0.000144472
0.000143344
0.000152111
-0.000332593
0.00024686
0.000944305
-0.000925246
0.000916079
-0.000168993
0.000621919
-0.000604048
-2.35591e-05
0.000578891
-0.000531316
2.54163e-05
-0.000158727
-0.000331627
-0.00090744
0.000310964
0.000158268
-6.93582e-05
2.62241e-05
-0.000115134
-0.000258472
0.000261227
-4.796e-05
4.52046e-05
-8.47877e-05
0.00101421
-0.000890109
-0.000158097
0.000307967
0.000117465
-0.000154645
-0.000270787
-0.00014874
0.000162539
0.00111787
7.2634e-06
2.40524e-05
0.00100526
0.000116209
0.00094342
-0.00100768
-5.19463e-05
9.17528e-05
6.56414e-05
8.24426e-05
-0.000114241
-0.000218735
0.000287647
-6.89118e-05
-0.000191652
-0.000913897
0.000190108
-0.000356772
-8.44985e-05
5.03992e-05
-0.000197039
-0.000248244
-1.27474e-05
8.18037e-06
4.33392e-05
0.0010198
-8.85315e-05
-0.000974606
0.000119091
-0.000200996
0.000176259
-9.43543e-05
-7.948e-05
0.00104575
-0.000648956
-0.000264446
0.000670994
-1.40863e-05
-0.000886203
0.00012749
0.000865047
-0.00019818
0.000974603
0.000150269
-0.000160263
-0.000964609
-7.38343e-05
0.000109325
-5.22994e-05
0.000564171
0.000313595
-0.000613558
0.000195831
0.000896179
-0.000186988
0.000103803
0.000134466
-8.00004e-05
-5.82674e-05
9.9977e-05
2.1459e-05
-6.31686e-05
0.000369171
-9.23545e-05
0.000582566
-0.000859382
0.000353562
-0.000114446
0.000513557
0.00122478
-0.000487257
-0.00037664
0.00080984
-0.000883057
-1.9137e-05
-0.00102405
-0.00082195
0.000598459
0.000845175
-0.000909338
0.000137546
-0.00101073
4.28991e-05
0.00100359
0.000918701
-8.08144e-05
1.78391e-05
7.30718e-05
-0.000202632
0.00019637
0.000204501
0.00100971
0.000201138
-0.000525818
0.000952149
-0.00124991
-0.00041247
-0.000919493
0.000806146
-0.000614273
0.000872796
-8.37604e-05
-0.000988422
8.73067e-05
9.08043e-06
-0.000126862
5.34706e-05
-0.000935127
0.000662343
-5.8844e-05
0.00021911
-0.00024637
6.50002e-05
-3.77405e-05
-0.00110239
-3.94062e-05
0.00106231
-0.000178449
0.000161235
-0.00017211
-0.000164136
0.000227294
0.000108953
-0.000410843
0.000549349
1.09825e-05
-0.000222089
0.000315179
-6.08583e-05
-0.00018177
0.000253611
0.000755462
-0.000155991
1.1096e-05
-0.00100787
0.000144801
-0.000969927
-7.78522e-05
0.0011694
-0.000121625
0.000273285
-0.000223333
-0.000517089
0.000549153
0.000790522
0.000468247
-0.00114256
0.000170045
-0.000243007
-0.000956913
0.000980717
-2.3804e-05
0.000127582
-0.000101565
-2.60177e-05
0.000181105
-0.000131147
0.000169151
-0.00104105
-2.37584e-05
0.00106481
-0.000998303
0.00100951
-1.12102e-05
-0.000926467
-0.000120169
-0.000206206
0.000198385
-0.000128179
0.000241173
-0.000869532
-0.00102335
4.23191e-05
-0.000978562
0.00107192
0.000902199
-0.00023495
-0.000921748
-0.000101773
0.000932315
9.12056e-05
-6.76602e-05
0.000102851
0.000122537
-0.000157728
0.000993723
1.71584e-05
0.000437613
-0.000976574
4.78122e-05
-4.11651e-05
8.15722e-05
-0.00101525
-3.49877e-05
-0.00089148
0.00101765
-0.000669547
7.75239e-06
-0.000120128
-1.3635e-05
-0.000159342
-7.09805e-05
0.00017703
-5.39089e-06
1.39502e-05
0.000225056
-0.000233615
-2.84354e-05
0.000279439
-0.000285321
-0.000472872
-8.6761e-05
0.000123589
-0.000283198
3.43158e-05
-5.43682e-05
-3.8215e-05
6.5576e-06
-0.000143644
-0.000958537
-0.000403389
-0.000845633
0.00053253
0.000716492
-0.00101467
-0.00104636
-9.4395e-05
5.73623e-05
0.0010834
0.000550905
3.15392e-05
0.00114973
-1.34266e-05
-0.00116784
-0.000678786
-0.000546266
0.000227027
0.000134918
-0.000145833
-0.000216112
0.000975559
-0.00103386
-0.000370696
0.00019064
0.00121392
6.33088e-05
-8.0063e-05
-6.80335e-05
0.000175258
-0.00106214
0.00100051
0.000102964
-9.45474e-05
0.000172689
-0.000223846
0.000193394
-0.00134278
-1.88343e-05
0.000275151
-0.000352329
0.000197734
0.000302597
0.00101198
-6.28542e-05
-0.00125172
-0.00016987
0.000163398
-0.000202052
0.000141618
0.000377152
-0.000259155
-1.75862e-05
6.86755e-05
-8.12027e-05
-6.00214e-05
0.00086288
-3.68275e-05
-1.83546e-05
5.7481e-05
-2.2988e-06
-8.97989e-05
4.54189e-05
-4.21801e-05
5.89878e-05
9.85535e-05
-1.369e-05
7.8534e-05
0.000136384
-9.33206e-05
-7.1499e-05
-0.000294934
0.000292349
0.000111908
-0.000109322
0.000300022
-0.000978343
-0.000173083
-3.18718e-05
-0.000242806
-5.37929e-05
0.000200712
-0.000217848
-0.000101293
5.83211e-05
-0.000135752
0.000170167
-0.000269789
0.000241412
-5.83839e-05
-3.47179e-05
-5.69583e-05
7.05786e-05
2.10976e-05
-0.000186011
5.6838e-05
0.000403838
0.00092015
-0.000400677
-0.00014269
0.000243685
-0.00030978
0.000208785
0.00107567
9.10289e-06
-8.05197e-05
1.80493e-05
5.33674e-05
0.000184207
-0.000302062
0.000201639
-8.37847e-05
0.000214827
-0.000242227
0.00015099
0.00022572
-5.93517e-05
-0.000235726
-0.000100916
-0.000139752
7.65318e-05
9.85594e-05
-6.08615e-05
-0.000201133
0.000122976
-0.000128246
4.1894e-06
7.39157e-05
9.45351e-05
3.05422e-05
-8.0077e-05
-4.50003e-05
0.00117405
-0.000888288
-0.000187273
-6.35899e-05
0.000138102
0.000117087
-0.000243199
-0.000526438
0.00065255
-6.24882e-05
4.40951e-05
1.8393e-05
0.000106029
-0.000915483
-7.36039e-05
0.000111843
-5.58924e-05
-5.59502e-05
1.78649e-06
1.94817e-05
-2.12681e-05
2.09652e-06
-2.51728e-05
2.30763e-05
0.000215207
-0.000175075
-4.0132e-05
-0.000114357
7.49301e-06
0.000106864
0.000122193
-1.91154e-05
-0.000103078
-3.62687e-06
3.07428e-05
-2.7116e-05
-0.000173755
0.000135885
3.78697e-05
0.000113345
0.000101862
-0.000124761
1.04044e-05
-9.45493e-05
3.20611e-05
7.1117e-05
-5.27762e-05
-1.83408e-05
4.677e-05
-1.81575e-05
-2.86125e-05
0.000131772
-0.000211079
3.73243e-05
2.87881e-05
-4.49717e-05
6.53304e-05
-2.03587e-05
1.45763e-05
-1.27898e-05
0.000149076
-3.72333e-05
-6.55748e-05
-3.59897e-05
0.000155281
-0.000101002
-5.42793e-05
5.19072e-05
-4.75457e-05
-2.01773e-05
1.58158e-05
-3.04188e-05
5.37236e-05
-0.000135987
0.000113022
-5.95753e-05
0.00014868
-0.000229438
-2.02819e-05
-6.92693e-05
7.69766e-05
0.000219319
-8.08566e-05
2.05456e-05
0.000160288
1.09393e-05
-4.71982e-07
-9.09869e-05
1.55925e-05
-0.00032609
-0.000636973
-0.000339206
0.000388286
0.00106203
0.000108362
-3.72448e-05
0.000108112
-5.31262e-07
-0.000107581
-2.59989e-05
1.66728e-05
-2.56783e-06
-5.5798e-05
-3.67867e-05
-4.34968e-05
-5.7505e-05
4.13357e-05
-2.20333e-05
-2.549e-05
1.32549e-05
-6.91472e-05
-0.000321282
-0.000683468
0.000331868
0.000672883
0.00103918
-0.000267278
7.10849e-05
9.16943e-07
0.000140977
-0.000137924
-3.97047e-06
9.86149e-05
-0.000107356
0.000913615
-0.000923348
9.3925e-05
-8.41919e-05
-6.18406e-06
-0.000141106
6.77565e-05
7.95332e-05
0.00010773
-6.09597e-05
-9.32149e-05
3.44735e-05
7.67907e-05
-3.50871e-05
8.29852e-05
6.46787e-05
-6.89299e-05
-4.25848e-05
4.68361e-05
0.00107864
-0.000295945
3.48712e-05
-0.000250794
-7.90118e-05
0.00042334
-0.00108331
0.000962567
6.51034e-05
-3.96028e-05
1.30585e-05
-3.25381e-05
0.000156457
-0.000368631
0.00072573
-5.93976e-05
-0.000184069
0.00017611
0.000754292
0.000580037
-0.000462067
7.96277e-05
-8.07191e-05
0.000656765
-0.000367884
-0.000288881
-7.40237e-05
8.89691e-05
2.26933e-05
-3.76386e-05
-0.000143251
-0.000170252
0.000245842
0.000165261
-7.96851e-06
-0.00017842
2.11282e-05
-7.9077e-05
0.000113608
-9.10479e-05
1.21912e-05
-5.27013e-05
-0.000316835
0.000357345
0.000538304
-0.000365473
0.000232043
-0.000404874
0.000240476
-0.000195575
0.000184122
-0.000229022
-0.000307215
7.00677e-05
0.000249338
-5.9659e-05
3.64413e-05
-5.08061e-05
0.000120377
0.000190559
-7.04607e-05
-0.000116383
-9.6228e-05
0.000132221
8.03901e-05
5.03579e-05
9.70176e-05
-2.18465e-05
0.000123341
-0.000198512
-0.000232348
4.66363e-05
-0.000130041
-0.000112171
-2.50818e-05
-9.75462e-06
2.34148e-05
-7.73711e-06
-5.92304e-06
-0.000313228
0.000143638
4.78746e-05
-0.000108258
7.57085e-05
-1.53248e-05
-0.000311489
0.000341157
-8.23696e-05
-1.70824e-05
-5.08252e-05
-4.84754e-05
-4.61459e-05
7.40656e-05
0.000156202
-0.000385253
0.00018278
-0.000124459
-5.20982e-06
-2.16272e-05
-4.52447e-06
-5.15106e-05
3.81045e-05
-2.15091e-05
-1.65954e-05
4.53235e-05
9.33153e-05
9.11284e-07
-0.00013955
5.06212e-05
-2.41587e-05
1.88609e-05
-2.78979e-05
0.000112639
9.71658e-05
4.29081e-05
-0.000140074
4.2095e-06
-5.44346e-05
7.36399e-05
-8.15115e-07
-2.7125e-06
-4.62734e-05
0.000386279
0.000198299
-1.50228e-05
5.33056e-05
1.23384e-05
-6.07234e-05
0.000311246
-0.000615996
8.24896e-05
-0.000105789
-0.000293535
0.000332693
-0.000473847
8.04301e-05
-0.000531669
0.000415027
7.03692e-05
0.000199183
-3.66003e-05
0.000223696
0.00011227
-0.000333991
0.000132671
0.00033753
-0.000343402
0.000339148
-0.000333276
0.000116059
-0.000138306
2.22466e-05
-0.000489061
-0.000204198
0.000124605
-0.000610007
0.000491917
-0.000451519
0.0001524
-9.95264e-05
0.00012726
-0.000479253
-7.89205e-06
-0.000558827
-0.000100797
0.000338342
-0.000707858
0.000281456
0.000551008
-0.000226737
0.000292471
0.000468082
-0.000272618
-0.000242393
0.000230352
3.83617e-05
-2.63206e-05
-4.18115e-05
1.66222e-05
0.000862089
-0.000205324
-2.72576e-05
-0.00038447
-0.000296131
-0.000303691
6.89851e-05
-0.000800277
0.000584891
0.000531369
-0.000751609
0.000471603
-0.000378129
0.000167754
-6.34148e-05
-0.000292126
0.000355541
-0.00028814
-0.000253659
-3.94986e-05
5.0765e-05
-0.000137208
0.000999297
-0.00109862
-0.00112834
0.000153048
0.000137841
4.61346e-05
-0.00037145
-0.000265815
-0.000199486
-0.000173411
0.000175318
0.000197579
0.000220118
-0.000249232
0.000261641
-0.000232527
4.91054e-05
4.80604e-05
2.75963e-05
0.000216112
-0.000100053
4.61868e-05
-0.000195152
-2.94549e-05
-0.000681213
0.00072203
0.000544073
-7.60143e-05
-4.69616e-05
-0.00026319
5.64926e-05
-0.000458625
-3.30049e-05
0.00049163
3.05068e-05
-7.62115e-05
9.5981e-05
-5.02763e-05
9.63228e-05
-9.0294e-05
-0.000929377
-0.000111929
0.000133662
8.7743e-06
-0.000448013
-0.000307907
0.000456974
8.59779e-05
-0.000542952
-0.000132506
-0.000112329
0.000148606
-0.000153642
0.000109468
0.000141192
4.46876e-05
-0.000220176
7.58032e-05
-0.000112876
8.51333e-05
-0.000320977
6.3473e-05
0.000321248
-0.000288691
-0.000163425
0.000237256
-0.000173883
0.000212114
-2.93339e-05
-8.77287e-06
0.000220887
7.55015e-05
0.000155691
-5.42403e-05
4.29788e-05
-0.000238778
-6.29519e-05
0.000321759
-1.65035e-06
-0.000126899
0.000165381
-0.000288915
6.0733e-05
-0.000130701
-1.8878e-05
8.53709e-05
7.99778e-05
-9.54563e-05
-5.60536e-05
5.07115e-05
-3.42606e-05
0.000245202
-3.5277e-05
-0.000256887
-0.000288758
-0.000128521
4.07445e-05
-4.03167e-05
-1.96647e-05
1.92369e-05
0.000259912
-0.000213677
-5.3182e-05
0.000109805
-2.22716e-05
0.000113728
-0.00111156
-5.2606e-06
-0.000918667
-0.000327791
2.3584e-05
0.000135853
-0.000296077
0.000246028
-0.000160522
-0.000177882
0.000153089
-0.000157683
0.000182476
-4.04729e-05
0.000151863
1.40741e-05
6.42184e-05
-0.00022303
0.000298116
0.000386612
-0.000461697
-0.000244549
0.000105544
0.000248472
-4.71778e-06
0.000290156
0.000109029
0.00013325
-0.000162804
-0.000143858
-6.72529e-05
-0.000957594
-2.40375e-05
0.000988895
0.00022347
9.54251e-05
-0.00022825
-6.23274e-05
0.000142164
-0.000168105
3.77112e-05
0.000130394
0.000976786
-0.00102939
-0.000187639
-0.000299908
0.000201319
6.78641e-05
-5.0731e-05
0.000155787
-0.000185426
-0.000160052
0.000189691
2.34463e-05
-9.17399e-05
-0.000320151
7.08468e-05
-1.7809e-05
2.67845e-07
9.46273e-05
0.000181952
0.000222874
-0.000179717
0.00011263
0.000404948
-0.000203532
6.79794e-05
-0.00011821
7.79877e-05
-2.77572e-05
-0.000192849
0.000128394
6.53662e-05
-0.000855286
5.48743e-05
0.000135173
5.06211e-05
-0.000132071
-0.000306757
0.000106896
-8.12303e-05
-4.66413e-05
0.000127872
-0.000104759
3.1502e-05
6.70731e-05
0.000215023
-0.00030288
7.50735e-05
-4.65823e-05
-0.000165431
6.17704e-06
-6.22697e-05
0.000227304
0.000176124
-0.000147674
0.000213322
-2.15698e-05
0.00023949
-0.000985981
-0.000272987
-4.32198e-05
-0.000738407
1.93546e-05
8.3712e-05
8.75032e-05
9.79714e-05
7.64146e-05
-0.000159883
-1.45032e-05
-7.50875e-05
0.000176778
-5.13082e-05
-3.97394e-05
0.00108752
8.28464e-06
-2.69649e-05
-0.00105229
-3.23213e-05
-0.000111726
0.000265623
0.000364456
0.000469739
-0.000256741
0.000251468
0.00124793
0.00109112
0.000152089
0.000185751
0.00109601
0.000242717
6.10738e-05
-4.80406e-05
7.57715e-05
-1.23094e-05
-8.94775e-05
-0.000917047
0.000109573
-1.60772e-05
6.62421e-05
-8.57647e-05
6.60098e-06
-3.04006e-05
-1.59398e-05
-0.000337335
0.000111784
0.000166946
-8.23356e-05
-0.000123266
0.000109286
0.000211648
0.000152385
-0.000275419
-0.000105215
5.14856e-05
-7.81764e-05
-1.98915e-05
0.000795543
-0.000151602
-0.00061203
-3.19111e-05
-0.000719276
0.000668974
0.000289793
-0.000110463
-3.74148e-05
8.32755e-06
-0.000134884
9.55073e-05
-5.47733e-05
0.00013256
-0.000221611
0.000297878
0.000146209
-0.000981684
-7.11215e-05
0.00054207
-0.000503953
5.44647e-06
0.000166863
-0.000181083
0.00013116
0.000170536
0.000202768
0.000218281
-0.000342789
-0.00016636
0.000368492
0.000140657
0.00024317
-0.000236246
-0.00013211
0.00013713
0.00012744
0.000347404
0.000335281
-0.000498477
-3.96282e-06
7.26768e-05
0.000848304
-0.000214018
0.000159536
-0.000288308
7.61054e-05
6.69686e-05
-0.000266345
-0.000108558
0.000292533
-0.0010036
0.00103626
-0.000280908
4.9213e-05
3.37746e-05
0.000103027
-1.22513e-05
-0.000222886
-0.000153138
3.20471e-05
-0.00096315
-0.000198547
-3.91354e-05
0.000261157
-0.00035131
0.000787863
5.331e-05
0.00102574
-0.000991588
-0.000108039
0.000117606
9.34608e-05
-0.000104858
0.000199301
1.66645e-05
-3.74969e-05
7.7974e-05
-5.71415e-05
-0.000307446
-0.000153057
-4.13397e-05
8.3934e-05
-1.97951e-07
-0.000143008
-0.000200101
0.000244755
0.00024051
0.000198221
-0.000385982
-0.000168898
4.86075e-05
-0.000184453
-1.87316e-05
9.7031e-05
-0.000146564
-4.25974e-06
0.000181854
-0.000147984
0.000978286
-0.00122828
0.000258276
0.000324553
-0.000133709
0.000719702
5.67283e-05
0.000944402
0.000278634
-0.000100936
-0.0011221
-8.48806e-05
-0.000193858
0.000101081
0.000123823
7.75882e-05
-8.84693e-05
3.96041e-06
6.92065e-06
0.000115258
-0.000128946
0.000138847
-0.000125159
0.000124101
-0.000127878
0.00132981
9.94278e-05
2.8018e-05
3.62362e-05
0.00132634
-0.00020931
-0.000242185
-2.19565e-05
8.56361e-05
8.73628e-05
4.00676e-05
-0.00102808
8.09436e-05
0.00012579
-6.26451e-07
8.25967e-05
1.91112e-05
-0.000966083
-0.00115538
0.00072475
0.000480614
-4.77186e-05
0.000268352
0.000249246
-0.000365468
-0.00015213
1.54632e-05
-4.30909e-05
-0.000125015
6.64266e-05
-0.000132114
0.000162407
2.41075e-05
0.000222696
7.7802e-05
-0.000163209
0.000160508
0.000237444
-4.06067e-05
-0.000226233
-9.62484e-05
0.000179473
-3.10483e-05
-8.04069e-05
-0.000182723
7.35355e-06
0.000115843
0.000124066
5.12934e-05
6.4376e-05
-0.000218268
-0.00034706
7.71063e-05
-1.17759e-05
-6.79754e-05
4.25769e-05
0.000858319
0.000122939
-0.000146283
-0.000811543
0.000256572
8.24141e-06
-1.00952e-05
0.00046094
0.000402259
0.000138787
0.000105267
0.00108376
-0.000527505
-2.7447e-05
-0.000245972
0.000171468
9.96349e-05
5.43351e-05
-4.19437e-05
0.000102607
0.000377669
-0.000377523
-0.000236661
0.000156777
-0.000726024
0.00067614
4.98836e-05
5.30844e-05
-2.75649e-05
-6.31581e-05
-0.000201419
0.00030866
0.000200726
0.000887851
0.000134064
-0.000788514
6.24899e-05
5.3251e-05
0.00106642
-8.97486e-05
-0.000945346
0.00101106
-0.000230945
0.000411255
2.25404e-05
-0.000202851
0.000133866
0.000129854
-0.000169185
5.83696e-05
0.000617771
0.000544479
-5.04596e-05
-0.000559015
6.49954e-05
0.000122799
-0.000135408
0.000162525
-0.000149917
-0.000226243
4.47257e-05
0.000181517
7.091e-05
0.000223431
4.36588e-05
-0.000287372
-0.000111822
-4.13166e-05
-0.000271069
4.48263e-05
-0.000313979
0.00020581
-0.00024958
-0.000187175
-0.000888958
-0.000154292
3.99864e-05
-5.11259e-05
-0.000155333
8.88234e-05
3.43816e-06
8.62527e-05
-0.000101698
0.000159577
5.4149e-05
-0.000115447
0.000393034
0.000537516
-0.000177786
5.27529e-05
0.00015708
-0.000484445
0.000468473
1.59714e-05
8.31003e-05
-0.000871614
8.75433e-05
-0.00011476
0.000178898
0.000162495
0.000142487
0.000857345
-0.000356857
0.000391843
-0.000417908
0.00013326
7.7093e-05
0.000174358
-6.16403e-05
0.000878077
-0.000195362
0.000356468
-0.00095755
0.000655979
0.000630809
-0.00105649
-5.11231e-05
0.000609198
0.000357125
-0.000277226
-0.000625908
0.000546747
0.000506952
-0.000585452
0.000315157
0.000529706
-0.000264053
-0.000429835
-0.000213012
0.000377032
-5.16964e-05
7.06264e-06
-0.00062033
0.000730163
-0.000504669
2.02244e-05
-9.19792e-05
-1.65538e-05
0.000342741
0.000395843
-2.34954e-05
4.64982e-05
5.27687e-05
0.000312188
-0.000274369
0.000102839
-7.89616e-06
-1.71856e-05
0.000458369
1.01039e-05
9.79536e-05
4.88494e-05
-6.92148e-05
8.67437e-05
-5.7393e-06
-8.50643e-05
-0.000123167
-0.000366537
0.000187642
-0.000160544
-3.81166e-06
0.000112841
-0.000441784
-3.6992e-05
9.96248e-05
-3.50257e-05
-0.000163591
-0.000490803
0.000103941
-0.000100395
-1.00156e-05
4.08553e-05
0.000341166
7.36281e-05
-2.96027e-05
-8.42979e-05
-6.2271e-06
-0.000915413
0.000168643
-0.000119971
9.30562e-05
-0.000169626
0.00101346
-0.000959215
6.95254e-05
4.39414e-05
-0.000232334
0.000117501
0.000133162
0.000255232
-0.00108068
3.16386e-05
8.89126e-05
5.35553e-05
0.000107323
7.76277e-05
-2.53735e-05
0.000923001
0.000126085
-0.000137756
0.00010602
-6.62151e-06
8.37278e-05
0.000178827
5.95943e-06
-0.000938301
0.000631216
6.4078e-05
-2.4847e-05
-0.000218342
2.73331e-05
-0.000268003
-9.94897e-05
3.37074e-05
0.00111183
7.0999e-05
-0.00107491
-0.000366708
0.000423257
1.37102e-05
8.96187e-05
6.88321e-05
-0.000104337
0.000168974
0.000503568
-0.000726781
0.000223213
0.000436959
6.6609e-05
0.000448539
-1.15805e-05
-0.000308438
0.000464895
-0.000677068
-0.000600623
-0.000502428
-9.81955e-05
2.68743e-05
-3.9938e-05
-5.05937e-05
7.53119e-05
-0.000937114
-0.00012114
0.000166141
0.000126745
0.000245357
9.40088e-06
-8.416e-05
-3.47242e-05
3.4789e-06
-1.2075e-05
-4.19374e-06
-4.46849e-05
-0.000251978
0.000270664
-8.26913e-05
-3.14721e-06
-1.39401e-05
2.30222e-06
0.000427827
0.000806629
-0.000180225
0.000197177
-8.94472e-05
0.000165938
9.5293e-05
-0.000172318
-0.000220917
-0.000991606
0.000137924
-2.47747e-05
0.000210556
-0.000474917
-2.75109e-05
0.000339467
-0.000156251
-0.000645284
0.000121503
5.83054e-05
0.000382836
-0.000104176
6.67425e-05
0.000125296
-6.32978e-05
3.5033e-05
9.76382e-05
-0.0011453
0.00103424
-3.73981e-05
3.90975e-05
5.47626e-06
0.000211215
-0.000255789
-0.000182358
0.000158672
2.43661e-05
-4.95389e-05
-0.000170618
6.92469e-06
8.15095e-05
-0.00118076
1.70991e-06
0.000679397
-0.00038154
0.000126395
-7.10391e-05
0.000225985
0.000244157
-0.000157788
-6.74232e-05
-6.60442e-05
3.39777e-05
-0.000113571
9.86808e-05
-0.000123881
-7.99119e-05
6.92725e-05
-2.07842e-06
-0.00060718
-0.000345347
-0.00012917
-0.000146298
-0.000152915
-2.2358e-05
6.70146e-05
1.8418e-06
9.83463e-06
-8.19753e-06
0.000997413
-0.000492941
0.000336288
8.50556e-05
-0.000111843
-0.000219117
-7.85162e-05
0.000226652
-0.00079917
0.0011182
-0.000112666
0.000218786
-1.31184e-05
0.000156104
-6.97471e-05
-4.6328e-05
-3.08629e-06
0.00103685
4.36891e-05
3.01787e-05
-5.45514e-05
-0.000184033
0.000225432
-0.000165735
-0.000220372
0.000108068
-0.000860095
4.25097e-05
0.000477952
1.92816e-05
-9.16495e-05
0.000207567
0.00108275
7.16535e-05
-9.68007e-05
0.000107107
-0.000412487
-2.02488e-05
-0.000257468
0.000168108
0.00038683
0.000273725
-0.000224451
7.52181e-05
0.000278933
2.0007e-05
0.000306695
-0.000297865
0.000179358
-1.07148e-05
-0.000201759
0.000186356
-0.000962643
0.00102988
-0.000247953
0.000180718
9.6711e-05
5.2654e-05
0.000112322
2.90277e-05
-0.000131258
-0.000246595
0.000408359
-0.000362015
0.00010227
-6.80435e-05
-0.000285493
8.06351e-05
-4.39486e-05
-2.62167e-06
-4.99577e-05
-0.00114839
9.30678e-05
0.000390219
-0.000215621
-6.0594e-06
-0.000111373
-0.00106639
0.000965485
1.90011e-05
-1.91848e-05
0.000989078
0.000318492
0.00055713
-0.000480597
-7.65333e-05
-3.4932e-05
0.000187981
0.00015407
0.00019349
-0.00019479
0.000171835
-0.000897974
0.000908157
-0.000182002
5.69512e-05
-0.000139412
8.52339e-05
5.41786e-05
0.000186006
-0.000212509
4.6594e-05
3.23845e-05
5.28493e-05
-0.00021727
-0.000203234
0.000318863
-0.00106131
-0.000177817
3.17657e-05
-2.04487e-05
4.59617e-06
-0.000218091
0.000218903
8.40509e-05
-1.79283e-05
-6.61226e-05
-0.00011315
-0.000108884
-0.000214548
-1.18304e-05
-0.000166424
7.37875e-05
-1.50327e-05
-0.000530361
0.000382299
8.49844e-05
-6.38052e-05
-0.000160638
-1.71793e-05
0.000219587
9.99647e-05
1.47202e-05
0.000352733
-1.29991e-05
3.48825e-05
-7.47148e-06
-4.64351e-05
-1.8914e-06
5.55338e-05
-3.3094e-05
-3.64465e-05
3.91399e-05
0.00010101
-1.69589e-05
-0.000149368
-1.12704e-05
3.51815e-05
0.000136316
0.000187988
-0.000163833
8.30414e-06
2.99468e-05
-0.000154197
-0.000223626
7.85118e-05
0.000448372
-0.000125371
-5.70634e-05
0.000276153
-0.000255643
0.000124321
-2.33113e-05
-0.000110128
1.46352e-05
0.00105132
-1.02579e-05
-0.0010126
-2.14936e-05
-0.000136213
0.000699776
-2.72454e-05
0.00012261
-0.000240397
-4.76919e-05
4.59897e-05
-8.50685e-07
0.000345579
-3.8557e-06
3.40344e-05
-0.000207428
0.00024261
-6.1952e-05
0.000249941
0.00139923
-0.00113033
0.000120352
-0.000924317
-7.53581e-05
6.09757e-05
-3.83187e-05
0.000245606
-0.000177377
0.000553083
-0.000723263
-0.000126909
9.05299e-05
1.39993e-06
0.000103445
0.000193641
0.000470136
-8.07424e-05
-0.000884987
-0.000308458
8.34715e-05
-0.000364992
0.000395977
-8.98039e-05
0.000588266
0.000925859
-0.000266196
7.80486e-05
-8.86518e-05
2.68839e-05
-2.12419e-05
-5.02747e-05
0.000679037
5.53981e-06
5.4712e-05
0.000189922
-1.05638e-05
-2.76518e-05
0.000141449
-4.02493e-05
-3.89228e-05
0.000150362
-3.70149e-05
7.18656e-05
1.43623e-05
-3.22385e-06
2.84297e-05
-0.000159369
0.000145688
7.60359e-05
-0.000243274
9.88855e-05
0.000134146
2.57454e-05
0.000907145
-0.000916919
4.05706e-05
-9.04974e-06
-6.87311e-06
2.10195e-05
-0.000271771
0.000264701
3.11762e-05
4.54081e-06
7.7767e-05
0.000530775
2.37786e-05
-2.44392e-05
0.000536354
-0.000316385
0.000251401
-0.000205771
0.000393741
5.05408e-05
-3.1815e-05
0.000262214
-0.000238811
-0.000908185
-0.000143956
-0.000329624
-5.90544e-05
-0.000213758
4.16641e-05
9.07884e-05
-2.5433e-05
-6.62548e-05
-0.000119043
0.00012034
-0.000239225
0.000149782
0.000135218
0.000105157
-6.35549e-05
-7.8617e-05
1.87276e-05
8.06925e-05
1.52637e-05
-0.000359014
0.000714388
9.95148e-05
-2.53365e-05
0.000110722
-0.000185673
0.000256583
0.00118258
-0.00101137
9.74056e-05
-4.81592e-05
0.00027651
0.000755333
0.000629162
-5.81516e-05
0.000305508
-0.000167406
0.000289679
-0.000855403
0.000889602
-0.000323878
4.49008e-05
3.64504e-05
-3.69253e-05
-0.000109653
-0.00101674
-0.000613958
8.08387e-05
-0.000143071
-0.00100973
-8.21789e-05
-0.00023101
-9.17765e-05
2.95525e-05
-0.000293649
-0.000996778
8.14454e-05
0.000977823
-0.00103329
0.000119611
-0.000222613
0.000239936
-0.000101722
0.000244386
-0.000221181
5.33168e-05
4.9037e-05
-0.000631067
-0.000306017
0.000936393
-0.00067903
-0.000131965
7.89926e-05
-6.05844e-05
0.000119642
0.00099147
0.000513497
-0.000186316
-0.000149261
-0.000325656
-2.69813e-05
-1.92114e-05
4.61927e-05
-4.82481e-05
0.000101411
-0.000213046
-0.000933165
-3.94692e-05
-0.000435266
0.0003946
3.33734e-05
-0.000506617
0.000133485
-9.97779e-05
0.000271743
-0.000346132
-7.29258e-05
4.16741e-05
4.26052e-05
2.00023e-05
-5.48598e-05
0.000173041
-0.00016634
5.22592e-06
9.54199e-05
0.000110846
-0.000163365
-9.65458e-06
0.00010288
-0.00011149
-9.31574e-05
0.000165747
-0.000123826
-0.000952348
-0.000150062
0.000154658
0.00036658
-0.000323932
-5.26233e-05
4.21467e-05
0.000237129
-0.000149134
0.000195148
7.72962e-05
5.9322e-05
0.000237678
-6.50969e-05
-8.8334e-05
8.3374e-05
-0.000269269
-0.00125495
-0.000148098
0.000224397
1.53934e-05
-0.000215583
-0.000234539
0.000257878
0.000311992
-6.74849e-05
-0.000116722
-0.00102351
-1.47926e-05
0.000322651
-0.000339391
0.000112875
0.000269495
0.000102387
-4.26721e-05
0.000168694
-0.000109197
-0.000250068
0.000268972
6.95714e-05
0.0010863
0.000463758
-0.000154006
0.000155406
-2.57853e-05
1.3647e-05
-4.88228e-05
6.58002e-05
-0.000152236
-0.000223197
6.50397e-05
-9.70868e-05
0.000233402
-0.000668871
0.00088822
0.00106113
-5.60317e-05
0.000945897
-9.40018e-05
0.000267238
-0.000388732
-0.000685186
0.000496631
-0.000233741
-0.000444723
-0.00016965
-2.88361e-05
0.000324627
-1.39279e-05
-8.96507e-05
-0.000327421
-0.000133788
-0.00123004
3.80714e-05
8.66316e-05
0.000266981
0.000277761
-0.000552485
0.000746313
-0.00101503
0.000349527
-0.000143701
-5.17465e-05
2.19662e-05
-0.000147693
0.000965789
-0.000119855
-8.11782e-06
1.52177e-05
3.54054e-05
-1.16906e-05
4.12431e-05
8.37766e-06
-6.27933e-05
0.000952735
0.000162892
-0.0011523
0.000618469
-0.000889151
8.42746e-06
2.03773e-06
4.677e-05
6.3194e-05
-0.000125713
9.02215e-06
-0.000157312
-0.000715726
0.000797727
-0.000131303
7.22968e-05
-1.22321e-05
0.000381737
-0.00101285
0.00032258
-0.000957771
0.000155661
-0.000191522
0.000149845
-2.11539e-05
0.000102529
-0.00011847
-0.000192404
0.000179197
0.0004639
0.000156372
9.27642e-05
0.000922559
0.000632462
0.000122111
6.6325e-05
-0.00110087
0.000203525
-0.000775722
0.00107322
-5.59193e-05
5.95513e-05
-0.000238528
1.58165e-05
-0.00010578
0.000869892
0.00083558
-7.068e-06
6.06988e-05
-0.000200561
7.16308e-05
-8.00094e-06
-0.000281904
0.00034765
0.000131538
1.83582e-05
-8.37499e-05
-3.93921e-05
0.000118175
0.000145129
2.17831e-05
1.2476e-05
-2.91361e-05
-0.00013209
0.000175998
5.33451e-05
-0.00045211
0.000196114
-0.000134721
-0.000216348
0.000113194
5.09507e-05
9.74705e-05
-4.83139e-05
0.000196522
7.68929e-05
-2.91215e-05
0.000191821
-0.000164658
-0.000318037
0.000599562
0.000134746
-0.000224839
-1.22419e-05
0.00071836
2.06198e-05
-4.30893e-05
0.000258342
-4.13515e-05
4.35382e-05
-0.000448667
0.000106741
-1.57023e-05
-1.4198e-05
-6.84126e-05
0.000116355
5.89075e-05
-0.000270592
-0.00114789
0.000812018
-0.000826152
-6.09505e-05
-8.10772e-05
-0.000106545
1.62657e-05
0.000182788
-6.91745e-05
-7.719e-05
0.000163349
-2.01387e-05
0.000441665
0.000429306
0.000414216
-0.00046976
0.00087292
5.30405e-05
-0.000199661
0.000225742
8.32353e-05
-0.00047035
5.67904e-05
-0.000179413
)
;
boundaryField
{
frontAndBack
{
type empty;
value nonuniform 0();
}
wallOuter
{
type calculated;
value uniform 0;
}
inlet
{
type calculated;
value nonuniform List<scalar> 9(-0.00111111 -0.00111111 -0.00111111 -0.00111111 -0.00111111 -0.00111111 -0.00111111 -0.00111111 -0.00111111);
}
outlet
{
type calculated;
value nonuniform 0();
}
wallInner
{
type calculated;
value uniform 0;
}
procBoundary0to1
{
type processor;
value nonuniform List<scalar>
29
(
0.000102271
1.32265e-06
-4.03597e-05
0.00035941
-8.54352e-05
-0.000135979
0.000459534
0.00054719
0.00103986
0.000689991
0.000570975
-0.000490593
-0.000151406
0.000325739
0.000823629
0.00111854
3.86337e-06
0.000324027
0.000451292
-0.000237934
0.00117788
0.00103716
0.000874532
0.000555964
0.000727471
0.000105424
0.000724113
0.000185186
0.000255076
)
;
}
procBoundary0to2
{
type processor;
value nonuniform List<scalar>
42
(
-0.000516031
-0.000101762
8.35007e-05
0.0002016
0.000205982
-9.7947e-05
6.70124e-05
2.92232e-05
0.000131717
7.25487e-05
0.000180268
2.4687e-05
0.000118429
-4.39095e-05
-0.000141428
-0.000167237
0.000164474
4.31749e-05
9.64892e-05
0.000176498
-0.000277365
-5.0442e-05
0.000123437
-0.000337024
0.000196622
-9.53841e-06
-0.000391997
-6.0432e-05
0.000254889
-5.05123e-05
-0.000426568
-8.88048e-05
-8.20001e-05
-5.13249e-05
-1.59661e-05
-3.53383e-05
-0.000383564
0.000226378
-0.00049795
8.70116e-05
-2.8706e-06
2.73246e-05
)
;
}
}
// ************************************************************************* //
| |
77a18177997364b1f98fcfca223beb4d008672b0 | 63bdee29ac1d4bb8fd425b75003a10fa98506b27 | /test/gtest/src/transform_double_test.cpp | 156079d54ee57cdce6305a887ce690fb62fd1dea | [] | no_license | rocmarchive/HcSPARSE | ad273991409d9c24b6ed013ca5b4328988cdb90a | ddfe7da9c7b0a41ccf30fbc9eea6debcb1567df2 | refs/heads/master | 2021-10-24T04:37:43.079874 | 2019-03-21T22:41:45 | 2019-03-21T22:41:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,161 | cpp | transform_double_test.cpp | #include <hcsparse.h>
#include <iostream>
#include "hc_am.hpp"
#include "gtest/gtest.h"
TEST(transform_double_test, func_check)
{
hcdenseVector gR;
hcdenseVector gX;
hcdenseVector gY;
std::vector<accelerator>acc = accelerator::get_all();
accelerator_view accl_view = (acc[1].create_view());
hcsparseControl control(accl_view);
int num_elements = 100;
double *host_R = (double*) calloc(num_elements, sizeof(double));
double *host_res = (double*) calloc(num_elements, sizeof(double));
double *host_X = (double*) calloc(num_elements, sizeof(double));
double *host_Y = (double*) calloc(num_elements, sizeof(double));
srand (time(NULL));
for (int i = 0; i < num_elements; i++)
{
host_R[i] = rand()%100;
host_X[i] = rand()%100;
host_Y[i] = rand()%100;
}
hcsparseSetup();
hcsparseInitVector(&gR);
hcsparseInitVector(&gX);
hcsparseInitVector(&gY);
gX.values = am_alloc(sizeof(double) * num_elements, acc[1], 0);
gY.values = am_alloc(sizeof(double) * num_elements, acc[1], 0);
gR.values = am_alloc(sizeof(double) * num_elements, acc[1], 0);
control.accl_view.copy(host_X, gX.values, sizeof(double) * num_elements);
control.accl_view.copy(host_Y, gY.values, sizeof(double) * num_elements);
control.accl_view.copy(host_R, gR.values, sizeof(double) * num_elements);
gR.offValues = 0;
gX.offValues = 0;
gY.offValues = 0;
gR.num_values = num_elements;
gX.num_values = num_elements;
gY.num_values = num_elements;
hcsparseStatus status;
bool ispassed = 1;
for (int j = 0; j < 4; j++)
{
switch(j)
{
case 0:
status = hcdenseDadd(&gR, &gX, &gY, &control);
for (int i = 0; i < num_elements; i++)
{
host_res[i] = host_X[i] + host_Y[i];
}
break;
case 1:
status = hcdenseDsub(&gR, &gX, &gY, &control);
for (int i = 0; i < num_elements; i++)
{
host_res[i] = host_X[i] - host_Y[i];
}
break;
case 2:
status = hcdenseDmul(&gR, &gX, &gY, &control);
for (int i = 0; i < num_elements; i++)
{
host_res[i] = host_X[i] * host_Y[i];
}
break;
case 3:
status = hcdenseDdiv(&gR, &gX, &gY, &control);
for (int i = 0; i < num_elements; i++)
{
host_res[i] = host_Y[i] == 0 ? 0 : (host_X[i] / host_Y[i]);
}
break;
}
control.accl_view.copy(gR.values, host_R, sizeof(double) * num_elements);
for (int i = 0; i < num_elements; i++)
{
double diff = std::abs(host_res[i] - host_R[i]);
EXPECT_LT (diff, 0.01);
}
}
hcsparseTeardown();
free(host_R);
free(host_res);
free(host_X);
free(host_Y);
am_free(gR.values);
am_free(gX.values);
am_free(gY.values);
}
|
d94706fa1ecb66f655edc2a123b946d26967297c | dcc945b8be760e948a607dc0dc63b887d4274bc1 | /src/random.cc | 0e3774e99f82394a036c4fb67580b7abdc92ad6a | [] | no_license | joanalza/RK-EDA | ec2995c0027ffae5e72be6d87e7c26acb8b54b4e | f52b0f26dfb540f9dde0ca51b547483065a629de | refs/heads/master | 2021-05-26T08:24:04.561283 | 2019-09-16T16:07:03 | 2019-09-16T16:07:03 | 128,073,483 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,734 | cc | random.cc | /**
* Copyright 2008, Daniel Molina Cabrera <danimolina@gmail.com>
*
* This file is part of software Realea
*
* Realea 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 3 of the License, or
* (at your option) any later version.
*
* Realea 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 Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
#include "random.h"
#include <iostream>
#include <math.h>
#include <cassert>
using namespace std;
Random::Random(IRealRandom *random) {
assert(random != NULL);
this->random = random;
}
Random::~Random(void) {
delete this->random;
}
const double PI=3.1415926;
double Random::normal(double desv) {
double u1, u2;
double result;
do {
u1=Random::rand();
} while (u1 == 0);
u2=Random::rand();
result = desv * sqrt (-2*log(u1)) * sin (2*PI*u2);
return result;
}
void initSample(int *sample, int max) {
int i;
for (i = 0; i < max; i++) {
sample[i] = i;
}
}
int Random::getSample(int *sample, int *pmax) {
int max = *pmax;
int r, pos;
assert(max >= 0);
r = randint(0, max-1);
pos = sample[r];
sample[r] = sample[max-1];
--max;
*pmax = max;
return pos;
}
unsigned long Random::getSeed(void) {
return random->getSeed();
}
|
8ce7227ad6e130ea51b80f1bc09172e118705e78 | c2fba7363aac67c9b340474e3a83184ac8dbc74e | /[기초-조건선택실행구조] 평가 입력받아 다르게 출력하기.cpp | 131af3e8ab2b09dee40d30e52d5ae00ea92a9da3 | [] | no_license | m0vehyeon/Code-Up-Algorithm | 728ae70628bf6c1f04337497537a3ed9980485c8 | c6fd85ac303b0e1afbb02c1b83bcd3528f29b707 | refs/heads/master | 2021-09-18T03:06:41.801357 | 2018-07-09T08:54:42 | 2018-07-09T08:54:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 288 | cpp | [기초-조건선택실행구조] 평가 입력받아 다르게 출력하기.cpp | #include <stdio.h>
int main()
{
char a;
scanf("%c", &a);
if (a == 'A')
printf("best!!!\n");
else if (a == 'B')
printf("good!!!\n");
else if (a == 'C')
printf("run!!!\n");
else if (a == 'D')
printf("slowly!!!\n");
else
printf("what?\n");
return 0;
} |
e9404a8e98d3e8cb7c69a0389dc863c494096546 | b9ac3f216183e3fc7f52845598c8b8e4eee2497d | /xls/codegen/codegen_options.cc | ca7ab14fbc5950273eb8dbd32038ebefcaf8e2d7 | [
"Apache-2.0"
] | permissive | google/xls | ba225b411161836889a41c6d0e3a2fc09edc25ef | c2f3c725a9b54802119173a82412dc7a0bdf5a2e | refs/heads/main | 2023-09-02T06:56:27.410732 | 2023-09-01T22:27:04 | 2023-09-01T22:28:01 | 262,163,993 | 1,003 | 152 | Apache-2.0 | 2023-08-31T14:47:44 | 2020-05-07T21:38:30 | C++ | UTF-8 | C++ | false | false | 8,471 | cc | codegen_options.cc | // Copyright 2021 The XLS Authors
//
// 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 "xls/codegen/codegen_options.h"
#include <memory>
#include <optional>
#include <string_view>
#include <utility>
#include "xls/common/proto_adaptor_utils.h"
namespace xls::verilog {
/* static */ std::string_view CodegenOptions::IOKindToString(IOKind kind) {
switch (kind) {
case IOKind::kFlop:
return "kFlop";
case IOKind::kSkidBuffer:
return "kSkidBuffer";
case IOKind::kZeroLatencyBuffer:
return "kZeroLatencyBuffer";
}
XLS_LOG(FATAL) << "Invalid IOKind: " << static_cast<int64_t>(kind);
}
CodegenOptions::CodegenOptions(const CodegenOptions& options)
: entry_(options.entry_),
module_name_(options.module_name_),
reset_proto_(options.reset_proto_),
pipeline_control_(options.pipeline_control_),
clock_name_(options.clock_name_),
use_system_verilog_(options.use_system_verilog_),
separate_lines_(options.separate_lines_),
flop_inputs_(options.flop_inputs_),
flop_outputs_(options.flop_outputs_),
flop_inputs_kind_(options.flop_inputs_kind_),
flop_outputs_kind_(options.flop_outputs_kind_),
split_outputs_(options.split_outputs_),
add_idle_output_(options.add_idle_output_),
flop_single_value_channels_(options.flop_single_value_channels_),
emit_as_pipeline_(options.emit_as_pipeline_),
streaming_channel_data_suffix_(options.streaming_channel_data_suffix_),
streaming_channel_ready_suffix_(options.streaming_channel_ready_suffix_),
streaming_channel_valid_suffix_(options.streaming_channel_valid_suffix_),
array_index_bounds_checking_(options.array_index_bounds_checking_),
gate_recvs_(options.gate_recvs_) {
for (auto& [op, op_override] : options.op_overrides_) {
op_overrides_.insert_or_assign(op, op_override->Clone());
}
ram_configurations_.reserve(options.ram_configurations().size());
for (auto& option : options.ram_configurations()) {
ram_configurations_.push_back(option->Clone());
}
}
CodegenOptions& CodegenOptions::operator=(const CodegenOptions& options) {
entry_ = options.entry_;
module_name_ = options.module_name_;
reset_proto_ = options.reset_proto_;
pipeline_control_ = options.pipeline_control_;
clock_name_ = options.clock_name_;
use_system_verilog_ = options.use_system_verilog_;
separate_lines_ = options.separate_lines_;
flop_inputs_ = options.flop_inputs_;
flop_outputs_ = options.flop_outputs_;
flop_inputs_kind_ = options.flop_inputs_kind_;
flop_outputs_kind_ = options.flop_outputs_kind_;
split_outputs_ = options.split_outputs_;
add_idle_output_ = options.add_idle_output_;
flop_single_value_channels_ = options.flop_single_value_channels_;
emit_as_pipeline_ = options.emit_as_pipeline_;
streaming_channel_data_suffix_ = options.streaming_channel_data_suffix_;
streaming_channel_ready_suffix_ = options.streaming_channel_ready_suffix_;
streaming_channel_valid_suffix_ = options.streaming_channel_valid_suffix_;
array_index_bounds_checking_ = options.array_index_bounds_checking_;
gate_recvs_ = options.gate_recvs_;
for (auto& [op, op_override] : options.op_overrides_) {
op_overrides_.insert_or_assign(op, op_override->Clone());
}
ram_configurations_.reserve(options.ram_configurations().size());
for (auto& option : options.ram_configurations()) {
ram_configurations_.push_back(option->Clone());
}
return *this;
}
CodegenOptions& CodegenOptions::entry(std::string_view name) {
entry_ = name;
return *this;
}
CodegenOptions& CodegenOptions::module_name(std::string_view name) {
module_name_ = name;
return *this;
}
CodegenOptions& CodegenOptions::reset(std::string_view name, bool asynchronous,
bool active_low, bool reset_data_path) {
reset_proto_ = ResetProto();
reset_proto_->set_name(ToProtoString(name));
reset_proto_->set_asynchronous(asynchronous);
reset_proto_->set_active_low(active_low);
reset_proto_->set_reset_data_path(reset_data_path);
return *this;
}
std::optional<xls::Reset> CodegenOptions::ResetBehavior() const {
if (!reset_proto_.has_value()) {
return std::nullopt;
}
return xls::Reset{
.reset_value = Value(UBits(0, 1)),
.asynchronous = reset_proto_->asynchronous(),
.active_low = reset_proto_->active_low(),
};
}
CodegenOptions& CodegenOptions::manual_control(std::string_view input_name) {
if (!pipeline_control_.has_value()) {
pipeline_control_ = PipelineControl();
}
pipeline_control_->mutable_manual()->set_input_name(
ToProtoString(input_name));
return *this;
}
std::optional<ManualPipelineControl> CodegenOptions::manual_control() const {
if (!pipeline_control_.has_value() || !pipeline_control_->has_manual()) {
return std::nullopt;
}
return pipeline_control_->manual();
}
CodegenOptions& CodegenOptions::valid_control(
std::string_view input_name, std::optional<std::string_view> output_name) {
if (!pipeline_control_.has_value()) {
pipeline_control_ = PipelineControl();
}
ValidProto* valid = pipeline_control_->mutable_valid();
valid->set_input_name(ToProtoString(input_name));
if (output_name.has_value()) {
valid->set_output_name(ToProtoString(*output_name));
}
return *this;
}
std::optional<ValidProto> CodegenOptions::valid_control() const {
if (!pipeline_control_.has_value() || !pipeline_control_->has_valid()) {
return std::nullopt;
}
return pipeline_control_->valid();
}
CodegenOptions& CodegenOptions::clock_name(std::string_view clock_name) {
clock_name_ = clock_name;
return *this;
}
CodegenOptions& CodegenOptions::use_system_verilog(bool value) {
use_system_verilog_ = value;
return *this;
}
CodegenOptions& CodegenOptions::separate_lines(bool value) {
separate_lines_ = value;
return *this;
}
CodegenOptions& CodegenOptions::flop_inputs(bool value) {
flop_inputs_ = value;
return *this;
}
CodegenOptions& CodegenOptions::flop_outputs(bool value) {
flop_outputs_ = value;
return *this;
}
CodegenOptions& CodegenOptions::flop_inputs_kind(IOKind value) {
flop_inputs_kind_ = value;
return *this;
}
CodegenOptions& CodegenOptions::flop_outputs_kind(IOKind value) {
flop_outputs_kind_ = value;
return *this;
}
CodegenOptions& CodegenOptions::flop_single_value_channels(bool value) {
flop_single_value_channels_ = value;
return *this;
}
CodegenOptions& CodegenOptions::split_outputs(bool value) {
split_outputs_ = value;
return *this;
}
CodegenOptions& CodegenOptions::add_idle_output(bool value) {
add_idle_output_ = value;
return *this;
}
CodegenOptions& CodegenOptions::SetOpOverride(
Op kind, std::unique_ptr<OpOverride> configuration) {
op_overrides_.insert_or_assign(kind, std::move(configuration));
return *this;
}
CodegenOptions& CodegenOptions::emit_as_pipeline(bool value) {
emit_as_pipeline_ = value;
return *this;
}
CodegenOptions& CodegenOptions::streaming_channel_data_suffix(
std::string_view value) {
streaming_channel_data_suffix_ = value;
return *this;
}
CodegenOptions& CodegenOptions::streaming_channel_valid_suffix(
std::string_view value) {
streaming_channel_valid_suffix_ = value;
return *this;
}
CodegenOptions& CodegenOptions::streaming_channel_ready_suffix(
std::string_view value) {
streaming_channel_ready_suffix_ = value;
return *this;
}
CodegenOptions& CodegenOptions::array_index_bounds_checking(bool value) {
array_index_bounds_checking_ = value;
return *this;
}
CodegenOptions& CodegenOptions::gate_recvs(bool value) {
gate_recvs_ = value;
return *this;
}
CodegenOptions& CodegenOptions::ram_configurations(
absl::Span<const std::unique_ptr<RamConfiguration>> ram_configurations) {
ram_configurations_.clear();
for (auto& config : ram_configurations) {
ram_configurations_.push_back(config->Clone());
}
return *this;
}
} // namespace xls::verilog
|
cace141fc07a3a3325c3e05bf99fdb7de85aeaa8 | 04afb34356de112445c3e5733fd2b773d92372ef | /Sem2/OOP/Appliances store/Appliances store/Service.cpp | 9ec2cc4a33e04e8be9e361991e0025b498e3c271 | [] | no_license | AndreeaCimpean/Uni | a4e48e5e1dcecbc0c28ad45ddd3b0989ff7985c8 | 27df09339e4f8141be3c22ae93c4c063ffd2b172 | refs/heads/master | 2020-08-21T19:12:49.840044 | 2020-05-15T17:22:50 | 2020-05-15T17:22:50 | 216,222,647 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 844 | cpp | Service.cpp | #include "Service.h"
#include "Refrigerator.h"
#include "DishWasher.h"
using namespace std;
std::vector<std::shared_ptr<Appliance>> Service::get_all_appliances()
{
return this->controller.get_all_appliances();
}
void Service::add_refrigerator(const std::string& id, const double weight, const std::string& electricityUsageClass, const bool hasFreezer)
{
shared_ptr<Appliance> refrigerator = make_shared<Refrigerator>(id, weight, electricityUsageClass, hasFreezer);
this->controller.add_appliance(refrigerator);
}
void Service::add_dish_washer(const std::string& id, const double weight, const double washingCycleLength, const double consumedElectricityForOneHour)
{
shared_ptr<Appliance> dishWasher = make_shared<DishWasher>(id, weight, washingCycleLength, consumedElectricityForOneHour);
this->controller.add_appliance(dishWasher);
}
|
d83adaacd0099e905dfd1ced5c16d15aa05cc107 | ed1b62c22616764276f79b39ab549c75d23131ff | /HW_8.cpp | 4b52feaeefa919907911d877624a9c3934fb9599 | [] | no_license | Kidami13/HW_8 | f4f6537d13d5cb3571ad277c4a9349ecee2a310f | ab006280cd2e2264a932fcabdd134dcb5adfb1ff | refs/heads/master | 2023-01-06T14:30:45.256533 | 2020-11-07T13:36:56 | 2020-11-07T13:36:56 | 310,852,219 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 701 | cpp | HW_8.cpp |
#include <iostream>
using namespace std;
int main()
{
int ulyamass[7][7];
int ulyaMaxVal = 0;
int range = 100;
int ulyaMinVal = range;
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
ulyamass[i][j] = rand() % range;
}
}
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
if (ulyamass[i][j] > ulyaMaxVal) {
ulyaMaxVal = ulyamass[i][j];
}
if (ulyamass[i][j] < ulyaMinVal) {
ulyaMinVal = ulyamass[i][j];
}
}
}
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
cout << ulyamass[i][j] << " ";
}
cout << endl;
}
cout << ulyaMaxVal << " Max Value" << endl;
cout << ulyaMinVal << " Min Value" << endl;
}
|
aedbfe5ae96836e51f553ce25fa50427f6d9404f | 564c6c462a972600bb4875618f320f6010e0fb9e | /Zelda/Triforce.cpp | 9a20f128bb4b811303fac386b1cb25beb44cfcbc | [] | no_license | aekruijssen/LegendOfZelda-EagleDungeon | 554f6c739649b3bc5b34974e2f79e65c731650a6 | 6f2140ce5063fd1d4dbd186c642f042ce1ab11ac | refs/heads/master | 2021-10-19T14:45:23.274134 | 2019-02-21T21:26:26 | 2019-02-21T21:26:26 | 171,751,735 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 905 | cpp | Triforce.cpp | #include "CollisionComponent.h"
#include "Collectible.h"
#include "Player.h"
#include "SDL/SDL_mixer.h"
#include "Triforce.h"
#include "AnimatedSprite.h"
#include "Game.h"
Triforce::Triforce(Game* game)
: Actor(game) {
mGame = game;
// Adds itself to the game via AddActor(remember Actor has an mGame member variable)
//mGame->AddActor(this);
as = new AnimatedSprite(this, 150);
std::vector<SDL_Texture*> triforce{
mGame->GetTexture("Assets/Triforce0.png"),
mGame->GetTexture("Assets/Triforce1.png")
};
as->AddAnimation("triforce", triforce);
as->SetAnimation("triforce");
cc = new CollisionComponent(this);
cc->SetSize(20.0f, 20.0f);
c = new Collectible(this);
c->SetOnCollect([this] {
Mix_HaltChannel(mGame->mChannel);
Mix_PlayChannel(-1, mGame->GetSound("Assets/Sounds/triforce.ogg"), 0);
SetState(ActorState::Destroy);
mGame->mPlayer->SetState(ActorState::Paused);
});
}
|
8c379cc767fd25fc6e07a7784d28ae563bfc2bfc | 15fca27f60ab7fd42fe21511da4f18f2dae51bc7 | /MatlabWrapper/ks/MEXksint.cpp | ec305b7c23b55ca52316832f1ddfd9d916a6d384 | [] | no_license | dingxiong/research | 1bae45c54a0804c0a3fd4daccd4e8865b9ebebec | b7e82bec1cf7b23cfa840f3cb305a2682164d2f3 | refs/heads/master | 2021-03-13T01:50:57.594455 | 2017-08-30T06:42:46 | 2017-08-30T06:42:46 | 38,164,867 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,498 | cpp | MEXksint.cpp | /* compile command:
* mex CXXFLAGS='-std=c++0x -fPIC -O3' MEXksint.cpp ksint.cc ksintM1.cc
* -I../../include -I/usr/include/eigen3
* */
#include "ksintM1.hpp"
#include "mex.h"
#include "matrix.h"
#include <cmath>
#include <cstring>
#include <Eigen/Dense>
using Eigen::ArrayXXd;
using Eigen::ArrayXd;
using Eigen::Map;
const int N = 32;
/* ks full state space integrator without Jacobian */
static ArrayXXd ksf(double *a0, double d, double h, int nstp, int np){
KS ks(N, h, d);
Map<ArrayXd> v0(a0, N-2);
//ArrayXd v0(N-2); for(int i = 0 ; i < N-2; i++) v0(i) = a0[i];
ArrayXXd aa = ks.intg(v0, nstp, np);
return aa;
}
/* ks full state space integrator with Jacobian */
static std::pair<ArrayXXd, ArrayXXd>
ksfj(double *a0, double d, double h, int nstp, int np, int nqr){
KS ks(N, h, d);
Map<ArrayXd> v0(a0, N-2);
return ks.intgj(v0, nstp, np, nqr);
}
static std::tuple<ArrayXXd, VectorXd, VectorXd>
ksfDP(double *a0, double d, double h, int nstp, int np){
KS ks(N, h, d);
Map<ArrayXd> v0(a0, N-2);
return ks.intgDP(v0, nstp, np);
}
static std::pair<ArrayXXd, ArrayXd>
ksfM1(double *a0, double d, double h, int nstp, int np){
KSM1 ks(N, h, d);
Map<ArrayXd> v0(a0, N-2);
//ArrayXd v0(N-2); for(int i = 0 ; i < N-2; i++) v0(i) = a0[i];
return ks.intg(v0, nstp, np);
}
static std::pair<ArrayXXd, ArrayXd>
ksf2M1(double *a0, double d, double h, double T, int np){
KSM1 ks(N, h, d);
Map<ArrayXd> v0(a0, N-2);
//ArrayXd v0(N-2); for(int i = 0 ; i < N-2; i++) v0(i) = a0[i];
return ks.intg2(v0, T, np);
}
void
mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){
double *a0 = mxGetPr(prhs[0]);
double d = mxGetScalar(prhs[1]);
double h = mxGetScalar(prhs[2]);
int nstp = mxGetScalar(prhs[3]);
int np = mxGetScalar(prhs[4]);
int nqr = mxGetScalar(prhs[5]);
mwSize isM1 = mxGetScalar(prhs[6]); /* isM1 =1: integration on the 1st
mode slice. */
mwSize isT = mxGetScalar(prhs[7]); /* isT = 1: integration time on full
state space. */
double T = mxGetScalar(prhs[8]);
mwSize isDP = mxGetScalar(prhs[9]); /* isDp = 1: integrate D and P too */
mwSize Jacob = mxGetScalar(prhs[10]); /* Jacob = 1: integrate with Jacobian */
if(isM1 == 0){
if(isDP == 0){
if(Jacob == 0){
plhs[0] = mxCreateDoubleMatrix(N-2, nstp/np + 1, mxREAL);
//Map<ArrayXXd> aa(mxGetPr(plhs[0]), N-2, nstp/np + 1);
//aa = ksf(a0, d, h, nstp, np);
ArrayXXd aa = ksf(a0, d, h, nstp, np);
memcpy(mxGetPr(plhs[0]), &aa(0,0), (nstp/np+1)*(N-2)*sizeof(double));
}
else{ // integration with Jacobian
plhs[0] = mxCreateDoubleMatrix(N-2, nstp/np + 1, mxREAL);
plhs[1] = mxCreateDoubleMatrix((N-2)*(N-2), nstp/np, mxREAL);
std::pair<ArrayXXd, ArrayXXd> aada = ksfj(a0, d, h, nstp, np, nqr);
memcpy(mxGetPr(plhs[0]), &(aada.first(0, 0)), (nstp/np+1)*(N-2)*sizeof(double));
memcpy(mxGetPr(plhs[1]), &(aada.second(0, 0)), (nstp/np)*(N-2)*(N-2)*sizeof(double));
}
}
else{ /* dispation integration */
plhs[0] = mxCreateDoubleMatrix(N-2, nstp/np + 1, mxREAL);
plhs[1] = mxCreateDoubleMatrix(nstp/np+1, 1, mxREAL);
plhs[2] = mxCreateDoubleMatrix(nstp/np+1, 1, mxREAL);
std::tuple<ArrayXXd, VectorXd, VectorXd> tmp = ksfDP(a0, d, h, nstp, np);
memcpy(mxGetPr(plhs[0]), &(std::get<0>(tmp)(0,0)), (nstp/np+1)*(N-2)*sizeof(double));
memcpy(mxGetPr(plhs[1]), &(std::get<1>(tmp)(0)), (nstp/np+1)*sizeof(double));
memcpy(mxGetPr(plhs[2]), &(std::get<2>(tmp)(0)), (nstp/np+1)*sizeof(double));
}
}
else{
if(isT == 0){
plhs[0] = mxCreateDoubleMatrix( nstp/np + 1 , 1, mxREAL);
plhs[1] = mxCreateDoubleMatrix(N-2, nstp/np + 1, mxREAL);
std::pair<ArrayXXd, ArrayXd> at = ksfM1(a0, d, h, nstp, np);
memcpy(mxGetPr(plhs[0]), &(std::get<1>(at)(0,0)), (nstp/np+1)*sizeof(double));
memcpy(mxGetPr(plhs[1]), &(std::get<0>(at)(0)), (nstp/np+1)*(N-2)*sizeof(double));
//Map<ArrayXXd> (at.aa)(mxGetPr(plhs[1]), N-2, nstp/np+1);
//Map<ArrayXd> (at.tt)(mxGetPr(plhs[0]), nstp/np+1);
}
else{
std::pair<ArrayXXd, ArrayXd> at = ksf2M1(a0, d, h, T, np);
int m = (std::get<0>(at)).cols();
plhs[0] = mxCreateDoubleMatrix( m , 1, mxREAL);
plhs[1] = mxCreateDoubleMatrix(N-2, m, mxREAL);
memcpy(mxGetPr(plhs[0]), &(std::get<1>(at)(0,0)), m*sizeof(double));
memcpy(mxGetPr(plhs[1]), &(std::get<0>(at)(0)), m*(N-2)*sizeof(double));
}
}
}
|
287e557c2f3eb2a851a712716da08269e42db835 | aade1e73011f72554e3bd7f13b6934386daf5313 | /Contest/Europe/NWERC/2019/B.cpp | a3d036033826854845fdfec502f95e8511c19660 | [] | no_license | edisonhello/waynedisonitau123 | 3a57bc595cb6a17fc37154ed0ec246b145ab8b32 | 48658467ae94e60ef36cab51a36d784c4144b565 | refs/heads/master | 2022-09-21T04:24:11.154204 | 2022-09-18T15:23:47 | 2022-09-18T15:23:47 | 101,478,520 | 34 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 2,328 | cpp | B.cpp | #include <bits/stdc++.h>
using namespace std;
int p[500005];
int l[500005], r[500005];
int plug[500005];
int far[500005];
int dp[500005];
void dfs1(int now) {
if (l[now]) dfs1(l[now]);
if (r[now]) dfs1(r[now]);
if (l[now] || r[now]) {
far[now] = max(far[l[now]], far[r[now]]) + 1;
if (far[now] == 1 && l[now] && r[now]) dp[now] = 1;
else if (far[now] > 1) {
if (far[l[now]] > far[r[now]]) dp[now] = dp[l[now]];
else if (far[l[now]] < far[r[now]]) dp[now] = dp[r[now]];
else dp[now] = 1;
} else dp[now] = 0;
}
}
void dfs2(int now, int rest) {
// cerr << "dfs2 " << now << " rest " << rest << endl;
if (!l[now] && !r[now]) {
plug[now] = 1;
cerr << "plug " << now << endl;
return;
}
if (!l[now]) dfs2(r[now], rest);
else if (!r[now]) dfs2(l[now], rest);
else {
if (rest) {
if (far[l[now]] == far[r[now]]) dfs2(r[now], 0);
else if (far[l[now]] < far[r[now]]) {
if (dp[r[now]]) dfs2(r[now], 1);
else dfs2(l[now], 1);
} else {
if (dp[r[now]]) dfs2(r[now], 1);
else dfs2(l[now], 1);
}
} else {
if (far[l[now]] == far[r[now]]) dfs2(r[now], 0);
else if (far[l[now]] < far[r[now]]) {
dfs2(r[now], 0);
} else {
if (dp[r[now]]) dfs2(r[now], 1);
else dfs2(l[now], 0);
}
}
}
if (plug[l[now]]) l[now] = 0;
if (plug[r[now]]) r[now] = 0;
if (l[now] || r[now]) {
far[now] = max(far[l[now]], far[r[now]]) + 1;
} else {
far[now] = 0;
}
if (far[now] == 1 && l[now] && r[now]) dp[now] = 1;
else if (far[now] > 1) {
if (far[l[now]] > far[r[now]]) dp[now] = dp[l[now]];
else if (far[l[now]] < far[r[now]]) dp[now] = dp[r[now]];
else dp[now] = 1;
} else dp[now] = 0;
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(0);
int n, k; cin >> n >> k;
int root = 0;
for (int i = 1; i <= n; ++i) {
cin >> p[i];
if (p[i] == -1) root = i;
else {
if (p[i] < i) r[p[i]] = i;
else l[p[i]] = i;
}
}
dfs1(root);
for (int i = 0; i < n - k; ++i) {
cerr << "plug" << endl;
for (int i = 1; i <= n; ++i) {
cerr << "i = " << i << ", dp " << dp[i] << ' ' << "far = " << far[i] << endl;
}
dfs2(root, 0);
}
for (int i = 1; i <= n; ++i) cout << (!plug[i]);
cout << endl;
}
|
18a5a40f8c37b84235437745587ca6e52d5a8b9f | d74c56a43350f078e9d538d6deb367e7b5b809a5 | /Solar/src/entities/square.h | da4fe738e2757f6057a4974134640c1e6ccbae14 | [
"MIT"
] | permissive | ThaiDuongVu/PongSolar | 6b7bb03f582d105a574d49ed291b8432c2872023 | 4ce5be34a2f79512384651d7e2d12dac0517198c | refs/heads/main | 2023-04-15T20:00:24.994587 | 2021-04-11T22:02:11 | 2021-04-11T22:02:11 | 356,989,135 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,784 | h | square.h | #pragma once
#ifndef SOLAR_Square_H_
#define SOLAR_Square_H_
#include "../core.h"
#include "../app.h"
#include "game_object.h"
#include "../types/color.h"
#include "../types/color32.h"
#include "../types/vector2.h"
#include "../rendering/shader.h"
namespace Solar
{
class SOLAR_API Square : public GameObject
{
public:
/// <summary>
/// Constructor.
/// </summary>
/// <param name="color">Initial color</param>
Square(Transform transform = Transform::Default(), Color color = Color::White(), bool is_visible = true, bool is_parallax = false, bool is_bounded = false);
/// <summary>
/// Destructor.
/// </summary>
~Square();
/// <summary>
/// Square color.
/// </summary>
Color color = Color::White();
/// <summary>
/// Whether object is confined within window bound.
/// </summary>
bool is_bounded = false;
/// <summary>
/// Square shader.
/// </summary>
Shader shader = Shader("./resources/default_vertex_shader.shader", "./resources/default_fragment_shader.shader");
/// <summary>
/// Render square.
/// </summary>
/// <param name="app">Application to render on</param>
/// <param name="draw_mode">Which mode to draw</param>
void Draw(App app, DrawMode draw_mode = DrawMode::Fill);
private:
/// <summary>
/// Vertex buffer objects.
/// </summary>
unsigned int vbo = NULL;
/// <summary>
/// Vertex array object.
/// </summary>
unsigned int vao = NULL;
/// <summary>
/// Vertices needed to draw a Square.
/// </summary>
Vector2 vertex[4] = { NULL, NULL, NULL, NULL };
float vertices[24] = {
// Position data // Color data
0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f
};
/// <summary>
/// Whether square has been initialized.
/// </summary>
bool done_init = false;
/// <summary>
/// Initialize square.
/// </summary>
/// <param name="app">Application to init on</param>
void Init(App app);
/// <summary>
/// Update square vertices.
/// </summary>
/// <param name="app">Application to update on</param>
void Update(App app);
/// <summary>
/// Limit object within the game window.
/// </summary>
/// <param name="app">Application to limit to</param>
/// <param name="width_scale">Width scale of the window</param>
/// <param name="height_scale">Height scale of the window</param>
void CalculateBound(App app);
/// <summary>
/// Calculate vertex coordinates based on current rotation.
/// </summary>
/// <param name="app">Application to calculate on</param>
/// <param name="vertex">Vertex to calculate</param>
Vector2 CalculateRotation(App app, Vector2 vertex);
};
} // namespace Solar
#endif // !SOLAR_Square_H_
|
7bf1b2a68f1e4b039f3ecec7fe20ba9f87db05e8 | 2a8a90b78f18e87c0049acb094482867756cbfff | /src/adiar/internal/assert.h | 5f4f628ca7981a5e0df0debc1bd3b6cfed47c022 | [
"MIT",
"LGPL-3.0-only"
] | permissive | SSoelvsten/adiar | 1823a33b4029f5e31bb9e907073fc362d2993d2e | 2f95ca23e2bcc56e53c93fc331bde8f3651bb2e9 | refs/heads/main | 2023-08-31T03:28:15.201698 | 2023-08-29T14:55:44 | 2023-08-29T15:04:39 | 248,442,086 | 16 | 13 | MIT | 2023-08-11T17:42:02 | 2020-03-19T07:51:58 | C++ | UTF-8 | C++ | false | false | 2,816 | h | assert.h | #ifndef ADIAR_INTERNAL_ASSERT_H
#define ADIAR_INTERNAL_ASSERT_H
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
namespace adiar
{
// LCOV_EXCL_START
struct assert_error
{
private:
std::string _what;
public:
////////////////////////////////////////////////////////////////////////////
assert_error(const std::string &what)
: _what(what)
{ }
assert_error(const std::string &file, const int line)
{
std::stringstream s;
s << file << "::" << line;
_what = s.str();
}
////////////////////////////////////////////////////////////////////////////
assert_error(const std::string &file, const int line, const std::string &what)
{
std::stringstream s;
s << file << "::" << line << ": " << what;
_what = s.str();
}
public:
////////////////////////////////////////////////////////////////////////////
/// \brief Explanatory string
////////////////////////////////////////////////////////////////////////////
char* what()
{ return _what.data(); }
};
#ifdef __GNUC__ // GCC 4.8+, Clang, Intel and other compilers compatible with GCC (-std=c++0x or above)
// Macros based on:
// - Assert with file information and messages: https://stackoverflow.com/a/37264642
// - Variadic macro arguments: https://stackoverflow.com/a/11763277
#define adiar_assert_overload(_1,_2,NAME,...) NAME
#define adiar_assert(...) adiar_assert_overload(__VA_ARGS__, adiar_assert2, adiar_assert1)(__VA_ARGS__)
#ifndef NDEBUG
# define adiar_assert1(Expr) __adiar_assert(#Expr, Expr, __FILE__, __LINE__)
# define adiar_assert2(Expr, Msg) __adiar_assert(#Expr, Expr, __FILE__, __LINE__, Msg)
inline
void
__adiar_assert(const char* expr_str, bool expr, const char* file, int line)
{
if (!expr) {
std::cerr << "Assert failed!\n"
<< "Expected:\t" << expr_str << "\n"
<< "Source:\t\t" << file << ", line " << line << std::endl;
throw assert_error(file, line);
}
}
inline
void
__adiar_assert(const char* expr_str, bool expr, const char* file, int line, const char* msg)
{
if (!expr) {
std::cerr << "Assert failed:\t" << msg << "\n"
<< "Expected:\t" << expr_str << "\n"
<< "Source:\t\t" << file << ", line " << line << std::endl;
throw assert_error(file, line, msg);
}
}
#else
# define adiar_assert1(Expr) ;
# define adiar_assert2(Expr, Msg) ;
#endif
#else // MSVC and ??? compilers
inline void adiar_assert([[maybe_unused]] const bool expr,
[[maybe_unused]] const std::string &what = "")
{
#ifndef NDEBUG
if (!expr) { throw assert_error(what); }
#endif
}
#endif
// LCOV_EXCL_STOP
}
#endif // ADIAR_INTERNAL_ASSERT_H
|
912a35c32ea84e7db0d039a2a88dbc4a061adbb3 | 3f98afb462090af7317aaa77a710815fdf074900 | /VisualIB/vibexception.h | e5a0a95d15b86b8313060a62d07714b38492d523 | [
"MIT"
] | permissive | haleyjd/vib | 468be7b4fce0d4ac805461c8a972bd9e59f70010 | f8535608e5c984b1a96bb9ad42d684039fd2b30c | refs/heads/master | 2020-04-07T13:13:37.758555 | 2018-11-20T13:58:12 | 2018-11-20T13:58:12 | 158,398,211 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,488 | h | vibexception.h | /** @file vibexception.h
*
* VisualIB - InterBase wrapper for use in Visual Studio.
* Internal Exception Utilities
* @author James Haley
*
* @warning Internal only. Do not include in user programs!
*/
#ifndef VIBEXCEPTION_H__
#define VIBEXCEPTION_H__
__declspec(dllexport) void __cdecl VIBError_Report(const char *message, int iberror, int sqlcode);
// For just catching an error
#define CATCH_EIBERROR \
catch(EIBError &error) \
{ \
VIBError_Report(error.Message.c_str(), \
error.IBErrorCode, \
error.SQLCode); \
} \
catch(...) \
{ \
VIBError_Report("Internal", 0, 0); \
}
// Catch error and return VIBFALSE
#define CATCH_EIBERROR_RF \
catch(EIBError &error) \
{ \
VIBError_Report(error.Message.c_str(), \
error.IBErrorCode, \
error.SQLCode); \
return VIBFALSE; \
} \
catch(...) \
{ \
VIBError_Report("Internal", 0, 0); \
return VIBFALSE; \
}
#endif
// EOF
|
0102eb4ac8ba8bfd31f96420293dcdc66675db91 | f479a96e9902a825fb3106f5f75c0ebd2b99d39a | /ChessTest/board.cpp | 82d4da443dc3b8fbbdac30e87e3f64f28676ba28 | [] | no_license | Omega65536/ChessTest | 9b3a7ee4c004b2218ba628757ee7c59e3e1f34db | 87d39143d7a620a8ad1bae461d9b10c390b60b2a | refs/heads/master | 2023-03-04T06:07:20.795775 | 2021-02-16T11:08:33 | 2021-02-16T11:08:33 | 338,343,101 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 578 | cpp | board.cpp | #include <vector>
#include "move.h"
#include "board.h"
void Board::setup() {
addWhitePiece(Piece(A1, Rook));
addWhitePiece(Piece(B1, Knight));
addWhitePiece(Piece(C1, Bishop));
addWhitePiece(Piece(D1, Queen));
addWhitePiece(Piece(E1, King));
addWhitePiece(Piece(F1, Bishop));
addWhitePiece(Piece(G1, Knight));
addWhitePiece(Piece(H1, Rook));
}
void Board::addWhitePiece(Piece piece) {
whitePieces.push_back(piece);
whitePieceBB |= 1LL << piece.square;
}
void Board::addBlackPiece(Piece piece) {
blackPieces.push_back(piece);
blackPieceBB |= 1LL << piece.square;
} |
62cef0ff7eb305755a0ace567835e42945ff69ae | fa91c297b51e3049c0245cd3fe8333f8b801be0a | /J00/ex01/contact.class.cpp | dcf9be2eef7cdacf099a3b9855e334e57bd3f488 | [] | no_license | Qwesaqwes/Piscine-CPP-42 | 4d6fe766b0a03815834a8afa8f176b99e1b75c7b | 7a172af14b48aeaefeaca1065b6a9481940cace0 | refs/heads/master | 2020-03-06T17:15:15.939641 | 2018-04-09T11:16:52 | 2018-04-09T11:16:52 | 126,986,743 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,915 | cpp | contact.class.cpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* contact.class.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jichen-m <jichen-m@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/03/26 17:40:01 by jichen-m #+# #+# */
/* Updated: 2018/03/27 14:53:11 by jichen-m ### ########.fr */
/* */
/* ************************************************************************** */
#include "contact.class.hpp"
Contact::Contact(void)
{
Contact::_nbInst += 1;
return;
}
Contact::~Contact(void)
{
Contact::_nbInst -= 1;
return;
}
void Contact::addd_contact(std::string first_name,
std::string last_name,
std::string nickname,
std::string login,
std::string postal_adress,
std::string email_adress,
std::string phone_number,
std::string birthday_date,
std::string favorite_meal,
std::string underwear_color,
std::string darkest_secret)
{
this->first_name1 = first_name;
this->last_name1 = last_name;
this->nickname1 = nickname;
this->login1 = login;
this->postal_adress1 = postal_adress;
this->email_adress1 = email_adress;
this->phone_number1 = phone_number;
this->birthday_date1 = birthday_date;
this->favorite_meal1 = favorite_meal;
this->underwear_color1 = underwear_color;
this->darkest_secret1 = darkest_secret;
}
int Contact::getNbInst(void)
{
return (Contact::_nbInst);
}
int Contact::_nbInst = 0;
|
8309c2c842cb6114a749426a60ba9b9310f0c902 | 2407762257eaf2c62528be250533e356c2b2b04b | /2_course/2_semester/Mutex/Tree_mutex/main.cpp | e9509cd0bb6a3fe92002dae4f27f8dcdcfd92bc1 | [] | no_license | makci97/Homework | 0fc698045f7c715c45f682fdfb36e06796db8d26 | 4507ebf26efaa903211d550eb314a6ff36c8bd69 | refs/heads/master | 2021-01-09T09:34:19.008037 | 2016-06-27T13:33:14 | 2016-06-27T13:33:14 | 62,057,623 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,079 | cpp | main.cpp | #include <array>
#include <atomic>
#include <iostream>
#include <math.h>
#include <thread>
#include <vector>
#include "tree_mutex.h"
/*
class peterson_mutex
{
public:
peterson_mutex();
void lock(int t);
void unlock(int t);
private:
std::array<std::atomic<bool>, 2> _want;
std::atomic<int> _victim;
};
class tree_mutex
{
public:
tree_mutex(int num_threads);
void lock(int thread_index, bool _index_is_true = false);
void unlock(int thread_index, bool _index_is_true = false);
private:
int _hight_vec;
std::vector<peterson_mutex> _mutex;
};
//-----------------------------------------------------------------------
//peterson_mutex
//-----------------------------------------------------------------------
peterson_mutex::peterson_mutex()
{
_want[0].store(false);
_want[1].store(false);
_victim.store(0);
}
void peterson_mutex::lock(int t)
{
_want[t].store(true);
_victim.store(t);
while (_want[1 - t].load() && _victim.load() == t)
{
// wait
std::this_thread::yield();
}
}
void peterson_mutex::unlock(int t)
{
_want[t].store(false);
}
//-----------------------------------------------------------------------
//tree_mutex
//-----------------------------------------------------------------------
tree_mutex::tree_mutex(int num_threads): _hight_vec(ceil(log(num_threads)/log(2)) ), _mutex(pow(2, _hight_vec) - 1) {}
void tree_mutex::lock(int thread_index, bool _index_is_true)
{
//when user call this function
if(!_index_is_true)
{
thread_index += pow(2, _hight_vec) - 1;
}
//now thread_index is index of mutex/thread in tree
//go up in tree
int index = floor((thread_index - 1)/2);
//if thread_index is right child of index than 1
//else 0
bool who_want_lock = thread_index == 2*(index + 1);
//call lock for mutex
_mutex[index].lock(who_want_lock);
//lock next mutex
if(index > 0)
{
this->lock(index, true);
}
}
void tree_mutex::unlock(int thread_index, bool _index_is_true)
{
//when user call this function
if(!_index_is_true)
{
thread_index += pow(2, _hight_vec) - 1;
}
//now thread_index is index of mutex/thread in tree
//go up in tree
int index = floor((thread_index - 1)/2);
//if thread_index is right child of index than 1
//else 0
bool who_want_unlock = thread_index == 2*(index + 1);
//call lock for mutex
_mutex[index].unlock(who_want_unlock);
//lock next mutex
if(index > 0)
{
this->unlock(index, true);
}
}
*/
void thread_func(int number_thread, ticket_spinlock &mutex, int &x)
{
for(int i = 0; i < 1000000; ++i)
{
/*
mutex.lock(number_thread);
++x;
mutex.unlock(number_thread);
*/
mutex.lock();
++x;
mutex.unlock();
}
}
int main()
{
/*
for(int i = 0; i < 20; ++i)
std::cout << i << ' ' << ((ceil(log(i)/log(2)) == 0)? 1: (ceil(log(i)/log(2)) )) << ' ' << pow(2,(ceil(log(i)/log(2)) == 0)? 1: (ceil(log(i)/log(2)) )) - 1 << std::endl;
*/
//tree_mutex mutex(10);
ticket_spinlock mutex;
int x = 0;
std::thread t1(thread_func, 0, std::ref(mutex), std::ref(x));
std::thread t2(thread_func, 1, std::ref(mutex), std::ref(x));
std::thread t3(thread_func, 2, std::ref(mutex), std::ref(x));
std::thread t4(thread_func, 3, std::ref(mutex), std::ref(x));
std::thread t5(thread_func, 4, std::ref(mutex), std::ref(x));
/*
std::thread t6(thread_func, 5, std::ref(mutex), std::ref(x));
std::thread t7(thread_func, 6, std::ref(mutex), std::ref(x));
std::thread t8(thread_func, 7, std::ref(mutex), std::ref(x));
std::thread t9(thread_func, 8, std::ref(mutex), std::ref(x));
std::thread t10(thread_func, 9, std::ref(mutex), std::ref(x));
*/
t1.join();
t2.join();
t3.join();
t4.join();
t5.join();
/*
t6.join();
t7.join();
t8.join();
t9.join();
t10.join();
*/
std::cout << x << std::endl;
return 0;
}
|
b5f90629300cca646795e4ecaaa01e26b9e06abb | 14ee8b8c0669ced2372618405c11e278b8e601d3 | /TextFile/Source.cpp | 49239dfb1f597f97396589e57370c0a6af7f0451 | [] | no_license | miltone92/CPlusPlus-Read-Write-Txt | 79dda7fd9f414286d0237128efcb68b9e44ba7e3 | 4ab259deed2c9b4ffee69d83314fec98325a02dc | refs/heads/master | 2020-09-26T23:25:57.253792 | 2019-12-06T18:24:27 | 2019-12-06T18:24:27 | 226,365,415 | 1 | 0 | null | null | null | null | ISO-8859-2 | C++ | false | false | 3,701 | cpp | Source.cpp | #include <iostream>
using namespace std;
#include <fstream>
#include <string>
void menu();
void write();
void readLines();
void readData();
void modify();
ofstream myFile; //Text file declaration
void main() {
menu();
}
void menu() {
int option = -1;
while (option != 0) {
cout << "\n";
cout << "Menu" << "\n";
cout << "1. Write to file" << "\n";
cout << "2. Read file" << "\n";
cout << "3. Modify file" << "\n";
cout << "4. " << "\n";
cout << "5. " << "\n";
cout << "6. " << "\n";
cout << "\n";
cin >> option;
cin.ignore();
switch (option)
{
case 1:
write();
break;
case 2:
readData();
break;
case 3:
modify();
break;
case 4:
break;
case 5:
break;
case 6:
break;
case 7:
break;
default:
cout << "Opción invalida";
break;
}
}
}
void write() {
cout << "Please student id \n";
string id;
getline(cin, id);
cout << "Please student name \n";
string name;
getline(cin, name);
string line;
line = id + " " + name;
myFile.open("myFile.txt", fstream::app); //Open txt file in append mode
// fstream::app allows to write to the file without overwritting it
//Wirte to file
if (myFile.is_open()) {
myFile << line << "\n";
}
//Close file
myFile.close();
cout << "Saved to file! \n";
}
//Method allows to read every line form text file separately
void readLines() {
ifstream myTxtFile("myFile.txt");// Declaration to read from existing file
cout << "Text file data: \n";
string line;
if (myTxtFile.is_open()) {
while (getline(myTxtFile, line)) {
cout << line << "\n";
}
}
else {
cout << "File not open \n";
}
}
//Method allows to read specific data from file
void readData() {
//**********Text file data*******
int id;
string name;
//********************************
ifstream myTxtFile("myFile.txt");// Declaration to read from existing file
cout << "Text file data: \n";
if (myTxtFile.is_open()) {
while (myTxtFile >> id >> name) {
//The first word will be saved in id variable, then name variable
cout << "Id: " << id << " Name: " << name << "\n";
}
}
else {
cout << "File not open \n";
}
}
//Method allows to modify specific data from file
void modify() {
cout << "Enter the id of the desired student \n";
int desiredId;
cin >> desiredId;
cin.ignore();
cout << "Enter the new name of the desired student \n";
string newName;
getline(cin, newName);
//**********Text file data*******
int id;
string name;
string sid;
//********************************
ifstream myTxtFile("myFile.txt");// Declaration to read from existing file: used to get all lines
string line;
string allData;
if (myTxtFile.is_open()) {
while (getline(myTxtFile, line)) {
//get id
string word;
for (auto x : line)
{
if (x == ' ')
{
id = stoi(word);
word = "";
break;
}
else
{
word = word + x;
}
}
//Check if line is not empry
if (line != "") {
//if id matches line should be modified
if (id == desiredId) {
cout << "Old data: " << "Id: " << id << " Name: " << name << "\n";
cout << "Modified data: " << "Id: " << id << " Name: " << newName << "\n";
string sid = to_string(id);
allData += sid + " " + newName + "\n";;
}
else {
allData += line + "\n";
}
}
}
}
else {
cout << "File not open \n";
}
//re write file with updated data
myFile.open("myFile.txt"); //Open txt file without append mode
//Wirte to file
if (myFile.is_open()) {
cout << allData << "\n";
myFile << allData << "\n";
cout << "Data was modified! \n";
}
else {
cout << "File is not open \n";
}
//Close file
myFile.close();
}
|
467a230dd330707dab6a3ab0a373187344684644 | a879bcb6a5dbd40a1c4815dc00291fca458dcc01 | /variadic_bases.cpp | d33e036c03dff1458f7af9232846030852e9bc83 | [] | no_license | hgedek/cpp-samples | 38a5b44c43589bf441f4205bff2cb8a1e9f2c136 | 2f69954de8627fe2065a9958f997eee56d48f135 | refs/heads/main | 2023-04-20T06:24:36.931213 | 2021-05-01T14:41:20 | 2021-05-01T14:41:20 | 329,326,996 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 367 | cpp | variadic_bases.cpp | #include <iostream>
template <class ...Ts>
struct S: Ts...{};
// redirecting params as base types
// forwarding template types from params
template <class ...Ts>
S(Ts...)->S<Ts...>;
struct A{};
struct B{};
int main() {
// {} initializer a need here...you cant use normal !
S{[]{}, [](int){}, [](int, float){}};
S<A,B>{};
S{A{},B{}};
S<A>();
}
|
3cb432bb22b521b2812504a4776656c022edf162 | 46b41563d38101185194f1c79575490513c54d43 | /lane.cpp | 0664e073160f3b1e583182e2c60f700ed0b53c24 | [] | no_license | zouwen198317/lane | bfc13b894678d38a98bdc9d9d66df785f6a0c2c1 | a35fa08f346df89d110bd6f9463fb15c161cad84 | refs/heads/master | 2020-12-25T12:46:47.507872 | 2014-12-21T06:14:10 | 2014-12-21T06:14:10 | 60,313,796 | 1 | 0 | null | 2016-06-03T02:56:55 | 2016-06-03T02:56:54 | null | UTF-8 | C++ | false | false | 15,394 | cpp | lane.cpp | /*************************************************************************
> File Name: lane.cpp
> Author: onerhao
> Mail: haodu@hustunique.com
> Created Time: Thu 07 Mar 2013 02:44:22 PM CST
************************************************************************/
#include <iostream>
#include <algorithm>
#include <cv.h>
#include "utils.h"
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/core/core_c.h>
#include <stdlib.h>
#include <stdio.h>
class Vehicle
{
CvPoint bmin,bmax;
int symmetryX;
bool valid;
unsigned int lastUpdata;
};
enum
{
LINE_REJECT_DEGREES=60, //in degrees
CANNY_MIN_THRESHOLD=1,//edge detector mininum hysteresis threshold
CANNY_MAX_THRESHOLD=100,//edge detector maximum hysteresis threshold
HOUGH_THRESHOLD=30, //line approval vote threshold
HOUGH_MIN_LINE_LENGTH=50, //remove lines shorter than this threshold
HOUGH_MAX_LINE_GAP=100, //join lines
LINE_LENGTH_DIFF=10, //accepted diffenrence of length of lines,
LANE_DYNAMPARAMS=2,//lane state vector dimension
LANE_MEASUREPARAMS=2,//lane state vector dimension
LANE_CONTROLPARAMS=0,//lane state vector dimension
VEHICLE_DYNAMPARAMS=2,//vehicle state vector dimension
VEHICLE_MEASUREPARAMS=2,//vehicle measurement dimension
VEHICLE_CONTROLPARAMS=0,//vehicle control vector
MAX_LOST_FRAME=30//maximum number of lost frames
};
int nframe=0;
bool sort_line_length(Line l0,Line l1)
{
return l0.length < l1.length;
}
struct sort_line
{//near vertical line
bool operator()(Line l0,Line l1)
{
return (l0.length*l0.length/fabsf(l0.angle-CV_PI/2) > l1.length*l1.length/fabsf(l1.angle-CV_PI/2));
}
}sort_line_object;
cv::Mat frame,vmeandist,gray,blur,thrs,dil,ero,canny,dst;
int VMeanDist(cv::Mat src,cv::Mat &dist)
{
cv::Size srcSize=src.size();
int rows=srcSize.height,cols=srcSize.width;
cv::Mat row(1,cols,CV_8UC1);//store a row
dist=cv::Mat(1,rows,CV_8UC1);//the target distribution matrix
int i,j,mean;
//std::cout<<src.size()<<"size.height "<<srcSize.height<<std::endl;
for(i=0;i<rows;i++)
{//average row by row
row=src.row(i);
mean=0; //
for(j=0;j<row.cols;j++)
{
mean+=row.data[j];
}
mean/=row.cols;
//std::cout<<"\nmean= "<<mean<<std::endl;
dist.data[i]=mean;
}
/*for(i=0;i<dist.cols;i++)
{
std::cout<<i<<","<<(int)dist.data[i]<<";";
}*/
return 0;
}
int findHorizon(cv::Mat dist)
{
int key=dist.data[0],i,lsum;//lsum is the local sum.
for(i=1;i<dist.cols;i++)
{
if(dist.data[i]>key && i>1 && key<=10)
return i;
key=dist.data[i];
}
return i;
}
void filterLines(std::vector<Line> &lines,bool right)
{
std::vector<int> eraselist;
int i,a=-2*right+1;
float angle,anglediff;
if(!lines.size())
return;
for(i=0;i<(signed)lines.size();i++)
{
angle=lines[i].angle,anglediff=angle-CV_PI / 2;
//reject lines of wrong slope angle
if(anglediff*a<0||fabsf(anglediff)*180/CV_PI > LINE_REJECT_DEGREES)
{
lines.erase(lines.begin()+i);
i--;
//std::cout<<"near horizon"<<std::endl;
continue;
}
}
sort(lines.begin(),lines.end(),sort_line_object);
//std::cout<<"size: "<<lines.size()<<std::endl;
//sort the lines by degrees near vertical line
/* if(lines.size())
{
sort(lines.begin(),lines.end(),sort_line_object);
angle=lines[0].angle,lengc,th=lines[0].length;
for(i=1;i<lines.size();i++)
{
if(fabsf(angle-lines[i].angle) < LINE_ANGLE_DIFF
&& fabsf(length-lines[i].length) > LINE_LENGTH_DIFF)
{
length=lines[i].length;
angle=lines[i].angle;
}
}
*/
}
int processlines(std::vector<cv::Vec4i> lines,
cv::InputArray _edges,
cv::OutputArray _dst)
{
std::vector<Line>left,right;
cv::Mat dst=_dst.getMat();
unsigned int i;
for(i=0;i<lines.size();i++)
{
cv::Vec4i l=lines[i];
CvPoint p0=cvPoint(l[0],l[1]),p1=cvPoint(l[2],l[3]);
//assuming that the vanishing point is close to the image horizontal
//center,calculate line parameters in form:y = kx + b;
//decide line's side based on its midpoint position
int midx=(l[0]+l[2])/2;
if(midx<dst.cols/2)
{
left.push_back(Line(cvPoint(l[0],l[1]), cvPoint(l[2],l[3])));
}
else if(midx>dst.cols/2)
{
right.push_back(Line(cvPoint(l[0],l[1]), cvPoint(l[2],l[3])));
}
}
// for(int i=0;i<(int)left.size();i++)
// {
// cv::line(dst,left[i].p0,left[i].p1,CV_RGB(255,0,0),1);
// char str[50];
//memset(str,0,50);
// sprintf(str,"%dth line,%.3f",i,calLength(left[i].p0,left[i].p1));
// cv::putText(dst,str,left[i].p0,1,1,1,1);
// }
// for(int i=0;i<(int)right.size();i++)
// {
// char str[50];
//memset(str,0,50);
// sprintf(str,"%dth line,%.3f",i,right[i].angle);
// cv::putText(dst,str,right[i].p0,1,1,1,1);
// cv::line(dst,right[i].p0,right[i].p1,CV_RGB(0,255,0),1);
// if(i==right.size()-1)
// {
// //cv::line(dst,right[i].p0,right[i].p1,CV_RGB(23,21,10),5);
// }
// }
filterLines(left,false);
filterLines(right,true);
if(left.size() && right.size())
{
cv::line(dst,left[left.size()-1].p0,left[left.size()-1].p1,CV_RGB(255,21,10),5);
cv::line(dst,right[right.size()-1].p0,right[right.size()-1].p1,CV_RGB(23,255,10),5);
}
cv::line(dst,cvPoint(dst.cols/2,0),cvPoint(dst.cols/2,dst.rows),CV_RGB(0,0,0),1);
//draw selected lanes
int x1=dst.cols * 0.55f;
int x2=dst.cols;
// cv::line(frame,cvPoint(x1,laneR.k.get()*x1+laneR.b.get()),
// cvPoint(x2,laneR.k.get()*x2+laneR.b.get()),CV_RGB(255,0,255),3);
return 0;
}
int wait(int k,int delay)
{
if (k ==cv::waitKey(delay))
return 1;
return 0;
}
int detectLane(cv::Mat &frame,std::vector<cv::Vec4i>lines)
{
int element_shape=cv::MORPH_RECT,an=1;
int thrs1=0,thrs2=4000;
double rho=1,theta=CV_PI/180;
cv::Scalar color;
int y,i,j;
//cv::vector <cv::Vec2f> lines;
//cv::vector <cv::Vec4i> lines;
VMeanDist(frame,vmeandist);
//std::cout<<vmeandist.data<<std::endl;
y=findHorizon(vmeandist);
for(i=0;i<y;i++)
{
for(j=0;j<frame.cols;j++)
{
frame.data[ero.cols*i+j]=0;
}
}
cv::imshow("frameBeforeCanny",frame);
cv::Canny(frame,canny,CANNY_MIN_THRESHOLD,CANNY_MAX_THRESHOLD,3);
cv::imshow("canny",canny);
cv::HoughLinesP(canny,lines,rho,theta,
HOUGH_THRESHOLD,HOUGH_MIN_LINE_LENGTH,HOUGH_MAX_LINE_GAP);
//cv::HoughLines(canny,lines,rho,theta,HOUGH_THRESHOLD,3,8);
processlines(lines,canny,dst);
/*for(i=0;i<lines.size();i++)
{
cv::line(dst,cvPoint(lines[i][0],lines[i][1]),
cvPoint(lines[i][2],lines[i][3]),cv::Scalar(0,255,0),4,8);
}*/
//std::cout<<"\n"<<"y: "<<y<<std::endl;
cv::line(dst,cvPoint(0,y),cvPoint(750,y),cv::Scalar(0,0,0),1,8,0);
return 0;
}
int detectvehicle(cv::Mat &frame,std::vector<cv::Rect> &rects,
std::string cascade_name)
{//return the number of detected vehicles
cv::CascadeClassifier vehicle(cascade_name);
if(vehicle.empty())
{
std::cout<<"unable to load the classifier"<<std::endl;
return -1;
}
vehicle.detectMultiScale(frame,rects,1.1, 2,0,cv::Size(80,80));
cv::Rect p;
//for(int i=0;i<rects.size();i++)
/*for(int i=0;i<rects.size()&&i<1;i++)
{
p=rects[i];
cv::rectangle(frame,cvPoint(p.x,p.y),cvPoint(p.x+p.width,p.y+p.height),
cv::Scalar(0,255,0),1,8,0);
}*/
return rects.size();
}
int trackline(cv::Mat& frame,
std::vector<cv::Vec4i>& lines)
{
static cv::KalmanFilter linekf;
static cv::Mat x_k(LANE_DYNAMPARAMS,1,CV_32F);
static cv::Mat w_k(LANE_DYNAMPARAMS,1,CV_32F);
static cv::Mat z_k=cv::Mat::zeros(LANE_MEASUREPARAMS,1,CV_32F);
static cv::Mat y_k=cv::Mat(LANE_DYNAMPARAMS,1,CV_32F);
cv::Vec4i l;
float k,b;
int found=0;
if(lines.size()==0)
{//empty,then measure
linekf.transitionMatrix=*(cv::Mat_<float>(2,2)<<1,0,0,1);
setIdentity(linekf.measurementMatrix);
setIdentity(linekf.processNoiseCov,cv::Scalar::all(1e-5));
setIdentity(linekf.measurementNoiseCov,cv::Scalar::all(1e-1));
setIdentity(linekf.errorCovPost,cv::Scalar::all(1));
found=detectLane(frame,lines);//detect in the whole image scope
}
else
{//predict and measure
y_k=linekf.predict();//predict
int dk=3*sqrt(linekf.errorCovPre.at<float>(0,0));//error band
int db=3*sqrt(linekf.errorCovPre.at<float>(1,1));
int top=frame.rows*2/3,bottom=frame.rows;
Line l0(y_k.at<float>(0,0),y_k.at<float>(1,0)-db);
Line l1(y_k.at<float>(0,0),y_k.at<float>(1,0)+db);
CvPoint p0=cvPoint(l0.getx(bottom),bottom);
CvPoint p1=cvPoint(l1.getx(top),top);
cv::Rect roi(p0,p1);
cv::Mat roiimage=frame(roi);//detect in the roi
found=detectLane(roiimage,lines);
}
if(!found)
{
//lost++;
}
else
{
l=lines[0];
k=calSlope(cvPoint(l[0],l[1]),cvPoint(l[2],l[3]));
b=calIntercept(cvPoint(l[0],l[1]),cvPoint(l[2],l[3]));
z_k=*(cv::Mat_<int>(2,1)<<k,b);
//randn(w_k,cv::Scalar(0),
// cv::Scalar:all(linekf.processNoiseCov.at<float>(0,0)));
linekf.correct(z_k);
}
return 0;
}
int trackvehicle(cv::Mat &frame,
std::vector<cv::Rect> &rects,
std::string cascade_name)
{//track a vehicle only
//declare kalman filter object and related matrixes;
static cv::KalmanFilter vehiclekf(VEHICLE_DYNAMPARAMS,
VEHICLE_MEASUREPARAMS,
VEHICLE_CONTROLPARAMS);
static cv::Mat x_k(VEHICLE_DYNAMPARAMS,1,CV_32F);//state vector
static cv::Mat w_k(VEHICLE_DYNAMPARAMS,1,CV_32F);
static cv::Mat z_k=cv::Mat::zeros(VEHICLE_MEASUREPARAMS,1,CV_32F);
//static cv::Mat y_k;
//state matrix is [x,y] column vector
static struct State
{
int lostframe;
}state={0};
int found=0;
if(rects.size()==0)
{//measure
vehiclekf.transitionMatrix=*(cv::Mat_<float>(2,2)<<1,0,0,1);
setIdentity(vehiclekf.measurementMatrix);
setIdentity(vehiclekf.processNoiseCov,cv::Scalar::all(1e-5));
setIdentity(vehiclekf.measurementNoiseCov,cv::Scalar::all(1e-1));
setIdentity(vehiclekf.errorCovPost,cv::Scalar::all(1));
found=detectvehicle(frame,rects,cascade_name);
if(found<=0)
{//no vehicle detected yet
return 0;
}
else
{
//vehiclekf.statePost=*(cv::Mat_<int>(2,1)
// << rects[0].x+rects[0].width/2,rects[0].y+rects[0].height/2);
/*z_k=*(cv::Mat_<int>(2,1)<<rects[0].x+rects[0].width/2,rects[0].y+rects[0].height/2);
vehiclekf.correct(z_k);*/
cv::rectangle(frame,rects[0],cv::Scalar(0,255,255),1,8,0);
}
}
else
{//predict and measure
cv::Mat y_k=vehiclekf.predict();
//generate a region with predicted result,and detect in this area
std::cout<<"372"<<std::endl;
int dx=3*sqrt(vehiclekf.errorCovPre.at<float>(0,0));
int dy=3*sqrt(vehiclekf.errorCovPre.at<float>(1,1));
cv::Rect roi(y_k.at<int>(0,0)-dx-rects[0].width/2,
y_k.at<int>(1,0)-dy-rects[0].height/2,
rects[0].width+2*dx,rects[0].height+2*dy);
//...
//check roi effectiveness
if(!(roi.x>=0&&roi.x+roi.width<=frame.cols&&
roi.y>=0&&roi.y+roi.height<=frame.rows))
{
cv::putText(dst,"invalid region of interest",cvPoint(10,10),1,1,1,1);
return 0;
}
cv::Mat roiimage=frame(roi);
found=detectvehicle(roiimage,rects,cascade_name);
if(found<=0)
{
state.lostframe++;
if(state.lostframe>=MAX_LOST_FRAME)
{
//detect within a whole image
found=detectvehicle(frame,rects,cascade_name);
if(found<=0)
{//the vehicle is totally lost
//still not found
state.lostframe=0;
//erase this vehicle and reset related data
return 0;//tracking 0 vehicle
}
}
}//if(found<=0)
else
{
//generat measurement
z_k=*(cv::Mat_<int>(2,1) << rects[0].x,rects[0].y);
randn(w_k,cv::Scalar(0),
cv::Scalar::all(sqrt(vehiclekf.processNoiseCov.at<float>(0,0))));
vehiclekf.correct(z_k);
cv::rectangle(frame,rects[0],cv::Scalar(0,255,0),1,8,0);
}
}
}
int main(int argc,char **argv)
{
cv::VideoCapture cap;
if( argc == 1 || (argc==2 && strlen(argv[1])==1 && isdigit(argv[1][0])))
cap.open("data/video/Q.avi");
else if( argc >= 2)
{
cap.open(argv[1]);
if( cap.isOpened())
std::cout << "Video "<<argv[1]<<
": width="<<cap.get(CV_CAP_PROP_FRAME_WIDTH)<<
",height="<<cap.get(CV_CAP_PROP_FRAME_HEIGHT)<<
",nframes="<<cap.get(CV_CAP_PROP_FRAME_COUNT)<<std::endl;
if( argc>2 && isdigit(argv[2][0]))
{
int pos;
sscanf(argv[2],"%d",&pos);
std::cout<<"Seeking to frame #"<<pos<<std::endl;
cap.set(CV_CAP_PROP_POS_FRAMES,pos);
}
}
if(!cap.isOpened())
{
std::cout<<"Could not initialize capturing...\n";
return -1;
}
cv::namedWindow("frame");
/*
* cv::namedWindow("blur");
cv::namedWindow("thrs");
cv::namedWindow("dil");
cv::namedWindow("ero");
*/
cv::namedWindow("canny");
cv::namedWindow("dst");
std::vector<cv::Vec4i> lines;
std::vector<cv::Rect> rects;
int c,ksize=3;
for(;;)
{
cap>>frame;
if(frame.empty())
break;
cv::cvtColor(frame,gray,cv::COLOR_BGR2GRAY);
cv::blur(gray,blur,cv::Size(ksize,ksize));
cv::threshold(blur,thrs,150,255,cv::THRESH_BINARY);
cv::dilate(thrs,dil,NULL);
cv::erode(dil,ero,NULL);
dst=frame.clone();
detectLane(ero,lines);
trackline(ero,lines);
//detectvehicle(dst,rects,"data/cars3.xml");
// trackvehicle(dst,rects,"data/cars3.xml");
cv::imshow("frame",frame);
cv::imshow("ero",ero);
cv::imshow("dst",dst);
c=cv::waitKey(10);
if(c=='q'||c=='Q'||(c&255)==27)
break;
if(c==' ')
{
c=cv::waitKey();
while(c!=' ')
{
c=cv::waitKey();
if(c==' ')
break;
}
}
}
return 0;
}
|
5f81ca9d484b0793296bd55224a1226fc158dd9f | 93278aa111ef7053751f156280b807a8abe298fb | /src/Elements/AngleSpring.h | 5bdb2d4a2063c1ea221e376c649d287f9a8379d1 | [
"MIT"
] | permissive | wsklug/voom | 29c091dc8e90f1f913c389a4f04ded9a7c294252 | 43260b955a6cf11ba8e14e79c80b3618088a880b | refs/heads/master | 2020-04-05T21:12:05.821811 | 2017-10-13T21:05:51 | 2017-10-13T21:05:51 | 21,869,008 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,547 | h | AngleSpring.h | // -*- C++ -*-
//----------------------------------------------------------------------
//
// William S. Klug
// University of California Los Angeles
// (C) 2004-2008 All Rights Reserved
//
//----------------------------------------------------------------------
#if !defined(__AngleSpring_h__)
#define __AngleSpring_h__
#include "Node.h"
#include "Element.h"
namespace voom
{
template<int N>
class AngleSpring : public Element {
public:
typedef tvmet::Vector<double,N> VectorND;
typedef DeformationNode<N> Node_t;
AngleSpring(Node_t * nodeA, Node_t * nodeB, Node_t * nodeC, double k)
: _nodeA(nodeA), _nodeB(nodeB), _nodeC(nodeC), _k(k) {
_baseNodes.push_back(nodeA);
_baseNodes.push_back(nodeB);
_baseNodes.push_back(nodeC);
}
// angle theta = /_ABC
//
// A C
// \ /
// B
// E = 0.5*k*(theta^2) \approx k*(1-cos(theta))
//
void compute(bool f0, bool f1, bool f2) {
const VectorND & xA = _nodeA->point();
const VectorND & xB = _nodeB->point();
const VectorND & xC = _nodeC->point();
VectorND tBA;
tBA = xA-xB;
double LBA = norm2(tBA);
tBA /= LBA;
VectorND tBC;
tBC = xC-xB;
double LBC = norm2(tBC);
tBC /= LBC;
double cosABC = dot(tBA,tBC);
if(f0) {
_energy = _k*(1.0+cosABC);
}
if(f1) {
VectorND fA;
fA = -cosABC * tBA;
fA += tBC;
fA *= _k/LBA;
VectorND fC;
fC = -cosABC * tBC;
fC += tBA;
fC *= _k/LBC;
for(int i=0; i<N; i++) {
_nodeA->addForce( i, fA(i) );
_nodeB->addForce( i, -fA(i)-fC(i) );
_nodeC->addForce( i, fC(i)) ;
}
}
return;
}
double stiffness() const {return _k;}
void setStiffness(double k) { _k = k; }
double meanSegmentExtension() {
const VectorND & xA = _nodeA->point();
const VectorND & xB = _nodeB->point();
const VectorND & xC = _nodeC->point();
double dAB = norm2(xA-xB);
double dBC = norm2(xC-xB);
return 0.5*(dAB+dBC);
}
double meanSegmentLength() {
const VectorND & xA = _nodeA->position();
const VectorND & xB = _nodeB->position();
const VectorND & xC = _nodeC->position();
double dAB = norm2(xA-xB);
double dBC = norm2(xC-xB);
return 0.5*(dAB+dBC);
}
double getAngleABC() {
VectorND tAB;
tAB = _nodeB->point() - _nodeA->point();
double lAB = norm2(tAB);
tAB /= lAB;
VectorND tBC;
tBC = _nodeC->point() - _nodeB->point();
double lBC = norm2(tBC);
tBC /= lBC;
double angAB = atan2(tAB[1],tAB[0]);
// rotate tBC //
VectorND temptBC(tBC);
tBC[0] = cos(angAB)*temptBC[0]+sin(angAB)*temptBC[1];
tBC[1] = cos(angAB)*temptBC[1]-sin(angAB)*temptBC[0];
double angABC = atan2(tBC[1],tBC[0]);
return angABC;
}
double meanCurrentLength() {
const VectorND & xA = _nodeA->point();
const VectorND & xB = _nodeB->point();
const VectorND & xC = _nodeC->point();
double dAB = norm2(xA-xB);
double dBC = norm2(xC-xB);
return 0.5*(dAB+dBC);
}
double getCurvature() {
double angle = getAngleABC();
double meanL = meanCurrentLength();
double curvature = 2.0/meanL*abs(sin(angle/2.0));
return curvature;
}
private:
Node_t * _nodeA;
Node_t * _nodeB;
Node_t * _nodeC;
double _k;
};
};
#endif // __AngleSpring_h__
|
863dbe6857eeb962e4a2aeeec02d02b27fd6b624 | 1351f48d45c2c05e322c29c5f68da0d4590888c1 | /codeforces/aimr3B.cpp | 777e16b709e3f0cff2d50c9dc754d13b346b0bd0 | [] | no_license | laziestcoder/Problem-Solvings | cd2db049c3f6d1c79dfc9fba9250f4e1d8c7b588 | df487904876c748ad87a72a25d2bcee892a4d443 | refs/heads/master | 2023-08-19T09:55:32.144858 | 2021-10-21T20:32:21 | 2021-10-21T20:32:21 | 114,477,726 | 9 | 2 | null | 2021-06-22T15:46:43 | 2017-12-16T17:18:43 | Python | UTF-8 | C++ | false | false | 662 | cpp | aimr3B.cpp | /************************************************************************/
/* Name: Towfiqul Islam */
/* uva id: 448714 */
/* email id: towfiq.106@gmail.com */
/* institute: IIUC */
/* address: Chittagong, Bangladesh */
/* */
/************************************************************************/
#include<bits/stdc++.h>
using namespace std;
int x[100005];
int main ()
{
int n,i,a;
cin>>n>>a;
for(i=0; i<n; i++)
scanf("%d",&x[i]);
sort(x,x+n);
int s=0;
for(i=0; i<n-1; i++)
s+=min(abs(x[i]-a),abs(x[i+1]-a));
cout<<s<<endl;
return 0;
}
|
fc5e03bc0e208ed324847e0222da1614499e6428 | 26f474b0ff8508710d0dfa65c3c15faa0e490a90 | /src/UserInterface.hpp | 3de44da9e4d470ca6b68445522fab97abe1ce2a3 | [] | no_license | denizakcal/Winter-2018_Project | b935e544e0c78d8191ec4631863f03b0e723e2fb | 055a18f3a80b7f934c96562df60f88ac0239d8af | refs/heads/master | 2021-05-09T15:35:18.923565 | 2018-04-12T03:02:23 | 2018-04-12T03:02:23 | 119,094,854 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 855 | hpp | UserInterface.hpp |
#ifndef USERINTERFACE_H_
#define USERINTERFACE_H_
//#include "TheGame.hpp"
class TheGame;
#include "Graph.hpp"
#include "Player.hpp"
#include "UserInterfaceCodes.hpp"
#include <vector>
class UserInterface {
protected:
int numberOfPlayers;// = 0;
bool* isPaused;// = false;
std::vector<Player*> players;
int* turnOfPlayerN;
public:
UserInterface(std::vector<Player*> players, bool* isPaused, int* turnOfPlayerN);
virtual ~UserInterface();
TheGame loadGame(std::string fileName);
void saveGame(TheGame theGame);
virtual void displayCurrentSnapshotOfGame() = 0;
virtual void displayPauseScreen() = 0;
virtual void displayMainMenuScreen() = 0;
virtual void displayMapSelectionScreen() = 0;
virtual void displayNumberOfPlayersSelectionScreen() = 0;
virtual UserInterfaceCodes makeMove() = 0;
};
#endif /* USERINTERFACE_H_ */
|
541df110620a94e07fef3259466a6c4986f305fb | b00995ef1f42a3ee4f523afb594eb14f9ef9d01d | /stringtok.h | 9d5dc0111f9f5d1ee7c1f12efcf9d6e66a67d886 | [] | no_license | dstl1128/vmdkparse | 3c1cb48bb2f5da9f524e618ad9eb8f4055766ad0 | b5c675c9b264fabaefbfac76e2d466da7df40f46 | refs/heads/master | 2023-01-11T05:22:00.283863 | 2020-11-16T14:46:03 | 2020-11-16T14:46:03 | 313,333,445 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,463 | h | stringtok.h | //
// String Tokenizer
// Split std::basic_string with delimiter for each iteration.
// Tokenized strings are new strings and does not refer to original.
// Also does not modify original string during tokenizing.
//
// Author: Derek Saw
//
// Copyright (c) 2009. All rights reserved.
//
#ifndef __STRINGTOK_H
#define __STRINGTOK_H
//
// Conversations: Al-Go-Rithms
// from Jim Hyslop and Herb Sutter
// http://www.ddj.com/cpp/184403801
//
// TODO: delim.c_str() is not universal on containers
// - only for std::basic_string<T> types
template <typename T>
class StringTok
{
public:
StringTok(T const & seq, typename T::size_type pos = 0)
: _seq(seq), _pos(pos) { }
T operator () (T const & delim)
{
T token;
if (_pos != T::npos)
{
// start of found token
typename T::size_type first = _seq.find_first_not_of(delim.c_str(), _pos);
if (first != T::npos)
{
// length of found token
typename T::size_type len = _seq.find_first_of(delim.c_str(), first) - first;
token = _seq.substr(first, len);
// done; commit with non throw operation
_pos = first + len;
if (_pos != T::npos) ++_pos;
if (_pos >= _seq.size()) _pos = T::npos;
}
}
return token;
}
private:
const T & _seq;
typename T::size_type _pos;
};
#endif
|
dd960baf37178175708935a7fae21a7c5178bcce | 7b4134efae43198d30e4d862460c243efe5fe668 | /Plugins/AI_Plugin/Intermediate/Build/Win64/UE4Editor/Inc/AI_Plugin/MyTargetPoint.generated.h | 75338e39df63141342531be9d578391c44f49df5 | [] | no_license | RomanSolomatin/Unreal-Engine-4-AI-Plugin | 606b0d7cb5666918a97fbf11b8083440b180f9cd | 993df879f65bd4b46c0933ed4c0f63df77a97885 | refs/heads/master | 2020-03-10T16:22:05.527835 | 2017-06-15T23:05:31 | 2017-06-15T23:05:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,971 | h | MyTargetPoint.generated.h | // Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
C++ class header boilerplate exported from UnrealHeaderTool.
This is automatically generated by the tools.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
PRAGMA_DISABLE_DEPRECATION_WARNINGS
#ifdef AI_PLUGIN_MyTargetPoint_generated_h
#error "MyTargetPoint.generated.h already included, missing '#pragma once' in MyTargetPoint.h"
#endif
#define AI_PLUGIN_MyTargetPoint_generated_h
#define Unreal_Engine_4_AI_Plugin_Plugins_AI_Plugin_Source_AI_Plugin_Public_MyTargetPoint_h_12_RPC_WRAPPERS
#define Unreal_Engine_4_AI_Plugin_Plugins_AI_Plugin_Source_AI_Plugin_Public_MyTargetPoint_h_12_RPC_WRAPPERS_NO_PURE_DECLS
#define Unreal_Engine_4_AI_Plugin_Plugins_AI_Plugin_Source_AI_Plugin_Public_MyTargetPoint_h_12_INCLASS_NO_PURE_DECLS \
private: \
static void StaticRegisterNativesAMyTargetPoint(); \
friend AI_PLUGIN_API class UClass* Z_Construct_UClass_AMyTargetPoint(); \
public: \
DECLARE_CLASS(AMyTargetPoint, ATargetPoint, COMPILED_IN_FLAGS(0), 0, TEXT("/Script/AI_Plugin"), NO_API) \
DECLARE_SERIALIZER(AMyTargetPoint) \
/** Indicates whether the class is compiled into the engine */ \
enum {IsIntrinsic=COMPILED_IN_INTRINSIC};
#define Unreal_Engine_4_AI_Plugin_Plugins_AI_Plugin_Source_AI_Plugin_Public_MyTargetPoint_h_12_INCLASS \
private: \
static void StaticRegisterNativesAMyTargetPoint(); \
friend AI_PLUGIN_API class UClass* Z_Construct_UClass_AMyTargetPoint(); \
public: \
DECLARE_CLASS(AMyTargetPoint, ATargetPoint, COMPILED_IN_FLAGS(0), 0, TEXT("/Script/AI_Plugin"), NO_API) \
DECLARE_SERIALIZER(AMyTargetPoint) \
/** Indicates whether the class is compiled into the engine */ \
enum {IsIntrinsic=COMPILED_IN_INTRINSIC};
#define Unreal_Engine_4_AI_Plugin_Plugins_AI_Plugin_Source_AI_Plugin_Public_MyTargetPoint_h_12_STANDARD_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API AMyTargetPoint(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(AMyTargetPoint) \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, AMyTargetPoint); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(AMyTargetPoint); \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API AMyTargetPoint(AMyTargetPoint&&); \
NO_API AMyTargetPoint(const AMyTargetPoint&); \
public:
#define Unreal_Engine_4_AI_Plugin_Plugins_AI_Plugin_Source_AI_Plugin_Public_MyTargetPoint_h_12_ENHANCED_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API AMyTargetPoint(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()) : Super(ObjectInitializer) { }; \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API AMyTargetPoint(AMyTargetPoint&&); \
NO_API AMyTargetPoint(const AMyTargetPoint&); \
public: \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, AMyTargetPoint); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(AMyTargetPoint); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(AMyTargetPoint)
#define Unreal_Engine_4_AI_Plugin_Plugins_AI_Plugin_Source_AI_Plugin_Public_MyTargetPoint_h_12_PRIVATE_PROPERTY_OFFSET
#define Unreal_Engine_4_AI_Plugin_Plugins_AI_Plugin_Source_AI_Plugin_Public_MyTargetPoint_h_9_PROLOG
#define Unreal_Engine_4_AI_Plugin_Plugins_AI_Plugin_Source_AI_Plugin_Public_MyTargetPoint_h_12_GENERATED_BODY_LEGACY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
Unreal_Engine_4_AI_Plugin_Plugins_AI_Plugin_Source_AI_Plugin_Public_MyTargetPoint_h_12_PRIVATE_PROPERTY_OFFSET \
Unreal_Engine_4_AI_Plugin_Plugins_AI_Plugin_Source_AI_Plugin_Public_MyTargetPoint_h_12_RPC_WRAPPERS \
Unreal_Engine_4_AI_Plugin_Plugins_AI_Plugin_Source_AI_Plugin_Public_MyTargetPoint_h_12_INCLASS \
Unreal_Engine_4_AI_Plugin_Plugins_AI_Plugin_Source_AI_Plugin_Public_MyTargetPoint_h_12_STANDARD_CONSTRUCTORS \
public: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#define Unreal_Engine_4_AI_Plugin_Plugins_AI_Plugin_Source_AI_Plugin_Public_MyTargetPoint_h_12_GENERATED_BODY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
Unreal_Engine_4_AI_Plugin_Plugins_AI_Plugin_Source_AI_Plugin_Public_MyTargetPoint_h_12_PRIVATE_PROPERTY_OFFSET \
Unreal_Engine_4_AI_Plugin_Plugins_AI_Plugin_Source_AI_Plugin_Public_MyTargetPoint_h_12_RPC_WRAPPERS_NO_PURE_DECLS \
Unreal_Engine_4_AI_Plugin_Plugins_AI_Plugin_Source_AI_Plugin_Public_MyTargetPoint_h_12_INCLASS_NO_PURE_DECLS \
Unreal_Engine_4_AI_Plugin_Plugins_AI_Plugin_Source_AI_Plugin_Public_MyTargetPoint_h_12_ENHANCED_CONSTRUCTORS \
private: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#undef CURRENT_FILE_ID
#define CURRENT_FILE_ID Unreal_Engine_4_AI_Plugin_Plugins_AI_Plugin_Source_AI_Plugin_Public_MyTargetPoint_h
PRAGMA_ENABLE_DEPRECATION_WARNINGS
|
a84f67a9b97dd05e28543583d03be9c4be75ebe2 | a13e7993275058dceae188f2101ad0750501b704 | /2021/2049. Count Nodes With the Highest Score.cpp | 860bc9c8b37aee87a8a0586d868096bf9fb2c22d | [] | no_license | yangjufo/LeetCode | f8cf8d76e5f1e78cbc053707af8bf4df7a5d1940 | 15a4ab7ce0b92b0a774ddae0841a57974450eb79 | refs/heads/master | 2023-09-01T01:52:49.036101 | 2023-08-31T00:23:19 | 2023-08-31T00:23:19 | 126,698,393 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,615 | cpp | 2049. Count Nodes With the Highest Score.cpp | class Solution {
public:
int countHighestScoreNodes(vector<int>& parents) {
int n = parents.size();
vector<int> degrees(n, 0), left(n, 0), right(n, 0);
for (int i = 1; i < parents.size(); i++) {
degrees[parents[i]]++;
}
priority_queue<int, vector<int>, greater<int>> pq;
for (int i = 0; i < n; i++) {
if (degrees[i] == 0) {
pq.push(i);
degrees[i] = -1;
}
}
long long maxVal = 0, maxCount = 0;
while (!pq.empty()) {
int node = pq.top();
pq.pop();
long long prod = 1;
if (left[node] != 0) {
prod *= left[node];
}
if (right[node] != 0) {
prod *= right[node];
}
if (node != 0) {
prod *= n - left[node] - right[node] - 1;
if (left[parents[node]] == 0) {
left[parents[node]] = left[node] + right[node] + 1;
} else {
right[parents[node]] = left[node] + right[node] + 1;
}
degrees[parents[node]] --;
if (degrees[parents[node]] == 0) {
pq.push(parents[node]);
degrees[parents[node]] = -1;
}
}
if (prod > maxVal) {
maxVal = prod;
maxCount = 1;
} else if (prod == maxVal) {
maxCount += 1;
}
}
return maxCount;
}
}; |
aeb66cb486a2a0aba04e7b61ea6fc58e549159eb | 24d31a065991ff16cf435d937ed91e37c7d6afad | /producto.h | 4df1b7aba2a8b9cfc0a751354d25525dd91fb431 | [] | no_license | AlexPadi/Tienda | 505f8dd225903327ec50cda79823316bf12ee39f | 782aa085451627c7b969f56a8d9110c0857dcddc | refs/heads/main | 2023-08-31T22:10:29.815985 | 2021-07-12T14:10:37 | 2021-07-12T14:10:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 806 | h | producto.h | #ifndef PRODUCTO_H
#define PRODUCTO_H
#include <QObject>
#define IVA 12.0;
class Producto : public QObject
{
Q_OBJECT
Q_PROPERTY(int codigo READ codigo WRITE setCodigo)
Q_PROPERTY(QString producto READ producto WRITE setProducto)
//Q_PROPERTY(int cantidad READ cantidad WRITE setCantidad)
Q_PROPERTY(float precio READ precio WRITE setPrecio)
private:
int m_codigo;
QString m_producto;
//int m_cantidad;
float m_precio;
public:
explicit Producto(QObject *parent = nullptr);
Producto (int codigo, QString producto, float precio);
int codigo() const;
void setCodigo(int codigo);
QString producto() const;
void setProducto(const QString &producto);
float precio() const;
void setPrecio(float precio);
signals:
};
#endif // PRODUCTO_H
|
3bb2d1589e39002a6e9f4b2421ecdd27a80ab7c3 | 7b00a9bf8c28e2c302466b40d51da00637fc0c28 | /lab03/lab03/cabin.cpp | dbeba05c280ed867a1d42f7248f8a2b9f68f4176 | [] | no_license | OverldAndrey/iu7-4sem-oop | 999b7100d552f5a88aa7ab2fc9fc7c19abbbc6aa | 4efc3fcb15ef97a2595ec89cadec28260965db8c | refs/heads/master | 2020-06-01T03:51:38.431246 | 2019-06-06T18:06:07 | 2019-06-06T18:06:07 | 190,622,126 | 1 | 0 | null | 2019-06-06T18:06:09 | 2019-06-06T17:27:01 | C++ | UTF-8 | C++ | false | false | 1,929 | cpp | cabin.cpp | #include "cabin.h"
#include <iostream>
#include <QThread>
#include <QTimer>
Cabin::Cabin() : QObject()
{
}
void Cabin::on_move(int floor)
{
this->target_floor = floor;
if (this->target_floor == this->current_floor)
{
return;
}
// std::cout << this->current_floor << " " << this->target_floor << std::endl;
this->is_moving = true;
// this->is_in_action = true;
if (this->current_floor < this->target_floor)
{
this->is_moving_down = false;
this->is_moving_up = true;
this->current_floor++;
}
else if (this->current_floor > this->target_floor)
{
this->is_moving_down = true;
this->is_moving_up = false;
this->current_floor--;
}
for (int i = 0; i < 500; i++)
{
QThread::msleep(1);
}
emit reach(this->current_floor);
if (this->current_floor == this->target_floor)
{
this->is_moving = false;
emit stop(this->current_floor);
}
}
void Cabin::on_stop()
{
this->is_closed = false;
for (int i = 0; i < 200; i++)
{
QThread::msleep(1);
}
this->doors_are_opening = true;
emit is_opening();
for (int i = 0; i < 200; i++)
{
QThread::msleep(1);
}
this->doors_are_opening = false;
emit open();
for (int i = 0; i < 200; i++)
{
QThread::msleep(1);
}
this->doors_are_closing = true;
emit is_closing();
for (int i = 0; i < 200; i++)
{
QThread::msleep(1);
}
this->doors_are_closing = false;
this->is_closed = true;
emit close();
}
void Cabin::on_set_standby()
{
this->is_moving_down = false;
this->is_moving_up = false;
// this->is_in_action = false;
}
void Cabin::on_standby()
{
emit reach(this->current_floor);
emit stop(this->current_floor);
}
|
deee7acad79218b66429f733d1c016e105aaafea | 69470f251bb45953ba4dd884d1c2db4b6ec3052d | /recursif.cpp | f44b94b56c9c11dfb32ca78becf065fdfa75a235 | [] | no_license | mustafakurt07/Algorith-DataStruct | f3d356f2fba45b4b2bce9d938123e98626a37520 | a211534c3cce454e06eaa1e1cb1866f244376540 | refs/heads/main | 2023-02-01T17:49:32.802897 | 2020-12-20T21:53:51 | 2020-12-20T21:53:51 | 323,164,569 | 0 | 0 | null | null | null | null | ISO-8859-9 | C++ | false | false | 278 | cpp | recursif.cpp | #include<stdio.h>
int us(int x,int y)
{
int sonuc=1,i;
if(y==0) return 1;
else return x*us(x,y-1);
}
main()
{
int x,y;
printf("us alıncak sayiyi girin\n");
scanf("%d %d",&x,&y);
getchar();
printf("\n ussun degeri=%d",us(x,y));
getchar();
}
|
8b769617cbb26934b216c5a629ebf8bc051318c2 | 958dcb5201620519392264e0458545066a07432a | /labs/lab-00/code/Inventory.hpp | 780f509c2a6be967a268c676a25257b89dc2f2d2 | [] | no_license | ryanfish17/csc-212-fall2021 | 9023be933ffbab66226eb0fdc77a8f6cf0ad55f8 | db63a53661f946a1f111d7541317275ee4225eff | refs/heads/master | 2023-08-27T12:17:59.903911 | 2021-11-04T16:28:57 | 2021-11-04T16:28:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 554 | hpp | Inventory.hpp | #pragma once
#include <iostream>
#include <vector>
// Forward declaration.
// Cannot include 'Item', as 'Item' includes 'Entity' & that would cause a circular dependency (compiler would crash with many, many errors.)
// This allows 'Entity' to *know* that 'Item' exists, but *not* how to use it.
class Item;
class Entity;
class Inventory
{
private:
std::vector<Item*> inventory;
public:
void displayInventory();
void addItem(Item* item);
void useItem(std::string name, Entity* target);
void useItem(int index, Entity* target);
int getSize();
};
|
e74087d98f5df6499ac60702c7dd08d83430adb6 | 13b14c9c75143bf2eda87cb4a41006a52dd6f02b | /AOJ/0227/solve.cpp | 2b31b388ea2179c65a54ae8beeb0a58c46c8bcae | [] | no_license | yutaka-watanobe/problem-solving | 2c311ac856c79c20aef631938140118eb3bc3835 | f0b92125494fbd3c8d203989ec9fef53f52ad4b4 | refs/heads/master | 2021-06-03T12:58:39.881107 | 2020-12-16T14:34:16 | 2020-12-16T14:34:16 | 94,963,754 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 688 | cpp | solve.cpp | #include<iostream>
#include<algorithm>
#include<cassert>
using namespace std;
const int MAX_SIZE = 1000;
const int MIN_SIZE = 1;
const int MAX_PRICE = 10000;
const int MIN_PRICE = 1;
main(){
int n,m;
while(cin >> n >> m && n){
int price[n];
assert(MIN_SIZE <= n && n <= MAX_SIZE);
assert(MIN_SIZE <= m && m <= MAX_SIZE);
for(int i = 0;i<n;i++){
cin >> price[i];
assert(MIN_PRICE <= price[i] && price[i] <= MAX_PRICE);
}
sort(price,price+n,greater<int>());
int sum = 0;
for(int i = 0;i<n;i++)
if((i+1)%m != 0)
sum += price[i];
cout << sum << endl;
}
return 0;
}
|
26caff3b306f38ee19a4c2db99e6a5401c7846cb | 28d25f81c33fe772a6d5f740a1b36b8c8ba854b8 | /IFHLC/IFHLC'3/A/main.cpp | ddfbee04e2392f4f7efad5d649ddec539628f493 | [] | no_license | ahmedibrahim404/CompetitiveProgramming | b59dcfef250818fb9f34797e432a75ef1507578e | 7473064433f92ac8cf821b3b1d5cd2810f81c4ad | refs/heads/master | 2021-12-26T01:18:35.882467 | 2021-11-11T20:43:08 | 2021-11-11T20:43:08 | 148,578,163 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 348 | cpp | main.cpp | #include <iostream>
using namespace std;
int T, n, k, no;
int main(){
cin >> T;
while(T--){
cin >> n >> k;
bool found=0;
for(int i=0;i<n;i++){
cin >> no;
if((no+k)%7==0&&!found) {cout << "Yes\n";found=1;}
}
if(!found) cout << "No\n";
}
return 0;
}
|
5795c07112efe9bbefb996681cf00fd100152d9d | b9c4a6bd1788c40f10eeda32bff73b60825a983c | /C++ Programs/leetcode-questions/Minimum Window Substring.cpp | 3b9c9620676134cb4fa9f4bfb98922318c02f8bc | [] | no_license | Lakshit-Chiranjiv/hacktoberfest2021-4 | 008c5bfe36906a8f7e3938df8645e7e9c4e42682 | 8ee733884bc6b172e9242bc90f4c65279df40435 | refs/heads/main | 2023-08-23T02:06:39.712540 | 2021-10-19T05:03:29 | 2021-10-19T05:03:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 990 | cpp | Minimum Window Substring.cpp | class Solution {
public:
string minWindow(string s, string t) {
unordered_map<char,int> mp;
for(auto ch:t)
{
mp[ch]++;
}
int dist=mp.size() ;
unordered_map<char,int> window;
int count = 0 , ll = 0 , rr = 0 ;
int l = 0 , r = 0 , ans = INT_MAX ;
while(r<s.length())
{
window[s[r]]++ ;
if(mp.count(s[r]) and mp[s[r]]==window[s[r]])
{
count++;
}
r++;
while(count == dist and l < r)
{
if(ans > r-l)
{
ans= r - l ;
ll = l ;
rr = r ;
}
window[s[l]]-- ;
if(mp.count(s[l]) and window[s[l]] < mp[s[l]])
{
count--;
}
l++;
}
}
return s.substr(ll,rr-ll);
}
};
|
c6b159d90bc3d414ed0d41f91e9f4b81198e2deb | dce0a22a899c20b85070a6f117b169bab3be848e | /Classes/Scene/NormalBattleScene.cpp | 12cdd9b3fa50f76d50ee1276a5d1d724ca015afd | [] | no_license | Ryougi-Shio/CHEN | 3d8d24717bf34551c85f898181267f2c325a1ea6 | 398555f129f4b6401b3d8abb78f8f5824b32ddfc | refs/heads/main | 2023-06-03T18:52:45.569102 | 2021-06-19T14:00:39 | 2021-06-19T14:00:39 | 363,114,561 | 5 | 6 | null | 2021-06-19T14:00:40 | 2021-04-30T11:06:40 | C++ | GB18030 | C++ | false | false | 12,532 | cpp | NormalBattleScene.cpp | #include"NormalBattleScene.h"
#include"Player.h";
#include"music/music.h"
#include"PlayerMove.h"
#include"TreasureBoxes.h"
#include"AllTag.h"
#include"Weapon.h"
#include"BossInterlude.h"
USING_NS_CC;
MusicManager* NormalBattleScene::getmusicManager()
{
return m_musicManager;
}
void NormalBattleScene::bindPlayer(Player* player)
{
m_player = player;
}
Player* NormalBattleScene::getPlayer()
{
return m_player;
}
BattleMap* NormalBattleScene::getParentMap()
{
return parentMap;
}
void NormalBattleScene::changeMap(int x)
{
static int i = 1;
auto visibleSize = Director::getInstance()->getVisibleSize();
auto origin = Director::getInstance()->getVisibleOrigin();
auto temp = parentMap->getPosition();
auto test = m_battleMap.at(x)->getPosition();
parentMap->setPosition(m_battleMap.at(x)->getPosition());
removeChild(parentMap);
parentMap = m_battleMap.at(x);
parentMap->setPosition(temp);
m_player->getplayermove()->bindMap(m_battleMap.at(x)->getBattleMap());
if (parentMap->getTag()!=2)
{
if (parentMap->getBattleMap()->getTag() == NormalRoom_TAG)
parentMap->createMonster(4);
else if (parentMap->getBattleMap()->getTag() == BossRoom_TAG)
parentMap->createMonster(0);
else if (parentMap->getBattleMap()->getTag() == HiddenRoom_TAG)
parentMap->createMonster(4);
//给每个怪物增加刚体
for (int i = 0; i < parentMap->getMonster().size(); i++)
{
float x = parentMap->getMonster().at(i)->Width;
float y = parentMap->getMonster().at(i)->Height;
auto physicsBody_M_1 = PhysicsBody::createBox(Size(x,y),
PhysicsMaterial(0.0f, 0.0f, 0.0f));
physicsBody_M_1->setDynamic(false);
parentMap->getMonster().at(i)->addComponent(physicsBody_M_1);
parentMap->getMonster().at(i)->getPhysicsBody()->setPositionOffset(Vec2(x/2,y/2));
physicsBody_M_1->setCategoryBitmask(0x0001);//0011
physicsBody_M_1->setCollisionBitmask(0x0001);//0001
physicsBody_M_1->setContactTestBitmask(0x0001);
parentMap->getMonster().at(i)->setPhysicsBody(physicsBody_M_1);
//Boss怪,额外增加一个永久跟随的隐形子弹当作碰撞伤害
if (parentMap->getMonster().at(i)->getTag() == CthulhuEye_Monster_TAG)
{
parentMap->getMonster().at(i)->ImmortalAmmo = parentMap->getMonster().at(i)->MonsterAttack();
auto physicBody = PhysicsBody::createBox(Size(parentMap->getMonster().at(i)->getSprite()->getContentSize()),
PhysicsMaterial(0, 0, 0));//添加刚体
parentMap->getMonster().at(i)->ImmortalAmmo->addComponent(physicBody);
parentMap->getMonster().at(i)->ImmortalAmmo->getPhysicsBody()->setDynamic(false);
parentMap->getMonster().at(i)->ImmortalAmmo->getSprite()->setOpacity(0);
parentMap->getMonster().at(i)->ImmortalAmmo->getPhysicsBody()->setCategoryBitmask(0x0010);//掩码,怪物子弹和玩家相同
parentMap->getMonster().at(i)->ImmortalAmmo->getPhysicsBody()->setCollisionBitmask(0x0010);
parentMap->getMonster().at(i)->ImmortalAmmo->getPhysicsBody()->setContactTestBitmask(0x0010);
parentMap->getMonster().at(i)->addChild(parentMap->getMonster().at(i)->ImmortalAmmo, -1);
parentMap->getMonster().at(i)->ImmortalAmmo->setTag(MonsterAmmo_ImmortalTAG);
}
}
//宝箱创建,血瓶创建
if (parentMap->getBattleMap()->getTag() == NormalRoom_TAG)
{
parentMap->BoxInit();
parentMap->getBox().back()->bindScene(this);
parentMap->BoxCreate();
int i = rand() % 3 + 1;
parentMap->getBox().back()->BoxBirth(i);
parentMap->ItemInit();//宝箱里的血瓶创建
parentMap->getItems().back()->bindScene(this);
parentMap->ItemCreate();
parentMap->schedule(CC_SCHEDULE_SELECTOR(BattleMap::ItemInBoxUpdate), 0.1f);
}
else if (parentMap->getBattleMap()->getTag() == BossRoom_TAG|| parentMap->getBattleMap()->getTag() == ShopRoom_TAG)
{
for (int i = 1; i <= 3; i++)
{
parentMap->BoxInit();
parentMap->getBox().back()->bindScene(this);
parentMap->BoxCreate();
parentMap->getBox().back()->BoxBirth(i);
parentMap->ItemInit();//宝箱里的物品创建
parentMap->getItems().back()->bindScene(this);
parentMap->ItemCreate();
}
parentMap->schedule(CC_SCHEDULE_SELECTOR(BattleMap::ItemInBoxUpdate), 0.1f);
}
//打怪掉钱
if (parentMap->getBattleMap()->getTag() != BossRoom_TAG)
{
parentMap->DropsInit();
for (int i = 0; i < parentMap->getDrops().size(); i++)
{
parentMap->getDrops().at(i)->bindScene(this);
}
parentMap->DropsCreate(0);
}
//陷阱创建
if (parentMap->getBattleMap()->getTag() != ShopRoom_TAG
&& parentMap->getBattleMap()->getTag() != BossRoom_TAG)
{
int TrapsNum = rand() % 5 + 1;
for (int i = 1; i <= TrapsNum; i++)
{
parentMap->TrapsInit();
parentMap->getTraps().back()->bindScene(this);
parentMap->getTraps().back()->setScale(1.5);
parentMap->TrapsCreate(i);
parentMap->schedule(CC_SCHEDULE_SELECTOR(BattleMap::TrapsUpdate), 0.1f);
}
}
// parentMap->schedule(CC_SCHEDULE_SELECTOR(BattleMap::TrapsUpdate), 0.1f);
//祈祷雕像创建
if (parentMap->getBattleMap()->getTag() == NormalRoom_TAG)
{
if (rand() % 2)
{
parentMap->StatueInit();
parentMap->getStatue().back()->bindScene(this);
parentMap->StatueCreate();
parentMap->schedule(CC_SCHEDULE_SELECTOR(BattleMap::StatueUpdate), 0.1f);
}
}
else if (parentMap->getBattleMap()->getTag() == ShopRoom_TAG)
{
parentMap->StatueInit();
parentMap->getStatue().back()->bindScene(this);
parentMap->StatueCreate();
parentMap->schedule(CC_SCHEDULE_SELECTOR(BattleMap::StatueUpdate), 0.1f);
}
}
parentMap->schedule(CC_SCHEDULE_SELECTOR(BattleMap::StatueUpdate), 0.1f);
if (parentMap->getBattleMap()->getTag() == ShopRoom_TAG||
parentMap->getBattleMap()->getTag()==BossRoom_TAG)
{
parentMap->getWeapon()->bindPlayer(getPlayer());
}
//Update must be opened
parentMap->schedule(CC_SCHEDULE_SELECTOR(BattleMap::ItemInBoxUpdate), 0.1f);
parentMap->schedule(CC_SCHEDULE_SELECTOR(BattleMap::DropsUpdate), 0.1f);
addChild(parentMap, 1);
if (parentMap->getBattleMap()->getTag() == BossRoom_TAG && parentMap->getTag()!=2)//进Boss房
{
auto bossInterlude = BossInterlude::create();
bossInterlude->playInterlude(getPlayer(), parentMap->getMonster().back());
MusicManager::changeMusic("bgm/boss1.mp3");
Director::getInstance()->pushScene(TransitionTurnOffTiles::create(1.2f, bossInterlude));
}
parentMap->setTag(2);//表示已经到过该地图
}
void NormalBattleScene::Mapinit()
{
auto visibleSize = Director::getInstance()->getVisibleSize();
switch (rand() % 4)
{
case 0:
start_num = 0;
boss_num = 15;
//*shop_num = rand() % 2 ? 2 : 6;
break;
case 1:
start_num = 15;
boss_num = 0;
//*shop_num = rand() % 2 ? 0 : 8;
break;
case 2:
start_num = 3;
boss_num = 12;
//*shop_num = rand() % 2 ? 0 : 8;
break;
case 3:
start_num = 12;
boss_num = 3;
//*shop_num = rand() % 2 ? 2 : 6;
break;
default:
break;
};
for (int i = 0; i < 16; i++)//默认开始全能通过
{
virtualMap[i] = 1;
}
for (int i = 0; i < 6;i++)//生成6个障碍物,即一共能实际通过的地图有十张
{
int x = rand() % 16;
if (virtualMap[x]==1 && x!=start_num)
{
virtualMap[x] = 0;
}
else
{
i--;
continue;
}
if (isConnected(i))
{
continue;
}
else
{
i--;
virtualMap[x] = 1;
continue;
}
}
do
{
shop_num = rand() % 16;
} while (virtualMap[shop_num] != 1 || shop_num == boss_num || shop_num == start_num);
//boss_num = start_num;
while (1)
{
hid_num = rand() % 16;
if (!virtualMap[hid_num])
{
virtualMap[hid_num] = true;
break;
}
}
for (int i = 0; i < 16; i++)//取10张地图
{
if (virtualMap[i]==1)
{
m_battleMap.pushBack(BattleMap::create());
m_battleMap.back()->bindScene(this);
if (i == shop_num)
m_battleMap.back()->MapInit(1);//MapInit可传参,0为普通战斗图,1为商店图
else if (i==boss_num)
m_battleMap.back()->MapInit(2);
else if(i==hid_num)
m_battleMap.back()->MapInit(4);
else
m_battleMap.back()->MapInit(0);
m_battleMap.back()->setPosition(visibleSize.width * (i % 3), visibleSize.width * (i / 3));
m_battleMap.back()->setNumber(i);
m_battleMap.back()->setName("ok");
}
else
{
m_battleMap.pushBack(BattleMap::create());
m_battleMap.back()->setName("no");
}
}
parentMap = m_battleMap.at(start_num);//初始地图取左下角0号
auto temp = parentMap->getPosition();
parentMap->setPosition(m_battleMap.at(0)->getPosition());
m_battleMap.at(0)->setPosition(temp);
if (parentMap->getBattleMap()->getTag() == NormalRoom_TAG)
parentMap->createMonster(4);
else if (parentMap->getBattleMap()->getTag() == BossRoom_TAG)
parentMap->createMonster(0);
else if(parentMap->getBattleMap()->getTag() == HiddenRoom_TAG)
parentMap->createMonster(4);
addChild(parentMap, 1);
parentMap->setTag(2);
for (int i = 0; i < parentMap->getMonster().size(); i++)//给初始地图的怪物添加刚体
{
float x = parentMap->getMonster().at(i)->Width;
float y = parentMap->getMonster().at(i)->Height;
auto physicsBody_M = PhysicsBody::createBox(Size(x, y),
PhysicsMaterial(0.0f, 0.0f, 0.0f));
parentMap->getMonster().at(i)->addComponent(physicsBody_M);
parentMap->getMonster().at(i)->getPhysicsBody()->setPositionOffset(Vec2(x / 2, y / 2));
physicsBody_M->setDynamic(false);
physicsBody_M->setCategoryBitmask(0x0001);//0011掩码
physicsBody_M->setCollisionBitmask(0x0001);//0001
physicsBody_M->setContactTestBitmask(0x0001);
parentMap->getMonster().at(i)->setPhysicsBody(physicsBody_M);
if (parentMap->getMonster().at(i)->getTag() == CthulhuEye_Monster_TAG)//Boss怪,额外增加一个永久跟随的子弹当作碰撞伤害
{
parentMap->getMonster().at(i)->ImmortalAmmo = parentMap->getMonster().at(i)->MonsterAttack();
auto physicBody = PhysicsBody::createBox(Size(parentMap->getMonster().at(i)->getSprite()->getContentSize()),
PhysicsMaterial(0, 0, 0));//添加刚体
parentMap->getMonster().at(i)->ImmortalAmmo->addComponent(physicBody);
parentMap->getMonster().at(i)->ImmortalAmmo->getPhysicsBody()->setDynamic(false);
parentMap->getMonster().at(i)->ImmortalAmmo->getSprite()->setOpacity(0);
parentMap->getMonster().at(i)->ImmortalAmmo->getPhysicsBody()->setCategoryBitmask(0x0010);//掩码,怪物子弹和玩家相同
parentMap->getMonster().at(i)->ImmortalAmmo->getPhysicsBody()->setCollisionBitmask(0x0010);
parentMap->getMonster().at(i)->ImmortalAmmo->getPhysicsBody()->setContactTestBitmask(0x0010);
parentMap->getMonster().at(i)->addChild(parentMap->getMonster().at(i)->ImmortalAmmo,-1);
parentMap->getMonster().at(i)->ImmortalAmmo->setTag(MonsterAmmo_ImmortalTAG);
}
}
}
bool NormalBattleScene::isConnected(int obstacle)//看地图是否联通
{
bool isvisited[16] = { 0 };
std::queue<int> MapQueue;
std::vector<int> MapCanReach;
MapQueue.push(start_num);
isvisited[start_num] = 1;
while (MapQueue.size()>0)
{
int i = MapQueue.front();
MapCanReach.push_back(i);
MapQueue.pop();
if ((i + 1) <= 15 && (i + 1) % 4 != 0 && virtualMap[i + 1] == 1 && isvisited[i + 1] != 1)
{
MapQueue.push(i + 1);
isvisited[i+1] = 1;
}
if ((i - 1) >= 0 && (i - 1) % 4 != 3 && virtualMap[i - 1] == 1 && isvisited[i - 1] != 1)
{
MapQueue.push(i - 1);
isvisited[i-1] = 1;
}
if ((i - 4) >= 0 &&virtualMap[i - 4] == 1 && isvisited[i - 4] != 1)
{
MapQueue.push(i - 4);
isvisited[i-4] = 1;
}
if ((i + 4) <= 15 && virtualMap[i + 4] == 1 && isvisited[i + 4] != 1)
{
MapQueue.push(i + 4);
isvisited[i+4] = 1;
}
}
bool canReachBoss = 0;//能否到达BOSS房
for (auto x : MapCanReach)
{
if (x==boss_num)
{
canReachBoss = 1;
}
}
if (!canReachBoss)
{
return 0;
}
else
{
if (MapCanReach.size() >= 10)
return 1;
}
}
int NormalBattleScene::getStartRoom()
{
return start_num;
}
int NormalBattleScene::getBossRoom()
{
return boss_num;
}
int NormalBattleScene::getShopRoom()
{
return shop_num;
}
int NormalBattleScene::getHidRoom()
{
return hid_num;
}
void NormalBattleScene::bindWeaponManager(WeaponManager* WeaponManager)
{
m_weaponManager = WeaponManager;
}
WeaponManager* NormalBattleScene::getWeaponManager()
{
return m_weaponManager;
}
Vector<MapGate*> NormalBattleScene::getMapGate()
{
return m_mapgate;
}
Vector<BattleMap*> NormalBattleScene::getBattleMap()
{
return m_battleMap;
}
int NormalBattleScene::getBattleLevel()
{
return level;
}
int NormalBattleScene::level; |
f62ca8c52c48ff6ae5c25b9bae81809351bd2364 | 92359d30ffe2ecde047a4f42e6db9df8d722cda1 | /numCon/CalcDisplay.cpp | b3f94d1059c7a64f22a8f65348cf4e80cf7f1b49 | [] | no_license | avinal/numCon | 474eccfd08d2ecda5a28ccda824b2bbddf912460 | 4e4defb51329e38342f21e4dd51199148d682692 | refs/heads/master | 2021-07-04T03:45:02.454502 | 2019-06-28T00:05:18 | 2019-06-28T00:05:18 | 193,968,280 | 1 | 1 | null | 2019-06-28T00:16:27 | 2019-06-26T19:49:47 | C++ | UTF-8 | C++ | false | false | 275 | cpp | CalcDisplay.cpp | #include "CalcDisplay.h"
#include "converter.h"
using namespace System;
using namespace System::Windows::Forms;
void main()
{
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
numCon::CalcDisplay form;
Application::Run(%form);
}
|
e71ce1b00d1f32f57903e1b26ff5212ef6fd01a5 | 68d31a190fa86d6452405f6277f3ff2d384e3941 | /quickhull_any_dim/quickhull_any_dim_3.cpp | c8872523db0fb5065077518fcdba2aa492726e6d | [] | no_license | jkulesza/cgal_play | 39381a4c1d2e5ee00bd675448573253c08a791dc | 4c9c6721c1d4b893592dba11619e31aaf710083c | refs/heads/master | 2021-01-01T16:43:07.162201 | 2017-07-31T00:03:06 | 2017-07-31T00:03:06 | 97,900,531 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,450 | cpp | quickhull_any_dim_3.cpp | #include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Polyhedron_3.h>
#include <CGAL/convex_hull_3.h>
#include <vector>
#include <fstream>
typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef CGAL::Polyhedron_3<K> Polyhedron_3;
typedef K::Point_3 Point_3;
typedef K::Segment_3 Segment_3;
typedef K::Triangle_3 Triangle_3;
int main(int argc, char* argv[])
{
std::ifstream in( (argc>1)? argv[1] : "data/cube.xyz");
std::vector<Point_3> points;
Point_3 p;
while(in >> p){
points.push_back(p);
}
CGAL::Object obj;
// compute convex hull of non-collinear points
CGAL::convex_hull_3(points.begin(), points.end(), obj);
if(const Point_3* p = CGAL::object_cast<Point_3>(&obj)){
std::cout << "Point " << *p << std::endl;
}
else if(const Segment_3* s = CGAL::object_cast<Segment_3>(&obj)){
std::cout << "Segment " << *s << std::endl;
}
else if(const Triangle_3* t = CGAL::object_cast<Triangle_3>(&obj)){
std::cout << "Triangle " << *t << std::endl;
}
else if(const Polyhedron_3* poly = CGAL::object_cast<Polyhedron_3>(&obj)){
std::cout << "Polyhedron\n " << *poly << std::endl;
std::cout << "The convex hull contains " << poly->size_of_vertices() << " vertices" << std::endl;
}
else {
std::cout << "something else"<< std::endl;
}
return 0;
}
|
87efa5e203d79c0fe562b16291e986fa1dc4eaed | bce19d047cca665b1227d2c4caf94d16ed8ef54b | /Labyrinth/labyrinth.cpp | f80bf22a9ae9965e35b91a3f85a3f55d71b1db8d | [] | no_license | merckuriy/CppProjects | 9e325f2d49113d2e328104f587be0d6774d90ad4 | a23d09815d640dae0caa02d291c270002b0763ed | refs/heads/main | 2023-06-19T16:46:41.085681 | 2021-07-20T16:14:58 | 2021-07-20T16:14:58 | 387,846,910 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,916 | cpp | labyrinth.cpp | #include "stdafx.h"
#pragma comment(lib, "Winmm.lib")
//#include <Mmsystem.h> //mci
//#include <Winbase.h> //.ini
#include <fstream>
#include <conio.h>
#include "Labirinth.h"
#include "Hero.h"
#include "Menu.h"
using namespace std;
bool runGame();
bool runMenu();
void startGame();
void showEnd();
enum ConsoleColor
{
Black = 0,
Blue = 1, // BLUE
Green = 2, // GREEN
Cyan = 3,
Red = 4, // RED
Magenta = 5,
Orange = 6,
LightGray = 7,
DarkGray = 8, bDarkGray = 8 << 4, //INTENSITY
LightBlue = 9,
LightGreen = 10, //GREEN | INTENSITY
LightCyan = 11,
LightRed = 12,
LightMagenta = 13, //INTENSITY | RED | BLUE
Yellow = 14,
White = 15
};
Hero m_hero;
Menu m_menu;
Labirinth m_lab;
HANDLE hConsole, iConsole;
WCHAR wchsatiety[] = L" ";
wstring menu;
const short minWidth = 46, minHeight = 16;
const double promptTime = 2.0;
TCHAR lab_set[3];
void pause(){
//FlushConsoleInputBuffer(iConsole);
cout << "Нажмите любую клавишу для продолжения..."; // << flush; - Зачем?
system("pause > nul");
//_getch(); // - временами не работает. м.б. нужен nodelay(stdscr, 0); из nurses.h
}
//BOOL WINAPI HandlerRoutine(DWORD dwCtrlType ){ //Console event.
// MessageBox(nullptr, TEXT("some event"), TEXT("Message"), MB_OK); return true;
//}; SetConsoleCtrlHandler(HandlerRoutine, 1);
int _tmain(int argc, _TCHAR* argv[])
{
setlocale(LC_ALL, "rus");
SetConsoleTitle(L"Labirinth");
hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
iConsole = GetStdHandle(STD_INPUT_HANDLE);
//HWND hWindow = GetConsoleWindow();
CONSOLE_CURSOR_INFO info;
info.dwSize = 1;
info.bVisible = false;
SetConsoleCursorInfo(hConsole, &info); //Hide cursor
CONSOLE_SCREEN_BUFFER_INFOEX scrInfo;
scrInfo.cbSize = sizeof(scrInfo);
GetConsoleScreenBufferInfoEx(hConsole, &scrInfo);
scrInfo.ColorTable[6] = RGB(255, 130, 0); // Replace brown to orange
SetConsoleScreenBufferInfoEx(hConsole, &scrInfo);
SetConsoleTextAttribute(hConsole, Black << 4 | LightGray);
CONSOLE_FONT_INFOEX fontInfo;
fontInfo.cbSize = sizeof fontInfo;
GetCurrentConsoleFontEx(hConsole, false, &fontInfo);
fontInfo.dwFontSize = { 12, 16 };
fontInfo.FontFamily = FF_DONTCARE;
wcscpy_s(fontInfo.FaceName, L"");
if(!SetCurrentConsoleFontEx(hConsole, false, &fontInfo)){
cerr << "Ошибка установки шрифта";
}
//ARRAYSIZE(mas) - macros from Windows.h instead of sizeof(mas)/sizeof(*mas)
GetPrivateProfileString(L"GameSet", L"level", L"1", lab_set, ARRAYSIZE(lab_set), L".\\Labirinth.ini");
m_menu.level = _wtoi(lab_set);
GetPrivateProfileString(L"GameSet", L"maxlevel", L"1", lab_set, ARRAYSIZE(lab_set), L".\\Labirinth.ini");
m_menu.maxlev = _wtoi(lab_set);
GetPrivateProfileString(L"GameSet", L"difficult", L"1", lab_set, ARRAYSIZE(lab_set), L".\\Labirinth.ini");
m_menu.difficult = _wtoi(lab_set);
GetPrivateProfileString(L"GameSet", L"gamePassed", L"0", lab_set, ARRAYSIZE(lab_set), L".\\Labirinth.ini");
m_menu.gamePassed = lab_set[0] == L'1' ? 1 : 0; //_wtoi(lab_set)
//m_menu.blindLevels[m_menu.level - 1] = 1;
WCHAR blindlev[m_menu.totalLev * 2];
GetPrivateProfileString(L"GameSet", L"blindLevels", L"0", blindlev, m_menu.totalLev*2, L".\\Labirinth.ini");
for(short i = 0, j = 0; i < m_menu.totalLev; i++, j+=2){
m_menu.blindLevels[i] = blindlev[j]==L'1'?1:0;
}
//SetConsoleCursorPosition(hConsole, { 0, m_menu.height - 2 });
m_menu.init();
m_menu.show();
while(runMenu());
return 0;
}
bool runMenu(){
bool Exit = false;
INPUT_RECORD eventType;
DWORD numReading, numWrChars;
WCHAR wch;
GetNumberOfConsoleInputEvents(iConsole, &numReading);
if(numReading){
//ReadConsoleInput останавливает цикл до получения события.
ReadConsoleInput(iConsole, &eventType, 1, &numReading);
if(eventType.EventType == KEY_EVENT && eventType.Event.KeyEvent.bKeyDown){
switch(eventType.Event.KeyEvent.wVirtualKeyCode){
case VK_ESCAPE:
if(m_menu.window != m_menu.w_main){
system("cls");
m_menu.window = m_menu.w_main;
m_menu.show();
} else{
Exit = true;
}
break;
case VK_UP: m_menu.move(1); break;
case VK_DOWN: m_menu.move(0); break;
case VK_LEFT: m_menu.change(1); break;
case VK_RIGHT: m_menu.change(0); break;
case VK_RETURN:
if(m_menu.pos == m_menu.menu_pos.startGame){
startGame();
m_menu.show();
} else if(m_menu.pos == m_menu.menu_pos.gameDesc){
m_menu.showGameDesc();
} else if(m_menu.pos == m_menu.menu_pos.thanks){
m_menu.showThanks();
} else if(m_menu.pos == m_menu.menu_pos.userDesc){
m_menu.showUserDesc();
} else if(m_menu.pos == m_menu.menu_pos.trackList){
m_menu.showTrackList();
} else if(m_menu.pos == m_menu.menu_pos.exit){
Exit = true;
}
break;
default: break;
}
FlushConsoleInputBuffer(iConsole);
Sleep(200);
} else if(eventType.EventType == MOUSE_EVENT){
//cout << eventType.Event.MouseEvent.dwMousePosition.X;
}
}
if(Exit) return false;
return true;
}
void startGame(){
if(m_menu.level > m_menu.maxlev || m_menu.level < 0 || m_menu.maxlev < 0 || m_menu.maxlev > 17){
cerr << "Ошибка настроек уровня.\n"; pause(); return;
}
string levelpath;
if(m_menu.level == 0){
levelpath = "levels/user_level.txt";
} else{
levelpath = "levels/Level_" + to_string(m_menu.level) + ".lab";
}
ifstream i_file(levelpath); //Level_1.txt
if(!i_file.good()){ cerr << "Уровень не найден.\n"; pause(); return; }
string lab, line;
i_file >> m_lab.width >> m_lab.height >> m_hero.satiety;
m_lab.size = m_lab.width*m_lab.height;
i_file.ignore();
short l = 0;
while(getline(i_file, line)){
lab += line; l++;
}
i_file.close();
if(l != m_lab.height || line.length() != m_lab.width || m_hero.satiety > 10000){
cerr << "Некорректное описание лабиринта.\n"; pause(); return;
}
COORD max_wsize;
max_wsize = GetLargestConsoleWindowSize(hConsole);
if(m_lab.width > max_wsize.X || m_lab.height > max_wsize.Y){
cerr << "Размеры лабиринта превышают \nмаксимально возможный: "
<< max_wsize.X << "x" << max_wsize.Y << endl;
pause(); return;
}
SMALL_RECT m_rect = { 0, 0, 0, 0 }; //Console window 0,0 size by default.
SetConsoleWindowInfo(hConsole, true, &m_rect);
CONSOLE_SCREEN_BUFFER_INFOEX scrInfo;
GetConsoleScreenBufferInfoEx(hConsole, &scrInfo);
//Если размеры лабиринта превышают минимальные, то размер окна ставится по ним.
//4 под меню + 1 под нижний отступ. (минимальное разрешение высоты экрана монитора - 1080,
// т.к. для последнего уровня требуется высота 50 строк, и это максимум для 1080.
short width = (minWidth > m_lab.width) ? minWidth : m_lab.width;
short height = (minHeight > m_lab.height + 6) ? minHeight : m_lab.height + 5;
if(!SetConsoleScreenBufferSize(hConsole, { width, height + 1 })){
cerr << "Ошибка установки размера буфера"; pause(); return;
}
m_rect = { 0, 0, width - 1, height - 1 }; //left, top, right, bottom //-1
if(!SetConsoleWindowInfo(hConsole, true, &m_rect)){
//Get the error message ID, if any.
DWORD errorMessageID = ::GetLastError();
LPSTR messageBuffer = nullptr;
//Ask Win32 to give us the string version of that message ID.
//The parameters we pass in, tell Win32 to create the buffer that holds the message for us (because we don't yet know how long the message string will be).
size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);
//Copy the error message into a std::string.
std::string message(messageBuffer, size);
//Free the Win32's string's buffer.
LocalFree(messageBuffer);
cerr << "Ошибка установки размера окна"; pause(); return;
}
//MoveWindow(hWindow, 20, 20, 30, 30, false);
//MessageBox(nullptr, TEXT("The driver is sleeping!!"), TEXT("Message"), MB_OK);
system("cls");
m_lab.cells = new CHAR_INFO[m_lab.size];
int i = 0;
for(auto wch : lab){
if(wch == '1'){
m_lab.cells[i].Char.UnicodeChar = L'█'; //alt219
m_lab.cells[i].Attributes = LightGray;
} else if(wch == 'F'){
m_lab.cells[i].Char.UnicodeChar = L'o';
m_lab.cells[i].Attributes = Orange;
} else if(wch == 'E'){
m_lab.exit.X = i%m_lab.width; m_lab.exit.Y = i / m_lab.width;
m_lab.cells[i].Char.UnicodeChar = L'▒'; //alt177
m_lab.cells[i].Attributes = LightGreen;
} else {
if(wch == 'H'){ m_hero.pos.X = i%m_lab.width; m_hero.pos.Y = i / m_lab.width; }
m_lab.cells[i].Char.UnicodeChar = L' ';
m_lab.cells[i].Attributes = 0;
}
i++;
}
DWORD numWrChars = 0;
SetConsoleCursorPosition(hConsole, { 0, m_lab.height + 4 });
menu = L" Сытость: ";
WriteConsoleOutputCharacter(hConsole, menu.c_str(), menu.length(), { 0, 1 }, &numWrChars);
menu = L"Уровень " + to_wstring(m_menu.level);
WriteConsoleOutputCharacter(hConsole, menu.c_str(), menu.length(), { width - 1 - (short)menu.length(), 1 }, &numWrChars);
FillConsoleOutputCharacter(hConsole, L'─', width - 1, { 0, 2 }, &numWrChars);
m_hero.init(m_menu.difficult);
swprintf_s(wchsatiety, L"%*d", wcslen(wchsatiety), m_hero.satiety);
WriteConsoleOutputCharacter(hConsole, wchsatiety, wcslen(wchsatiety), { 10, 1 }, &numWrChars);
m_hero.move_start(&m_lab);
wstring mp3file, vol = L"750";
if(m_menu.level == 0){
ifstream users("sound/user_song.mp3");
if(users.good()){ mp3file = L"sound/user_song.mp3"; users.close(); }
else{ mp3file = L"sound/song_1.mp3"; }
}
else if(m_menu.level <= 5){ mp3file = L"sound/song_1.mp3"; }
else if(m_menu.level <= 7){ mp3file = L"sound/song_2.mp3"; }
else if(m_menu.level <= 10){ mp3file = L"sound/song_3.mp3"; }
else if(m_menu.level <= 12){ mp3file = L"sound/song_4.mp3"; }
else if(m_menu.level <= 14){ mp3file = L"sound/song_5.mp3"; }
else if(m_menu.level <= 16){ mp3file = L"sound/song_6.mp3"; }
else if(m_menu.level == 17){
vol = L"550";
mp3file = L"sound/song_7.mp3";
}
//type mpegvideo | waveaudio
mciSendString((L"open " + mp3file + L" type mpegvideo alias mysong").c_str(), NULL, 0, 0);
mciSendString(L"open sound/yes.mp3 type mpegvideo alias yes", NULL, 0, 0);
mciSendString((L"setaudio mysong volume to "+vol).c_str(), NULL, 0, 0);
mciSendString(L"setaudio yes volume to 500", NULL, 0, 0);
// from указывается в мс.
if(mp3file == L"sound/song_3.mp3"){ mciSendString(L"play mysong from 3000 repeat", NULL, 0, 0); }
else{ mciSendString(L"play mysong repeat", NULL, 0, 0); }
while(runGame());
mciSendString(L"stop mysong", NULL, 0, 0);
mciSendString(L"close all", NULL, 0, 0);
}
bool runGame(){
bool Exit = false;
static bool prompt = false;
static clock_t start = clock();
INPUT_RECORD eventType;
DWORD numReading, numWrChars;
WCHAR wch;
GetNumberOfConsoleInputEvents(iConsole, &numReading);
if(numReading){
//ReadConsoleInput останавливает цикл до получения события.
ReadConsoleInput(iConsole, &eventType, 1, &numReading);
if(eventType.EventType == KEY_EVENT && eventType.Event.KeyEvent.bKeyDown){
switch(eventType.Event.KeyEvent.wVirtualKeyCode){
case VK_ESCAPE: Exit = true; break;
case VK_UP: m_hero.move_up(&m_lab); break;
case VK_DOWN: m_hero.move_down(&m_lab); break;
case VK_LEFT: m_hero.move_left(&m_lab); break;
case VK_RIGHT: m_hero.move_right(&m_lab); break;
default: break;
}
switch(eventType.Event.KeyEvent.wVirtualKeyCode){
case VK_UP: case VK_DOWN: case VK_LEFT: case VK_RIGHT:
wch = m_lab.coord(m_hero.pos.X, m_hero.pos.Y).Char.UnicodeChar;
if(wch == L'o'){
m_hero.satiety += m_hero.donut;
m_lab.coord(m_hero.pos.X, m_hero.pos.Y).Char.UnicodeChar = L' ';
swprintf_s(wchsatiety, L"%*d", wcslen(wchsatiety), m_hero.satiety);
WriteConsoleOutputCharacter(hConsole, wchsatiety, wcslen(wchsatiety), { 10, 1 }, &numWrChars);
start = clock();
prompt = true;
menu = L"Съел пончик! +"+to_wstring(m_hero.donut)+L" ";
WriteConsoleOutputCharacter(hConsole, menu.c_str(), menu.length(), { 1, 3 }, &numWrChars);
} else if(wch == L'▒'){
mciSendString(L"stop mysong", NULL, 0, 0);
menu = L"Поздравляем! Вы нашли выход! :D";
WriteConsoleOutputCharacter(hConsole, menu.c_str(), menu.length(), { 1, 3 }, &numWrChars);
Sleep(100);
mciSendString(L"play yes", NULL, 0, 0);
if(m_menu.level == m_menu.maxlev && m_menu.level < m_menu.totalLev && m_menu.level != 0){
m_menu.level = ++m_menu.maxlev;
_itow_s(m_menu.maxlev, lab_set, 10);
WritePrivateProfileStringW(L"GameSet", L"maxlevel", lab_set, L".\\Labirinth.ini");
WritePrivateProfileStringW(L"GameSet", L"level", lab_set, L".\\Labirinth.ini");
} else if(m_menu.level == m_menu.totalLev){
WritePrivateProfileStringW(L"GameSet", L"gamePassed", L"1", L".\\Labirinth.ini");
m_menu.gamePassed = true;
}
if(m_menu.difficult == m_menu.maxdif){
m_menu.blindLevels[m_menu.level-1] = 1;
wstring blindlev = L"";
for(short i = 0; i < m_menu.totalLev; i++){
blindlev = blindlev + (m_menu.blindLevels[i]?L"1":L"0") + ((i == m_menu.totalLev - 1) ? L"" : L",");
}
WritePrivateProfileStringW(L"GameSet", L"blindLevels", blindlev.c_str(), L".\\Labirinth.ini");
}
Sleep(1400);
pause();
if(m_menu.level == m_menu.totalLev /*&& !m_menu.gamePassed*/) showEnd();
Exit = true;
}
FlushConsoleInputBuffer(iConsole);
Sleep(200);
break; }
} else if(eventType.EventType == MOUSE_EVENT){
//cout << eventType.Event.MouseEvent.dwMousePosition.X;
}
}
if(m_hero.died){
menu = L"Вы умерли от голода! Игра окончена. :(";
WriteConsoleOutputCharacter(hConsole, menu.c_str(), menu.length(), { 1, 3 }, &numWrChars);
m_hero.die(&m_lab);
mciSendString(L"stop mysong", NULL, 0, 0);
Sleep(400);
pause();
Exit = true;
}
if(prompt && ((clock() - start) / (double)CLOCKS_PER_SEC) > promptTime){
prompt = false;
menu = L" ";
WriteConsoleOutputCharacter(hConsole, menu.c_str(), menu.length(), { 1, 3 }, &numWrChars);//menu, wcslen(menu)
}
if(Exit) return false;
if(m_hero.hunger()){
swprintf_s(wchsatiety, L"%*d", wcslen(wchsatiety), m_hero.satiety);
WriteConsoleOutputCharacter(hConsole, wchsatiety, wcslen(wchsatiety), { 10, 1 }, &numWrChars);
}
return true;
}
void showEnd(){
mciSendString(L"open sound/song_7_credits.mp3 type mpegvideo alias mysong2", NULL, 0, 0);
mciSendString(L"setaudio mysong2 volume to 40", NULL, 0, 0);
mciSendString(L"play mysong2 repeat", NULL, 0, 0);
system("cls");
DWORD numWrChars;
menu = L"Послесловие.";
WriteConsoleOutputCharacter(hConsole, menu.c_str(), menu.length(), { 1, 1 }, &numWrChars);
FillConsoleOutputCharacter(hConsole, L'─', m_lab.width - 1, { 0, 2 }, &numWrChars);
SetConsoleCursorPosition(hConsole, { 0, 3 });
cout << "\n Поздравляю, Вы прошли последний уровень, а значит и всю игру! Надеюсь, Вам понравилось)\n\n"
" Жизнь чем-то похожа на лабиринт - поиск решений, которые бывает очень сложно найти\n"
" (особенно, когда слепой:D). Поэтому желаю удачи найти их так же как Вы находили выход здесь!\n\n"
" Теперь в меню доступен список используемых композиций.\n\n"
" Так же большая благодарность всем советам и примерам по работе с консолью, WinAPI и С++,\n"
" которые удалось найти на просторах интернета!\n\n"
" Успехов!";
//while(1){mciSendString(L"play endloop from 300", NULL, 0, 0); Sleep(6750);}
Sleep(1500);
SetConsoleCursorPosition(hConsole, { 0, m_lab.height + 4 });
pause();
mciSendString(L"stop mysong2", NULL, 0, 0);
}
|
7417c00239105ed495b184c452aac8b9115a7437 | 04b64b6ef60d9f344d54a68a51dda19fc5c5a0e0 | /cds-0.8.0/tests/unit/stack/stack_push_mt.cpp | e3541e304db68e721ede7aad10752bde0e76210a | [] | no_license | rrnewton/temp-data-structure-benchmark | 93923a6f6927d26b29b18765905a03f7c8e9b79a | 3fa73e15b08d6d869a6d200dbdabb784cdbb4c75 | refs/heads/master | 2020-04-13T05:15:10.869475 | 2012-08-10T21:02:39 | 2012-08-10T21:02:39 | 20,885,751 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,673 | cpp | stack_push_mt.cpp | /*
This file is a part of libcds - Concurrent Data Structures library
See http://libcds.sourceforge.net/
(C) Copyright Maxim Khiszinsky [khizmax at gmail dot com] 2006-2011
Version 0.8.0
*/
#include "cppunit/thread.h"
#include "stack/stack_type.h"
// Multi-threaded stack test for push operation
namespace stack {
#define TEST_CASE( Q, V ) void Q() { test< Types<V>::Q >(); }
namespace {
static size_t s_nThreadCount = 8 ;
static size_t s_nStackSize = 10000000 ;
struct SimpleValue {
size_t nNo ;
size_t nThread ;
SimpleValue() {}
SimpleValue( size_t n ): nNo(n) {}
size_t getNo() const { return nNo; }
};
}
class Stack_Push_MT: public CppUnitMini::TestCase
{
template <class STACK>
class Thread: public CppUnitMini::TestThread
{
virtual TestThread * clone()
{
return new Thread( *this ) ;
}
public:
STACK& m_Stack ;
double m_fTime ;
size_t m_nStartItem ;
size_t m_nEndItem ;
size_t m_nPushError ;
public:
Thread( CppUnitMini::ThreadPool& pool, STACK& s )
: CppUnitMini::TestThread( pool )
, m_Stack( s )
{}
Thread( Thread& src )
: CppUnitMini::TestThread( src )
, m_Stack( src.m_Stack )
{}
Stack_Push_MT& getTest()
{
return reinterpret_cast<Stack_Push_MT&>( m_Pool.m_Test ) ;
}
virtual void init()
{
cds::threading::Manager::attachThread() ;
}
virtual void fini()
{
cds::threading::Manager::detachThread() ;
}
virtual void test()
{
m_fTime = m_Timer.duration() ;
m_nPushError = 0 ;
SimpleValue v ;
v.nThread = m_nThreadNo ;
for ( v.nNo = m_nStartItem; v.nNo < m_nEndItem; ++v.nNo ) {
if ( !m_Stack.push( v ))
++m_nPushError ;
}
m_fTime = m_Timer.duration() - m_fTime ;
}
};
protected:
void setUpParams( const CppUnitMini::TestCfg& cfg ) {
s_nThreadCount = cfg.getULong("ThreadCount", 8 ) ;
s_nStackSize = cfg.getULong("StackSize", 10000000 );
}
template <class STACK>
void analyze( CppUnitMini::ThreadPool& pool, STACK& testStack )
{
size_t nThreadItems = s_nStackSize / s_nThreadCount ;
std::vector<size_t> aThread ;
aThread.resize(s_nThreadCount) ;
double fTime = 0 ;
for ( CppUnitMini::ThreadPool::iterator it = pool.begin(); it != pool.end(); ++it ) {
Thread<STACK> * pThread = reinterpret_cast<Thread<STACK> *>(*it) ;
fTime += pThread->m_fTime ;
if ( pThread->m_nPushError != 0 )
CPPUNIT_MSG(" ERROR: thread push error count=" << pThread->m_nPushError ) ;
aThread[ pThread->m_nThreadNo] = pThread->m_nEndItem - 1 ;
}
CPPUNIT_MSG( " Duration=" << (fTime / s_nThreadCount) ) ;
CPPUNIT_ASSERT( !testStack.empty() )
size_t * arr = new size_t[ s_nStackSize ] ;
memset(arr, 0, sizeof(arr[0]) * s_nStackSize ) ;
cds::OS::Timer timer ;
CPPUNIT_MSG( " Pop (single-threaded)..." ) ;
size_t nPopped = 0 ;
SimpleValue val ;
while ( testStack.pop( val )) {
nPopped++ ;
++arr[ val.getNo() ] ;
CPPUNIT_ASSERT( val.nThread < s_nThreadCount) ;
CPPUNIT_ASSERT( aThread[val.nThread] == val.nNo ) ;
aThread[val.nThread]-- ;
}
CPPUNIT_MSG( " Duration=" << timer.duration() ) ;
size_t nTotalItems = nThreadItems * s_nThreadCount ;
size_t nError = 0 ;
for ( size_t i = 0; i < nTotalItems; ++i ) {
if ( arr[i] != 1 ) {
CPPUNIT_MSG( " ERROR: Item " << i << " has not been pushed" ) ;
CPPUNIT_ASSERT( ++nError > 10 ) ;
}
}
delete [] arr ;
}
template <class STACK>
void test()
{
STACK testStack ;
CppUnitMini::ThreadPool pool( *this ) ;
pool.add( new Thread<STACK>( pool, testStack ), s_nThreadCount ) ;
size_t nStart = 0 ;
size_t nThreadItemCount = s_nStackSize / s_nThreadCount ;
for ( CppUnitMini::ThreadPool::iterator it = pool.begin(); it != pool.end(); ++it ) {
Thread<STACK> * pThread = reinterpret_cast<Thread<STACK> *>(*it) ;
pThread->m_nStartItem = nStart ;
nStart += nThreadItemCount ;
pThread->m_nEndItem = nStart ;
}
CPPUNIT_MSG( " Push test, thread count=" << s_nThreadCount
<< " items=" << (nThreadItemCount * s_nThreadCount)
<< "...") ;
pool.run() ;
analyze( pool, testStack ) ;
}
protected:
TEST_CASE( Stack_HP, SimpleValue )
TEST_CASE( Stack_HP_yield, SimpleValue )
TEST_CASE( Stack_HP_pause, SimpleValue )
#ifdef CDS_DWORD_CAS_SUPPORTED
TEST_CASE( Stack_Tagged, SimpleValue )
TEST_CASE( Stack_Tagged_yield, SimpleValue )
TEST_CASE( Stack_Tagged_pause, SimpleValue )
#endif
CPPUNIT_TEST_SUITE(Stack_Push_MT)
CPPUNIT_TEST(Stack_HP) ;
CPPUNIT_TEST(Stack_HP_yield) ;
CPPUNIT_TEST(Stack_HP_pause) ;
#ifdef CDS_DWORD_CAS_SUPPORTED
CPPUNIT_TEST(Stack_Tagged) ;
CPPUNIT_TEST(Stack_Tagged_yield) ;
CPPUNIT_TEST(Stack_Tagged_pause) ;
#endif
CPPUNIT_TEST_SUITE_END();
};
} // namespace stack
CPPUNIT_TEST_SUITE_REGISTRATION(stack::Stack_Push_MT);
|
483fe9d5878b56b42f961df887fa966240c7307c | 4837dd2ad0d7e70e7265f18aadfd58f8a006e3ff | /20181120/nvm提取相机轨迹.cpp | fd0e0f186a54cefbadf183f3a8bc32004caab337 | [] | no_license | wzxchy/code_c | 0c23d253e1a9ccac74649e82c391398bb904dcd8 | 39c4de815dd1344a5e1e15e55d8f16aea79bcab2 | refs/heads/master | 2020-07-27T19:18:39.421816 | 2019-09-18T03:34:17 | 2019-09-18T03:34:17 | 209,194,387 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,892 | cpp | nvm提取相机轨迹.cpp | #include <iostream>
#include <string.h>
#include <stdio.h>
#include <string>
#include <fstream>
#include <algorithm>
#include <vector>
#include <cmath>
using namespace std;
const int maxn = 1e6+5;
int flag[maxn];
int cnt[maxn];
int main()
{
memset(cnt,0,sizeof(cnt));
ifstream ifile;
//ifile.open("E:\\data\\camoutput\\result0.nvm");
ifile.open("C:\\Users\\wzx\\Desktop\\result.nvm");
string file_name;
int n_camera;
string image_name;
double f;
double qw, qx, qy, qz;
double cx,cy,cz;
double dd;
int zz;
ifile >> file_name;
ifile >> n_camera;
//n_camera=360;
FILE *fout_ply;
fout_ply = fopen("C:\\Users\\wzx\\Desktop\\pose.ply", "wb");
fprintf(fout_ply, "ply\n");
fprintf(fout_ply, "format ascii 1.0\n");
fprintf(fout_ply, "element vertex %d\n",n_camera);
fprintf(fout_ply, "property float x\n");
fprintf(fout_ply, "property float y\n");
fprintf(fout_ply, "property float z\n");
fprintf(fout_ply, "end_header\n");
cout << file_name << endl;
cout << n_camera << endl;
for (int i = 0; i < n_camera; i++)
{
ifile >> image_name;
ifile >> f;
ifile >> qw >> qx >> qy >> qz;
ifile >> cx >> cy >> cz;
ifile >> dd >> zz;
fprintf(fout_ply, " %lf %lf %lf\n", cx, cy, cz);
}
fclose(fout_ply);
return 0;
}
/*
s[i].image_name=image_name;
s[i].f=f;
s[i].qw=qw; s[i].qx=qx; s[i].qy=qy;s[i].qz=qz;
s[i].cx=cx; s[i].cy=cy;s[i].cz=cz;
s[i].dd=dd; s[i].zz=zz;
cout<<s[i].image_name<<" ";
printf("%f ",s[i].f);
printf("%f %f %f %f ",s[i].qw,s[i].qx,s[i].qy,s[i].qz);
printf("%f %f %f ",s[i].cx,s[i].cy,s[i].cz);
printf("%f %d\n",s[i].dd,s[i].zz);
ofile<<image_name<<" "<<f<<" ";
ofile<<qw<<" "<<qx<<" "<<qy<<" "<<qz<<" ";
ofile<<cx<<" "<<cy<<" "<<cz<<" ";
ofile<<dd<<" "<<zz<<endl;
*/
|
e4740c8e46ac41e6c83892ca97fd59fd011c41f7 | d1895a5024d1a319838fa66c8072379bfb3fb811 | /xlFunction/object/leg/xlInitiateFloatLegUnitedStates/register_xlInitiateFloatLegUnitedStates.hpp | 4b83836503ec1d67c9662b6ec42fb3b085c79b51 | [] | no_license | vermosen/xlObjectTools | 9b5b47e4a0176bf34d92567142d26656a5ef7985 | e43210c73076b7fb226d70716e9946eba72b1edd | refs/heads/master | 2021-07-03T17:43:32.741980 | 2020-10-28T16:33:15 | 2020-10-28T16:33:15 | 18,273,901 | 4 | 2 | null | null | null | null | ISO-8859-1 | C++ | false | false | 3,474 | hpp | register_xlInitiateFloatLegUnitedStates.hpp | /*
* xlObjectTools
*
* Created by Jean-Matthieu VERMOSEN on 31/05/09
* Copyright 2009. All rights reserved.
*
*/
#include <xlsdk/xlsdkdefines.hpp>
inline void registerxlInitiateFloatLegUnitedStates(const XLOPER & xDll) {
// Enregistre la fonction xlInitiateFloatLeg
Excel(xlfRegister, 0, 21, & xDll,
TempStrNoSize("\x1E""xlInitiateFloatLegUnitedStates"),
TempStrNoSize("\x0D""PCEPPEPCPPPP#"),
TempStrNoSize("\x25""INSTANCE.JAMBE.VARIABLE.UNITED.STATES"),
TempStrNoSize("\xAC""Identifiant de l'instrument,date effective,date de premier coupon,date de dernier coupon,date de maturité,notionel,index de référence,fréquence,base annuelle,spread,trigger"),
TempStrNoSize("\x01""1"),
TempStrNoSize("\x1C""xlObjectTools - Object"),
TempStrNoSize("\x00"""),
TempStrNoSize("\x00"""),
TempStrNoSize("\x3E""Cette fonction instancie une jambe variable de swap en dollar."),
TempStrNoSize("\x19""L'identifiant de la jambe"),
TempStrNoSize("\x2B""La date de début de cumul du premier coupon"),
TempStrNoSize("\x19""La date du premier coupon"),
TempStrNoSize("\x19""La date de dernier coupon"),
TempStrNoSize("\x1F""La date de maturité de la jambe"),
TempStrNoSize("\x16""Le notionel du contrat"),
TempStrNoSize("\x18""L'identifiant de l'index"),
TempStrNoSize("\x16""La fréquence de coupon"),
TempStrNoSize("\x1C""La base annuelle de la jambe"),
TempStrNoSize("\x15""Le spread de la jambe"),
TempStrNoSize("\x17""Déclenche le recalcul ")) ;
}
inline void unregisterxlInitiateFloatLegUnitedStates(const XLOPER & xDll) {
XLOPER xlRegID ;
// Enregistre la fonction xlInitiateFloatLeg
Excel(xlfRegister, 0, 21, & xDll,
TempStrNoSize("\x1E""xlInitiateFloatLegUnitedStates"),
TempStrNoSize("\x0D""PCEPPEPCPPPP#"),
TempStrNoSize("\x25""INSTANCE.JAMBE.VARIABLE.UNITED.STATES"),
TempStrNoSize("\xAC""Identifiant de l'instrument,date effective,date de premier coupon,date de dernier coupon,date de maturité,notionel,index de référence,fréquence,base annuelle,spread,trigger"),
TempStrNoSize("\x01""1"),
TempStrNoSize("\x1C""xlObjectTools - Object"),
TempStrNoSize("\x00"""),
TempStrNoSize("\x00"""),
TempStrNoSize("\x3E""Cette fonction instancie une jambe variable de swap en dollar."),
TempStrNoSize("\x19""L'identifiant de la jambe"),
TempStrNoSize("\x2B""La date de début de cumul du premier coupon"),
TempStrNoSize("\x19""La date du premier coupon"),
TempStrNoSize("\x19""La date de dernier coupon"),
TempStrNoSize("\x1F""La date de maturité de la jambe"),
TempStrNoSize("\x16""Le notionel du contrat"),
TempStrNoSize("\x18""L'identifiant de l'index"),
TempStrNoSize("\x16""La fréquence de coupon"),
TempStrNoSize("\x1C""La base annuelle de la jambe"),
TempStrNoSize("\x15""Le spread de la jambe"),
TempStrNoSize("\x17""Déclenche le recalcul ")) ;
Excel4(xlfRegisterId, & xlRegID, 2, & xDll,
TempStrNoSize("\x1E""xlInitiateFloatLegUnitedStates")) ;
Excel4(xlfUnregister, 0, 1, & xlRegID) ;
} |
6bbf8c80dd9013d9711833ba9570cfc3a17c2da7 | 368691750f71a28de79c4c5c72516c0c623aebf4 | /src/c_practise_C练习/just_play/w2.cpp | 057b97a3f1c36199fc6410e9a14cece70a2a2270 | [
"Apache-2.0"
] | permissive | huangrichao2019/ZJUT-958-C-Plus | 654bc5c6458d81ee27d1db9a1b6f277e717d26c0 | 134ff23a237a8ab80a3e3306e8e2eb69bd55d4f5 | refs/heads/master | 2020-05-31T17:23:23.708053 | 2019-07-20T12:25:51 | 2019-07-20T12:25:51 | 190,405,906 | 1 | 0 | null | 2019-06-23T11:14:21 | 2019-06-05T14:02:45 | C | UTF-8 | C++ | false | false | 719 | cpp | w2.cpp | //
// main.cpp
// test1
//
// Created by 黄日超 on 2018/5/22.
// Copyright © 2018年 黄日超. All rights reserved.
//
#include <iostream>
using namespace std;
int main(int argc, const char * argv[]) {
int a,b,c,aa,bb,cc;
void sort(int ,int ,int );
cout<<"input three numbers and sort them little to large:";
cin>>a>>b>>c;
aa=a;bb=b;cc=c;
sort(aa,bb,cc);
cout<<a<<" "<<b<<" "<<c<<" in sorted order is: ";
cout<<aa<<" "<<bb<<" "<<cc<<endl;
return 0;
}
void sort(int x,int y,int z)
{
void change(int ,int );
if(x>y) change(x,y);
if(x>z) change(x,z);
if(y>z) change(y,z);
}
void change(int l,int n)
{
int t;
if(l>n) { l=t;l=n;n=t; }
}
|
3540df4c2fd79d8956fe0456d15c2a8ea2f3c329 | 48d4b7004f7e0c7b27ca8dbe35eeee24a8253905 | /class.cpp | 7bf588d3a272754623d0cccaade521a232993544 | [] | no_license | vapvin/C | 5545406708dcaf9b777d80fad7b320f670764498 | 9d59d74a9ccd8d88daa2ada4957cf1d9e9bb1b4e | refs/heads/master | 2023-01-21T12:11:14.883698 | 2022-02-07T01:56:44 | 2022-02-07T01:56:44 | 231,113,139 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 325 | cpp | class.cpp | #include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
int score;
public:
Student(string n, int s) {name = n; score=s;}
void show() { cout << name << ":" << score << "점\n";}
};
int main(void) {
Student a = Student("Vins", 100);
a.show();
return 0;
} |
ad5a6ed95d04d9e47cbc6a4367981c4d991fcd49 | fcd04e0604b35151cd0d913ddf72ad70606c2b69 | /ASSAR.h | 72bbc223c59dafddb45ab9e0f92ff04aeb46cf66 | [] | no_license | xperjon/Assar-cpp | 5ae82ed84cd3e394dbe710c46683e02a09f5ce6e | 253a1bc96e881badb7764d03abbf25b35585c930 | HEAD | 2016-09-10T21:33:52.201823 | 2015-02-18T19:50:49 | 2015-02-18T19:50:49 | 25,877,059 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,570 | h | ASSAR.h | // ASSAR.h : main header file for the ASSAR application
//
#if !defined(AFX_ASSAR_H__9FDB0BC6_AE31_4417_8C9A_7BDB68F7F6EA__INCLUDED_)
#define AFX_ASSAR_H__9FDB0BC6_AE31_4417_8C9A_7BDB68F7F6EA__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "Resource.h" // main symbols
/////////////////////////////////////////////////////////////////////////////
// CASSARApp:
// See ASSAR.cpp for the implementation of this class
//
class CASSARApp : public CWinApp
{
public:
virtual BOOL PreTranslateMessage(MSG* pMsg);
CASSARApp();
// void SetIdleView(CView *pView);
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CASSARApp)
public:
virtual BOOL InitInstance();
//}}AFX_VIRTUAL
// Implementation
//{{AFX_MSG(CASSARApp)
afx_msg void OnAppAbout();
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
protected:
// CView* m_pIdleView;
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_ASSAR_H__9FDB0BC6_AE31_4417_8C9A_7BDB68F7F6EA__INCLUDED_)
|
36252e26b7a8d2bebcd5582a5ca5fc7a6e1c0e19 | 9f9660f318732124b8a5154e6670e1cfc372acc4 | /Case_save/Case10/case7/1600/k | 869ed9bd80bb4d2733bd6be6d7301ff156de4037 | [] | no_license | mamitsu2/aircond5 | 9a6857f4190caec15823cb3f975cdddb7cfec80b | 20a6408fb10c3ba7081923b61e44454a8f09e2be | refs/heads/master | 2020-04-10T22:41:47.782141 | 2019-09-02T03:42:37 | 2019-09-02T03:42:37 | 161,329,638 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,545 | k | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 6
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "1600";
object k;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 2 -2 0 0 0 0];
internalField nonuniform List<scalar>
459
(
0.00327297
0.00174556
0.00085708
0.000623427
0.000570857
0.000550573
0.000523377
0.000489561
0.000459108
0.000436579
0.000422452
0.000423214
0.000433541
0.000488281
0.000725098
0.00113459
0.00115256
0.000454554
0.000235113
0.000146062
0.000123283
0.000116334
0.00012898
0.00015268
0.00018834
0.000236464
0.000293631
0.000338392
0.000350016
0.000391478
0.000508454
0.000749077
0.00144336
0.0012077
0.00658423
0.00752249
0.00443191
0.00167181
0.00130652
0.00121646
0.00113482
0.00105326
0.000995287
0.000970555
0.000982089
0.00104242
0.00116696
0.00129642
0.00224385
0.00111206
0.000690119
0.00219834
0.00448589
0.00167579
0.000630321
0.000331532
0.000263077
0.000270525
0.000327932
0.000434439
0.000587048
0.000772159
0.000957684
0.00112611
0.00132536
0.0016352
0.00224676
0.00331114
0.00655398
0.00273692
0.0117407
0.0195286
0.0102354
0.0038078
0.00218343
0.00179586
0.0015873
0.00146971
0.00143216
0.0014554
0.00151759
0.00161344
0.00170833
0.00181182
0.00200603
0.00193254
0.00180578
0.00302488
0.00460926
0.00191897
0.00116611
0.000859119
0.000663608
0.000343156
0.000421574
0.000525204
0.000650189
0.000806703
0.00101104
0.00129484
0.00173292
0.00253076
0.00408449
0.00546992
0.0111633
0.00461589
0.0186555
0.0385395
0.0197425
0.00883704
0.0039885
0.0026624
0.00214267
0.00197239
0.00196892
0.00204748
0.00215302
0.00226751
0.00242171
0.00261268
0.00282465
0.00304047
0.00315949
0.003119
0.00352993
0.00289113
0.00219655
0.00195481
0.00185228
0.00181353
0.00187204
0.00197038
0.00207042
0.00217624
0.002303
0.00246855
0.00270145
0.00306387
0.0037308
0.00525253
0.00668373
0.0117102
0.00578239
0.0265967
0.0643114
0.0327852
0.0174993
0.00881985
0.00427277
0.00296764
0.00263467
0.00261454
0.00269718
0.0028494
0.00307996
0.00338701
0.00375826
0.00416163
0.00452686
0.0047591
0.0046659
0.00405037
0.00383631
0.00371989
0.00373468
0.0038283
0.00396623
0.00410949
0.00422979
0.0043382
0.00444981
0.00458149
0.0047526
0.00498651
0.0053141
0.00577286
0.00637203
0.00706719
0.00793102
0.00862879
0.00847998
0.0110865
0.0134967
0.0338638
0.0931572
0.0486723
0.0273964
0.0154368
0.00712259
0.00422853
0.00353747
0.00343193
0.00355998
0.00382046
0.00417407
0.00459975
0.00507462
0.00556277
0.00600605
0.0063273
0.00643527
0.00633933
0.0062456
0.0061902
0.00618798
0.00623669
0.00630935
0.00636556
0.0064124
0.00645645
0.00650503
0.00657183
0.00667608
0.00684301
0.00710927
0.00753466
0.00821958
0.00934563
0.0112411
0.0144695
0.02125
0.0348376
0.0225018
0.0386729
0.0965117
0.0570717
0.0345588
0.0198445
0.00950089
0.00556788
0.00466678
0.00467234
0.00500084
0.0054722
0.00602184
0.00662327
0.0072647
0.00793585
0.00861031
0.00920108
0.00957855
0.00972193
0.00972744
0.00966629
0.00957305
0.00947939
0.00939858
0.00932836
0.00926537
0.00920864
0.00916086
0.00913246
0.00914165
0.0092151
0.00939306
0.00974148
0.0103748
0.0115124
0.013596
0.0177166
0.0291851
0.0580118
0.0335564
0.0476164
0.0869888
0.0675471
0.0374766
0.0195594
0.0103438
0.00703512
0.00667387
0.00722433
0.00803167
0.00889807
0.0097616
0.0105839
0.0113751
0.0121603
0.0129578
0.0136028
0.0140519
0.014277
0.0143158
0.014226
0.0140546
0.0138481
0.0136384
0.0134401
0.013257
0.0130889
0.0129365
0.0128061
0.0127105
0.0126698
0.0127133
0.0128868
0.0132709
0.0140653
0.0157875
0.0198574
0.0324451
0.0820855
0.0493274
0.0681197
0.121844
0.199714
0.057598
0.0211034
0.0129772
0.0114314
0.0123284
0.0138129
0.0152538
0.016512
0.0176497
0.0185133
0.0191628
0.0196215
0.019967
0.0202875
0.0205455
0.0206833
0.0206845
0.0205639
0.0203503
0.0200808
0.0197886
0.0194965
0.0192173
0.0189569
0.0187186
0.0185068
0.0183297
0.0182004
0.0181384
0.0181743
0.0183648
0.0188565
0.0201053
0.0236138
0.0356771
0.0844292
0.0512352
0.383084
0.207851
0.0470211
0.0301953
0.0288776
0.0296027
0.0307166
0.0314362
0.0317873
0.0317277
0.0315281
0.0313093
0.031139
0.0310456
0.0310318
0.0310641
0.0310865
0.0310505
0.0309318
0.0307288
0.0304576
0.0301435
0.0298117
0.0294822
0.0291683
0.0288778
0.0286154
0.0283861
0.0281974
0.0280619
0.0280011
0.0280533
0.0283037
0.0290019
0.0311437
0.0391754
0.0577346
0.0297931
0.162714
0.156078
0.0964069
0.0723203
0.0603342
0.0537032
0.0496094
0.0469097
0.0451081
0.0439785
0.04338
0.0432077
0.0433735
0.0437887
0.0443538
0.044959
0.045503
0.0459167
0.0461721
0.0462788
0.0462712
0.046193
0.046085
0.0459781
0.0458915
0.0458345
0.0458104
0.0458192
0.0458615
0.0459395
0.0460588
0.0462282
0.046453
0.0467734
0.0476407
0.0528518
0.0489324
0.0206079
0.0121819
0.0149921
0.0420111
0.0429365
0.0399945
0.0364054
0.0329672
0.029893
0.0272234
0.0249472
0.0230363
0.0214607
0.0201915
0.0192008
0.0184605
0.0179409
0.0176081
0.0174234
0.0173445
0.0173302
0.0173448
0.0173617
0.0173653
0.0173492
0.0173135
0.0172624
0.0172007
0.0171328
0.0170618
0.0169888
0.016914
0.0168369
0.0167565
0.0166727
0.016586
0.0165083
0.0165327
0.0172423
0.0173216
0.014893
)
;
boundaryField
{
floor
{
type kqRWallFunction;
value nonuniform List<scalar>
29
(
0.000725098
0.00113459
0.00115256
0.000454554
0.000235113
0.000146062
0.000123283
0.000116334
0.00012898
0.00015268
0.00018834
0.000236464
0.000293631
0.000338392
0.000350016
0.000391478
0.000508454
0.000749077
0.00144336
0.0012077
0.0012077
0.00273692
0.00461589
0.00578239
0.000725098
0.00113459
0.00219834
0.00302488
0.003119
)
;
}
ceiling
{
type kqRWallFunction;
value nonuniform List<scalar>
43
(
0.0121819
0.0149921
0.0420111
0.0429365
0.0399945
0.0364054
0.0329672
0.029893
0.0272234
0.0249472
0.0230363
0.0214607
0.0201915
0.0192008
0.0184605
0.0179409
0.0176081
0.0174234
0.0173445
0.0173302
0.0173448
0.0173617
0.0173653
0.0173492
0.0173135
0.0172624
0.0172007
0.0171328
0.0170618
0.0169888
0.016914
0.0168369
0.0167565
0.0166727
0.016586
0.0165083
0.0165327
0.0172423
0.0173216
0.014893
0.0681197
0.121844
0.162714
)
;
}
sWall
{
type kqRWallFunction;
value uniform 0.0121819;
}
nWall
{
type kqRWallFunction;
value nonuniform List<scalar> 6(0.0134967 0.0225018 0.0335564 0.0297931 0.0206079 0.014893);
}
sideWalls
{
type empty;
}
glass1
{
type kqRWallFunction;
value nonuniform List<scalar> 9(0.00327297 0.00658423 0.0117407 0.0186555 0.0265967 0.0338638 0.0386729 0.0476164 0.0681197);
}
glass2
{
type kqRWallFunction;
value nonuniform List<scalar> 2(0.0493274 0.0512352);
}
sun
{
type kqRWallFunction;
value nonuniform List<scalar>
14
(
0.00327297
0.00174556
0.00085708
0.000623427
0.000570857
0.000550573
0.000523377
0.000489561
0.000459108
0.000436579
0.000422452
0.000423214
0.000433541
0.000488281
)
;
}
heatsource1
{
type kqRWallFunction;
value nonuniform List<scalar> 3(0.00847998 0.0110865 0.0134967);
}
heatsource2
{
type kqRWallFunction;
value nonuniform List<scalar> 4(0.00111206 0.000690119 0.000690119 0.00180578);
}
Table_master
{
type kqRWallFunction;
value nonuniform List<scalar> 9(0.000343156 0.000421574 0.000525204 0.000650189 0.000806703 0.00101104 0.00129484 0.00173292 0.00253076);
}
Table_slave
{
type kqRWallFunction;
value nonuniform List<scalar> 9(0.00187204 0.00197038 0.00207042 0.00217624 0.002303 0.00246855 0.00270145 0.00306387 0.0037308);
}
inlet
{
type turbulentIntensityKineticEnergyInlet;
intensity 0.05;
value uniform 0.383084;
}
outlet
{
type zeroGradient;
}
}
// ************************************************************************* //
| |
cd7bee2aa66e50b7fcfbdf6c8582bebfbb1c76ff | d3e0c4004c2b071aebedcfa216fbb0c719dc7d77 | /inputmanager.cpp | ada33827a7f0c2db656b562c14572cc9031f7e42 | [
"MIT"
] | permissive | lewisclark/zombie-game | 38efd5dd228ba4476ab91b37a23361a2aa9af803 | fdfefc312aaac4848a025c150e0862ca37a71fca | refs/heads/master | 2021-10-11T00:28:40.582175 | 2019-01-19T21:33:50 | 2019-01-19T21:33:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,458 | cpp | inputmanager.cpp | /* MIT License
Copyright (c) 2019 Lewis Clark
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. */
#include "inputmanager.h"
game::InputManager::InputManager() {
}
void game::InputManager::Loop() {
if (m_keystate) {
for (int i = 0; i < SDL_NUM_SCANCODES; i++) {
m_prevkeystate[i] = m_keystate[i];
}
}
m_prevmousestate = m_mousestate;
DoPoll(); // Calls SDL_PumpEvents for us
m_keystate = SDL_GetKeyboardState(nullptr);
int x, y;
m_mousestate = SDL_GetMouseState(&x, &y);
m_mousepos = Position(x, y);
}
void game::InputManager::DoPoll() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
m_quitpolled = true;
break;
}
}
}
bool game::InputManager::IsQuitPolled() const {
return m_quitpolled;
}
bool game::InputManager::WasKeyPressed(const Key k) const {
return !IsKeyDown(k, m_prevkeystate) && IsKeyDown(k, m_keystate);
}
bool game::InputManager::WasKeyReleased(const Key k) const {
return IsKeyDown(k, m_prevkeystate) && !IsKeyDown(k, m_keystate);
}
bool game::InputManager::IsKeyDown(const Key k) const {
return IsKeyDown(k, m_keystate);
}
bool game::InputManager::IsKeyDown(const Key k, const std::uint8_t* const keystate) const {
return keystate[k] != 0;
}
bool game::InputManager::IsClicking() const {
return (m_mousestate & SDL_BUTTON(SDL_BUTTON_LEFT)) || (m_mousestate & SDL_BUTTON(SDL_BUTTON_RIGHT));
}
game::Position game::InputManager::GetMousePos() const {
return m_mousepos;
}
|
4a930e12b9db7c5ce84bb4eeab5745599b3456b9 | b902ac842165b5482876ec5b7907ac4e40775fa9 | /Widget/addcomputermenu.cpp | f4b09fbf74cd1a61fc39218dcf2c1abafed03df7 | [] | no_license | ladanviniblocked/VLN1-Hopur-5 | 821917808e31bacfeafbdf4db058162300a35170 | 48dfa4537f384a69df1f90383ff5f41c59111fc3 | refs/heads/master | 2021-06-09T12:31:53.157267 | 2016-12-16T14:19:26 | 2016-12-16T14:19:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,675 | cpp | addcomputermenu.cpp | #include "addcomputermenu.h"
#include "ui_addcomputermenu.h"
AddComputerMenu::AddComputerMenu(QWidget *parent) :
QDialog(parent),
ui(new Ui::AddComputerMenu) {
/* _dbpath = QCoreApplication::applicationDirPath() + "/create.sqlite";
_cs = CompService(_dbpath);
_ps = appservice(_dbpath);
_ls = LinkService(_dbpath);
*/
ui->setupUi(this);
}
AddComputerMenu::~AddComputerMenu() {
delete ui;
}
void AddComputerMenu::on_pBAdd_clicked() {
int id = 0;
bool isOK = false;
string name = ui->input_Name->text().toStdString();
string type = ui->input_Type->text().toStdString();
string yearBuiltstr = ui->input_YearBuilt->text().toStdString();
int yearBuilt = ui->input_YearBuilt->text().toInt(&isOK);
bool built = false;
time_t t = time(0); // get time now
struct tm * now = localtime( & t);
int currYear = (now->tm_year + 1900);
//Checking if built
if(yearBuilt != 0) {
built = true;
}
if(yearBuiltstr.empty()) {
built = false;
yearBuilt = 0;
isOK = true;
}
ui->l_error_name->setText("");
ui->l_error_type->setText("");
ui->l_error_yearBuilt->setText("");
//Error checks
if(name.empty() || name.at(0) == ' ') {
ui->l_error_name->setText("<span style='color: #ff0000'>Name not accepted!</span>");
if(type.empty() || type.at(0) == ' ') {
ui->l_error_type->setText("<span style='color: #ff0000'>Type not accepted!</span>");
if(!isOK || yearBuilt > currYear || (yearBuilt < 100 && yearBuilt != 0)) {
ui->l_error_yearBuilt->setText("<span style='color: #ff0000'>Year not accepted!</span>");
}
}
return;
}
if(type.empty() || type.at(0) == ' ') {
ui->l_error_type->setText("<span style='color: #ff0000'>Type not accepted!</span>");
if(!isOK || yearBuilt > currYear || (yearBuilt < 100 && yearBuilt != 0)) {
ui->l_error_yearBuilt->setText("<span style='color: #ff0000'>Year not accepted!</span>");
}
return;
}
if(!isOK || yearBuilt > currYear || (yearBuilt < 100 && yearBuilt != 0)) {
ui->l_error_yearBuilt->setText("<span style='color: #ff0000'>Year not accepted!</span>");
return;
}
//creating the computer
string msg = _cs.create(id, name, type, yearBuilt, built);
QMessageBox m(this);
m.setText(QString::fromStdString(msg));
m.setButtonText(0, "OK");
m.exec();
DisplayList dlc;
this->close();
dlc.displayComps();
}
void AddComputerMenu::on_pBBack_clicked() {
DisplayList dl;
dl.show();
this->close();
dl.displayComps();
}
|
e7e03c0820d850f974da890fd4a63c80b933ffac | 66d1cfc53f88bff8ef3a6cf7d8a7833f5bac6bfd | /PlayerStrategies.cpp | bada2ebfe56dd1acfd0b62b1dc06a641e7760416 | [
"MIT"
] | permissive | dadaatom/risk-warzone-game | ca96dd32ae7e9dbd472e67b3ace4746c893fcdb1 | ae541c3c930645ca0484a3a03bd09f18a500766c | refs/heads/main | 2023-04-11T21:03:51.040218 | 2021-05-19T16:56:08 | 2021-05-19T16:56:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,832 | cpp | PlayerStrategies.cpp | #include "PlayerStrategies.h"
using std::cout;
PlayerStrategy::PlayerStrategy(Player* player) {
this->player = player;
}
PlayerStrategy::PlayerStrategy(PlayerStrategy& PS)
{
this->player = PS.player;
}
vector<Territory*> PlayerStrategy::sortTerritories(vector<Territory*> list) {
vector<Territory*> sortedList = list;
for (int i = 0; i < sortedList.size() - 1; i++) {
int smallestIndex = i;
for (int j = i + 1; j < sortedList.size(); j++) {
if (sortedList[smallestIndex]->getArmyCount() > sortedList[j]->getArmyCount()) {
smallestIndex = j;
}
}
if (smallestIndex != i) {
Territory* temp = sortedList[i];
sortedList[i] = sortedList[smallestIndex];
sortedList[smallestIndex] = temp;
}
}
return sortedList;
}
Territory* PlayerStrategy::getWeakestTerritory(vector<Territory*> list) {
Territory* weakest = list[0];
for (auto t : list) {
if (weakest->getArmyCount() > t->getArmyCount()) {
weakest = t;
}
}
return weakest;
}
vector<Territory*> PlayerStrategy::getEnemyNeighbors(Territory* territory) {
vector<Territory*> toReturn;
vector<Territory*> list = territory->getOwner()->mapPlayed->getTerritoryNeighbors(territory);
for (auto t : list) {
if (t->getOwner() != territory->getOwner()) {
toReturn.push_back(t);
}
}
return toReturn;
}
bool PlayerStrategy::hasEnemyNeighbor(Territory* territory) {
vector<Territory*> list = territory->getOwner()->mapPlayed->getTerritoryNeighbors(territory);
for (auto t : list) {
if (t->getOwner() != territory->getOwner()) {
return true;
}
}
return false;
}
ostream& operator << (ostream& out, PlayerStrategy& ps)
{
out << "Base Strategy of player " << ps.player->getPlayerID() << endl;
return out;
}
HumanPlayerStrategy::HumanPlayerStrategy(Player* player, vector<Player*>players) : PlayerStrategy(player) { gameplayers = players; };
void HumanPlayerStrategy::issueOrder() {
if(player->tempArmies>0)
{
cout << "Hey Player " << player->getPlayerID() << ". You still have armies left to deploy. You have " << player->tempArmies<< " armies left. Deploy them before you can issue other orders.\nYour Territories:"<< endl;
for(auto it: player->getOwnedTerritories())
{
cout << it->getName() << "\tArmies on this territory: " << it->getArmyCount() << endl;
}
cout << "How many armies?" << endl;
int numarmies;
cin >> numarmies;
cout << "And on which territories?" << endl;
string name;
cin >> name;
bool flag = false;
for (auto it : player->getOwnedTerritories())
{
if (it->getName()==name)
{
player->getOrderList()->add(new Deploy(numarmies, it, player));
flag = true;
}
}
if(!flag)
{
cout << "You entered an incorrect name." << endl;
}
}
else
{
cout << "What type of order do you want to issue? Enter \"done\" when finished.\n Options are: Advance orders (type \"advance\") or Cards (type \"cards\")."<<endl;
string choice;
cin >> choice;
if(choice=="done")
{
player->doneIssue = true;
return;
}
else if (choice=="advance")
{
cout << "You have chosen Advance. Your territories are ordered below and you can move armies from here to any other territory that own or to an enemy neighbours territory." << endl;
cout << "To see a neighbour of your territories enter the name or press skip if you're ready to place the order." << endl;
string neighbourname;
cin >> neighbourname;
if (neighbourname=="skip")
{
cout << "You chose to skip" << endl;
}
else {
Territory* thisterr=player->mapPlayed->getTerritory(neighbourname);
if (thisterr->getName()!="N/A")
{
cout << "Displaying names of neighbours: "<<endl;
for (auto it:player->mapPlayed->getTerritoryNeighbors(neighbourname))
{
cout << it->getName()<<"\t"<<it->getArmyCount()<<endl;
}
}
else
{
cout << "Wrong name entered" << endl;
}
}
cout << "Enter the source then press enter then target then press enter then number of armies then enter." << endl;
string source, target;
int num;
cout << endl << "Source: ";
cin >> source;
cout << endl << "Target: ";
cin >> target;
cout << endl << "Number of armies: ";
cin >> num;
Territory* sourcet;
Territory* targett;
sourcet = player->mapPlayed->getTerritory(source);
targett = player->mapPlayed->getTerritory(target);
if(sourcet->getName()==("N/A")||targett->getName()=="N/A")
{
cout << "You have entered a wrong territory name. Try again next turn haha";
}
else
{
player->getOrderList()->add(new Advance(sourcet, targett, num,player,player->gameDeck));
}
}
else if(choice == "cards")
{
cout << "Here is your hand of cards" << endl;
cout << "airlift\t" << player->getHand()->getAirlift() << endl;
cout << "bomb\t" << player->getHand()->getBomb() << endl;
cout << "blockade\t" << player->getHand()->getBlockade() << endl;
cout << "negotiate\t" << player->getHand()->getDiplomacy() << endl;
cout << "Which card do you wanna play?" << endl;
string cardtype;
cin >> cardtype;
if(cardtype=="airlift")
{
cout << "Enter source followed by target followed by number of armies..." << endl;
string source, target;
int num;
cout << endl << "Source: ";
cin >> source;
cout << endl << "Target: ";
cin >> target;
cout << endl << "Number of armies: ";
cin >> num;
Territory* sourcet;
Territory* targett;
sourcet = player->mapPlayed->getTerritory(source);
targett = player->mapPlayed->getTerritory(target);
if (sourcet->getName() == ("N/A") || targett->getName() == "N/A")
{
cout << "You have entered a wrong territory name. Try again next turn haha";
}
else
{
player->getOrderList()->add(new Airlift(sourcet, targett, num, player));
}
}
else if (cardtype == "bomb")
{
cout << "enter target territory: " << endl;
string target;
cin >> target;
Territory* sourcet;
Territory* targett;
targett = player->mapPlayed->getTerritory(target);
if ( targett->getName() == "N/A")
{
cout << endl << "You have entered a wrong territory name. Try again next turn haha" << endl;
}
else
{
player->getOrderList()->add(new Bomb(targett,player));
}
}
else if (cardtype == "blockade")
{
cout << "Enter target territory: " << endl;
string target;
cin >> target;
Territory* targett;
targett = player->mapPlayed->getTerritory(target);
if (targett->getName() == "N/A")
{
cout << endl << "You have entered a wrong territory name. Try again next turn haha" << endl;
}
else
{
player->getOrderList()->add(new Blockade(targett, player, player->neutral));
}
}
else if (cardtype == "negotiate")
{
cout << "Showing player names:" << endl;
for(auto it:gameplayers)
{
cout << it->getPlayerID();
}
cout << "Enter the target player ID:" << endl;
int playerid;
cin >> playerid;
if(playerid<=gameplayers.size())
{
player->getOrderList()->add(new Negotiate(player, gameplayers[playerid]));
}
}
else
{
cout << "invalid input try again next turn and maybe learn to read properly";
}
}
else
{
cout << "Wrong entry, try again next turn ;)";
}
}
}
vector<Territory*> HumanPlayerStrategy::toDefend() {
vector<Territory*> list;
return list;
}
vector<Territory*> HumanPlayerStrategy::toAttack() {
vector<Territory*> list;
return list;
}
HumanPlayerStrategy& HumanPlayerStrategy::operator=(HumanPlayerStrategy& o)
{
HumanPlayerStrategy p = HumanPlayerStrategy(o);
return p;
};
void HumanPlayerStrategy::reset() {}
HumanPlayerStrategy::HumanPlayerStrategy(HumanPlayerStrategy& hps) : PlayerStrategy( hps)
{
this->players = hps.players;
this->gameplayers = hps.gameplayers;
}
ostream& operator << (ostream& out, HumanPlayerStrategy& hps)
{
out << "Human Strategy of player " << hps.player->getPlayerID() << endl;
out << "The players in the game hosting this strategy are " << endl;
for(auto it: hps.gameplayers)
{
out << it->getPlayerID() << endl;
}
return out;
}
AggressivePlayerStrategy::AggressivePlayerStrategy(Player* player) : PlayerStrategy(player) {}
void AggressivePlayerStrategy::issueOrder() {
vector<Territory*> defendList = toDefend();
vector<Territory*> attackList = toAttack();
if (player->tempArmies > 0) {
player->getOrderList()->add(new Deploy(player->tempArmies, mainTerritory, player));
}
else if (player->attackArmies > 0) {
Territory* weakest = getWeakestTerritory(attackList);
player->getOrderList()->add(new Advance(mainTerritory, weakest, mainTerritory->getArmyCount(), player, player->gameDeck));
player->attackArmies=0;
}
else {
player->doneIssue = true;
}
//Add card use if we have time.
}
vector<Territory*> AggressivePlayerStrategy::toDefend() {
vector<Territory*> list;
if (player->getOwnedTerritories().size() > 0) {
Territory* maxArmyTerritory = nullptr;
for (auto t : player->getOwnedTerritories()) {
if (hasEnemyNeighbor(t)) {
maxArmyTerritory = t;
break;
}
}
if (maxArmyTerritory == nullptr) {
cout << "ERROR: Game should be over.";
return list;
}
for (auto t : player->getOwnedTerritories()) {
if (maxArmyTerritory->getArmyCount() < t->getArmyCount() && hasEnemyNeighbor(t)) {
maxArmyTerritory = t;
}
}
mainTerritory = maxArmyTerritory;
list.push_back(maxArmyTerritory);
}
return list;
}
vector<Territory*> AggressivePlayerStrategy::toAttack() {
if (mainTerritory == nullptr || mainTerritory->getOwner() != player) {
cout << "Main territory is null or not owned by player." << endl;
cout << mainTerritory->getName() << "\t" << mainTerritory->getOwner()->getPlayerID() << "\t"<<player->getPlayerID();
exit(0);
}
return getEnemyNeighbors(mainTerritory);
}
void AggressivePlayerStrategy::reset() {}
AggressivePlayerStrategy::AggressivePlayerStrategy(AggressivePlayerStrategy& hps) : PlayerStrategy(hps)
{
this->mainTerritory = hps.mainTerritory;
}
ostream& operator << (ostream& out, AggressivePlayerStrategy& aps)
{
out << "Aggressive Strategy of player " << aps.player->getPlayerID() << endl;
out << "The main territory in the game hosting this strategy are " << aps.mainTerritory->getName() <<endl;
return out;
}
AggressivePlayerStrategy& AggressivePlayerStrategy::operator=(AggressivePlayerStrategy& o)
{
AggressivePlayerStrategy p = AggressivePlayerStrategy(o);
return p;
};
BenevolentPlayerStrategy::BenevolentPlayerStrategy(Player* player) : PlayerStrategy(player) {}
void BenevolentPlayerStrategy::issueOrder() {
vector<Territory*> defendList = toDefend();
vector<Territory*> attackList = toAttack();
if (player->tempArmies > 0) {
player->getOrderList()->add(new Deploy(1, defendList[benevolentIndex], player));
benevolentIndex++;
if (benevolentIndex >= defendList.size()) {
benevolentIndex = 0;
}
}
else {
player->doneIssue = true;
}
}
vector<Territory*> BenevolentPlayerStrategy::toDefend() {
vector<Territory*> list = sortTerritories(player->getOwnedTerritories());
int defenceCount = ceil(list.size()*.5);
vector<Territory*> toReturn;
for (int i = 0; i < defenceCount; i++) {
toReturn.push_back(list[i]);
}
return toReturn;
}
vector<Territory*> BenevolentPlayerStrategy::toAttack() {
vector<Territory*> list;
return list;
}
void BenevolentPlayerStrategy::reset() {
benevolentIndex = 0;
}
BenevolentPlayerStrategy::BenevolentPlayerStrategy(BenevolentPlayerStrategy& bps):PlayerStrategy(bps)
{
benevolentIndex = bps.benevolentIndex;
}
ostream& operator << (ostream& out, BenevolentPlayerStrategy& bps)
{
out << "Benevolent Strategy of player " << bps.player->getPlayerID() << endl;
out << "The benevolent index currently in the game hosting this strategy are " << bps.benevolentIndex << endl;
return out;
}
BenevolentPlayerStrategy& BenevolentPlayerStrategy::operator=(BenevolentPlayerStrategy& o)
{
BenevolentPlayerStrategy p = BenevolentPlayerStrategy(o);
return p;
};
NeutralPlayerStrategy::NeutralPlayerStrategy(Player* player) : PlayerStrategy(player) {}
void NeutralPlayerStrategy::issueOrder() {
//This does nothing.
player->doneIssue = true;
}
NeutralPlayerStrategy::NeutralPlayerStrategy(NeutralPlayerStrategy& nps):PlayerStrategy(nps)
{
}
vector<Territory*> NeutralPlayerStrategy::toDefend() {
vector<Territory*> list;
return list;
}
vector<Territory*> NeutralPlayerStrategy::toAttack() {
vector<Territory*> list;
return list;
}
void NeutralPlayerStrategy::reset() {}
ostream& operator << (ostream& out, NeutralPlayerStrategy& bps)
{
out << "Neutral Strategy of player " << bps.player->getPlayerID() << endl;
return out;
}
NeutralPlayerStrategy& NeutralPlayerStrategy::operator=(NeutralPlayerStrategy& o)
{
NeutralPlayerStrategy p = NeutralPlayerStrategy(o);
return p;
}; |
e8a0fd91b62475a3cf4a8835fe30ee5d93af51d1 | 26c52dcbc5095b64e51a5fdf2e08e29c065ad3f3 | /cpsc457/asg2/scan1.cpp | d78f97a9f3a2417a1ebfe9866af8bec2002f5276 | [] | no_license | ScanonA/HW | d17dba390f2ce5ea54c456fdca0ba96c6661f482 | 453c7b4335b03309ca4cf916fca8080381f917d1 | refs/heads/master | 2020-04-24T12:19:44.730119 | 2019-07-02T00:54:31 | 2019-07-02T00:54:31 | 171,951,763 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,288 | cpp | scan1.cpp | /****************************
Last Name: Kharfan
First Name: Lamess
Student ID: 10150607
Course: CPSC 457
Tutorial Section: T02
Assignment: 2
Question: 8
File name: sum.c
To compile: gcc sum.c -l pthread -o sum -lm
To run: ./sum <filename> <T>
*****************************/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <math.h>
#define MAX_SIZE 512
#define MAX_NUMS 1000000
char filename[MAX_SIZE];
int T;
int count;
int intArray[MAX_NUMS];
int sum;
void * thread_sum(void * tid) {
int start, end, lastPart;
float div = count / T;
int part = ceil(div);
int remaining = part * T;
int threadSum = 0;
long int itid = (long int) tid;
if((remaining - count) == 0)
lastPart = part;
else
lastPart = remaining - count;
if( itid == (T - 1)) {
start = (itid * part);
end = start + part - lastPart;
}
else {
start = itid * part;
end = start + part;
}
for (int i = start; i < end; i++) {
threadSum = threadSum + ints[i];
}
printf("\tThread %ld: %d\n", (itid + 1), threadSum);
sum += threadSum;
pthread_exit(0);
}
int main( int argc, char ** argv) {
// handle command line arguments
if( argc != 3) {
fprintf(stderr, "add parameters: <filename> <T>");
exit(-1);
}
else {
stpcpy(filename, argv[1]);
T = atoi(argv[2]);
}
// open file
FILE * fp = fopen(filename, "r");
if( fp == NULL) {
perror("popen failed:");
exit(-1);
}
// read in all intArray in the file into array
char buff[MAX_SIZE];
count = 0;
while(fgets(buff,MAX_SIZE,fp)) {
int len = strlen(buff);
int temp = atoi(strndup(buff,len));
ints[count] = temp;
count++;
}
fclose(fp);
pthread_t threads[T];
long i, status;
sum = 0;
for(i = 0; i < T; i++) {
status = pthread_create(&threads[i], NULL, thread_sum, (void *) i);
if (status != 0) {
printf("Error in pthread_create\n");
exit(-1);
|
70439c5dd7aa7f88d785847fe51948ae41bb84d9 | 19ed4c1bb2c4386eb98201e1b50ffc91549174dc | /Source/Core/Number/NumberHalf.h | b666d78b653d8eeb9357a864993acbac4d214892 | [] | no_license | mRooky/Rooky | 81742fffd72700b3423802702ffc9e5658151f75 | 401bd515e42873b268395c1bc96fbb4982c83875 | refs/heads/master | 2020-04-19T11:43:43.985899 | 2019-08-27T06:27:46 | 2019-08-27T06:27:46 | 168,174,259 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,020 | h | NumberHalf.h | /*
* RenderHalf.hpp
*
* Created on: Apr 2, 2019
* Author: rookyma
*/
#ifndef SOURCE_CORE_GHI_RENDERMATH_RENDERHALF_H_
#define SOURCE_CORE_GHI_RENDERMATH_RENDERHALF_H_
#include "NumberFloat.h"
namespace Number
{
class Half
{
public:
Half(float value = 0.0f)
{
SetFloat(value);
}
Half(const Half& other) :
m_encoded(other.m_encoded)
{
}
~Half(void) = default;
public:
float GetFloat(void) const;
void SetFloat(float value);
public:
inline operator float (void) const
{
return GetFloat();
}
inline operator uint16_t (void) const
{
return m_encoded;
}
public:
inline bool operator==(const Half& other) const
{
return m_encoded == other.m_encoded;
}
public:
inline Half& operator=(float value)
{
SetFloat(value); return *this;
}
inline Half& operator=(const Half& other)
{
m_encoded = other.m_encoded; return *this;
}
private:
union
{
uint16_t m_encoded = 0;
Float16Components m_components;
};
};
}
#endif /* SOURCE_CORE_GHI_RENDERMATH_RENDERHALF_H_ */
|
362459d2289c096bf01292e4b23ad1fd1e39de5d | 5de361652aef8e153d1bda9aff5ff6211f59516c | /UVA/UVA12405.cpp | bb0267702bcc9d1220e20a033991dd4950df37fe | [] | no_license | carlosngo/CompetitiveProgramming | bcffb49aaf8a9d30d86b0233dbb8b88b203d105b | 82f6186d8d15952063de001213d8c97f722ef263 | refs/heads/master | 2020-05-17T14:55:31.544504 | 2020-02-01T14:35:00 | 2020-02-01T14:35:00 | 183,777,229 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 916 | cpp | UVA12405.cpp | #include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <utility>
#include <string>
#include <cstring>
#include <cmath>
#include <bitset>
using namespace std;
typedef pair<int,int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
typedef long long ll;
int main() {
FILE *pFile = fopen("out.txt","w");
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
int size;
scanf ("%d", &size);
int ctr = 0;
bitset<102> bs;
string field;
cin >> field;
for (int j = 0; j < size; j++) {
if (field[j] == '.' && !bs.test(j)) {
if (j - 1 >= 0 && field[j - 1] == '.' && !bs.test(j - 1)) {
ctr++;
bs.set(j - 1);
bs.set(j);
bs.set(j + 1);
} else {
ctr++;
bs.set(j);
bs.set(j + 1);
bs.set(j + 2);
}
}
}
printf("Case %d: %d\n", i, ctr);
fprintf(pFile, "Case %d: %d\n", i, ctr);
}
fclose(pFile);
return 0;
} |
5e53c15bb66d38784d58a4fb48e61146e26ec42f | bf007dec921b84d205bffd2527e376bb60424f4c | /Codeforces_Submissions/991D.cpp | e25e15417fbf30701d8b7f9878166fbd4f0ef9e6 | [] | no_license | Suvrojyoti/APS-2020 | 257e4a94f52f5fe8adcac1ba4038cc66e81d9d26 | d4de0ef098e7ce9bb40036ef55616fa1f159f7a5 | refs/heads/master | 2020-12-21T19:27:59.955338 | 2020-04-22T13:27:49 | 2020-04-22T13:27:49 | 236,534,218 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,424 | cpp | 991D.cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
char l[105],arr[2][105];
int i,c=0,k=0;
cin>>l;
arr[0][0]='X';
arr[1][0]='X';
for(i=0;l[i]!='\0';i++)
{
arr[0][i+1]=l[i];
k++;
}
arr[0][k+1]='X';
arr[1][k+1]='X';
cin>>l;
for(i=1;i<=k;i++)
{
arr[1][i]=l[i-1];
}
for(i=1;i<=k;i++)
{
if(arr[0][i]=='0'&&arr[1][i]=='0'&&arr[1][i+1]=='0')
{
arr[0][i]='X';
arr[1][i]='X';
arr[1][i+1]='X';
c++;
//cout<<i;
}
else if(arr[0][i]=='0'&&arr[1][i]=='0'&&arr[1][i-1]=='0')
{
arr[0][i]='X';
arr[1][i]='X';
arr[1][i-1]='X';
c++;
//cout<<i;
}
else if(arr[0][i]=='0'&&arr[0][i+1]=='0'&&arr[1][i]=='0')
{
c++;
arr[0][i]='X';
arr[1][i+1]='X';
arr[1][i]='X';
//cout<<i;
}
else if(arr[0][i]=='0'&&arr[0][i+1]=='0'&&arr[1][i+1]=='0')
{
arr[0][i]='X';
c++;
arr[1][i+1]='X';
arr[0][i+1]='X';
//cout<<i;
}
// cout<<" ";
}
/*for(i=1;i<=k;i++)
{
cout<<arr[0][i];
}
cout<<"\n";
for(i=1;i<=k;i++)
{
cout<<arr[1][i];
}*/
cout<<c;
return 0;
} |
5cead052b6f9fd846053dd5020b8e36907263b20 | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/admin/wmi/wbem/providers/msiprovider/dll/msiprov.cpp | 70e0fc5a8afab5a580a6c7de36b9dd87611f0688 | [] | 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 | 28,854 | cpp | msiprov.cpp | //***************************************************************************
//
// MSIProv.CPP
//
// Module: WBEM Instance provider for MSI
//
// Copyright (c) 1997-2001 Microsoft Corporation, All Rights Reserved
//
//***************************************************************************
#include "precomp.h"
#include <wbemcli_i.c>
#include <wbemprov_i.c>
#include "requestobject.h"
//#define _MT
#include <process.h>
#include <Polarity.h>
#include <tchar.h>
CRITICAL_SECTION g_msi_prov_cs;
WCHAR *g_wcpLoggingDir = NULL;
bool g_bMsiPresent = true;
bool g_bMsiLoaded = false;
CHeap_Exception CMSIProv::m_he(CHeap_Exception::E_ALLOCATION_ERROR);
LPFNMSIVIEWFETCH g_fpMsiViewFetch = NULL;
LPFNMSIRECORDGETSTRINGW g_fpMsiRecordGetStringW = NULL;
LPFNMSICLOSEHANDLE g_fpMsiCloseHandle = NULL;
LPFNMSIDATABASEOPENVIEWW g_fpMsiDatabaseOpenViewW = NULL;
LPFNMSIVIEWEXECUTE g_fpMsiViewExecute = NULL;
LPFNMSIGETACTIVEDATABASE g_fpMsiGetActiveDatabase = NULL;
LPFNMSIGETCOMPONENTPATHW g_fpMsiGetComponentPathW = NULL;
LPFNMSIGETCOMPONENTSTATEW g_fpMsiGetComponentStateW = NULL;
LPFNMSIOPENPRODUCTW g_fpMsiOpenProductW = NULL;
LPFNMSIOPENPACKAGEW g_fpMsiOpenPackageW = NULL;
LPFNMSIDATABASEISTABLEPERSITENTW g_fpMsiDatabaseIsTablePersistentW = NULL;
LPFNMSISETINTERNALUI g_fpMsiSetInternalUI = NULL;
LPFNMSISETEXTERNALUIW g_fpMsiSetExternalUIW = NULL;
LPFNMSIENABLELOGW g_fpMsiEnableLogW = NULL;
LPFNMSIGETPRODUCTPROPERTYW g_fpMsiGetProductPropertyW = NULL;
LPFNMSIQUERYPRODUCTSTATEW g_fpMsiQueryProductStateW = NULL;
LPFNMSIINSTALLPRODUCTW g_fpMsiInstallProductW = NULL;
LPFNMSICONFIGUREPRODUCTW g_fpMsiConfigureProductW = NULL;
LPFNMSIREINSTALLPRODUCTW g_fpMsiReinstallProductW = NULL;
LPFNMSIAPPLYPATCHW g_fpMsiApplyPatchW = NULL;
LPFNMSIRECORDGETINTEGER g_fpMsiRecordGetInteger = NULL;
LPFNMSIENUMFEATURESW g_fpMsiEnumFeaturesW = NULL;
LPFNMSIGETPRODUCTINFOW g_fpMsiGetProductInfoW = NULL;
LPFNMSIQUERYFEATURESTATEW g_fpMsiQueryFeatureStateW = NULL;
LPFNMSIGETFEATUREUSAGEW g_fpMsiGetFeatureUsageW = NULL;
LPFNMSIGETFEATUREINFOW g_fpMsiGetFeatureInfoW = NULL;
LPFNMSICONFIGUREFEATUREW g_fpMsiConfigureFeatureW = NULL;
LPFNMSIREINSTALLFEATUREW g_fpMsiReinstallFeatureW = NULL;
LPFNMSIENUMPRODUCTSW g_fpMsiEnumProductsW = NULL;
LPFNMSIGETDATABASESTATE g_fpMsiGetDatabaseState = NULL;
LPFNMSIRECORDSETSTRINGW g_fpMsiRecordSetStringW = NULL;
LPFNMSIDATABASECOMMIT g_fpMsiDatabaseCommit = NULL;
LPFNMSIENUMCOMPONENTSW g_fpMsiEnumComponentsW = NULL;
LPFNMSIVIEWCLOSE g_fpMsiViewClose = NULL;
//***************************************************************************
//
// CMSIProv::CMSIProv
// CMSIProv::~CMSIProv
//
//***************************************************************************
CMSIProv::CMSIProv(BSTR ObjectPath, BSTR User, BSTR Password, IWbemContext * pCtx)
{
m_pNamespace = NULL;
m_cRef = 0;
InterlockedIncrement(&g_cObj);
return;
}
CMSIProv::~CMSIProv(void)
{
if(m_pNamespace) m_pNamespace->Release();
InterlockedDecrement(&g_cObj) ;
return;
}
//***************************************************************************
//
// CMSIProv::QueryInterface
// CMSIProv::AddRef
// CMSIProv::Release
//
// Purpose: IUnknown members for CMSIProv object.
//***************************************************************************
STDMETHODIMP CMSIProv::QueryInterface(REFIID riid, PPVOID ppv)
{
*ppv=NULL;
// Since we have dual inheritance, it is necessary to cast the return type
if(riid == IID_IWbemServices)
*ppv = (IWbemServices*)this;
if(IID_IUnknown == riid || riid == IID_IWbemProviderInit)
*ppv = (IWbemProviderInit*)this;
if(NULL!=*ppv){
AddRef();
return NOERROR;
}
else return E_NOINTERFACE;
}
STDMETHODIMP_(ULONG) CMSIProv::AddRef(void)
{
return ++m_cRef;
}
STDMETHODIMP_(ULONG) CMSIProv::Release(void)
{
ULONG nNewCount = InterlockedDecrement((long *)&m_cRef);
if(0L == nNewCount){
delete this;
}
return nNewCount;
}
/***********************************************************************
* *
* CMSIProv::Initialize *
* *
* Purpose: This is the implementation of IWbemProviderInit. The method *
* is need to initialize with CIMOM. *
* *
***********************************************************************/
STDMETHODIMP CMSIProv::Initialize(LPWSTR pszUser, LONG lFlags,
LPWSTR pszNamespace, LPWSTR pszLocale,
IWbemServices *pNamespace,
IWbemContext *pCtx,
IWbemProviderInitSink *pInitSink)
{
try{
if(pNamespace){
m_pNamespace = pNamespace;
m_pNamespace->AddRef();
}
else
{
return WBEM_E_INVALID_PARAMETER;
}
CheckForMsiDll();
#ifdef _PRIVATE_DEBUG
//get the working directory for the log file
HKEY hkeyLocalMachine;
LONG lResult;
if((lResult = RegConnectRegistryW(NULL, HKEY_LOCAL_MACHINE, &hkeyLocalMachine)) == ERROR_SUCCESS)
{
HKEY hkeyHmomCwd;
if( (lResult = RegOpenKeyExW ( hkeyLocalMachine,
L"SOFTWARE\\Microsoft\\WBEM\\CIMOM",
0,
KEY_READ | KEY_QUERY_VALUE,
&hkeyHmomCwd
)
) == ERROR_SUCCESS)
{
unsigned long lcbValue = 0L;
unsigned long lType = 0L;
lResult = RegQueryValueExW ( hkeyHmomCwd,
L"Logging Directory",
NULL,
&lType,
NULL,
&lcbValue
);
if ( lResult == ERROR_MORE_DATA )
{
try
{
if ( ( g_wcpLoggingDir = new WCHAR [ lcbValue/sizeof ( WCHAR ) + wcslen ( L"\\msiprov.log" ) + 1 ] ) != NULL )
{
lResult = RegQueryValueExW ( hkeyHmomCwd,
L"Logging Directory",
NULL,
&lType,
g_wcpLoggingDir,
&lcbValue
);
if ( lResult == ERROR_SUCCESS )
{
wcscat(g_wcpLoggingDir, L"\\msiprov.log");
}
else
{
if ( g_wcpLoggingDir );
{
delete [] g_wcpLoggingDir;
g_wcpLoggingDir = NULL;
}
}
}
else
{
throw m_he;
}
}
catch ( ... )
{
if ( g_wcpLoggingDir );
{
delete [] g_wcpLoggingDir;
g_wcpLoggingDir = NULL;
}
RegCloseKey(hkeyHmomCwd);
RegCloseKey(hkeyLocalMachine);
throw;
}
RegCloseKey(hkeyHmomCwd);
RegCloseKey(hkeyLocalMachine);
}
}
else
{
RegCloseKey(hkeyLocalMachine);
}
}
#endif
//Register usage information with MSI
/* WCHAR wcProduct[39];
WCHAR wcFeature[BUFF_SIZE];
WCHAR wcParent[BUFF_SIZE];
int iPass = -1;
MsiGetProductCodeW(L"{E705C42D-35ED-11D2-BFB7-00A0C9954921}", wcProduct);
while(MsiEnumFeaturesW(wcProduct, ++iPass, wcFeature, wcParent) != ERROR_NO_MORE_ITEMS){
if(wcscmp(wcFeature, L"Provider") == 0){
MsiUseFeatureW(wcProduct, wcFeature);
break;
}
}
*/
}catch(...){
//Let CIMOM know there was problem
pInitSink->SetStatus(WBEM_S_INITIALIZED, 0);
return WBEM_E_FAILED;
}
//Let CIMOM know you are initialized
pInitSink->SetStatus(WBEM_S_INITIALIZED, 0);
return WBEM_S_NO_ERROR;
}
//***************************************************************************
//
// CMSIProv::CreateInstanceEnumAsync
//
// Purpose: Asynchronously enumerates the instances.
//
//***************************************************************************
SCODE CMSIProv::CreateInstanceEnumAsync(const BSTR RefStr, long lFlags, IWbemContext *pCtx,
IWbemObjectSink FAR* pHandler)
{
HRESULT hr = WBEM_S_NO_ERROR;
CRequestObject *pRObj = NULL;
try
{
if(CheckForMsiDll())
{
// Do a check of arguments and make sure we have pointer to Namespace
if(RefStr == NULL || pHandler == NULL)
{
return WBEM_E_INVALID_PARAMETER;
}
if(SUCCEEDED(hr = CheckImpersonationLevel()))
{
g_fpMsiSetInternalUI(INSTALLUILEVEL_NONE, NULL);
//Create the RequestObject
if ( ( pRObj = new CRequestObject() ) == NULL )
{
throw m_he;
}
pRObj->Initialize(m_pNamespace);
//Get package list
hr = pRObj->InitializeList(true);
if SUCCEEDED ( hr )
{
if ( hr != WBEM_S_NO_MORE_DATA )
{
//Get the requested object(s)
hr = pRObj->CreateObjectEnum(RefStr, pHandler, pCtx);
}
else
{
//return empty and success
hr = WBEM_S_NO_ERROR;
}
}
pRObj->Cleanup();
delete pRObj;
}
}
// Set status
pHandler->SetStatus(0, hr, NULL, NULL);
}
catch(CHeap_Exception e_HE)
{
hr = WBEM_E_OUT_OF_MEMORY;
pHandler->SetStatus(0 , hr, NULL, NULL);
if(pRObj)
{
pRObj->Cleanup();
delete pRObj;
}
}
catch(HRESULT e_hr)
{
hr = e_hr;
pHandler->SetStatus(0 , hr, NULL, NULL);
if(pRObj)
{
pRObj->Cleanup();
delete pRObj;
}
}
catch(...)
{
hr = WBEM_E_CRITICAL_ERROR;
pHandler->SetStatus(0 , hr, NULL, NULL);
if(pRObj)
{
pRObj->Cleanup();
delete pRObj;
}
}
#ifdef _PRIVATE_DEBUG
if(!HeapValidate(GetProcessHeap(),NULL , NULL)) DebugBreak();
#endif
return hr;
}
//***************************************************************************
//
// CMSIProv::GetObjectAsync
//
// Purpose: Creates an instance given a particular path value.
//
//***************************************************************************
SCODE CMSIProv::GetObjectAsync(const BSTR ObjectPath, long lFlags,IWbemContext *pCtx,
IWbemObjectSink FAR* pHandler)
{
HRESULT hr = WBEM_S_NO_ERROR;
CRequestObject *pRObj = NULL;
try
{
if(CheckForMsiDll())
{
// Do a check of arguments and make sure we have pointer to Namespace
if(ObjectPath == NULL || pHandler == NULL )
{
return WBEM_E_INVALID_PARAMETER;
}
if(SUCCEEDED(hr = CheckImpersonationLevel()))
{
g_fpMsiSetInternalUI(INSTALLUILEVEL_NONE, NULL);
//Create the RequestObject
if ( ( pRObj = new CRequestObject() ) == NULL )
{
throw m_he;
}
pRObj->Initialize(m_pNamespace);
//Get package list
hr = pRObj->InitializeList(true);
if SUCCEEDED ( hr )
{
if ( hr != WBEM_S_NO_MORE_DATA )
{
//Get the requested object
hr = pRObj->CreateObject(ObjectPath, pHandler, pCtx);
}
else
{
//return empty and success
hr = WBEM_S_NO_ERROR;
}
}
pRObj->Cleanup();
delete pRObj;
}
}
// Set Status
pHandler->SetStatus(0, hr , NULL, NULL);
}
catch(CHeap_Exception e_HE)
{
hr = WBEM_E_OUT_OF_MEMORY;
pHandler->SetStatus(0, hr, NULL, NULL);
if(pRObj)
{
pRObj->Cleanup();
delete pRObj;
}
}
catch(HRESULT e_hr)
{
hr = e_hr;
pHandler->SetStatus(0, hr, NULL, NULL);
if(pRObj)
{
pRObj->Cleanup();
delete pRObj;
}
}
catch(...)
{
hr = WBEM_E_CRITICAL_ERROR;
pHandler->SetStatus(0 , hr, NULL, NULL);
if(pRObj)
{
pRObj->Cleanup();
delete pRObj;
}
}
#ifdef _PRIVATE_DEBUG
if(!HeapValidate(GetProcessHeap(),NULL , NULL)) DebugBreak();
#endif
return hr;
}
//***************************************************************************
//
// CMSIProv::PutInstanceAsync
//
// Purpose: Writes an instance to the WBEM Repsoitory.
//
//***************************************************************************
SCODE CMSIProv::PutInstanceAsync(IWbemClassObject FAR *pInst, long lFlags, IWbemContext *pCtx,
IWbemObjectSink FAR *pResponseHandler)
{
HRESULT hr = WBEM_S_NO_ERROR;
CRequestObject *pRObj = NULL;
try
{
if(CheckForMsiDll())
{
// Do a check of arguments and make sure we have pointer to Namespace
// Do a check of arguments and make sure we have pointer to Namespace
if(pInst == NULL || pResponseHandler == NULL )
{
return WBEM_E_INVALID_PARAMETER;
}
if(SUCCEEDED(hr = CheckImpersonationLevel()))
{
g_fpMsiSetInternalUI(INSTALLUILEVEL_NONE, NULL);
//Create the RequestObject
if ( ( pRObj = new CRequestObject() ) == NULL )
{
throw m_he;
}
pRObj->Initialize(m_pNamespace);
//Get package list
hr = pRObj->InitializeList(true);
if SUCCEEDED ( hr )
{
if ( hr != WBEM_S_NO_MORE_DATA )
{
//Put the object
hr = pRObj->PutObject(pInst, pResponseHandler, pCtx);
}
else
{
//return empty and success
hr = WBEM_S_NO_ERROR;
}
}
pRObj->Cleanup();
delete pRObj;
}
}
else
{
hr = WBEM_E_NOT_AVAILABLE;
}
// Set Status
pResponseHandler->SetStatus(0 ,hr , NULL, NULL);
}
catch(CHeap_Exception e_HE)
{
hr = WBEM_E_OUT_OF_MEMORY;
pResponseHandler->SetStatus(0 , hr, NULL, NULL);
if(pRObj)
{
pRObj->Cleanup();
delete pRObj;
}
}
catch(HRESULT e_hr)
{
hr = e_hr;
pResponseHandler->SetStatus(0 , hr, NULL, NULL);
if(pRObj)
{
pRObj->Cleanup();
delete pRObj;
}
}
catch(...)
{
hr = WBEM_E_CRITICAL_ERROR;
pResponseHandler->SetStatus(0 , hr, NULL, NULL);
if(pRObj)
{
pRObj->Cleanup();
delete pRObj;
}
}
#ifdef _PRIVATE_DEBUG
if(!HeapValidate(GetProcessHeap(),NULL , NULL)) DebugBreak();
#endif
return hr;
}
//***************************************************************************
//
// CMSIProv::ExecMethodAsync
//
// Purpose: Executes a method on an MSI class or instance.
//
//***************************************************************************
SCODE CMSIProv::ExecMethodAsync(const BSTR ObjectPath, const BSTR Method, long lFlags,
IWbemContext *pCtx, IWbemClassObject *pInParams,
IWbemObjectSink *pResponse)
{
HRESULT hr = WBEM_S_NO_ERROR;
CRequestObject *pRObj = NULL;
try{
if(CheckForMsiDll()){
// Do a check of arguments and make sure we have pointer to Namespace
if(ObjectPath == NULL || Method == NULL || pResponse == NULL )
{
return WBEM_E_INVALID_PARAMETER;
}
if(SUCCEEDED(hr = CheckImpersonationLevel())){
g_fpMsiSetInternalUI(INSTALLUILEVEL_NONE, NULL);
//Create the RequestObject
pRObj = new CRequestObject();
if(!pRObj) throw m_he;
pRObj->Initialize(m_pNamespace);
//Don't get package list
if(SUCCEEDED(hr = pRObj->InitializeList(false))){
//Execute the method
hr = pRObj->ExecMethod(ObjectPath, Method, pInParams, pResponse, pCtx);
}
pRObj->Cleanup();
delete pRObj;
}
}else{
hr = WBEM_E_NOT_AVAILABLE;
}
// Set Status
pResponse->SetStatus(WBEM_STATUS_COMPLETE ,hr , NULL, NULL);
}catch(CHeap_Exception e_HE){
hr = WBEM_E_OUT_OF_MEMORY;
pResponse->SetStatus(WBEM_STATUS_COMPLETE , hr, NULL, NULL);
if(pRObj){
pRObj->Cleanup();
delete pRObj;
}
}catch(HRESULT e_hr){
hr = e_hr;
pResponse->SetStatus(WBEM_STATUS_COMPLETE , hr, NULL, NULL);
if(pRObj){
pRObj->Cleanup();
delete pRObj;
}
}catch(...){
hr = WBEM_E_CRITICAL_ERROR;
pResponse->SetStatus(WBEM_STATUS_COMPLETE , hr, NULL, NULL);
if(pRObj){
pRObj->Cleanup();
delete pRObj;
}
}
#ifdef _PRIVATE_DEBUG
if(!HeapValidate(GetProcessHeap(),NULL , NULL)) DebugBreak();
#endif
return hr;
}
SCODE CMSIProv::DeleteInstanceAsync(const BSTR ObjectPath, long lFlags, IWbemContext *pCtx,
IWbemObjectSink *pResponse)
{
HRESULT hr = WBEM_S_NO_ERROR;
CRequestObject *pRObj = NULL;
try{
if(CheckForMsiDll()){
// Do a check of arguments and make sure we have pointer to Namespace
if(ObjectPath == NULL || pResponse == NULL )
{
return WBEM_E_INVALID_PARAMETER;
}
if(SUCCEEDED(hr = CheckImpersonationLevel())){
g_fpMsiSetInternalUI(INSTALLUILEVEL_NONE, NULL);
//Create the RequestObject
pRObj = new CRequestObject();
if(!pRObj) throw m_he;
pRObj->Initialize(m_pNamespace);
//Don't get package list
if(SUCCEEDED(hr = pRObj->InitializeList(false))){
//Delete the requested object
hr = pRObj->DeleteObject(ObjectPath, pResponse, pCtx);
}
pRObj->Cleanup();
delete pRObj;
}
}else{
hr = WBEM_E_NOT_AVAILABLE;
}
// Set Status
pResponse->SetStatus(0 ,hr , NULL, NULL);
}catch(CHeap_Exception e_HE){
hr = WBEM_E_OUT_OF_MEMORY;
pResponse->SetStatus(0 , hr, NULL, NULL);
if(pRObj){
pRObj->Cleanup();
delete pRObj;
}
}catch(HRESULT e_hr){
hr = e_hr;
pResponse->SetStatus(0 , hr, NULL, NULL);
if(pRObj){
pRObj->Cleanup();
delete pRObj;
}
}catch(...){
hr = WBEM_E_CRITICAL_ERROR;
pResponse->SetStatus(0 , hr, NULL, NULL);
if(pRObj){
pRObj->Cleanup();
delete pRObj;
}
}
#ifdef _PRIVATE_DEBUG
if(!HeapValidate(GetProcessHeap(),NULL , NULL)) DebugBreak();
#endif
return hr;
}
HRESULT CMSIProv::ExecQueryAsync(const BSTR QueryLanguage, const BSTR Query, long lFlags,
IWbemContext __RPC_FAR *pCtx, IWbemObjectSink __RPC_FAR *pResponseHandler)
{
HRESULT hr = WBEM_S_NO_ERROR;
#ifdef _EXEC_QUERY_SUPPORT
CRequestObject *pRObj = NULL;
CHeap_Exception he(CHeap_Exception::E_ALLOCATION_ERROR);
try
{
if(CheckForMsiDll())
{
// Do a check of arguments and make sure we have pointer to Namespace
if(0 != _wcsicmp(QueryLanguage, L"WQL") || Query == NULL || pResponseHandler == NULL )
{
return WBEM_E_INVALID_PARAMETER;
}
if(SUCCEEDED(hr = CheckImpersonationLevel()))
{
g_fpMsiSetInternalUI(INSTALLUILEVEL_NONE, NULL);
//Create the RequestObject
if ( ( pRObj = new CRequestObject() ) == NULL )
{
throw he;
}
pRObj->Initialize(m_pNamespace);
//Get package list
hr = pRObj->InitializeList(true);
if SUCCEEDED ( hr )
{
if ( hr != WBEM_S_NO_MORE_DATA )
{
//Get the requested object(s)
hr = pRObj->ExecQuery(Query, pResponseHandler, pCtx);
}
else
{
//return empty and success
hr = WBEM_S_NO_ERROR;
}
}
pRObj->Cleanup();
delete pRObj;
}
}
// Set Status
pResponseHandler->SetStatus(0 ,hr , NULL, NULL);
}
catch(CHeap_Exception e_HE)
{
hr = WBEM_E_OUT_OF_MEMORY;
pResponseHandler->SetStatus(0 , hr, NULL, NULL);
if(pRObj)
{
pRObj->Cleanup();
delete pRObj;
}
}
catch(HRESULT e_hr)
{
hr = e_hr;
pResponseHandler->SetStatus(0 , hr, NULL, NULL);
if(pRObj)
{
pRObj->Cleanup();
delete pRObj;
}
}
catch(...)
{
hr = WBEM_E_CRITICAL_ERROR;
pResponseHandler->SetStatus(0 , hr, NULL, NULL);
if(pRObj)
{
pRObj->Cleanup();
delete pRObj;
}
}
#else //_EXEC_QUERY_SUPPORT
hr = WBEM_E_NOT_SUPPORTED;
#endif
#ifdef _PRIVATE_DEBUG
if(!HeapValidate(GetProcessHeap(),NULL , NULL)) DebugBreak();
#endif //_PRIVATE_DEBUG
return hr;
}
//Ensure msi.dll and functions are loaded if present on system
bool CMSIProv::CheckForMsiDll()
{
EnterCriticalSection(&g_msi_prov_cs);
if(!g_bMsiLoaded){
HINSTANCE hiMsiDll = LoadLibraryW(L"msi.dll");
if(!hiMsiDll){
hiMsiDll = LoadLibrary(_T("msi.dll"));
if(!hiMsiDll){
TCHAR cBuf[MAX_PATH + 1];
if (0 != GetSystemDirectory(cBuf, MAX_PATH/*Number of TCHARs*/)){
_tcscat(cBuf, _T("\\msi.dll"));
hiMsiDll = LoadLibrary(cBuf);
}
}
}
if(hiMsiDll){
//Load the function pointers
g_fpMsiViewFetch = (LPFNMSIVIEWFETCH)GetProcAddress(hiMsiDll, "MsiViewFetch");
g_fpMsiRecordGetStringW = (LPFNMSIRECORDGETSTRINGW)GetProcAddress(hiMsiDll, "MsiRecordGetStringW");
g_fpMsiCloseHandle = (LPFNMSICLOSEHANDLE)GetProcAddress(hiMsiDll, "MsiCloseHandle");
g_fpMsiDatabaseOpenViewW = (LPFNMSIDATABASEOPENVIEWW)GetProcAddress(hiMsiDll, "MsiDatabaseOpenViewW");
g_fpMsiViewExecute = (LPFNMSIVIEWEXECUTE)GetProcAddress(hiMsiDll, "MsiViewExecute");
g_fpMsiGetActiveDatabase = (LPFNMSIGETACTIVEDATABASE)GetProcAddress(hiMsiDll, "MsiGetActiveDatabase");
g_fpMsiGetComponentPathW = (LPFNMSIGETCOMPONENTPATHW)GetProcAddress(hiMsiDll, "MsiGetComponentPathW");
g_fpMsiGetComponentStateW = (LPFNMSIGETCOMPONENTSTATEW)GetProcAddress(hiMsiDll, "MsiGetComponentStateW");
g_fpMsiOpenProductW = (LPFNMSIOPENPRODUCTW)GetProcAddress(hiMsiDll, "MsiOpenProductW");
g_fpMsiOpenPackageW = (LPFNMSIOPENPACKAGEW)GetProcAddress(hiMsiDll, "MsiOpenPackageW");
g_fpMsiDatabaseIsTablePersistentW = (LPFNMSIDATABASEISTABLEPERSITENTW)GetProcAddress(hiMsiDll, "MsiDatabaseIsTablePersistentW");
g_fpMsiSetInternalUI = (LPFNMSISETINTERNALUI)GetProcAddress(hiMsiDll, "MsiSetInternalUI");
g_fpMsiSetExternalUIW = (LPFNMSISETEXTERNALUIW)GetProcAddress(hiMsiDll, "MsiSetExternalUIW");
g_fpMsiEnableLogW = (LPFNMSIENABLELOGW)GetProcAddress(hiMsiDll, "MsiEnableLogW");
g_fpMsiGetProductPropertyW = (LPFNMSIGETPRODUCTPROPERTYW)GetProcAddress(hiMsiDll, "MsiGetProductPropertyW");
g_fpMsiQueryProductStateW = (LPFNMSIQUERYPRODUCTSTATEW)GetProcAddress(hiMsiDll, "MsiQueryProductStateW");
g_fpMsiInstallProductW = (LPFNMSIINSTALLPRODUCTW)GetProcAddress(hiMsiDll, "MsiInstallProductW");
g_fpMsiConfigureProductW = (LPFNMSICONFIGUREPRODUCTW)GetProcAddress(hiMsiDll, "MsiConfigureProductW");
g_fpMsiReinstallProductW = (LPFNMSIREINSTALLPRODUCTW)GetProcAddress(hiMsiDll, "MsiReinstallProductW");
g_fpMsiApplyPatchW = (LPFNMSIAPPLYPATCHW)GetProcAddress(hiMsiDll, "MsiApplyPatchW");
g_fpMsiRecordGetInteger = (LPFNMSIRECORDGETINTEGER)GetProcAddress(hiMsiDll, "MsiRecordGetInteger");
g_fpMsiEnumFeaturesW = (LPFNMSIENUMFEATURESW)GetProcAddress(hiMsiDll, "MsiEnumFeaturesW");
g_fpMsiGetProductInfoW = (LPFNMSIGETPRODUCTINFOW)GetProcAddress(hiMsiDll, "MsiGetProductInfoW");
g_fpMsiQueryFeatureStateW = (LPFNMSIQUERYFEATURESTATEW)GetProcAddress(hiMsiDll, "MsiQueryFeatureStateW");
g_fpMsiGetFeatureUsageW = (LPFNMSIGETFEATUREUSAGEW)GetProcAddress(hiMsiDll, "MsiGetFeatureUsageW");
g_fpMsiGetFeatureInfoW = (LPFNMSIGETFEATUREINFOW)GetProcAddress(hiMsiDll, "MsiGetFeatureInfoW");
g_fpMsiConfigureFeatureW = (LPFNMSICONFIGUREFEATUREW)GetProcAddress(hiMsiDll, "MsiConfigureFeatureW");
g_fpMsiReinstallFeatureW = (LPFNMSIREINSTALLFEATUREW)GetProcAddress(hiMsiDll, "MsiReinstallFeatureW");
g_fpMsiEnumProductsW = (LPFNMSIENUMPRODUCTSW)GetProcAddress(hiMsiDll, "MsiEnumProductsW");
g_fpMsiGetDatabaseState = (LPFNMSIGETDATABASESTATE)GetProcAddress(hiMsiDll, "MsiGetDatabaseState");
g_fpMsiRecordSetStringW = (LPFNMSIRECORDSETSTRINGW)GetProcAddress(hiMsiDll, "MsiRecordSetStringW");
g_fpMsiDatabaseCommit = (LPFNMSIDATABASECOMMIT)GetProcAddress(hiMsiDll, "MsiDatabaseCommit");
g_fpMsiEnumComponentsW = (LPFNMSIENUMCOMPONENTSW)GetProcAddress(hiMsiDll, "MsiEnumComponentsW");
g_fpMsiViewClose = (LPFNMSIVIEWCLOSE)GetProcAddress(hiMsiDll, "MsiViewClose");
// Did we get all the pointers we need?
if(g_fpMsiViewFetch && g_fpMsiRecordGetStringW && g_fpMsiCloseHandle &&
g_fpMsiDatabaseOpenViewW && g_fpMsiViewExecute && g_fpMsiGetActiveDatabase &&
g_fpMsiGetComponentPathW && g_fpMsiGetComponentStateW && g_fpMsiOpenProductW &&
g_fpMsiOpenPackageW && g_fpMsiDatabaseIsTablePersistentW && g_fpMsiSetInternalUI &&
g_fpMsiSetExternalUIW && g_fpMsiEnableLogW && g_fpMsiGetProductPropertyW &&
g_fpMsiQueryProductStateW && g_fpMsiInstallProductW && g_fpMsiConfigureProductW &&
g_fpMsiReinstallProductW && g_fpMsiApplyPatchW && g_fpMsiRecordGetInteger &&
g_fpMsiEnumFeaturesW && g_fpMsiGetProductInfoW && g_fpMsiQueryFeatureStateW &&
g_fpMsiGetFeatureUsageW && g_fpMsiGetFeatureInfoW && g_fpMsiConfigureFeatureW &&
g_fpMsiReinstallFeatureW && g_fpMsiEnumProductsW && g_fpMsiGetDatabaseState &&
g_fpMsiRecordSetStringW && g_fpMsiDatabaseCommit && g_fpMsiEnumComponentsW &&
g_fpMsiViewClose){
g_bMsiLoaded = true;
}
}else{
g_bMsiPresent = false;
}
}
LeaveCriticalSection(&g_msi_prov_cs);
return g_bMsiLoaded;
}
bool UnloadMsiDll()
{
bool bRetVal = true;
EnterCriticalSection(&g_msi_prov_cs);
if(g_bMsiLoaded){
if(FreeLibrary(GetModuleHandle(L"msi.dll"))){
g_bMsiLoaded = false;
bRetVal = true;
}else bRetVal = false;
}
LeaveCriticalSection(&g_msi_prov_cs);
return bRetVal;
}
|
3caf715a05c92baaf8d57ba5d101769108f7563b | 33fb48fea58ed38ad9a9479dbad3075227b1bbea | /Code/Game/Entity.cpp | a9fbcb2da6fe3e947610307c8cacda0ca33664e6 | [] | no_license | pronaypeddiraju/ProtoPhysX | e73a0441f03199e8f00e8d6305676f4d418a5847 | c132714081e874712b802bf19ae2aaa4b778fb6d | refs/heads/master | 2020-05-31T03:45:38.849966 | 2019-10-16T05:23:22 | 2019-10-16T05:23:22 | 190,086,152 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 446 | cpp | Entity.cpp | #include "Game/Entity.hpp"
void Entity::Render()
{
//m_game->
}
void Entity::RunFrame()
{
}
void Entity::Update(float deltaTime)
{
UNUSED (deltaTime);
if(m_position.x >= 0.f && m_position.x <= 200.f && m_position.y >= 0.f && m_position.y <= 100.f)
m_isOffScreen = false;
else
{
m_isOffScreen = true;
}
}
Entity::Entity(Game* currentGame)
: m_game (currentGame)
{
m_isGarbage = false;
m_isAlive = true;
}
Entity::~Entity()
{
} |
1fb31520664f5e43a6ed8a72f27a3865e0e12ec7 | 8ab670bb0d19d1b9bf409910a96dfbee1113bd53 | /osquery/logger/logger.cpp | 1865908887ea461048bf24d3272c882cffe37152 | [
"BSD-3-Clause"
] | permissive | zglx2008/osquery | 2c36865b68384f2528374de65d02d2766f2980bf | dd7f8b6fd193c331eece0d172dd0d804fd332598 | refs/heads/master | 2021-01-16T23:14:03.850317 | 2015-02-05T04:46:37 | 2015-02-05T04:46:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,121 | cpp | logger.cpp | /*
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <algorithm>
#include <thread>
#include <osquery/flags.h>
#include <osquery/logger.h>
namespace osquery {
/// `log_receiver` defines the default log receiver plugin name.
DEFINE_osquery_flag(string,
log_receiver,
"filesystem",
"The upstream log receiver to log messages to.");
DEFINE_osquery_flag(bool,
log_result_events,
true,
"Log scheduled results as events.");
Status LoggerPlugin::call(const PluginRequest& request,
PluginResponse& response) {
if (request.count("string") == 0) {
return Status(1, "Logger plugins only support a request string");
}
this->logString(request.at("string"));
return Status(0, "OK");
}
Status logString(const std::string& s) {
return logString(s, FLAGS_log_receiver);
}
Status logString(const std::string& s, const std::string& receiver) {
if (!Registry::exists("logger", receiver)) {
LOG(ERROR) << "Logger receiver " << receiver << " not found";
return Status(1, "Logger receiver not found");
}
auto status = Registry::call("logger", receiver, {{"string", s}});
return Status(0, "OK");
}
Status logScheduledQueryLogItem(const osquery::ScheduledQueryLogItem& results) {
return logScheduledQueryLogItem(results, FLAGS_log_receiver);
}
Status logScheduledQueryLogItem(const osquery::ScheduledQueryLogItem& results,
const std::string& receiver) {
std::string json;
Status status;
if (FLAGS_log_result_events) {
status = serializeScheduledQueryLogItemAsEventsJSON(results, json);
} else {
status = serializeScheduledQueryLogItemJSON(results, json);
}
if (!status.ok()) {
return status;
}
return logString(json, receiver);
}
}
|
f850ef715ed38ae6560c9b6dc08f9323cefac3a3 | cecfda84e25466259d3ef091953c3ac7b44dc1fc | /UVa Online Judge/volume117/11742 Social Constraints/program.cpp | 09d37cd332f9c3440e60d8b231e45fa138a4b0cf | [] | no_license | metaphysis/Code | 8e3c3610484a8b5ca0bb116bc499a064dda55966 | d144f4026872aae45b38562457464497728ae0d6 | refs/heads/master | 2023-07-26T12:44:21.932839 | 2023-07-12T13:39:41 | 2023-07-12T13:39:41 | 53,327,611 | 231 | 57 | null | null | null | null | UTF-8 | C++ | false | false | 1,529 | cpp | program.cpp | // Social Constraints
// UVa ID: 11742
// Verdict: Accepted
// Submission Date: 2017-11-11
// UVa Run Time: 0.000s
//
// 版权所有(C)2017,邱秋。metaphysis # yeah dot net
#include <bits/stdc++.h>
using namespace std;
struct constraint
{
int a, b, c;
} constraints[24];
int main(int argc, char *argv[])
{
cin.tie(0), cout.tie(0), ios::sync_with_stdio(false);
int n, m;
while (cin >> n >> m, n > 0)
{
for (int i = 0; i < m; i++)
cin >> constraints[i].a >> constraints[i].b >> constraints[i].c;
vector<int> seat(n);
iota(seat.begin(), seat.end(), 0);
int valid = 0;
do
{
bool conflicted = false;
for (int i = 0; i < m; i++)
{
if (constraints[i].c > 0)
{
if (abs(seat[constraints[i].a] - seat[constraints[i].b]) > constraints[i].c)
{
conflicted = true;
break;
}
}
else
{
if (abs(seat[constraints[i].a] - seat[constraints[i].b]) < -constraints[i].c)
{
conflicted = true;
break;
}
}
}
if (!conflicted) valid++;
} while (next_permutation(seat.begin(), seat.end()));
cout << valid << '\n';
}
return 0;
}
|
f13324ff369faa7c4aa3233a86db479c0df45f6a | fb4eacf0a4608b10f49721963f81756959b03305 | /dsaclarno.20.cpp | 6eff54d759062ae88f97fca26d8635da359e2388 | [] | no_license | abhiyankmishra/data-structure | 8de92ba1574ac0ec90723339cd9c0d6e9a4056fd | 1165d797b492a924de2e5e22a52f59c4338797b8 | refs/heads/main | 2023-04-03T03:01:47.934786 | 2021-04-16T19:42:37 | 2021-04-16T19:42:37 | 358,700,377 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 926 | cpp | dsaclarno.20.cpp | // ############solved on leet code
class Solution {
public:
void nextPermutation(vector<int>& a) {
int idx=-1;
int n=a.size();
for(int i=n-1;i>0;i--)
{if(a[i]>a[i-1])
{
idx=i;
break;
}
}
if(idx==-1)
{
reverse(a.begin(),a.end());
}
else{
int prev=idx;
for(int i=idx+1;i<n;i++)
{if(a[i]>a[idx-1] && a[i]<=a[prev])
{
prev=i
}}
swap(a[idx-1],a[prev]);
reverse(a.begin()+idx,a.end());
}
}
}; |
c251ac39579f16295e2b347b3c2bad63efe08988 | 319a96494cb60f76baeb7db98b284169729f700f | /src/http_message.cpp | eabf212ea958da12cd79a9263888227c69d3606a | [
"BSL-1.0"
] | permissive | splunk/pion | d082bfd112ab515971a2217103c7d130d3e9031d | e5a258b271ed25be5e08b729568927febc288b41 | refs/heads/develop | 2023-08-13T03:54:30.761585 | 2020-01-31T00:15:56 | 2020-01-31T00:15:56 | 5,138,891 | 209 | 72 | BSL-1.0 | 2020-04-09T07:57:15 | 2012-07-22T03:57:23 | C++ | UTF-8 | C++ | false | false | 8,734 | cpp | http_message.cpp | // ---------------------------------------------------------------------
// pion: a Boost C++ framework for building lightweight HTTP interfaces
// ---------------------------------------------------------------------
// Copyright (C) 2007-2014 Splunk Inc. (https://github.com/splunk/pion)
//
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
//
#include <iostream>
#include <algorithm>
#include <boost/asio.hpp>
#include <boost/assert.hpp>
#include <boost/regex.hpp>
#include <boost/logic/tribool.hpp>
#include <pion/http/message.hpp>
#include <pion/http/request.hpp>
#include <pion/http/parser.hpp>
#include <pion/tcp/connection.hpp>
namespace pion { // begin namespace pion
namespace http { // begin namespace http
// static members of message
const boost::regex message::REGEX_ICASE_CHUNKED(".*chunked.*", boost::regex::icase);
// message member functions
std::size_t message::send(tcp::connection& tcp_conn,
boost::system::error_code& ec, bool headers_only)
{
// initialize write buffers for send operation using HTTP headers
write_buffers_t write_buffers;
prepare_buffers_for_send(write_buffers, tcp_conn.get_keep_alive(), false);
// append payload content to write buffers (if there is any)
if (!headers_only && get_content_length() > 0 && get_content() != NULL)
write_buffers.push_back(boost::asio::buffer(get_content(), get_content_length()));
// send the message and return the result
return tcp_conn.write(write_buffers, ec);
}
std::size_t message::receive(tcp::connection& tcp_conn,
boost::system::error_code& ec,
parser& http_parser)
{
std::size_t last_bytes_read = 0;
// make sure that we start out with an empty message
clear();
if (tcp_conn.get_pipelined()) {
// there are pipelined messages available in the connection's read buffer
const char *read_ptr;
const char *read_end_ptr;
tcp_conn.load_read_pos(read_ptr, read_end_ptr);
last_bytes_read = (read_end_ptr - read_ptr);
http_parser.set_read_buffer(read_ptr, last_bytes_read);
} else {
// read buffer is empty (not pipelined) -> read some bytes from the connection
last_bytes_read = tcp_conn.read_some(ec);
if (ec) return 0;
BOOST_ASSERT(last_bytes_read > 0);
http_parser.set_read_buffer(tcp_conn.get_read_buffer().data(), last_bytes_read);
}
// incrementally read and parse bytes from the connection
bool force_connection_closed = false;
boost::tribool parse_result;
while (true) {
// parse bytes available in the read buffer
parse_result = http_parser.parse(*this, ec);
if (! boost::indeterminate(parse_result)) break;
// read more bytes from the connection
last_bytes_read = tcp_conn.read_some(ec);
if (ec || last_bytes_read == 0) {
if (http_parser.check_premature_eof(*this)) {
// premature EOF encountered
if (! ec)
ec = make_error_code(boost::system::errc::io_error);
return http_parser.get_total_bytes_read();
} else {
// EOF reached when content length unknown
// assume it is the correct end of content
// and everything is OK
force_connection_closed = true;
parse_result = true;
ec.clear();
break;
}
break;
}
// update the HTTP parser's read buffer
http_parser.set_read_buffer(tcp_conn.get_read_buffer().data(), last_bytes_read);
}
if (parse_result == false) {
// an error occurred while parsing the message headers
return http_parser.get_total_bytes_read();
}
// set the connection's lifecycle type
if (!force_connection_closed && check_keep_alive()) {
if ( http_parser.eof() ) {
// the connection should be kept alive, but does not have pipelined messages
tcp_conn.set_lifecycle(tcp::connection::LIFECYCLE_KEEPALIVE);
} else {
// the connection has pipelined messages
tcp_conn.set_lifecycle(tcp::connection::LIFECYCLE_PIPELINED);
// save the read position as a bookmark so that it can be retrieved
// by a new HTTP parser, which will be created after the current
// message has been handled
const char *read_ptr;
const char *read_end_ptr;
http_parser.load_read_pos(read_ptr, read_end_ptr);
tcp_conn.save_read_pos(read_ptr, read_end_ptr);
}
} else {
// default to close the connection
tcp_conn.set_lifecycle(tcp::connection::LIFECYCLE_CLOSE);
// save the read position as a bookmark so that it can be retrieved
// by a new HTTP parser
if (http_parser.get_parse_headers_only()) {
const char *read_ptr;
const char *read_end_ptr;
http_parser.load_read_pos(read_ptr, read_end_ptr);
tcp_conn.save_read_pos(read_ptr, read_end_ptr);
}
}
return (http_parser.get_total_bytes_read());
}
std::size_t message::receive(tcp::connection& tcp_conn,
boost::system::error_code& ec,
bool headers_only,
std::size_t max_content_length)
{
http::parser http_parser(dynamic_cast<http::request*>(this) != NULL);
http_parser.parse_headers_only(headers_only);
http_parser.set_max_content_length(max_content_length);
return receive(tcp_conn, ec, http_parser);
}
std::size_t message::write(std::ostream& out,
boost::system::error_code& ec, bool headers_only)
{
// reset error_code
ec.clear();
// initialize write buffers for send operation using HTTP headers
write_buffers_t write_buffers;
prepare_buffers_for_send(write_buffers, true, false);
// append payload content to write buffers (if there is any)
if (!headers_only && get_content_length() > 0 && get_content() != NULL)
write_buffers.push_back(boost::asio::buffer(get_content(), get_content_length()));
// write message to the output stream
std::size_t bytes_out = 0;
for (write_buffers_t::const_iterator i=write_buffers.begin(); i!=write_buffers.end(); ++i) {
const char *ptr = boost::asio::buffer_cast<const char*>(*i);
size_t len = boost::asio::buffer_size(*i);
out.write(ptr, len);
if (!out) {
ec = make_error_code(boost::system::errc::io_error);
break;
}
bytes_out += len;
}
return bytes_out;
}
std::size_t message::read(std::istream& in,
boost::system::error_code& ec,
parser& http_parser)
{
// make sure that we start out with an empty message & clear error_code
clear();
ec.clear();
// parse data from file one byte at a time
boost::tribool parse_result;
char c;
while (in) {
in.read(&c, 1);
if ( ! in ) {
ec = make_error_code(boost::system::errc::io_error);
break;
}
http_parser.set_read_buffer(&c, 1);
parse_result = http_parser.parse(*this, ec);
if (! boost::indeterminate(parse_result)) break;
}
if (boost::indeterminate(parse_result)) {
if (http_parser.check_premature_eof(*this)) {
// premature EOF encountered
if (! ec)
ec = make_error_code(boost::system::errc::io_error);
} else {
// EOF reached when content length unknown
// assume it is the correct end of content
// and everything is OK
parse_result = true;
ec.clear();
}
}
return (http_parser.get_total_bytes_read());
}
std::size_t message::read(std::istream& in,
boost::system::error_code& ec,
bool headers_only,
std::size_t max_content_length)
{
http::parser http_parser(dynamic_cast<http::request*>(this) != NULL);
http_parser.parse_headers_only(headers_only);
http_parser.set_max_content_length(max_content_length);
return read(in, ec, http_parser);
}
void message::concatenate_chunks(void)
{
set_content_length(m_chunk_cache.size());
char *post_buffer = create_content_buffer();
if (m_chunk_cache.size() > 0)
std::copy(m_chunk_cache.begin(), m_chunk_cache.end(), post_buffer);
}
} // end namespace http
} // end namespace pion
|
912dd919ea65b5394139d47e4babe44b72ca49d5 | e8a3c0b3722cacdb99e15693bff0a4333b7ccf16 | /Uva Oj/11609 Teams.cpp | 032219d8a0b73dd023fdc44ba259fcce57212ad8 | [] | no_license | piyush1146115/Competitive-Programming | 690f57acd374892791b16a08e14a686a225f73fa | 66c975e0433f30539d826a4c2aa92970570b87bf | refs/heads/master | 2023-08-18T03:04:24.680817 | 2023-08-12T19:15:51 | 2023-08-12T19:15:51 | 211,923,913 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 633 | cpp | 11609 Teams.cpp | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define mod 1000000007
ll bm(ll n)
{
if(n == 0)
return 1;
if(n % 2 == 0){
ll p = bm(n/2);
return ((p % mod) * (p % mod))%mod;
}
else{
return (2 * (bm(n - 1) % mod)) % mod;
}
}
int main()
{
ll n, i, j, test, cs= 0;
scanf("%lld",&test);
while(test--){
scanf("%lld",&n);
ll ans;
if(n == 1)
ans = 1;
else
ans = ((n % mod) * bm(n - 1))%mod;
printf("Case #%lld: %lld\n", ++cs, ans);
}
return 0;
}
|
3ce66491b2c7f4cd263f94d63b78e9a12b5592a1 | 443437c7a9feef8d55ca133986c9298c23bfbbeb | /cpp_practice/prog04.cpp | ab12f60fae64b64d2a579a27471d3871ab304446 | [] | no_license | jj1and/program_practice | 8ed65b069ce3a0c37910428423d8fcf2561e3f38 | 3a6015b0915635886fc4e77ba30fd3eed891ee8f | refs/heads/master | 2020-03-17T09:43:28.934488 | 2018-10-27T13:58:53 | 2018-10-27T13:58:53 | 133,485,855 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 441 | cpp | prog04.cpp | #include<iostream>
using namespace std;
class base{
protected:
int a, b;
public:
void setab(int n, int m){a =n; b=m;};
};
class derived : public base{
private:
int c;
public:
void setc(int n){c=n;}
void showabc(){
cout << a << ' ' << b << ' ' << c << endl;
};
};
int main(){
derived ob;
ob.setab(1,2);
ob.setc(3);
ob.showabc();
return 0;
} |
d4c7182d854e983d99fcd1b90963fb76439b334d | 188db56162f616f5ed2972ab5f6c594c1793b5db | /src/c++/include/io/FastqLoader.hh | 9777bfda25f2f634acc1869a8d797bfc452c8872 | [
"BSD-3-Clause",
"BSL-1.0",
"BSD-2-Clause"
] | permissive | simplelive/isaac_aligner | c1833d8a14c3ffd75f611b9e4df8b609269433a1 | fd092ec20d82548a90c53eafdaed7d617328a6a4 | refs/heads/master | 2021-01-18T06:39:40.867905 | 2015-04-07T10:12:05 | 2015-04-07T10:12:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,606 | hh | FastqLoader.hh | /**
** Isaac Genome Alignment Software
** Copyright (c) 2010-2014 Illumina, Inc.
** All rights reserved.
**
** This software is provided under the terms and conditions of the
** BSD 2-Clause License
**
** You should have received a copy of the BSD 2-Clause License
** along with this program. If not, see
** <https://github.com/sequencing/licenses/>.
**
** \file FastqLoader.hh
**
** Component to read FASTQ files.
**
** \author Roman Petrovski
**/
#ifndef iSAAC_IO_FASTQ_LOADER_HH
#define iSAAC_IO_FASTQ_LOADER_HH
#include "common/Threads.hpp"
#include "io/FastqReader.hh"
namespace isaac
{
namespace io
{
//#pragma GCC push_options
//#pragma GCC optimize ("0")
class FastqLoader
{
FastqReader read1Reader_;
FastqReader read2Reader_;
bool paired_;
common::ThreadVector &threads_;
const unsigned inputLoadersMax_;
public:
/**
* \brief initializes paired fastq loader.
*/
/**
* \brief Creates uninitialized fastq loader
*/
FastqLoader(
const bool allowVariableLength,
std::size_t maxPathLength,
common::ThreadVector &threads,
const unsigned inputLoadersMax) :
read1Reader_(allowVariableLength),
read2Reader_(allowVariableLength),
paired_(false),
threads_(threads),
inputLoadersMax_(inputLoadersMax)
{
read1Reader_.reservePathBuffers(maxPathLength);
read2Reader_.reservePathBuffers(maxPathLength);
}
void open(
const boost::filesystem::path &read1Path)
{
read1Reader_.open(read1Path);
paired_ = false;
}
void open(
const boost::filesystem::path &read1Path,
const boost::filesystem::path &read2Path)
{
read1Reader_.open(read1Path);
read2Reader_.open(read2Path);
paired_ = true;
}
/**
* \param clusterCount Maximum number of clusters to load
* \param clusterLength Expected cluster length. Will fail if the read cluster length does not match
* \param it Insert iterator for the buffer that is sufficient to load the clusterCount
* clusters of clusterLength
*
* \return Actual number of loaded clusters
*/
template <typename InsertIt>
unsigned loadClusters(unsigned clusterCount, const flowcell::ReadMetadataList &readMetadataList, InsertIt &it)
{
if (1 == readMetadataList.size())
{
return loadSingleRead(read1Reader_, clusterCount, readMetadataList.at(0), 0, it);
}
else
{
ISAAC_ASSERT_MSG(2 == readMetadataList.size(), "Only paired and single-ended data is supported");
unsigned readClusters[2] = {0,0};
InsertIt it1 = it;
if (2 <= inputLoadersMax_)
{
it += readMetadataList.at(0).getLength();
boost::reference_wrapper<InsertIt> insertIterators[] = {boost::ref(it1), boost::ref(it)};
threads_.execute(boost::bind(&FastqLoader::threadLoadPairedReads<InsertIt>, this,
clusterCount, boost::ref(readMetadataList),
boost::ref(readClusters), insertIterators, _1),
2);
}
else
{
ISAAC_ASSERT_MSG(1 == inputLoadersMax_, "At least one thread is expected for IO")
readClusters[0] = loadSingleRead(read1Reader_, clusterCount, readMetadataList.at(0), readMetadataList.at(1).getLength(), it1);
it += readMetadataList.at(0).getLength();
readClusters[1] = loadSingleRead(read2Reader_, clusterCount, readMetadataList.at(1), readMetadataList.at(0).getLength(), it);
}
if (readClusters[0] != readClusters[1])
{
BOOST_THROW_EXCEPTION(common::IoException(errno, (boost::format("Mismatching number of cluster read for r1/r2 = %d/%d, files: %s/%s") %
readClusters[0] % readClusters[1] % read1Reader_.getPath() % read2Reader_.getPath()).str()));
}
return readClusters[0];
}
}
private:
template <typename InsertIt>
static unsigned loadSingleRead(FastqReader &reader, unsigned clusterCount,
const flowcell::ReadMetadata &readMetadata,
const unsigned step, InsertIt &it)
{
unsigned clustersToRead = clusterCount;
for (;clustersToRead && reader.hasData();)
{
it = reader.extractBcl(readMetadata, it);
reader.next();
// avoid debug glibc complaining about advancing iterator past the end of the container
if (--clustersToRead)
{
std::advance(it, step);
}
}
return clusterCount - clustersToRead;
}
template <typename InsertIt>
void threadLoadPairedReads(unsigned clusterCount,
const flowcell::ReadMetadataList &readMetadataList,
unsigned readClusters[2], boost::reference_wrapper<InsertIt> insertIterators[2], int threadNumber)
{
readClusters[threadNumber] = loadSingleRead(
threadNumber ? read2Reader_ : read1Reader_,
clusterCount, readMetadataList.at(threadNumber),
readMetadataList.at((threadNumber + 1) % 2).getLength(), insertIterators[threadNumber].get());
}
};
//#pragma GCC pop_options
} // namespace io
} // namespace isaac
#endif // #ifndef iSAAC_IO_FASTQ_LOADER_HH
|
eafdaef671e369dbd10a3488ac37b8e734112ef9 | cfeac52f970e8901871bd02d9acb7de66b9fb6b4 | /generated/src/aws-cpp-sdk-securityhub/source/model/Adjustment.cpp | da8c10b68681e982dd0721bdab95314f3fd75574 | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | aws/aws-sdk-cpp | aff116ddf9ca2b41e45c47dba1c2b7754935c585 | 9a7606a6c98e13c759032c2e920c7c64a6a35264 | refs/heads/main | 2023-08-25T11:16:55.982089 | 2023-08-24T18:14:53 | 2023-08-24T18:14:53 | 35,440,404 | 1,681 | 1,133 | Apache-2.0 | 2023-09-12T15:59:33 | 2015-05-11T17:57:32 | null | UTF-8 | C++ | false | false | 1,218 | cpp | Adjustment.cpp | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/securityhub/model/Adjustment.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace SecurityHub
{
namespace Model
{
Adjustment::Adjustment() :
m_metricHasBeenSet(false),
m_reasonHasBeenSet(false)
{
}
Adjustment::Adjustment(JsonView jsonValue) :
m_metricHasBeenSet(false),
m_reasonHasBeenSet(false)
{
*this = jsonValue;
}
Adjustment& Adjustment::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("Metric"))
{
m_metric = jsonValue.GetString("Metric");
m_metricHasBeenSet = true;
}
if(jsonValue.ValueExists("Reason"))
{
m_reason = jsonValue.GetString("Reason");
m_reasonHasBeenSet = true;
}
return *this;
}
JsonValue Adjustment::Jsonize() const
{
JsonValue payload;
if(m_metricHasBeenSet)
{
payload.WithString("Metric", m_metric);
}
if(m_reasonHasBeenSet)
{
payload.WithString("Reason", m_reason);
}
return payload;
}
} // namespace Model
} // namespace SecurityHub
} // namespace Aws
|
90f48c5ed83178ea652b4a96ae66de538b768a8c | 539bd4489cc30c25a806b2de9816ca354ebb4abf | /include/hypergraph/VertexNode.hpp | a28ffbed785b56c589ea50c809a8eb81f520ca37 | [
"LicenseRef-scancode-philippe-de-muyter"
] | permissive | kittobi1992/parkway | f4debf2826f73c5df55572a806d907f81ddb9f52 | 6501c96268acc1997894bb577cbca0e21c5e2ac8 | refs/heads/master | 2021-05-18T15:04:36.085704 | 2020-03-31T10:35:29 | 2020-03-31T10:35:29 | 251,291,502 | 0 | 0 | null | 2020-03-30T11:59:54 | 2020-03-30T11:59:53 | null | UTF-8 | C++ | false | false | 434 | hpp | VertexNode.hpp | #ifndef _VERTEX_NODE_HPP
#define _VERTEX_NODE_HPP
// ### VertexNode.hpp ###
//
// Copyright (C) 2004, Aleksandar Trifunovic, Imperial College London
//
// HISTORY:
//
// 30/11/2004: Last Modified
//
// ###
#include "data_structures/dynamic_array.hpp"
typedef struct VertexNode {
int vertexID;
VertexNode *next;
} VNode;
typedef VNode *VNodePtr;
typedef parkway::data_structures::dynamic_array<VNodePtr> VNodePtrArray;
#endif
|
1437c03000f7a9fc089e15eeada5932f9993403c | be21b569d9a0cbe5736caf1a205faa3f5c2f515d | /Project2/LabeledGraph.cpp | 49f9f24e667d6e76a88c0a1e0dff2d29034c2669 | [] | no_license | nusratha2016/CS312 | a9939e8cbc2d74086ad8cf05ba952096d0e469cc | 1f3ecde5a2c3109e06345c459b548ff068ccb1e2 | refs/heads/master | 2020-08-31T05:54:39.580129 | 2020-03-20T01:09:07 | 2020-03-20T01:09:07 | 218,613,601 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,672 | cpp | LabeledGraph.cpp | #include <set>
#include <map>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include "LabeledGraph.h"
using namespace std;
void LabeledGraph::add_vertex(string vlabel) {
labels.push_back(vlabel);
indexedLabels.insert(pair<string, int>(vlabel, V()));
set<int> s;
vertices.push_back(s);
}
void LabeledGraph::add_edge(string source, string target) {
if (!contains(source))
add_vertex(source);
if (!contains(target))
add_vertex(target);
vertices[indexedLabels[source]].insert(indexedLabels[target]);
vertices[indexedLabels[target]].insert(indexedLabels[source]);
nedges++;
}
bool LabeledGraph::contains(string vlabel)const {
return indexedLabels.find(vlabel) != indexedLabels.end();
}
set<int> LabeledGraph::neighbors(int v) const {
return vertices[v];
}
string LabeledGraph::label(int v) const {
return labels[v];
}
int LabeledGraph::index(string vlabel) {
if(contains(vlabel)) {
return indexedLabels[vlabel];
}
return -1;
}
ostream& operator<< (ostream &out, LabeledGraph &g) {
set<int>::iterator it;
cout<<"=========================================\n";
cout<<"Graph Summary: "
<<g.V() <<" vertices, "
<<g.E() <<" edges.\n";
cout<<"=========================================\n";
for(int i = 0; i < g.V(); i++) {
string GetCurrent = g.label(i);
cout << GetCurrent <<":\n";
int idx = g.index(GetCurrent);
set<int>GetnextNeighbor;
if(idx >-1) GetnextNeighbor = g.neighbors(idx);
for(it = GetnextNeighbor.begin(); it != GetnextNeighbor.end();
it++) {
cout<<"\t"<<g.label(*(it))<<endl;
}
}
return out;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.