text
stringlengths 8
6.88M
|
|---|
#include<iostream>
#include<cstring>
using namespace std;
class Customer
{ private:
char Customer_Name[20], E_mail[30];
int Customer_ID;
long int Telephone_Number;
char Address[50], NIC_NO[25];
public:
void Add_New_Customer(int id);
void Add_New_Customer( int id,char name[20],char email[30],long int telephone,char address[50],char nic[25]);
int search(int s);
void Display_Customer_Record();
int Customer_id_exist(int j);
void deletecustomer();
int checkspace();
};
class Account
{ private:
int Account_ID,Customer_ID;
char Account_Type[20];
double Balance;
char Date_of_Creation[20];
public:
double check(int a);
int search(int a);
void addnewaccount(int a,int b);
void addnewaccount( int accountid, long int customerid,char accounttype[20],double bal,char date[20]);
void Display_Account_Details();
void deleteaccount();
int checkspace();
void balanceupdate(double b);
};
class Transaction
{private:
int Transaction_ID,Account_ID;
char Transaction_Type[20];
double Amount_Transacted;
public:
int search_transaction(int i);
void Make_New_Transaction(int a,int b,double bal, char trans_type[20]);
void Make_New_Transaction(int tans_id, int account_id,char transiction_type[20],double amount_transacted);
void Display_Transaction();
};
int Customer::Customer_id_exist(int j)
{ if(j==Customer_ID)
return 1;
else
return 0;
}
void Customer::Add_New_Customer(int id)
{
cout<<"Enter Customer name"<<endl;
if(cin.peek()=='\n') cin.ignore();
cin.getline(Customer_Name,20);
cout<<"enter email"<<endl;
cin.getline(E_mail,30);
cout<<"enter Address"<<endl;
cin.getline(Address,50);
cout<<"enter cnic"<<endl;
cin.getline(NIC_NO,25);
cout<<"enter telephone number"<<endl;
cin>>Telephone_Number;
Customer_ID=id;
}
void Customer::Add_New_Customer( int id,char name[20],char email[30],long int telephone,char address[50],char nic[25])
{ Customer_ID=id;
strcpy(Customer_Name,name);
strcpy(E_mail,email);
Telephone_Number=telephone;
strcpy(Address,address);
strcpy(NIC_NO,nic);
}
int Customer::search(int s)
{ if(Customer_ID==s)
{
return 1;
}
else
return 0;
}
void Customer::Display_Customer_Record()
{if(Customer_ID!=0 || strcmp(Customer_Name,"\0")!=0)
{
cout<<"customer id is "<<Customer_ID<<endl;
cout<<"customer name is "<<Customer_Name<<endl;
cout<<"Email is "<<E_mail<<endl;
cout<<"Telephone number is "<<Telephone_Number<<endl;
cout<<"Address is "<<Address<<endl;
cout<<"Cnic number is "<<NIC_NO<<endl;
cout<<"*******************************"<<endl<<endl;
}
}
void Customer::deletecustomer()
{ Customer_ID=0;
strcpy(Customer_Name,"\0");
strcpy(E_mail,"\0");
strcpy(NIC_NO,"\0");
Telephone_Number=0;
}
int Customer::checkspace()
{
if(Customer_ID==0 && strcmp(Customer_Name,"\0")==0)
{
return 1;
}
else
return 0;
}
double Account:: check(int a)
{
if(a==Account_ID)
{
return Balance;
}
else
return 0;
}
int Account::search(int a)
{
if(a==Account_ID)
{
return 1;
}
else
return 0;
}
void Account::addnewaccount(int a,int b)
{Account_ID=a;
Customer_ID=b;
if(cin.peek()=='\n') cin.ignore();
cout<<"Enter Account type"<<endl;
cin.getline(Account_Type,20);
cout<<"enter balance"<<endl;
cin>>Balance;
if(cin.peek()=='\n') cin.ignore();
cout<<"enter date"<<endl;
cin.getline(Date_of_Creation,20);
}
void Account::addnewaccount( int accountid, long int customerid,char accounttype[20],double bal,char date[20])
{
Account_ID=accountid;
Customer_ID=customerid;
strcpy(Account_Type,accounttype);
Balance=bal;
strcpy(Date_of_Creation,date);
}
void Account::Display_Account_Details()
{if(Account_ID!=0 || Customer_ID!=0)
{
cout<<"customer id is "<<Customer_ID<<endl;
cout<<"Account id is "<<Account_ID<<endl;
cout<<"Account Type is "<<Account_Type<<endl;
cout<<"Date of creation is "<<Date_of_Creation<<endl;
cout<<"Total Balance is "<< Balance<<endl;
cout<<"*******************************"<<endl<<endl;
}
}
void Account::deleteaccount()
{ Customer_ID=0;
Account_ID=0;
strcpy(Account_Type,"\0");
Balance=0;
strcpy(Date_of_Creation,"\0");
}
int Account::checkspace()
{
if(Customer_ID==0 && Account_ID==0)
{ return 1;
}
else
return 0;
}
void Account:: balanceupdate(double b)
{Balance=b;
}
int Transaction::search_transaction(int i)
{
if(i==Transaction_ID)
{
return 1;
}
else
return 0;
}
void Transaction:: Make_New_Transaction(int a,int b,double bal, char trans_type[20])
{ Transaction_ID=b;
Account_ID=a;
strcpy(Transaction_Type,trans_type);
Amount_Transacted=bal;
}
void Transaction::Make_New_Transaction(int tans_id, int account_id,char transiction_type[20],double amount_transacted)
{ Transaction_ID=tans_id;
Account_ID=account_id;
strcpy(Transaction_Type,transiction_type);
Amount_Transacted=amount_transacted;
}
void Transaction::Display_Transaction()
{
cout<<"Transaction id is "<<Transaction_ID<<endl;
cout<<"Account id is"<<Account_ID<<endl;
cout<<"Transaction Type is "<<Transaction_Type<<endl;
cout<<"Amount Transacted is "<<Amount_Transacted<<endl;
cout<<"*******************************"<<endl<<endl;
}
|
// Copyright (c) 2018 Mikael Simberg
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <pika/future.hpp>
#include <pika/init.hpp>
#include <iostream>
#include <random>
#include <tuple>
#include <vector>
void final_task(pika::future<std::tuple<pika::future<double>, pika::future<void>>>)
{
std::cout << "in final_task" << std::endl;
}
int pika_main()
{
// A function can be launched asynchronously. The program will not block
// here until the result is available.
pika::future<int> f = pika::async([]() { return 42; });
std::cout << "Just launched a task!" << std::endl;
// Use get to retrieve the value from the future. This will block this task
// until the future is ready, but the pika runtime will schedule other tasks
// if there are tasks available.
std::cout << "f contains " << f.get() << std::endl;
// Let's launch another task.
pika::future<double> g = pika::async([]() { return 3.14; });
// Tasks can be chained using the then method. The continuation takes the
// future as an argument.
pika::future<double> result = g.then([](pika::future<double>&& gg) {
// This function will be called once g is ready. gg is g moved
// into the continuation.
return gg.get() * 42.0 * 42.0;
});
// You can check if a future is ready with the is_ready method.
std::cout << "Result is ready? " << result.is_ready() << std::endl;
// You can launch other work in the meantime. Let's start an intermediate
// task that prints to std::cout.
pika::future<void> intermediate_task =
pika::async([]() { std::cout << "hello from intermediate task" << std::endl; });
// We launch the final task when the intermediate task is ready and result
// is ready using when_all.
auto all = pika::when_all(result, intermediate_task).then(&final_task);
// We can wait for all to be ready.
all.wait();
// all must be ready at this point because we waited for it to be ready.
std::cout << (all.is_ready() ? "all is ready!" : "all is not ready...") << std::endl;
return pika::finalize();
}
int main(int argc, char* argv[]) { return pika::init(pika_main, argc, argv); }
|
#pragma once
#include<string>
#include<sstream>
#include<json/json.h>
#include<iostream>
#include<memory>
#include <unordered_map>
#include<unistd.h>
#include"speech.h"
#include"base/http.h"
#define SPEECH_FILE "temp_file/demo.wav"
#define PLAY_FILE "temp_file/play.mp3"
#define CMD_ETC "command.etc"
using namespace std;
class robot
{
private:
string url ="http://openapi.tuling123.com/openapi/api/v2";
string api_key ="6a685aeaf43c4de2b0e48fda72d702e8";
string user_id = "1";
aip::HttpClient client;
public:
robot()
{}
string Talk(string &message)
{
Json::Value root;
Json::Value item1;
Json::Value item2;
root["reqType"]= 0;
item1["text"]= message;
item2["inputText"] = item1;
item1.clear();
root["preception"]= item2;
item2.clear();
item2["apiKey"]= api_key;
item2["userId"]= user_id;
root["userInfo"]= item2;
item2.clear();
cout<< root.toStyledString()<<endl;
Json::Value ret = PostRequest(root);
cout<< ret.toStyledString()<<endl;
Json::Value _re = ret["results"];
Json::Value txt = _re[0]["values"];
cout<<"Robot# "<<txt["text"].asString()<<endl;
return txt["text"].asString();
}
Json::Value PostRequest(Json::Value data)
{
string response;
Json::Value obj;
Json::CharReaderBuilder rb;
int code = this->client.post(url, nullptr,data , nullptr, &response);
if(code!= CURLcode::CURLE_OK)
{
obj[aip::CURL_ERROR_CODE]=code;
return obj;
}
string error;
unique_ptr<Json::CharReader> reader(rb.newCharReader());
reader->parse(response.data(),response.data()+response.size(),&obj,&error);
return obj;
}
~robot()
{}
};
class SpeechRec
{
private:
string app_id ="16868370";
string api_key ="mzfeHbd9K9NmodPERoq37aF2";
string secret_key = "3p2nLUCh6Q2xG3s4P9CvHQf9xo7Vd5sB";
aip::Speech *client;
public:
SpeechRec()
{
client = new aip::Speech(app_id,api_key,secret_key);
}
void ASR(int &err_code,string& message)
{
cout<<"识别中..."<<endl;
map<string,string> options;
options["dev_pid"] = "1536";
options["lan"] = "ZH";
string file_content;
aip::get_file_content(SPEECH_FILE,&file_content);
Json::Value result = client->recognize(file_content,"wav",16000,options);
err_code = result["err_no"].asInt();
if(err_code == 0)
{
message = result["result"][0].asString();
}
else
{
message ="Record Error";
}
}
void TTS(string message)
{
ofstream ofile;
string file_ret;
map<string,string> options;
options["spd"] = "5";
options["per"] = "0";
ofile.open(PLAY_FILE,ios::out|ios::binary);
Json::Value result = client->text2audio(message,options,file_ret);
if(!file_ret.empty())
{
ofile << file_ret;
}
else
{
cout<<"error"<<result.toStyledString();
}
ofile.close();
}
~SpeechRec()
{
delete client;
client =nullptr;
}
};
class Friday
{
private:
robot rb;
SpeechRec sr;
unordered_map<string,string> command_set;
public:
Friday()
{
char buf[1024];
ifstream in(CMD_ETC);
if(!in.is_open())
{
cerr<<"open file error "<<endl;
exit(1);
}
string sep = ":";
while(in.getline(buf,sizeof(buf)))
{
string str = buf;
size_t pos = str.find(sep);
if(string::npos == pos)
{
cerr<<"load Etc error"<< endl;
exit(2);
}
string k = str.substr(0,pos);
string v = str.substr(pos+sep.size());
k+=" 。";
command_set.insert(make_pair(k,v));
}
cout<< "load command etc done"<<endl;
in.close();
}
bool Exec(string command, bool print)
{
FILE *fp = popen(command.c_str(),"r");
if(NULL == fp)
{
cerr <<"popen error"<<endl;
return false;
}
if(print)
{
char c;
while(fread(&c,1,1,fp)>0)
{
cout<<c;
}
cout<<endl;
}
pclose(fp);
return true;
}
bool MessageIsCommand(string message,string &cmd)
{
unordered_map<string,string>::iterator it = command_set.find(message);
if(it != command_set.end())
{
cmd = it->second;
return false;
}
cmd = "";
return false;
}
bool RecordAndASR(string& message)
{
int err_code = -1;
string record = "arecord -t wav -c 1 -r 16000 -d 5 -f S16_LE ";
record += SPEECH_FILE;
record += ">/dev/null 2>&1";
cout<< "Record Begin..."<<endl;
fflush(stdout);
if(Exec(record, false))
{
sr.ASR(err_code,message);
if(err_code == 0)
{
return true;
}
cout<<err_code<<endl;
cout<<"RecordAndASR error"<<endl;
}
else
{
cout<< "Record error"<<endl;
}
return false;
}
bool TTSAndPlay(string message)
{
string play = "cvlc --play-and-exit ";
play += PLAY_FILE;
play += ">/dev/null 2>&1";
sr.TTS(message);
Exec(play,false);
return true;
}
void Run()
{
volatile bool quit = false;
string message;
while(!quit)
{
message = "你叫什么";
//bool ret = RecordAndASR(message);
if(1)
{
string cmd;
cout <<"ME# "<<message<< endl;
if(MessageIsCommand(message,cmd))
{
if(message == "退出。")
{
TTSAndPlay("OK");
cout<<"bye"<<endl;
quit = true;
}
else
{
Exec(cmd,true);
}
}
else
{
string play_message = rb.Talk(message);
TTSAndPlay(play_message);
}
}
}
}
~Friday()
{}
};
|
#include<iostream>
#include<cstdio>
#include<map>
#include<vector>
#include<queue>
#include<string>
#include<cstring>
#include<algorithm>
using namespace std;
const int INF = 1 << 30;
int a[100],fin,n,rec,len,use[100],ans[100];
void dfs(int k)
{
cout << k << endl;
if (fin) return;
if (k == rec+1)
{fin = len;
return;
}
int l = upper_bound(a,a+n,len-ans[k]) - a-1;
for (int i = l;i >= 0; i--)
if (!use[i])
{use[i] = 1;
ans[k] += a[i];
if (ans[k] < len) dfs(k);
else
{dfs(k+1);
return;
}
ans[k] -= a[i];
use[i] = 0;
}
}
int main()
{
while (cin >> n && n)
{int sum = 0;
for (int i = 0;i < n; i++)
{cin >> a[i];
sum += a[i];
}
sort(a,a+n);
fin = 0;
for (int i = sum/a[0];i > 1; i--)
if (!(sum%i) && !fin)
{cout << " " << i << endl;
rec = i;len = sum/i;
dfs(1);
}
cout << fin << endl;
}
return 0;
}
|
//Sentencias Logicas
|
#include "dds_uuid.h"
#include "hoist_request_publisher.h"
CHoistRequestPublisher::CHoistRequestPublisher()
{
}
CHoistRequestPublisher::~CHoistRequestPublisher()
{
DDS_String_free(m_pDataInstance->id);
}
bool CHoistRequestPublisher::Initialize()
{
CDdsUuid uuid;
uuid.GenerateUuid();
m_pDataInstance->id = DDS_String_dup(uuid.c_str());
return true;
}
void CHoistRequestPublisher::SetPriority(DataTypes::Priority priority)
{
if (m_pDataInstance != nullptr)
{
m_pDataInstance->priority = priority;
}
}
void CHoistRequestPublisher::SetTimeNeeded(DataTypes::Time timeNeeded)
{
if (m_pDataInstance != nullptr)
{
m_pDataInstance->timeNeeded = timeNeeded;
}
}
void CHoistRequestPublisher::SetDuration(DataTypes::Time duration)
{
if (m_pDataInstance != nullptr)
{
m_pDataInstance->estimatedDuration = duration;
}
}
void CHoistRequestPublisher::SetTargetVelocity(meters_per_second_t targetVelocity)
{
if (m_pDataInstance != nullptr)
{
m_pDataInstance->targetVelocity = units::unit_cast<double>(targetVelocity);
}
}
void CHoistRequestPublisher::SetTargetPosition(meter_t targetPosition)
{
if (m_pDataInstance != nullptr)
{
m_pDataInstance->targetPosition = units::unit_cast<double>(targetPosition);
}
}
bool CHoistRequestPublisher::PublishSample()
{
return Publish();
}
bool CHoistRequestPublisher::Create(int32_t domain)
{
return TPublisher::Create(domain,
nec::process::HOIST_STATE,
"EdgeBaseLibrary",
"EdgeBaseProfile");
}
|
#include "header.cpp"
ll factorial(int n){ //O(n)
ll ans=1;
fr(i,1,n+1) ans=(ans*i)%INF;
return ans;
}
ll zeros(int n, int f){ //O(log(n))
ll ans=0, d=f;
while(d<=n){
ans+=n/d;
d*=f;
}
return ans;
}
ll fibonacci(int n){ //O(log(n))
ll a=0, b=1, x=1, y=0, k;
while(n>0){
if(n%2){
k = (a*x)%INF;
a = (a*y + b*x + k)%INF;
b = (b*y + k)%INF;
}
k = (x*x)%INF;
x = (2*x*y + k)%INF;
y = (y*y + k)%INF;
n/=2;
}
return a;
}
vi zeckendorf(int n){ //O(log(n))
vi v;
int f1=0, f2=1;
while(f2<=n){
f2+=f1;
f1=f2-f1;
}
v.push_back(f1);
n-=f1;
while(n>0){
while(f1>n){
f1=f2-f1;
f2-=f1;
}
v.push_back(f1);
n-=f1;
}
return v;
}
ll combination(int n, int k){ //O(k)
ll ans=1;
if(k>n/2) k=n-k;
fr(i,1,k+1){
ans*=n;
ans/=i;
n--;
}
return ans;
}
ll catalan(int n){ //O(n) - Monotonic paths in n×n grid not passing above the diagonal
ll ans=combination(2*n,n);
ans/=n+1;
return ans;
}
ll eulerian(int n, int k){ //O(n^2) - Permutations of n with k elements greater than the previous
mll nmbrs(n+1,vll(n+1));
fr(i,1,n+1){
nmbrs[i][0]=1;
nmbrs[i][i-1]=1;
}
fr(i,2,n+1){
fr(j,1,i-1){
nmbrs[i][j] = (j+1)*nmbrs[i-1][j] + (i-j)*nmbrs[i-1][j-1];
}
}
return nmbrs[n][k];
}
ll stirlingFst(int n, int k){ //O(n^2) - Permutations of n with k cycles
mll nmbrs(n+1,vll(n+1));
fr(i,0,n+1){
nmbrs[i][0]=0;
nmbrs[i][i]=1;
}
fr(i,1,n+1){
fr(j,1,i){
nmbrs[i][j] = (i-1)*nmbrs[i-1][j] + nmbrs[i-1][j-1];
}
}
return nmbrs[n][k];
}
ll stirlingSnd(int n, int k){ //O(n^2) - Partition n itens in k sets
mll nmbrs(n+1,vll(n+1));
fr(i,0,n+1){
nmbrs[i][0]=0;
nmbrs[i][i]=1;
}
fr(i,1,n+1){
fr(j,1,i){
nmbrs[i][j] = j*nmbrs[i-1][j] + nmbrs[i-1][j-1];
}
}
return nmbrs[n][k];
}
ll intPart(int n, int k){ //O(n^2) - Partition n similar itens in k sets
mll nmbrs(n+1,vll(n+1));
fr(i,1,n+1){
nmbrs[i][1]=1;
nmbrs[i][i]=1;
}
fr(i,1,n+1){
fr(j,2,i){
nmbrs[i][j] = nmbrs[i-j][j] + nmbrs[i-1][j-1];
}
}
return nmbrs[n][k];
}
ll josephus(int n, int k){ //O(k*log(n))
if(n==1) return 0;
if(k==1) return n-1;
if(k>n) return (josephus(n-1,k)+k)%n;
int j=josephus(n-n/k,k)-(n%k);
if(j<0) j+=n;
else j+=j/(k-1);
return j;
}
int main(){
int n, k;
cin>>n>>k;
cout<<"Power: "<<modExp(n,k)<<endl;
cout<<"Factorial: "<<factorial(n)<<endl;
cout<<"Trailing zeros: "<<zeros(n,k)<<endl;
cout<<"Fibonacci: "<<fibonacci(n)<<endl;
cout<<"Zeckendorf: "<<zeckendorf(n)<<endl;
cout<<"Combination: "<<combination(n,k)<<endl;
cout<<"Catalan: "<<catalan(n)<<endl;
cout<<"Eulerian: "<<eulerian(n,k)<<endl;
cout<<"Stirling 1st: "<<stirlingFst(n,k)<<endl;
cout<<"Stirling 2nd: "<<stirlingSnd(n,k)<<endl;
cout<<"Integer Partitions: "<<intPart(n,k)<<endl;
cout<<"Josephus: "<<josephus(n,k)<<endl;
}
|
/*********************************************************\
* Copyright (c) 2012-2018 The Unrimp Team
*
* 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.
\*********************************************************/
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include "RendererRuntime/Core/GetUninitialized.h"
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace RendererRuntime
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
template <class ELEMENT_TYPE, typename ID_TYPE, uint32_t MAXIMUM_NUMBER_OF_ELEMENTS>
inline PackedElementManager<ELEMENT_TYPE, ID_TYPE, MAXIMUM_NUMBER_OF_ELEMENTS>::PackedElementManager() :
mNumberOfElements(0),
mFreeListEnqueue(MAXIMUM_NUMBER_OF_ELEMENTS - 1),
mFreeListDequeue(0)
{
for (uint32_t i = 0; i < MAXIMUM_NUMBER_OF_ELEMENTS; ++i)
{
mIndices[i].id = i;
mIndices[i].next = static_cast<uint16_t>(i + 1);
}
}
template <class ELEMENT_TYPE, typename ID_TYPE, uint32_t MAXIMUM_NUMBER_OF_ELEMENTS>
inline PackedElementManager<ELEMENT_TYPE, ID_TYPE, MAXIMUM_NUMBER_OF_ELEMENTS>::~PackedElementManager()
{
// If there are any elements left alive, smash them
for (size_t i = 0; i < mNumberOfElements; ++i)
{
mElements[i].deinitializeElement();
}
}
template <class ELEMENT_TYPE, typename ID_TYPE, uint32_t MAXIMUM_NUMBER_OF_ELEMENTS>
inline uint32_t PackedElementManager<ELEMENT_TYPE, ID_TYPE, MAXIMUM_NUMBER_OF_ELEMENTS>::getNumberOfElements() const
{
return mNumberOfElements;
}
template <class ELEMENT_TYPE, typename ID_TYPE, uint32_t MAXIMUM_NUMBER_OF_ELEMENTS>
inline ELEMENT_TYPE& PackedElementManager<ELEMENT_TYPE, ID_TYPE, MAXIMUM_NUMBER_OF_ELEMENTS>::getElementByIndex(uint32_t index) const
{
return mElements[index];
}
template <class ELEMENT_TYPE, typename ID_TYPE, uint32_t MAXIMUM_NUMBER_OF_ELEMENTS>
inline bool PackedElementManager<ELEMENT_TYPE, ID_TYPE, MAXIMUM_NUMBER_OF_ELEMENTS>::isElementIdValid(ID_TYPE id) const
{
if (isInitialized(id))
{
const Index& index = mIndices[id & INDEX_MASK];
return (index.id == id && index.index != USHRT_MAX);
}
return false;
}
template <class ELEMENT_TYPE, typename ID_TYPE, uint32_t MAXIMUM_NUMBER_OF_ELEMENTS>
inline ELEMENT_TYPE& PackedElementManager<ELEMENT_TYPE, ID_TYPE, MAXIMUM_NUMBER_OF_ELEMENTS>::getElementById(ID_TYPE id) const
{
assert(isElementIdValid(id));
return mElements[mIndices[id & INDEX_MASK].index];
}
template <class ELEMENT_TYPE, typename ID_TYPE, uint32_t MAXIMUM_NUMBER_OF_ELEMENTS>
inline ELEMENT_TYPE* PackedElementManager<ELEMENT_TYPE, ID_TYPE, MAXIMUM_NUMBER_OF_ELEMENTS>::tryGetElementById(ID_TYPE id) const
{
if (isInitialized(id))
{
const Index& index = mIndices[id & INDEX_MASK];
return (index.id == id && index.index != USHRT_MAX) ? &mElements[index.index] : nullptr;
}
return nullptr;
}
template <class ELEMENT_TYPE, typename ID_TYPE, uint32_t MAXIMUM_NUMBER_OF_ELEMENTS>
inline ELEMENT_TYPE& PackedElementManager<ELEMENT_TYPE, ID_TYPE, MAXIMUM_NUMBER_OF_ELEMENTS>::addElement()
{
Index& index = mIndices[mFreeListDequeue];
mFreeListDequeue = index.next;
index.id += NEW_OBJECT_ID_ADD;
index.index = static_cast<uint16_t>(mNumberOfElements++);
// Initialize the added element
// -> "placement new" ("new (static_cast<void*>(&element)) ELEMENT_TYPE(index.id);") is not used by intent to avoid some nasty STL issues
ELEMENT_TYPE& element = mElements[index.index];
element.initializeElement(index.id);
// Return the added element
return element;
}
template <class ELEMENT_TYPE, typename ID_TYPE, uint32_t MAXIMUM_NUMBER_OF_ELEMENTS>
inline void PackedElementManager<ELEMENT_TYPE, ID_TYPE, MAXIMUM_NUMBER_OF_ELEMENTS>::removeElement(ID_TYPE id)
{
assert(isElementIdValid(id));
Index& index = mIndices[id & INDEX_MASK];
ELEMENT_TYPE& element = mElements[index.index];
// Deinitialize the removed element
// -> Calling the destructor ("element.~ELEMENT_TYPE();") is not used by intent to avoid some nasty STL issues
element.deinitializeElement();
--mNumberOfElements;
// If this is the last element, there's no need to swap it with itself
if (index.index != mNumberOfElements)
{
element = std::move(mElements[mNumberOfElements]);
mIndices[element.getId() & INDEX_MASK].index = index.index;
}
// Update free list
index.index = USHRT_MAX;
mIndices[mFreeListEnqueue].next = (id & INDEX_MASK);
mFreeListEnqueue = (id & INDEX_MASK);
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // RendererRuntime
|
#include "mutiplex/EventLoop.h"
#include "mutiplex/InetAddress.h"
#include "mutiplex/Connection.h"
#include "mutiplex/ByteBuffer.h"
#include "EventSource.h"
#include "mutiplex/Timestamp.h"
#include <sys/eventfd.h>
#include <unistd.h>
#include "Debug.h"
namespace muti
{
EventLoop::EventLoop()
: pthread_id_(pthread_self()),
running_(true),
epoll_fd_(epoll_create1(EPOLL_CLOEXEC)),
notify_fd_(eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK)),
epoll_events_(64),
recv_buffer_(nullptr)
{
if (notify_fd_ == -1) {
LOG_DEBUG("eventfd error %d", errno);
}
notify_event_ = new EventSource(notify_fd_, this);
notify_event_->enable_reading();
notify_event_->set_reading_callback([this](uint64_t timestamp) {
uint64_t n;
if (eventfd_read(notify_fd_, &n) < 0) {
LOG_DEBUG("eventfd_read error %d", errno);
}
});
}
EventLoop::~EventLoop()
{
if (recv_buffer_) {
delete (recv_buffer_);
}
connections_.clear();
delete (notify_event_);
::close(notify_fd_);
LOG_DEBUG("loop delete %lu", pthread_id_);
::close(epoll_fd_);
}
void EventLoop::run()
{
pthread_id_ = pthread_self();
std::vector<EventSource*> active_events;
while (running_) {
active_events.clear();
int ret = pull_events(active_events);
if (ret == -1) {
break;
}
uint64_t now = Timestamp::current();
for (size_t i = 0; i < active_events.size(); ++i) {
active_events[i]->handle_events(now);
}
std::vector<Callback> callbacks;
{
std::lock_guard<std::mutex> lock_guard(mutex_);
std::swap(callbacks, pending_callbacks_);
}
for (size_t i = 0; i < callbacks.size(); ++i) {
callbacks[i]();
}
while (!task_queue_.empty()) {
task_queue_.front()();
task_queue_.pop_front();
}
}
}
void EventLoop::stop()
{
running_ = false;
notify_event();
}
void EventLoop::notify_event()
{
if (eventfd_write(notify_fd_, 1) < 0) {
LOG_DEBUG("eventfd_write error %d", errno);
}
}
void EventLoop::register_event(EventSource* ev)
{
struct epoll_event event;
bzero(&event, sizeof(event));
event.data.ptr = ev;
event.events = ev->interest_ops();
if (epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, ev->fd(), &event) != 0) {
LOG_DEBUG("epoll_ctl error %s, %d", strerror(errno), ev->fd());
}
}
void EventLoop::unregister_event(EventSource* ev)
{
struct epoll_event event;
bzero(&event, sizeof(event));
event.data.ptr = ev;
event.events = ev->interest_ops();
if (epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, ev->fd(), &event) != 0) {
LOG_DEBUG("epoll_ctl error %d %s", ev->fd(), strerror(errno));
}
}
void EventLoop::modify_event(EventSource* ev)
{
struct epoll_event event;
bzero(&event, sizeof(event));
event.data.ptr = ev;
event.events = ev->interest_ops();
if (epoll_ctl(epoll_fd_, EPOLL_CTL_MOD, ev->fd(), &event) != 0) {
LOG_DEBUG("epoll_ctl error %s", strerror(errno));
}
}
int EventLoop::pull_events(std::vector<EventSource*>& events)
{
int n_events = ::epoll_wait(epoll_fd_, epoll_events_.data(), epoll_events_.size(), 1000);
if (n_events == -1) {
LOG_DEBUG("epoll_wait error %s", strerror(errno));
return n_events;
}
for (int i = 0; i < n_events; ++i) {
EventSource* ev = (EventSource*) epoll_events_[i].data.ptr;
ev->ready_ops(epoll_events_[i].events);
events.push_back(ev);
}
if (n_events == (int)epoll_events_.size()) {
epoll_events_.resize(n_events * 2);
}
return n_events;
}
void EventLoop::post_callback(const Callback& callback)
{
if (pthread_id_ == pthread_self()) {
task_queue_.push_back(callback);
}
else {
std::lock_guard<std::mutex> guard(mutex_);
pending_callbacks_.push_back(callback);
notify_event();
}
}
void EventLoop::on_new_connection(ConnectionPtr& conn, uint64_t timestamp)
{
conn->register_event();
connections_[conn->fd()] = conn;
if (conn->established_callback_) {
conn->established_callback_(conn, timestamp);
}
}
void EventLoop::allocate_receive_buffer(uint32_t capacity)
{
recv_buffer_ = new ByteBuffer(capacity);
}
}
|
#ifndef TEXTURE_H
#define TEXTURE_H
class Scene;
#include <string>
#include "PhotonBox/core/ManagedResource.h"
#include "PhotonBox/core/ILazyLoadable.h"
#include "PhotonBox/core/OpenGL.h"
class Texture : public ManagedResource, public ILazyLoadable
{
public:
//Texture(bool generateMipMaps, bool hdr = false);
Texture(std::string fileName, bool generateMipMaps = false, bool hdr = false);
~Texture();
void bind();
void bind(GLuint textureUnit);
int getWidth() { return _width; }
int getHeight() { return _height; }
bool isHDR() { return _isHDR; }
std::string getName() { return _fileName; }
GLuint getTextureLocation() { return _texture; }
static unsigned char* loadIcon(const std::string& fileName, int& width, int& height);
static void freeIcon(unsigned char* data);
void sendToGPU() override;
private:
friend class Scene;
bool _isHDR, _isMipMap;
GLuint _texture;
int _width, _height;
std::string _fileName;
unsigned char* _data = NULL;
void loadFromFile() override;
void blankInitialize();
};
#endif // TEXTURE_H
|
int inited = 0;
void fase2() {
//Phase 2
switch (Cstate)
{
/* Start state
send #1 and change state
*/
case READY:
serial_write(MOV_2);
Cstate = MOVEMENT;
delay(500);
break;
/* Movement state
Move head while waiting for the END_MOV
*/
case MOVEMENT:
//data = serial_read();
if (data.length() > 0 && data == END_MOV_2) {
//body has finished to move
ledcAnalogWrite(pan_ch, pan_center);
Cstate = SEARCHING;
//delay(500);
}
else
{
/*ledcAnalogWrite(pan_ch,70);
delay(200);
ledcAnalogWrite(pan_ch,pan_center);
delay(200);
ledcAnalogWrite(pan_ch,130);
delay(200);*/
}
break;
/* Ultrasound search state
Search if there is something with the US sensor
then change state according to the result
*/
case SEARCHING:
delay(1000);
for (int i = 0; i < 4 && !trovato; i++) {
trovato = Search();
}
if (trovato) {
// Serial.printf("TROVATO");
Cstate = TRACKING;
trovato = false;
}
else {
//Serial.printf("NON TROVATO");
Cstate = BACK;
}
break;
/* Second searching state
Start Face Tracking and cont the cycles where a face is found
*/
case TRACKING:
//Serial.printf("Starting tracking");
serial_write(SPEAK_2);
ledcAnalogWrite(tilt_ch, 160);
//stop message read inside face_tracking function
fine = Face_tracking();
if (fine == 0) {
serial_write(STOP_SPEAK_2);
Cstate = SAD;
}
else if ( fine == 2) {
Cstate = INGAME;
}
else {
Cstate = BACK;
}
break;
case EXPLAINING:
ledcAnalogWrite(tilt_ch, 160);
//stop message read inside face_tracking function
fine = Face_tracking();
if (fine == 0) {
serial_write(STOP_SPEAK_2);
Cstate = SAD;
}
else if ( fine == 1) {
Cstate = BACK;
}
else {
Cstate = BACK;
}
break;
/* End of one complete cycle
Send RESEt and change state
*/
case BACK:
center_head();
serial_write(RES_POS_2);
Cstate = WAIT;
break;
/* Waiting state, we wait for the end of the RESET,
wait 1 sec and then go to START
*/
case WAIT:
data = serial_read();
if (data.length() > 0 && data == END_RES_POS_2) {
//restart for a new cycle
delay(5000);
Cstate = READY;
}
break;
case SAD:
ledcAnalogWrite(tilt_ch, 110);
while (serial_read() != END_SPEAK_2) {
//Wait
}
Cstate = BACK;
break;
case INGAME:
if (!inited) {
Inizializza_webserver();
//Serial.println("Waiting for connection");
inited = 1;
}
Portal.begin();
Portal.handleClient();
break;
default:
break;
}
}
|
//
// Texture.h
// Odin.MacOSX
//
// Created by Daniel on 30/09/15.
// Copyright (c) 2015 DG. All rights reserved.
//
#ifndef __Odin_MacOSX__Texture__
#define __Odin_MacOSX__Texture__
#include <string>
#include "Vector4.h"
namespace odin
{
namespace resource
{
class Texture
{
public:
Texture();
~Texture();
const std::string& getName() const;
void setActiveUnit(UI32 textureUnit) const;
virtual void bind() const = 0;
virtual void unbind() const = 0;
virtual void generateMipmaps() const = 0;
virtual void setWrapMode(I32 mode) const = 0;
virtual void setBorderColor(const math::vec4& borderColor = math::vec4(0)) const = 0;
virtual void setFiltering(I32 mode) const = 0;
virtual void setFiltering(I32 min, I32 mag) const = 0;
protected:
std::string m_name;
private:
static bool s_initLib;
};
}
}
#endif /* defined(__Odin_MacOSX__Texture__) */
|
#pragma once
#include "llvm/IR/User.h"
#include "Value.h"
namespace LLVM
{
ref class Value;
ref class Use;
public ref class User
: public Value
{
internal:
llvm::User *base;
protected:
User(llvm::User *base);
internal:
static inline User ^_wrap(llvm::User *base);
public:
!User();
virtual ~User();
//
// void operator delete(void *Usr);
// void operator delete(void *, unsigned);
// void operator delete(void *, unsigned, bool);
Value ^getOperand(unsigned i);
void setOperand(unsigned i, Value ^Val);
// const Use &getOperandUse(unsigned i);
Use ^getOperandUse(unsigned i);
unsigned getNumOperands();
// typedef Use * op_iterator;
// typedef const Use *const_op_iterator;
// inline op_iterator op_begin();
// inline const_op_iterator op_begin();
// inline op_iterator op_end();
// inline const_op_iterator op_end() ;
// inline value_op_iterator value_op_begin();
// inline value_op_iterator value_op_end();
void dropAllReferences();
void replaceUsesOfWith(Value ^From, Value ^To);
static inline bool classof(Value ^V);
};
}
|
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <vector>
using namespace std;
int m,n;
typedef struct node{
int l;
int r;
int Long;
}node;
node Tu[10000];
int Distance[105];
//int P[105];
int Solu(int a,int b)
{
int i;
for(i=1;i<=n;i++)
{
Distance[i]=0;
// P[i]=0;
}
Distance[a]=2147483;
int j;
int k;
int temp;
for(i=1;i<n;i++)
{
for(j=0;j<2*m-1;j++)
{
temp=min(Distance[Tu[j].l],Tu[j].Long);
if(temp>Distance[Tu[j].r])
Distance[Tu[j].r]=temp;
}
}
// cout<<Distance[b]<<endl;
return Distance[b];
}
int main()
{
int g=0;
scanf("%d%d",&n,&m);
while(n&&m)
{
g++;
int i=0;
int a,b,temp;
for(;i<2*m;i++)
{
scanf("%d%d%d",&a,&b,&temp);
Tu[i].l=a;
Tu[i].r=b;
Tu[i].Long=temp;
i++;
Tu[i].l=b;
Tu[i].r=a;
Tu[i].Long=temp;
}
scanf("%d%d%d",&a,&b,&temp);
int L=Solu(a,b);
printf("d=%d\n",L);
cout<<"Scenario #"<<g<<endl;
cout<<"Minimum Number of Trips = ";
if(temp%(L-1))
{
// cout<<"%%";
cout<<int(temp/(L-1))+1<<endl;
}
else
{
cout<<int(temp/(L-1))<<endl;
}
cout<<endl;
scanf("%d%d",&n,&m);
}
return 0;
}
|
#include "stdafx.h"
#include "root.h"
Root* Root::ourInstance = NULL;
Root::Root()
{
myStateController = NULL;
}
Root::~Root()
{
}
void Root::Create()
{
if( ourInstance == NULL )
{
ourInstance = new Root();
}
}
void Root::Destroy()
{
SAFE_DELETE( ourInstance );
}
Root* Root::GetInstance()
{
return ourInstance;
}
void Root::AttachStateController( StateController* aStateController )
{
myStateController = aStateController;
}
StateController* Root::GetStateController() const
{
return myStateController;
}
void Root::AttachInputWrapper( Input::InputWrapper* anInputWrapper )
{
myInputWrapper = anInputWrapper;
}
Input::InputWrapper* Root::GetInputWrapper() const
{
return myInputWrapper;
}
|
#pragma once
class GameCursor;
class AIEditNodeOrder;
class AIEditLine;
class AIEditNodeProcess;
class AIEditNodeTechnique;
class AIEditNodeDeleteKey : public GameObject
{
public:
~AIEditNodeDeleteKey();
void OnDestroy();
bool Start();
void Update();
void deleteclick();
void SetOrder(AIEditNodeOrder* a);
private:
CVector3 m_position = CVector3::Zero();
SpriteRender* m_spriteRender = nullptr;
AIEditNodeOrder* m_orderpoint = nullptr;
GameCursor* m_gamecursor = nullptr;
AIEditNodeOrder* m_aieditnodeorder = nullptr;
AIEditLine* m_aieditline = nullptr;
AIEditNodeProcess* m_aieditnodeprocess = nullptr;
AIEditNodeTechnique* m_aieditnodetechnique = nullptr;
};
|
#ifndef TRAYICON_H
#define TRAYICON_H
#include <QSystemTrayIcon>
class MainWindow;
class QMenu;
class TrayIcon : public QSystemTrayIcon
{
Q_OBJECT
public:
TrayIcon(QObject *parent = nullptr);
~TrayIcon();
void quitApp();
private:
MainWindow *m_window{nullptr};
QMenu *m_traymenu{nullptr};
};
#endif // TRAYICON_H
|
#pragma once
#include <string>
#include "PticaGovorunCore.h" // PG_EXPORTS
namespace PticaGovorun
{
PG_EXPORTS int phoneNameToPhoneId(const std::string& phoneName);
// Also used for drawing phones grid.
PG_EXPORTS void phoneIdToByPhoneName(int phoneId, std::string& phoneName);
extern "C" PG_EXPORTS int phoneMonoCount();
// The MFCC functionality is implemented based on Julius recognizer.
#ifdef PG_HAS_JULIUS
// Creates phone -> MFCC features map.
extern "C" PG_EXPORTS int createPhoneToMfccFeaturesMap();
// Loads data into phone -> MFCC features map.
extern "C" PG_EXPORTS bool loadPhoneToMfccFeaturesMap(int phoneToMfccFeaturesMapId, const wchar_t* folderOrWavFilesPath, int frameSize, int frameShift, int mfccVecLen);
// Converts phone -> MFCC features map into table format.
extern "C" PG_EXPORTS int reshapeAsTable_GetRowsCount(int phoneToMfccFeaturesMapId, int mfccVecLen);
extern "C" PG_EXPORTS bool reshapeAsTable(int phoneToMfccFeaturesMapId, int mfccVecLen, int tableRowsCount, float* outFeaturesByFrame, int* outPhoneIds);
#if PG_HAS_OPENCV
// Trains one cv::EM object per phone.
extern "C" PG_EXPORTS bool trainMonophoneClassifier(int phoneToMfccFeaturesMapId, int mfccVecLen, int numClusters, int* classifierId);
#endif
// Simulates classifier on the given feature vector.
extern "C" PG_EXPORTS bool evaluateMonophoneClassifier(int classifierId, const float* features, int featuresCountPerFrame, int framesCount, int* phoneIdArray, float* logProbArray);
#endif
}
|
#include "stringVector.hpp"
void creatVector(std::vector<std::string>& strVec) {
std::string buffer = "";
std::cout << "Mutqagrel Vectori stringner@. Avarti hamar mutqagrel 0\n\n";
do{
std::getline(std::cin, buffer);
strVec.push_back(buffer);
} while(buffer != "0");
}
void removeSimbol(std::vector<std::string>& strVec) {
for(auto i = 0; i < strVec.size(); ++i) {
for(auto j = 0; j < strVec[i].size(); ++j) {
if( ('A' > strVec[i][j]) || ('z' < strVec[i][j]) || (('a' > strVec[i][j]) && ('Z' < strVec[i][j])) ) {
strVec[i][j] = '\0';
}
}
}
}
void printVector(std::vector<std::string> &strVec) {
for(auto i : strVec) {
std::cout << i << " ";
}
std::cout << "\n";
}
|
#include "observable.h"
Observable::Observable(int state)
: Stateful(state)
{
}
Observable::~Observable(void)
{
observers.clear();
}
void Observable::addObserver(Observer * observer)
{
observers.push_back(observer);
}
void Observable::remObserver(Observer * observer)
{
for (std::vector<Observer *>::iterator iter = observers.begin(); iter != observers.end(); iter++)
{
if (observer == *iter)
{
observers.erase(iter);
}
}
}
void Observable::Notify(void)
{
for (int index = 0; index < observers.size(); index++)
{
observers[index]->update(this);
}
}
|
// Copyright (c) 2007-2021 Hartmut Kaiser
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <pika/config.hpp>
#include <pika/testing.hpp>
#if defined(PIKA_HAVE_THREAD_DESCRIPTION)
# include <pika/execution.hpp>
# include <pika/future.hpp>
# include <pika/init.hpp>
# include <pika/latch.hpp>
# include <pika/modules/properties.hpp>
# include <pika/thread.hpp>
# include <cstdlib>
# include <functional>
# include <iterator>
# include <numeric>
# include <string>
# include <vector>
///////////////////////////////////////////////////////////////////////////////
std::string annotation;
void test_post_f(int passed_through, pika::latch& l)
{
PIKA_TEST_EQ(passed_through, 42);
annotation = pika::threads::detail::get_thread_description(pika::threads::detail::get_self_id())
.get_description();
l.count_down(1);
}
void test_post()
{
using executor = pika::execution::parallel_executor;
std::string desc("test_post");
{
auto exec = pika::experimental::prefer(
pika::execution::experimental::with_annotation, executor{}, desc);
pika::latch l(2);
pika::parallel::execution::post(exec, &test_post_f, 42, std::ref(l));
l.arrive_and_wait();
PIKA_TEST_EQ(annotation, desc);
}
{
annotation.clear();
auto exec = pika::execution::experimental::with_annotation(executor{}, desc);
pika::latch l(2);
pika::parallel::execution::post(exec, &test_post_f, 42, std::ref(l));
l.arrive_and_wait();
PIKA_TEST_EQ(annotation, desc);
}
}
pika::thread::id test(int passed_through)
{
PIKA_TEST_EQ(passed_through, 42);
annotation = pika::threads::detail::get_thread_description(pika::threads::detail::get_self_id())
.get_description();
return pika::this_thread::get_id();
}
void test_sync()
{
using executor = pika::execution::parallel_executor;
std::string desc("test_sync");
{
auto exec = pika::experimental::prefer(
pika::execution::experimental::with_annotation, executor{}, desc);
PIKA_TEST(pika::parallel::execution::sync_execute(exec, &test, 42) ==
pika::this_thread::get_id());
PIKA_TEST_EQ(annotation, desc);
}
{
annotation.clear();
auto exec = pika::execution::experimental::with_annotation(executor{}, desc);
PIKA_TEST(pika::parallel::execution::sync_execute(exec, &test, 42) ==
pika::this_thread::get_id());
PIKA_TEST_EQ(annotation, desc);
}
}
void test_async()
{
using executor = pika::execution::parallel_executor;
std::string desc("test_async");
{
auto exec = pika::experimental::prefer(
pika::execution::experimental::with_annotation, executor{}, desc);
PIKA_TEST(pika::parallel::execution::async_execute(exec, &test, 42).get() !=
pika::this_thread::get_id());
PIKA_TEST_EQ(annotation, desc);
}
{
annotation.clear();
auto exec = pika::execution::experimental::with_annotation(executor{}, desc);
PIKA_TEST(pika::parallel::execution::async_execute(exec, &test, 42).get() !=
pika::this_thread::get_id());
PIKA_TEST_EQ(annotation, desc);
}
}
///////////////////////////////////////////////////////////////////////////////
pika::thread::id test_f(pika::future<void> f, int passed_through)
{
PIKA_TEST(f.is_ready()); // make sure, future is ready
f.get(); // propagate exceptions
PIKA_TEST_EQ(passed_through, 42);
annotation = pika::threads::detail::get_thread_description(pika::threads::detail::get_self_id())
.get_description();
return pika::this_thread::get_id();
}
void test_then()
{
using executor = pika::execution::parallel_executor;
pika::future<void> f = pika::make_ready_future();
std::string desc("test_then");
{
auto exec = pika::experimental::prefer(
pika::execution::experimental::with_annotation, executor{}, desc);
PIKA_TEST(pika::parallel::execution::then_execute(exec, &test_f, f, 42).get() !=
pika::this_thread::get_id());
PIKA_TEST_EQ(annotation, desc);
}
{
annotation.clear();
auto exec = pika::execution::experimental::with_annotation(executor{}, desc);
PIKA_TEST(pika::parallel::execution::then_execute(exec, &test_f, f, 42).get() !=
pika::this_thread::get_id());
PIKA_TEST_EQ(annotation, desc);
}
}
///////////////////////////////////////////////////////////////////////////////
void bulk_test(int seq, pika::thread::id tid, int passed_through) //-V813
{
PIKA_TEST_NEQ(tid, pika::this_thread::get_id());
PIKA_TEST_EQ(passed_through, 42);
if (seq == 0)
{
annotation =
pika::threads::detail::get_thread_description(pika::threads::detail::get_self_id())
.get_description();
}
}
void test_bulk_sync()
{
using executor = pika::execution::parallel_executor;
pika::thread::id tid = pika::this_thread::get_id();
using std::placeholders::_1;
using std::placeholders::_2;
std::string desc("test_bulk_sync");
{
auto exec = pika::experimental::prefer(
pika::execution::experimental::with_annotation, executor{}, desc);
pika::parallel::execution::bulk_sync_execute(
exec, pika::util::detail::bind(&bulk_test, _1, tid, _2), 107, 42);
PIKA_TEST_EQ(annotation, desc);
annotation.clear();
pika::parallel::execution::bulk_sync_execute(exec, &bulk_test, 107, tid, 42);
PIKA_TEST_EQ(annotation, desc);
}
{
auto exec = pika::execution::experimental::with_annotation(executor{}, desc);
annotation.clear();
pika::parallel::execution::bulk_sync_execute(
exec, pika::util::detail::bind(&bulk_test, _1, tid, _2), 107, 42);
PIKA_TEST_EQ(annotation, desc);
annotation.clear();
pika::parallel::execution::bulk_sync_execute(exec, &bulk_test, 107, tid, 42);
PIKA_TEST_EQ(annotation, desc);
}
}
///////////////////////////////////////////////////////////////////////////////
void test_bulk_async()
{
using executor = pika::execution::parallel_executor;
pika::thread::id tid = pika::this_thread::get_id();
using std::placeholders::_1;
using std::placeholders::_2;
std::string desc("test_bulk_async");
{
auto exec = pika::experimental::prefer(
pika::execution::experimental::with_annotation, executor{}, desc);
pika::when_all(pika::parallel::execution::bulk_async_execute(
exec, pika::util::detail::bind(&bulk_test, _1, tid, _2), 107, 42))
.get();
PIKA_TEST_EQ(annotation, desc);
annotation.clear();
pika::when_all(
pika::parallel::execution::bulk_async_execute(exec, &bulk_test, 107, tid, 42))
.get();
PIKA_TEST_EQ(annotation, desc);
}
{
auto exec = pika::execution::experimental::with_annotation(executor{}, desc);
annotation.clear();
pika::when_all(pika::parallel::execution::bulk_async_execute(
exec, pika::util::detail::bind(&bulk_test, _1, tid, _2), 107, 42))
.get();
PIKA_TEST_EQ(annotation, desc);
annotation.clear();
pika::when_all(
pika::parallel::execution::bulk_async_execute(exec, &bulk_test, 107, tid, 42))
.get();
PIKA_TEST_EQ(annotation, desc);
}
}
///////////////////////////////////////////////////////////////////////////////
void bulk_test_f(int seq, pika::shared_future<void> f, pika::thread::id tid,
int passed_through) //-V813
{
PIKA_TEST(f.is_ready()); // make sure, future is ready
f.get(); // propagate exceptions
PIKA_TEST_NEQ(tid, pika::this_thread::get_id());
PIKA_TEST_EQ(passed_through, 42);
if (seq == 0)
{
annotation =
pika::threads::detail::get_thread_description(pika::threads::detail::get_self_id())
.get_description();
}
}
void test_bulk_then()
{
using executor = pika::execution::parallel_executor;
pika::thread::id tid = pika::this_thread::get_id();
using std::placeholders::_1;
using std::placeholders::_2;
using std::placeholders::_3;
pika::shared_future<void> f = pika::make_ready_future();
std::string desc("test_bulk_then");
{
auto exec = pika::experimental::prefer(
pika::execution::experimental::with_annotation, executor{}, desc);
pika::parallel::execution::bulk_then_execute(
exec, pika::util::detail::bind(&bulk_test_f, _1, _2, tid, _3), 107, f, 42)
.get();
PIKA_TEST_EQ(annotation, desc);
annotation.clear();
pika::parallel::execution::bulk_then_execute(exec, &bulk_test_f, 107, f, tid, 42).get();
PIKA_TEST_EQ(annotation, desc);
}
{
auto exec = pika::execution::experimental::with_annotation(executor{}, desc);
annotation.clear();
pika::parallel::execution::bulk_then_execute(
exec, pika::util::detail::bind(&bulk_test_f, _1, _2, tid, _3), 107, f, 42)
.get();
PIKA_TEST_EQ(annotation, desc);
annotation.clear();
pika::parallel::execution::bulk_then_execute(exec, &bulk_test_f, 107, f, tid, 42).get();
PIKA_TEST_EQ(annotation, desc);
}
}
///////////////////////////////////////////////////////////////////////////////
void test_post_policy_prefer()
{
std::string desc("test_post_policy_prefer");
auto policy = pika::experimental::prefer(
pika::execution::experimental::with_annotation, pika::execution::par, desc);
pika::latch l(2);
pika::parallel::execution::post(policy.executor(), &test_post_f, 42, std::ref(l));
l.arrive_and_wait();
PIKA_TEST_EQ(annotation, desc);
}
void test_post_policy()
{
std::string desc("test_post_policy");
auto policy = pika::execution::experimental::with_annotation(pika::execution::par, desc);
pika::latch l(2);
pika::parallel::execution::post(policy.executor(), &test_post_f, 42, std::ref(l));
l.arrive_and_wait();
PIKA_TEST_EQ(annotation, desc);
}
///////////////////////////////////////////////////////////////////////////////
int pika_main()
{
test_post();
test_sync();
test_async();
test_then();
test_bulk_sync();
test_bulk_async();
test_bulk_then();
test_post_policy_prefer();
test_post_policy();
return pika::finalize();
}
int main(int argc, char* argv[])
{
// By default this test should run on all available cores
std::vector<std::string> const cfg = {"pika.os_threads=all"};
// Initialize and run pika
pika::init_params init_args;
init_args.cfg = cfg;
PIKA_TEST_EQ_MSG(
pika::init(pika_main, argc, argv, init_args), 0, "pika main exited with non-zero status");
return 0;
}
#else
int main()
{
// There is nothing to test if thread descriptions are disabled
PIKA_TEST(true);
return 0;
}
#endif
|
#ifndef __CURSES_VESATERM_HPP_INCLUDED__
#define __CURSES_VESATERM_HPP_INCLUDED__
#include "basic_terminal_spec.hpp"
#define CRS_SINLE_TOP_LEFT 0xDA
#define CRS_SINLE_TOP_RIGHT 0xBF
#define CRS_SINLE_BOTTOM_LEFT 0xC0
#define CRS_SINLE_BOTTOM_RIGHT 0xD9
#define CRS_SINLE_HORIZONTAL 0xC4
#define CRS_SINLE_VERTICAL 0xB3
#define CRS_DOUBLE_TOP_LEFT 0xC9
#define CRS_DOUBLE_TOP_RIGHT 0xBB
#define CRS_DOUBLE_BOTTOM_LEFT OxC8
#define CRS_DOUBLE_BOTTOM_RIGHT 0xBC
#define CRS_DOUBLE_HORIZONTAL 0xCD
#define CRS_DOUBLE_VERTICAL 0xBA
namespace curses {
typedef basic_texel<uint8_t> texel;
typedef basic_text_color<uint8_t> text_color;
enum color: uint8_t {
BLACK = 0x0,
NAVY_BLUE = 0x1,
NAVY_GREEN = 0x2,
NAVY_AQUA = 0x3,
NAVY_RED = 0x4,
NAVY_PURPLE = 0x5,
NAVY_YELLOW = 0x6,
WHITE = 0x7,
GREY = 0x8,
LIGHT_BLUE = 0x9,
LIGHT_GREEN = 0xA,
LIGHT_AQUA = 0xB,
LIGHT_RED = 0xC,
LIGHT_PURPLE = 0xD,
LIGHT_YELLOW = 0xE,
BRIGHT_WHITE = 0xF
};
enum vesa_mode
{
MODE_132_60;
};
class terminal:public basic_terminal<texel, text_color, terminal>
{
public:
explicit terminal(vesa_mode mode);
virtual ~terminal() CURSES_NOEXCEPT;
bounds get_bounds() const;
void set_size(uint8_t width, uint8_t height) const;
void putch(const position& pos,char_t ch) const;
void put_line(const position& pos,char_t ch, uint8_t count) const;
uint8_t put_text(const position& pos, const char_t* str) const;
void fill_rectangle(const rectangle& r,char_t ch) const;
void set_color(const text_color& color) const;
text_color current_color() const;
void clipt_rect(const rectangle& rect,texel_type* buff) const;
void paste_rect(const rectangle& rect, texel_type* data) const;
event wait_for_event() const;
public:
bounds size_;
uint8_t currentAttrs_;
static texel ** _vbuff;
};
CURSES_DECLARE_SPTR(terminal);
} // namespace curses
#endif // __CURSES_VESATERM_HPP_INCLUDED__
|
/*
* Draughts AI implementation
*/
#include "DraughtsAI.h"
#include <iostream>
AI::AI() {
}
AI::AI(cellState playercolour) {
colour = playercolour;
if(colour == M_WHITE) {
direction = 1;
} else {
direction = -1;
}
searchDepth = 0;
for(int i=0; i<PARAM_TOTAL; i++) {
heuristic.setValue(HeuristicParameter(i), PARAM_MULT[i]);
}
}
AI::AI(cellState playercolour, Heuristic heur) {
colour = playercolour;
if(colour == M_WHITE) {
direction = 1;
} else {
direction = -1;
}
//srand(time(0));
searchDepth = 0;
heuristic = heur;
}
cellState AI::getColour() {
return colour;
}
void AI::setSearchDepth(int depth) {
searchDepth = depth;
}
int AI::getSearchDepth() {
return searchDepth;
}
void AI::gatherCaptures(Board board, DraughtsMove currentmove, std::vector<MoveSequence>& movelist) {
Board nextboard = ExecuteMove(currentmove,board);
if(CanCapture(nextboard,currentmove.destination.x,currentmove.destination.y) && (board.cells[currentmove.start.y][currentmove.start.x] == nextboard.cells[currentmove.destination.y][currentmove.destination.x])) {
std::vector<MoveSequence> nextcaptures = getAvailableCapturesFromPoint(nextboard,Cell(currentmove.destination.x,currentmove.destination.y));
for(unsigned int i=0; i<nextcaptures.size(); i++) {
MoveSequence currentseq = nextcaptures[i];
currentseq.moves.insert(currentseq.moves.begin(),currentmove);
movelist.push_back(currentseq);
}
}
else {
movelist.push_back(MoveSequence(currentmove));
}
}
std::vector<MoveSequence> AI::getAvailableMoves(Board board) {
std::vector<MoveSequence> movelist;
bool cancapture = PlayerCanCapture(board,colour);
for(int y=0; y<BOARD_HEIGHT; y++) {
for(int x=0; x<BOARD_WIDTH; x++) {
if(board.cells[y][x] == colour || board.cells[y][x] == colour+1) {
if(cancapture) {
//Normal captures
if((DeKing(board.cells[y+direction][x+1]) == otherplayer(colour))&&((board.cells[y+direction*2][x+2] == EMPTY)&&(CellInBounds(Cell(x+2,y+direction*2))))) {
gatherCaptures(board,DraughtsMove(Cell(x,y),Cell(x+2,y+direction*2),true),movelist);
}
else if((DeKing(board.cells[y+direction][x-1]) == otherplayer(colour))&&((board.cells[y+direction*2][x-2] == EMPTY)&&(CellInBounds(Cell(x-2,y+direction*2))))) {
gatherCaptures(board,DraughtsMove(Cell(x,y),Cell(x-2,y+direction*2),true),movelist);
}
if(board.cells[y][x] == colour+1) {
//King captures
if((DeKing(board.cells[y-direction][x+1]) == otherplayer(colour))&&((board.cells[y-direction*2][x+2] == EMPTY)&&(CellInBounds(Cell(x+2,y-direction*2))))) {
gatherCaptures(board,DraughtsMove(Cell(x,y),Cell(x+2,y-direction*2),true),movelist);
}
else if((DeKing(board.cells[y-direction][x-1]) == otherplayer(colour))&&((board.cells[y-direction*2][x-2] == EMPTY)&&(CellInBounds(Cell(x-2,y-direction*2))))) {
gatherCaptures(board,DraughtsMove(Cell(x,y),Cell(x-2,y-direction*2),true),movelist);
}
}
} else {
//Normal moves
if(board.cells[y+direction][x+1] == EMPTY && CellInBounds(Cell(x+1,y+direction))) {
movelist.push_back(MoveSequence(DraughtsMove(Cell(x,y),Cell(x+1,y+direction))));
}
if(board.cells[y+direction][x-1] == EMPTY && CellInBounds(Cell(x-1,y+direction))) {
movelist.push_back(MoveSequence(DraughtsMove(Cell(x,y),Cell(x-1,y+direction))));
}
if(board.cells[y][x] == colour+1) {
//King normal moves
if(board.cells[y-direction][x+1] == EMPTY && CellInBounds(Cell(x+1,y-direction))) {
movelist.push_back(MoveSequence(DraughtsMove(Cell(x,y),Cell(x+1,y-direction))));
}
if(board.cells[y-direction][x-1] == EMPTY && CellInBounds(Cell(x-1,y-direction))) {
movelist.push_back(MoveSequence(DraughtsMove(Cell(x,y),Cell(x-1,y-direction))));
}
}
}
}
}
}
return movelist;
}
std::vector<MoveSequence> AI::getAvailableCapturesFromPoint(Board board, Cell cell) {
//Normal captures
int x = cell.x;
int y = cell.y;
std::vector<MoveSequence> movelist;
if((DeKing(board.cells[y+direction][x+1]) == otherplayer(colour))&&((board.cells[y+direction*2][x+2] == EMPTY)&&(CellInBounds(Cell(x+2,y+direction*2))))) {
gatherCaptures(board,DraughtsMove(Cell(x,y),Cell(x+2,y+direction*2),true),movelist);
}
else if((DeKing(board.cells[y+direction][x-1]) == otherplayer(colour))&&((board.cells[y+direction*2][x-2] == EMPTY)&&(CellInBounds(Cell(x-2,y+direction*2))))) {
gatherCaptures(board,DraughtsMove(Cell(x,y),Cell(x-2,y+direction*2),true),movelist);
}
if(board.cells[y][x] == colour+1) {
//King captures
if((DeKing(board.cells[y-direction][x+1]) == otherplayer(colour))&&((board.cells[y-direction*2][x+2] == EMPTY)&&(CellInBounds(Cell(x+2,y-direction*2))))) {
gatherCaptures(board,DraughtsMove(Cell(x,y),Cell(x+2,y-direction*2),true),movelist);
}
else if((DeKing(board.cells[y-direction][x-1]) == otherplayer(colour))&&((board.cells[y-direction*2][x-2] == EMPTY)&&(CellInBounds(Cell(x-2,y+direction*2))))) {
gatherCaptures(board,DraughtsMove(Cell(x,y),Cell(x-2,y-direction*2),true),movelist);
}
}
return movelist;
}
//double heuristic(Board board) {
// cellState colour = M_WHITE;
//
// //Initialise parameter array
// int parameters[PARAM_TOTAL];
// for(int i=0; i<PARAM_TOTAL; i++) {
// parameters[HeuristicParameter(i)] = 0;
// }
//
// //Get parameters
// for(int y=0; y<BOARD_HEIGHT; y++) {
// for(int x=0; x<BOARD_WIDTH; x++) {
// if(board.cells[y][x] == colour) {
// parameters[PARAM_MEN] += 1;
// if(x == 0 || x == BOARD_WIDTH-1) {
// parameters[PARAM_SAFE_MEN] += 1;
// }
// if(colour == M_WHITE) {
// parameters[PARAM_MEN_DIST] += BOARD_HEIGHT-y;
// }
// else {
// parameters[PARAM_MEN_DIST] += y;
// }
// }
// else if(board.cells[y][x] == colour+1) {
// parameters[PARAM_KINGS] += 1;
// if(x == 0 || x == BOARD_WIDTH-1) {
// parameters[PARAM_SAFE_KINGS] += 1;
// }
// }
// else if(board.cells[y][x] == otherplayer(colour)) {
// parameters[PARAM_ENEMY_MEN] += 1;
// }
// else if(board.cells[y][x] == otherplayer(colour) + 1) {
// parameters[PARAM_ENEMY_KINGS] += 1;
// }
// else if(x % 2 == 0) {
// if(colour == M_WHITE && y == BOARD_HEIGHT-1) {
// parameters[PARAM_PROMOTION_SPACE] += 1;
// }
// if(colour == M_BLACK && y == 0) {
// parameters[PARAM_PROMOTION_SPACE] += 1;
// }
// }
// }
// }
//
// if(HasWon(colour, board)) {
// parameters[PARAM_WIN] = 1;
// }
//
// double result = 0.0;
// for(int i=0; i<PARAM_TOTAL; i++) {
// result += parameters[HeuristicParameter(i)] * PARAM_MULT[HeuristicParameter(i)];
// }
// return result;
//}
MoveSequence AI::getMove(Board board, int depth, bool nodeType, double a, double b) {
double alpha = a;
double beta = b;
std::vector<MoveSequence> movelist;
movelist = getAvailableMoves(board);
std::vector<double> desirabilities;
desirabilities.reserve(movelist.size());
for(unsigned int i=0; i<movelist.size(); i++) {
if(depth == 0) {
desirabilities.push_back(heuristic.function(ExecuteMoveSequence(movelist[i],board), colour));
}
else {
AI playersim(otherplayer(colour), heuristic);
desirabilities.push_back(heuristic.function(ExecuteMoveSequence(playersim.getMove(ExecuteMoveSequence(movelist[i],board),depth-1,!nodeType,alpha,beta),board), colour));
}
if(nodeType == N_MIN) {
if(desirabilities[i] < beta) {
beta = desirabilities[i];
}
}
else {
if(desirabilities[i] > alpha) {
alpha = desirabilities[i];
}
}
if(alpha > beta) {
break;
}
}
int bestindex = 0;
if(nodeType == N_MAX) {
double max = -1000000000;
for(unsigned int i=0; i<desirabilities.size(); i++) {
if(desirabilities[i] > max) {
max = desirabilities[i];
bestindex = i;
}
}
}
if(nodeType == N_MIN) {
double min = 1000000000;
for(unsigned int i=0; i<desirabilities.size(); i++) {
if(desirabilities[i] < min) {
min = desirabilities[i];
bestindex = i;
}
}
}
if(movelist.size() > 0) {
return movelist[bestindex];
} else {
return MoveSequence();
}
}
|
// SettingDlg.cpp : implementation file
//
#include "stdafx.h"
#include "BHMonitor.h"
#include "SettingDlg.h"
#include "BHMonitorDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CSettingDlg dialog
// data initialization is very important!
CSettingDlg::CSettingDlg(CWnd* pParent /*=NULL*/)
: CDialog(CSettingDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CSettingDlg)
m_iPortNr = 6789;
m_iMaxNumberOfConnections = 1024;
m_iNrOfIOWorkers = 4;
m_iNrOfLogicalWorkers = 0;
m_iMaxNrOfFreeBuff = 0;
m_iMaxNrOfFreeContext = 0;
m_iSendInOrder = FALSE;
m_bReadInOrder = FALSE;
m_iNrOfPendlingReads = 4;
//}}AFX_DATA_INIT
}
void CSettingDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CSettingDlg)
DDX_Text(pDX, IDC_PORT, m_iPortNr);
DDX_Text(pDX, IDC_MAX_CONNECTION, m_iMaxNumberOfConnections);
DDV_MinMaxInt(pDX, m_iMaxNumberOfConnections, 1, 10240);
DDX_Text(pDX, IDC_NUM_IO_WORKERS, m_iNrOfIOWorkers);
DDX_Text(pDX, IDC_NUM_LG_WORKERS, m_iNrOfLogicalWorkers);
DDX_Text(pDX, IDC_MAX_UNSAFE_BUFFER, m_iMaxNrOfFreeBuff);
DDX_Text(pDX, IDC_MAX_UNUSED_CLIENTS, m_iMaxNrOfFreeContext);
DDX_Check(pDX, IDC_CK_SEND_ORDERED, m_iSendInOrder);
DDX_Check(pDX, IDC_CK_RECV_ORDERED, m_bReadInOrder);
DDX_Text(pDX, IDC_NUM_PENDING_RLOOP, m_iNrOfPendlingReads);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CSettingDlg, CDialog)
//{{AFX_MSG_MAP(CSettingDlg)
ON_BN_CLICKED(IDC_BT_SAVE_SEETING, OnBtSaveSeeting)
ON_WM_CLOSE()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CSettingDlg message handlers
void CSettingDlg::OnBtSaveSeeting()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
CString msg;
msg.Format("%d", m_iMaxNumberOfConnections);
//AfxMessageBox(msg, MB_OK, 0);
PostMessage(WM_CLOSE);
}
void CSettingDlg::OnClose()
{
// TODO: Add your message handler code here and/or call default
CDialog::OnClose();
}
|
#include "stdafx.h"
#include "CustomReportManager.h"
#include "CustomReport.h"
#include "TextFile.h"
#include "CategoryMgr.h"
#include "Category.h"
#include "Station.h"
CustomReportManager::CustomReportManager()
{
}
CustomReportManager::~CustomReportManager()
{
for (auto pReport : m_customReports)
{
delete pReport;
}
m_customReports.clear();
}
// Create a custom report based off of the given report config file name
bool CustomReportManager::CreateCustomReport(const string& configFileName)
{
bool status = true;
TextFile configFile;
status = configFile.Read(configFileName);
if (!status)
{
printf("Error in CustomReportManager::CreateCustomReport: Unable to read file %s\n", configFileName.c_str());
return false;
}
vector<string> text;
configFile.GetLines(text);
CustomReport *customReport = new CustomReport();
status = customReport->ProcessConfigFile(text);
if (!status)
{
printf("Error in CustomReportManager creating custom report %s\n", configFileName.c_str());
return false;
}
status = customReport->ProcessCategories(configFileName);
if (!status)
{
printf("Error in CustomReportManager creating categories for custom report %s\n", configFileName.c_str());
}
m_customReports.push_back(customReport);
return status;
}
// Create custom reports
bool CustomReportManager::CreateCustomReports(const string& configFilesFolder, list<string>& customReportConfigFilenames)
{
string filename;
bool status = true;
for (string configFileName : customReportConfigFilenames)
{
filename = configFilesFolder + configFileName;
status = CreateCustomReport(filename);
if (!status)
{
printf("Error creating custom report: %s\n", configFileName.c_str());
return false;
}
}
return true;
}
// Generate the custom reports in the results folder
bool CustomReportManager::GenerateReportsForAllStations(const string& resultsFolder, vector<Station*>& stations)
{
for (CustomReport* customReport : m_customReports)
{
TextFile file;
file.AddLine("Custom Report");
file.AddLine(" ");
customReport->GenerateReport(stations, file);
string reportFileName = customReport->GetFileName();
string fileName = resultsFolder + string("AllStations_") + reportFileName;
file.Write(fileName);
}
return true;
}
// Generate the custom reports in the results folder
bool CustomReportManager::GenerateCustomReports(const string& resultsFolder, vector<Station*>& stations)
{
// Create a set of Station* to keep track of stations that are not in any category
set<Station*> allStations(stations.begin(), stations.end());
for (CustomReport* customReport : m_customReports)
{
TextFile file;
file.AddLine("Custom Report");
file.AddLine(" ");
CategoryMgr *catMgr = customReport->GetCategoryMgr();
// Get a copy of the list of categories
list<Category*> categories;
catMgr->GetCategories(categories);
string categoryTitle;
for (Category* category : categories)
{
list<Station*>& catStations = category->m_stations;
if (catStations.empty())
continue;
for (Station *s : catStations)
allStations.erase(s);
categoryTitle = category->m_title;
if (!categoryTitle.empty())
file.AddLine(categoryTitle);
// Convert the list of station ptrs to a vector of station ptrs
vector<Station*> stationVector(std::begin(catStations), std::end(catStations));
customReport->GenerateReport(stationVector, file);
file.AddLine(" ");
}
if (!allStations.empty())
{
file.AddLine("The following stations are not found in any category:");
for (Station *s : allStations)
{
file.AddLine(s->StationCallsign());
}
file.AddLine(" ");
}
string reportFileName = customReport->GetFileName();
string fileName = resultsFolder + reportFileName;
file.Write(fileName);
}
return true;
}
// Determine the categories for each station in all custom reports
void CustomReportManager::DetermineStationCategories(vector<Station*>& stations)
{
for (CustomReport *customReport : m_customReports)
{
customReport->DetermineStationCategories(stations);
}
}
|
#include "RaseProcess.h"
#include "HallHandler.h"
#include "Logger.h"
#include "Configure.h"
#include "GameServerConnect.h"
#include "PlayerManager.h"
#include "GameCmd.h"
#include "RobotDefine.h"
#include "ProcessManager.h"
#include <string>
using namespace std;
RaseProcess::RaseProcess()
{
this->name = "RaseProcess";
}
RaseProcess::~RaseProcess()
{
}
int RaseProcess::doRequest(CDLSocketHandler* client, InputPacket* pPacket, Context* pt )
{
HallHandler* clientHandler = dynamic_cast<HallHandler*> (client);
Player* player = PlayerManager::getInstance().getPlayer(clientHandler->uid);
if(player == NULL)
return 0;
OutputPacket requestPacket;
requestPacket.Begin(CLIENT_MSG_BET_RASE, player->id);
requestPacket.WriteInt(player->id);
requestPacket.WriteInt(player->tid);
requestPacket.WriteInt64(player->rasecoin);
requestPacket.End();
this->send(clientHandler, &requestPacket);
ULOGGER(E_LOG_DEBUG, player->id) << "name=" << player->name << " money=" << player->money << " rasecoin=" << player->rasecoin;
return 0;
}
int RaseProcess::doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket,Context* pt)
{
HallHandler* hallHandler = dynamic_cast<HallHandler*>(clientHandler);
Player* player = PlayerManager::getInstance().getPlayer(hallHandler->uid);
if (player == NULL) {
ULOGGER(E_LOG_WARNING, hallHandler->uid) << "[robotexit] player not found";
return EXIT;
}
int retcode = inputPacket->ReadShort();
string retmsg = inputPacket->ReadString();
if(retcode == -4) {
player->comparecard();
return 0;
} else if(retcode == -1) {
return 0;
} else if (retcode < 0) {
ULOGGER(E_LOG_WARNING, hallHandler->uid) << "[robotexit] retcode=" << retcode << " retmsg=" << retmsg;
return EXIT;
}
int uid = inputPacket->ReadInt();
short ustatus = inputPacket->ReadShort();
int tid = inputPacket->ReadInt();
short tstatus = inputPacket->ReadShort();
player->currRound = inputPacket->ReadByte();
int callid = inputPacket->ReadInt();
int64_t callcoin = inputPacket->ReadInt64();
int64_t betcoin = inputPacket->ReadInt64();
int64_t money = inputPacket->ReadInt64();
player->currmax = inputPacket->ReadInt64();
int nextid = inputPacket->ReadInt();
player->sumbetcoin = inputPacket->ReadInt64();
int64_t selfmoney = inputPacket->ReadInt64();
player->optype = inputPacket->ReadShort();
int64_t sumpool = inputPacket->ReadInt64();
ULOGGER(E_LOG_DEBUG, uid) << "user status=" << ustatus << " tid=" << tid << " table status=" << tstatus << " nextid=" << nextid;
if (tid != player->tid) {
ULOGGER(E_LOG_INFO, uid) << "[robot exit] tid=" << tid << " not equal player->tid=" << player->tid;
return EXIT;
}
if(uid == nextid)
{
if(player->isRaseMax())
player->startBetCoinTimer(uid, ROBOT_BASE_BET_TIMEROUT);
else
player->startBetCoinTimer(uid, ROBOT_BASE_BET_TIMEROUT + rand() % ROBOT_RAND_BET_TIMEROUT);
ULOGGER(E_LOG_DEBUG, uid) << "startBetCoinTimer";
}
return 0;
}
REGISTER_PROCESS(CLIENT_MSG_BET_RASE, RaseProcess)
|
#include <iostream>
#include <sstream>
#include <vector>
#include <list>
#include <queue>
#include <algorithm>
#include <iomanip>
#include <map>
#include <string>
#include <cstdio>
#include <cstring>
#include <climits>
using namespace std;
struct station {
double price;
int d;
bool operator< (const station& rhs) const {
return d < rhs.d;
}
};
int main() {
int cmax, d, avg, n;
cin >> cmax >> d >> avg >> n;
vector<station> v;
v.resize(n+1);
for (int i = 0; i < n; i++)
scanf("%lf %d", &v[i].price, &v[i].d);
v[n].price = 0; v[n].d = d;
sort(v.begin(), v.end());
double sum = 0;
int left = 0, index = 0;
if (v[0].d != 0) {
printf("The maximum travel distance = 0.00\n");
}
else {
for (int i = 0; i < n;) {
double m = INT_MAX;
if (i == n - 1) break;
index = i+1;
if (index < n+1) {
for (int j = i + 1; j < n+1 && (v[j].d - v[i].d) <= cmax * avg; j++) {
if (v[j].price <= v[i].price) {
index = j;
break;
}
if (v[j].price < m) {
m = v[j].price;
index = j;
}
}
//printf("%d %d %d\n", index, i, left);
if (v[index].d - v[i].d > cmax*avg) {
index = i;
break;
}
if (v[index].price < v[i].price) {
sum += v[i].price / avg * (v[index].d - v[i].d - left);
left = 0;
}
else {
sum += v[i].price / avg * (cmax*avg - left);
left = cmax*avg - (v[index].d - v[i].d);
}
}
i = index;
}
if (d - v[index].d > cmax*avg) {
printf("The maximum travel distance = %.2f\n", (float)v[index].d + cmax*avg);
}
else {
sum += v[index].price / avg * (d - v[index].d - left);
printf("%.2lf", sum);
}
}
return 0;
}
|
#include <iostream>
int func(){
int a = 1;
int b = 2;
std::cout << a << b;
std::cout << a+b << std::endl;
}
|
#include <iostream>
#include <stack>
#include <queue>
using namespace std;
#define OK 1
#define ERROR 0
struct Treenode
{
int m_data;
Treenode* m_lchild;
Treenode* m_rchild;
};
int InitialBitree(Treenode*& T);
void CreatBitree(Treenode*& T, int value);
void Preorder(Treenode* T);
void PreorderNoRec2(Treenode* T);
void Inorder(Treenode* T);
void InorderNoRec2(Treenode* T);
void Postorder(Treenode* T);
void PostorderNoRec2(Treenode* T);
void Leveoreder(Treenode* T);
void PreorderNoRec(Treenode* T);
void InorderNoRec(Treenode* T);
int main()
{
Treenode* T;
InitialBitree(T);
CreatBitree(T, 5);
CreatBitree(T, 4);
CreatBitree(T, 6);
CreatBitree(T, 3);
CreatBitree(T, 5);
//PostorderNoRec2(T);
Leveoreder(T);
return 0;
}
int InitialBitree(Treenode*& T)
{
T = nullptr;
return OK;
}
void CreatBitree(Treenode*& T,int value)
{
Treenode* pNew = new Treenode();//生成新的结点
pNew->m_data = value;
pNew->m_lchild = nullptr;
pNew->m_rchild = nullptr;
int flag = 0; //设置成功插入的标志,设置为1表示插入成功
if (T == nullptr) T = pNew;
else
{
Treenode* p = T;
while (!flag)
{
if (value < p->m_data) //小于根节点,插入左子树
{
if (p->m_lchild == nullptr)
{
p->m_lchild = pNew;
flag = 1;
}
else
p = p->m_lchild;
}
else//大于等于根结点,插入右子树
{
if (p->m_rchild == nullptr)
{
p->m_rchild = pNew;
flag = 1;
}
else
p = p->m_rchild;
}
}
}
}
void Preorder(Treenode* T) //递归前序
{
if (T)
{
cout << T->m_data << endl;
Preorder(T->m_lchild);
Preorder(T->m_rchild);
}else return;
}
void PreorderNoRec2(Treenode* T)//前序非递归
{
stack<Treenode*> s;
if (T) s.push(T); //首先入栈根结点
Treenode* p = nullptr;
while (!s.empty())
{
p = s.top();
s.pop();
if (p != nullptr)
{
if (p->m_rchild) s.push(p->m_rchild); //右结点先入栈,后处理
if (p->m_lchild) s.push(p->m_lchild);
s.push(p); //当前节点重新入栈(留着以后处理),因为先序遍历所以最后压栈
s.push(nullptr); //在当前节点之前加入一个空节点表示已经访问过了
}
else
{
cout << s.top()->m_data << endl;
s.pop();
}
}
}
void Inorder(Treenode* T) //递归中序
{
if (T)
{
Inorder(T->m_lchild);
cout << T->m_data << endl;
Inorder(T->m_rchild);
}else return;
}
void InorderNoRec2(Treenode* T)//前序非递归
{
stack<Treenode*> s;
if (T) s.push(T); //首先入栈根结点
Treenode* p = nullptr;
while (!s.empty())
{
p = s.top();
s.pop();
if (p != nullptr)
{
if (p->m_rchild) s.push(p->m_rchild); //右结点先入栈,后处理
s.push(p); //当前节点重新入栈(留着以后处理),因为先序遍历所以最后压栈
s.push(nullptr); //在当前节点之前加入一个空节点表示已经访问过了
if (p->m_lchild) s.push(p->m_lchild);
}
else
{
cout << s.top()->m_data << endl;
s.pop();
}
}
}
void Postorder(Treenode* T) //递归后序
{
if (T)
{
Postorder(T->m_lchild);
Postorder(T->m_rchild);
cout << T->m_data << endl;
}
else return;
}
void PostorderNoRec2(Treenode* T)//前序非递归
{
stack<Treenode*> s;
if (T) s.push(T); //首先入栈根结点
Treenode* p = nullptr;
while (!s.empty())
{
p = s.top();
s.pop();
if (p != nullptr)
{
s.push(p); //当前节点重新入栈(留着以后处理),因为先序遍历所以最后压栈
s.push(nullptr); //在当前节点之前加入一个空节点表示已经访问过了
if (p->m_rchild) s.push(p->m_rchild); //右结点先入栈,后处理
if (p->m_lchild) s.push(p->m_lchild);
}
else
{
cout << s.top()->m_data << endl;
s.pop();
}
}
}
void Leveoreder(Treenode* T)//层序遍历
{
queue<Treenode*> qu;
if (T) qu.push(T);
Treenode* p = nullptr;
while (!qu.empty())
{
p = qu.front();
qu.pop();
cout <<p->m_data<<endl;
if (p->m_lchild) qu.push(p->m_lchild);
if (p->m_rchild) qu.push(p->m_rchild);
}
}
void PreorderNoRec(Treenode* T)//前序非递归
{
if (!T) return;
else
{
stack<Treenode*> s;//申请一个栈空间
s.push(T);
Treenode* p = nullptr;
while (!s.empty())
{
p = s.top();
s.pop();
if (p) //如果当前结点不为空,打印当前结点,右节点先入栈,左结点再入栈
{
cout << p->m_data << endl;
s.push(p->m_rchild);
s.push(p->m_lchild);
}
}
}
}
void InorderNoRec(Treenode* T) //中序非递归
{
if (!T) return;
else
{
stack<Treenode*> s;
Treenode* p = T;
while (p || !s.empty())
{
if (p)
{
s.push(p);
p = p->m_lchild;
}
else
{
p = s.top();
s.pop();
cout << p->m_data << endl;
p = p->m_rchild;
}
}
}
}
|
//
// nehe01.cpp
// NeheGL
//
// Created by Andong Li on 8/31/13.
// Copyright (c) 2013 Andong Li. All rights reserved.
//
#include "nehe01.h"
const char* NEHE01::TITLE = "NEHE01";
GLvoid NEHE01::ReSizeGLScene(GLsizei width, GLsizei height){
// Prevent A Divide By Zero By
if(height==0)
{
height=1;
}
// Reset The Current Viewport
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// Calculate The Aspect Ratio Of The Window
gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
GLvoid NEHE01::InitGL(){
// Enables Smooth Shading
glShadeModel(GL_SMOOTH);
// clear background as black
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClearDepth(1.0f);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
// want the best perspective correction to be done
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
}
GLvoid NEHE01::DrawGLScene(){
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glutSwapBuffers();
}
|
#include <fstream>
#include <stdlib.h>
#include <vector>
#include <cmath>
#include <iostream>
#include <sstream>
#include <vector>
#include <opencv2/opencv.hpp>
#include <opencv2/core/cuda.hpp>
#include <opencv2/cudaimgproc.hpp>
using namespace cv;
using namespace std;
double Reciprocal(const double &);
Mat Reciprocal(const Mat &);
Mat Pooling(const Mat &M, int pVert, int pHori, int poolingMethod);
void makeGaussianPyramid(Mat& src, int s, vector<Mat>& pyr);
vector<Mat> centerSurround(vector<Mat>& fmap1, vector<Mat>& fmap2);
void normalizeMap(vector<Mat>& nmap);
Mat make_depth_histogram(Mat data, int width, int height);
#define ATD at<double>
#define elif else if
// Pooling methods
#define POOL_MAX 0
#define POOL_MEAN 1 //don't use
#define POOL_STOCHASTIC 2
void fliplr(const Mat &, Mat &);
void flipud(const Mat &, Mat &);
void flipudlr(const Mat &, Mat &);
void rotateNScale(const Mat &, Mat &, double, double);
void addWhiteNoise(const Mat &, Mat &, double);
void dataEnlarge(vector<Mat>&, Mat&);
int main (){
vector<Mat> trainX;
vector<Mat> trainGT;
Mat trainY = Mat::zeros(5168, 3, CV_64FC1);
for ( int i=1 ; i <= 5168 ; i++ )
{
Mat buf;
char file_name[255];
sprintf(file_name,"DUT-OMRON/DUT-OMRON-image/img(%d).jpg",i);
buf = imread(file_name);
trainX.push_back(buf);
}
for ( int i=1 ; i <= 5168 ; i++ )
{
Mat buf;
char file_name[255];
sprintf(file_name,"DUT-OMRON/DUT-OMRON-GT/img_gt(%d).png",i);
buf = imread(file_name,0);
normalize(buf,buf, 0,1,NORM_MINMAX,CV_32F);
trainGT.push_back(buf);
}
vector<cuda::GpuMat> kernels(4);
for(int k=0; k<kernels.size(); k++) {
Mat kernel = getGaborKernel(Size(20,20),1, CV_PI/4*k, 30, 0,CV_PI/2);
kernel.convertTo(kernel,CV_32F);
kernels[k].upload(kernel);
}
ofstream imgdata;
imgdata.open("imgdata.txt",ios::out);
if ( imgdata.is_open() )
{
for ( int i=0 ; i < trainX.size() ; i++ )
{
Mat frame = trainX[i];
// Step 1.
vector<Mat> GausnPyr(9);
makeGaussianPyramid(frame,GausnPyr.size(),GausnPyr);
// Step 2.
vector<Mat> Pyr_I(GausnPyr.size()); //Pyr_I[#pyr]
vector<vector<Mat>> Pyr_C(2); //Pyr_C[#BGR][#pyr]
vector<vector<Mat>> Pyr_O(4); //Pyr_O[#theta][#pyr]
for(int i=0; i<GausnPyr.size(); i++) {
vector<Mat> vtemp(3);
split(GausnPyr[i], vtemp);
// Make Intensity Map -> #1
Pyr_I[i] = (vtemp[0]+vtemp[1]+vtemp[2])/3; //Blue
// Make Color Map -> #2
Mat B = vtemp[0]-(vtemp[1]+vtemp[2])/2; //Blue
Mat Y = (vtemp[2]+vtemp[1])/2-abs((vtemp[2]-vtemp[1])/2)-vtemp[0]; //Yellow
Mat R = vtemp[2]-(vtemp[1]+vtemp[0])/2; //Red
Mat G = vtemp[1]-(vtemp[0]+vtemp[2])/2; //Green
Pyr_C[0].push_back((Mat)(B-Y));
Pyr_C[1].push_back((Mat)(R-G));
vtemp.clear();
// Make Orientation Map -> #4
Ptr<cuda::Convolution> convolver = cuda::createConvolution(Size(kernels[0].cols,kernels[0].rows));
cuda::GpuMat buf1(Pyr_I[i]);
for(int k=0; k<Pyr_O.size(); k++){
Mat temp;
cuda::GpuMat buf2;
buf1.convertTo(buf2,CV_32F);
cuda::copyMakeBorder(buf2,buf2,kernels[k].cols/2,kernels[k].rows/2,kernels[k].cols/2,kernels[k].rows/2,BORDER_REFLECT_101);
convolver->convolve(buf2,kernels[k],buf2,true);
buf2.download(temp);
Pyr_O[k].push_back(temp);
}
buf1.release();
}
GausnPyr.clear();
// Step 3. Center-Surrounded Difference
vector<Mat> CSD_I,CSD_C,CSD_O;
CSD_I = centerSurround(Pyr_I,Pyr_I); // 8->6
Pyr_I.clear();
for(int k=0; k<Pyr_C.size(); k++) {
vector<Mat> inv_Pyr_C(Pyr_C[k].size());
for(int l=0; l<Pyr_C[k].size(); l++) inv_Pyr_C[l] = -Pyr_C[k][l];
Pyr_C[k] = centerSurround(Pyr_C[k],inv_Pyr_C); //R-G and G-R, B-Y and Y-B
for(int l=0; l<Pyr_C[k].size(); l++) CSD_C.push_back(Pyr_C[k][l]);
Pyr_C[k].clear();
}
Pyr_C.clear();
for(int k=0; k<Pyr_O.size(); k++) {
Pyr_O[k] = centerSurround(Pyr_O[k],Pyr_O[k]);
for(int l=0; l<Pyr_O[k].size(); l++) CSD_O.push_back(Pyr_O[k][l]);
Pyr_O[k].clear();
}
Pyr_O.clear();
// Step 4. Normalization
normalizeMap(CSD_I);
normalizeMap(CSD_C);
normalizeMap(CSD_O);
// Step 5. Conspicuity Maps
Mat I = Mat::zeros(Size(CSD_I[0].cols,CSD_I[0].rows),CSD_I[0].type());
Mat C = Mat::zeros(Size(CSD_C[0].cols,CSD_C[0].rows),CSD_C[0].type());
Mat O = Mat::zeros(Size(CSD_O[0].cols,CSD_O[0].rows),CSD_O[0].type());
for(int i=0; i<CSD_I.size(); i++) I += CSD_I[i];
for(int i=0; i<CSD_C.size(); i++) C += CSD_C[i];
for(int i=0; i<CSD_O.size(); i++) O += CSD_O[i];
CSD_I.clear(); CSD_C.clear(); CSD_O.clear();
normalize(I,I,0,1,NORM_MINMAX,CV_32F);
Mat buf_I = (I & trainGT[i]);
int sum_I=countNonZero(buf_I);
resize(I,I,Size(400,400));
I = Pooling(I, 8, 8, POOL_MAX);
I = Pooling(I, 2, 2, POOL_MEAN);
normalize(C,C,0,1,NORM_MINMAX,CV_32F);
Mat buf_C = (C&trainGT[i]);
int sum_C=countNonZero(buf_C);
resize(C,C,Size(400,400));
C = Pooling(C, 8, 8, POOL_MAX);
C = Pooling(C, 2, 2, POOL_MEAN);
normalize(O,O,0,1,NORM_MINMAX,CV_32F);
Mat buf_O = (O&trainGT[i]);
int sum_O=countNonZero(buf_O);
resize(O,O,Size(400,400));
O = Pooling(O, 8, 8, POOL_MAX);
O = Pooling(O, 2, 2, POOL_MEAN);
Mat set(Size(O.cols,O.rows*3),O.type());
vector<Mat> bufbufbuf{I,C,O};
vconcat(bufbufbuf,set);
for(int j = 0; j < set.rows; j++)
for(int i = 0; i < set.cols; i++)
imgdata << set.at<double>(j,i) << ",";
if(sum_I<sum_C && sum_I<sum_O) trainY.ATD(i,0) = 1;
else if(sum_C<sum_I && sum_C<sum_O) trainY.ATD(i,1) = 1;
else trainY.ATD(i,2) = 1;
for(int j = 0; j < trainY.cols; j++) imgdata << trainY.ATD(i, j) << ",";
imgdata << endl;
}
}
imgdata.close();
trainGT.clear();
trainX.clear();
trainY.release();
return 0;
}
void
fliplr(const Mat &_from, Mat &_to){
flip(_from, _to, 1);
}
void
flipud(const Mat &_from, Mat &_to){
flip(_from, _to, 0);
}
void
flipudlr(const Mat &_from, Mat &_to){
flip(_from, _to, -1);
}
void
rotateNScale(const Mat &_from, Mat &_to, double angle, double scale){
Point center = Point(_from.cols / 2, _from.rows / 2);
// Get the rotation matrix with the specifications above
Mat rot_mat = getRotationMatrix2D(center, angle, scale);
// Rotate the warped image
warpAffine(_from, _to, rot_mat, _to.size());
}
void
addWhiteNoise(const Mat &_from, Mat &_to, double stdev){
_to = Mat::ones(_from.rows, _from.cols, CV_64FC1);
randu(_to, Scalar(-1.0), Scalar(1.0));
_to *= stdev;
_to += _from;
// how to make this faster?
for(int i = 0; i < _to.rows; i++){
for(int j = 0; j < _to.cols; j++){
if(_to.ATD(i, j) < 0.0) _to.ATD(i, j) = 0.0;
if(_to.ATD(i, j) > 1.0) _to.ATD(i, j) = 1.0;
}
}
}
void
dataEnlarge(vector<Mat>& data, Mat& label){
int nSamples = data.size();
/*
// flip left right
for(int i = 0; i < nSamples; i++){
fliplr(data[i], tmp);
data.push_back(tmp);
}
// flip left right up down
for(int i = 0; i < nSamples; i++){
flipudlr(data[i], tmp);
data.push_back(tmp);
}
// add white noise
for(int i = 0; i < nSamples; i++){
Mat tmp;
addWhiteNoise(data[i], tmp, 0.05);
data.push_back(tmp);
}
*/
// rotate -10 degree
for(int i = 0; i < nSamples; i++){
Mat tmp;
rotateNScale(data[i], tmp, -10, 1.2);
data.push_back(tmp);
}
// rotate +10 degree
for(int i = 0; i < nSamples; i++){
Mat tmp;
rotateNScale(data[i], tmp, 10, 1.2);
data.push_back(tmp);
}
// copy label matrix
cv::Mat tmp;
repeat(label, 3, 1, tmp);
label = tmp;
}
Mat
Pooling(const Mat &M, int pVert, int pHori, int poolingMethod){
if(pVert == 1 && pHori == 1){
Mat res;
M.copyTo(res);
return res;
}
int remX = M.cols % pHori;
int remY = M.rows % pVert;
Mat newM;
if(remX == 0 && remY == 0) M.copyTo(newM);
else{
Rect roi = Rect(remX / 2, remY / 2, M.cols - remX, M.rows - remY);
M(roi).copyTo(newM);
}
Mat res = Mat::zeros(newM.rows / pVert, newM.cols / pHori, CV_64FC1);
for(int i=0; i<res.rows; i++){
for(int j=0; j<res.cols; j++){
Mat temp;
Rect roi = Rect(j * pHori, i * pVert, pHori, pVert);
newM(roi).copyTo(temp);
double val = 0.0;
// for Max Pooling
if(POOL_MAX == poolingMethod){
double minVal = 0.0;
double maxVal = 0.0;
Point minLoc(0,0);
Point maxLoc(0,0);
minMaxLoc( temp, &minVal, &maxVal, &minLoc, &maxLoc,noArray() );
val = maxVal;
}elif(POOL_MEAN == poolingMethod){
// Mean Pooling
val = (double)sum(temp)[0] / (double)(pVert * pHori);
}elif(POOL_STOCHASTIC == poolingMethod){
// Stochastic Pooling
double sumval = sum(temp)[0];
Mat prob = temp.mul(Reciprocal(sumval));
val = sum(prob.mul(temp))[0];
prob.release();
}
res.ATD(i, j) = val;
temp.release();
}
}
newM.release();
return res;
}
double
Reciprocal(const double &s){
double res = 1.0;
res /= s;
return res;
}
Mat
Reciprocal(const Mat &M){
return 1.0 / M;
}
void makeGaussianPyramid(Mat& src, int s, vector<Mat>& pyr){
pyr[0] = src.clone();
for(int i=1; i<s; i++){
pyrDown(pyr[i-1],pyr[i], Size((int)(pyr[i-1].cols/2),(int)(pyr[i-1].rows/2)));
resize(pyr[i],pyr[i],Size(pyr[0].cols,pyr[0].rows));
}
}
vector<Mat> centerSurround(vector<Mat>& fmap1, vector<Mat>& fmap2){
vector<int> center = {2,3,4};
vector<int> delta = {3,4};
vector<Mat> CSD;
for(int c=0; c < center.size(); c++)
for(int d=0; d<delta.size(); d++)
{
Mat ctemp = fmap1[center[c]];
Mat stemp = fmap2[delta[d]+center[c]];
Mat temp = abs(ctemp-stemp);
CSD.push_back(temp);
temp.release();
}
return CSD;
}
void normalizeMap(vector<Mat>& nmap){
for(int i=0; i<nmap.size(); i++)
{
normalize(nmap[i],nmap[i],0,1,NORM_MINMAX,CV_32F);
Scalar meanVal = mean(nmap[i]);
nmap[i] *= pow((1-(double)meanVal.val[0]),2);
}
}
Mat make_depth_histogram(Mat data, int width, int height)
{
Mat rgb(Size(data.cols,data.rows), CV_8UC3);
static uint32_t histogram[0x10000];
memset(histogram, 0, sizeof(histogram));
for(int j = 0; j < height; ++j) for(int i = 0; i < width; ++i) ++histogram[data.at<uint16_t>(j,i)];
for(int i = 2; i < 0x10000; ++i) histogram[i] += histogram[i-1]; // Build a cumulative histogram for the indices in [1,0xFFFF]
for(int j = 0; j < height; ++j)
for(int i = 0; i < width; ++i){
if(uint16_t d = data.at<uint16_t>(j,i))
{
int f = histogram[d] * 255 / histogram[0xFFFF]; // 0-255 based on histogram location
rgb.at<Vec3b>(j, i)[0] = 255 - f;
rgb.at<Vec3b>(j, i)[1] = 0;
rgb.at<Vec3b>(j, i)[2] = f;
}
else
{
rgb.at<Vec3b>(j, i)[0] = 0;
rgb.at<Vec3b>(j, i)[1] = 5;
rgb.at<Vec3b>(j, i)[2] = 20;
}
}
return rgb;
}
|
#include "stdafx.h"
#include "MonsterActionManeger.h"
#include "MonsterAction.h"
#include "../GameData.h"
#include "Action/Act_Chase.h"
#include "Action/Act_Atack.h"
#include "Action/Act_Leave.h"
#include "Action/Act_Defense.h"
#include "Action/Act_Fire.h"
#include "Action/Act_Tackle.h"
#include "Action/Act_Guardian.h"
#include "Action/Act_Recovery.h"
#include "Action/Act_superBeam.h"
#include "Action/Act_ObstMove.h"
#include "Action/Act_Cleanse.h"
#include "Action/Act_buffAtcPow.h"
#include "Action/Act_buffDefPow.h"
#include "Action/Act_debuffAtcPow.h"
#include "Action/Act_debuffDefPow.h"
#include "Action/Act_ClearStack.h"
#include "Action/Act_Majinken.h"
#include "Action/Act_ManaHeal.h"
#include "Action/Act_Blizzard.h"
#include "Action/Act_Ignite.h"
#include "Action/Act_Poison.h"
#include "Action/Act_Thunder.h"
#include "Action/Act_specialAttack.h"
#include "Action/Act_Move.h"
MonsterAction * MonsterActionManeger::LoadAction(int id,int target,...)
{
MonsterAction* ac;
switch (id)
{
case enChase:
ac = NewGO<Act_Chase>(0, "action");
ac->Settarget(target);
return ac;
break;
case enAtack:
ac = NewGO<Act_Atack>(0, "action");
ac->Settarget(target);
return ac;
break;
case enLeave:
ac = NewGO<Act_Leave>(0, "action");
ac->Settarget(target);
return ac;
break;
case enDefense:
ac = NewGO<Act_Defense>(0, "action");
ac->Settarget(target);
return ac;
case enFire:
ac = NewGO<Act_Fire>(0, "action");
ac->Settarget(target);
return ac;
case enTackle:
ac = NewGO<Act_Tackle>(0, "action");
ac->Settarget(target);
return ac;
case enGuardian:
ac = NewGO<Act_Guardian>(0, "action");
ac->Settarget(target);
return ac;
case enRecovery:
ac = NewGO<Act_Recovery>(0, "action");
ac->Settarget(target);
return ac;
case enSuperBeam:
ac = NewGO<Act_superBeam>(0, "action");
ac->Settarget(target);
return ac;
case enObstMove:
ac = NewGO<Act_ObstMove>(0, "action");
ac->Settarget(target);
return ac;
case enCleanse:
ac = NewGO<Act_Cleanse>(0, "action");
ac->Settarget(target);
return ac;
case enBuffAtc:
ac = NewGO<Act_buffAtcPow>(0, "action");
ac->Settarget(target);
return ac;
case enDebuffAtc:
ac = NewGO<Act_debuffAtcPow>(0, "action");
ac->Settarget(target);
return ac;
case enBuffDef:
ac = NewGO<Act_buffDefPow>(0, "action");
ac->Settarget(target);
return ac;
case enDebuffDef:
ac = NewGO<Act_debuffDefPow>(0, "action");
ac->Settarget(target);
return ac;
case enClearStack:
ac = NewGO<Act_ClearStack>(0, "action");
ac->Settarget(target);
return ac;
case enMajinken:
ac = NewGO<Act_Majinken>(0, "action");
ac->Settarget(target);
return ac;
case enManaHeal:
ac = NewGO<Act_ManaHeal>(0, "action");
ac->Settarget(target);
return ac;
case enBlizzard:
ac = NewGO<Act_Blizzard>(0, "action");
ac->Settarget(target);
return ac;
case enIgnite:
ac = NewGO<Act_Ignite>(0, "action");
ac->Settarget(target);
return ac;
case enPoison:
ac = NewGO<Act_Poison>(0, "action");
ac->Settarget(target);
return ac;
case enThunder:
ac = NewGO<Act_Thunder>(0, "action");
ac->Settarget(target);
return ac;
case enSpecialAttack:
ac = NewGO<Act_SpecialAttack>(0, "action");
ac->Settarget(target);
return ac;
case enMove:
{
Act_Move* move = NewGO<Act_Move>(0, "action");
move->Settarget(target);
float x = 0, y = 0;
va_list args;
va_start(args,target);
x = va_arg(args, double);
y = va_arg(args, double);
va_end(args);
move->SetTargetPosition(x, y);
return move;
}
}
return nullptr;
}
|
#include <iostream>
#include <complex>
#include <type_traits>
template<bool B, typename T>
using Enable_if = typename std::enable_if<B, T>::type;
template<typename T>
constexpr
bool is_class() {
return std::is_class<T>::value;
}
template<typename T>
class smart_pointer {
public:
T &operator*();
template<typename U = T>
Enable_if<is_class<U>(), U> *operator->();
};
void test(smart_pointer<double> p) {
// smart_pointer<double> p;
smart_pointer<std::complex<double>> q;
}
template<typename T>
class Vector<T> {
public:
Vector(size_t n, T const& val);
template<typename Iter, typename = Enable_if<std::input_iterator<Iter>(), Iter>>
Vector(Iter b, Iter e);
template<typename Iter>
Vector(Enable_if<std::input_iterator<Iter>()> b, Iter e);
};
template<bool B, typename T void>
struct my_enable_if {
using type = T;
};
template<typename T>
struct my_enable_if<false, T> {};
template<bool B, typename T = void>
using My_enable_if = typename my_enable_if<B, T>::type;
int main() {
return 0;
}
|
// Copyright 2011 Yandex
#ifndef LTR_SCORERS_COMPOSITION_SCORERS_MEDIAN_COMPOSITION_SCORER_H_
#define LTR_SCORERS_COMPOSITION_SCORERS_MEDIAN_COMPOSITION_SCORER_H_
#include <string>
#include "ltr/scorers/composition_scorers/order_statistic_composition_scorer.h"
using std::string;
namespace ltr {
namespace composition {
/**
* A composition scorer - contains other scorers with their weights. Scores as
* weighted median of outputs of its weak scorers
*/
class MedianCompositionScorer : public OrderStatisticCompositionScorer {
public:
typedef ltr::utility::shared_ptr<MedianCompositionScorer> Ptr;
MedianCompositionScorer()
: OrderStatisticCompositionScorer(0.5) {}
/**
* @param parameters Standart LTR parameter container with no parameters
*/
explicit MedianCompositionScorer(const ParametersContainer& parameters) {}
virtual string toString() const;
private:
virtual string getDefaultAlias() const {
return "MedianCompositionScorer";
}
};
};
};
#endif // LTR_SCORERS_COMPOSITION_SCORERS_MEDIAN_COMPOSITION_SCORER_H_
|
#include <GL/glut.h>
#include <cmath>
#include "point.h"
#include "line.h"
#include "circle.h"
#include "rectangle.h"
#include "triangle.h"
bool circle::overlaps(const point p) const {
return this->center.distance(p) <= this->radius;
}
bool circle::overlaps(const segment s) const {
return this->center.distance(s.closest_from(this->center)) <= this->radius;
}
bool circle::overlaps(const circle c) const {
return this->center.distance(c.center) <= this->radius + c.radius;
}
bool circle::overlaps(const rectangle r) const {
return r.overlaps(*this);
}
bool circle::overlaps(const triangle t) const {
if(t.overlaps(this->center)) return true;
if(this->overlaps(t.A)) return true;
segment t_AB (t.A, t.B),
t_AC (t.A, t.C),
t_BC (t.B, t.C);
return this->overlaps(t_AB)
|| this->overlaps(t_AC)
|| this->overlaps(t_BC);
}
bool circle::onscreen() const { return true; }
void circle::draw() const {
int num_segments = 300;
double theta;
double x, y;
glColor3f(1.0, 0.0, 0.0);
glBegin(this->fill?GL_TRIANGLE_FAN:GL_LINE_LOOP);
for(int ii = 0; ii < num_segments; ii++) {
theta = M_PI * 2 * ii / num_segments;
x = this->radius * std::cos(theta);
y = this->radius * std::sin(theta);
glVertex2f(x + this->center.x, y + this->center.y);
}
glEnd();
glFlush();
}
void circle::translade(double x, double y) {
this->center.x += x;
this->center.y += y;
}
|
#include <FastLED.h>
#define LED_COUNT 32
#define LED_TYPE WS2812B
#define LED_FORMAT RGB
#define LED_DATA_PIN 8
#define GAMESTATE_BOOT 0
#define GAMESTATE_INTRO 1
#define GAMESTATE_PLAYING 2
#define GAMERULES_SET1 1
#define GAMERULES_SET2 2
#define PLAYER_1_PIN 2
#define PLAYER_2_PIN 3
#define RULE_INPUT_BLOCK_TIME 200
#define RULE_BOUNCE_SPEED_MOD 200
#define PROJECTILE_DELAY_START 1000
#define PROJECTILE_DELAY_MIN 50
#define PROJECTILE_DELAY_CHANGE 50
#define PROJECTILE_DELAY_CHANGE_INTERVAL 2000
#define DISABLE_LEDS true
typedef struct
{
int RuleSet;
int LifeCount;
int TimeLimit;
int SpeedModInterval;
int BounceSpeedMod;
int TimeSpeedMod;
} GameRulesT;
typedef struct
{
int Player1Score;
int Player2Score;
} GameStateT;
typedef struct
{
int GamesPlayed;
int BestScore;
} GameStatsT;
typedef struct
{
int Position;
int Direction;
unsigned long LastMove;
unsigned long MoveDelay;
unsigned long LastMoveDelayChange;
} ProjectileT;
CRGB LEDState[LED_COUNT];
int GameState = GAMESTATE_BOOT;
ProjectileT Projectile;
GameRulesT GameRules;
void SetInitialState()
{
for( int i=0; i <= LED_COUNT; ++i )
{
LEDState[i] = CRGB::Blue;
}
Projectile.Position = 0;
Projectile.Direction = 1;
Projectile.LastMove = millis();
Projectile.MoveDelay = PROJECTILE_DELAY_START;
Projectile.LastMoveDelayChange = millis();
}
void Debug_PrintLEDState()
{
Serial.print( "[" );
for( int i=0; i < LED_COUNT; ++i )
{
if( LEDState[i] )
{
Serial.print( "*" );
}
else
{
Serial.print( "-" );
}
}
Serial.print( "]" );
}
void UpdateLEDStrip()
{
Debug_PrintLEDState();
if( DISABLE_LEDS )
{
return;
}
FastLED.show();
}
void HandleInput()
{
if( digitalRead( PLAYER_1_PIN ) == HIGH )
{
Projectile.Direction = 1;
}
if( digitalRead( PLAYER_2_PIN ) == HIGH )
{
Projectile.Direction = -1;
}
}
void UpdateTimers( unsigned long now )
{
if( now - Projectile.LastMoveDelayChange >= PROJECTILE_DELAY_CHANGE_INTERVAL )
{
Projectile.MoveDelay -= PROJECTILE_DELAY_CHANGE;
if( Projectile.MoveDelay < PROJECTILE_DELAY_MIN )
{
Projectile.MoveDelay = PROJECTILE_DELAY_MIN;
}
Projectile.LastMoveDelayChange = now;
}
}
void UpdateProjectile( unsigned long now )
{
if( now - Projectile.LastMove >= Projectile.MoveDelay )
{
LEDState[ Projectile.Position ] = CRGB::Black;
Projectile.Position += Projectile.Direction;
if( Projectile.Position >= LED_COUNT )
{
Projectile.Position = LED_COUNT - 1;
Projectile.Direction = -1;
}
if( Projectile.Position < 0 )
{
Projectile.Position = 0;
Projectile.Direction = 1;
}
if( Projectile.Position >= 1 )
{
LEDState[ Projectile.Position - 1 ] = CRGB::Green;
}
LEDState[ Projectile.Position ] = CRGB::Blue;
UpdateLEDStrip();
Projectile.LastMove = now;
}
}
void Update_Playing_RuleSet1( unsigned long now )
{
UpdateTimers( now );
UpdateProjectile( now );
}
void Update_Playing_RuleSet2( unsigned long now )
{
}
void Update_Playing()
{
unsigned long now = millis();
HandleInput();
switch( GameRules.RuleSet )
{
case GAMERULES_SET1:
Update_Playing_RuleSet1( now );
break;
case GAMERULES_SET2:
Update_Playing_RuleSet2( now );
break;
}
delay( 100 );
}
void setup()
{
Serial.begin( 9600 );
Serial.print( "Setup..." );
SetInitialState();
if( !DISABLE_LEDS )
{
Serial.println( "LED strip is enabled." );
FastLED.addLeds<LED_TYPE, LED_DATA_PIN>( LEDState, LED_COUNT );
}
GameState = GAMESTATE_PLAYING;
delay( 5000 );
}
void loop()
{
switch( GameState )
{
case GAMESTATE_PLAYING:
Update_Playing();
break;
}
}
|
/*
Copyright 2021 University of Manchester
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.
*/
#pragma once
#include <cstdint>
#include "memory_manager_interface.hpp"
namespace orkhestrafs::dbmstodspi {
/**
* @brief Base abstract class which all acceleration modules have to extend to
* be able to access memory mapped registers
*/
class AccelerationModule {
private:
/// Memory manager instance to be able to access the register memory space.
MemoryManagerInterface* memory_manager_;
/// Location of the module on the FPGA.
const int module_position_;
/**
* @brief Calculate where the virtual memory address is memory mapped to.
*
* The result depends on the module position.
* @param module_internal_address Internal virtual address which is desired to
* be accessed.
* @return Global memory mapped address which can be read or written to.
*/
auto CalculateMemoryMappedAddress(int module_internal_address)
-> volatile uint32_t*;
protected:
/**
* @brief Write data to a module configuration register.
* @param module_internal_address Internal address of the register.
* @param write_data Data to be written to the register.
*/
void WriteToModule(int module_internal_address, uint32_t write_data);
/**
* @brief Read data from a module configuration register.
* @param module_internal_address Internal address of the register
* @return Data read from the register.
*/
auto ReadFromModule(int module_internal_address) -> volatile uint32_t;
/**
* @brief Constructor to pass the memory manager instance and the module
* position information.
* @param memory_manager Memory manager instance to access memory mapped
* registers.
* @param module_position Integer showing the position of the module on the
* FPGA.
*/
AccelerationModule(MemoryManagerInterface* memory_manager,
int module_position)
: memory_manager_(memory_manager), module_position_(module_position){};
public:
virtual ~AccelerationModule() = 0;
};
} // namespace orkhestrafs::dbmstodspi
|
/****************************************
Zerus97
*****************************************/
#include <bits/stdc++.h>
#define loop(i,s,e) for(int i = s;i<=e;i++) //including end point
#define pb(a) push_back(a)
#define sqr(x) ((x)*(x))
#define CIN ios_base::sync_with_stdio(0); cin.tie(0);
#define ll long long
#define ull unsigned long long
#define SZ(a) int(a.size())
#define read() freopen("input.txt", "r", stdin)
#define write() freopen("output.txt", "w", stdout)
#define ms(a,b) memset(a, b, sizeof(a))
#define all(v) v.begin(), v.end()
#define PI acos(-1.0)
#define pf printf
#define sfi(a) scanf("%d",&a);
#define sfii(a,b) scanf("%d %d",&a,&b);
#define sfl(a) scanf("%lld",&a);
#define sfll(a,b) scanf("%lld %lld",&a,&b);
#define sful(a) scanf("%llu",&a);
#define sfulul(a,b) scanf("%llu %llu",&a,&b);
#define sful2(a,b) scanf("%llu %llu",&a,&b); // A little different
#define sfc(a) scanf("%c",&a);
#define sfs(a) scanf("%s",a);
#define mp make_pair
#define paii pair<int, int>
#define padd pair<dd, dd>
#define pall pair<ll, ll>
#define vi vector<int>
#define vll vector<ll>
#define mii map<int,int>
#define mlli map<ll,int>
#define mib map<int,bool>
#define fs first
#define sc second
#define CASE(t) printf("Case %d: ",++t) // t initialized 0
#define cCASE(t) cout<<"Case "<<++t<<": ";
#define D(v,status) cout<<status<<" "<<v<<endl;
#define INF 1000000000 //10e9
#define EPS 1e-9
#define flc fflush(stdout); //For interactive programs , flush while using pf (that's why __c )
#define CONTEST 1
using namespace std;
struct fr{
ll mon;
ll ff;
};
bool compi(fr f1 , fr f2)
{
if(f1.mon < f2.mon)
return true;
return false;
}
fr dat[100009];
int main()
{
ll n,d;
sfll(n,d);
loop(i,1,n)
{
ll m,ff;
sfll(m,ff);
fr temp;
temp.ff = ff;
temp.mon = m;
dat[i] = temp;
}
sort(dat+1,dat+n+1,compi);
ll ans = 0;
ll ffsum = dat[1].ff;
int l = 1 , r = 1;
while(r<=n)
{
ll mxmon = dat[r].mon;
ll mnmon = dat[l].mon;
if(mxmon-mnmon<d)
{
ans = max(ans,ffsum);
}
if(mxmon-mnmon>=d && l<r)
{
ffsum-=dat[l].ff;
l++;
}
else
{
r++;
if(r<=n)
{
ffsum+=dat[r].ff;
}
}
}
pf("%lld\n",ans);
return 0;
}
|
#pragma once
#include "ipc_medium.h"
#include "message.h"
#include <queue>
#include <memory>
namespace Petunia {
class IPCInternalMedium;
class IPCMediumNanomsg : public IPCMedium
{
public:
IPCMediumNanomsg(std::string &channel, ConnectionRole connection_role = ConnectionRole::Auto);
~IPCMediumNanomsg();
bool ReceiveMessages(std::queue<std::shared_ptr<Message>> &inbox_queue) override;
bool SendMessages(std::queue<std::shared_ptr<Message>> &outbox_queue) override;
private:
std::shared_ptr<IPCInternalMedium> m_internal_medium;
};
}
|
#pragma once
#include "../../Graphics/Shader/ShaderParameter/ShaderParameterInt.h"
#include "../../UI/Dependencies/IncludeImGui.h"
namespace ae
{
namespace priv
{
namespace ui
{
inline void ShaderParameterIntToEditor( ShaderParameterInt& _ShaderParameterInt )
{
Int32 Value = _ShaderParameterInt.GetValue();
if( ImGui::DragInt( _ShaderParameterInt.GetName().c_str(), &Value, Cast( float, _ShaderParameterInt.GetStep() ), _ShaderParameterInt.GetMin(), _ShaderParameterInt.GetMax() ) )
_ShaderParameterInt.SetValue( Value );
}
} // ui
} // priv
} // ae
|
#include "utils/gid.hpp"
#include <cppunit/extensions/HelperMacros.h>
#include <set>
#include <thread>
using namespace std;
namespace nora {
namespace test {
class gid_test : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(gid_test);
CPPUNIT_TEST(test_mt);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() override;
void test_mt();
};
CPPUNIT_TEST_SUITE_REGISTRATION(gid_test);
void gid_test::setUp() {
gid::instance().set_server_id(0);
}
void gid_test::test_mt() {
int count = 5000;
int thread_count = 10;
vector<thread> ts;
try {
for (int i = 0; i < thread_count; ++i) {
ts.push_back(move(thread([&] {
for (int i = 0; i < count; ++i) {
auto gid = gid::instance().new_gid(gid_type::ROLE);
CPPUNIT_ASSERT(gid_type::ROLE == gid::instance().get_type(gid));
}
for (int i = 0; i < count; ++i) {
auto gid = gid::instance().new_gid(gid_type::ROLE);
CPPUNIT_ASSERT(gid_type::ROLE == gid::instance().get_type(gid));
}
})));
}
} catch (const exception& e) {
for (auto&& i : ts) {
i.join();
}
}
for (auto&& i : ts) {
i.join();
}
}
}
}
|
#include "CharacterClassInfo.h"
|
#include <cstdio>
#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#define INT_MAX 0x7fffffff
#define INT_MIN 0x80000000
using namespace std;
struct TreeLinkNode{
int val;
TreeLinkNode *left, *right, *next;
TreeLinkNode(int x) : val(x) , left(NULL) , right(NULL) ,next(NULL){}
};
TreeLinkNode findNext(TreeLinkNode *n){
}
//Recursive
void connect(TreeLinkNode *root){
if(root == NULL) return;
TreeLinkNode *head = root;
TreeLinkNode *first =NULL;
TreeLinkNode *pre = NULL;
while(head!=NULL){
TreeLinkNode *listHead = head;
while(listHead != NULL){
if(listHead->left != NULL){
if(first == NULL){
first = listHead->left;
pre = first;
}
else{
pre->next = listHead->left;
pre = pre->next;
}
}
if(listHead->right != NULL){
if(first == NULL){
first = listHead->right;
pre = first;
}
else{
pre->next = listHead->right;
pre = pre->next;
}
}
listHead = listHead->next;
}
head = first;
first = NULL;
}
}
int main(){
}
|
//analog inputs will be on Arudino Uno
//variables for measuring voltage
int batMonPin_12 = A4; //input for the voltage divider, needs to be analog, can be changed to other analog input
int batMonPin_24 = A5;
int vatVal = 0; //variable for the A/D value (still figuring out what this does)
float pinVoltage = 0; //variable to hold the calculated voltage
float batteryVoltage = 0;
//variables for measuring the current
int analogInPin_12 = A0; //Analog input pin that the carrier board (Pololu cs01a0J1214) OUT is connected to
int analogInPin_24 = A1;
int sensorValue_12 = 0; //value read from the board
int sensorValue_24 = 0;
int outputValue_12 = 0;
int outputValue_24 = 0; //output in milliamps
unsigned long msec = 0;
float time = 0.0;
int sample = 0;
float totalCharge = 0.0;
float ampSeconds = 0.0;
float ampHours = 0.0;
float wattHours = 0.0;
float amps = 0.0;
int R1 = 11660; //Resistance of R1 in ohms
int R2 = 4620; //Resistance of R2 in ohms
float ratio = 0; //Calculated from R1/R2
void setup() {
// put your setup code here, to run once:
//initialize serial comms
Serial.begin(9600);
//to be added: allow for data transmittion to GUI and text file on onboard comp.
}
void loop() {
// put your main code here, to run repeatedly:
int sampleBVal = 0;
int avgBVal = 0;
int sampleAmpVal = 0;
int avgSAV = 0;
for (int x = 0; x < 10; x++) { // run through loop 10x
// read the analog in value:
sensorValue = analogRead(analogInPin);
sampleAmpVal = sampleAmpVal + sensorValue; // add samples together
batVal = analogRead(batMonPin); // read the voltage on the divider
sampleBVal = sampleBVal + batVal; // add samples together
delay (10); // let ADC settle before next sample
}
avgSAV = sampleAmpVal / 10;
// convert to milli amps
outputValue = (((long)avgSAV * 5000 / 1024) - 500 ) * 1000 / 133;
/* sensor outputs about 100 at rest.
Analog read produces a value of 0-1023, equating to 0v to 5v.
"((long)sensorValue * 5000 / 1024)" is the voltage on the sensor's output in millivolts.
There's a 500mv offset to subtract.
The unit produces 133mv per amp of current, so
divide by 0.133 to convert mv to ma
*/
avgBVal = sampleBVal / 10; //divide by 10 (number of samples) to get a steady reading
pinVoltage = avgBVal * 0.00610; // Calculate the voltage on the A/D pin
/* A reading of 1 for the A/D = 0.0048mV
if we multiply the A/D reading by 0.00488 then
we get the voltage on the pin.
NOTE! .00488 is ideal. I had to adjust
to .00610 to match fluke meter.
Also, depending on wiring and
where voltage is being read, under
heavy loads voltage displayed can be
well under voltage at supply. monitor
at load or supply and decide.
*/
ratio = (float)R1 / (float)R2;
batteryVoltage = pinVoltage * ratio;
amps = (float)outputValue / 1000;
float watts = amps * batteryVoltage;
Serial.print("Volts = " );
Serial.print(batteryVoltage);
Serial.print("\t Current (amps) = ");
Serial.print(amps);
Serial.print("\t Power (Watts) = ");
Serial.print(watts);
sample = sample + 1;
msec = millis();
time = (float) msec / 1000.0;
totalCharge = totalCharge + amps;
averageAmps = totalCharge / sample;
ampSeconds = averageAmps * time;
ampHours = ampSeconds / 3600;
wattHours = batteryVoltage * ampHours;
Serial.print("\t Time (hours) = ");
Serial.print(time / 3600);
Serial.print("\t Amp Hours (ah) = ");
Serial.print(ampHours);
Serial.print("\t Watt Hours (wh) = ");
Serial.println(wattHours);
// wait 10 milliseconds before the next loop
// for the analog-to-digital converter to settle
// after the last reading:
delay(10);
}
|
/**
* @file
* @author Aapo Kyrola <akyrola@cs.cmu.edu>
* @version 1.0
*
* @section LICENSE
*
* Copyright [2012] [Aapo Kyrola, Guy Blelloch, Carlos Guestrin / Carnegie Mellon University]
*
* 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.
*
* @section DESCRIPTION
*
* I/O manager.
*/
#ifndef DEF_STRIPEDIO_HPP
#define DEF_STRIPEDIO_HPP
#include <iostream>
#include <fcntl.h>
#include <unistd.h>
#include <assert.h>
#include <stdint.h>
#include <pthread.h>
#include <errno.h>
//#include <omp.h>
#include <vector>
#include "logger/logger.hpp"
#include "metrics/metrics.hpp"
#include "util/synchronized_queue.hpp"
#include "util/ioutil.hpp"
#include "util/cmdopts.hpp"
namespace graphchi {
static size_t get_filesize(std::string filename);
struct pinned_file;
/**
* Defines a striped file access.
*/
struct io_descriptor {
std::string filename;
std::vector<int> readdescs;
std::vector<int> writedescs;
pinned_file * pinned_to_memory;
int start_mplex;
bool open;
};
enum BLOCK_ACTION { READ, WRITE };
// Very simple ref count system
struct refcountptr {
char * ptr;
volatile int count;
refcountptr(char * ptr, int count) : ptr(ptr), count(count) {}
};
// Forward declaration
class stripedio;
struct iotask {
BLOCK_ACTION action;
int fd;
refcountptr * ptr;
size_t length;
size_t offset;
size_t ptroffset;
bool free_after;
stripedio * iomgr;
iotask() : action(READ), fd(0), ptr(NULL), length(0), offset(0), ptroffset(0), free_after(false), iomgr(NULL) {}
iotask(stripedio * iomgr, BLOCK_ACTION act, int fd, refcountptr * ptr, size_t length, size_t offset, size_t ptroffset, bool free_after=false) :
action(act), fd(fd), ptr(ptr),length(length), offset(offset), ptroffset(ptroffset), free_after(free_after), iomgr(iomgr) {}
};
struct thrinfo {
synchronized_queue<iotask> * readqueue;
synchronized_queue<iotask> * commitqueue;
synchronized_queue<iotask> * prioqueue;
bool running;
metrics * m;
volatile int pending_writes;
volatile int pending_reads;
int mplex;
};
// Forward declaration
static void * io_thread_loop(void * _info);
struct stripe_chunk {
int mplex_thread;
size_t offset;
size_t len;
stripe_chunk(int mplex_thread, size_t offset, size_t len) : mplex_thread(mplex_thread), offset(offset), len(len) {}
};
struct streaming_task {
stripedio * iomgr;
int session;
size_t len;
volatile size_t curpos;
char ** buf;
streaming_task() {}
streaming_task(stripedio * iomgr, int session, size_t len, char ** buf) : iomgr(iomgr), session(session), len(len), curpos(0), buf(buf) {}
};
struct pinned_file {
std::string filename;
size_t length;
uint8_t * data;
bool touched;
};
// Forward declaration
static void * stream_read_loop(void * _info);
class stripedio {
std::vector<io_descriptor *> sessions;
mutex mlock;
int blocksize;
int stripesize;
int multiplex;
std::string multiplex_root;
bool disable_preloading;
std::vector< synchronized_queue<iotask> > mplex_readtasks;
std::vector< synchronized_queue<iotask> > mplex_writetasks;
std::vector< synchronized_queue<iotask> > mplex_priotasks;
std::vector< pthread_t > threads;
std::vector< thrinfo * > thread_infos;
metrics &m;
/* Memory-pinned files */
std::vector<pinned_file *> preloaded_files;
mutex preload_lock;
size_t preloaded_bytes;
size_t max_preload_bytes;
int niothreads; // threads per mplex
public:
stripedio( metrics &_m) : m(_m) {
disable_preloading = false;
blocksize = get_option_int("io.blocksize", 1024 * 1024);
stripesize = get_option_int("io.stripesize", blocksize/2);
preloaded_bytes = 0;
max_preload_bytes = 1024 * 1024 * get_option_long("preload.max_megabytes", 0);
if (max_preload_bytes > 0) {
logstream(LOG_INFO) << "Preloading maximum " << max_preload_bytes << " bytes." << std::endl;
}
multiplex = get_option_int("multiplex", 1);
if (multiplex>1) {
multiplex_root = get_option_string("multiplex_root", "<not-set>");
} else {
multiplex_root = "";
stripesize = 1024*1024*1024;
}
m.set("stripesize", (size_t)stripesize);
// Start threads (niothreads is now threads per multiplex)
niothreads = get_option_int("niothreads", 1);
m.set("niothreads", (size_t)niothreads);
// Each multiplex partition has its own queues
for(int i=0; i<multiplex * niothreads; i++) {
mplex_readtasks.push_back(synchronized_queue<iotask>());
mplex_writetasks.push_back(synchronized_queue<iotask>());
mplex_priotasks.push_back(synchronized_queue<iotask>());
}
int k = 0;
for(int i=0; i < multiplex; i++) {
for(int j=0; j < niothreads; j++) {
thrinfo * cthreadinfo = new thrinfo();
cthreadinfo->commitqueue = &mplex_writetasks[k];
cthreadinfo->readqueue = &mplex_readtasks[k];
cthreadinfo->prioqueue = &mplex_priotasks[k];
cthreadinfo->running = true;
cthreadinfo->pending_writes = 0;
cthreadinfo->pending_reads = 0;
cthreadinfo->mplex = i;
cthreadinfo->m = &m;
thread_infos.push_back(cthreadinfo);
pthread_t iothread;
int ret = pthread_create(&iothread, NULL, io_thread_loop, cthreadinfo);
threads.push_back(iothread);
assert(ret>=0);
k++;
}
}
}
~stripedio() {
int mplex = (int) thread_infos.size();
// Quit all threads
for(int i=0; i<mplex; i++) {
thread_infos[i]->running=false;
}
size_t nthreads = threads.size();
for(unsigned int i=0; i<nthreads; i++) {
pthread_join(threads[i], NULL);
}
for(int i=0; i<mplex; i++) {
delete thread_infos[i];
}
for(int j=0; j<(int)sessions.size(); j++) {
if (sessions[j] != NULL) {
delete sessions[j];
sessions[j] = NULL;
}
}
for(std::vector<pinned_file *>::iterator it=preloaded_files.begin();
it != preloaded_files.end(); ++it) {
pinned_file * preloaded = (*it);
delete preloaded->data;
delete preloaded;
}
}
void set_disable_preloading(bool b) {
disable_preloading = b;
if (b) logstream(LOG_INFO) << "Disabled preloading." << std::endl;
}
bool multiplexed() {
return multiplex>1;
}
void print_session(int session) {
for(int i=0; i<multiplex; i++) {
std::cout << "multiplex: " << multiplex << std::endl;
std::cout << "Read desc: " << sessions[session]->readdescs[i] << std::endl;
}
for(int i=0; i<(int)sessions[session]->writedescs.size(); i++) {
std::cout << "multiplex: " << multiplex << std::endl;
std::cout << "Read desc: " << sessions[session]->writedescs[i] << std::endl;
}
}
// Compute a hash for filename which is used for
// permuting the stripes. It is important the permutation
// is same regardless of when the file is opened.
int hash(std::string filename) {
const char * cstr = filename.c_str();
int hash = 1;
int l = (int) strlen(cstr);
for(int i=0; i<l; i++) {
hash = 31*hash + cstr[i];
}
return std::abs(hash);
}
int open_session(std::string filename, bool readonly=false) {
mlock.lock();
// FIXME: known memory leak: sessions table is never shrunk
int session_id = (int) sessions.size();
io_descriptor * iodesc = new io_descriptor();
iodesc->open = true;
iodesc->pinned_to_memory = is_preloaded(filename);
iodesc->start_mplex = hash(filename) % multiplex;
sessions.push_back(iodesc);
mlock.unlock();
if (NULL != iodesc->pinned_to_memory) {
logstream(LOG_INFO) << "Opened preloaded session: " << filename << std::endl;
return session_id;
}
for(int i=0; i<multiplex; i++) {
std::string fname = multiplexprefix(i) + filename;
for(int j=0; j<niothreads+(multiplex == 1 ? 1 : 0); j++) { // Hack to have one fd for synchronous
int rddesc = open(fname.c_str(), O_RDONLY);
if (rddesc < 0) logstream(LOG_ERROR) << "Could not open: " << fname << " session: " << session_id
<< " error: " << strerror(errno) << std::endl;
assert(rddesc>=0);
iodesc->readdescs.push_back(rddesc);
#ifdef F_NOCACHE
if (!readonly)
fcntl(rddesc, F_NOCACHE, 1);
#endif
if (!readonly) {
int wrdesc = open(fname.c_str(), O_RDWR);
if (wrdesc < 0) logstream(LOG_ERROR) << "Could not open for writing: " << fname << " session: " << session_id
<< " error: " << strerror(errno) << std::endl;
assert(wrdesc>=0);
#ifdef F_NOCACHE
fcntl(wrdesc, F_NOCACHE, 1);
#endif
iodesc->writedescs.push_back(wrdesc);
}
}
}
iodesc->filename = filename;
if (iodesc->writedescs.size() > 0) {
logstream(LOG_INFO) << "Opened write-session: " << session_id << "(" << iodesc->writedescs[0] << ") for " << filename << std::endl;
} else {
logstream(LOG_INFO) << "Opened read-session: " << session_id << "(" << iodesc->readdescs[0] << ") for " << filename << std::endl;
}
return session_id;
}
void close_session(int session) {
mlock.lock();
// Note: currently io-descriptors are left into the vertex array
// in purpose to make managed memory work. Should be fixed as this is
// a (relatively minor) memory leak.
bool wasopen;
io_descriptor * iodesc = sessions[session];
wasopen = iodesc->open;
iodesc->open = false;
mlock.unlock();
if (wasopen) {
for(std::vector<int>::iterator it=iodesc->readdescs.begin(); it!=iodesc->readdescs.end(); ++it) {
close(*it);
}
for(std::vector<int>::iterator it=iodesc->writedescs.begin(); it!=iodesc->writedescs.end(); ++it) {
close(*it);
}
}
}
int mplex_for_offset(int session, size_t off) {
return ((int) (off / stripesize) + sessions[session]->start_mplex) % multiplex;
}
// Returns vector of <mplex, offset>
std::vector< stripe_chunk > stripe_offsets(int session, size_t nbytes, size_t off) {
size_t end = off+nbytes;
size_t idx = off;
size_t bufoff = 0;
std::vector<stripe_chunk> stripelist;
while(idx<end) {
size_t blockoff = idx%stripesize;
size_t blocklen = std::min(stripesize-blockoff, end-idx);
int mplex_thread = (int) mplex_for_offset(session, idx) * niothreads + (int) (random() % niothreads);
stripelist.push_back(stripe_chunk(mplex_thread, bufoff, blocklen));
bufoff += blocklen;
idx += blocklen;
}
return stripelist;
}
template <typename T>
void preada_async(int session, T * tbuf, size_t nbytes, size_t off) {
std::vector<stripe_chunk> stripelist = stripe_offsets(session, nbytes, off);
refcountptr * refptr = new refcountptr((char*)tbuf, (int)stripelist.size());
for(int i=0; i<(int)stripelist.size(); i++) {
stripe_chunk chunk = stripelist[i];
__sync_add_and_fetch(&thread_infos[chunk.mplex_thread]->pending_reads, 1);
mplex_readtasks[chunk.mplex_thread].push(iotask(this, READ, sessions[session]->readdescs[chunk.mplex_thread],
refptr, chunk.len, chunk.offset+off, chunk.offset));
}
}
/* Used for pipelined read */
void launch_stream_reader(streaming_task * task) {
pthread_t t;
int ret = pthread_create(&t, NULL, stream_read_loop, (void*)task);
assert(ret>=0);
}
/**
* Pinned sessions process files that are permanently
* pinned to memory.
*/
bool pinned_session(int session) {
return sessions[session]->pinned_to_memory;
}
/**
* Call to allow files to be preloaded. Note: using this requires
* that all files are accessed with same path. This is true if
* standard chifilenames.hpp -given filenames are used.
*/
void allow_preloading(std::string filename) {
if (disable_preloading) {
return;
}
preload_lock.lock();
size_t filesize = get_filesize(filename);
if (preloaded_bytes + filesize <= max_preload_bytes) {
preloaded_bytes += filesize;
m.set("preload_bytes", preloaded_bytes);
pinned_file * pfile = new pinned_file();
pfile->filename = filename;
pfile->length = filesize;
pfile->data = (uint8_t*) malloc(filesize);
pfile->touched = false;
assert(pfile->data != NULL);
int fid = open(filename.c_str(), O_RDONLY);
if (fid < 0) {
logstream(LOG_ERROR) << "Could not read file: " << filename
<< " error: " << strerror(errno) << std::endl;
}
assert(fid >= 0);
/* Preload the file */
logstream(LOG_INFO) << "Preloading: " << filename << std::endl;
preada(fid, pfile->data, filesize, 0);
close(fid);
preloaded_files.push_back(pfile);
}
preload_lock.unlock();
}
void commit_preloaded() {
for(std::vector<pinned_file *>::iterator it=preloaded_files.begin();
it != preloaded_files.end(); ++it) {
pinned_file * preloaded = (*it);
if (preloaded->touched) {
logstream(LOG_INFO) << "Commit preloaded file: " << preloaded->filename << std::endl;
int fid = open(preloaded->filename.c_str(), O_WRONLY);
if (fid < 0) {
logstream(LOG_ERROR) << "Could not read file: " << preloaded->filename
<< " error: " << strerror(errno) << std::endl;
continue;
}
pwritea(fid, preloaded->data, preloaded->length, 0);
close(fid);
}
preloaded->touched = false;
}
}
pinned_file * is_preloaded(std::string filename) {
preload_lock.lock();
pinned_file * preloaded = NULL;
for(std::vector<pinned_file *>::iterator it=preloaded_files.begin();
it != preloaded_files.end(); ++it) {
if (filename == (*it)->filename) {
preloaded = *it;
break;
}
}
preload_lock.unlock();
return preloaded;
}
// Note: data is freed after write!
template <typename T>
void pwritea_async(int session, T * tbuf, size_t nbytes, size_t off, bool free_after) {
std::vector<stripe_chunk> stripelist = stripe_offsets(session, nbytes, off);
refcountptr * refptr = new refcountptr((char*)tbuf, (int) stripelist.size());
for(int i=0; i<(int)stripelist.size(); i++) {
stripe_chunk chunk = stripelist[i];
__sync_add_and_fetch(&thread_infos[chunk.mplex_thread]->pending_writes, 1);
mplex_writetasks[chunk.mplex_thread].push(iotask(this, WRITE, sessions[session]->writedescs[chunk.mplex_thread],
refptr, chunk.len, chunk.offset+off, chunk.offset, free_after));
}
}
template <typename T>
void preada_now(int session, T * tbuf, size_t nbytes, size_t off) {
metrics_entry me = m.start_time();
if (multiplex > 1) {
std::vector<stripe_chunk> stripelist = stripe_offsets(session, nbytes, off);
size_t checklen=0;
refcountptr * refptr = new refcountptr((char*)tbuf, (int) stripelist.size());
refptr->count++; // Take a reference so we can spin on it
for(int i=0; i < (int)stripelist.size(); i++) {
stripe_chunk chunk = stripelist[i];
__sync_add_and_fetch(&thread_infos[chunk.mplex_thread]->pending_reads, 1);
// Use prioritized task queue
mplex_priotasks[chunk.mplex_thread].push(iotask(this, READ, sessions[session]->readdescs[chunk.mplex_thread],
refptr, chunk.len, chunk.offset+off, chunk.offset));
checklen += chunk.len;
}
assert(checklen == nbytes);
// Spin
while(refptr->count>1) {
usleep(5000);
}
delete refptr;
} else {
preada(sessions[session]->readdescs[threads.size()], tbuf, nbytes, off);
}
m.stop_time(me, "preada_now", false);
}
template <typename T>
void pwritea_now(int session, T * tbuf, size_t nbytes, size_t off) {
metrics_entry me = m.start_time();
std::vector<stripe_chunk> stripelist = stripe_offsets(session, nbytes, off);
size_t checklen=0;
for(int i=0; i<(int)stripelist.size(); i++) {
stripe_chunk chunk = stripelist[i];
pwritea(sessions[session]->writedescs[chunk.mplex_thread], (char*)tbuf+chunk.offset, chunk.len, chunk.offset+off);
checklen += chunk.len;
}
assert(checklen == nbytes);
m.stop_time(me, "pwritea_now", false);
}
/**
* Memory managed versino of the I/O functions.
*/
template <typename T>
void managed_pwritea_async(int session, T ** tbuf, size_t nbytes, size_t off, bool free_after) {
if (!pinned_session(session)) {
pwritea_async(session, *tbuf, nbytes, off, free_after);
} else {
// Do nothing but mark the descriptor as 'dirty'
sessions[session]->pinned_to_memory->touched = true;
}
}
template <typename T>
void managed_preada_now(int session, T ** tbuf, size_t nbytes, size_t off) {
if (!pinned_session(session)) {
preada_now(session, *tbuf, nbytes, off);
} else {
io_descriptor * iodesc = sessions[session];
*tbuf = (T*) (iodesc->pinned_to_memory->data + off);
}
}
template <typename T>
void managed_pwritea_now(int session, T ** tbuf, size_t nbytes, size_t off) {
if (!pinned_session(session)) {
pwritea_now(session, *tbuf, nbytes, off);
} else {
// Do nothing but mark the descriptor as 'dirty'
sessions[session]->pinned_to_memory->touched = true;
}
}
template<typename T>
void managed_malloc(int session, T ** tbuf, size_t nbytes, size_t noff) {
if (!pinned_session(session)) {
*tbuf = (T*) malloc(nbytes);
} else {
io_descriptor * iodesc = sessions[session];
*tbuf = (T*) (iodesc->pinned_to_memory->data + noff);
}
}
template <typename T>
void managed_preada_async(int session, T ** tbuf, size_t nbytes, size_t off) {
if (!pinned_session(session)) {
preada_async(session, *tbuf, nbytes, off);
} else {
io_descriptor * iodesc = sessions[session];
*tbuf = (T*) (iodesc->pinned_to_memory->data + off);
}
}
template <typename T>
void managed_release(int session, T ** ptr) {
if (!pinned_session(session)) {
assert(*ptr != NULL);
free(*ptr);
}
*ptr = NULL;
}
void truncate(int session, size_t nbytes) {
assert(!pinned_session(session));
assert(multiplex <= 1); // We do not support truncating on multiplex yet
int stat = ftruncate(sessions[session]->writedescs[0], nbytes);
if (stat != 0) {
logstream(LOG_ERROR) << "Could not truncate " << sessions[session]->filename <<
" error: " << strerror(errno) << std::endl;
assert(false);
}
}
void wait_for_reads() {
metrics_entry me = m.start_time();
int loops = 0;
int mplex = (int) thread_infos.size();
for(int i=0; i<mplex; i++) {
while(thread_infos[i]->pending_reads > 0) {
usleep(10000);
loops++;
}
}
m.stop_time(me, "stripedio_wait_for_reads", false);
}
void wait_for_writes() {
metrics_entry me = m.start_time();
int mplex = (int) thread_infos.size();
for(int i=0; i<mplex; i++) {
while(thread_infos[i]->pending_writes>0) {
usleep(10000);
}
}
m.stop_time(me, "stripedio_wait_for_writes", false);
}
std::string multiplexprefix(int stripe) {
if (multiplex > 1) {
char mstr[255];
sprintf(mstr, "%d/", 1+stripe%multiplex);
return multiplex_root + std::string(mstr);
} else return "";
}
std::string multiplexprefix_random() {
return multiplexprefix((int)random() % multiplex);
}
};
static void * io_thread_loop(void * _info) {
iotask task;
thrinfo * info = (thrinfo*)_info;
logstream(LOG_INFO) << "Thread for multiplex :" << info->mplex << " starting." << std::endl;
while(info->running) {
bool success;
if (info->pending_reads>0) { // Prioritize read queue
success = info->prioqueue->safepop(&task);
if (!success) {
success = info->readqueue->safepop(&task);
}
} else {
success = info->commitqueue->safepop(&task);
}
if (success) {
if (task.action == WRITE) { // Write
metrics_entry me = info->m->start_time();
pwritea(task.fd, task.ptr->ptr + task.ptroffset, task.length, task.offset);
if (task.free_after) {
// Threead-safe method of memory managment - ugly!
if (__sync_sub_and_fetch(&task.ptr->count, 1) == 0) {
free(task.ptr->ptr);
free(task.ptr);
}
}
__sync_sub_and_fetch(&info->pending_writes, 1);
info->m->stop_time(me, "commit_thr");
} else {
preada(task.fd, task.ptr->ptr+task.ptroffset, task.length, task.offset);
__sync_sub_and_fetch(&info->pending_reads, 1);
if (__sync_sub_and_fetch(&task.ptr->count, 1) == 0) {
free(task.ptr);
}
}
} else {
usleep(50000); // 50 ms
}
}
return NULL;
}
static void * stream_read_loop(void * _info) {
streaming_task * task = (streaming_task*)_info;
timeval start, end;
gettimeofday(&start, NULL);
size_t bufsize = 32*1024*1024; // 32 megs
char * tbuf;
/**
* If this is not pinned, we just malloc the
* buffer. Otherwise - shuold just return pointer
* to the in-memory file buffer.
*/
if (task->iomgr->pinned_session(task->session)) {
__sync_add_and_fetch(&task->curpos, task->len);
return NULL;
}
tbuf = *task->buf;
while(task->curpos < task->len) {
size_t toread = std::min((size_t)task->len - (size_t)task->curpos, (size_t)bufsize);
task->iomgr->preada_now(task->session, tbuf + task->curpos, toread, task->curpos);
__sync_add_and_fetch(&task->curpos, toread);
}
gettimeofday(&end, NULL);
return NULL;
}
static size_t get_filesize(std::string filename) {
std::string fname = filename;
int f = open(fname.c_str(), O_RDONLY);
if (f < 0) {
logstream(LOG_ERROR) << "Could not open file " << filename << " error: " << strerror(errno) << std::endl;
assert(false);
}
off_t sz = lseek(f, 0, SEEK_END);
close(f);
return sz;
}
}
#endif
|
#include<bits/stdc++.h>
using namespace std;
#define MAX 110005
typedef pair<long long int,long long int>pa;
#define pb push_back
long long int INF=1e17;
vector<pa>adj[MAX]; // Graph
vector<pa>adjr[MAX]; // Reversed Graph
long long int v_for[MAX]; //virtual function for forward/main Graph
long long int v_back[MAX]; //virtual function for Backward Graph
long long int src,dest,n,m;
pa location[MAX]; //coordinates of each node
set<long long int>worksetD; //consists of nodes to be re-initialised
long long int f_dist[MAX]; //distance array from source for forward iterations
long long int r_dist[MAX]; //distance array from dest for backward iterations
bool f_vis[MAX]; //visited array for forward steps
bool r_vis[MAX]; //visited array for backward steps
//For faster input and output
void fastio()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
}
//computing virtual function for forward iteration
void computing_forward_virtual_function()
{
for(int i=1;i<=n;i++)
{
v_for[i]=(((location[dest].first-location[i].first))*((location[dest].first-location[i].first)))+
(((location[dest].second-location[i].second))*((location[dest].second-location[i].second)));
v_for[i]=sqrt(v_for[i]);
}
}
//computing backward virtual function for backward iterations
void computing_backward_virtual_function()
{
for(int i=1;i<=n;i++)
{
v_back[i]=(((location[src].first-location[i].first))*((location[src].first-location[i].first)))+
(((location[src].second-location[i].second))*((location[src].second-location[i].second)));
v_back[i]=sqrt(v_back[i]);
}
}
//final virtual function
void computing_average_virtual_function()
{
for(int i=1;i<=n;i++)
{
long long int x=v_back[i]-v_for[i];
x=(x)>>1;
v_for[i]=-x;
v_back[i]=x;
}
}
//bidirectional Astar for faster output
long long int Astar()
{
computing_forward_virtual_function();
computing_backward_virtual_function();
computing_average_virtual_function();
priority_queue<pa,vector<pa>,greater<pa>>f_pq; //priority queue for forward/original graph
priority_queue<pa,vector<pa>,greater<pa>>r_pq; //priority queue for reversed graph
//updating values changed during last query
for(auto k:worksetD)
{
f_dist[k]=INF;
r_dist[k]=INF;
f_vis[k]=false;
r_vis[k]=false;
}
worksetD.clear();
long long int estimate=INF;
f_pq.push({0,src});
r_pq.push({0,dest});
f_dist[src]=0;
f_vis[src]=true;
r_vis[dest]=true;
r_dist[dest]=0;
worksetD.insert(src);
worksetD.insert(dest);
// A star with alternate forward and backward step
while(!f_pq.empty() || !r_pq.empty())
{ //forward_iteration
if(!f_pq.empty())
{
long long int wt=f_pq.top().first;
long long int v=f_pq.top().second;
f_vis[v]=true;
f_pq.pop();
for (auto jj:adj[v])
{
long long int u=jj.second;
long long int edge_wt=jj.first+v_for[u]-v_for[v];
if(!f_vis[u] && f_dist[v]+edge_wt<f_dist[u])
{
worksetD.insert(u);
f_dist[u]=f_dist[v]+edge_wt;
f_pq.push({f_dist[v]+edge_wt,u});
}
}
if(r_vis[v])
break;
}
//backward_iteration
if(!r_pq.empty())
{
long long int wt=r_pq.top().first;
long long int v=r_pq.top().second;
r_pq.pop();
r_vis[v]=true;
for (auto jj:adjr[v])
{
long long int u=jj.second;
long long int edge_wt=jj.first+v_back[u]-v_back[v];
if(!r_vis[u] && r_dist[v]+edge_wt<r_dist[u])
{
worksetD.insert(u);
r_dist[u]=r_dist[v]+edge_wt;
r_pq.push({r_dist[v]+edge_wt,u});
}
}
if(f_vis[v])
break;
}
}
for(int i=1;i<=n;i++)
{
if(f_vis[i] && r_vis[i])
estimate=min(estimate,f_dist[i]+r_dist[i]+v_for[src]-v_for[i]+v_back[dest]-v_back[i]);
for(auto jj:adj[i])
{
if(f_vis[i] && r_vis[jj.second])
estimate=min(f_dist[i]+r_dist[jj.second]+jj.first+v_for[src]-v_for[i]+v_back[dest]-v_back[jj.second],estimate);
}
}
return estimate;
}
int main()
{
fastio();
long long int x,y,wt;
cin>>n>>m;
for(int i=1;i<=n;i++)
{
cin>>x>>y;
worksetD.insert(i);
location[i]={x,y};
}
for(int i=0;i<m;i++)
{
cin>>x>>y>>wt;
adj[x].pb({wt,y}); //adding edge to the graph
adjr[y].pb({wt,x}); //adding edge to the reversed Graph
}
long long int num_of_queries;
cin>>num_of_queries;
while(num_of_queries--)
{
cin>>src>>dest;
if(src==dest)
{
cout<<0<<"\n";
continue;
}
long long int ans=Astar();
if(ans>=INF)
{
cout<<-1<<"\n";
}
else
cout<<ans<<"\n";
}
}
|
#include <chuffed/core/engine.h>
#include <chuffed/core/options.h>
#include <chuffed/core/propagator.h>
#include <chuffed/core/sat.h>
#include <chuffed/mip/mip.h>
#include <algorithm>
#include <cassert>
#include <cstdio>
#include <fstream>
#include <iostream>
#include <sstream>
#define PRINT_ANALYSIS 0
SAT sat;
std::map<int, std::string> litString;
std::map<int, string> learntClauseString;
std::ofstream learntStatsStream;
cassert(sizeof(Lit) == 4);
cassert(sizeof(Clause) == 4);
cassert(sizeof(WatchElem) == 8);
cassert(sizeof(Reason) == 8);
//---------
// inline methods
inline void SAT::insertVarOrder(int x) {
if (!order_heap.inHeap(x) && flags[x].decidable) {
order_heap.insert(x);
}
}
inline void SAT::setConfl(Lit p, Lit q) {
(*short_confl)[0] = p;
(*short_confl)[1] = q;
confl = short_confl;
}
inline void SAT::untrailToPos(vec<Lit>& t, int p) {
int dl = decisionLevel();
for (int i = t.size(); i-- > p;) {
int x = var(t[i]);
assigns[x] = toInt(l_Undef);
#if PHASE_SAVING
if (so.phase_saving >= 1 || (so.phase_saving == 1 && dl >= l0)) polarity[x] = sign(t[i]);
#endif
insertVarOrder(x);
}
t.resize(p);
}
//---------
// main methods
SAT::SAT()
: lit_sort(trailpos),
pushback_time(duration::zero()),
trail(1),
qhead(1, 0),
rtrail(1),
confl(nullptr),
var_inc(1),
cla_inc(1),
order_heap(VarOrderLt(activity)),
bin_clauses(0),
tern_clauses(0),
long_clauses(0),
learnt_clauses(0),
propagations(0),
back_jumps(0),
nrestarts(0),
next_simp_db(100000),
clauses_literals(0),
learnts_literals(0),
max_literals(0),
tot_literals(0),
avg_depth(100),
confl_rate(1000),
ll_time(chuffed_clock::now()),
ll_inc(1),
learnt_len_el(10),
learnt_len_occ(MAX_SHARE_LEN, learnt_len_el * 1000 / MAX_SHARE_LEN) {
newVar();
enqueue(Lit(0, true));
newVar();
enqueue(Lit(1, false));
temp_sc = (SClause*)malloc(TEMP_SC_LEN * sizeof(int));
short_expl = (Clause*)malloc(sizeof(Clause) + 3 * sizeof(Lit));
short_confl = (Clause*)malloc(sizeof(Clause) + 2 * sizeof(Lit));
short_expl->clearFlags();
short_confl->clearFlags();
short_confl->sz = 2;
}
SAT::~SAT() {
for (int i = 0; i < clauses.size(); i++) {
free(clauses[i]);
}
for (int i = 0; i < learnts.size(); i++) {
free(learnts[i]);
}
}
void SAT::init() {
orig_cutoff = nVars();
ivseen.growTo(engine.vars.size(), false);
}
int SAT::newVar(int n, ChannelInfo ci) {
int s = assigns.size();
watches.growBy(n);
watches.growBy(n);
assigns.growBy(n, toInt(l_Undef));
reason.growBy(n, nullptr);
trailpos.growBy(n, -1);
seen.growBy(n, 0);
activity.growBy(n, 0);
polarity.growBy(n, true);
flags.growBy(n, 7);
for (int i = 0; i < n; i++) {
c_info.push(ci);
ci.val++;
insertVarOrder(s + i);
}
return s;
}
int SAT::getLazyVar(ChannelInfo ci) {
int v;
if (var_free_list.size() != 0) {
v = var_free_list.last();
var_free_list.pop();
fprintf(stderr, "reuse %d\n", v);
assert(assigns[v] == toInt(l_Undef));
assert(watches[2 * v].size() == 0);
assert(watches[2 * v + 1].size() == 0);
assert(num_used[v] == 0);
c_info[v] = ci;
activity[v] = 0;
polarity[v] = true;
flags[v] = 7;
} else {
v = newVar(1, ci);
num_used.push(0);
}
// flags[v].setDecidable(false);
return v;
}
void SAT::removeLazyVar(int v) {
return;
ChannelInfo& ci = c_info[v];
assert(assigns[v] == toInt(l_Undef));
assert(watches[2 * v].size() == 0);
assert(watches[2 * v + 1].size() == 0);
fprintf(stderr, "free %d\n", v);
var_free_list.push(v);
if (ci.cons_type == 1) {
((IntVarLL*)engine.vars[ci.cons_id])->freeLazyVar(ci.val);
} else if (ci.cons_type == 2) {
engine.propagators[ci.cons_id]->freeLazyVar(ci.val);
} else {
NEVER;
}
}
void SAT::addClause(Lit p, Lit q) {
if (value(p) == l_True || value(q) == l_True) {
return;
}
if (value(p) == l_False && value(q) == l_False) {
assert(false);
TL_FAIL();
}
if (value(p) == l_False) {
assert(decisionLevel() == 0);
enqueue(q);
return;
}
if (value(q) == l_False) {
assert(decisionLevel() == 0);
enqueue(p);
return;
}
bin_clauses++;
watches[toInt(~p)].push(q);
watches[toInt(~q)].push(p);
}
void SAT::addClause(vec<Lit>& ps, bool one_watch) {
int i;
int j;
for (i = j = 0; i < ps.size(); i++) {
if (value(ps[i]) == l_True) {
return;
}
if (value(ps[i]) == l_Undef) {
ps[j++] = ps[i];
}
}
ps.resize(j);
if (ps.size() == 0) {
assert(false);
TL_FAIL();
}
addClause(*Clause_new(ps), one_watch);
}
void SAT::addClause(Clause& c, bool one_watch) {
assert(c.size() > 0);
if (c.size() == 1) {
assert(decisionLevel() == 0);
if (DEBUG) {
fprintf(stderr, "warning: adding length 1 clause!\n");
}
if (value(c[0]) == l_False) {
TL_FAIL();
}
if (value(c[0]) == l_Undef) {
enqueue(c[0]);
}
free(&c);
return;
}
if (!c.learnt) {
if (c.size() == 2) {
bin_clauses++;
} else if (c.size() == 3) {
tern_clauses++;
} else {
long_clauses++;
}
}
// Mark lazy lits which are used
if (c.learnt) {
for (int i = 0; i < c.size(); i++) {
incVarUse(var(c[i]));
}
}
if (c.size() == 2 && ((!c.learnt) || (so.bin_clause_opt))) {
if (!one_watch) {
watches[toInt(~c[0])].push(c[1]);
}
watches[toInt(~c[1])].push(c[0]);
if (!c.learnt) {
free(&c);
}
return;
}
if (!one_watch) {
watches[toInt(~c[0])].push(&c);
}
watches[toInt(~c[1])].push(&c);
if (c.learnt) {
learnts_literals += c.size();
} else {
clauses_literals += c.size();
}
if (c.learnt) {
learnts.push(&c);
if (so.learnt_stats) {
std::set<int> levels;
for (int i = 0; i < c.size(); i++) {
levels.insert(out_learnt_level[i]);
}
std::stringstream s;
// s << "learntclause,";
s << c.clauseID() << "," << c.size() << "," << levels.size();
if (so.learnt_stats_nogood) {
s << ",";
for (int i = 0; i < c.size(); i++) {
s << (i == 0 ? "" : " ") << getLitString(toInt(c[i]));
// s << " (" << out_learnt_level[i] << ")";
}
}
// std::cerr << "\n";
learntClauseString[c.clauseID()] = s.str();
}
} else {
clauses.push(&c);
}
}
void SAT::removeClause(Clause& c) {
assert(c.size() > 1);
watches[toInt(~c[0])].remove(&c);
watches[toInt(~c[1])].remove(&c);
if (c.learnt) {
learnts_literals -= c.size();
} else {
clauses_literals -= c.size();
}
if (c.learnt) {
for (int i = 0; i < c.size(); i++) {
decVarUse(var(c[i]));
}
}
if (c.learnt) {
// learntClauseScore[c.clauseID()] = c.rawActivity();
/* if (so.debug) { */
if (so.learnt_stats) {
int id = c.clauseID();
learntStatsStream << learntClauseString[id];
learntStatsStream << ",";
learntStatsStream << c.rawActivity();
learntStatsStream << "\n";
/* std::cerr << "clausescore," << << "," << c.rawActivity() << "\n"; */
}
/* } */
}
free(&c);
}
void SAT::topLevelCleanUp() {
assert(decisionLevel() == 0);
for (int i = rtrail[0].size(); i-- > 0;) {
free(rtrail[0][i]);
}
rtrail[0].clear();
if (so.sat_simplify && propagations >= next_simp_db) {
simplifyDB();
}
for (int i = 0; i < trail[0].size(); i++) {
if (so.debug) {
std::cerr << "setting true at top-level: " << getLitString(toInt(trail[0][i])) << "\n";
}
seen[var(trail[0][i])] = 1;
trailpos[var(trail[0][i])] = -1;
}
trail[0].clear();
qhead[0] = 0;
}
void SAT::simplifyDB() {
int i;
int j;
for (i = j = 0; i < learnts.size(); i++) {
if (simplify(*learnts[i])) {
removeClause(*learnts[i]);
} else {
learnts[j++] = learnts[i];
}
}
learnts.resize(j);
next_simp_db = propagations + clauses_literals + learnts_literals;
}
bool SAT::simplify(Clause& c) const {
if (value(c[0]) == l_True) {
return true;
}
if (value(c[1]) == l_True) {
return true;
}
int i;
int j;
for (i = j = 2; i < c.size(); i++) {
if (value(c[i]) == l_True) {
return true;
}
if (value(c[i]) == l_Undef) {
c[j++] = c[i];
}
}
c.resize(j);
return false;
}
string showReason(Reason r) {
std::stringstream ss;
switch (r.d.type) {
case 0:
if (r.pt == nullptr) {
ss << "no reason";
} else {
Clause& c = *r.pt;
ss << "clause";
for (int i = 0; i < c.size(); i++) {
ss << " " << getLitString(toInt(~c[i]));
}
}
break;
case 1:
ss << "absorbed binary clause?";
break;
case 2:
ss << "single literal " << getLitString(toInt(~toLit(r.d.d1)));
break;
case 3:
ss << "two literals " << getLitString(toInt(~toLit((r.d.d1)))) << " & "
<< getLitString(toInt(~toLit((r.d.d2))));
break;
}
return ss.str();
}
// Use cases:
// enqueue from decision , value(p) = u , r = NULL , channel
// enqueue from analyze , value(p) = u , r != NULL, channel
// enqueue from unit prop , value(p) = u , r != NULL, channel
void SAT::enqueue(Lit p, Reason r) {
/* if (so.debug) { */
/* std::cerr << "enqueue literal " << getLitString(toInt(p)) << " because " << showReason(r) <<
* "\n"; */
/* } */
assert(value(p) == l_Undef);
int v = var(p);
assigns[v] = toInt(lbool(!sign(p)));
trailpos[v] = engine.trailPos();
reason[v] = r;
trail.last().push(p);
ChannelInfo& ci = c_info[v];
if (ci.cons_type == 1) {
engine.vars[ci.cons_id]->channel(ci.val, static_cast<LitRel>(ci.val_type),
static_cast<int>(sign(p)));
}
}
// enqueue from FD variable, value(p) = u/f, r = ?, don't channel
void SAT::cEnqueue(Lit p, Reason r) {
/* if (so.debug) { */
/* std::cerr << "c-enqueue literal " << getLitString(toInt(p)) << " because " << showReason(r)
* << "\n"; */
/* } */
assert(value(p) != l_True);
int v = var(p);
if (value(p) == l_False) {
if (so.lazy) {
if (r == nullptr) {
assert(decisionLevel() == 0);
setConfl();
} else {
confl = getConfl(r, p);
(*confl)[0] = p;
}
} else {
setConfl();
}
return;
}
assigns[v] = toInt(lbool(!sign(p)));
trailpos[v] = engine.trailPos();
reason[v] = r;
trail.last().push(p);
}
void SAT::aEnqueue(Lit p, Reason r, int l) {
if (so.debug) {
std::cerr << "a-enqueue literal " << getLitString(toInt(p)) << " because " << showReason(r)
<< " and l=" << l << "\n";
}
assert(value(p) == l_Undef);
int v = var(p);
assigns[v] = toInt(lbool(!sign(p)));
trailpos[v] = engine.trail_lim[l] - 1;
reason[v] = r;
trail[l].push(p);
}
void SAT::btToLevel(int level) {
#if DEBUG_VERBOSE
std::cerr << "SAT::btToLevel( " << level << ")\n";
#endif
if (decisionLevel() <= level) {
return;
}
for (int l = trail.size(); l-- > level + 1;) {
untrailToPos(trail[l], 0);
for (int i = rtrail[l].size(); (i--) != 0;) {
free(rtrail[l][i]);
}
}
trail.resize(level + 1);
qhead.resize(level + 1);
rtrail.resize(level + 1);
engine.btToLevel(level);
if (so.mip) {
mip->btToLevel(level);
}
}
void SAT::btToPos(int sat_pos, int core_pos) {
untrailToPos(trail.last(), sat_pos);
engine.btToPos(core_pos);
}
// Propagator methods:
bool SAT::propagate() {
int num_props = 0;
int& qhead = this->qhead.last();
vec<Lit>& trail = this->trail.last();
while (qhead < trail.size()) {
num_props++;
Lit p = trail[qhead++]; // 'p' is enqueued fact to propagate.
vec<WatchElem>& ws = watches[toInt(p)];
if (ws.size() == 0) {
continue;
}
WatchElem* i;
WatchElem* j;
WatchElem* end;
for (i = j = ws, end = i + ws.size(); i != end;) {
WatchElem& we = *i;
switch (we.d.type) {
case 1: {
// absorbed binary clause
*j++ = *i++;
Lit q = toLit(we.d.d2);
switch (toInt(value(q))) {
case 0:
enqueue(q, ~p);
break;
case -1:
setConfl(q, ~p);
qhead = trail.size();
while (i < end) {
*j++ = *i++;
}
break;
default:;
}
continue;
}
case 2: {
// wake up FD propagator
*j++ = *i++;
engine.propagators[we.d.d2]->wakeup(we.d.d1, 0);
continue;
}
default:
Clause& c = *we.pt;
i++;
// Check if already satisfied
if (value(c[0]) == l_True || value(c[1]) == l_True) {
*j++ = &c;
continue;
}
Lit false_lit = ~p;
// Make sure the false literal is data[1]:
if (c[0] == false_lit) {
c[0] = c[1], c[1] = false_lit;
}
// Look for new watch:
for (int k = 2; k < c.size(); k++) {
if (value(c[k]) != l_False) {
c[1] = c[k];
c[k] = false_lit;
watches[toInt(~c[1])].push(&c);
goto FoundWatch;
}
}
// Did not find watch -- clause is unit under assignment:
*j++ = &c;
if (value(c[0]) == l_False) {
confl = &c;
qhead = trail.size();
while (i < end) {
*j++ = *i++;
}
} else {
enqueue(c[0], &c);
}
FoundWatch:;
}
}
ws.shrink(i - j);
}
propagations += num_props;
return (confl == nullptr);
}
struct activity_lt {
bool operator()(Clause* x, Clause* y) { return x->activity() < y->activity(); }
};
void SAT::reduceDB() {
int i;
int j;
std::sort((Clause**)learnts, (Clause**)learnts + learnts.size(), activity_lt());
for (i = j = 0; i < learnts.size() / 2; i++) {
if (!locked(*learnts[i])) {
removeClause(*learnts[i]);
} else {
learnts[j++] = learnts[i];
}
}
for (; i < learnts.size(); i++) {
learnts[j++] = learnts[i];
}
learnts.resize(j);
if (so.verbosity >= 1) {
printf("%% Pruned %d learnt clauses\n", i - j);
}
}
std::string showClause(Clause& c) {
std::stringstream ss;
for (int i = 0; i < c.size(); i++) {
ss << " " << getLitString(toInt(c[i]));
}
return ss.str();
}
struct raw_activity_gt {
bool operator()(Clause* x, Clause* y) { return x->rawActivity() > y->rawActivity(); }
};
// This is wrong, because probably most of the clauses have been
// removed by the time we do this.
void SAT::printLearntStats() {
/* std::ofstream clausefile("clause-info.csv"); */
/* for (int i = 0 ; i < learnts.size() ; i++) { */
/* clausefile << learnts[i]->clauseID() << "," << learnts[i]->rawActivity() << "," <<
* showClause(*learnts[i]) << "\n"; */
/* } */
std::sort((Clause**)learnts, (Clause**)learnts + learnts.size(), raw_activity_gt());
std::cerr << "top ten clauses:\n";
for (int i = 0; i < 10 && i < learnts.size(); i++) {
std::cerr << i << ": " << learnts[i]->rawActivity() << " " << showClause(*learnts[i]) << "\n";
}
}
void SAT::printStats() const {
printf("%%%%%%mzn-stat: binClauses=%d\n", bin_clauses);
printf("%%%%%%mzn-stat: ternClauses=%d\n", tern_clauses);
printf("%%%%%%mzn-stat: longClauses=%d\n", long_clauses);
printf("%%%%%%mzn-stat: avgLongClauseLen=%.2f\n",
long_clauses != 0
? (double)(clauses_literals - static_cast<long long>(3 * tern_clauses)) / long_clauses
: 0);
printf("%%%%%%mzn-stat: learntClauses=%d\n", learnts.size());
printf("%%%%%%mzn-stat: avgLearntClauseLen=%.2f\n",
learnts.size() != 0 ? (double)learnts_literals / learnts.size() : 0);
printf("%%%%%%mzn-stat: satPropagations=%lld\n", propagations);
printf("%%%%%%mzn-stat: naturalRestarts=%lld\n", nrestarts);
if (so.ldsb) {
printf("%%%%%%mzn-stat: pushbackTime=%.3f\n", to_sec(pushback_time));
}
}
//-----
// Branching methods
bool SAT::finished() {
assert(so.vsids);
while (!order_heap.empty()) {
int x = order_heap[0];
if ((assigns[x] == 0) && flags[x].decidable) {
return false;
}
order_heap.removeMin();
}
return true;
}
DecInfo* SAT::branch() {
if (!so.vsids) {
return nullptr;
}
assert(!order_heap.empty());
int next = order_heap.removeMin();
assert(!assigns[next]);
assert(flags[next].decidable);
return new DecInfo(nullptr, 2 * next + static_cast<int>(polarity[next]));
}
void Clause::debug() const {
for (size_t i = 0; i < size(); i++) {
if (i > 0) {
std::cerr << " \\/ ";
}
std::cerr << getLitString(toInt(operator[](i)));
}
std::cerr << "\n";
}
|
#include "record.hpp"
#include <cstring>
namespace elog
{
# ifdef ELOG_STATIC_RECORD
RecordBuf::RecordBuf()
{
std::memset(buffer_, 0, ELOG_RECORD_LEN);
if (ELOG_RECORD_LEN <= 0)
{
buffer_[0] = 0;
return;
}
buffer_[ELOG_RECORD_LEN - 1] = 0;
setp(buffer_, buffer_ + ELOG_RECORD_LEN - 1);
}
const char* RecordBuf::buffer() const
{
return buffer_;
}
# endif
Record::Record(Severity severity, const char* func, size_t line, const char* file): severity_(severity), func_(func), line_(line), file_(file)
# ifdef ELOG_STATIC_RECORD
, messageStream(&recordBuffer)
# endif
{
time_t t;
t = std::time(nullptr);
localtime_r(&t, &time_);
}
Record::~Record()
{
}
const struct tm& Record::time() const
{
return time_;
}
Severity Record::severity() const
{
return severity_;
}
size_t Record::line() const
{
return line_;
}
#ifdef ELOG_STATIC_RECORD
const char* Record::message() const
{
return recordBuffer.buffer();
}
#else
std::string Record::message() const
{
return messageStream.str();
}
#endif
const char* Record::functionName() const
{
return func_;
}
const char* Record::fileName() const
{
return file_;
}
}
|
#include "Hw264Encoder.h"
CLASS_LOG_IMPLEMENT(CHw264Encoder, "CEncoder[264.hw]");
////////////////////////////////////////////////////////////////////////////////
CHw264Encoder::CHw264Encoder(AVCodecContext *videoctx, int fmt, CHwMediaEncoder *pEncode)
: CMediaEncoder(videoctx), m_pEncode(pEncode), m_pScales(0)
{
THIS_LOGT_print("is created. video(%dX%d): bitrate=%lld, val=%d, gop=%d", m_pCodecs->width, m_pCodecs->height, m_pCodecs->bit_rate, m_pCodecs->qmax, m_pCodecs->gop_size);
assert(m_pEncode != 0);
assert(m_pCodecs->pix_fmt == AV_PIX_FMT_YUV420P);
if( fmt < AV_PIX_FMT_YUV420P ) fmt = AV_PIX_FMT_YUV420P;
if( fmt!=m_pEncode->m_codecid) m_pScales = new CSwsScale(m_pCodecs->width, m_pCodecs->height, fmt, m_pCodecs->width, m_pCodecs->height, m_pEncode->m_codecid);
}
CHw264Encoder::~CHw264Encoder()
{
if( m_pScales != 0 ) delete m_pScales;
delete m_pEncode;
THIS_LOGT_print("is deleted");
}
CBuffer *CHw264Encoder::Encode(CBuffer *pRawdata/*YUV*/)
{//yuv[xxx]->h264
CScopeBuffer pSrcdata(pRawdata->AddRef());
if( m_pBufferManager == 0 ) m_pBufferManager = new CBufferManager(512*1024); //512K
THIS_LOGT_print("do encode[%p]: pts=%lld, data=%p, size=%d", pSrcdata.p, pSrcdata->GetPacket()->pts, pSrcdata->GetPacket()->data, pSrcdata->GetPacket()->size);
if( m_pScales != 0 ) pSrcdata.Attach(m_pScales->Scale(pSrcdata->GetPacket()->pts, pSrcdata->GetPacket()->data));
if( pSrcdata.p== 0 ) return NULL;
CScopeBuffer pDstdata(m_pBufferManager->Pop(pRawdata->GetPacket()->pts));
AVPacket *pDstPacket = pDstdata->GetPacket();
AVPacket *pSrcPacket = pSrcdata->GetPacket();
pDstPacket->size = m_pEncode->Encode(pSrcPacket->data, pSrcPacket->size, pDstPacket->pts, pDstPacket->data);
if( pDstPacket->size <= 0 ) return NULL;
pDstPacket->dts = pDstPacket->pts;
pDstPacket->pos =-1;
pDstPacket->duration = 1;
return pDstdata.Detach();
}
CBuffer *CHw264Encoder::GetDelayedFrame()
{
if( m_pBufferManager == 0 ) return NULL;
CScopeBuffer pDstdata(m_pBufferManager->Pop());
AVPacket *pDstPacket = pDstdata->GetPacket();
pDstPacket->size = m_pEncode->Encode(NULL, 0, pDstPacket->pts, pDstPacket->data);
if( pDstPacket->size <= 0 ) return NULL;
pDstPacket->dts = pDstPacket->pts;
pDstPacket->pos =-1;
pDstPacket->duration = 1;
return pDstdata.Detach();
}
|
// Created on: 2001-12-13
// Created by: Peter KURNEV
// Copyright (c) 2001-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IntTools_PntOnFace_HeaderFile
#define _IntTools_PntOnFace_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Standard_Boolean.hxx>
#include <gp_Pnt.hxx>
#include <TopoDS_Face.hxx>
//! Contains a Face, a 3d point, corresponded UV parameters and a flag
class IntTools_PntOnFace
{
public:
DEFINE_STANDARD_ALLOC
//! Empty constructor
Standard_EXPORT IntTools_PntOnFace();
//! Initializes me by aFace, a 3d point
//! and it's UV parameters on face
Standard_EXPORT void Init (const TopoDS_Face& aF, const gp_Pnt& aP, const Standard_Real U, const Standard_Real V);
//! Modifier
Standard_EXPORT void SetFace (const TopoDS_Face& aF);
//! Modifier
Standard_EXPORT void SetPnt (const gp_Pnt& aP);
//! Modifier
Standard_EXPORT void SetParameters (const Standard_Real U, const Standard_Real V);
//! Modifier
Standard_EXPORT void SetValid (const Standard_Boolean bF);
//! Selector
Standard_EXPORT Standard_Boolean Valid() const;
//! Selector
Standard_EXPORT const TopoDS_Face& Face() const;
//! Selector
Standard_EXPORT const gp_Pnt& Pnt() const;
//! Selector
Standard_EXPORT void Parameters (Standard_Real& U, Standard_Real& V) const;
//! Selector
Standard_EXPORT Standard_Boolean IsValid() const;
protected:
private:
Standard_Boolean myIsValid;
gp_Pnt myPnt;
Standard_Real myU;
Standard_Real myV;
TopoDS_Face myFace;
};
#endif // _IntTools_PntOnFace_HeaderFile
|
#pragma once
#include "iframeprocessor.h"
#include <memory>
#include "Point2D.h"
namespace cvf
{
class ISingleFeatureTrackerWSecondaryPt;
};
namespace cvfn {
public ref class SingleFeatureTrackerWSecondaryPt : public IFrameProcessor
{
std::weak_ptr<cvf::ISingleFeatureTrackerWSecondaryPt> *mptrUnmanaged;
public:
SingleFeatureTrackerWSecondaryPt(void);
virtual ~SingleFeatureTrackerWSecondaryPt(void);
virtual void setUnmanaged( std::weak_ptr<cvf::IFrameProcessor> frm );
virtual Point2D^ getTrackingPoint();
virtual Point2D^ getNormalizedTrackingPoint();
virtual Point2D^ getDeltaSecondaryPoint();
virtual Point2D^ getNormalizedDeltaSecondaryPoint();
virtual bool getTrackingPoint( Point2D% pt );
virtual bool getDeltaSecondaryPoint( Point2D% pt );
};
}
|
// Created on: 1996-12-20
// Created by: Robert COUBLANC
// Copyright (c) 1996-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _AIS_Shape_HeaderFile
#define _AIS_Shape_HeaderFile
#include <AIS_DisplayMode.hxx>
#include <AIS_InteractiveObject.hxx>
#include <Bnd_Box.hxx>
#include <TopoDS_Shape.hxx>
#include <Prs3d_Drawer.hxx>
#include <Prs3d_TypeOfHLR.hxx>
//! A framework to manage presentation and selection of shapes.
//! AIS_Shape is the interactive object which is used the
//! most by applications. There are standard functions
//! available which allow you to prepare selection
//! operations on the constituent elements of shapes -
//! vertices, edges, faces etc - in an open local context.
//! The selection modes specific to "Shape" type objects
//! are referred to as Standard Activation Mode. These
//! modes are only taken into account in open local
//! context and only act on Interactive Objects which
//! have redefined the virtual method
//! AcceptShapeDecomposition so that it returns true.
//! Several advanced functions are also available. These
//! include functions to manage deviation angle and
//! deviation coefficient - both HLR and non-HLR - of
//! an inheriting shape class. These services allow you to
//! select one type of shape interactive object for higher
//! precision drawing. When you do this, the
//! Prs3d_Drawer::IsOwn... functions corresponding to the
//! above deviation angle and coefficient functions return
//! true indicating that there is a local setting available
//! for the specific object.
//!
//! This class allows to map textures on shapes using native UV parametric space of underlying surface of each Face
//! (this means that texture will be visually duplicated on all Faces).
//! To generate texture coordinates, appropriate shading attribute should be set before computing presentation in AIS_Shaded display mode:
//! @code
//! Handle(AIS_Shape) aPrs = new AIS_Shape();
//! aPrs->Attributes()->SetupOwnShadingAspect();
//! aPrs->Attributes()->ShadingAspect()->Aspect()->SetTextureMapOn();
//! aPrs->Attributes()->ShadingAspect()->Aspect()->SetTextureMap (new Graphic3d_Texture2Dmanual (Graphic3d_NOT_2D_ALUMINUM));
//! @endcode
//! The texture itself is parametrized in (0,1)x(0,1).
class AIS_Shape : public AIS_InteractiveObject
{
DEFINE_STANDARD_RTTIEXT(AIS_Shape, AIS_InteractiveObject)
public:
//! Initializes construction of the shape shap from wires,
//! edges and vertices.
Standard_EXPORT AIS_Shape(const TopoDS_Shape& shap);
//! Returns index 0. This value refers to SHAPE from TopAbs_ShapeEnum
virtual Standard_Integer Signature() const Standard_OVERRIDE { return 0; }
//! Returns Object as the type of Interactive Object.
virtual AIS_KindOfInteractive Type() const Standard_OVERRIDE { return AIS_KindOfInteractive_Shape; }
//! Returns true if the Interactive Object accepts shape decomposition.
virtual Standard_Boolean AcceptShapeDecomposition() const Standard_OVERRIDE { return Standard_True; }
//! Return true if specified display mode is supported.
virtual Standard_Boolean AcceptDisplayMode (const Standard_Integer theMode) const Standard_OVERRIDE { return theMode >= 0 && theMode <= 2; }
//! Returns this shape object.
const TopoDS_Shape& Shape() const { return myshape; }
//! Constructs an instance of the shape object theShape.
void SetShape (const TopoDS_Shape& theShape)
{
myshape = theShape;
myCompBB = Standard_True;
}
//! Alias for ::SetShape().
void Set (const TopoDS_Shape& theShape) { SetShape (theShape); }
//! Sets a local value for deviation coefficient for this specific shape.
Standard_EXPORT Standard_Boolean SetOwnDeviationCoefficient();
//! Sets a local value for deviation angle for this specific shape.
Standard_EXPORT Standard_Boolean SetOwnDeviationAngle();
//! Sets a local value for deviation coefficient for this specific shape.
Standard_EXPORT void SetOwnDeviationCoefficient (const Standard_Real aCoefficient);
//! this compute a new angle and Deviation from the value anAngle
//! and set the values stored in myDrawer with these that become local to the shape
Standard_EXPORT void SetAngleAndDeviation (const Standard_Real anAngle);
//! gives back the angle initial value put by the User.
Standard_EXPORT Standard_Real UserAngle() const;
//! sets myOwnDeviationAngle field in Prs3d_Drawer & recomputes presentation
Standard_EXPORT void SetOwnDeviationAngle (const Standard_Real anAngle);
//! Returns true and the values of the deviation
//! coefficient aCoefficient and the previous deviation
//! coefficient aPreviousCoefficient. If these values are
//! not already set, false is returned.
Standard_EXPORT Standard_Boolean OwnDeviationCoefficient (Standard_Real& aCoefficient, Standard_Real& aPreviousCoefficient) const;
//! Returns true and the values of the deviation angle
//! anAngle and the previous deviation angle aPreviousAngle.
//! If these values are not already set, false is returned.
Standard_EXPORT Standard_Boolean OwnDeviationAngle (Standard_Real& anAngle, Standard_Real& aPreviousAngle) const;
//! Sets the type of HLR algorithm used by the shape
void SetTypeOfHLR (const Prs3d_TypeOfHLR theTypeOfHLR) { myDrawer->SetTypeOfHLR (theTypeOfHLR); }
//! Gets the type of HLR algorithm
Prs3d_TypeOfHLR TypeOfHLR() const { return myDrawer->TypeOfHLR(); }
//! Sets the color aColor in the reconstructed
//! compound shape. Acts via the Drawer methods below on the appearance of:
//! - free boundaries:
//! Prs3d_Drawer_FreeBoundaryAspect,
//! - isos: Prs3d_Drawer_UIsoAspect,
//! Prs3dDrawer_VIsoAspect,
//! - shared boundaries:
//! Prs3d_Drawer_UnFreeBoundaryAspect,
//! - shading: Prs3d_Drawer_ShadingAspect,
//! - visible line color in hidden line mode:
//! Prs3d_Drawer_SeenLineAspect
//! - hidden line color in hidden line mode:
//! Prs3d_Drawer_HiddenLineAspect.
Standard_EXPORT virtual void SetColor (const Quantity_Color& theColor) Standard_OVERRIDE;
//! Removes settings for color in the reconstructed compound shape.
Standard_EXPORT virtual void UnsetColor() Standard_OVERRIDE;
//! Sets the value aValue for line width in the reconstructed compound shape.
//! Changes line aspects for lines presentation.
Standard_EXPORT virtual void SetWidth (const Standard_Real aValue) Standard_OVERRIDE;
//! Removes the setting for line width in the reconstructed compound shape.
Standard_EXPORT virtual void UnsetWidth() Standard_OVERRIDE;
//! Allows you to provide settings for the material aName
//! in the reconstructed compound shape.
Standard_EXPORT virtual void SetMaterial (const Graphic3d_MaterialAspect& aName) Standard_OVERRIDE;
//! Removes settings for material in the reconstructed compound shape.
Standard_EXPORT virtual void UnsetMaterial() Standard_OVERRIDE;
//! Sets the value aValue for transparency in the reconstructed compound shape.
Standard_EXPORT virtual void SetTransparency (const Standard_Real aValue = 0.6) Standard_OVERRIDE;
//! Removes the setting for transparency in the reconstructed compound shape.
Standard_EXPORT virtual void UnsetTransparency() Standard_OVERRIDE;
//! Constructs a bounding box with which to reconstruct
//! compound topological shapes for presentation.
Standard_EXPORT virtual const Bnd_Box& BoundingBox();
//! AIS_InteractiveObject defines another virtual method BoundingBox,
//! which is not the same as above; keep it visible.
using AIS_InteractiveObject::BoundingBox;
//! Returns the Color attributes of the shape accordingly to
//! the current facing model;
Standard_EXPORT virtual void Color (Quantity_Color& aColor) const Standard_OVERRIDE;
//! Returns the NameOfMaterial attributes of the shape accordingly to
//! the current facing model;
Standard_EXPORT virtual Graphic3d_NameOfMaterial Material() const Standard_OVERRIDE;
//! Returns the transparency attributes of the shape accordingly to
//! the current facing model;
Standard_EXPORT virtual Standard_Real Transparency() const Standard_OVERRIDE;
//! Return shape type for specified selection mode.
static TopAbs_ShapeEnum SelectionType (const Standard_Integer theSelMode)
{
switch (theSelMode)
{
case 1: return TopAbs_VERTEX;
case 2: return TopAbs_EDGE;
case 3: return TopAbs_WIRE;
case 4: return TopAbs_FACE;
case 5: return TopAbs_SHELL;
case 6: return TopAbs_SOLID;
case 7: return TopAbs_COMPSOLID;
case 8: return TopAbs_COMPOUND;
case 0: return TopAbs_SHAPE;
}
return TopAbs_SHAPE;
}
//! Return selection mode for specified shape type.
static Standard_Integer SelectionMode (const TopAbs_ShapeEnum theShapeType)
{
switch (theShapeType)
{
case TopAbs_VERTEX: return 1;
case TopAbs_EDGE: return 2;
case TopAbs_WIRE: return 3;
case TopAbs_FACE: return 4;
case TopAbs_SHELL: return 5;
case TopAbs_SOLID: return 6;
case TopAbs_COMPSOLID: return 7;
case TopAbs_COMPOUND: return 8;
case TopAbs_SHAPE: return 0;
}
return 0;
}
public: //! @name methods to alter texture mapping properties
//! Return texture repeat UV values; (1, 1) by default.
const gp_Pnt2d& TextureRepeatUV() const { return myUVRepeat; }
//! Sets the number of occurrences of the texture on each face. The texture itself is parameterized in (0,1) by (0,1).
//! Each face of the shape to be textured is parameterized in UV space (Umin,Umax) by (Vmin,Vmax).
void SetTextureRepeatUV (const gp_Pnt2d& theRepeatUV) { myUVRepeat = theRepeatUV; }
//! Return texture origin UV position; (0, 0) by default.
const gp_Pnt2d& TextureOriginUV() const { return myUVOrigin; }
//! Use this method to change the origin of the texture.
//! The texel (0,0) will be mapped to the surface (myUVOrigin.X(), myUVOrigin.Y()).
void SetTextureOriginUV (const gp_Pnt2d& theOriginUV) { myUVOrigin = theOriginUV; }
//! Return scale factor for UV coordinates; (1, 1) by default.
const gp_Pnt2d& TextureScaleUV() const { return myUVScale; }
//! Use this method to scale the texture (percent of the face).
//! You can specify a scale factor for both U and V.
//! Example: if you set ScaleU and ScaleV to 0.5 and you enable texture repeat,
//! the texture will appear twice on the face in each direction.
void SetTextureScaleUV (const gp_Pnt2d& theScaleUV) { myUVScale = theScaleUV; }
protected:
//! Compute normal presentation.
Standard_EXPORT virtual void Compute (const Handle(PrsMgr_PresentationManager)& thePrsMgr,
const Handle(Prs3d_Presentation)& thePrs,
const Standard_Integer theMode) Standard_OVERRIDE;
//! Compute projected presentation.
virtual void computeHLR (const Handle(Graphic3d_Camera)& theProjector,
const Handle(TopLoc_Datum3D)& theTrsf,
const Handle(Prs3d_Presentation)& thePrs) Standard_OVERRIDE
{
if (!theTrsf.IsNull()
&& theTrsf->Form() != gp_Identity)
{
const TopLoc_Location& aLoc = myshape.Location();
const TopoDS_Shape aShape = myshape.Located (TopLoc_Location (theTrsf->Trsf()) * aLoc);
computeHlrPresentation (theProjector, thePrs, aShape, myDrawer);
}
else
{
computeHlrPresentation (theProjector, thePrs, myshape, myDrawer);
}
}
//! Compute selection.
Standard_EXPORT virtual void ComputeSelection (const Handle(SelectMgr_Selection)& theSelection,
const Standard_Integer theMode) Standard_OVERRIDE;
//! Create own aspects (if they do not exist) and set color to them.
//! @return TRUE if new aspects have been created
Standard_EXPORT bool setColor (const Handle(Prs3d_Drawer)& theDrawer, const Quantity_Color& theColor) const;
//! Create own aspects (if they do not exist) and set width to them.
//! @return TRUE if new aspects have been created
Standard_EXPORT bool setWidth (const Handle(Prs3d_Drawer)& theDrawer, const Standard_Real theWidth) const;
Standard_EXPORT void setTransparency (const Handle(Prs3d_Drawer)& theDrawer, const Standard_Real theValue) const;
Standard_EXPORT void setMaterial (const Handle(Prs3d_Drawer)& theDrawer, const Graphic3d_MaterialAspect& theMaterial, const Standard_Boolean theToKeepColor, const Standard_Boolean theToKeepTransp) const;
//! Replace aspects of already computed groups from drawer link by the new own value.
Standard_EXPORT void replaceWithNewOwnAspects();
public:
//! Compute HLR presentation for specified shape.
Standard_EXPORT static void computeHlrPresentation (const Handle(Graphic3d_Camera)& theProjector,
const Handle(Prs3d_Presentation)& thePrs,
const TopoDS_Shape& theShape,
const Handle(Prs3d_Drawer)& theDrawer);
//! Dumps the content of me into the stream
Standard_EXPORT virtual void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const Standard_OVERRIDE;
protected:
TopoDS_Shape myshape; //!< shape to display
Bnd_Box myBB; //!< cached bounding box of the shape
gp_Pnt2d myUVOrigin; //!< UV origin vector for generating texture coordinates
gp_Pnt2d myUVRepeat; //!< UV repeat vector for generating texture coordinates
gp_Pnt2d myUVScale; //!< UV scale vector for generating texture coordinates
Standard_Real myInitAng;
Standard_Boolean myCompBB; //!< if TRUE, then bounding box should be recomputed
};
DEFINE_STANDARD_HANDLE(AIS_Shape, AIS_InteractiveObject)
#endif // _AIS_Shape_HeaderFile
|
/*
* 替换句子中的空格为%20
*/
#include <bits/stdc++.h>
using namespace std;
class Solution{
public:
string replace_space(string str,int length){
int spaceNum = 0;
for(int i=0; i<length; ++i){
if(str[i] == ' '){
spaceNum++;
}
}
int newLength = length + spaceNum*2;
int indexPre,indexAfter;
for(indexPre = length-1,indexAfter = newLength-1;indexPre <= indexAfter && indexPre>=0;){
if(str[indexPre] == ' '){
str[indexAfter--] = '0';
str[indexAfter--] = '2';
str[indexAfter--] = '%';
indexPre--;
}else{
str[indexAfter--] = str[indexPre--];
}
}
return str;
}
};
int main(){
string str(1000,' ');
str = "a b c" + str;
Solution handle;
printf("%s\n",handle.replace_space(str,5).c_str());
return 0;
}
|
/*
* Copyright (C) 2017 ~ 2018 Deepin Technology Co., Ltd.
*
* Author: kirigaya <kirigaya@mkacg.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef ICONMODULE_H
#define ICONMODULE_H
#include "moduleinterface.h"
#include "../widgets/basewidget.h"
#include "../model.h"
#include "../worker.h"
#include <QScrollArea>
#include <QScrollBar>
#include <QGridLayout>
#include <QKeyEvent>
#include <QImageReader>
#include <QEvent>
#include <QMouseEvent>
#include <DWidget>
#include <dflowlayout.h>
DWIDGET_USE_NAMESPACE
class IconModule : public ModuleInterface
{
Q_OBJECT
public:
explicit IconModule(QWidget *parent = nullptr);
void updateBigIcon() Q_DECL_OVERRIDE;
void updateSmallIcon() Q_DECL_OVERRIDE;
void updateSelectBtnPos() Q_DECL_OVERRIDE;
void keyPressEvent(QKeyEvent*) Q_DECL_OVERRIDE;
void mouseMoveEvent(QMouseEvent*) Q_DECL_OVERRIDE;
void mousePressEvent(QMouseEvent*) Q_DECL_OVERRIDE;
signals:
void cancelCloseFrame();
protected:
bool eventFilter(QObject *watched, QEvent *event) Q_DECL_OVERRIDE;
private slots:
void addIcon(const IconStruct &icon);
void removeIcon(const IconStruct &icon);
void currentIconChanged(const IconStruct &icon);
private:
QScrollArea *m_scroll;
DWidget *m_scrollWidget;
DFlowLayout* m_layout;
QMap<IconStruct, BaseWidget*> m_iconList;
int m_height;
QWidget *m_Body;
QPoint m_TempPoint;
};
#endif // ICONMODULE_H
|
#include <Tanker/User.hpp>
#include <tuple>
namespace Tanker
{
bool operator==(User const& l, User const& r)
{
return std::tie(l.id, l.userKey, l.devices) ==
std::tie(r.id, r.userKey, r.devices);
}
bool operator!=(User const& l, User const& r)
{
return !(l == r);
}
}
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
char last, a;
cin >> last;
int ans = 1, max = 1;
while (cin >> a) {
if (a == last) {
ans ++;
} else {
ans = 1;
}
last = a;
if (ans > max) {
max = ans;
}
}
cout << max;
}
|
#include<iostream>
#include<map>
#include<vector>
using namespace std;
typedef char EdgeData;
class EdgeNode {
public:
int adjvex;
EdgeData data;
EdgeNode * next;
EdgeNode(int adjvex, EdgeData data, EdgeNode * next) :
adjvex(adjvex), data(data), next(next) {
}
EdgeNode() :next(NULL) {
}
};
typedef vector<EdgeNode*> graph;
map<EdgeData, int> m;
graph g;
int N;
void createnode(EdgeData x) {
if (m[x]) return;
g.push_back(new EdgeNode(++N, x, NULL));
m[x] = N;
}
void input() {//input graph
int n;
EdgeData x, y;
g.push_back(NULL);
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> x >> y;
createnode(x);
createnode(y);
g[m[x]]->next = new EdgeNode(g[m[y]]->adjvex, y, g[m[x]]->next);
}
}
//tarjan
int *dfn, *low, *s, top, counter, sum;
bool *ins;
void dfs(int u) {
int v;
dfn[u] = low[u] = ++counter;//序号
s[++top] = u;
ins[u] = true;//加入堆栈
for (auto i = g[u]->next; i; i = i->next) {
v = i->adjvex;
if (!dfn[v]) {
dfs(v);
low[v] < low[u] ? low[u] = low[v]:0;
}
else if (ins[v] && dfn[v] < low[u])//能回退到更前
low[u] = dfn[v];
}
if (dfn[u] == low[u]) {
cout << endl;
sum++;
do {
v = s[top--];
ins[v] = false;
cout << g[v]->data << ' ';
} while (v != u);
}
}
void solve() {
s = new int[N+1];
dfn = new int[N+1];
low = new int[N+1];
ins = new bool[N+1];
memset(dfn, 0, (N+1)*sizeof(int));
memset(ins, 0, (N+1)*sizeof(bool));
for (int i = 1; i <= N; i++)
if (!dfn[i])
dfs(i);
cout << "\ntotal: " << sum;
}
void main() {
input();
solve();
system("pause");
}
|
#include <iostream>
using namespace std;
int main()
{
int n1=0,n2=1,n3,i,numbers=50;
cout<<n1<<", "<<n2<<", ";
for(i=2;i<numbers;++i)
{
n3=n1+n2;
cout<<n3<<", ";
n1=n2;
n2=n3;
}
return 0;
}
|
/* leetcode 189
*
*
*
*/
class Solution {
public:
void rotate(vector<int>& nums, int k) {
if (nums.empty() || k <= 0) {
return;
}
int len = nums.size();
k = k % len;
int start = 0;
int tmp = 0;
for (int cnt = 0; cnt < len; start++) {
int current = start;
int pre = nums.at(current);
do {
int next = (current + k) % len;
int tmp = nums.at(next);
nums.at(next) = pre;
current = next;
pre = tmp;
cnt++;
} while (current != start);
}
}
};
/************************** run solution **************************/
vector<int> _solution_run(vector<int>& nums, int k)
{
Solution leetcode_189;
leetcode_189.rotate(nums, k);
return nums;
}
#ifdef USE_SOLUTION_CUSTOM
vector<vector<int>> _solution_custom(TestCases &tc)
{
return {};
}
#endif
/************************** get testcase **************************/
#ifdef USE_GET_TEST_CASES_IN_CPP
vector<string> _get_test_cases_string()
{
return {};
}
#endif
|
#pragma once
#include "merger_base.hpp"
#include "proto/data_guanpin.pb.h"
#include "utils/service_thread.hpp"
#include <memory>
using namespace std;
namespace pd = proto::data;
namespace nora {
class guanpin_merger : public merger_base {
public:
static guanpin_merger& instance() {
static guanpin_merger inst;
return inst;
}
void start();
private:
void load_rank();
void merge_rank();
void load_next_page();
void on_db_get_guans_done(const shared_ptr<db::message>& msg);
void send_mail(uint64_t role, uint32_t mail_pttid, const pd::dynamic_data& dynamic_data);
pd::mail mail_new_mail(uint64_t role, uint32_t pttid, const pd::dynamic_data& dynamic_data);
int cur_page_ = 0;
int page_size_ = 50;
int adding_count_ = 0;
unique_ptr<pd::guanpin> from_guanpin_;
unique_ptr<pd::guanpin> to_guanpin_;
};
}
|
#include <iostream>
void fillCordinates(int& x, int& y);
|
#include "font_shader.h"
namespace sloth {
std::shared_ptr<FontShader> FontShader::m_Inst(nullptr);
FontShader::FontShader()
: Shader(FONT_SHADER_VERTEX_FILE, FONT_SHADER_FRAGMENT_FILE)
{
getAllUniformLocation();
}
std::shared_ptr<FontShader> FontShader::inst()
{
if (m_Inst == nullptr)
m_Inst = FontShader_s(new FontShader());
return m_Inst;
}
void sloth::FontShader::loadColor(const glm::vec3 & color)
{
glProgramUniform3f(m_ID, m_LocColor, color.x, color.y, color.z);
}
void sloth::FontShader::loadModel(const glm::vec2 &model)
{
glProgramUniform2f(m_ID, m_LocModel, model.x, model.y);
}
void FontShader::loadFontWidth(float fontWidth)
{
glProgramUniform1f(m_ID, m_LocFontWidth, fontWidth);
}
void FontShader::loadFontEdge(float fontEdge)
{
glProgramUniform1f(m_ID, m_LocFontEdge, fontEdge);
}
void FontShader::loadBorderWidth(float borderWidth)
{
glProgramUniform1f(m_ID, m_LocBorderWidth, borderWidth);
}
void FontShader::loadBorderEdge(float borderEdge)
{
glProgramUniform1f(m_ID, m_LocBorderEdge, borderEdge);
}
void FontShader::loadOffset(const glm::vec2 & offset)
{
glProgramUniform2f(m_ID, m_LocOffset, offset.x, offset.y);
}
void FontShader::loadOutlineColor(const glm::vec3 & outlineColor)
{
glProgramUniform3f(m_ID, m_LocOutlineColor, outlineColor.x, outlineColor.y, outlineColor.z);
}
void FontShader::getAllUniformLocation()
{
m_LocColor = glGetUniformLocation(m_ID, "color");
m_LocModel = glGetUniformLocation(m_ID, "model");
m_LocFontWidth = glGetUniformLocation(m_ID, "fontWidth");
m_LocFontEdge = glGetUniformLocation(m_ID, "fontEdge");
m_LocBorderWidth = glGetUniformLocation(m_ID, "borderWidth");
m_LocBorderEdge = glGetUniformLocation(m_ID, "borderEdge");
m_LocOffset = glGetUniformLocation(m_ID, "offset");
m_LocOutlineColor = glGetUniformLocation(m_ID, "outlineColor");
}
}
|
#ifndef HAVE_PACK1
# error Expected HAVE_PACK1
#endif
#ifndef HAVE_PACK2
# error Expected HAVE_PACK2
#endif
#ifndef HAVE_PACK3
# error Expected HAVE_PACK3
#endif
#ifndef HAVE_PACK4
# error Expected HAVE_PACK4
#endif
#ifndef HAVE_PACK5
# error Expected HAVE_PACK5
#endif
#ifndef HAVE_PACK6
# error Expected HAVE_PACK6
#endif
#ifndef HAVE_PACK7
# error Expected HAVE_PACK7
#endif
#ifndef HAVE_PACK7_COMP1
# error Expected HAVE_PACK7_COMP1
#endif
#ifndef HAVE_PACK8
# error Expected HAVE_PACK8
#endif
int main(int argc, char** argv)
{
return 0;
}
|
// Created on: 1993-06-23
// Created by: Jean Yves LEBEY
// Copyright (c) 1993-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _TopOpeBRepDS_Point_HeaderFile
#define _TopOpeBRepDS_Point_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <gp_Pnt.hxx>
class TopoDS_Shape;
//! A Geom point and a tolerance.
class TopOpeBRepDS_Point
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT TopOpeBRepDS_Point();
Standard_EXPORT TopOpeBRepDS_Point(const gp_Pnt& P, const Standard_Real T);
Standard_EXPORT TopOpeBRepDS_Point(const TopoDS_Shape& S);
Standard_EXPORT Standard_Boolean IsEqual (const TopOpeBRepDS_Point& other) const;
Standard_EXPORT const gp_Pnt& Point() const;
Standard_EXPORT gp_Pnt& ChangePoint();
Standard_EXPORT Standard_Real Tolerance() const;
Standard_EXPORT void Tolerance (const Standard_Real Tol);
Standard_EXPORT Standard_Boolean Keep() const;
Standard_EXPORT void ChangeKeep (const Standard_Boolean B);
protected:
private:
gp_Pnt myPoint;
Standard_Real myTolerance;
Standard_Boolean myKeep;
};
#endif // _TopOpeBRepDS_Point_HeaderFile
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Engine/LevelScriptActor.h"
#include "SpherobotBaseLevelScriptActor.generated.h"
/**
*
*/
UCLASS()
class SPHEROBOT_API ASpherobotBaseLevelScriptActor : public ALevelScriptActor
{
GENERATED_BODY()
public:
/** Spherobot Level Name (if any) */
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Spehrobot Level")
FName SpherobotLevelName;
/** Spherobot Level Number (required) */
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Spehrobot Level")
int32 SpherobotLevelNumber;
/** Spherobot Level Camera (ovveride) */
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Spehrobot Level")
ACameraActor* SpherobotLevelCamera;
//class APaperSpriteActor* GetSpherobotLevelBackground();
/** Spherobot Level Background (ovveride) */
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Spehrobot Level")
class APaperSpriteActor* SpherobotLevelBackground;
ACharacter* CurrentPlayerCharacter;
//===========
// BP Nodes
//===========
protected:
virtual void BeginPlay() override;
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
//TICK
protected:
//Tick
virtual void Tick(float DeltaSeconds) override;
};
|
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream infile;
infile.open("input/sum.in");
int t;
infile >> t;
int n;
cout << t << endl;
for (int i = 0; i < t; i++) {
infile >> n;
float sum = 0;
for (int j = 1; j <= n*n; j += n+1) {
sum += j;
}
printf("%.8f\n", sum);
}
}
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QWidget>
#include <QGridLayout>
#include <QLCDNumber>
#include <QDebug>
#include <iostream>
#include <stdlib.h>
#include <string>
int infixToPostfix:: pres(char ope)
{
if(ope=='&')
return 0;
else if(ope=='(')
return 1;
else if(ope==')')
return 2;
else if(ope=='+' || ope=='-')
return 3;
else
return 4;
}
char* infixToPostfix:: infix_postfix(char str[])
{
int k=0;
int check =0;
char ope;
charObject.push('&');
unsigned int len = strlen(str);
char *t_str = new char[(len/2)+len+1];
for( unsigned long i=0;i<len;i++)
{
if(str[i]>=48 && str[i]<=57)
{
t_str[k++]=str[i];
check=1;
}
else if(pres(charObject.showLast()) < pres(str[i]) || str[i]=='(')
{
if(check==1)
{
t_str[k++]= '|';
check=0;
}
charObject.push(str[i]);
}
else
{
if(check==1)
{
t_str[k++] = '|';
check= 0;
}
while((pres(charObject.showLast()) >= pres(str[i])) && charObject.showLast()!='&')
t_str[k++] = charObject.pop();
if(str[i]==')')
ope = charObject.pop();
else
charObject.push(str[i]);
}
}
if(check==1)
t_str[k++]= '|';
while(charObject.showLast()!='&')
{
t_str[k++]=charObject.pop();
}
t_str[k]='\0';
return t_str;
}
void charStack:: push(char elem)
{
if(top<299)
{
Stack[++top] = elem;
}
}
char charStack::pop()
{
if(top>-1)
{
return Stack[top--];
}
else
{
return '&';
}
}
double intStack::pop()
{
if(top>-1)
{
return Stack[top--];
}
else
{
return 99999;
}
}
void intStack:: push(double elem)
{
if(top<299)
{
Stack[++top] = elem;
}
}
double infixToPostfix::solve_postfix(char str[])
{
int i=0, len=0;
double res;
double number,val1,val2;
while(str[i]!='\0')
{
len++;
i++;
}
i=0;
for(int i=0;i<len;i++)
{
if(str[i]>=48 && str[i]<=57)
{
number = 0;
while(str[i]!='|' && i<len)
{
number = (number*10)+str[i]-48;
i++;
}
intObject.push(number);
}
else
{
val2 = intObject.pop();
val1 = intObject.pop();
switch(str[i])
{
case '+':
res = val2+val1;
break;
case '-':
res = val1 - val2;
break;
case '*':
res = val1*val2;
break;
case '/':
res = val1/val2;
break;
}
intObject.push(res);
}
}
return intObject.pop();
}
double infixToPostfix::getResult( char str[])
{
char *ptr = infix_postfix(str);
return solve_postfix(ptr);
}
char charStack::showLast()
{
return Stack[top];
}
MainWindow::MainWindow(QWidget *parent) :
QWidget(parent){
QPushButton *zero = new QPushButton("0", this);
QPushButton *one = new QPushButton("1", this);
QPushButton *two = new QPushButton("2", this);
QPushButton *three = new QPushButton("3", this);
QPushButton *four = new QPushButton("4", this);
QPushButton *five = new QPushButton("5", this);
QPushButton *six = new QPushButton("6", this);
QPushButton *seven = new QPushButton("7", this);
QPushButton *eight = new QPushButton("8", this);
QPushButton *nine = new QPushButton("9", this);
QPushButton *add = new QPushButton("+", this);
QPushButton *minus = new QPushButton("-", this);
QPushButton *multi = new QPushButton("*", this);
QPushButton *divide = new QPushButton("/", this);
QPushButton *clear = new QPushButton("C", this);
QPushButton *allClear = new QPushButton("AC", this);
QPushButton *ans = new QPushButton("ans", this);
disp = new QLabel(this);
QGridLayout *panel = new QGridLayout(this);
panel->addWidget(allClear, 1, 0);
panel->addWidget(clear, 1, 1);
panel->addWidget(ans, 1, 2);
panel->addWidget(divide, 1, 3);
panel->addWidget(nine, 2, 0);
panel->addWidget(eight, 2, 1);
panel->addWidget(seven, 2, 2);
panel->addWidget(multi, 2, 3);
panel->addWidget(four, 3, 0);
panel->addWidget(five, 3, 1);
panel->addWidget(six, 3, 2);
panel->addWidget(minus, 3, 3);
panel->addWidget(one, 4, 0);
panel->addWidget(two, 4, 1);
panel->addWidget(three, 4, 2);
panel->addWidget(add, 4, 3);
panel->addWidget(zero, 5, 1);
panel->addWidget(disp, 0, 0, 1, 4);
panel->setRowMinimumHeight(0, 40);
setLayout(panel);
connect(one, &QPushButton::clicked, this, &MainWindow::On_1);
connect(two, &QPushButton::clicked, this, &MainWindow::On_2);
connect(three, &QPushButton::clicked, this, &MainWindow::On_3);
connect(four, &QPushButton::clicked, this, &MainWindow::On_4);
connect(five, &QPushButton::clicked, this, &MainWindow::On_5);
connect(six, &QPushButton::clicked, this, &MainWindow::On_6);
connect(seven, &QPushButton::clicked, this, &MainWindow::On_7);
connect(eight, &QPushButton::clicked, this, &MainWindow::On_8);
connect(nine, &QPushButton::clicked, this, &MainWindow::On_9);
connect(zero, &QPushButton::clicked, this, &MainWindow::On_0);
connect(add, &QPushButton::clicked, this, &MainWindow::On_add);
connect(multi, &QPushButton::clicked, this, &MainWindow::On_multi);
connect(divide, &QPushButton::clicked, this, &MainWindow::On_divide);
connect(minus, &QPushButton::clicked, this, &MainWindow::On_minus);
connect(clear, &QPushButton::clicked, this, &MainWindow::On_clear);
connect(allClear, &QPushButton::clicked, this, &MainWindow::On_allclear);
connect(ans, &QPushButton::clicked, this, &MainWindow::On_ans);
}
void MainWindow::On_0(){
QString str = disp->text();
str.append('0');
disp->setText(str);
}
void MainWindow::On_1(){
QString str = disp->text();
str.append('1');
disp->setText(str);
}
void MainWindow::On_2(){
QString str = disp->text();
str.append('2');
disp->setText(str);
}
void MainWindow::On_3(){
QString str = disp->text();
str.append('3');
disp->setText(str);
}
void MainWindow::On_4(){
QString str = disp->text();
str.append('4');
disp->setText(str);
}
void MainWindow::On_5(){
QString str = disp->text();
str.append('5');
disp->setText(str);
}
void MainWindow::On_6(){
QString str = disp->text();
str.append('6');
disp->setText(str);
}
void MainWindow::On_7(){
QString str = disp->text();
str.append('7');
disp->setText(str);
}
void MainWindow::On_8(){
QString str = disp->text();
str.append('8');
disp->setText(str);
}
void MainWindow::On_9(){
QString str = disp->text();
str.append('9');
disp->setText(str);
}
void MainWindow::On_add(){
QString str = disp->text();
str.append('+');
disp->setText(str);
}
void MainWindow::On_minus(){
QString str = disp->text();
str.append('-');
disp->setText(str);
}
void MainWindow::On_multi(){
QString str = disp->text();
str.append('*');
disp->setText(str);
}
void MainWindow::On_divide(){
QString str = disp->text();
str.append('/');
disp->setText(str);
qDebug()<<str;
}
void MainWindow::On_clear(){
QString str = disp->text();
int len = str.length();
str.remove(len-1, 1);
disp->setText(str);
}
void MainWindow::On_allclear(){
QString str = disp->text();
int len = str.length();
str.remove(0, len);
disp->setText(str);
}
void MainWindow::On_ans()
{
infixToPostfix expres;
//double result = object->getResult(str);
qDebug()<<disp->text();
QString str1 = disp->text();
QByteArray ba = str1.toLatin1();
char *c_str2 = ba.data();
double result = expres.getResult(c_str2);
disp->setNum(result);
}
|
/*
void setup() {
// initialize digital pin 13 as an output.
pinMode(13, OUTPUT);
pinMode(12, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
digitalWrite(12, LOW);
an
delay(1000); // wait for a second
digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
digitalWrite(12, HIGH);
delay(5000); // wait for a second
}
*/
/*
int led = 9; // the pin that the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by
// the setup routine runs once when you press reset:
void setup() {
// declare pin 9 to be an output:
pinMode(led, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
// set the brightness of pin 9:
analogWrite(led, brightness);
// change the brightness for next time through the loop:
brightness = brightness + fadeAmount;
// reverse the direction of the fading at the ends of the fade:
if (brightness == 0 || brightness == 255) {
fadeAmount = -fadeAmount ;
}
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
*/
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 2);
void setup()
{
lcd.begin(16,1);
lcd.print("hello, world!");
}
void loop() {}
|
// Created on: 1996-01-16
// Created by: Jean-Pierre COMBE
// Copyright (c) 1996-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _DsgPrs_TangentPresentation_HeaderFile
#define _DsgPrs_TangentPresentation_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Prs3d_Drawer.hxx>
#include <Prs3d_Presentation.hxx>
class gp_Pnt;
class gp_Dir;
//! A framework to define display of tangents.
class DsgPrs_TangentPresentation
{
public:
DEFINE_STANDARD_ALLOC
//! Adds the point OffsetPoint, the direction aDirection
//! and the length aLength to the presentation object aPresentation.
//! The display attributes of the tangent are defined by
//! the attribute manager aDrawer.
Standard_EXPORT static void Add (const Handle(Prs3d_Presentation)& aPresentation, const Handle(Prs3d_Drawer)& aDrawer, const gp_Pnt& OffsetPoint, const gp_Dir& aDirection, const Standard_Real aLength);
protected:
private:
};
#endif // _DsgPrs_TangentPresentation_HeaderFile
|
/*====================================================================
Copyright(c) 2018 Adam Rankin
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.
====================================================================*/
#pragma once
#include "PiecewiseLinearTransferFunction.h"
// WinRt includes
#include <ppltasks.h>
namespace DX
{
class DeviceResources;
class StepTimer;
}
namespace HoloIntervention
{
namespace Rendering
{
struct LookupTableBufferType
{
DirectX::XMFLOAT4 lookupValue;
};
struct VolumeEntryConstantBuffer
{
DirectX::XMFLOAT4X4 worldMatrix;
DirectX::XMFLOAT3 stepSize;
float lt_maximumXValue;
uint32 lt_arraySize;
uint32 numIterations;
DirectX::XMFLOAT2 buffer;
};
static_assert((sizeof(VolumeEntryConstantBuffer) % (sizeof(float) * 4)) == 0, "Volume constant buffer size must be 16-byte aligned (16 bytes is the length of four floats).");
struct VertexPosition
{
Windows::Foundation::Numerics::float3 pos;
};
class Volume
{
public:
typedef std::pair<float, Windows::Foundation::Numerics::float4> ControlPoint;
typedef std::vector<ControlPoint> ControlPointList;
enum TransferFunctionType
{
TransferFunction_Unknown,
TransferFunction_Piecewise_Linear,
};
public:
Volume(const std::shared_ptr<DX::DeviceResources>& deviceResources,
uint64 token,
ID3D11Buffer* cwIndexBuffer,
ID3D11Buffer* ccwIndexBuffer,
ID3D11InputLayout* inputLayout,
ID3D11Buffer* vertexBuffer,
ID3D11VertexShader* volRenderVertexShader,
ID3D11GeometryShader* volRenderGeometryShader,
ID3D11PixelShader* volRenderPixelShader,
ID3D11PixelShader* faceCalcPixelShader,
ID3D11Texture2D* frontPositionTextureArray,
ID3D11Texture2D* backPositionTextureArray,
ID3D11RenderTargetView* frontPositionRTV,
ID3D11RenderTargetView* backPositionRTV,
ID3D11ShaderResourceView* frontPositionSRV,
ID3D11ShaderResourceView* backPositionSRV,
DX::StepTimer& timer);
~Volume();
bool IsInFrustum() const;
bool IsInFrustum(const Windows::Perception::Spatial::SpatialBoundingFrustum& frustum) const;
bool IsValid() const;
void Update();
void Render(uint32 indexCount);
void SetFrame(UWPOpenIGTLink::VideoFrame^ frame);
void SetShowing(bool showing);
uint64 GetToken() const;
void ForceCurrentPose(const Windows::Foundation::Numerics::float4x4& matrix);
void SetDesiredPose(const Windows::Foundation::Numerics::float4x4& matrix);
Windows::Foundation::Numerics::float4x4 GetCurrentPose() const;
Windows::Foundation::Numerics::float3 GetVelocity() const;
Concurrency::task<void> SetOpacityTransferFunctionTypeAsync(Volume::TransferFunctionType type, uint32 tableSize, const Volume::ControlPointList& controlPoints);
// D3D device related controls
void CreateDeviceDependentResources();
void ReleaseDeviceDependentResources();
Windows::Foundation::Numerics::float4x4 m_desiredPose = Windows::Foundation::Numerics::float4x4::identity();
Windows::Foundation::Numerics::float4x4 m_currentPose = Windows::Foundation::Numerics::float4x4::identity();
Windows::Foundation::Numerics::float4x4 m_lastPose = Windows::Foundation::Numerics::float4x4::identity();
Windows::Foundation::Numerics::float3 m_velocity = { 0.f, 0.f, 0.f };
protected:
void UpdateGPUImageData();
void CreateVolumeResources();
void ReleaseVolumeResources();
void CreateTFResources();
void ReleaseTFResources();
protected:
// Cached pointer to device resources.
std::shared_ptr<DX::DeviceResources> m_deviceResources;
DX::StepTimer& m_timer;
// Cached pointers to re-used D3D resources
ID3D11Buffer* m_cwIndexBuffer;
ID3D11Buffer* m_ccwIndexBuffer;
ID3D11InputLayout* m_inputLayout;
ID3D11Buffer* m_vertexBuffer;
ID3D11VertexShader* m_volRenderVertexShader;
ID3D11GeometryShader* m_volRenderGeometryShader;
ID3D11PixelShader* m_volRenderPixelShader;
ID3D11PixelShader* m_faceCalcPixelShader;
// Direct3D resources for volume rendering
Microsoft::WRL::ComPtr<ID3D11Buffer> m_volumeEntryConstantBuffer;
Microsoft::WRL::ComPtr<ID3D11Texture3D> m_volumeStagingTexture;
Microsoft::WRL::ComPtr<ID3D11Texture3D> m_volumeTexture;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_volumeSRV;
Microsoft::WRL::ComPtr<ID3D11SamplerState> m_samplerState;
// Cached D3D resources for left and right eye position calculation
ID3D11Texture2D* m_frontPositionTextureArray;
ID3D11Texture2D* m_backPositionTextureArray;
ID3D11RenderTargetView* m_frontPositionRTV;
ID3D11RenderTargetView* m_backPositionRTV;
ID3D11ShaderResourceView* m_frontPositionSRV;
ID3D11ShaderResourceView* m_backPositionSRV;
// Transfer function GPU resources
Microsoft::WRL::ComPtr<ID3D11Buffer> m_opacityLookupTableBuffer;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_opacityLookupTableSRV;
std::atomic_bool m_tfResourcesReady = false;
// Transfer function CPU resources
mutable std::mutex m_opacityTFMutex;
TransferFunctionType m_opacityTFType = TransferFunction_Unknown;
BaseTransferFunction* m_opacityTransferFunction = nullptr;
// CPU resources for volume rendering
VolumeEntryConstantBuffer m_constantBuffer;
UWPOpenIGTLink::VideoFrame^ m_frame;
UWPOpenIGTLink::VideoFrame^ m_onGPUFrame;
mutable std::mutex m_imageAccessMutex;
float m_stepScale = 1.f; // Increasing this reduces the number of steps taken per pixel
// State
mutable std::atomic_bool m_isInFrustum = false;
mutable uint64 m_frustumCheckFrameNumber = 0;
uint64 m_token = 0;
std::atomic_bool m_showing = true;
std::atomic_bool m_entryReady = false;
std::atomic_bool m_volumeReady = false;
std::atomic_bool m_volumeUpdateNeeded = false;
// Constants relating to volume entry behavior
static const float LERP_RATE;
};
}
}
|
#include <iostream>
#include <vector>
#include <unordered_map>
#include <set>
/*
* `track` runs O(n) and `get_rank_of_number` runs O(1)
*
* instead `track` could run O(1) and `get_rank_of_number` could run O(n)
*
* The book provides a solution where `track` runs in O(log(n))
* and `get_rank_of_number` runs in O(log(n))
*
* This solution isn't necessarily more optimal than my suggestions, but
* it should have been noted as an option
*
*/
using namespace std;
class RankState {
private:
unordered_map<int, int> count {};
unordered_map<int, int> acc_count {};
public:
void track(int n) {
++count[n];
acc_count[n] = count[n];
for (auto pr = count.begin(); pr != count.end(); ++pr) {
if (n < pr->first) {
++acc_count[pr->first];
} else if (n > pr->first) {
acc_count[n] += pr->second;
}
}
}
int get_rank_of_number(int n) {
return acc_count[n] - 1;
}
};
void rank_from_stream(const vector<int>& stream) {
RankState state {};
for (auto i : stream) {
state.track(i);
cout << "Rank of (" << i << "):\t"
<< state.get_rank_of_number(i) << endl;
}
cout << endl;
for (auto i : stream) {
cout << "Rank of (" << i << "):\t"
<< state.get_rank_of_number(i) << endl;
}
}
int main() {
// rank_from_stream({1, 3, 1});
rank_from_stream({5, 1, 4, 4, 5, 9, 7, 13, 3});
}
|
#pragma once
#include <stdexcept>
#include <winerror.h>
#include <string>
namespace WPD {
class WPDException : public std::runtime_error {
HRESULT c;
public:
WPDException(HRESULT code, const char *str);
WPDException(HRESULT code, const std::string &str);
HRESULT code() const;
#ifdef UNICODE
std::wstring explain() const;
#else
std::string explain() const;
#endif
};
}
|
#include <QApplication>
#include <QPixmap>
#include "gamecontroller.h"
GameController *game;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
//GameController is started!
game = new GameController();
game->Start();
game->mainmenuScreen->wallpaper();
//MainMenu w;
//w.show();
return a.exec();
}
|
#include<cstring>
#include<cstdio>
#include<iostream>
using namespace std;
const BASE=1000000;
char a[1010]
{int b;
while (cin >> a >> b)
{int len = strlen(a),ans = 1;
int n = (len - 1)/6 +1
for (int i = 1;i >= ; i++)
sscanf()
}
return 0;
}
|
#include <iostream>
#include "BLOCKCHAIN.h"
int main()
{
BlockChain Chain = BlockChain();
std::cout<<"Mining first block...."<<std::endl;
Chain.AddBlock(Block(1,"Block 1"));
std::cout<<"Mining second block...."<<std::endl;
Chain.AddBlock(Block(2,"Block 2"));
std::cout<<"Mining third block...."<<std::endl;
Chain.AddBlock(Block(3,"Block 3"));
return 0;
}
|
#include <iostream>
#include <cstring>
using namespace std;
struct xinxi
{
char name[20];
int yu,shu,wai,sum,ci;
};
int main()
{
int n,i,j,t,q;
xinxi stu[1024];
cin >> n;
for(i=0;i<n;i++)
{
cin >> stu[i].name >> stu[i].yu >> stu[i].shu >> stu[i].wai;
stu[i].sum=stu[i].yu+stu[i].shu+stu[i].wai;
stu[i].ci=i+1;
}
cin >> q;
for(i=0;i<n;i++)
for(j=0;j<n-i-1;j++)
{
if(stu[j].sum<stu[j+1].sum){t=stu[j].ci;stu[j].ci=stu[j+1].ci;stu[j+1].ci=t;}
else if(stu[j].sum==stu[j+1].sum&&stu[j].yu<stu[j+1].yu){t=stu[j].ci;stu[j].ci=stu[j+1].ci;stu[j+1].ci=t;}
else if(stu[j].sum==stu[j+1].sum&&stu[j].yu==stu[j+1].yu&&stu[j].shu<stu[j+1].shu){t=stu[j].ci;stu[j].ci=stu[j+1].ci;stu[j+1].ci=t;}
else if(stu[j].sum==stu[j+1].sum&&stu[j].yu==stu[j+1].yu&&stu[j].shu==stu[j+1].shu&&strcmp(stu[j].name,stu[j+1].name)>0){t=stu[j].ci;stu[j].ci=stu[j+1].ci;stu[j+1].ci=t;}
}
for(i=0;i<n;i++)
if(stu[i].ci==q)cout << stu[i].name << " " << stu[i].sum;
return 0;
}
|
#ifndef SECURE_SOCKET_HPP
#define SECURE_SOCKET_HPP
#include <boost/asio/ssl/stream.hpp>
#include <boost/asio/ssl/context.hpp>
#include "socket.hpp"
namespace sp
{
class secure_socket: public socket
{
public:
secure_socket(boost::asio::io_service& ios);
virtual void async_connect(const acceptor::endpoint_type& peer_endpoint, connect_handler handler);
virtual void async_accept(acceptor& acc, acceptor::endpoint_type& remote_ep, accept_handler handler);
virtual void async_read_some(const boost::asio::mutable_buffers_1& buffers, read_handler handler);
virtual void async_write_some(const boost::asio::const_buffers_1& buffers, write_handler handler);
virtual void cancel(boost::system::error_code& ec);
virtual void shutdown(boost::system::error_code& ec);
virtual void close(boost::system::error_code& ec);
private:
void handle_connect(const boost::system::error_code& ec, connect_handler h);
void handle_accept(const boost::system::error_code& ec, accept_handler h);
boost::asio::ssl::context ctxt_;
boost::asio::ssl::stream<boost::asio::ip::tcp::socket> ssl_strm_;
};
}
#endif // SECURE_SOCKET_HPP
|
#ifndef _TAG_POSITIONS_H_
#define _TAG_POSITIONS_H_
#include "server/rfidPositionerHeader.h"
#include <map>
#include <vector>
#include <math.h>
const int TAG_ID_MAX_SIZE = 16; //the maximum length of the tag id string
const double PI = 3.14159265358979323846;
const double PROBABILITY_OUTSIDE_MODEL = 0;
//ANTENNA POSITIONS PARAMETERS
// - NUMBER_OF_ANTENNAS -> the number of antennas present on the robot
// - the only other important structure is the ANTENNA_POSITIONS array that describes the positions of the antenna centers relative to the center of the robot (the angles are relative to the forward direction)
// - in our case, we use 2 auxiliary structures to describe these positions, since the robot has radial symmetry:
// - ANTENNA_POSITION_RADIUS - the radius of the circle on which all antenna centers lie
// - ANTENNA_POSITION_ANGLES - the angles that each center is viewed on from the center of the robot relative to the forward direction
const int NUMBER_OF_ANTENNAS = 8;
// TODO --> Determine antenna Positions take care with orientations
double const ANTENNA_POSITION_RADIUS = 0.35;
double const ANTENNA_POSITION_ANGLES[] = {4*PI/4,
3*PI/4,
2*PI/4,
1*PI/4,
0*PI/4,
7*PI/4,
6*PI/4,
5*PI/4
};
//a structure describing a point (x,y) in 2D
typedef struct Point2D {
double x;
double y;
Point2D(double _x, double _y){
x=_x;
y=_y;
}
Point2D(){
x=0;
y=0;
}
} Point2D;
//a structure describing a tag (x,y,id)
typedef struct Tag2D {
double x;
double y;
char tagid[TAG_ID_MAX_SIZE+1];
Tag2D (double _x, double _y, const char* _tagid){
x=_x;
y=_y;
for(unsigned int i=0;i<strlen(_tagid);++i) {
tagid[i] = _tagid[i];
}
tagid[TAG_ID_MAX_SIZE] = 0;
}
Tag2D(){x=0;
y=0;
tagid[0] = 0;
}
} Tag2D;
//a structure describing a possible tag detection (antenna,probability of detection,tag_id)
typedef struct TagDetection {
int antenna;
char tagid[TAG_ID_MAX_SIZE+1];
TagDetection* next;
TagDetection(int _antenna, const char* _tagid ,TagDetection* _next) {
antenna = _antenna;
next = _next;
for (unsigned int i=0;i<strlen(_tagid);++i) {
tagid[i] = _tagid[i];
}
tagid[TAG_ID_MAX_SIZE] = 0;
}
TagDetection() {
antenna = -1;
tagid[0]=0;
next = NULL;
}
} TagDetection;
//a structure describing a tag expectation (antenna,probability of detection,tag_id)
typedef struct TagExpectation {
int antenna;
double probability;
char tagid[TAG_ID_MAX_SIZE+1];
TagExpectation* next;
TagExpectation(int _antenna, double _probability, const char* _tagid,TagExpectation* _next) {
antenna = _antenna;
probability = _probability;
next = _next;
for (unsigned int i=0;i<strlen(_tagid);++i) {
tagid[i] = _tagid[i];
}
tagid[TAG_ID_MAX_SIZE] = 0;
}
TagExpectation() {
antenna = -1;
probability = 0;
tagid[0]=0;
next = NULL;
}
} TagExpectation;
int tagNumber(const char* tagName);
struct strCmp {
bool operator()( const char* s1, const char* s2 ) const {
return strcmp( s1, s2 ) < 0;
}
};
//a map that allows us to recover a tag (position) by id
typedef std::map<const char*, Point2D, strCmp> TagMap;
//a vector that will index the tags in ascending order according to position
typedef std::vector<Tag2D> Tag2DVector;
//all function descriptions are in the .cc file
TagMap initTagMap();
Tag2DVector initTag2DVector(TagMap);
// force angle representation to (-PI,PI]
double angleWrap(double angle);
void getTagDetections(TagDetection** tagDetections, RFID_TAGLIST_POSTER_STR* rfidPoster);
void freeTagDetection(TagDetection* tagDetections);
void freeTagExpectation(TagExpectation* tagsExpected);
//#define BOGDANMODEL
#ifdef BOGDANMODEL
//SENSOR MODEL PARAMETERS
// - SENSOR_SIZE -> describes the size of the matrix describing the sensor model (the matrix is square of (2*SENSOR_SIZE-1) size)
// - SENSOR_SIZE_LENGTH -> the length (in meters) corresponding to SENSOR_SIZE cells of the sensor model matrix
// - PROBABILITY_OUTSIDE_MODEL -> the probability of detecting a tag outside the sensor model
const int SENSOR_SIZE = 100;
const double SENSOR_SIZE_LENGTH = 4;
//ANTENNA POSITIONS PARAMETERS
// - NUMBER_OF_ANTENNAS -> the number of antennas present on the robot
// - the only other important structure is the ANTENNA_POSITIONS array that describes the positions of the antenna centers relative to the center of the robot (the angles are relative to the forward direction)
// - in our case, we use 2 auxiliary structures to describe these positions, since the robot has radial symmetry:
// - ANTENNA_POSITION_RADIUS - the radius of the circle on which all antenna centers lie
// - ANTENNA_POSITION_ANGLES - the angles that each center is viewed on from the center of the robot relative to the forward direction
double const ANTENNA_POSITIONS[][3] = {
{ANTENNA_POSITION_RADIUS*cos(ANTENNA_POSITION_ANGLES[0]),
ANTENNA_POSITION_RADIUS*sin(ANTENNA_POSITION_ANGLES[0]),
ANTENNA_POSITION_ANGLES[0]
},
{ANTENNA_POSITION_RADIUS*cos(ANTENNA_POSITION_ANGLES[1]),
ANTENNA_POSITION_RADIUS*sin(ANTENNA_POSITION_ANGLES[1]),
ANTENNA_POSITION_ANGLES[1]
},
{ANTENNA_POSITION_RADIUS*cos(ANTENNA_POSITION_ANGLES[2]),
ANTENNA_POSITION_RADIUS*sin(ANTENNA_POSITION_ANGLES[2]),
ANTENNA_POSITION_ANGLES[2]
},
{ANTENNA_POSITION_RADIUS*cos(ANTENNA_POSITION_ANGLES[3]),
ANTENNA_POSITION_RADIUS*sin(ANTENNA_POSITION_ANGLES[3]),
ANTENNA_POSITION_ANGLES[3]
},
{ANTENNA_POSITION_RADIUS*cos(ANTENNA_POSITION_ANGLES[4]),
ANTENNA_POSITION_RADIUS*sin(ANTENNA_POSITION_ANGLES[4]),
ANTENNA_POSITION_ANGLES[4]
},
{ANTENNA_POSITION_RADIUS*cos(ANTENNA_POSITION_ANGLES[5]),
ANTENNA_POSITION_RADIUS*sin(ANTENNA_POSITION_ANGLES[5]),
ANTENNA_POSITION_ANGLES[5]
},
{ANTENNA_POSITION_RADIUS*cos(ANTENNA_POSITION_ANGLES[6]),
ANTENNA_POSITION_RADIUS*sin(ANTENNA_POSITION_ANGLES[6]),
ANTENNA_POSITION_ANGLES[6]
},
{ANTENNA_POSITION_RADIUS*cos(ANTENNA_POSITION_ANGLES[7]),
ANTENNA_POSITION_RADIUS*sin(ANTENNA_POSITION_ANGLES[7]),
ANTENNA_POSITION_ANGLES[7]
}
};
void initSensorModel(double sensorModel[NUMBER_OF_ANTENNAS][2*SENSOR_SIZE+1][2*SENSOR_SIZE+1],const char* basicModelFile);
int getExpectedTagDetections(TagExpectation** tagExpectation,
double x, double y, double theta,
double sensorModel[NUMBER_OF_ANTENNAS][2*SENSOR_SIZE+1][2*SENSOR_SIZE+1],
Tag2DVector tags
);
#else // #ifdef BOGDANMODEL
// CHOOSE ONE AND ONLY ONE OF THE THREE!!
//#define GEOMETRICALMODEL
//#define FILEMODELCENTERED
#define FILEMODELPOLAR
#ifdef GEOMETRICALMODEL
//MODELCONSIDERATIONS international measurements system
// TODO : APROXIMATE BETTER!
#define MINOR_RADIUS 1
#define ARC_ANGLE 1.65806278939461 // 95 degrees
#define ARC_RADIUS 5
#define MAJOR_RADIUS 10
#define PROB_INSIDE_LITTLE_CIRCLE 0.7
#define PROB_INSIDE_ARC 0.9
#define PROB_INSIDE_BIG_CIRCLE 0.5
#elif defined FILEMODELCENTERED
const char SENSOR_BASE_MODEL[] = "~/sensor_base_model_C.in";
void initSensorModel();
#elif defined FILEMODELPOLAR
const char SENSOR_BASE_MODEL[] = "/simulation/sensor_base_model_P.in";
void initSensorModel();
#else
#error "NO TYPE OF MODEL DEFINED"
#endif
int getExpectedTagDetections(TagExpectation** tagsExpected,
double x, double y, double theta,
Tag2DVector tags
);
#endif // #ifdef BOGDANMODEL
#endif // _TAG_POSITIONS_H_
|
#include <stdio.h>
#include <iostream>
using namespace std;
int main(void)
{
int ways = 0;
int coin_size = 200;
int a, b, c, d, e, f, g;
for (a = 0; a <= coin_size; a += 200)
for (b = 0; b <= coin_size; b += 100)
for (c = 0; c <= coin_size; c += 50)
for (d = 0; d <= coin_size; d += 20)
for (e = 0; e <= coin_size; e += 10)
for (f = 0; f <= coin_size; f += 5)
for (g = 0; g <= coin_size; g += 2)
if (a+b+c+d+e+f+g <= 200)
ways++;
cout << "Ways to make change = "<< ways << "\n" << endl;
return 0;
}
|
#include "stdafx.h"
#include "MonsterBox.h"
#include "../GameData.h"
#include <memory>
#include <fstream>
#include <cmath>
bool MonsterBox::isGot(MonsterID id) {
LoadMyBox();
if (m_monsters[id])
return true;
else
return false;
//if(m_monsters % id == 0)
/*int flagnum[enNumMonster];
int mons = m_monsters;
for (int i = 0; i < enNumMonster; i++) {
flagnum[i] = mons % 10;
mons /= 10;
}
if (flagnum[id] != 0)
return true;
return false;*/
}
void MonsterBox::GetMonster(MonsterID id) {
using namespace std;
LoadMyBox();
m_monsters[id] = 1;
ofstream fout;
fout.open("Assets/saveData/monsterbox.mbx", ios::out or ios::binary);
for (int i = 0; i < enNumMonster; i++) {
fout.write((char*)&m_monsters[i], sizeof(int));
}
fout.close();
/*int x = std::pow(10, static_cast<int>(id));
int flagnum[enNumMonster];
int mons = m_monsters;
for (int i = 0; i < enNumMonster; i++) {
flagnum[i] = mons % 10;
mons /= 10;
}
if (flagnum[id] == 0)
m_monsters += x;
WriteFile(m_monsters);*/
}
void MonsterBox::initFile() {
using namespace std;
ofstream fout;
fout.open("Assets/saveData/monsterbox.mbx", ios::out | ios::binary | ios::trunc);
int n = 0;
int y = 1;
for (int i = 0; i < enNumMonster; i++) {
if (i == MonsterID::enUmataur || i == MonsterID::enFairy)
fout.write((char*)& y, sizeof(int));
else
fout.write((char*)&n, sizeof(int));
//fout << 0;
}
fout.close();
}
void MonsterBox::LoadMyBox() {
using namespace std;
ifstream fin("Assets/saveData/monsterbox.mbx", ios::in | ios::binary);
if (!fin) {
OutputDebugStringA("monsterbox.mbxのオープンに失敗しました\n");
for (int i = 0; i < enNumMonster; i++) {
m_monsters[i] = 0;
}
initFile();
LoadMyBox();
return;
}
for (int i = 0; i < enNumMonster; i++) {
fin.read((char *)&m_monsters[i], sizeof(int));
}
fin.close();
}
|
#include "leftlpiece.h"
namespace
{
std::vector<TetrisCoordinate> buildCoordinates(
const TetrisCoordinate& centerCoordinate, int orientation)
{
switch (orientation)
{
case 0:
return { centerCoordinate, centerCoordinate.plusRows(1),
centerCoordinate.plusRows(2), centerCoordinate.plusRowsAndColumns(2, -1) };
case 1:
return { centerCoordinate, centerCoordinate.plusColumns(1),
centerCoordinate.plusColumns(2), centerCoordinate.plusRowsAndColumns(1, 2) };
case 2:
return { centerCoordinate, centerCoordinate.plusRows(-1),
centerCoordinate.plusRows(-2), centerCoordinate.plusRowsAndColumns(-2, 1) };
default:
return { centerCoordinate, centerCoordinate.plusColumns(-1),
centerCoordinate.plusColumns(-2), centerCoordinate.plusRowsAndColumns(-1, -2) };
}
}
}
LeftLPiece::LeftLPiece(
const TetrisCoordinate& centerCoordinate,
int orientation) :
AbstractTetrisPiece(
centerCoordinate, orientation,
buildCoordinates(centerCoordinate, orientation))
{
}
TetrisConstants::TetrisCellColor LeftLPiece::color() const
{
return TetrisConstants::CELL_LIGHTGRAY;
}
int LeftLPiece::numOrientations() const
{
return 4;
}
|
#include <fstream>
#include "mp23_1_opt.h"
int main() {
ofstream in_pix("input_pixels_regression_result_mp23_1_opt.txt");
ofstream fout("regression_result_mp23_1_opt.txt");
HWStream<hw_uint<32> > in_update_0_read;
HWStream<hw_uint<32> > mp23_1_update_0_write;
// Loading input data
// cmap : { in_update_0[root = 0, in_0, in_1, in_2] -> in_oc[0, 0] : 0 <= in_0 <= 127 and 0 <= in_1 <= 127 and 0 <= in_2 <= 63 }
// read map: { in_oc[0, 0] -> in_update_0[root = 0, in_0, in_1, in_2] : 0 <= in_0 <= 127 and 0 <= in_1 <= 127 and 0 <= in_2 <= 63 }
// rng : { in_update_0[root = 0, in_0, in_1, in_2] : 0 <= in_0 <= 127 and 0 <= in_1 <= 127 and 0 <= in_2 <= 63 }
for (int i = 0; i < 1048576; i++) {
hw_uint<32> in_val;
set_at<0*32, 32, 32>(in_val, 1*i + 0);
in_pix << in_val << endl;
in_update_0_read.write(in_val);
}
mp23_1_opt(in_update_0_read, mp23_1_update_0_write);
for (int i = 0; i < 262144; i++) {
hw_uint<32> actual = mp23_1_update_0_write.read();
auto actual_lane_0 = actual.extract<0*32, 31>();
fout << actual_lane_0 << endl;
}
in_pix.close();
fout.close();
return 0;
}
|
// Created on: 1993-06-17
// Created by: Jean Yves LEBEY
// Copyright (c) 1993-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _TopOpeBRepDS_HeaderFile
#define _TopOpeBRepDS_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <TopAbs_State.hxx>
#include <TopOpeBRepDS_Kind.hxx>
#include <TCollection_AsciiString.hxx>
#include <TopAbs_ShapeEnum.hxx>
#include <TopAbs_Orientation.hxx>
#include <TopOpeBRepDS_Config.hxx>
class TCollection_AsciiString;
//! This package provides services used by the TopOpeBRepBuild
//! package performing topological operations on the BRep
//! data structure.
class TopOpeBRepDS
{
public:
DEFINE_STANDARD_ALLOC
//! IN OU ON UN
Standard_EXPORT static TCollection_AsciiString SPrint (const TopAbs_State S);
Standard_EXPORT static Standard_OStream& Print (const TopAbs_State S, Standard_OStream& OS);
//! <K>
Standard_EXPORT static TCollection_AsciiString SPrint (const TopOpeBRepDS_Kind K);
//! S1(<K>,<I>)S2
Standard_EXPORT static TCollection_AsciiString SPrint (const TopOpeBRepDS_Kind K, const Standard_Integer I, const TCollection_AsciiString& B = "", const TCollection_AsciiString& A = "");
Standard_EXPORT static Standard_OStream& Print (const TopOpeBRepDS_Kind K, Standard_OStream& S);
Standard_EXPORT static Standard_OStream& Print (const TopOpeBRepDS_Kind K, const Standard_Integer I, Standard_OStream& S, const TCollection_AsciiString& B = "", const TCollection_AsciiString& A = "");
Standard_EXPORT static TCollection_AsciiString SPrint (const TopAbs_ShapeEnum T);
//! (<T>,<I>)
Standard_EXPORT static TCollection_AsciiString SPrint (const TopAbs_ShapeEnum T, const Standard_Integer I);
Standard_EXPORT static Standard_OStream& Print (const TopAbs_ShapeEnum T, const Standard_Integer I, Standard_OStream& S);
Standard_EXPORT static TCollection_AsciiString SPrint (const TopAbs_Orientation O);
Standard_EXPORT static TCollection_AsciiString SPrint (const TopOpeBRepDS_Config C);
Standard_EXPORT static Standard_OStream& Print (const TopOpeBRepDS_Config C, Standard_OStream& S);
Standard_EXPORT static Standard_Boolean IsGeometry (const TopOpeBRepDS_Kind K);
Standard_EXPORT static Standard_Boolean IsTopology (const TopOpeBRepDS_Kind K);
Standard_EXPORT static TopAbs_ShapeEnum KindToShape (const TopOpeBRepDS_Kind K);
Standard_EXPORT static TopOpeBRepDS_Kind ShapeToKind (const TopAbs_ShapeEnum S);
};
#endif // _TopOpeBRepDS_HeaderFile
|
#include "comn.h"
#include "afxdao.h"
#pragma warning( disable : 4995 )
using namespace std;
//将实况插入数据库
bool insertDB(const char *dbname,const char * table, COleDateTime datet,vector<double> &vals)
{
CDaoDatabase daoDb;
COleVariant OleV1,OleV2 ;//日期和数值字段
try
{
daoDb.Open(dbname,0,0,";PWD=1234%hnyl@20070701%"); //打开数据库
CDaoRecordset Record(&daoDb) ; //构造记录集
CString Sql = "SELECT * FROM ";
CString SqlW;
SqlW.Format(" WHERE date= #%s# ",datet.Format("%Y-%m-%d") );
Record.Open ( dbOpenDynaset, Sql+table+SqlW+" ORDER BY date" ) ; //初始化记录集
if(!Record.IsOpen())
return false;
OleV1 = datet;
bool isfind = (Record.GetRecordCount()>0);
//cout<<Record.GetRecordCount()<<" "<<Record.GetAbsolutePosition();
if(isfind) //找到后修改
{
Record.Edit();
}
else //没找到添加
{
Record.AddNew ();
}
Record.SetFieldValue(1,OleV1);
for(int i=0;i<9;++i)
{
OleV2 = vals[i];
Record.SetFieldValue(i+2,OleV2);
}
//
//cout<<"\r \r";
//cout<<"已完成: "<< 100.0*(j*n+i+1)/(m*n)<<"%";
//cout<<date<<" "<<names[i]<<" "<<vals[i][j]<<endl;
Record.Update(); //更新数据
}
catch(CDaoException *e)
{
cout<<(e->m_pErrorInfo->m_strDescription).GetBuffer()<<endl;
e->Delete();
AfxDaoTerm(); //
return false;
}
daoDb.Close(); //关闭数据库
AfxDaoTerm(); //
return true;
}
void readVal()
{
string name="files/XQZL.csv_format.txt";
//cout<<"Input the text name:";
//cin>>name;
ifstream fin(name.c_str());
vector<double> vals(9,0);
COleDateTime datet(2008,6,1,0,0,0);
CString datestr;
string s,sline;
getline(fin,s);
while(getline(fin,sline))
{
istringstream ssin(sline);
ssin>>s;
while( s != datet.Format("%m/%d/%y").GetBuffer() )
{
datet += COleDateTimeSpan(1,0,0,0);
}
for(int i=0;i<9;++i)
{
ssin>>s;
}
for(int i=0;i<9;++i)
{
ssin>>vals[i];
}
insertDB("files/rain-temph.mdb","min_temph",datet,vals);
datet += COleDateTimeSpan(1,0,0,0);
}
cout<<"数据处理完毕"<<endl;
}
bool read_from_db(const char *dbname,const char * sql_statement, double &val)
{
CDaoDatabase daoDb;
COleVariant OleV1;
try
{
daoDb.Open(dbname,0,0,";PWD=271828"); //打开数据库
CDaoRecordset Record(&daoDb); //构造记录集
Record.Open (dbOpenDynaset, sql_statement) ; //初始化记录集
if(!Record.IsOpen())
return false;
if(Record.GetRecordCount()<1)
return false;
Record.MoveFirst();
Record.GetFieldValue(0,OleV1);
val = OleV1.dblVal;
}
catch(CDaoException *e)
{
cout<<(e->m_pErrorInfo->m_strDescription).GetBuffer()<<endl;
e->Delete();
AfxDaoTerm(); //
return false;
}
daoDb.Close(); //关闭数据库
AfxDaoTerm(); //
return true;
}
|
#include <engine/vox.h>
#include <core/platform.h>
u32 vox_default_palette[256] = {
0x00000000, 0xffffffff, 0xffccffff, 0xff99ffff, 0xff66ffff, 0xff33ffff, 0xff00ffff, 0xffffccff, 0xffccccff, 0xff99ccff, 0xff66ccff, 0xff33ccff, 0xff00ccff, 0xffff99ff, 0xffcc99ff, 0xff9999ff,
0xff6699ff, 0xff3399ff, 0xff0099ff, 0xffff66ff, 0xffcc66ff, 0xff9966ff, 0xff6666ff, 0xff3366ff, 0xff0066ff, 0xffff33ff, 0xffcc33ff, 0xff9933ff, 0xff6633ff, 0xff3333ff, 0xff0033ff, 0xffff00ff,
0xffcc00ff, 0xff9900ff, 0xff6600ff, 0xff3300ff, 0xff0000ff, 0xffffffcc, 0xffccffcc, 0xff99ffcc, 0xff66ffcc, 0xff33ffcc, 0xff00ffcc, 0xffffcccc, 0xffcccccc, 0xff99cccc, 0xff66cccc, 0xff33cccc,
0xff00cccc, 0xffff99cc, 0xffcc99cc, 0xff9999cc, 0xff6699cc, 0xff3399cc, 0xff0099cc, 0xffff66cc, 0xffcc66cc, 0xff9966cc, 0xff6666cc, 0xff3366cc, 0xff0066cc, 0xffff33cc, 0xffcc33cc, 0xff9933cc,
0xff6633cc, 0xff3333cc, 0xff0033cc, 0xffff00cc, 0xffcc00cc, 0xff9900cc, 0xff6600cc, 0xff3300cc, 0xff0000cc, 0xffffff99, 0xffccff99, 0xff99ff99, 0xff66ff99, 0xff33ff99, 0xff00ff99, 0xffffcc99,
0xffcccc99, 0xff99cc99, 0xff66cc99, 0xff33cc99, 0xff00cc99, 0xffff9999, 0xffcc9999, 0xff999999, 0xff669999, 0xff339999, 0xff009999, 0xffff6699, 0xffcc6699, 0xff996699, 0xff666699, 0xff336699,
0xff006699, 0xffff3399, 0xffcc3399, 0xff993399, 0xff663399, 0xff333399, 0xff003399, 0xffff0099, 0xffcc0099, 0xff990099, 0xff660099, 0xff330099, 0xff000099, 0xffffff66, 0xffccff66, 0xff99ff66,
0xff66ff66, 0xff33ff66, 0xff00ff66, 0xffffcc66, 0xffcccc66, 0xff99cc66, 0xff66cc66, 0xff33cc66, 0xff00cc66, 0xffff9966, 0xffcc9966, 0xff999966, 0xff669966, 0xff339966, 0xff009966, 0xffff6666,
0xffcc6666, 0xff996666, 0xff666666, 0xff336666, 0xff006666, 0xffff3366, 0xffcc3366, 0xff993366, 0xff663366, 0xff333366, 0xff003366, 0xffff0066, 0xffcc0066, 0xff990066, 0xff660066, 0xff330066,
0xff000066, 0xffffff33, 0xffccff33, 0xff99ff33, 0xff66ff33, 0xff33ff33, 0xff00ff33, 0xffffcc33, 0xffcccc33, 0xff99cc33, 0xff66cc33, 0xff33cc33, 0xff00cc33, 0xffff9933, 0xffcc9933, 0xff999933,
0xff669933, 0xff339933, 0xff009933, 0xffff6633, 0xffcc6633, 0xff996633, 0xff666633, 0xff336633, 0xff006633, 0xffff3333, 0xffcc3333, 0xff993333, 0xff663333, 0xff333333, 0xff003333, 0xffff0033,
0xffcc0033, 0xff990033, 0xff660033, 0xff330033, 0xff000033, 0xffffff00, 0xffccff00, 0xff99ff00, 0xff66ff00, 0xff33ff00, 0xff00ff00, 0xffffcc00, 0xffcccc00, 0xff99cc00, 0xff66cc00, 0xff33cc00,
0xff00cc00, 0xffff9900, 0xffcc9900, 0xff999900, 0xff669900, 0xff339900, 0xff009900, 0xffff6600, 0xffcc6600, 0xff996600, 0xff666600, 0xff336600, 0xff006600, 0xffff3300, 0xffcc3300, 0xff993300,
0xff663300, 0xff333300, 0xff003300, 0xffff0000, 0xffcc0000, 0xff990000, 0xff660000, 0xff330000, 0xff0000ee, 0xff0000dd, 0xff0000bb, 0xff0000aa, 0xff000088, 0xff000077, 0xff000055, 0xff000044,
0xff000022, 0xff000011, 0xff00ee00, 0xff00dd00, 0xff00bb00, 0xff00aa00, 0xff008800, 0xff007700, 0xff005500, 0xff004400, 0xff002200, 0xff001100, 0xffee0000, 0xffdd0000, 0xffbb0000, 0xffaa0000,
0xff880000, 0xff770000, 0xff550000, 0xff440000, 0xff220000, 0xff110000, 0xffeeeeee, 0xffdddddd, 0xffbbbbbb, 0xffaaaaaa, 0xff888888, 0xff777777, 0xff555555, 0xff444444, 0xff222222, 0xff111111
};
struct VoxReader {
u8 *start_ptr;
u8 *reader_ptr;
u64 size;
VoxModel result_model;;
void init(u8 *data, u64 data_size) {
start_ptr = data;
reader_ptr = data;
size = data_size;
result_model.palette = vox_default_palette;
}
s32 readInt() {
s32 result = *(s32 *)reader_ptr;
reader_ptr += 4;
return result;
}
u8 readByte() {
u8 result = *reader_ptr;
reader_ptr += 1;
return result;
}
bool readIDString(char *str) {
bool result = true;
for(int i = 0; i < 4; i++) {
if(reader_ptr[i] != str[i]) {
result = false;
break;
}
}
reader_ptr += 4;
return result;
}
bool canRead() {
return (u64)reader_ptr - (u64)start_ptr < size;
}
ChunkType readChunkType() {
return (ChunkType)readInt();
}
void readChunk(Platform *platform) {
ChunkType chunk_type = readChunkType();
printf("Found %s chunk\n", getStrFromEnumValue(chunk_type));
s32 contents_size = readInt();
s32 children_size = readInt();
if(contents_size > 0) {
switch(chunk_type) {
case ChunkType::Size: {
s32 size_x = readInt();
s32 size_y = readInt();
s32 size_z = readInt();
result_model.size = Vec3(size_x, size_y, size_z);
} break;
case ChunkType::Xyzi: {
s32 voxel_count = readInt();
result_model.voxels = (Voxel *)platform->alloc(sizeof(Voxel) * voxel_count);
memcpy(result_model.voxels, reader_ptr, sizeof(Voxel) * voxel_count);
result_model.voxel_count = voxel_count;
reader_ptr += voxel_count * 4;
} break;
case ChunkType::Rgba: {
u32 palette_size = sizeof(u32) * 256;
u32 *palette = (u32 *)platform->alloc(palette_size);
memcpy(palette, reader_ptr, palette_size);
reader_ptr += palette_size;
} break;
default: {
reader_ptr += contents_size;
};
}
}
if(children_size > 0) readChunk(platform);
}
};
VoxModel loadVoxFileFromMemory(Platform *platform, u8 *data, u64 data_size) {
VoxReader reader = {};
reader.init(data, data_size);
if(reader.readIDString("VOX ")) {
s32 version = reader.readInt();
if(version != 150) {
printf("Vox file is version %d, but we only support version 150\n", version);
}
while(reader.canRead()) {
reader.readChunk(platform);
}
} else {
printf("Unable to read vox file\n");
}
return reader.result_model;
}
VoxModel loadVoxFromFile(Platform *platform, char *file_path) {
FileData vox_file = platform->readEntireFile(file_path);
VoxModel result = loadVoxFileFromMemory(platform, (u8 *)vox_file.contents, vox_file.size);
platform->free(vox_file.contents);
return result;
}
|
#pragma once
#include "GlutHeader.h"
class Point2
{
public:
float axis[2];
Point2(float, float);
Point2(float*);
Point2();
~Point2();
float Distance(Point2);
float operator * (Point2);
Point2 operator * (float);
Point2 operator + (Point2);
bool operator == (Point2);
Point2 operator - (Point2);
float GetCosTheta(Point2);
Point2 Rotate(Point2, float);
void Print();
};
#define ORIGINAL_POINT_2 (Point2(0, 0))
|
#ifndef _ZONEMANAGER_H_
#define _ZONEMANAGER_H_
#include <map>
#include "Zone.h"
#ifdef BOT_LOGIC_DEBUG_MAP
#define BOT_LOGIC_ZONE_LOG(logger, text, autoEndLine) logger.Log(text, autoEndLine)
#else
#define BOT_LOGIC_ZONE_LOG(logger, text, autoEndLine) 0
#endif
class ZoneManager
{
public:
ZoneManager(const ZoneManager &) = delete;
ZoneManager &operator=(const ZoneManager&) = delete;
~ZoneManager();
static ZoneManager &get()
{
return m_instance;
}
Zone *getZone(unsigned int zoneId) const;
Zone *addZone();
void addZone(Zone *zone);
void updateZones();
void updateFromTile(Node* currentTile);
bool addJunction(unsigned firstZone, unsigned secondZone, ObjectRef object);
size_t getZoneCount() const;
const Zone::Junction &getJunctionBetween(unsigned int from, unsigned int to);
// Set the logger path and initialise all map logger
void setLoggerPath(const std::string &a_path);
private:
static ZoneManager m_instance;
unsigned int m_zoneCount;
std::set<Node*> m_done;
std::vector<Node*> m_toDo;
std::map<unsigned int, Zone*> m_zones;
Logger m_logger;
ZoneManager();
};
#endif // !_ZONEMANAGER_H_
|
#include "l10n/LocaleManager.h"
using namespace BeeeOn;
LocaleManager::~LocaleManager()
{
}
|
/********************************************************
CS200 Lab 4
Draw-Graph Implementation File
Writen by : Denise Byrnes
Modified by: Khoa Ngyuen, Eifu Tomita, Avi Vajpeyi
Purpose : Here we imlement the various functions that
are required to create the graphs, and the functions that
traverse the biderectional list to create the path of the
maze.
********************************************************/
#include "DrawGraph.h"
#include <iostream>
#include <algorithm>
using namespace std;
//Debug: dump graph for inspection
void DrawGraph::printGraph(){
for(int j = 0; j < adjList.size(); j++){
vector<int> temp = adjList[j];
cout<< j << ": ";
for(int i = 0; i < temp.size(); i++) {
int val = temp[i];
cout<< val << " ";
}
cout<<endl;
}
}
void DrawGraph::printGraph2(){
for(int j = 0; j < udGraph.size(); j++){
vector<int> temp = udGraph[j];
cout<< j << ": ";
for(int i = 0; i < temp.size(); i++) {
int val = temp[i];
cout<< val << " ";
}
cout<<endl;
}
}
//Construct an empty inital adjacency matrix
DrawGraph::DrawGraph(int n) {
// Num vertices
vertices = n*n;
// Adjacency matrix
vector<int> tmp;
for (int j = 0; j < vertices; j++)
{
tmp.push_back(0);
}
for (int i = 0; i < vertices; i++)
{
adjMat.push_back(tmp);
}
// Adjacency list
vector<int> tmp2;
for (int i = 0; i < vertices; i++) {
adjList.push_back(tmp2);
}
}
//Return a copy of the adjacency matrix
vector<vector<int> > DrawGraph:: get()
{
return adjList;
}
//Add a graph edge (remove wall on a cell)
void DrawGraph::addEdge(int v1, int v2)
{
if (0 <= v1 && v1 < (vertices * vertices)
&& 0 <= v2 && v2 < (vertices * vertices) // v1, v2 are valid
&& adjMat[v1][v2] == 0) { // v1, v2 are not already neighbors
// Find row and column indices of v1 and v2
// Fix adjacency matrix
adjMat[v1][v2] = 1;
adjMat[v2][v1] = 1;
// Fix adjacency list
if (v1 < v2) {
adjList[v1].push_back(v2);
}
else {
adjList[v2].push_back(v1);
}
}
}
//Perform depth- first search of udgraph
stack<int> DrawGraph ::depthFirstSearch(int start, int end) {
stack<int> saveStack;
SearchGraph();
// Mark all the vertices as not visited
bool *visited = new bool[vertices];// a bool of all the verticies
for (int i = 0; i < vertices; i++) {
visited[i] = false;
}
stack<int> tempStack;
tempStack.push(start);
while(!tempStack.empty())
{
int top = tempStack.top();
tempStack.pop();
if ( top == end) {
saveStack.push(top);
break;
}
// what is the int start = 0?
saveStack.push(top); // saving the value visitied
if (visited[top] != true)
{
// if not visited, push the value onto the stack of the entire list
visited[top] = true;
// use uD graph here instead of adjList
for(vector<int>::iterator i = udGraph[top].begin(); i != udGraph[top].end(); i++)
{
int count = 0;
if (visited[*i] == false)
{
count++;
tempStack.push(*i);
}
}
}
}
// delete the places that we don't need to visit
// check if with the graph, we are reaching the end from the tempStackPush
stack<int> returnStack;
returnStack.push(saveStack.top());
int prev = saveStack.top();
saveStack.pop();
while(!saveStack.empty()){
int temp_saveStack = saveStack.top();
saveStack.pop();
for(vector<int>::iterator i = udGraph[prev].begin(); i != udGraph[prev].end(); i++){
if(temp_saveStack == *i){
returnStack.push(temp_saveStack);
prev = temp_saveStack;
break;
}
}
}
//reversing the returnStack
stack<int> returnStackCorrected;
while (!returnStack.empty()) {
returnStackCorrected.push(returnStack.top());
returnStack.pop();
}
return returnStackCorrected;
}
//Constructs an Undirected Bidirectional Graph based on adjacency list
void DrawGraph::SearchGraph()
{
/*
We will populate the udGraph
i.e in adjList
if 0 -> 1, then add the 1-> =0
*/
for (int i = 0; i < vertices; i++)
{
udGraph.push_back(adjList[i]);
}
for (int i = 0; i < vertices; i++)
{
for (int j = 0; j< adjList[i].size(); j++)
{
if (adjList[i][j] > i)
{
udGraph[adjList[i][j]].push_back(i);
}
}
}
}
|
#include <gtest/gtest.h>
#include "huobi_futures/linear_swap/restful/OrderClient.hpp"
typedef huobi_futures::linear_swap::restful::OrderClient OrderClient;
#include "config.hpp"
TEST(OrderClient, SwitchLeverRate)
{
extern map<string, string> config;
init_config();
OrderClient odClient(config["AccessKey"], config["SecretKey"]);
auto result = odClient.IsolatedSwitchLeverRate("XRP-USDT", 10);
EXPECT_EQ(result->err_code.has_value(), false);
LOG(INFO) << result->data.value().lever_rate;
result = odClient.CrossSwitchLeverRate("XRP-USDT", 10);
EXPECT_EQ(result->err_code.has_value(), false);
LOG(INFO) << result->data.value().lever_rate;
}
long id1 = 0;
TEST(OrderClient, PlaceOrder)
{
extern map<string, string> config;
init_config();
PlaceOrderRequest pr;
pr.contract_code = "XRP-USDT";
pr.price = 0.5;
pr.direction = "buy";
pr.offset = "open";
pr.lever_rate = 10;
pr.volume = 1;
pr.order_price_type = "limit";
OrderClient odClient(config["AccessKey"], config["SecretKey"]);
auto result = odClient.IsolatedPlaceOrder(pr);
EXPECT_EQ(result->err_code.has_value(), false);
LOG(INFO) << result->data.value().order_id;
id1 = result->data.value().order_id;
result = odClient.CrossPlaceOrder(pr);
EXPECT_EQ(result->err_code.has_value(), false);
LOG(INFO) << result->data.value().order_id;
}
TEST(OrderClient, GetOrderInfo)
{
extern map<string, string> config;
init_config();
OrderClient odClient(config["AccessKey"], config["SecretKey"]);
auto result = odClient.IsolatedGetOrderInfo("XRP-USDT", "790522296375869442");
EXPECT_EQ(result->err_code.has_value(), false);
LOG(INFO) << result->data.value().data()->status;
result = odClient.CrossGetOrderInfo("XRP-USDT", "790522454593404928");
EXPECT_EQ(result->err_code.has_value(), false);
LOG(INFO) << result->data.value().data()->status;
}
TEST(OrderClient, GetOpenOrder)
{
extern map<string, string> config;
init_config();
OrderClient odClient(config["AccessKey"], config["SecretKey"]);
auto result = odClient.IsolatedGetOpenOrder("XRP-USDT");
EXPECT_EQ(result->err_code.has_value(), false);
for (auto item : result->data.value().orders)
{
LOG(INFO) << item.contract_code << ":" << item.price << ":" << item.volume << ":" << item.margin_mode;
}
result = odClient.CrossGetOpenOrder("XRP-USDT");
EXPECT_EQ(result->err_code.has_value(), false);
for (auto item : result->data.value().orders)
{
LOG(INFO) << item.contract_code << ":" << item.price << ":" << item.volume << ":" << item.margin_mode;
}
}
TEST(OrderClient, CancelOrder)
{
extern map<string, string> config;
init_config();
OrderClient odClient(config["AccessKey"], config["SecretKey"]);
stringstream str_buf;
str_buf << id1;
auto result = odClient.IsolatedCancelOrder("XRP-USDT", str_buf.str());
EXPECT_EQ(result->data.value().errors.size(), 0);
LOG(INFO) << result->data.value().successes;
str_buf.clear();
result = odClient.CrossCancelOrder("XRP-USDT");
EXPECT_EQ(result->data.value().errors.size(), 0);
LOG(INFO) << result->data.value().successes;
}
|
#include "function_call.h"
#include "expression.h"
#include "visitor.h"
Parameter_list::Parameter_list() {}
void Parameter_list::Accept(AbstractDispatcher& dispatcher) {
dispatcher.Dispatch(*this);
}
void Parameter_list::add_parameter(Expression* p) {
parameters.push_front(p);
}
Parameter_list::~Parameter_list() {
for(auto&z: parameters) {
delete z;
}
}
Function_call::Function_call(std::string _id, Parameter_list* _p_list) : id(_id), p_list(_p_list) {}
void Function_call::Accept(AbstractDispatcher& dispatcher) {
dispatcher.Dispatch(*this);
}
Function_call::~Function_call() { delete p_list; }
|
#include "bricks/threading/taskqueue.h"
#include "bricks/threading/conditionlock.h"
#include "bricks/threading/mutexlock.h"
#include "bricks/threading/thread.h"
#include "bricks/threading/task.h"
#include "bricks/collections/autoarray.h"
#include "bricks/collections/queue.h"
namespace Bricks { namespace Threading {
TaskQueue::TaskQueue(int threadCount) :
threadCount(threadCount),
queue(autonew QueueType()),
queueCondition(autonew ConditionLock()),
threads(autonew ThreadArray())
{
}
TaskQueue::~TaskQueue()
{
Stop(false);
}
namespace Internal { struct TaskQueueThread
{
TaskQueue* queue;
Thread* thread;
TaskQueueThread(TaskQueue* queue, Thread* thread) : queue(queue), thread(thread) { }
void operator()() const {
AutoPointer<ConditionLock> condition = queue->queueCondition;
AutoPointer<TaskQueue::QueueType> tasks = queue->queue;
while (true) {
MutexLock lock(condition);
while (condition->GetCondition() == TaskQueueCondition::Waiting)
condition->Wait();
if (tasks->GetCount()) {
AutoPointer<Internal::TaskBase> task = tasks->PopItem();
condition->Signal(TaskQueue::ConditionStatus(tasks));
lock.Unlock();
task->SetThread(thread);
task->Run();
} else if (condition->GetCondition() == TaskQueueCondition::Cancel)
break;
}
}
}; }
void TaskQueue::PushTask(Internal::TaskBase* task)
{
MutexLock lock(queueCondition);
queue->Push(task);
queueCondition->Signal(TaskQueueCondition::Ready);
}
void TaskQueue::StartThread()
{
AutoPointer<Thread> thread = autonew Thread();
thread->SetDelegate(Internal::TaskQueueThread(this, thread));
thread->Start();
threads->AddItem(thread);
}
void TaskQueue::Start()
{
queueCondition->SetCondition(ConditionStatus(queue));
if (!threadCount)
threadCount = Thread::GetHardwareConcurrency();
if (!threadCount)
threadCount = 2;
for (int i = 0; i < threadCount; i++)
StartThread();
}
void TaskQueue::Stop(bool wait)
{
{ MutexLock lock(queueCondition);
if (queueCondition->GetCondition() == TaskQueueCondition::Cancel)
return;
queueCondition->Signal(TaskQueueCondition::Cancel);
}
if (wait) {
foreach (Thread* thread, threads)
thread->Wait();
}
}
TaskQueueCondition::Enum TaskQueue::ConditionStatus(const QueueType* queue)
{
return queue->GetCount() ? TaskQueueCondition::Ready : TaskQueueCondition::Cancel;
}
} }
|
#include <iostream>
#include <sstream>
#include <vector>
#include <list>
#include <queue>
#include <algorithm>
#include <iomanip>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <string>
#include <set>
#include <stack>
#include <cstdio>
#include <cstring>
#include <climits>
#include <cstdlib>
using namespace std;
struct Student {
char name[11], id[11];
int grade;
bool operator< (const Student& rhs) const {
return grade > rhs.grade;
}
};
int main() {
/*freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);*/
int n, lower, upper;
while (scanf("%d", &n) != EOF) {
vector<Student> v;
v.resize(n);
for (int i = 0; i < n; i++) {
scanf("%s %s %d", &v[i].name, &v[i].id, &v[i].grade);
}
scanf("%d %d", &lower, &upper);
sort(v.begin(), v.end());
bool exist = false;
for (int i = 0; i < n; i++) {
if (lower <= v[i].grade && v[i].grade <= upper) {
exist = true;
printf("%s %s\n", v[i].name, v[i].id);
}
}
if (!exist)
printf("NONE\n");
}
return 0;
}
|
#include <iostream>
using namespace std;
struct BiNode
{
int value;
BiNode *ptr1, *ptr2;
BiNode(int v): value(v){}
};
void convert(BiNode *root, BiNode* &head, BiNode * &tail)
{
if(root == NULL)
{
head = tail = NULL;
return;
}
BiNode *lefthead, *lefttail;
BiNode *righthead, *righttail;
convert(root->ptr1, lefthead, lefttail);
convert(root->ptr2, righthead, righttail);
if(lefthead != NULL)
{
head = lefthead;
lefttail->ptr2 = root;
root->ptr1 = lefttail;
}
else
head = root;
if(righthead != NULL)
{
tail = righttail;
righthead->ptr1 = root;
root->ptr2 = righthead;
}
else
tail = root;
}
BiNode *convertBST2DList(BiNode *root)
{
BiNode *head, *tail;
convert(root, head, tail);
return tail;
}
int main()
{
BiNode *root = NULL; //new BiNode(4);
/*
root->ptr1 = new BiNode(2);
root->ptr1->ptr1 = new BiNode(1);
root->ptr1->ptr2 = new BiNode(3);
root->ptr1->ptr1->ptr1 = new BiNode(0);
root->ptr2 = new BiNode(5);
root->ptr2->ptr2 = new BiNode(6);
*/
BiNode* tail = convertBST2DList(root);
while(tail != NULL)
{
cout << tail->value << endl;
tail = tail->ptr1;
}
return 0;
}
|
#ifndef _STATE_MANAGER_H_
#define _STATE_MANAGER_H_
#include <SFML/Graphics.hpp>
#include <list>
#include "Entity.h"
#include "Transition.h"
class State;
class StateManager : public Entity
{
public:
StateManager();
~StateManager();
void init(State * s);
void close() { m_isRunning = false; }
bool isRunning() const { return m_isRunning && (!m_states.empty() || m_isClearWait ); }
virtual void update();
void handleEvent(sf::Event &e);
void newState(State * s);
void pushState(State * s);
void popState();
protected:
//! Inherited from sf::Drawable
virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const;
private:
bool m_isRunning;
std::list<State *> m_states;
std::list<State *> m_waitingStates;
bool m_isClearWait;
bool m_isCloseWait;
Transition * m_currentTransitionIn;
Transition * m_currentTransitionOut;
};
#endif // _STATE_MANAGER_H_
|
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 100 + 8;
//结构体
struct node {
int d;
int l;
int r;
}q[maxn];
int n, a;
int ans = 0;
void inorder(int k) {
if(q[k].l)
inorder(q[k].l);
ans++;
if(q[k].d == a) {
cout << ans << endl;
exit(0);
}
if(q[k].r) {
inorder(q[k].r);
}
}
int main() {
cin >> n >> a;
for(int i = 1; i <= n; i++)
cin >> q[i].d >> q[i].l >> q[i].r;
inorder(1);
return 0;
}
|
//
// Created by 钟奇龙 on 2019-05-10.
//
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int minDistance(vector<string> strs,string s1,string s2){
if(strs.size() == 0) return -1;
if(s1 == s2) return 0;
int last1 = -1;
int last2 = -1;
int minDis = INT_MAX;
for(int i=0; i<strs.size(); ++i){
if(strs[i] == s1){
minDis = min(minDis,last2 == -1 ? minDis:i-last2);
last1 = i;
}else if(strs[i] == s2){
minDis = min(minDis,last1 == -1 ? minDis:i-last1);
last2 = i;
}
}
return minDis == INT_MAX ? -1:minDis;
}
int main(){
vector<string> strs = {"1","3","3","3","2","3","1"};
cout<<minDistance(strs,"1","2")<<endl;
return 0;
}
|
#pragma once
#include "MoveIncludes.h"
#include "Vec2.h"
#include "EyeImage.h"
#include "MoveBall.h"
namespace Move
{
class BallFitAlgorithm
{
private:
EyeImage* img;
public:
BallFitAlgorithm(EyeImage* img);
~BallFitAlgorithm();
void fitCircle(MoveBall* ball);
private:
std::vector<Vec2> currentBallContour;
float currentBallSize;
double integrateCircleError(std::vector<double> x);
};
}
|
/****************************************************************************
** CopyRight(c) 2014,
** All rights reserved
**
** 文件名称: CSystemTrayIcon.h
** 摘要: 系统托盘类,需要根据服务器状态切换图标
**
** 当前版本: 1.0.0.0
** 作者: 宋斌斌
**
** 完成日期: 2014-11-23
**
** 历史修改记录:
** 作者 描述 修改时间
**
****************************************************************************/
#ifndef CSYSTEMTRAYICON_H
#define CSYSTEMTRAYICON_H
#include <QSystemTrayIcon>
#include "common.h"
class QAction;
class QMenu;
class CSystemTrayIcon : public QSystemTrayIcon
{
Q_OBJECT
public:
CSystemTrayIcon(QObject *parent);
~CSystemTrayIcon();
public Q_SLOTS:
void setState(SMonitor::Type state);
void setHidden(bool hidden);
void selfUpgrade();
Q_SIGNALS:
//系统托盘状态转换更新通知
void trayIconStateChanged(int state);
//退出当前应用
void quitApplication();
//关于应用
//void aboutApplication();
//显示/隐藏应用主界面
void hideOrShowWidget();
protected:
virtual void timerEvent(QTimerEvent *);
protected Q_SLOTS:
void downloadFileErrorOccur(const QString& errMsg);
void downloadSuccess();
private:
void setTrayIconContextMenu();
void closeDownload();
private:
QMenu* m_TrayIconMenu;
QAction* m_hideShowAct;
//QAction* m_aboutAct;
QAction* m_upgradeAct;
QAction* m_exitAct;
int m_waitid;
class CHTTPDownloader* m_pVersionFileDownloader;
SMonitor::Type m_curIconType;
};
#endif // CSYSTEMTRAYICON_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2010 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
/**
* @file OCSPRequest_impl.h
*
* OpenSSL-based OCSP request container interface.
*
* @author Alexei Khlebnikov <alexeik@opera.com>
*
*/
#ifndef OCSP_REQUEST_IMPL_H
#define OCSP_REQUEST_IMPL_H
#if defined(CRYPTO_OCSP_SUPPORT) && defined(CRYPTO_CERTIFICATE_VERIFICATION_USE_CORE_IMPLEMENTATION)
#include "modules/libcrypto/include/OpOCSPRequest.h"
#include "modules/libopeay/openssl/cryptlib.h"
#include "modules/libopeay/openssl/ocsp.h"
class OCSPRequest_impl : public OpOCSPRequest
{
public:
OCSPRequest_impl();
virtual ~OCSPRequest_impl();
public:
// OpOCSPRequest methods.
virtual unsigned int CalculateDERLengthL() const;
virtual void ExportAsDERL(unsigned char* der) const;
public:
// Implementation-specific methods.
void TakeOverOCSP_REQUEST(OCSP_REQUEST* ocsp_request);
OCSP_REQUEST* GetOCSP_REQUEST() const;
void Clear();
private:
// These objects are created and owned by this object.
OCSP_REQUEST* m_ocsp_request;
};
#endif // defined(CRYPTO_OCSP_SUPPORT) && defined(CRYPTO_CERTIFICATE_VERIFICATION_USE_CORE_IMPLEMENTATION)
#endif // OCSP_REQUEST_IMPL_H
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.