blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2 values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905 values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 10.4M | extension stringclasses 115 values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c785b64b16be440f107c762357ce17bc722ecc39 | 5bedc85ef4ad015cb1075f048a85768a3ead0717 | /src/modules/ESModuleOscillatorBase.h | 5fa9040ff1dd1c1028aeafe8555b525442727700 | [
"MIT"
] | permissive | siqueiraets/essynth | a875ff071303fb69200cf4e65516de11a4a6435a | acd2a32752530728787cdc92962bc88b7df4ba48 | refs/heads/master | 2021-09-09T10:06:20.931082 | 2018-03-15T02:06:40 | 2018-03-15T02:06:40 | 118,532,038 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,562 | h | #ifndef ESMODULEOSCILLATORBASE_H_
#define ESMODULEOSCILLATORBASE_H_
#include "ESEngine.h"
#define ES_OSC_RESOLUTION 1024
// TODO sample rate needs to be read at runtime
#define SAMPLE_RATE 44100
namespace ESSynth {
enum class ESModuleOscillatorBaseInputs { Frequency, Clock };
enum class ESModuleOscillatorBaseOutputs { Amplitude };
enum class ESModuleOscillatorBaseInternals { Phase };
template <typename Type>
struct ESModuleOscillatorBase
: ESModule<ESModuleOscillatorBase<Type>, ESModuleOscillatorBaseInputs,
ESModuleOscillatorBaseOutputs, ESModuleOscillatorBaseInternals> {
using BaseType = ESModule<ESModuleOscillatorBase<Type>, ESModuleOscillatorBaseInputs,
ESModuleOscillatorBaseOutputs, ESModuleOscillatorBaseInternals>;
static ESFloatType osc_table[ES_OSC_RESOLUTION];
static constexpr auto GetInputList() {
return BaseType::MakeIoList(
BaseType::MakeInput(ESDataType::Float, "Frequency", BaseType::TIn::Frequency),
BaseType::MakeInput(ESDataType::Integer, "Clock", BaseType::TIn::Clock));
}
static constexpr auto GetOutputList() {
return BaseType::MakeIoList(
BaseType::MakeOutput(ESDataType::Float, "Amplitude", BaseType::TOut::Amplitude));
}
static constexpr auto GetInternalList() {
return BaseType::MakeIoList(
BaseType::MakeInternal(ESDataType::Float, "Phase", BaseType::TInt::Phase));
}
static ESInt32Type Process(const ESData* inputs, ESOutputRuntime* outputs, ESData* internals,
const ESInt32Type& flags) {
if (!(flags & BaseType::InputFlag(BaseType::TIn::Clock))) {
return 0;
}
ESFloatType frequency = BaseType::template Input<BaseType::TIn::Frequency>(inputs);
ESFloatType increment = (ES_OSC_RESOLUTION * frequency) / (ESFloatType)SAMPLE_RATE;
ESFloatType phase = BaseType::template Internal<BaseType::TInt::Phase>(internals);
phase += increment;
if (phase >= (ESFloatType)ES_OSC_RESOLUTION) {
phase -= (ESFloatType)ES_OSC_RESOLUTION;
}
ESFloatType value = osc_table[(ESInt32Type)phase];
BaseType::template Internal<BaseType::TInt::Phase>(internals) = phase;
BaseType::template WriteOutput<BaseType::TOut::Amplitude>(outputs, value);
return 0;
}
};
template <typename Type>
ESFloatType ESModuleOscillatorBase<Type>::osc_table[ES_OSC_RESOLUTION];
} // namespace ESSynth
#endif /* ESMODULEOSCILLATORBASE_H_ */
| [
"siqueiraets@gmail.com"
] | siqueiraets@gmail.com |
b1b7969b2e76d46428c40d1c8b690ec9c8f22448 | c74e77aed37c97ad459a876720e4e2848bb75d60 | /800-899/854/(30197365)[WRONG_ANSWER]D[ b'Jury Meeting' ].cpp | aed6d71d77c2fbf97929480890ff7c5224ac9f9a | [] | no_license | yashar-sb-sb/my-codeforces-submissions | aebecf4e906a955f066db43cb97b478d218a720e | a044fccb2e2b2411a4fbd40c3788df2487c5e747 | refs/heads/master | 2021-01-21T21:06:06.327357 | 2017-11-14T21:20:28 | 2017-11-14T21:28:39 | 98,517,002 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,189 | cpp | #include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef unsigned long long uLL;
typedef long double ldb;
typedef pair<int,int> pii;
vector<int> C[1000001];
LL OC[1000001];
vector<int> F[1000001];
map<int,int> ma;
int n, m, k;
LL sum = 0;
void fun(int i)
{
for(int j = 0; j < int(F[i].size()); ++j)
{
if(!ma.count(F[i][j]))
{
ma[F[i][j]] = C[i][j];
sum += C[i][j];
}
else if(C[i][j]<ma[F[i][j]])
{
sum -= ma[F[i][j]] - C[i][j];
ma[F[i][j]] = C[i][j];
}
}
if(int(ma.size())==n)
OC[i] = sum;
else
OC[i] = 1e18;
}
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int d, f, t, c;
cin>>n>>m>>k;
for(int i = 0; i < m; ++i)
{
cin>>d>>f>>t>>c;
f= max(f, t);
F[d].push_back(f);
C[d].push_back(c);
}
for(int i = 1000000; i > 0; --i)
fun(i);
sum = 0;
ma.clear();
LL ans = 1e18;
for(int i = 0; i < 1000000-k; ++i)
{
fun(i);
ans = min(ans, OC[i]+OC[i+k+1]);
}
if(ans > 1e15)
ans = -1;
cout<<ans<<endl;
return 0;
}
| [
"yashar_sb_sb@yahoo.com"
] | yashar_sb_sb@yahoo.com |
317a32a13b362247e026cb11bc72104b18b3f5c2 | 69a8a80e7016e3ff2b26f0355941dba0d441a638 | /src/Block.cpp | 894595ad022474c6a7283d60f975def1598c9f0d | [] | no_license | questcoinn/Qkcolb | 7231f5787e0a7ddaaf3ba5350b7c7e86b2e58515 | 03961303f85605c0b0ed0fced1752319ff34719f | refs/heads/master | 2023-05-02T03:18:11.859874 | 2021-05-10T10:56:31 | 2021-05-10T10:56:31 | 365,523,492 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,802 | cpp | #include <ctime>
#include "Block.hpp"
#include "sha256.hpp"
#ifdef DEBUG
#include <iostream>
#endif
qb::Block::Block(std::string data, std::string prevBlockHash, int64 targetBit)
:data(data)
,prevBlockHash(prevBlockHash)
{
this->timestamp = std::chrono::system_clock::now();
this->setHash(targetBit);
}
void qb::Block::setHash(int64 targetBit) {
std::string _timestamp = std::to_string(std::chrono::system_clock::to_time_t(this->timestamp));
std::string targetHash = "";
for(int i = 0; i < 64; i++) {
if(i != (targetBit - 1) / 4) {
targetHash += '0';
}
else if(targetBit % 4 == 0) {
targetHash += '1';
}
else if(targetBit % 4 == 3) {
targetHash += '2';
}
else if(targetBit % 4 == 2) {
targetHash += '4';
}
else {
targetHash += '8';
}
}
#ifdef DEBUG
std::cout << "Mining the block containing \"" << this->data << "\"\n";
#endif
for(int64 salt = 0; salt < INT64_MAX; salt++) {
std::string _salt = std::to_string(salt);
std::string newHash = qb::sha256(this->prevBlockHash + this->data + _timestamp + _salt);
#ifdef DEBUG
std::cout << "\r" << newHash;
#endif
if(newHash < targetHash) {
this->hash = newHash;
this->nonce = salt;
break;
}
}
#ifdef DEBUG
std::cout << "\n\n";
#endif
}
bool qb::Block::isValid() {
std::string _timestamp = std::to_string(std::chrono::system_clock::to_time_t(this->timestamp));
std::string _nonce = std::to_string(this->nonce);
return this->hash == qb::sha256(this->prevBlockHash + this->data + _timestamp + _nonce);
}
#ifdef DEBUG
void qb::Block::print() {
std::cout << "Prev. hash: " << std::hex << this->prevBlockHash << "\n";
std::cout << "Data: " << std::hex << this->data << "\n";
std::cout << "Hash: " << std::hex << this->hash << "\n";
std::cout << "\n";
}
#endif
qb::BlockChain::BlockChain(int64 targetBit)
:targetBit(targetBit)
{
this->list = std::list<qb::Block>();
this->list.push_back(qb::Block("Genesis Block", "", this->targetBit));
}
std::list<qb::Block>::iterator &qb::BlockChain::begin() {
this->iterator = this->list.begin();
return this->iterator;
}
std::list<qb::Block>::iterator &qb::BlockChain::end() {
this->iterator = this->list.end();
return this->iterator;
}
std::size_t qb::BlockChain::size() {
return this->list.size();
}
void qb::BlockChain::addBlock(std::string data) {
qb::Block newBlock(data, this->list.back().hash, this->targetBit);
if(newBlock.isValid()) {
this->list.push_back(newBlock);
}
#ifdef DEBUG
else {
std::cout << "Failed mining for some reason\n";
}
#endif
} | [
"iopell2007@gmail.com"
] | iopell2007@gmail.com |
aa23b09b3c4e8803a5c6279d42d878e0949508d9 | 7e16344d6eea32fbee8c8fc018025530417ea9fb | /src/GameObjects.cpp | 24aea87a2a6afa249798745adad2c2cebe401b52 | [] | no_license | Bezifabr/BoardGameProject-Editor | 8df1c57687e1dcd55b1c2955ab408a8bbae6e080 | 9d0e5037c3d0c2e14af70e5624c6c8522f5e7d2b | refs/heads/master | 2020-03-22T10:59:42.246626 | 2018-07-07T09:36:23 | 2018-07-07T09:36:23 | 139,939,962 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,206 | cpp | /// ////////////////////////////////////////////////////////////////////////////
//
// Project: 'The Board Game Project'
// GameObjects.cpp
// Purpose: Contains the definitions of Item, Skill and Effect classes containers.
//
// Copyright (C) Maciej Saranda 2016 (Bezifabr@gmail.com)
// Code written only for use by Mighty Gorilla Studio.
//
//
//
/// ////////////////////////////////////////////////////////////////////////////
#include <fstream>
#include "GameObjects.h"
#include <iostream>
#include <exception>
bool GameObjects::AddItem(std::string key, Item item)
{
if (items_.count(key) == 0)
{
items_[key] = item;
itemsKeys_.push_back(key);
return true;
}
std::cout << "GameObjects::AddItem(): key is occupied" << std::endl;
return false;
}
bool GameObjects::ChangeItem(std::string key, Item item)
{
if (items_.count(key) == 1)
{
items_[key] = item;
return true;
}
std::cout << "GameObjects::ChangeItem(): item doesn't exist" << std::endl;
return false;
}
bool GameObjects::RemoveItem(std::string key)
{
if (items_.count(key) == 1)
{
items_.erase(key);
if (!itemsKeys_.empty())
{
for (auto i = itemsKeys_.begin(); i != itemsKeys_.end(); i++)
if (itemsKeys_[std::distance(itemsKeys_.begin(), i)] == key)
{
itemsKeys_.erase(i);
break;
}
}
return true;
}
std::cout << "GameObjects::RemoveItem(): item doesn't exist" << std::endl;
return false;
}
Item & GameObjects::GetItem(std::string key)
{
if (items_.count(key) == 0)
throw "GameObjects::GetItem(): Item doesn't exist";
return items_[key];
}
bool GameObjects::AddSkill(std::string key, Skill skill)
{
if (skills_.count(key) == 0)
{
skills_[key] = skill;
skillsKeys_.push_back(key);
return true;
}
std::cout << "GameObjects::AddSkill(): key is occupied" << std::endl;
return false;
}
bool GameObjects::ChangeSkill(std::string key, Skill skill)
{
if (skills_.count(key) == 1)
{
skills_[key] = skill;
return true;
}
std::cout << "GameObjects::ChangeSkill(): skill doesn't exist" << std::endl;
return false;
}
bool GameObjects::RemoveSkill(std::string key)
{
if (skills_.count(key) == 1)
{
skills_.erase(key);
if (!skillsKeys_.empty())
{
for (auto i = skillsKeys_.begin(); i != skillsKeys_.end(); i++)
if (skillsKeys_[std::distance(skillsKeys_.begin(), i)] == key)
{
skillsKeys_.erase(i);
break;
}
}
return true;
}
std::cout << "GameObjects::RemoveSkill(): skill doesn't exist" << std::endl;
return false;
}
Skill & GameObjects::GetSkill(std::string key)
{
if (skills_.count(key) == 0)
throw "GameObjects::GetSkill(): Skill doesn't exist";
return skills_[key];
}
bool GameObjects::AddEffect(std::string key, Effect effect)
{
if (effects_.count(key) == 0)
{
effect.SetID(key);
effects_[key] = effect;
effectsKeys_.push_back(key);
return true;
}
std::cout << "GameObjects::AddEffect(): key is occupied" << std::endl;
return false;
}
bool GameObjects::ChangeEffect(std::string key, Effect effect)
{
if (effects_.count(key) == 1)
{
effects_[key] = effect;
effects_[key].SetID(key);
return true;
}
std::cout << "GameObjects::ChangeEffect(): Effect doesn't exist" << std::endl;
return false;
}
bool GameObjects::RemoveEffect(std::string key)
{
if (effects_.count(key) == 1)
{
effects_.erase(key);
RemoveEffectsKeys(key);
return true;
}
std::cout << "GameObjects::RemoveEffect(): Effect doesn't exist" << std::endl;
return false;
}
Effect& GameObjects::GetEffect(std::string key)
{
if (effects_.count(key) == 0)
throw "Effect doesn't exists";
return effects_[key];
}
std::vector<std::string>& GameObjects::GetItemsKeys()
{
if(itemsKeys_.empty())
std::cout << "GameObjects::GetItemsKeys(): vector is empty" << std::endl;
return itemsKeys_;
}
std::vector<std::string>& GameObjects::GetSkillsKeys()
{
if (skillsKeys_.empty())
std::cout << "GameObjects::GetSkillsKeys(): vector is empty" << std::endl;
return skillsKeys_;
}
std::vector<std::string>& GameObjects::GetEffectsKeys()
{
if (effectsKeys_.empty())
std::cout << "GameObjects::GetEffectsKeys(): vector is empty" << std::endl;
return effectsKeys_;
}
bool GameObjects::SetEffectID(std::string currentID, std::string newID)
{
if (effects_.count(currentID) == 1)
{
effects_[currentID].SetID(newID);
for (auto i = effectsKeys_.begin(); i != effectsKeys_.end(); i++)
if (effectsKeys_[std::distance(effectsKeys_.begin(), i)] == currentID)
{
effectsKeys_[std::distance(effectsKeys_.begin(), i)] = newID;
break;
}
return true;
}
return false;
}
bool GameObjects::SetSkillID(std::string currentID, std::string newID)
{
if (skills_.count(currentID) == 1)
{
skills_[currentID].SetName(newID);
for (auto i = skillsKeys_.begin(); i != skillsKeys_.end(); i++)
if (skillsKeys_[std::distance(skillsKeys_.begin(), i)] == currentID)
{
skillsKeys_[std::distance(skillsKeys_.begin(), i)] = newID;
break;
}
return true;
}
return false;
}
void GameObjects::SaveEffects()
{
std::ofstream file;
if (remove("Effects.txt") != 0)
perror("Creating new file to save data");
else
puts("File found and prepared to save data");
file.open("Effects.txt", std::ofstream::out | std::ofstream::trunc);
for (auto itr = effects_.begin(), end = effects_.end(); itr != end; itr++)
{
file << "Effect{" << std::endl;
file << "ID = " << itr->second.GetID() << std::endl;
for (int i = 0; i <= itr->second.GetOrdersNumber() + 1; i++)
{
file << "Order = " << itr->second.GetFrontOrder() << std::endl;
itr->second.PopOrder();
}
file << "}" << std::endl;
}
file.close();
}
void GameObjects::SaveItems()
{
std::ofstream file;
if (remove("Items.txt") != 0)
perror("Creating new file to save data");
else
puts("File found and prepared to save data");
file.open("Items.txt", std::ofstream::out | std::ofstream::trunc);
for (auto itr = items_.begin(), end = items_.end(); itr != end; itr++)
{
file << "Item{" << std::endl;
file << "ID = " << itr->second.GetID() << std::endl;
file << "Name = " << itr->second.GetName() << std::endl;
file << "Description = " << itr->second.GetDescription() << std::endl;
file << "Icon = " << itr->second.GetIconTextureID() << std::endl;
file << "Cooldown = " << itr->second.GetTimeOfCooldown() << std::endl;
file << "Charges = " << itr->second.GetAmounOfCharges() << std::endl;
file << "Price = " << itr->second.GetPrice() << std::endl;
file << "IsTargetingAlly = " << ConvertToString(itr->second.IsTargetingAlly()) << std::endl;
file << "IsTargetingEnemy = " << ConvertToString(itr->second.IsTargetingEnemy()) << std::endl;
file << "IsTargetingSelf = " << ConvertToString(itr->second.IsTargetingSelf()) << std::endl;
file << "IsUsingOnTarget = " << ConvertToString(itr->second.IsUsingOnTarget()) << std::endl;
file << "IsUsingImmediately = " << ConvertToString(itr->second.IsUsingImmediately()) << std::endl;
file << "IsUsable = " << ConvertToString(itr->second.IsUsable()) << std::endl;
file << "}" << std::endl;
}
}
void GameObjects::SaveSkills()
{
std::ofstream file;
if (remove("Skills.txt") != 0)
perror("Creating new file to save data");
else
puts("File found and prepared to save data");
file.open("Skills.txt", std::ofstream::out | std::ofstream::trunc);
for (auto itr = skills_.begin(), end = skills_.end(); itr != end; itr++)
{
file << "Skill{" << std::endl;
file << "ID = " << itr->second.GetID() << std::endl
<< "Name = " << itr->second.GetName() << std::endl
<< "Description = " << itr->second.GetDescription() << std::endl
<< "Icon = " << itr->second.GetIconTextureID() << std::endl
<< "Cooldown = " << std::to_string(itr->second.GetTimeOfCooldown()) << std::endl;
file << "IsTargetingSelf = " << ConvertToString(itr->second.IsTargetingSelf()) << std::endl;
file << "IsTargetingEnemy = " << ConvertToString(itr->second.IsTargetingEnemy()) << std::endl;
file << "IsTargetingAlly = " << ConvertToString(itr->second.IsTargetingAlly()) << std::endl;
file << "IsUseImmediately = " << ConvertToString(itr->second.IsUsingImmediately()) << std::endl;
file << "IsUseOnTarget = " << ConvertToString(itr->second.IsUsingOnTarget()) << std::endl;
file << "IsUsable = " << ConvertToString(itr->second.IsUsable()) << std::endl;
file << "}" << std::endl;
}
}
void GameObjects::LoadEffects()
{
std::ifstream openFile("Effects.txt");
if (openFile.is_open())
{
effects_.clear();
effectsKeys_.clear();
bool effectFound;
Effect tempEffect;
while (!openFile.eof())
{
std::string line;
std::getline(openFile, line); //< Load line
line.erase(std::remove(line.begin(), line.end(), ' '), line.end()); //< Remove spaces from line
if (line.find("//") != std::string::npos)
line.erase(line.begin(), line.end());
else if (line.find("Effect{") != std::string::npos)
effectFound = true;
if(effectFound == true)
if (line.find("ID=") != std::string::npos || line.find("id=") != std::string::npos)
{
line.erase(0, line.find('=') + 1);
tempEffect.SetID(line);
std::cout << "ID(" << line << ")" << std::endl
<< "Orders: " << std::endl;
}
else if (line.find("Order=") != std::string::npos || line.find("order=") != std::string::npos)
{
line.erase(0, line.find('=') + 1);
tempEffect.PushOrder(line);
std::cout << "- " << line << std::endl;
}
if (line.find("}") != std::string::npos)
{
AddEffect(tempEffect.GetID(), tempEffect);
effectFound = false;
}
}
}
}
void GameObjects::LoadItems()
{
std::ifstream openFile("Items.txt");
if (openFile.is_open())
{
items_.clear();
itemsKeys_.clear();
Item tempItem;
bool itemFound;
while (!openFile.eof())
{
std::string line;
std::getline(openFile, line);
line.erase(std::remove(line.begin(), line.end(), ' '), line.end());
if (line.find("//") != std::string::npos)
line.erase(line.begin(), line.end());
else if (line.find("Item{") != std::string::npos)
itemFound = true;
if (itemFound == true)
{
if(line.find("ID=") != std::string::npos)
tempItem.SetID(LoadStringValue(line, "ID="));
if(line.find("Name=") != std::string::npos)
tempItem.SetName(LoadStringValue(line, "Name="));
if(line.find("Description=") != std::string::npos)
tempItem.SetDescription(LoadStringValue(line, "Description="));
if (line.find("Icon=") != std::string::npos)
tempItem.SetIconTextureID(LoadStringValue(line, "Icon="));
if (line.find("Cooldown=") != std::string::npos)
tempItem.SetTimeOfCooldown(LoadIntegerValue(line, "Cooldown="));
if (line.find("Charges=") != std::string::npos)
tempItem.SetAmountOfCharges(LoadIntegerValue(line, "Charges="));
if (line.find("Price=") != std::string::npos)
tempItem.SetPrice(LoadIntegerValue(line, "Price="));
if (line.find("IsTargetingAlly=") != std::string::npos)
tempItem.IsTargetingAlly(LoadBooleanValue(line, "IsTargetingAlly="));
if (line.find("IsTargetingEnemy=") != std::string::npos)
tempItem.IsTargetingEnemy(LoadBooleanValue(line, "IsTargetingEnemy="));
if (line.find("IsTargetingSelf=") != std::string::npos)
tempItem.IsTargetingSelf(LoadBooleanValue(line, "IsTargetingSelf="));
if (line.find("IsUsingImmediately=") != std::string::npos)
tempItem.IsUsingImmediately(LoadBooleanValue(line, "IsUsingImmediately="));
if (line.find("IsUsingOnTarget=") != std::string::npos)
tempItem.IsUsingOnTarget(LoadBooleanValue(line, "IsUsingOnTarget="));
if (line.find("IsUsable=") != std::string::npos)
tempItem.IsUsable(LoadBooleanValue(line, "IsUsable="));
}
if (line.find("}") != std::string::npos)
{
AddItem(tempItem.GetID(), tempItem);
itemFound = false;
}
}
}
}
void GameObjects::LoadSkills()
{
std::ifstream openFile("Skills.txt");
if (openFile.is_open())
{
items_.clear();
itemsKeys_.clear();
Skill tempSkill;
bool skillFound;
while (!openFile.eof())
{
std::string line;
std::getline(openFile, line);
line.erase(std::remove(line.begin(), line.end(), ' '), line.end());
if (line.find("//") != std::string::npos)
line.erase(line.begin(), line.end());
else if (line.find("Skill{") != std::string::npos)
skillFound = true;
if (skillFound == true)
{
if (line.find("ID=") != std::string::npos)
tempSkill.SetID(LoadStringValue(line, "ID="));
if(line.find("Name=") != std::string::npos)
tempSkill.SetName(LoadStringValue(line, "Name="));
if (line.find("Descr-tion=") != std::string::npos)
tempSkill.SetDescription(LoadStringValue(line, "Description="));
if(line.find("Icon=") !=std::string::npos)
tempSkill.SetIconTextureID(LoadStringValue(line,"Icon="));
if(line.find("Cooldown=") != std::string::npos)
tempSkill.SetTimeOfCooldown(LoadIntegerValue(line, "Cooldown="));
if(line.find("IsTargetingSelf=") != std::string::npos)
tempSkill.IsTargetingSelf(LoadBooleanValue(line, "IsTargetingSelf="));
if(line.find("IsTargetingEnemy=") != std::string::npos)
tempSkill.IsTargetingEnemy(LoadBooleanValue(line, "IsTargetingEnemy="));
if(line.find("IsTargetingAlly=") != std::string::npos)
tempSkill.IsTargetingAlly(LoadBooleanValue(line, "IsTargetingAlly="));
if(line.find("IsUseImmediately=") != std::string::npos)
tempSkill.IsUsingImmediately(LoadBooleanValue(line, "IsUseImmediately="));
if(line.find("IsUseOnTarget=")!=std::string::npos)
tempSkill.IsUsingOnTarget(LoadBooleanValue(line, "IsUseOnTarget="));
if(line.find("IsUsable=") != std::string::npos)
tempSkill.IsUsable(LoadBooleanValue(line,"IsUsable="));
if(line.find("}") != std::string::npos)
{
skillFound=false;
AddSkill(tempSkill.GetID(), tempSkill);
}
}
}
}
}
bool GameObjects::DidItemExists(std::string key)
{
if (items_.count(key) == 1)
return true;
std::cout << "GameObjects::DidItemExists(): Item doesn't exists" << std::endl;
return false;
}
bool GameObjects::DidEffectExists(std::string key)
{
if (effects_.count(key) == 1)
return true;
std::cout << "GameObjects::DidEffectExists(): Effect doesn't exists" << std::endl;
return false;
}
bool GameObjects::DidSkillExists(std::string key)
{
if (skills_.count(key) == 1)
return true;
std::cout << "GameObjects::DidSkillsExists(): Skill doesn't exists" << std::endl;
return false;
}
int GameObjects::LoadIntegerValue(std::string textLine, std::string searchedCommand)
{
textLine.erase(0, textLine.find('=') + 1);
std::cout << searchedCommand << textLine << std::endl;
return atoi(textLine.c_str());
}
std::string GameObjects::LoadStringValue(std::string textLine, std::string searchedCommand)
{
textLine.erase(0, textLine.find('=') + 1);
std::cout << searchedCommand << textLine << std::endl;
return textLine;
}
bool GameObjects::LoadBooleanValue(std::string textLine, std::string searchedCommand)
{
textLine.erase(0, textLine.find('=') + 1);
std::cout << searchedCommand << textLine << std::endl;
if(textLine == "True"||textLine == "true" || textLine == "1")
return true;
return false;
}
std::string GameObjects::ConvertToString(bool booleanVariable)
{
if (booleanVariable == true)
return "true";
return "false";
}
std::string GameObjects::ConvertToString(int integerVariable)
{
return std::to_string(integerVariable);
}
void GameObjects::RemoveEffectsKeys(std::string key)
{
if (!effectsKeys_.empty())
{
for (auto i = effectsKeys_.begin(); i != effectsKeys_.end(); i++)
if (effectsKeys_[std::distance(effectsKeys_.begin(), i)] == key)
{
effectsKeys_.erase(i);
break;
}
}
else std::cout << "GameObjects::RemoveEffectsKeys(): keys vector is empty" << std::endl;
}
bool GameObjects::SetItemID(std::string currentID, std::string newID)
{
if (items_.count(currentID) == 1)
{
items_[currentID].SetName(newID);
for (auto i = itemsKeys_.begin(); i != itemsKeys_.end(); i++)
if (itemsKeys_[std::distance(itemsKeys_.begin(), i)] == currentID)
{
itemsKeys_[std::distance(itemsKeys_.begin(), i)] = newID;
break;
}
return true;
}
return false;
}
| [
"bezifabr@gmail.com"
] | bezifabr@gmail.com |
20f66cc234465bfa5861f0c1bcdc94db680bfa50 | 734686d6c88a779eda24392ede30311872790490 | /Main/UVLeds.ino | 9275f3d486c1b24730b320352b97ef8b9166913e | [] | no_license | jeroenremans/bomb_escape | 47e4340e82b5b2583ededbd7440827a995e8a02e | 0afa422f9d0eaac28bb46661322137e3a00fd975 | refs/heads/master | 2021-04-06T00:16:11.333517 | 2018-03-11T17:24:30 | 2018-03-11T17:24:30 | 124,778,637 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 714 | ino | // 14-17
const int LED_1_PIN = 22;
const int LED_2_PIN = 23;
const int LED_3_PIN = 24;
const int LED_4_PIN = 25;
void uvLedsSetup() {
// Servo
pinMode(LED_1_PIN, OUTPUT);
pinMode(LED_2_PIN, OUTPUT);
pinMode(LED_3_PIN, OUTPUT);
pinMode(LED_4_PIN, OUTPUT);
}
void uvLedsLoop() {
digitalWrite(22, LOW);
digitalWrite(23, LOW);
}
void demoLoopUvLeds() {
if ((millis()/1000) % 2 == 0) {
digitalWrite(LED_1_PIN, HIGH);
digitalWrite(LED_2_PIN, HIGH);
digitalWrite(LED_3_PIN, HIGH);
digitalWrite(LED_4_PIN, HIGH);
} else {
digitalWrite(LED_1_PIN, LOW);
digitalWrite(LED_2_PIN, LOW);
digitalWrite(LED_3_PIN, LOW);
digitalWrite(LED_4_PIN, LOW);
}
}
| [
"joenremans@gmail.com"
] | joenremans@gmail.com |
fb2982d24264bf30d3025e8802a736477a2ab730 | 08a46d882b8e69efd5090555915f39583cb0067a | /src/rpc/client.cpp | f4e6c87f5f99ae2f71e64ceeeb4717c95d7f8bd4 | [
"MIT"
] | permissive | Bitcoin-OLD/Bitcoin-OLD | 3a7d36ce9d7ba6c238b5e67443290172318c09d0 | 16627f390aa418a99103843f9d94c48931fad826 | refs/heads/master | 2020-04-16T21:00:10.631744 | 2019-01-15T19:39:39 | 2019-01-15T19:39:39 | 165,907,352 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,689 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoinold Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpc/client.h"
#include "rpc/protocol.h"
#include "util.h"
#include <set>
#include <stdint.h>
#include <boost/algorithm/string/case_conv.hpp> // for to_lower()
#include <univalue.h>
using namespace std;
class CRPCConvertParam
{
public:
std::string methodName; //!< method whose params want conversion
int paramIdx; //!< 0-based idx of param to convert
std::string paramName; //!< parameter name
};
/**
* Specifiy a (method, idx, name) here if the argument is a non-string RPC
* argument and needs to be converted from JSON.
*
* @note Parameter indexes start from 0.
*/
static const CRPCConvertParam vRPCConvertParams[] =
{
{ "setmocktime", 0, "timestamp" },
{ "generate", 0, "nblocks" },
{ "generate", 1, "maxtries" },
{ "generatetoaddress", 0, "nblocks" },
{ "generatetoaddress", 2, "maxtries" },
{ "getnetworkhashps", 0, "nblocks" },
{ "getnetworkhashps", 1, "height" },
{ "sendtoaddress", 1, "amount" },
{ "sendtoaddress", 4, "subtractfeefromamount" },
{ "settxfee", 0, "amount" },
{ "getreceivedbyaddress", 1, "minconf" },
{ "getreceivedbyaccount", 1, "minconf" },
{ "listreceivedbyaddress", 0, "minconf" },
{ "listreceivedbyaddress", 1, "include_empty" },
{ "listreceivedbyaddress", 2, "include_watchonly" },
{ "listreceivedbyaccount", 0, "minconf" },
{ "listreceivedbyaccount", 1, "include_empty" },
{ "listreceivedbyaccount", 2, "include_watchonly" },
{ "getbalance", 1, "minconf" },
{ "getbalance", 2, "include_watchonly" },
{ "getblockhash", 0, "height" },
{ "waitforblockheight", 0, "height" },
{ "waitforblockheight", 1, "timeout" },
{ "waitforblock", 1, "timeout" },
{ "waitfornewblock", 0, "timeout" },
{ "move", 2, "amount" },
{ "move", 3, "minconf" },
{ "sendfrom", 2, "amount" },
{ "sendfrom", 3, "minconf" },
{ "listtransactions", 1, "count" },
{ "listtransactions", 2, "skip" },
{ "listtransactions", 3, "include_watchonly" },
{ "listaccounts", 0, "minconf" },
{ "listaccounts", 1, "include_watchonly" },
{ "walletpassphrase", 1, "timeout" },
{ "getblocktemplate", 0, "template_request" },
{ "listsinceblock", 1, "target_confirmations" },
{ "listsinceblock", 2, "include_watchonly" },
{ "sendmany", 1, "amounts" },
{ "sendmany", 2, "minconf" },
{ "sendmany", 4, "subtractfeefrom" },
{ "addmultisigaddress", 0, "nrequired" },
{ "addmultisigaddress", 1, "keys" },
{ "createmultisig", 0, "nrequired" },
{ "createmultisig", 1, "keys" },
{ "listunspent", 0, "minconf" },
{ "listunspent", 1, "maxconf" },
{ "listunspent", 2, "addresses" },
{ "getblock", 1, "verbose" },
{ "getblockheader", 1, "verbose" },
{ "gettransaction", 1, "include_watchonly" },
{ "getrawtransaction", 1, "verbose" },
{ "createrawtransaction", 0, "inputs" },
{ "createrawtransaction", 1, "outputs" },
{ "createrawtransaction", 2, "locktime" },
{ "signrawtransaction", 1, "prevtxs" },
{ "signrawtransaction", 2, "privkeys" },
{ "sendrawtransaction", 1, "allowhighfees" },
{ "fundrawtransaction", 1, "options" },
{ "gettxout", 1, "n" },
{ "gettxout", 2, "include_mempool" },
{ "gettxoutproof", 0, "txids" },
{ "lockunspent", 0, "unlock" },
{ "lockunspent", 1, "transactions" },
{ "importprivkey", 2, "rescan" },
{ "importaddress", 2, "rescan" },
{ "importaddress", 3, "p2sh" },
{ "importpubkey", 2, "rescan" },
{ "importmulti", 0, "requests" },
{ "importmulti", 1, "options" },
{ "verifychain", 0, "checklevel" },
{ "verifychain", 1, "nblocks" },
{ "pruneblockchain", 0, "height" },
{ "keypoolrefill", 0, "newsize" },
{ "getrawmempool", 0, "verbose" },
{ "estimatefee", 0, "nblocks" },
{ "estimatepriority", 0, "nblocks" },
{ "estimatesmartfee", 0, "nblocks" },
{ "estimatesmartpriority", 0, "nblocks" },
{ "prioritisetransaction", 1, "priority_delta" },
{ "prioritisetransaction", 2, "fee_delta" },
{ "setban", 2, "bantime" },
{ "setban", 3, "absolute" },
{ "setnetworkactive", 0, "state" },
{ "getmempoolancestors", 1, "verbose" },
{ "getmempooldescendants", 1, "verbose" },
{ "bumpfee", 1, "options" },
// Echo with conversion (For testing only)
{ "echojson", 0, "arg0" },
{ "echojson", 1, "arg1" },
{ "echojson", 2, "arg2" },
{ "echojson", 3, "arg3" },
{ "echojson", 4, "arg4" },
{ "echojson", 5, "arg5" },
{ "echojson", 6, "arg6" },
{ "echojson", 7, "arg7" },
{ "echojson", 8, "arg8" },
{ "echojson", 9, "arg9" },
};
class CRPCConvertTable
{
private:
std::set<std::pair<std::string, int>> members;
std::set<std::pair<std::string, std::string>> membersByName;
public:
CRPCConvertTable();
bool convert(const std::string& method, int idx) {
return (members.count(std::make_pair(method, idx)) > 0);
}
bool convert(const std::string& method, const std::string& name) {
return (membersByName.count(std::make_pair(method, name)) > 0);
}
};
CRPCConvertTable::CRPCConvertTable()
{
const unsigned int n_elem =
(sizeof(vRPCConvertParams) / sizeof(vRPCConvertParams[0]));
for (unsigned int i = 0; i < n_elem; i++) {
members.insert(std::make_pair(vRPCConvertParams[i].methodName,
vRPCConvertParams[i].paramIdx));
membersByName.insert(std::make_pair(vRPCConvertParams[i].methodName,
vRPCConvertParams[i].paramName));
}
}
static CRPCConvertTable rpcCvtTable;
/** Non-RFC4627 JSON parser, accepts internal values (such as numbers, true, false, null)
* as well as objects and arrays.
*/
UniValue ParseNonRFCJSONValue(const std::string& strVal)
{
UniValue jVal;
if (!jVal.read(std::string("[")+strVal+std::string("]")) ||
!jVal.isArray() || jVal.size()!=1)
throw runtime_error(string("Error parsing JSON:")+strVal);
return jVal[0];
}
UniValue RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
UniValue params(UniValue::VARR);
for (unsigned int idx = 0; idx < strParams.size(); idx++) {
const std::string& strVal = strParams[idx];
if (!rpcCvtTable.convert(strMethod, idx)) {
// insert string value directly
params.push_back(strVal);
} else {
// parse string as JSON, insert bool/number/object/etc. value
params.push_back(ParseNonRFCJSONValue(strVal));
}
}
return params;
}
UniValue RPCConvertNamedValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
UniValue params(UniValue::VOBJ);
for (const std::string &s: strParams) {
size_t pos = s.find("=");
if (pos == std::string::npos) {
throw(std::runtime_error("No '=' in named argument '"+s+"', this needs to be present for every argument (even if it is empty)"));
}
std::string name = s.substr(0, pos);
std::string value = s.substr(pos+1);
if (!rpcCvtTable.convert(strMethod, name)) {
// insert string value directly
params.pushKV(name, value);
} else {
// parse string as JSON, insert bool/number/object/etc. value
params.pushKV(name, ParseNonRFCJSONValue(value));
}
}
return params;
}
| [
"bitcoinold@protonmail.com"
] | bitcoinold@protonmail.com |
64f47e1458608b9e4a50813a2f9ea782da0c6433 | 65ece8de4e4f0b440454c316e6e4fc8702221894 | /chapter4/ex4.7.1.cpp | 3ad596752a4240a1d7e14c021ad25a22ae179f9d | [] | no_license | bobchin/self-study-cpp | da765839cb0b2a5cbd1f03c68988b7e6bacb88ef | fd244d915ebe29eca66aeabff3c0e751553e4157 | refs/heads/master | 2021-01-15T08:32:10.456531 | 2016-10-11T05:03:52 | 2016-10-11T05:03:52 | 68,779,098 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 613 | cpp | #include <iostream>
using namespace std;
class myclass
{
int who;
public:
myclass(int n) {
who = n;
cout << "コンストラクタ呼び出し" << who << "\n";
}
~myclass() { cout << "デストラクタ呼び出し" << who << "\n"; }
int id() { return who; }
};
// myclassオブジェクトを値渡しする
void f(myclass o)
{
cout << "受け取り " << o.id() << "\n";
}
int main()
{
// 値渡ししているのでオブジェクトがコピーされ
// デストラクタが関数の終わりでコールされる
myclass x(1);
f(x);
return 0;
} | [
"k-ichihashi@hokkai-v.co.jp"
] | k-ichihashi@hokkai-v.co.jp |
a6bedb2125e6a6a65bc4e2c6b505beec43c42de5 | c3a424748ca2a3bc8604d76f1bf70ff3fee40497 | /legacy_POL_source/POL_2008/src/clib/sckutil.h | db2cc990fee3681e6fb6a9443e1f9cf6a7818fbf | [] | no_license | polserver/legacy_scripts | f597338fbbb654bce8de9c2b379a9c9bd4698673 | 98ef8595e72f146dfa6f5b5f92a755883b41fd1a | refs/heads/master | 2022-10-25T06:57:37.226088 | 2020-06-12T22:52:22 | 2020-06-12T22:52:22 | 23,924,142 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 379 | h | #ifndef SCKUTIL_H
#define SCKUTIL_H
#include <string>
class Socket;
bool readline( Socket& sck,
std::string& s,
unsigned long interchar_timeout_secs = 0,
unsigned maxlen = 0 );
void writeline( Socket& sck, const std::string& s );
bool readstring( Socket& sck, string& s, unsigned long interchar_secs, unsigned length );
#endif
| [
"hopelivesproject@gmail.com"
] | hopelivesproject@gmail.com |
f3d85195f02824ace4971350cec934c1c1d033ce | 388299829e68a249430ac1c21afc3261ad7ca6dc | /src/test/matrix_io_test.cc | 7abea1e6388c9116efcdc6e348ad76f631b00aee | [
"Apache-2.0"
] | permissive | raindreams/parameter_server-1 | 7c85e5b96145be44b6326dca2f5324726cafc814 | c54bb1913b5d2b2187012eb5f063ab01387943f0 | refs/heads/master | 2021-01-12T22:19:37.490735 | 2014-09-22T02:32:39 | 2014-09-22T02:32:39 | 24,549,568 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,770 | cc | #include "gtest/gtest.h"
#include "base/matrix_io_inl.h"
using namespace PS;
class MatrixIOTest : public ::testing::Test {
protected:
virtual void SetUp() {
}
void verifyRCV1(MatrixPtrList<double> data) {
EXPECT_EQ(data.size(), 2);
auto y = data[0]->value().eigenArray();
EXPECT_EQ(y.size(), 20242);
EXPECT_EQ(y.sum(), 740);
auto X = std::static_pointer_cast<SparseMatrix<uint64, double> >(data[1]);
auto os = X->offset().eigenArray();
// auto idx = X->index().eigenArray();
auto val = X->value().eigenArray();
EXPECT_EQ(os.sum(), 15016151914);
// EXPECT_EQ(idx.sum(), 35335196536);
EXPECT_GE(val.sum(), 138760);
EXPECT_LE(val.sum(), 138770);
EXPECT_EQ(SizeR(1, 47237), SizeR(X->info().col()));
// LL << data[0]->info().DebugString();
// LL << data[0]->debugString();
// LL << data[1]->debugString();
}
};
TEST_F(MatrixIOTest, ReadRCV1Single) {
DataConfig dc;
dc.set_format(DataConfig::TEXT);
dc.set_text(DataConfig::LIBSVM);
dc.add_file("../data/rcv1_train.binary");
auto data = readMatricesOrDie<double>(dc);
verifyRCV1(data);
}
TEST_F(MatrixIOTest, ReadRCV1Multi) {
DataConfig dc;
dc.set_format(DataConfig::TEXT);
dc.set_text(DataConfig::LIBSVM);
dc.add_file("../data/rcv1/train/part.*");
dc.add_file("../data/rcv1/test/part.*");
auto data = readMatricesOrDie<double>(searchFiles(dc));
verifyRCV1(data);
}
TEST_F(MatrixIOTest, ReadADFEA) {
DataConfig dc;
dc.set_format(DataConfig::TEXT);
dc.set_text(DataConfig::ADFEA);
dc.add_file("../../data/ctrc/train/part-0001.gz");
auto data = readMatricesOrDie<double>(dc);
// for (int i = 0; i < data.size(); ++i) {
// data[i]->info().clear_ins_info();
// LL << data[i]->debugString();
// }
}
| [
"muli@cs.cmu.edu"
] | muli@cs.cmu.edu |
7479b30794e09926f655b5a65d801b1d3888a066 | 50e0524989ca0c59fa169169897979e1de28506b | /aliengo_gazebo/src/body.h | 481f0125b96ac4af0b13bcc848ea7f007f664ce9 | [] | no_license | SiChiTong/aliengo_delivery | dfadcf8170b51fc46d474775ded88c951e11aa1d | c4f28b91c32dd42f6043e5a582cc32a87aa3870e | refs/heads/master | 2023-01-31T07:33:46.249875 | 2020-12-09T07:15:39 | 2020-12-09T07:15:39 | 320,000,768 | 1 | 1 | null | 2020-12-09T15:35:48 | 2020-12-09T15:35:47 | null | UTF-8 | C++ | false | false | 820 | h | /************************************************************************
Copyright (c) 2018-2019, Unitree Robotics.Co.Ltd. All rights reserved.
Use of this source code is governed by the MPL-2.0 license, see LICENSE.
************************************************************************/
#ifndef __BODY_H__
#define __BODY_H__
#include "ros/ros.h"
#include "laikago_msgs/LowCmd.h"
#include "laikago_msgs/LowState.h"
#include "laikago_msgs/HighState.h"
#define PosStopF (2.146E+9f)
#define VelStopF (16000.f)
namespace laikago_model {
extern ros::Publisher servo_pub[12];
extern ros::Publisher highState_pub;
extern laikago_msgs::LowCmd lowCmd;
extern laikago_msgs::LowState lowState;
void stand();
void motion_init();
void sendServoCmd();
void moveAllPosition(double* jointPositions, double duration);
}
#endif
| [
"e0444217@u.nus.edu"
] | e0444217@u.nus.edu |
c105f68c2e3379ed124e265ce0505fa8055b16e3 | d2fb019e63eb66f9ddcbdf39d07f7670f8cf79de | /groups/bsl/bslalg/bslalg_bidirectionallink.h | ff9f8579bdb9deced864adcaa629371da52aa650 | [
"MIT"
] | permissive | gosuwachu/bsl | 4fa8163a7e4b39e4253ad285b97f8a4d58020494 | 88cc2b2c480bcfca19e0f72753b4ec0359aba718 | refs/heads/master | 2021-01-17T05:36:55.605787 | 2013-01-15T19:48:00 | 2013-01-15T19:48:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,330 | h | // bslalg_bidirectionallink.h -*-C++-*-
#ifndef INCLUDED_BSLALG_BIDIRECTIONALLINK
#define INCLUDED_BSLALG_BIDIRECTIONALLINK
#ifndef INCLUDED_BSLS_IDENT
#include <bsls_ident.h>
#endif
BSLS_IDENT("$Id: $")
//@PURPOSE: Provide a basic link type for building doubly-linked lists.
//
//@CLASSES:
// bslalg::BidirectionalLink : A node in a doubly-linked list
//
//@SEE_ALSO: bslalg_bidirectionallinklistutil, bslalg_hashtableimputil
//
//@DESCRIPTION: This component provides a single POD-like class,
// 'BidirectionalLink', used to represent a node in a doubly-linked list. A
// 'BidirectionalLink' provides the address to its preceding node, and the
// address of its successor node. A null-pointer value for either address
// signifies the end of the list. 'BidirectionalLink' does not, however,
// contain "payload" data (e.g., a value), as it is intended to work with
// generalized list operations (see 'bslalg_bidirectionallinklistutil').
// Clients creating a doubly-linked list must define their own node type that
// incorporates 'BidirectionalLink' (generally via inheritance), and that
// maintains the "value" stored in that node.
//
//-----------------------------------------------------------------------------
//
///Usage
///-----
// This section illustrates intended usage of this component.
//
///Example 1: Creating and Using a List Template Class
///- - - - - - - - - - - - - - - - - - - - - - - - - -
// Suppose we want to create a linked list template class, it will be called
// 'MyList'.
//
// First, we create the 'MyNode' class, which derives from the
// BidirectionalLink class to carry a 'PAYLOAD' object.
//..
// template <class PAYLOAD>
// class MyNode : public bslalg::BidirectionalLink {
// public:
// // PUBLIC TYPES
// typedef PAYLOAD ValueType;
//
// private:
// // DATA
// ValueType d_value;
//
// private:
// // NOT IMPLEMENTED
// MyNode();
// MyNode(const MyNode&);
// MyNode& operator=(const MyNode&);
//
// public:
// // CREATOR
// ~MyNode() {}
// // Destroy this object.
//
// // MANIPULATOR
// ValueType& value() { return d_value; }
// // Return a reference to the modifiable value stored in this node.
//
// // ACCESSOR
// const ValueType& value() const { return d_value; }
// // Return a reference to the non-modifiable value stored in this
// // node.
// };
//..
// Next, we create the iterator helper class, which will eventually be
// defined as a nested type within the 'MyList' class.
//..
// // ===============
// // MyList_Iterator
// // ===============
//
// template <class PAYLOAD>
// class MyList_Iterator {
// // PRIVATE TYPES
// typedef MyNode<PAYLOAD> Node;
//
// // DATA
// Node *d_node;
//
// // FRIENDS
// template <class PL>
// friend bool operator==(MyList_Iterator<PL>,
// MyList_Iterator<PL>);
//
// public:
// // CREATORS
// MyList_Iterator() : d_node(0) {}
// explicit
// MyList_Iterator(Node *node) : d_node(node) {}
// //! MyList_Iterator(const MyList_Iterator& original) = default;
// //! MyList_Iterator& operator=(const MyList_Iterator& other) = default;
// //! ~MyList_Iterator() = default;
//
// // MANIPULATORS
// MyList_Iterator operator++();
//
// // ACCESSORS
// PAYLOAD& operator*() const { return d_node->value(); }
// };
//..
// Then, we define our 'MyList' class, with 'MyList::Iterator' being a public
// typedef of 'MyList_Iterator'. For brevity, we will omit a lot of
// functionality that a full, general-purpose list class would have,
// implmenting only what we will need for this example.
//..
// // ======
// // MyList
// // ======
//
// template <class PAYLOAD>
// class MyList {
// // PRIVATE TYPES
// typedef MyNode<PAYLOAD> Node;
//
// public:
// // PUBLIC TYPES
// typedef PAYLOAD ValueType;
// typedef MyList_Iterator<ValueType> Iterator;
//
// private:
// // DATA
// Node *d_begin;
// Node *d_end;
// bslma::Allocator *d_allocator_p;
//
// public:
// // CREATORS
// explicit
// MyList(bslma::Allocator *basicAllocator = 0)
// : d_begin(0)
// , d_end(0)
// , d_allocator_p(bslma::Default::allocator(basicAllocator))
// {}
//
// ~MyList();
//
// // MANIPULATORS
// Iterator begin();
// Iterator end();
// void pushBack(const ValueType& value);
// void popBack();
// };
//..
// Next, we implment the functions for the iterator type.
//..
// // ---------------
// // MyList_Iterator
// // ---------------
//
// // MANIPULATORS
// template <class PAYLOAD>
// MyList_Iterator<PAYLOAD> MyList_Iterator<PAYLOAD>::operator++()
// {
// d_node = (Node *) d_node->nextLink();
// return *this;
// }
//
// template <class PAYLOAD>
// inline
// bool operator==(MyList_Iterator<PAYLOAD> lhs,
// MyList_Iterator<PAYLOAD> rhs)
// {
// return lhs.d_node == rhs.d_node;
// }
//
// template <class PAYLOAD>
// inline
// bool operator!=(MyList_Iterator<PAYLOAD> lhs,
// MyList_Iterator<PAYLOAD> rhs)
// {
// return !(lhs == rhs);
// }
//..
// Then, we implement the functions for the 'MyList' class:
//..
// // ------
// // MyList
// // ------
//
// // CREATORS
// template <class PAYLOAD>
// MyList<PAYLOAD>::~MyList()
// {
// for (Node *p = d_begin; p; ) {
// Node *toDelete = p;
// p = (Node *) p->nextLink();
//
// d_allocator_p->deleteObjectRaw(toDelete);
// }
// }
//
// // MANIPULATORS
// template <class PAYLOAD>
// typename MyList<PAYLOAD>::Iterator MyList<PAYLOAD>::begin()
// {
// return Iterator(d_begin);
// }
//
// template <class PAYLOAD>
// typename MyList<PAYLOAD>::Iterator MyList<PAYLOAD>::end()
// {
// return Iterator(0);
// }
//
// template <class PAYLOAD>
// void MyList<PAYLOAD>::pushBack(const PAYLOAD& value)
// {
// Node *node = (Node *) d_allocator_p->allocate(sizeof(Node));
// node->setNextLink(0);
// node->setPreviousLink(d_end);
// bslalg::ScalarPrimitives::copyConstruct(&node->value(),
// value,
// d_allocator_p);
//
// if (d_end) {
// BSLS_ASSERT_SAFE(d_begin);
//
// d_end->setNextLink(node);
// d_end = node;
// }
// else {
// BSLS_ASSERT_SAFE(0 == d_begin);
//
// d_begin = d_end = node;
// }
// }
//
// template <class PAYLOAD>
// void MyList<PAYLOAD>::popBack()
// {
// BSLS_ASSERT_SAFE(d_begin && d_end);
//
// Node *toDelete = d_end;
// d_end = (Node *) d_end->previousLink();
//
// if (d_begin != toDelete) {
// BSLS_ASSERT_SAFE(0 != d_end);
// d_end->setNextLink(0);
// }
// else {
// BSLS_ASSERT_SAFE(0 == d_end);
// d_begin = 0;
// }
//
// d_allocator_p->deleteObject(toDelete);
// }
//..
// Next, in 'main', we use our 'MyList' class to store a list of ints:
//..
// MyList<int> intList;
//..
// Then, we declare an array of ints to populate it with:
//..
// int intArray[] = { 8, 2, 3, 5, 7, 2 };
// enum { NUM_INTS = sizeof intArray / sizeof *intArray };
//..
// Now, we iterate, pushing ints to the list:
//..
// for (const int *pInt = intArray; pInt < intArray + NUM_INTS; ++pInt) {
// intList.pushBack(*pInt);
// }
//..
// Finally, we use our 'Iterator' type to traverse the list and observe its
// values:
//..
// MyList<int>::Iterator it = intList.begin();
// assert(8 == *it);
// assert(2 == *++it);
// assert(3 == *++it);
// assert(5 == *++it);
// assert(7 == *++it);
// assert(2 == *++it);
// assert(intList.end() == ++it);
//..
#ifndef INCLUDED_BSLSCM_VERSION
#include <bslscm_version.h>
#endif
namespace BloombergLP {
namespace bslalg {
// =======================
// class BidirectionalLink
// =======================
class BidirectionalLink {
// This POD-like 'class' describes a node suitable for use in a doubly-
// linked (bidirectional) list, holding the addresses of the preceding and
// succeeding nodes, either or both of which may be 0. This class is
// "POD-like" to facilitate efficient allocation and use in the context of
// a container implementations. In order to meet the essential
// requirements of a POD type, this 'class' does not declare a constructor
// or destructor. However its data members are private. It satisfies the
// requirements of a *trivial* type and a *standard* *layout* type defined
// by the C++11 standard. Note that this type does not contain any
// "payload" member data: Clients creating a doubly-linked list of data
// must define an appropriate node type that incorporates
// 'BidirectionalLink' (generally via inheritance), and that holds the
// "value" of any data stored in that node.
private:
// DATA
BidirectionalLink *d_next_p; // The next node in a list traversal
BidirectionalLink *d_prev_p; // The preceding node in a list traversal
public:
// CREATORS
//! BidirectionalLink() = default;
// Create a 'BidirectionalLink' object having uninitialized values,
// or zero-initialized values if value-initialized.
//! BidirectionalLink(const BidirectionalLink& original) = default;
// Create a 'BidirectionalLink' object having the same data member
// values as the specified 'original' object.
//! ~BidirectionalLink() = default;
// Destroy this object.
// MANIPULATORS
//! BidirectionalLink& operator= (const BidirectionalLink& rhs) = default;
// Assign to the data members of this object the values of the data
// members of the specified 'rhs' object, and return a reference
// providing modifiable access to this object.
void setNextLink(BidirectionalLink *next);
// Set the successor of this node to be the specified 'next' link.
void setPreviousLink(BidirectionalLink *previous);
// Set the predecessor of this node to be the specified 'prev' link.
void reset();
// Set the 'nextLink' and 'previousLink' attributes of this value to 0.
// ACCESSORS
BidirectionalLink *nextLink() const;
// Return the address of the next node linked from this node.
BidirectionalLink *previousLink() const;
// Return the address of the preceding node linked from this node.
};
// ===========================================================================
// TEMPLATE AND INLINE FUNCTION DEFINITIONS
// ===========================================================================
//------------------------
// class BidirectionalLink
//------------------------
// MANIPULATORS
inline
void BidirectionalLink::setNextLink(BidirectionalLink *next)
{
d_next_p = next;
}
inline
void BidirectionalLink::setPreviousLink(BidirectionalLink *previous)
{
d_prev_p = previous;
}
inline
void BidirectionalLink::reset()
{
d_prev_p = 0;
d_next_p = 0;
}
// ACCESSORS
inline
BidirectionalLink *BidirectionalLink::nextLink() const
{
return d_next_p;
}
inline
BidirectionalLink *BidirectionalLink::previousLink() const
{
return d_prev_p;
}
} // close namespace bslalg
} // close enterprise namespace
#endif
// ----------------------------------------------------------------------------
// Copyright (C) 2012 Bloomberg L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
| [
"abeels@bloomberg.net"
] | abeels@bloomberg.net |
c01abc4221d204f7b00785a4efb7dc23025165c0 | d31b701323aa0d0752fee4a373c8e41f0304f5f8 | /lge_texcache.cpp | 92cbd545ace9f237d3e2e6d74d9b2565dc89fa79 | [
"CC0-1.0"
] | permissive | lieff/lge | 444c2b93ad6b9cb92585e9dce3617bbe98d77c29 | 2738ddcdb83431a5113bdce06fac80d7571a39ee | refs/heads/master | 2020-04-22T02:55:15.575204 | 2015-09-08T16:26:50 | 2015-09-08T16:26:50 | 42,123,892 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,328 | cpp | #include "lge_texcache.h"
CTexturesCache::CTexturesCache()
{
m_tex_ssbo_buf = 0;
m_ssbo_buf_size = 0;
m_commit_needed = false;
m_textures.reserve(16);
m_tex_handles.reserve(16);
}
CTexturesCache::~CTexturesCache()
{
DeleteTexturesBlock(0, (unsigned int)m_textures.size());
}
unsigned int CTexturesCache::AllocTexture()
{
GLuint texId = 0;
glGenTextures(1, &texId);
if (!m_free_gaps.empty())
{
std::map<unsigned int, bool>::iterator it = m_free_gaps.begin();
m_textures[it->first] = texId;
m_tex_handles[it->first] = 0;
m_free_gaps.erase(it);
return it->first;
}
if (m_textures.size() == m_textures.capacity())
{
m_textures.reserve(m_textures.capacity() * 2);
m_tex_handles.reserve(m_textures.capacity() * 2);
}
m_textures.push_back(texId);
m_tex_handles.push_back(0);
m_commit_needed = true;
return (unsigned int)(m_textures.size() - 1);
}
unsigned int CTexturesCache::AllocTexture(unsigned int width, unsigned int height, void *image)
{
unsigned int tex = AllocTexture();
glBindTexture(GL_TEXTURE_2D, m_textures[tex]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image);
pglGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
GLuint64 texHandle = pglGetTextureHandleNV(m_textures[tex]);
pglMakeTextureHandleResidentNV(texHandle);
m_tex_handles[tex] = texHandle;
return tex;
}
bool CTexturesCache::AllocTextureBlock(unsigned int count, unsigned int *texs)
{
for (unsigned int i = 0; i < count; i++)
texs[i] = AllocTexture();
return true;
}
unsigned int CTexturesCache::LoadTexture(const char *filename)
{
int tex = AllocTexture();
return tex;
}
bool CTexturesCache::LoadToTexture(unsigned int tex, const char *filename)
{
return true;
}
void CTexturesCache::DeleteTexture(unsigned int tex)
{
glDeleteTextures(1, &m_textures[tex]);
m_textures[tex] = 0;
m_tex_handles[tex] = 0;
m_free_gaps[tex] = true;
}
void CTexturesCache::DeleteTexturesBlock(unsigned int first, unsigned int count)
{
for (unsigned int i = 0; i < count; i++)
DeleteTexture(i);
}
void CTexturesCache::DeleteTexturesBuf(unsigned int *texs, unsigned int count)
{
for (unsigned int i = 0; i < count; i++)
DeleteTexture(texs[i]);
}
void CTexturesCache::CommitToGPU()
{
if (!m_commit_needed || m_tex_handles.size() == 0)
return;
bool allocated = false;
if (m_tex_handles.size() != m_ssbo_buf_size)
{
if (m_tex_ssbo_buf)
pglDeleteBuffers(1, &m_tex_ssbo_buf);
pglGenBuffers(1, &m_tex_ssbo_buf);
allocated = true;
}
pglBindBuffer(GL_UNIFORM_BUFFER, m_tex_ssbo_buf);
if (allocated)
pglBufferData(GL_UNIFORM_BUFFER, m_tex_handles.size()*sizeof(GLuint64), &m_tex_handles[0], GL_DYNAMIC_DRAW);
else
pglBufferSubData(GL_UNIFORM_BUFFER, 0, m_tex_handles.size()*sizeof(GLuint64), &m_tex_handles[0]);
pglBindBufferRange(GL_SHADER_STORAGE_BUFFER, TEX_SSBO_BINDING, m_tex_ssbo_buf, 0, m_tex_handles.size()*sizeof(GLuint64));
pglBindBuffer(GL_UNIFORM_BUFFER, 0);
}
| [
"lieff@users.noreply.github.com"
] | lieff@users.noreply.github.com |
9b86b7fbc7674926693b9f1ae7ccb69aac45400a | 9bbc105183d2241fa7204201e3dac18078bdc14c | /cpp/src/msgpack/rpc/session_pool.cc | e0a9d551285999f0aba53949d874653db501b37a | [
"Apache-2.0"
] | permissive | nowelium/msgpack-rpc | f220a4b0d2849f18abce72b7a55e44ab7afc715e | a9a5762d981524d7559bc67ba2feb0f4e58bf188 | refs/heads/master | 2021-01-17T12:06:04.481011 | 2010-06-08T11:50:25 | 2010-06-08T11:50:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,093 | cc | //
// msgpack::rpc::session_pool - MessagePack-RPC for C++
//
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "session_pool.h"
#include "session_impl.h"
namespace msgpack {
namespace rpc {
MP_UTIL_DEF(session_pool) {
bool step_timeout();
};
session_pool::session_pool(loop lo) :
loop_util(lo)
{
m_loop->add_timer(1.0, 1.0,
mp::bind(&MP_UTIL_IMPL(session_pool)::step_timeout, &MP_UTIL));
// FIXME thisの寿命: weak_ptrのlock()が失敗したらタイマーを終了?
//start_timer(&t, &t,
// mp::bind(&session_pool::step_timeout, this,
// mp::weak_ptr<session_pool>(shared_from_this()) ));
}
session_pool::~session_pool()
{
}
session session_pool::get_session(const address& addr)
{
table_ref ref(m_table);
table_t::iterator found = ref->find(addr);
if(found != ref->end()) {
shared_session s = found->second.lock();
if(s) {
return session(s);
}
}
shared_session s = create_session(addr);
ref->insert( table_t::value_type(addr, weak_session(s)) );
return session(s);
}
shared_session session_pool::create_session(const address& addr)
{
return shared_session(new session_impl(
addr, m_default_opt, address(), NULL, m_loop));
}
bool MP_UTIL_IMPL(session_pool)::step_timeout()
{
table_ref ref(m_table);
for(table_t::iterator it(ref->begin());
it != ref->end(); ) {
shared_session s(it->second.lock());
if(s) {
s->step_timeout();
++it;
} else {
ref->erase(it++);
}
}
return true;
}
} // namespace rpc
} // namespace msgpack
| [
"frsyuki@users.sourceforge.jp"
] | frsyuki@users.sourceforge.jp |
04627e49abe72378ce57c80066d3472ee4d9ea35 | 0ecfa021ff82d67132b18ffe6ad7ad05c4e3a71d | /Convolutional Code/S_random interleaver/s-random.cpp | 331305507e035a0937e85f22217c0a800d4a0d6f | [] | no_license | JosephHuang913/Channel-Coding | 954673264db96cc4c882a09fca6e818b4c2e8584 | 6e6efa9f3970a93a343b8ec36f49365df5607e30 | refs/heads/main | 2023-01-21T00:08:12.570899 | 2020-11-24T01:07:35 | 2020-11-24T01:07:35 | 315,481,921 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,622 | cpp | /**********************************************/
/* Author: Chao-wang Huang */
/* Date: Thursday, September 23, 2004 */
/* S-random interleaver generator */
/**********************************************/
#include <stdio.h>
#include <math.h>
//#include <time.h>
#include <ctime>
#include <conio.h>
#include <stdlib.h>
#include <iostream>
#include <stdafx.h>
using namespace std;
#define N 2048 // Interleaver size
#define S 32 // S parameter of S-random interleaver
int main(void)
{
time_t t, start, end;
int i, j, k, sol, position, flag, count, *interleaver, *check;
FILE *fp1;
start = time(NULL);
printf("S-random Interleaver Generator\n");
printf("This program is running. Don't close, please!\n\n");
srand((unsigned) time(&t));
interleaver = new int[N];
check = new int[N];
fp1 = fopen("s_random.txt", "w");
count = 0;
do
{
count ++;
for(i=0; i<N; i++)
check[i] = 0;
for(i=0; i<N; i++)
{
do
{
flag = 0;
//position = random(N);
position = rand() % N;
if(check[position]==1)
flag = 1;
else
{
for(j=i-1; (j>i-S && j>=0); j--)
if(abs(position - interleaver[j]) < S)
{
flag = 1;
break;
}
if(flag==1)
{
for(k=0; k<N; k++)
if(check[k]==0)
{
sol = 1;
for(j=i-1; (j>i-S && j>=0); j--)
if(abs(k - interleaver[j]) < S)
{
sol = 0;
break;
}
if(sol==1)
break;
}
if(sol==0)
{
flag = 0;
}
}
}
}
while(flag);
// printf("%d %d\n", i, position);
// cout << i << " " << position << endl;
check[position] = 1;
interleaver[i] = position;
}
}
while(sol==0);
cout << endl << "Iteration: " << count << endl;
for(i=0; i<N; i++)
fprintf(fp1, "%d %d\n", i, interleaver[i]);
delete interleaver;
delete check;
fclose(fp1);
end = time(NULL);
printf("Total elapsed time: %.0f(sec)\n", difftime(end,start));
printf("This program is ended. Press any key to continue.\n");
getch();
return 0;
}
| [
"huangcw913@gmail.com"
] | huangcw913@gmail.com |
73497bc7b6d44357f434c69ef5ef567cdb63c810 | d5328e2f5c2817cf8e558119f7084528a9ab75eb | /src/std/rng.cpp | 218aa8f25fab20a860cf974bdd8622c71e422692 | [
"MIT"
] | permissive | arudei-dev/Feral | a0e31517fd809533b5b1b8836c69fb991cf0d1c1 | 44c0254f9f85dbf0f11f8cc1f86dc106f6a16d92 | refs/heads/master | 2023-06-09T11:24:00.851064 | 2021-06-29T13:21:59 | 2021-06-29T13:22:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,755 | cpp | /*
MIT License
Copyright (c) 2021 Feral Language repositories
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.
*/
#include <random>
#include "VM/VM.hpp"
gmp_randstate_t rngstate;
//////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////// Functions ////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
var_base_t *rng_seed(vm_state_t &vm, const fn_data_t &fd)
{
if(!fd.args[1]->istype<var_int_t>()) {
vm.fail(fd.src_id, fd.idx, "expected seed value to be integer, found: %s",
vm.type_name(fd.args[1]).c_str());
return nullptr;
}
gmp_randseed(rngstate, INT(fd.args[1])->get());
return vm.nil;
}
// [0, to)
var_base_t *rng_get(vm_state_t &vm, const fn_data_t &fd)
{
if(!fd.args[1]->istype<var_int_t>()) {
vm.fail(fd.src_id, fd.idx, "expected upper bound to be an integer, found: %s",
vm.type_name(fd.args[1]).c_str());
return nullptr;
}
var_int_t *res = make<var_int_t>(0);
mpz_urandomm(res->get(), rngstate, INT(fd.args[1])->get());
return res;
}
INIT_MODULE(rng)
{
gmp_randinit_default(rngstate);
var_src_t *src = vm.current_source();
src->add_native_fn("seed", rng_seed, 1);
src->add_native_fn("get_native", rng_get, 1);
return true;
}
DEINIT_MODULE(rng)
{
gmp_randclear(rngstate);
} | [
"ElectruxRedsworth@gmail.com"
] | ElectruxRedsworth@gmail.com |
1765c3149420624afd5706ed72ee3f974a935d11 | 5c0bc7d833e37161ad7409d2e56fd1207e3234b2 | /HW_5/exam.cpp | 478ea8787b52a1a642018fd0a0debb5d15790edb | [] | no_license | gabrieletrata/MTH_3300 | 9888c00b2c75cca307817fd7c19cdfe36123fe77 | 24030cac363181b50841bf73ad8ee0547393d6a3 | refs/heads/master | 2020-03-24T05:56:59.347450 | 2018-07-27T00:58:38 | 2018-07-27T00:58:38 | 142,510,175 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,838 | cpp | //******************************************************************************
// exam.cpp
// Computes the probability of passing an exam.
// This exam is 35 multiple choice questions, with 5 choices per question.
// A score of 11, or greater is considered a pass.
//******************************************************************************
// Name: Gabriel Etrata
// Class: MTH 3300
// Professor: Evan Fink
// Homework_5
//******************************************************************************
// Collaborators/outside sources used: @Evan Fink
//******************************************************************************
// @author Gabriel Etrata
// @version 1.0 03/19/17
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <ctime>
#include <iomanip>
using namespace std;
//Initializes program
int main()
{
srand ((time(NULL))); //ignore precision error;
int trials = 1e6;
double questions[35];
int questionsRight = 0;
double numOfPasses = 0;
double probability;
for(int i = 0; i < trials; i++){ //runs 1e6 simulations
questionsRight = 0; //reset questionsRight to 0 after each simulation
for(int j = 0; j < 35; j++){ //runs through 35 questions
questions[j] = ((rand() % 5) + 1);
if(questions[j] == 5){
questionsRight++; //if choice 5 is picked, increment questionsRight
}
if(questionsRight >= 11){
numOfPasses++; //if questionsRight >= 11, increment numOfPasses
questionsRight = 0; //reset questionsRight back to 0 after each exam trial is finished
}
}
}
probability = numOfPasses/trials; //compute the probability of event
cout << setprecision (3) << probability << endl;
system("pause");
return 0;
}
| [
"gabrieletrata@gmail.com"
] | gabrieletrata@gmail.com |
9a269666a41104087c46932f21163b0f89806dbe | 3a6b77c6d8b8997334468667df5a92b2fba6dd26 | /twain-v2/twain_png.cpp | ea0341ae87a2d651eb173e8900308117d8d78f47 | [] | no_license | miyako/4d-plugin-twain | 0071bcc723915268200b1fc8502cb43c72316f76 | 79ed909badc39cbef3897cfc3effccb9315ae71d | refs/heads/master | 2022-04-12T10:31:56.962629 | 2020-04-05T03:01:42 | 2020-04-05T03:01:42 | 104,451,668 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,382 | cpp | #include "twain_png.h"
void PNG::write_data_fn(png_structp png_ptr, png_bytep buf, png_size_t size)
{
C_BLOB *blob = (C_BLOB *)png_get_io_ptr(png_ptr);
blob->addBytes((const uint8_t *)buf, (uint32_t)size);
}
void PNG::output_flush_fn(png_structp png_ptr)
{
}
void png_write_blob(C_BLOB &data, C_BLOB &picture,
int width,
int height,
int depth,
int bytes_per_line,
int color,
int dpi_x,
int dpi_y)
{
C_BLOB png;
png_structp png_ptr;
png_infop info_ptr;
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if(png_ptr)
{
info_ptr = png_create_info_struct(png_ptr);
if(info_ptr)
{
if(setjmp(png_jmpbuf(png_ptr)))
{
png_destroy_write_struct(&png_ptr, &info_ptr);
}else{
png_set_write_fn(png_ptr, (png_voidp)&png, PNG::write_data_fn, PNG::output_flush_fn);
png_set_IHDR(png_ptr, info_ptr,
width, //pixels_per_line
height,//lines
depth,
color,
PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT,
PNG_FILTER_TYPE_DEFAULT);
png_set_pHYs(png_ptr, info_ptr,
dpi_x * INCHES_PER_METER,
dpi_y * INCHES_PER_METER,
PNG_RESOLUTION_METER);
//TODO:support icc_profile
png_write_info(png_ptr, info_ptr);
unsigned char *p = (unsigned char *)data.getBytesPtr();
/*
//takes as much time, with no way to yield
std::vector<png_byte *>rows(height);
for(int y = 0; y < height; y++)
{
rows[y] = p;
p += bytes_per_line;
}//height
png_write_image(png_ptr, &rows[0]);
*/
for(int y = 0; y < height; y++)
{
//byteswap for depth 16
if (depth == 16)
{
unsigned char *byte_l, *byte_h, *ptr;
ptr = p;
for (int j = 0; j < bytes_per_line; j += 2)
{
byte_l = ptr;
byte_h = ptr + 1;
unsigned char b = *byte_l;
*byte_l = *byte_h;
*byte_h = b;
ptr += 2;
}
}
png_write_row(png_ptr, p);
p += bytes_per_line;
}//height
png_write_end(png_ptr, info_ptr);
png_destroy_write_struct(&png_ptr, &info_ptr);
size_t outbuffersize = png.getBytesLength();
picture.addBytes((const uint8_t *)&outbuffersize, sizeof(outbuffersize));
}
}
}
}
| [
"miyako@wakanda.jp"
] | miyako@wakanda.jp |
3ab0453f080f4bb201b3210c8febf37062e197d8 | c82d5b7031d567ad7b76f1a9fffafb717b5e23de | /面试高频题/HashTable.h | 322222c313342c1ca8fbee8f693a7d48a6b1077a | [] | no_license | newhandLiu/First | 55cd2715df924423f6afacc59a4cfe925284a0e2 | 37d1ba62531737a0809f74c298d1b013048e8aca | refs/heads/master | 2021-01-01T17:00:07.552590 | 2012-04-23T05:58:19 | 2012-04-23T05:58:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,307 | h | //链地址散列表
#ifndef HASHTABLE_H
#define HASHTABLE_H
#include<vector>
#include<list>
#include<string>
#include<algorithm>
using namespace std;
template<class T>
class HashTable
{
public:
explicit HashTable(int size=101);
bool contains(const T& obj)const;
void clear();
bool insert(const T& obj);
bool remove(const T& obj);
private:
void reHash();//expand the size of HashTable
int myHash(const T& obj)const; //hash function
private:
vector<list<T> > theLists; //The array of lists
int currentSize;
};
int hash(string key);
int hash(int key);
#endif
int hash(string key)
{
int hashVal = 0;
for(int i=0; i<key.length(); ++i)
{
hashVal = 37*hashVal + key[i];
}
return hashVal;
}
int hash(int key)
{
return key*key;
}
template<class T>
int HashTable<T>::myHash(const T& obj)const
{
int hashVal = hash(obj);
hashVal %= theLists.size();
if(hashVal<0)
hashVal += theLists.size();
return hashVal;
}
template<class T>
void HashTable<T>::reHash()
{
vector<list<T> > oldLists = theLists;
theLists.resize(theLists.size()*2);
int i;
for(i=0; i<theLists.size(); ++i)
{
theLists[i].clear();
}
typename list<T>::iterator itr;
currentSize = 0;
for(i=0; i<oldLists.size(); ++i)
{
itr = oldLists[i].begin();
while(itr!=oldLists[i].end())
{
insert(*itr++);
}
}
}
template<class T>
HashTable<T>::HashTable(int size)
:theLists(size)
{
clear();
}
template<class T>
bool HashTable<T>::contains(const T& obj)const
{
const list<T> & theList = theLists[myHash(obj)];
return (find(theList.begin(), theList.end(), obj)!=theList.end());
}
template<class T>
void HashTable<T>::clear()
{
for(int i=0; i<theLists.size(); i++)
{
theLists[i].clear();
}
currentSize = 0;
}
template<class T>
bool HashTable<T>::insert(const T& obj)
{
list<T> & theList = theLists[myHash(obj)];
if(find(theList.begin(), theList.end(), obj)==theList.end())
{
theList.push_back(obj);
if(++currentSize>theLists.size())
{
reHash();
}
return true;
}
else
{
return false;
}
}
template<class T>
bool HashTable<T>::remove(const T& obj)
{
list<T>& theList = theLists[myHash(obj)];
typename list<T>::iterator itr = find(theList.begin(), theList.end(), obj);
if(itr!=theList.end())
{
theList.erase(itr);
--currentSize;
return true;
}
else
{
return false;
}
}
| [
"dearliujun@gmail.com"
] | dearliujun@gmail.com |
f1338377d4bfc15dee127bcec2220087e998249d | cd5cb70f499898578772195a217ce3b9c9c606ba | /common/redisapi/redisbase.hpp | 07f993bda51aac00154ef4a27ee61c8e0291cbee | [] | no_license | qinchun2000/autotrader | 9aa6ebdef31a01597f52c55cedea1c7f22de6279 | 8651754e2562188a5acf9ac400e9709c693afe5e | refs/heads/main | 2023-03-21T19:25:07.257203 | 2021-03-08T09:40:22 | 2021-03-08T09:40:22 | 340,294,521 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 876 | hpp | #ifndef _REDISBASE_H_
#define _REDISBASE_H_
#include <iostream>
#include <string.h>
#include <string>
#include <stdio.h>
#include <hiredis/hiredis.h>
#include <json/json.h>
#include "depthmarket.hpp"
using namespace std;
class RedisBase
{
public:
RedisBase();
~RedisBase();
std::string GetHost();
void SetDbNumber(int num);
int GetDbNumber();
redisContext *GetRedisContext();
void SetRedisReply(redisReply *reply);
redisReply *GetRedisReply();
bool Connect(string host, int port);
void DisConnect();
void Empty();
void SelectDb();
void SelectDb(int num);
int GetDbSize();
int Exists(string key);
void FlushDB();
string Get(string key);
void Set(string key, string value);
private:
redisContext* _connect=nullptr;
redisReply *_reply=nullptr;
std::string _host;
int _port;
int _dbnumber=0;
};
#endif //_REDISBASE_H_
| [
"root@localhost.localdomain"
] | root@localhost.localdomain |
00e97a5d1663024ba9e5858d25fab591af090fb7 | 39a6b3e717a3b49bbca508b4b8c602d99e6b08f5 | /tensorflow/compiler/mlir/xla/hlo_utils.cc | bfa57d97336ee88e7d73cb126036bcca10330718 | [
"Apache-2.0"
] | permissive | lucigrigo/tensorflow | a584b81c9c7de513197a5ef9aabf1eb3411b5cce | 39ee10bb064086ea7fd6d4cb831e02958671cfb7 | refs/heads/master | 2020-12-10T11:58:37.722788 | 2020-01-13T10:20:58 | 2020-01-13T10:20:58 | 233,582,234 | 2 | 0 | Apache-2.0 | 2020-04-16T17:12:35 | 2020-01-13T11:40:52 | null | UTF-8 | C++ | false | false | 3,134 | cc | /* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// This file defines helpers useful when creating or manipulating lhlo/hlo.
#include "tensorflow/compiler/mlir/xla/hlo_utils.h"
#include "mlir/IR/Attributes.h" // TF:llvm-project
#include "mlir/IR/StandardTypes.h" // TF:llvm-project
#include "mlir/IR/TypeUtilities.h" // TF:llvm-project
#include "tensorflow/compiler/xla/literal.h"
namespace xla {
namespace {
using mlir::Builder;
using mlir::DenseElementsAttr;
using mlir::ShapedType;
using xla::Literal;
using xla::StatusOr;
template <typename CppType>
::mlir::DenseElementsAttr CreateDenseAttrFromLiteral(const ShapedType& type,
const Literal& literal) {
auto data_span = literal.data<CppType>();
return ::mlir::DenseElementsAttr::get(
type, llvm::makeArrayRef(data_span.data(), data_span.size()));
}
} // namespace
StatusOr<mlir::DenseElementsAttr> CreateDenseElementsAttrFromLiteral(
const Literal& literal, Builder builder) {
TF_ASSIGN_OR_RETURN(auto type,
ConvertTensorShapeToType<mlir::RankedTensorType>(
literal.shape(), builder));
auto element_type = literal.shape().element_type();
switch (element_type) {
case PrimitiveType::PRED:
return CreateDenseAttrFromLiteral<bool>(type, literal);
case PrimitiveType::F16:
return CreateDenseAttrFromLiteral<float>(type, literal);
case PrimitiveType::F32:
return CreateDenseAttrFromLiteral<float>(type, literal);
case PrimitiveType::F64:
return CreateDenseAttrFromLiteral<double>(type, literal);
case PrimitiveType::S8:
return CreateDenseAttrFromLiteral<int8>(type, literal);
case PrimitiveType::S16:
return CreateDenseAttrFromLiteral<int16>(type, literal);
case PrimitiveType::S32:
return CreateDenseAttrFromLiteral<int32>(type, literal);
case PrimitiveType::S64:
return CreateDenseAttrFromLiteral<int64>(type, literal);
default:
return tensorflow::errors::Internal(
absl::StrCat("Unsupported type: ", PrimitiveType_Name(element_type)));
}
}
mlir::DenseIntElementsAttr CreateDenseIntElementsAttrFromVector(
const llvm::ArrayRef<int64> vector, mlir::Builder builder) {
return mlir::DenseIntElementsAttr::get(
mlir::RankedTensorType::get(vector.size(),
builder.getIntegerType(64)),
vector)
.cast<mlir::DenseIntElementsAttr>();
}
} // namespace xla
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
747caa5696a175c03637a3efc80546768a7c0fb2 | 93f4aa14d544952c0fdc7ed29404d47fd2fda32a | /Source/Delay.cpp | 37fe8ae75f4c84f412d16d7bd8e7c69ad01d1ca8 | [] | no_license | harpershapiro/BuzzSaw | be2c248d8cfa58f5009ddbfd8889a6106695ef20 | c2f92771464ac48f2f6a2a66358507b99a77fac2 | refs/heads/master | 2022-12-10T07:43:17.715081 | 2020-09-07T22:27:01 | 2020-09-07T22:27:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,369 | cpp | /*
==============================================================================
Delay.cpp
Created: 23 May 2020 5:47:22pm
Author: harpe
==============================================================================
*/
#include "Delay.h"
Delay::Delay() : delayWritePosition(0), delayReadPosition(0)
{
}
Delay::~Delay() {
}
void Delay::initialize(double sampleRate) {
// Allocate and zero the delay buffer (size will depend on current sample rate)
delayBufferLength = static_cast<int>(2.0 * sampleRate);
//sanity check length
if (delayBufferLength < 1) delayBufferLength = 1;
delayBuffer.setSize(1, delayBufferLength);
delayBuffer.clear();
this->sampleRate = sampleRate;
delayReadPosition = static_cast<int>(delayWritePosition - (delaySec * sampleRate)
+ delayBufferLength) % delayBufferLength;
setActive(true);
}
//process a single channel
void Delay::processBlock(float* buffer, const int numSamples) {
//bypassed
if (!isActive || delaySec<=0) {
return;
}
//temps for write and read positions
int dpr = delayReadPosition;
int dpw = delayWritePosition;
//assuming a single channel so i'll just use the left
float* delayData = delayBuffer.getWritePointer(0);
//
for (int i = 0; i < numSamples; i++) {
const float in = buffer[i];
float out = 0.0;
//output blended
out = (dryLevel * in) + (wetLevel * delayData[dpr]);
delayData[dpw] = in + (delayData[dpr] * feedback);
//increment + wrap r/w positions
if (++dpr >= delayBufferLength) dpr = 0;
if (++dpw >= delayBufferLength) dpw = 0;
buffer[i] = out;
}
//write back r/w positions
delayReadPosition = dpr;
delayWritePosition = dpw;
}
void Delay::setDelaySec(float ds) {
delaySec = ds;
//just trying this to parameterize delaySec
delayReadPosition = static_cast<int>(delayWritePosition - (delaySec * sampleRate)
+ delayBufferLength) % delayBufferLength;
}
void Delay::setFeedback(float fb) {
feedback = fb;
}
void Delay::setWetLevel(float wl) {
wetLevel = wl;
}
void Delay::setDryLevel(float dl) {
dryLevel = dl;
}
void Delay::setActive(bool state) {
isActive = state;
//clear buffer when disabled
if (!state) {
delayBuffer.clear();
}
} | [
"harper.shapiro@gmail.com"
] | harper.shapiro@gmail.com |
91d4679d82f33124715e5012d041495a05108cdb | 33a0162aa373ecf1e99fa587bd5d7a09ad6c81ab | /lib/tvseg/settings/serializerbase.h | 0898368bd7a4d389ae17e0bd0bfd038598f1e125 | [
"MIT",
"BSD-3-Clause",
"BSL-1.0",
"BSD-2-Clause"
] | permissive | nihalsid/tvseg | 8b972febb36964bca57455edcdcebb096e81b07a | a97a63f81cc45d25f450199e044f041f5d81c150 | refs/heads/master | 2020-04-19T14:23:51.751661 | 2019-01-29T23:06:20 | 2019-01-29T23:06:20 | 168,243,627 | 0 | 0 | null | 2019-01-29T23:03:37 | 2019-01-29T23:03:37 | null | UTF-8 | C++ | false | false | 1,118 | h | #ifndef TVSEG_SETTINGS_SERIALIZERBASE_H
#define TVSEG_SETTINGS_SERIALIZERBASE_H
#include "serializer.h"
#include "backend.h"
namespace tvseg {
namespace settings {
class SerializerBase : public Serializer
{
public: // types
typedef Backend::iterator iterator;
typedef Backend::const_iterator const_iterator;
public:
SerializerBase(BackendPtr backend, std::string location = "");
// Serializer interface
public:
void save(std::string location = "");
void load(std::string location = "");
protected:
virtual void saveImpl(std::string location) = 0;
virtual void loadImpl(std::string location) = 0;
iterator begin() { return backend_->begin(); }
const_iterator begin() const { return backend_->begin(); }
iterator end() { return backend_->end(); }
const_iterator end() const { return backend_->end(); }
BackendConstPtr backend() const { return backend_; }
BackendPtr backend() { return backend_; }
private:
BackendPtr backend_;
std::string lastLocation_;
};
} // namespace settings
} // namespace tvseg
#endif // TVSEG_SETTINGS_SERIALIZERBASE_H
| [
"nikolaus@nikolaus-demmel.de"
] | nikolaus@nikolaus-demmel.de |
17d5e8f0e19ff0de249bc01951094aa1b308a5e6 | 719e93f4e5799fb75ed99a4e3f69abd6ad9b8895 | /lab_1/main.cpp | fde6ec0013a8213dea1912901cc2140a3ab2ce3e | [] | no_license | rafal166/pamsi_project | acdad488901779ef1f904f8a05d11d7b7b75c7ea | ba4d25b838f602c47b7156dd2d629634459d2d1d | refs/heads/master | 2021-02-13T17:20:24.457833 | 2020-05-07T11:39:00 | 2020-05-07T11:39:00 | 244,716,117 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,308 | cpp | /*
* File: main.cpp
* Author: rafal
*
* Created on 24 marca 2020, 17:37
*/
#include <cstdlib>
#include <iostream>
#include <vector>
#include <cmath>
#include <memory>
#include <time.h>
#include <thread>
#include "utilities.h"
#include "MergeSort.h"
#include "HeapSort.h"
#include "QuickSort.h"
#include "IntroSort.h"
#include "CSVSaver.h"
using namespace std;
#define NUM_ARRAYS 100
#define NUM_ELEM_IN_ARRAY_LV0 10000 // A
#define NUM_ELEM_IN_ARRAY_LV1 50000 // B
#define NUM_ELEM_IN_ARRAY_LV2 100000 // C
#define NUM_ELEM_IN_ARRAY_LV3 500000 // D
#define NUM_ELEM_IN_ARRAY_LV4 1000000 // E
#define SAVING_VERSION 4
vector<string> CSVcolumnList = {"sortType", "A", "B", "C", "D", "E"};
vector<float> sortTypes = {0, 25, 50, 75, 95, 99, 99.7};
void test_merge_sort() {
CSVSaver saver = CSVSaver("MergeSort_" + to_string(SAVING_VERSION) + ".csv", CSVcolumnList);
shared_ptr<vector < shared_ptr<vector < int>>>> array_lv0, array_lv1, array_lv2, array_lv3, array_lv4;
for (float type : sortTypes) {
saver.addData("First " + to_string(type) + " sorted");
array_lv0 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV0, type);
array_lv1 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV1, type);
array_lv2 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV2, type);
array_lv3 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV3, type);
array_lv4 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV4, type);
saver.addData(MergeSort<int>::sortAll(array_lv0));
saver.addData(MergeSort<int>::sortAll(array_lv1));
saver.addData(MergeSort<int>::sortAll(array_lv2));
saver.addData(MergeSort<int>::sortAll(array_lv3));
saver.addData(MergeSort<int>::sortAll(array_lv4));
saver.newLine();
}
// Wszystkie elementy posortowane odwrotnie
saver.addData("All sorted reverse");
array_lv0 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV0, 100, true);
array_lv1 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV1, 100, true);
array_lv2 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV2, 100, true);
array_lv3 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV3, 100, true);
array_lv4 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV4, 100, true);
saver.addData(MergeSort<int>::sortAll(array_lv0));
saver.addData(MergeSort<int>::sortAll(array_lv1));
saver.addData(MergeSort<int>::sortAll(array_lv2));
saver.addData(MergeSort<int>::sortAll(array_lv3));
saver.addData(MergeSort<int>::sortAll(array_lv4));
saver.save();
}
void test_quick_sort() {
CSVSaver saver = CSVSaver("QuickSort_" + to_string(SAVING_VERSION) + ".csv", CSVcolumnList);
shared_ptr<vector < shared_ptr<vector < int>>>> array_lv0, array_lv1, array_lv2, array_lv3, array_lv4;
for (float type : sortTypes) {
saver.addData("First " + to_string(type) + " sorted");
array_lv0 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV0, type);
array_lv1 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV1, type);
array_lv2 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV2, type);
array_lv3 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV3, type);
array_lv4 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV4, type);
saver.addData(QuickSort<int>::sortAll(array_lv0));
saver.addData(QuickSort<int>::sortAll(array_lv1));
saver.addData(QuickSort<int>::sortAll(array_lv2));
saver.addData(QuickSort<int>::sortAll(array_lv3));
saver.addData(QuickSort<int>::sortAll(array_lv4));
saver.newLine();
}
// Wszystkie elementy posortowane odwrotnie
saver.addData("All sorted reverse");
array_lv0 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV0, 100, true);
array_lv1 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV1, 100, true);
array_lv2 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV2, 100, true);
array_lv3 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV3, 100, true);
array_lv4 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV4, 100, true);
saver.addData(QuickSort<int>::sortAll(array_lv0));
saver.addData(QuickSort<int>::sortAll(array_lv1));
saver.addData(QuickSort<int>::sortAll(array_lv2));
saver.addData(QuickSort<int>::sortAll(array_lv3));
saver.addData(QuickSort<int>::sortAll(array_lv4));
saver.save();
}
void test_intro_sort() {
CSVSaver saver = CSVSaver("IntroSort_" + to_string(SAVING_VERSION) + ".csv", CSVcolumnList);
shared_ptr<vector < shared_ptr<vector < int>>>> array_lv0, array_lv1, array_lv2, array_lv3, array_lv4;
for (float type : sortTypes) {
saver.addData("First " + to_string(type) + " sorted");
array_lv0 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV0, type);
array_lv1 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV1, type);
array_lv2 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV2, type);
array_lv3 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV3, type);
array_lv4 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV4, type);
saver.addData(IntroSort<int>::sortAll(array_lv0));
saver.addData(IntroSort<int>::sortAll(array_lv1));
saver.addData(IntroSort<int>::sortAll(array_lv2));
saver.addData(IntroSort<int>::sortAll(array_lv3));
saver.addData(IntroSort<int>::sortAll(array_lv4));
saver.newLine();
}
// Wszystkie elementy posortowane odwrotnie
saver.addData("All sorted reverse");
array_lv0 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV0, 100, true);
array_lv1 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV1, 100, true);
array_lv2 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV2, 100, true);
array_lv3 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV3, 100, true);
array_lv4 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV4, 100, true);
saver.addData(IntroSort<int>::sortAll(array_lv0));
saver.addData(IntroSort<int>::sortAll(array_lv1));
saver.addData(IntroSort<int>::sortAll(array_lv2));
saver.addData(IntroSort<int>::sortAll(array_lv3));
saver.addData(IntroSort<int>::sortAll(array_lv4));
saver.save();
}
int main(int argc, char** argv) {
srand((unsigned) time(NULL)); // inicjowanie generatora liczb losowych
thread merge_thread(test_merge_sort);
thread quick_thread(test_quick_sort);
thread intro_thread(test_intro_sort);
merge_thread.join();
quick_thread.join();
intro_thread.join();
return 0;
}
| [
"rafal.rzewucki@gmail.com"
] | rafal.rzewucki@gmail.com |
af147a75f5134d9b3c19feedb30deafd7efcf4ea | 77ffb0bb747d96a7995c5a750e5ca9d41a64eff8 | /ethzasl_msf/msf_core/include/msf_core/msf_IMUHandler_ROS.h | 3d9b72d3c88f1ec3cca9e761b6a4bb72df76ae3c | [
"Apache-2.0"
] | permissive | Sprann9257/3D-mapping | 43a634c8e49de7a869c0c414aa201b92c61e90c5 | 8d59fe91bb7fd128a7d716da3b7f6984de6697f3 | refs/heads/master | 2021-04-03T07:07:03.217522 | 2017-05-18T13:18:46 | 2017-05-18T13:18:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,245 | h | /*
* Copyright (C) 2012-2013 Simon Lynen, ASL, ETH Zurich, Switzerland
* You can contact the author at <slynen at ethz dot ch>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MSF_IMUHANDLER_ROS_H_
#define MSF_IMUHANDLER_ROS_H_
#include <msf_core/msf_IMUHandler.h>
namespace msf_core {
template<typename EKFState_T>
class IMUHandler_ROS : public IMUHandler<EKFState_T> {
ros::Subscriber subState_; ///< subscriber to external state propagation
ros::Subscriber subImu_; ///< subscriber to IMU readings
ros::Subscriber subImuCustom_; ///< subscriber to IMU readings for asctec custom
public:
IMUHandler_ROS(MSF_SensorManager<EKFState_T>& mng,
const std::string& topic_namespace,
const std::string& parameternamespace)
: IMUHandler<EKFState_T>(mng, topic_namespace, parameternamespace) {
ros::NodeHandle nh(topic_namespace);
subImu_ = nh.subscribe("imu_state_input", 100, &IMUHandler_ROS::IMUCallback,
this);
subState_ = nh.subscribe("hl_state_input", 10,
&IMUHandler_ROS::StateCallback, this);
}
virtual ~IMUHandler_ROS() { }
void StateCallback(const sensor_fusion_comm::ExtEkfConstPtr & msg) {
static_cast<MSF_SensorManagerROS<EKFState_T>&>(this->manager_)
.SetHLControllerStateBuffer(*msg);
// Get the imu values.
msf_core::Vector3 linacc;
linacc << msg->linear_acceleration.x, msg->linear_acceleration.y, msg
->linear_acceleration.z;
msf_core::Vector3 angvel;
angvel << msg->angular_velocity.x, msg->angular_velocity.y, msg
->angular_velocity.z;
int32_t flag = msg->flag;
// Make sure we tell the HL to ignore if data playback is on.
if (this->manager_.GetDataPlaybackStatus())
flag = sensor_fusion_comm::ExtEkf::ignore_state;
bool isnumeric = true;
if (flag == sensor_fusion_comm::ExtEkf::current_state) {
isnumeric = CheckForNumeric(
Eigen::Map<const Eigen::Matrix<float, 10, 1> >(msg->state.data()),
"before prediction p,v,q");
}
// Get the propagated states.
msf_core::Vector3 p, v;
msf_core::Quaternion q;
p = Eigen::Matrix<double, 3, 1>(msg->state[0], msg->state[1],
msg->state[2]);
v = Eigen::Matrix<double, 3, 1>(msg->state[3], msg->state[4],
msg->state[5]);
q = Eigen::Quaternion<double>(msg->state[6], msg->state[7], msg->state[8],
msg->state[9]);
q.normalize();
bool is_already_propagated = false;
if (flag == sensor_fusion_comm::ExtEkf::current_state && isnumeric) {
is_already_propagated = true;
}
this->ProcessState(linacc, angvel, p, v, q, is_already_propagated,
msg->header.stamp.toSec(), msg->header.seq);
}
void IMUCallback(const sensor_msgs::ImuConstPtr & msg) {
static int lastseq = constants::INVALID_SEQUENCE;
if (static_cast<int>(msg->header.seq) != lastseq + 1
&& lastseq != constants::INVALID_SEQUENCE) {
MSF_WARN_STREAM(
"msf_core: imu message drop curr seq:" << msg->header.seq
<< " expected: " << lastseq + 1);
}
lastseq = msg->header.seq;
msf_core::Vector3 linacc;
linacc << msg->linear_acceleration.x, msg->linear_acceleration.y, msg
->linear_acceleration.z;
msf_core::Vector3 angvel;
angvel << msg->angular_velocity.x, msg->angular_velocity.y, msg
->angular_velocity.z;
this->ProcessIMU(linacc, angvel, msg->header.stamp.toSec(),
msg->header.seq);
}
virtual bool Initialize() {
return true;
}
};
}
#endif // MSF_IMUHANDLER_ROS_H_
| [
"chenmengxiao11@nudt.edu.cn"
] | chenmengxiao11@nudt.edu.cn |
1b1a1d6a27f6de29e618a4706f34a72c6a77039f | adf8386eae06b82a85b1c9a4ff0abb2ec1057464 | /MengeConfig/src/main/ContextManager.cpp | e3ab5d98ccd4e1a8ef69e2ac6debf1492d560fed | [] | no_license | curds01/MengeConfig | 5fa847ce632164c96099d1197295d2dcc30c569e | b1e5086e2b05d8e0c1655475bbdbaa13f3efb4c9 | refs/heads/master | 2021-01-18T05:13:30.165985 | 2017-03-08T04:30:10 | 2017-03-08T04:30:10 | 84,278,174 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,457 | cpp | #include "ContextManager.hpp"
#include "QtContext.h"
///////////////////////////////////////////////////////////////////////////////
// Implementation of ContextManager
///////////////////////////////////////////////////////////////////////////////
ContextManager * ContextManager::_instance = 0x0;
size_t ContextManager::_nextId = 1;
///////////////////////////////////////////////////////////////////////////////
ContextManager::ContextManager() : _active(0x0), _idToContext(), _contextToId() {
}
///////////////////////////////////////////////////////////////////////////////
QtContext * ContextManager::getContext(size_t id) {
std::unordered_map<size_t, QtContext *>::const_iterator itr = _idToContext.find(id);
if (itr != _idToContext.end()) {
return itr->second;
}
return 0;
}
///////////////////////////////////////////////////////////////////////////////
ContextManager * ContextManager::instance() {
if (_instance == 0x0) {
_instance = new ContextManager();
}
return _instance;
}
///////////////////////////////////////////////////////////////////////////////
size_t ContextManager::registerContext(QtContext * ctx) {
std::unordered_map<QtContext *, size_t>::const_iterator itr = _contextToId.find(ctx);
size_t id = 0;
if (itr == _contextToId.end()) {
id = _nextId;
++_nextId;
_contextToId[ctx] = id;
_idToContext[id] = ctx;
}
else {
id = itr->second;
}
return id;
}
///////////////////////////////////////////////////////////////////////////////
void ContextManager::unregisterContext(QtContext * ctx) {
std::unordered_map<QtContext *, size_t>::const_iterator itr = _contextToId.find(ctx);
if (itr != _contextToId.end()) {
_idToContext.erase(itr->second);
_contextToId.erase(itr);
}
}
///////////////////////////////////////////////////////////////////////////////
size_t ContextManager::activate(QtContext * ctx) {
if (_active != 0x0) {
size_t id = _contextToId[_active];
_active->deactivate();
emit deactivated(id);
_active = 0x0;
}
size_t id = 0;
if (ctx != 0x0) {
std::unordered_map<QtContext *, size_t>::iterator itr = _contextToId.find(ctx);
if (itr == _contextToId.end()) {
return 0;
}
id = itr->second;
_active = ctx;
_active->activate();
emit activated(id);
}
return id;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
| [
"Sean"
] | Sean |
6e1c98a0e62f74dbd84661f052ae9a31c508fadf | 76420c48c525228d1947f3a22e89a2904262dc79 | /incl/subber.hpp | da74917b6dca876427dd4e0840936ec9d0e640f6 | [] | no_license | longde123/caxe | 559c16f9011693db5a03b4a8c82fa3487644cf53 | 8bf411e936a2ca9c45d72a9b8b2f30971f5d7b2b | refs/heads/master | 2020-07-10T21:19:54.506801 | 2012-11-25T12:30:48 | 2012-11-25T12:30:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 541 | hpp | #ifndef subber_hpp
#define subber_hpp
#include <parser_obj.hpp>
#include <caxe_util.hpp>
#include <deque>
#include <vector>
#include <string>
class Subber : public Thread {
ref<std::deque<ptr<MFile>>::iterator> ite;
ref<tsDeque<ptr<MFile>>> files;
size_t run();
public:
Subber();
void init(std::deque<ptr<MFile>>::iterator&,tsDeque<ptr<MFile>>&);
};
void subs_data(std::vector<ptr<State>>& ret, std::vector<ptr<State>>& in_data, ptr<Macros> macros);
void subs(ptr<Scope> cscope);
#endif
| [
"luca@deltaluca.me.uk"
] | luca@deltaluca.me.uk |
4bd89306ab76ec3f50e4859e2fe2f92c02240073 | b086e2648679bb952cb2dbc0a8255932981adfe4 | /src/YScoket.h | a0f4af2fb597422cfec7df2c9f89b5a0bda7519a | [] | no_license | yuangu/YNet | 845092164f9443bc540bc688ccb227b59305b2a0 | fdf7d7c832b4f1172381938e4de9473903b7ddf5 | refs/heads/master | 2020-04-11T20:21:38.757975 | 2019-04-02T10:41:53 | 2019-04-02T10:41:53 | 162,068,004 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,323 | h | #pragma once
#include "socket_header.h"
#include "poll/IOPoll.h"
#ifndef Y_BUFF_SIZE
#define Y_BUFF_SIZE 1024
#endif
class YAddress;
class YSocket;
class YTLS;
typedef std::function<void(YSocket*)> SocketEventCallBack;
class YSocket
{
public:
YSocket();
YSocket(SOCKET_FD fd);
virtual ~YSocket();
void bind(YAddress* address, bool allow_reuse = true);
virtual void setSSLFlag(bool enable);
virtual bool close();
bool isClosed();
bool isBlocking();
void setBlocking(bool blocking);
unsigned int getTimeout();
void setTimeout(unsigned int timeout);
bool getOption(int level, int optname, void *optval, socklen_t *optlen);
bool setOption(int level, int optname, const void *optval, socklen_t optlen);
int getLastError();
SOCKET_FD fd();
//YAddress* localAddress();
virtual bool isTCP() = 0;
public:
virtual void setIOPoll(IOPoll*);
void onError(SocketEventCallBack);
void onWrite(SocketEventCallBack);
protected:
virtual void onErrorCallBack();
virtual void onWriteCallBack();
virtual void onReadCallBack();
SocketEventCallBack errorCallBack;
SocketEventCallBack writeCallBack;
SocketEventCallBack readCallBack;
IOPoll* mPoll;
protected:
void createSocketIfNecessary(bool isIPV6);
protected:
bool isBlock;
bool mIsClose;
bool mIsEableSSL;
YTLS* mYTLS;
SOCKET_FD mfd;
};
| [
"lifulinghan@aol.com"
] | lifulinghan@aol.com |
2ffc3ac3a984e5f4d4e5ec5b5d7eaf72dcdf577d | f3102a100ad7f5606af620caca37c706ed2d5e55 | /Baekjoon/10952.cpp | c56ccfbb5d3bf55462ed557645c7f42dc933b736 | [] | no_license | ameliacode/Algorithm | c746797b27cf1f783874acc89d024920c0b45897 | d6de240c5c0347cd8f58b59361a8eed5e79733db | refs/heads/master | 2022-02-22T12:36:06.466225 | 2022-02-17T02:55:05 | 2022-02-17T02:55:05 | 210,334,019 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 171 | cpp | #include<iostream>
using namespace std;
int main() {
int a, b;
while(1) {
cin >> a >> b;
if (a == 0 && b == 0) break;
cout << a + b << endl;
}
return 0;
} | [
"emilyjr1@naver.com"
] | emilyjr1@naver.com |
cb63f0c808e5f127d5e0bd339782d6d1f1651ebc | 815486fd4ac8010bebce3d7cce1081d56a54179c | /exp01/task02.cpp | 9a5e690f31c6ef101804f64c86ffe931b0dd9b8c | [] | no_license | Jinyers/homework | ca7d567bc3d4f2125be11eabf7808506960e6085 | 1331a6e145a33501abaa1dc3bda19f9b3dad99d2 | refs/heads/master | 2023-02-05T18:00:30.988969 | 2020-12-21T22:57:11 | 2020-12-21T22:57:11 | 308,596,044 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 644 | cpp | #include <iostream>
using namespace std;
int main()
{
int size = 0;
cout << "Введите размер массива: ";
cin >> size;
int* massive = new int[size];
for (int i=0; i<size; i++)
{
cout << "Введите " << i+1 << "-ный элемент: ";
cin >> massive[i];
}
// Sum
int sum = 0;
for (int i=0; i<size; i++)
{
if (massive[i]%2 == -1) // В проверке massive[i] < 0 нет необходимости
sum += massive[i];
}
// End
cout << "Сумма нечетных отрицательных элементов: " << sum << endl;
delete[] massive;
return 0;
}
| [
"jinyer@Jinyer-Mac.local"
] | jinyer@Jinyer-Mac.local |
a0dd47af1b552d19f3583c8095e67390cde686ca | c824d97cc1208744e4453bac916dcc24dc77a377 | /libcaf_core/src/type_erased_value.cpp | 6392f29a4c3bd63d2d4a6602762335f894baa512 | [
"BSL-1.0"
] | permissive | DePizzottri/actor-framework | 1a033440660c4ea507b743b0d46a46de7fd30df6 | bdbd19541b1e1e6ec0abe16bcf7db90d73c649d2 | refs/heads/master | 2021-01-24T00:23:18.672012 | 2018-04-28T13:04:21 | 2018-04-28T13:04:21 | 59,172,681 | 0 | 0 | null | 2017-03-07T04:22:26 | 2016-05-19T04:04:18 | C++ | UTF-8 | C++ | false | false | 1,799 | cpp | /******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2016 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#include "caf/type_erased_value.hpp"
namespace caf {
type_erased_value::~type_erased_value() {
// nop
}
bool type_erased_value::matches(uint16_t nr, const std::type_info* ptr) const {
auto tp = type();
if (tp.first != nr)
return false;
if (nr == 0)
return ptr != nullptr ? *tp.second == *ptr : false;
return true;
}
} // namespace caf
| [
"dominik.charousset@haw-hamburg.de"
] | dominik.charousset@haw-hamburg.de |
f69a60ba7ee7ce0ed00722e076682df16cecbaf2 | 61fcc3fc81cb5ab59f8e857f0ecab472917f04b1 | /datastructure/cumulativesum/cumulativesum.hpp | 8dce6fe589b1814681ac821f73d7159cc34f176a | [] | no_license | morioprog/cpplib | 4a4e6b9c0eb5dd3d8306041580e4c6c76b65d11e | 71697ee35e8da1c7ae706e323304c170ad1851d6 | refs/heads/master | 2023-01-30T22:31:01.629203 | 2020-12-12T15:14:07 | 2020-12-12T15:14:07 | 257,325,284 | 0 | 0 | null | 2020-10-27T10:20:23 | 2020-04-20T15:33:06 | C++ | UTF-8 | C++ | false | false | 670 | hpp | /**
* @brief 1次元累積和
* @docs docs/datastructure/cumulativesum/cumulativesum.md
*/
template <typename T>
struct CumulativeSum {
int sz;
vector<T> data;
CumulativeSum(const vector<T> &v, const T margin = 0)
: sz(v.size()), data(1, margin) {
for (int i = 0; i < sz; ++i) data.emplace_back(data[i] + v[i]);
}
T query(const int &l, const int &r) const {
if (l >= r) return 0;
return data[min(r, sz)] - data[max(l, 0)];
}
T operator[](const int &k) const {
return query(k, k + 1);
}
void print() {
for (int i = 0; i < sz; ++i) cerr << data[i] << ' ';
cerr << endl;
}
};
| [
"morio.prog@gmail.com"
] | morio.prog@gmail.com |
1829e9a55811d0596400923fd7a80e179c26a823 | d2e0ec84698d691195500365ad6dca0b4737b72d | /skse64/skse64/ScaleformCallbacks.cpp | 579a5f07de57b19c9b28abdb2114a28c56af44ed | [
"MIT"
] | permissive | michaeljdietz/NpcVoiceActivation | 26fc9c170710b8f0a05ed9841369f3a036c0605e | df62efc5e6ed9510e4f9423561071d7119a3a44b | refs/heads/master | 2020-03-14T12:30:39.768955 | 2018-04-30T19:52:09 | 2018-04-30T19:52:09 | 131,613,327 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 776 | cpp | #include "ScaleformCallbacks.h"
#include <typeinfo>
UInt32 g_GFxFunctionHandler_count = 0;
GFxFunctionHandler::GFxFunctionHandler()
{
g_GFxFunctionHandler_count++;
}
GFxFunctionHandler::~GFxFunctionHandler()
{
g_GFxFunctionHandler_count--;
}
FunctionHandlerCache g_functionHandlerCache;
RelocAddr<FxDelegateHandler::Callback> PlaySoundCallback(0x00906320);
FxResponseArgsList::FxResponseArgsList()
{
args.values = nullptr;
args.size = 0;
args.capacity = 0;
}
FxResponseArgsList::~FxResponseArgsList()
{
Clear();
}
void FxResponseArgsList::Clear()
{
if (args.values) {
for (UInt32 i = 0; i < args.size; i++)
args.values[i].CleanManaged();
ScaleformHeap_Free(args.values);
args.values = NULL;
args.size = 0;
}
}
| [
"michael.dietz@shelterlogic.com"
] | michael.dietz@shelterlogic.com |
0d2de1cd68d86ba5beae70eb86b90f6ce81f3175 | 33eaafc0b1b10e1ae97a67981fe740234bc5d592 | /tests/RandomSAT/z3-master/src/math/euclid/euclidean_solver.cpp | af11d43044ded464574903c7fa76fb8d10d7c9b5 | [
"MIT"
] | permissive | akinanop/mvl-solver | 6c21bec03422bb2366f146cb02e6bf916eea6dd0 | bfcc5b243e43bddcc34aba9c34e67d820fc708c8 | refs/heads/master | 2021-01-16T23:30:46.413902 | 2021-01-10T16:53:23 | 2021-01-10T16:53:23 | 48,694,935 | 6 | 2 | null | 2016-08-30T10:47:25 | 2015-12-28T13:55:32 | C++ | UTF-8 | C++ | false | false | 29,230 | cpp | /*++
Copyright (c) 2011 Microsoft Corporation
Module Name:
euclidean_solver.cpp
Abstract:
Euclidean Solver with support for explanations.
Author:
Leonardo de Moura (leonardo) 2011-07-08.
Revision History:
--*/
#include"euclidean_solver.h"
#include"numeral_buffer.h"
#include"heap.h"
struct euclidean_solver::imp {
typedef unsigned var;
typedef unsigned justification;
typedef unsynch_mpq_manager numeral_manager;
typedef numeral_buffer<mpz, numeral_manager> mpz_buffer;
typedef numeral_buffer<mpq, numeral_manager> mpq_buffer;
typedef svector<justification> justification_vector;
static const justification null_justification = UINT_MAX;
#define null_var UINT_MAX
#define null_eq_idx UINT_MAX
typedef svector<var> var_vector;
typedef svector<mpz> mpz_vector;
typedef svector<mpq> mpq_vector;
struct elim_order_lt {
unsigned_vector & m_solved;
elim_order_lt(unsigned_vector & s):m_solved(s) {}
bool operator()(var x1, var x2) const { return m_solved[x1] < m_solved[x2]; }
};
typedef heap<elim_order_lt> var_queue; // queue used for scheduling variables for applying substitution.
static unsigned pos(unsigned_vector const & xs, unsigned x_i) {
if (xs.empty())
return UINT_MAX;
int low = 0;
int high = xs.size() - 1;
while (true) {
int mid = low + ((high - low) / 2);
var x_mid = xs[mid];
if (x_i > x_mid) {
low = mid + 1;
if (low > high)
return UINT_MAX;
}
else if (x_i < x_mid) {
high = mid - 1;
if (low > high)
return UINT_MAX;
}
else {
return mid;
}
}
}
/**
Equation as[0]*xs[0] + ... + as[n-1]*xs[n-1] + c = 0 with justification bs[0]*js[0] + ... + bs[m-1]*js[m-1]
*/
struct equation {
mpz_vector m_as;
var_vector m_xs;
mpz m_c;
// justification
mpq_vector m_bs;
justification_vector m_js;
unsigned size() const { return m_xs.size(); }
unsigned js_size() const { return m_js.size(); }
var x(unsigned i) const { return m_xs[i]; }
var & x(unsigned i) { return m_xs[i]; }
mpz const & a(unsigned i) const { return m_as[i]; }
mpz & a(unsigned i) { return m_as[i]; }
mpz const & c() const { return m_c; }
mpz & c() { return m_c; }
var j(unsigned i) const { return m_js[i]; }
var & j(unsigned i) { return m_js[i]; }
mpq const & b(unsigned i) const { return m_bs[i]; }
mpq & b(unsigned i) { return m_bs[i]; }
unsigned pos_x(unsigned x_i) const { return pos(m_xs, x_i); }
};
typedef ptr_vector<equation> equations;
typedef svector<unsigned> occs;
numeral_manager * m_manager;
bool m_owns_m;
equations m_equations;
equations m_solution;
svector<bool> m_parameter;
unsigned_vector m_solved; // null_eq_idx if var is not solved, otherwise the position in m_solution
vector<occs> m_occs; // occurrences of the variable in m_equations.
unsigned m_inconsistent; // null_eq_idx if not inconsistent, otherwise it is the index of an unsatisfiable equality in m_equations.
unsigned m_next_justification;
mpz_buffer m_decompose_buffer;
mpz_buffer m_as_buffer;
mpq_buffer m_bs_buffer;
var_vector m_tmp_xs;
mpz_buffer m_tmp_as;
mpq_buffer m_tmp_bs;
var_vector m_norm_xs_vector;
mpz_vector m_norm_as_vector;
mpq_vector m_norm_bs_vector;
var_queue m_var_queue;
// next candidate
unsigned m_next_eq;
var m_next_x;
mpz m_next_a;
bool m_next_pos_a;
numeral_manager & m() const { return *m_manager; }
bool solved(var x) const { return m_solved[x] != null_eq_idx; }
template<typename Numeral>
void sort_core(svector<Numeral> & as, unsigned_vector & xs, numeral_buffer<Numeral, numeral_manager> & buffer) {
std::sort(xs.begin(), xs.end());
unsigned num = as.size();
for (unsigned i = 0; i < num; i++) {
m().swap(as[i], buffer[xs[i]]);
}
}
template<typename Numeral>
void sort(svector<Numeral> & as, unsigned_vector & xs, numeral_buffer<Numeral, numeral_manager> & buffer) {
unsigned num = as.size();
for (unsigned i = 0; i < num; i++) {
m().set(buffer[xs[i]], as[i]);
}
sort_core(as, xs, buffer);
}
equation * mk_eq(unsigned num, mpz const * as, var const * xs, mpz const & c, unsigned num_js, mpq const * bs, justification const * js,
bool sort = true) {
equation * new_eq = alloc(equation);
for (unsigned i = 0; i < num; i++) {
m().set(m_as_buffer[xs[i]], as[i]);
new_eq->m_as.push_back(mpz());
new_eq->m_xs.push_back(xs[i]);
}
sort_core(new_eq->m_as, new_eq->m_xs, m_as_buffer);
m().set(new_eq->m_c, c);
for (unsigned i = 0; i < num_js; i++) {
m().set(m_bs_buffer[js[i]], bs[i]);
new_eq->m_bs.push_back(mpq());
new_eq->m_js.push_back(js[i]);
}
if (sort)
sort_core(new_eq->m_bs, new_eq->m_js, m_bs_buffer);
return new_eq;
}
template<typename Numeral>
void div(svector<Numeral> & as, mpz const & g) {
unsigned n = as.size();
for (unsigned i = 0; i < n; i++)
m().div(as[i], g, as[i]);
}
void normalize_eq(unsigned eq_idx) {
if (inconsistent())
return;
equation & eq = *(m_equations[eq_idx]);
TRACE("euclidean_solver", tout << "normalizing:\n"; display(tout, eq); tout << "\n";);
unsigned num = eq.size();
if (num == 0) {
// c == 0 inconsistency
if (!m().is_zero(eq.c())) {
TRACE("euclidean_solver", tout << "c = 0 inconsistency detected\n";);
m_inconsistent = eq_idx;
}
else {
del_eq(&eq);
m_equations[eq_idx] = 0;
}
return;
}
mpz g;
mpz a;
m().set(g, eq.a(0));
m().abs(g);
for (unsigned i = 1; i < num; i++) {
if (m().is_one(g))
break;
m().set(a, eq.a(i));
m().abs(a);
m().gcd(g, a, g);
}
if (m().is_one(g))
return;
if (!m().divides(g, eq.c())) {
// g does not divide c
TRACE("euclidean_solver", tout << "gcd inconsistency detected\n";);
m_inconsistent = eq_idx;
return;
}
div(eq.m_as, g);
div(eq.m_bs, g);
m().del(g);
m().del(a);
TRACE("euclidean_solver", tout << "after normalization:\n"; display(tout, eq); tout << "\n";);
}
bool is_better(mpz const & a, var x, unsigned eq_sz) {
SASSERT(m().is_pos(a));
if (m_next_x == null_var)
return true;
if (m().lt(a, m_next_a))
return true;
if (m().lt(m_next_a, a))
return false;
if (m_occs[x].size() < m_occs[m_next_x].size())
return true;
if (m_occs[x].size() > m_occs[m_next_x].size())
return false;
return eq_sz < m_equations[m_next_eq]->size();
}
void updt_next_candidate(unsigned eq_idx) {
if (!m_equations[eq_idx])
return;
mpz abs_a;
equation const & eq = *(m_equations[eq_idx]);
unsigned num = eq.size();
for (unsigned i = 0; i < num; i++) {
mpz const & a = eq.a(i);
m().set(abs_a, a);
m().abs(abs_a);
if (is_better(abs_a, eq.x(i), num)) {
m().set(m_next_a, abs_a);
m_next_x = eq.x(i);
m_next_eq = eq_idx;
m_next_pos_a = m().is_pos(a);
}
}
m().del(abs_a);
}
/**
\brief Select next variable to be eliminated.
Return false if there is not variable to eliminate.
The result is in
m_next_x variable to be eliminated
m_next_eq id of the equation containing x
m_next_a absolute value of the coefficient of x in eq.
m_next_pos_a true if the coefficient of x is positive in eq.
*/
bool select_next_var() {
while (!m_equations.empty() && m_equations.back() == 0)
m_equations.pop_back();
if (m_equations.empty())
return false;
SASSERT(!m_equations.empty() && m_equations.back() != 0);
m_next_x = null_var;
unsigned eq_idx = m_equations.size();
while (eq_idx > 0) {
--eq_idx;
updt_next_candidate(eq_idx);
// stop as soon as possible
// TODO: use heuristics
if (m_next_x != null_var && m().is_one(m_next_a))
return true;
}
CTRACE("euclidean_solver_bug", m_next_x == null_var, display(tout););
SASSERT(m_next_x != null_var);
return true;
}
template<typename Numeral>
void del_nums(svector<Numeral> & as) {
unsigned sz = as.size();
for (unsigned i = 0; i < sz; i++)
m().del(as[i]);
as.reset();
}
void del_eq(equation * eq) {
m().del(eq->c());
del_nums(eq->m_as);
del_nums(eq->m_bs);
dealloc(eq);
}
void del_equations(equations & eqs) {
unsigned sz = eqs.size();
for (unsigned i = 0; i < sz; i++) {
if (eqs[i])
del_eq(eqs[i]);
}
}
/**
\brief Store the "solved" variables in xs into m_var_queue.
*/
void schedule_var_subst(unsigned num, var const * xs) {
for (unsigned i = 0; i < num; i++) {
if (solved(xs[i]))
m_var_queue.insert(xs[i]);
}
}
void schedule_var_subst(var_vector const & xs) {
schedule_var_subst(xs.size(), xs.c_ptr());
}
/**
\brief Store as1*xs1 + k*as2*xs2 into new_as*new_xs
If UpdateOcc == true,
Then,
1) for each variable x occurring in xs2 but not in xs1:
- eq_idx is added to m_occs[x]
2) for each variable that occurs in xs1 and xs2 and the resultant coefficient is zero,
- eq_idx is removed from m_occs[x] IF x != except_var
If UpdateQueue == true
Then,
1) for each variable x occurring in xs2 but not in xs1:
- if x is solved, then x is inserted into m_var_queue
2) for each variable that occurs in xs1 and xs2 and the resultant coefficient is zero,
- if x is solved, then x is removed from m_var_queue
*/
template<typename Numeral, bool UpdateOcc, bool UpdateQueue>
void addmul(svector<Numeral> const & as1, var_vector const & xs1,
mpz const & k, svector<Numeral> const & as2, var_vector const & xs2,
numeral_buffer<Numeral, numeral_manager> & new_as, var_vector & new_xs,
unsigned eq_idx = null_eq_idx, var except_var = null_var) {
Numeral new_a;
SASSERT(as1.size() == xs1.size());
SASSERT(as2.size() == xs2.size());
new_as.reset();
new_xs.reset();
unsigned sz1 = xs1.size();
unsigned sz2 = xs2.size();
unsigned i1 = 0;
unsigned i2 = 0;
while (true) {
if (i1 == sz1) {
// copy remaining entries from as2*xs2
while (i2 < sz2) {
var x2 = xs2[i2];
if (UpdateOcc)
m_occs[x2].push_back(eq_idx);
if (UpdateQueue && solved(x2))
m_var_queue.insert(x2);
new_as.push_back(Numeral());
m().mul(k, as2[i2], new_as.back());
new_xs.push_back(x2);
i2++;
}
break;
}
if (i2 == sz2) {
// copy remaining entries from as1*xs1
while (i1 < sz1) {
new_as.push_back(as1[i1]);
new_xs.push_back(xs1[i1]);
i1++;
}
break;
}
var x1 = xs1[i1];
var x2 = xs2[i2];
if (x1 < x2) {
new_as.push_back(as1[i1]);
new_xs.push_back(xs1[i1]);
i1++;
}
else if (x1 > x2) {
if (UpdateOcc)
m_occs[x2].push_back(eq_idx);
if (UpdateQueue && solved(x2))
m_var_queue.insert(x2);
new_as.push_back(Numeral());
m().mul(k, as2[i2], new_as.back());
new_xs.push_back(x2);
i2++;
}
else {
m().addmul(as1[i1], k, as2[i2], new_a);
TRACE("euclidean_solver_add_mul", tout << "i1: " << i1 << ", i2: " << i2 << " new_a: " << m().to_string(new_a) << "\n";
tout << "as1: " << m().to_string(as1[i1]) << ", k: " << m().to_string(k) << ", as2: " << m().to_string(as2[i2]) << "\n";);
if (m().is_zero(new_a)) {
// variable was canceled
if (UpdateOcc && x1 != except_var)
m_occs[x1].erase(eq_idx);
if (UpdateQueue && solved(x1) && m_var_queue.contains(x1))
m_var_queue.erase(x1);
}
else {
new_as.push_back(new_a);
new_xs.push_back(x1);
}
i1++;
i2++;
}
}
m().del(new_a);
}
template<bool UpdateOcc, bool UpdateQueue>
void apply_solution(var x, mpz_vector & as, var_vector & xs, mpz & c, mpq_vector & bs, justification_vector & js,
unsigned eq_idx = null_eq_idx, var except_var = null_var) {
SASSERT(solved(x));
unsigned idx = pos(xs, x);
if (idx == UINT_MAX)
return;
mpz const & a1 = as[idx];
SASSERT(!m().is_zero(a1));
equation const & eq2 = *(m_solution[m_solved[x]]);
SASSERT(eq2.pos_x(x) != UINT_MAX);
SASSERT(m().is_minus_one(eq2.a(eq2.pos_x(x))));
TRACE("euclidean_solver_apply",
tout << "applying: " << m().to_string(a1) << " * "; display(tout, eq2); tout << "\n";
for (unsigned i = 0; i < xs.size(); i++) tout << m().to_string(as[i]) << "*x" << xs[i] << " "; tout << "\n";);
addmul<mpz, UpdateOcc, UpdateQueue>(as, xs, a1, eq2.m_as, eq2.m_xs, m_tmp_as, m_tmp_xs, eq_idx, except_var);
m().addmul(c, a1, eq2.m_c, c);
m_tmp_as.swap(as);
m_tmp_xs.swap(xs);
SASSERT(as.size() == xs.size());
TRACE("euclidean_solver_apply", for (unsigned i = 0; i < xs.size(); i++) tout << m().to_string(as[i]) << "*x" << xs[i] << " "; tout << "\n";);
addmul<mpq, false, false>(bs, js, a1, eq2.m_bs, eq2.m_js, m_tmp_bs, m_tmp_xs);
m_tmp_bs.swap(bs);
m_tmp_xs.swap(js);
SASSERT(pos(xs, x) == UINT_MAX);
}
void apply_solution(mpz_vector & as, var_vector & xs, mpz & c, mpq_vector & bs, justification_vector & js) {
m_var_queue.reset();
schedule_var_subst(xs);
while (!m_var_queue.empty()) {
var x = m_var_queue.erase_min();
apply_solution<false, true>(x, as, xs, c, bs, js);
}
}
void apply_solution(equation & eq) {
apply_solution(eq.m_as, eq.m_xs, eq.m_c, eq.m_bs, eq.m_js);
}
void display(std::ostream & out, equation const & eq) const {
unsigned num = eq.js_size();
for (unsigned i = 0; i < num; i ++) {
if (i > 0) out << " ";
out << m().to_string(eq.b(i)) << "*j" << eq.j(i);
}
if (num > 0) out << " ";
out << "|= ";
num = eq.size();
for (unsigned i = 0; i < num; i++) {
out << m().to_string(eq.a(i)) << "*x" << eq.x(i) << " + ";
}
out << m().to_string(eq.c()) << " = 0";
}
void display(std::ostream & out, equations const & eqs) const {
unsigned num = eqs.size();
for (unsigned i = 0; i < num; i++) {
if (eqs[i]) {
display(out, *(eqs[i]));
out << "\n";
}
}
}
void display(std::ostream & out) const {
if (inconsistent()) {
out << "inconsistent: ";
display(out, *(m_equations[m_inconsistent]));
out << "\n";
}
out << "solution set:\n";
display(out, m_solution);
out << "todo:\n";
display(out, m_equations);
}
void add_occs(unsigned eq_idx) {
equation const & eq = *(m_equations[eq_idx]);
unsigned sz = eq.size();
for (unsigned i = 0; i < sz; i++)
m_occs[eq.x(i)].push_back(eq_idx);
}
imp(numeral_manager * m):
m_manager(m == 0 ? alloc(numeral_manager) : m),
m_owns_m(m == 0),
m_decompose_buffer(*m_manager),
m_as_buffer(*m_manager),
m_bs_buffer(*m_manager),
m_tmp_as(*m_manager),
m_tmp_bs(*m_manager),
m_var_queue(16, elim_order_lt(m_solved)) {
m_inconsistent = null_eq_idx;
m_next_justification = 0;
m_next_x = null_var;
m_next_eq = null_eq_idx;
}
~imp() {
m().del(m_next_a);
del_equations(m_equations);
del_equations(m_solution);
if (m_owns_m)
dealloc(m_manager);
}
var mk_var(bool parameter) {
var x = m_solved.size();
m_parameter.push_back(parameter);
m_solved.push_back(null_eq_idx);
m_occs.push_back(occs());
m_as_buffer.push_back(mpz());
m_var_queue.reserve(x+1);
return x;
}
justification mk_justification() {
justification r = m_next_justification;
m_bs_buffer.push_back(mpq());
m_next_justification++;
return r;
}
void assert_eq(unsigned num, mpz const * as, var const * xs, mpz const & c, justification j) {
if (inconsistent())
return;
equation * eq;
if (j == null_justification) {
eq = mk_eq(num, as, xs, c, 0, 0, 0);
}
else {
mpq one(1);
eq = mk_eq(num, as, xs, c, 1, &one, &j);
}
TRACE("euclidean_solver", tout << "new-eq:\n"; display(tout, *eq); tout << "\n";);
unsigned eq_idx = m_equations.size();
m_equations.push_back(eq);
apply_solution(*eq);
normalize_eq(eq_idx);
add_occs(eq_idx);
TRACE("euclidean_solver", tout << "asserted:\n"; display(tout, *eq); tout << "\n";);
}
justification_vector const & get_justification() const {
SASSERT(inconsistent());
return m_equations[m_inconsistent]->m_js;
}
template<typename Numeral>
void neg_coeffs(svector<Numeral> & as) {
unsigned sz = as.size();
for (unsigned i = 0; i < sz; i++) {
m().neg(as[i]);
}
}
void substitute_most_recent_solution(var x) {
SASSERT(!m_solution.empty());
equation & eq = *(m_solution.back());
TRACE("euclidean_solver", tout << "applying solution for x" << x << "\n"; display(tout, eq); tout << "\n";);
occs & use_list = m_occs[x];
occs::iterator it = use_list.begin();
occs::iterator end = use_list.end();
for (; it != end; ++it) {
unsigned eq_idx = *it;
// remark we don't want to update the use_list of x while we are traversing it.
equation & eq2 = *(m_equations[eq_idx]);
TRACE("euclidean_solver", tout << "eq before substituting x" << x << "\n"; display(tout, eq2); tout << "\n";);
apply_solution<true, false>(x, eq2.m_as, eq2.m_xs, eq2.m_c, eq2.m_bs, eq2.m_js, eq_idx, x);
TRACE("euclidean_solver", tout << "eq after substituting x" << x << "\n"; display(tout, eq2); tout << "\n";);
normalize_eq(eq_idx);
if (inconsistent())
break;
}
use_list.reset();
}
void elim_unit() {
SASSERT(m().is_one(m_next_a));
equation & eq = *(m_equations[m_next_eq]);
TRACE("euclidean_solver", tout << "eliminating equation with unit coefficient:\n"; display(tout, eq); tout << "\n";);
if (m_next_pos_a) {
// neg coeffs... to make sure that m_next_x is -1
neg_coeffs(eq.m_as);
neg_coeffs(eq.m_bs);
m().neg(eq.m_c);
}
unsigned sz = eq.size();
for (unsigned i = 0; i < sz; i++) {
m_occs[eq.x(i)].erase(m_next_eq);
}
m_solved[m_next_x] = m_solution.size();
m_solution.push_back(&eq);
m_equations[m_next_eq] = 0;
substitute_most_recent_solution(m_next_x);
}
void decompose(bool pos_a, mpz const & abs_a, mpz const & a_i, mpz & new_a_i, mpz & r_i) {
mpz abs_a_i;
bool pos_a_i = m().is_pos(a_i);
m().set(abs_a_i, a_i);
if (!pos_a_i)
m().neg(abs_a_i);
bool new_pos_a_i = pos_a_i;
if (pos_a)
new_pos_a_i = !new_pos_a_i;
m().div(abs_a_i, abs_a, new_a_i);
if (m().divides(abs_a, a_i)) {
m().reset(r_i);
}
else {
if (pos_a_i)
m().submul(a_i, abs_a, new_a_i, r_i);
else
m().addmul(a_i, abs_a, new_a_i, r_i);
}
if (!new_pos_a_i)
m().neg(new_a_i);
m().del(abs_a_i);
}
void decompose_and_elim() {
m_tmp_xs.reset();
mpz_buffer & buffer = m_decompose_buffer;
buffer.reset();
var p = mk_var(true);
mpz new_a_i;
equation & eq = *(m_equations[m_next_eq]);
TRACE("euclidean_solver", tout << "decompositing equation for x" << m_next_x << "\n"; display(tout, eq); tout << "\n";);
unsigned sz = eq.size();
unsigned j = 0;
for (unsigned i = 0; i < sz; i++) {
var x_i = eq.x(i);
if (x_i == m_next_x) {
m().set(new_a_i, -1);
buffer.push_back(new_a_i);
m_tmp_xs.push_back(m_next_x);
m_occs[x_i].erase(m_next_eq);
}
else {
decompose(m_next_pos_a, m_next_a, eq.a(i), new_a_i, eq.m_as[j]);
buffer.push_back(new_a_i);
m_tmp_xs.push_back(x_i);
if (m().is_zero(eq.m_as[j])) {
m_occs[x_i].erase(m_next_eq);
}
else {
eq.m_xs[j] = x_i;
j++;
}
}
}
SASSERT(j < sz);
// add parameter: p to new equality, and m_next_pos_a * m_next_a * p to current eq
m().set(new_a_i, 1);
buffer.push_back(new_a_i);
m_tmp_xs.push_back(p);
m().set(eq.m_as[j], m_next_a);
if (!m_next_pos_a)
m().neg(eq.m_as[j]);
eq.m_xs[j] = p;
j++;
unsigned new_sz = j;
// shrink current eq
for (; j < sz; j++)
m().del(eq.m_as[j]);
eq.m_as.shrink(new_sz);
eq.m_xs.shrink(new_sz);
// ajust c
mpz new_c;
decompose(m_next_pos_a, m_next_a, eq.m_c, new_c, eq.m_c);
// create auxiliary equation
equation * new_eq = mk_eq(m_tmp_xs.size(), buffer.c_ptr(), m_tmp_xs.c_ptr(), new_c, 0, 0, 0, false);
// new_eq doesn't need to normalized, since it has unit coefficients
TRACE("euclidean_solver", tout << "decomposition: new parameter x" << p << " aux eq:\n";
display(tout, *new_eq); tout << "\n";
display(tout, eq); tout << "\n";);
m_solved[m_next_x] = m_solution.size();
m_solution.push_back(new_eq);
substitute_most_recent_solution(m_next_x);
m().del(new_a_i);
m().del(new_c);
}
bool solve() {
if (inconsistent()) return false;
TRACE("euclidean_solver", tout << "solving...\n"; display(tout););
while (select_next_var()) {
CTRACE("euclidean_solver_bug", m_next_x == null_var, display(tout););
TRACE("euclidean_solver", tout << "eliminating x" << m_next_x << "\n";);
if (m().is_one(m_next_a) || m().is_minus_one(m_next_a))
elim_unit();
else
decompose_and_elim();
TRACE("euclidean_solver", display(tout););
if (inconsistent()) return false;
}
return true;
}
bool inconsistent() const {
return m_inconsistent != null_eq_idx;
}
bool is_parameter(var x) const {
return m_parameter[x];
}
void normalize(unsigned num, mpz const * as, var const * xs, mpz const & c, mpz & a_prime, mpz & c_prime, justification_vector & js) {
TRACE("euclidean_solver", tout << "before applying solution set\n";
for (unsigned i = 0; i < num; i++) {
tout << m().to_string(as[i]) << "*x" << xs[i] << " ";
}
tout << "\n";);
m_norm_xs_vector.reset();
m_norm_as_vector.reset();
for (unsigned i = 0; i < num; i++) {
m_norm_xs_vector.push_back(xs[i]);
m_norm_as_vector.push_back(mpz());
m().set(m_norm_as_vector.back(), as[i]);
}
sort(m_norm_as_vector, m_norm_xs_vector, m_as_buffer);
m_norm_bs_vector.reset();
js.reset();
m().set(c_prime, c);
apply_solution(m_norm_as_vector, m_norm_xs_vector, c_prime, m_norm_bs_vector, js);
TRACE("euclidean_solver", tout << "after applying solution set\n";
for (unsigned i = 0; i < m_norm_as_vector.size(); i++) {
tout << m().to_string(m_norm_as_vector[i]) << "*x" << m_norm_xs_vector[i] << " ";
}
tout << "\n";);
// compute gcd of the result m_norm_as_vector
if (m_norm_as_vector.empty()) {
m().set(a_prime, 0);
}
else {
mpz a;
m().set(a_prime, m_norm_as_vector[0]);
m().abs(a_prime);
unsigned sz = m_norm_as_vector.size();
for (unsigned i = 1; i < sz; i++) {
if (m().is_one(a_prime))
break;
m().set(a, m_norm_as_vector[i]);
m().abs(a);
m().gcd(a_prime, a, a_prime);
}
m().del(a);
}
// REMARK: m_norm_bs_vector contains the linear combination of the justifications. It may be useful if we
// decided (one day) to generate detailed proofs for this step.
del_nums(m_norm_as_vector);
del_nums(m_norm_bs_vector);
}
};
euclidean_solver::euclidean_solver(numeral_manager * m):
m_imp(alloc(imp, m)) {
}
euclidean_solver::~euclidean_solver() {
dealloc(m_imp);
}
euclidean_solver::numeral_manager & euclidean_solver::m() const {
return m_imp->m();
}
void euclidean_solver::reset() {
numeral_manager * m = m_imp->m_manager;
bool owns_m = m_imp->m_owns_m;
m_imp->m_owns_m = false;
dealloc(m_imp);
m_imp = alloc(imp, m);
m_imp->m_owns_m = owns_m;
}
euclidean_solver::var euclidean_solver::mk_var() {
return m_imp->mk_var(false);
}
euclidean_solver::justification euclidean_solver::mk_justification() {
return m_imp->mk_justification();
}
void euclidean_solver::assert_eq(unsigned num, mpz const * as, var const * xs, mpz const & c, justification j) {
m_imp->assert_eq(num, as, xs, c, j);
}
bool euclidean_solver::solve() {
return m_imp->solve();
}
euclidean_solver::justification_vector const & euclidean_solver::get_justification() const {
return m_imp->get_justification();
}
bool euclidean_solver::inconsistent() const {
return m_imp->inconsistent();
}
bool euclidean_solver::is_parameter(var x) const {
return m_imp->is_parameter(x);
}
void euclidean_solver::normalize(unsigned num, mpz const * as, var const * xs, mpz const & c, mpz & a_prime, mpz & c_prime,
justification_vector & js) {
return m_imp->normalize(num, as, xs, c, a_prime, c_prime, js);
}
void euclidean_solver::display(std::ostream & out) const {
m_imp->display(out);
}
| [
"nikaponens@gmail.com"
] | nikaponens@gmail.com |
0f6ade00767bd619b2ea46bda9b7b705151d31b6 | ffcdb598bebc8a8c9d190b98cc88953c748dc88a | /05.cc | 30e7a6b36bf469fd71d74d5ed7e5a9df19094ce2 | [] | no_license | aztecrex/try-sdl | e2cfa961bc187ccd78473625f47b12f999b2c641 | 1468979d55c44fc21189c34006cdc32bbf9ba6aa | refs/heads/master | 2021-01-20T00:21:36.370424 | 2017-04-29T21:44:33 | 2017-04-29T21:44:33 | 89,119,244 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,455 | cc | /*This source code copyrighted by Lazy Foo' Productions (2004-2015)
and may not be redistributed without written permission.*/
//Using SDL, standard IO, and strings
#include <SDL.h>
#include <stdio.h>
#include <string>
//Screen dimension constants
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
//Starts up SDL and creates window
bool init();
//Loads media
bool loadMedia();
//Frees media and shuts down SDL
void close();
//Loads individual image
SDL_Surface* loadSurface( std::string path );
//The window we'll be rendering to
SDL_Window* gWindow = NULL;
//The surface contained by the window
SDL_Surface* gScreenSurface = NULL;
//Current displayed image
SDL_Surface* gStretchedSurface = NULL;
bool init()
{
//Initialization flag
bool success = true;
//Initialize SDL
if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
{
printf( "SDL could not initialize! SDL Error: %s\n", SDL_GetError() );
success = false;
}
else
{
//Create window
gWindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
if( gWindow == NULL )
{
printf( "Window could not be created! SDL Error: %s\n", SDL_GetError() );
success = false;
}
else
{
//Get window surface
gScreenSurface = SDL_GetWindowSurface( gWindow );
}
}
return success;
}
bool loadMedia()
{
//Loading success flag
bool success = true;
//Load stretching surface
gStretchedSurface = loadSurface( "05_stretch.bmp" );
if( gStretchedSurface == NULL )
{
printf( "Failed to load stretching image!\n" );
success = false;
}
return success;
}
void close()
{
//Free loaded image
SDL_FreeSurface( gStretchedSurface );
gStretchedSurface = NULL;
//Destroy window
SDL_DestroyWindow( gWindow );
gWindow = NULL;
//Quit SDL subsystems
SDL_Quit();
}
SDL_Surface* loadSurface( std::string path )
{
//The final optimized image
SDL_Surface* optimizedSurface = NULL;
//Load image at specified path
SDL_Surface* loadedSurface = SDL_LoadBMP( path.c_str() );
if( loadedSurface == NULL )
{
printf( "Unable to load image %s! SDL Error: %s\n", path.c_str(), SDL_GetError() );
}
else
{
//Convert surface to screen format
optimizedSurface = SDL_ConvertSurface( loadedSurface, gScreenSurface->format, 0 );
if( optimizedSurface == NULL )
{
printf( "Unable to optimize image %s! SDL Error: %s\n", path.c_str(), SDL_GetError() );
}
//Get rid of old loaded surface
SDL_FreeSurface( loadedSurface );
}
return optimizedSurface;
}
int main( int argc, char* args[] )
{
//Start up SDL and create window
if( !init() )
{
printf( "Failed to initialize!\n" );
}
else
{
//Load media
if( !loadMedia() )
{
printf( "Failed to load media!\n" );
}
else
{
//Main loop flag
bool quit = false;
//Event handler
SDL_Event e;
//While application is running
while( !quit )
{
//Handle events on queue
while( SDL_PollEvent( &e ) != 0 )
{
//User requests quit
if( e.type == SDL_QUIT )
{
quit = true;
}
}
//Apply the image stretched
SDL_Rect stretchRect;
stretchRect.x = 0;
stretchRect.y = 0;
stretchRect.w = SCREEN_WIDTH;
stretchRect.h = SCREEN_HEIGHT;
SDL_BlitScaled( gStretchedSurface, NULL, gScreenSurface, &stretchRect );
//Update the surface
SDL_UpdateWindowSurface( gWindow );
}
}
}
//Free resources and close SDL
close();
return 0;
}
| [
"aztec.rex@jammm.com"
] | aztec.rex@jammm.com |
8f76b106331437044891d34a5ff1c9d03cc99d29 | 595f3608b6563f5cf162159704d7175326bb576f | /Src/AmrTask/rts_impls/mpi/PackageQueue.H | 9d6eb4f092a129436dc26d026ff9ebf5dcb794d5 | [
"BSD-2-Clause"
] | permissive | ChrisDeGrendele/amrex | b89ca9f5a3b475ee730ed5371f318eae2841e8b5 | 586ea4491d9920d4bb0b925cf3809cb1de1df493 | refs/heads/master | 2020-06-02T18:17:16.998018 | 2019-05-31T20:50:55 | 2019-05-31T20:50:55 | 191,254,393 | 0 | 0 | NOASSERTION | 2019-06-10T22:29:00 | 2019-06-10T22:28:59 | null | UTF-8 | C++ | false | false | 1,409 | h | #ifndef P_PACKAGEQUEUE_H
#define P_PACKAGEQUEUE_H
#include <PerillaConfig.H>
#include <pthread.h>
#include <mpi.h>
class Package
{
private:
int source, destination;
public:
double *databuf;
int bufSize;
pthread_mutex_t packageLock;
volatile bool completed; //message transfer is done
volatile bool served; //message transfer request has been served but may have not completed
volatile bool notified;
MPI_Request request; //!for MPI
Package();
~Package();
Package(int size);
Package(int src, int dest);
Package(int src, int dest, int size);
void setPackageSource(int src);
void setPackageDestination(int dest);
void completeRequest(void);
void completeRequest(bool lockIgnore);
bool checkRequest(void);
void generatePackage(int size);
};
class PackageQueue
{
private:
Package *buffer[perilla::MSG_QUEUE_DEFAULT_MAXSIZE];
volatile int n;
volatile int front;
volatile int rear;
volatile int prear;
int max_size;
public:
pthread_mutex_t queueLock;
PackageQueue();
~PackageQueue();
int queueSize(void);
int queueSize(bool lockIgnore);
void enqueue(Package* package);
void enqueue(Package* package, bool lockIgnore);
Package* dequeue(void);
Package* dequeue(bool lockIgnore);
Package* getRear(void);
Package* getRear(bool lockIgnore);
Package* getFront(void);
Package* getFront(bool lockIgnore);
void emptyQueue();
};
#endif
| [
"tannguyen@lbl.gov"
] | tannguyen@lbl.gov |
a90bbf71662b50c08b720b550e0f7b663fea5fba | aea5a52d44cd8907efc483fcbb0c6092ba571735 | /gamewidget.cpp | d0491f8b25723aee62f812b4b74fce0f122f755d | [] | no_license | giarld/gxinMine | b06400e14527a3aad65fd4121f5f31dbeef65a81 | 7b3ba6bcd7c49f9a622d4a891cabd02659277ecf | refs/heads/master | 2020-04-10T22:47:30.019065 | 2014-07-06T15:26:51 | 2014-07-06T15:26:51 | 21,043,468 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,496 | cpp | #include "gamewidget.h"
#include <ctime>
#include <cstring>
GameWidget::GameWidget(QWidget *parent) :
QWidget(parent)
{
this->setFixedSize(QSize(270+100,270+100));
init();
// newGame();
}
void GameWidget::init()
{
this->wCount=this->hCount=9;
this->MineCount=10;
blockSize=30;
update();
for(int i=0;i<Max;i++)
{
for(int j=0;j<Max;j++)
{
map[i][j]=new Block(this);
map[i][j]->setPoint(j,i);
map[i][j]->setFixedSize(blockSize,blockSize);
map[i][j]->move(50+30*j,50+30*i);
map[i][j]->setVisible(false);
map[i][j]->locked();
connect(this,SIGNAL(setmk()),map[i][j],SLOT(setmk()));
}
}
}
void GameWidget::updateMap()
{
this->mapSize.setWidth(wCount*blockSize);
this->mapSize.setHeight(hCount*blockSize);
this->setFixedSize(QSize(mapSize.width()+100,mapSize.height()+100));
}
///public
int rr[2][8]={{0,1,0,-1,1,1,-1,-1},{1,0,-1,0,1,-1,1,-1}};
void GameWidget::createGame()
{
if(firstRun)
firstRun=0;
else
return;
int i,j;
for(i=0;i<hCount;i++)
{
for(j=0;j<wCount;j++)
{
for(int k=0;k<8;k++)
{
if(cmp(i+rr[0][k],j+rr[1][k]))
{
map[i][j]->setBrothers(map[i+rr[0][k]][j+rr[1][k]]);
}
}
map[i][j]->setInit();
}
}
blockSum=hCount*wCount;
flagSum=0;
Block *temp=qobject_cast<Block *>(sender());
int lod;
double q=(double)MineCount/(double)blockSum;
if(q<0.5)
{
lod=MineCount;
qsrand(time(NULL));
while(lod>0)
{
int rw=qrand()%wCount;
int rh=qrand()%hCount;
if(!map[rh][rw]->isMine() &&
(rw!=temp->getPoint().x() && rh!=temp->getPoint().y()) &&
!(temp->isBrother(map[rh][rw]) ))
{
map[rh][rw]->setMine(1);
lod--;
}
}
}
else
{
//qDebug()<<">=0.5";
lod=blockSum-MineCount;
bool dmap[Max][Max];
memset(dmap,1,sizeof(dmap));
qsrand(time(NULL));
int tx=temp->getPoint().y();
int ty=temp->getPoint().x();
dmap[tx][ty]=0;
for(int i=0;i<8;i++)
{
dmap[tx+rr[0][i]][ty+rr[1][i]]=0;
}
lod-=9;
while(lod>0)
{
int rw=qrand()%wCount;
int rh=qrand()%hCount;
if(dmap[rh][rw])
{
dmap[rh][rw]=0;
lod--;
}
}
for(int i=0;i<hCount;i++)
{
for(int j=0;j<wCount;j++)
{
if(dmap[i][j])
map[i][j]->setMine(1);
}
}
}
emit start();
}
///slots
bool GameWidget::cmp(int i, int j)
{
if(i<0 || j<0) return false;
if(i>=hCount || j>=wCount) return false;
return true;
}
void GameWidget::newGame()
{
for(int i=0;i<Max;i++)
{
for(int j=0;j<Max;j++)
{
map[i][j]->setVisible(false);
map[i][j]->reBrothers();
map[i][j]->setInit();
}
}
for(int i=0;i<hCount;i++)
{
for(int j=0;j<wCount;j++)
{
map[i][j]->setVisible(true);
connect(map[i][j],SIGNAL(start()),this,SLOT(createGame()));
connect(map[i][j],SIGNAL(isOpen()),this,SLOT(openBlock()));
connect(map[i][j],SIGNAL(isBoom()),this,SLOT(gameMiss()));
connect(map[i][j],SIGNAL(isFlag()),this,SLOT(isFlag()));
connect(map[i][j],SIGNAL(disFlag()),this,SLOT(disFlag()));
map[i][j]->unLocked();
}
}
firstRun=1;
emit mineSum(MineCount);
}
void GameWidget::gameMiss()
{
emit miss();
}
void GameWidget::gamePause()
{
for(int i=0;i<hCount;i++)
{
for(int j=0;j<wCount;j++)
{
map[i][j]->locked();
map[i][j]->setVisible(false);
}
}
}
void GameWidget::gameStart()
{
for(int i=0;i<hCount;i++)
{
for(int j=0;j<wCount;j++)
{
map[i][j]->unLocked();
map[i][j]->setVisible(true);
}
}
}
void GameWidget::setLevel(int w,int h,int s)
{
this->wCount=w;
this->hCount=h;
this->MineCount=s;
newGame();
}
void GameWidget::openBlock()
{
blockSum--;
// qDebug()<<blockSum;
if(blockSum==MineCount)
{
for(int i=0;i<Max;i++)
{
for(int j=0;j<Max;j++)
{
if(map[i][j]->getStatus()==Block::Default)
{
map[i][j]->setFlag();
}
map[i][j]->locked();
}
}
emit win();
}
}
void GameWidget::isFlag()
{
flagSum++;
emit mineSum(MineCount-flagSum);
}
void GameWidget::disFlag()
{
flagSum--;
if(flagSum<0)
flagSum=0;
emit mineSum(MineCount-flagSum);
}
void GameWidget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing,true);
QPen pen;
pen.setWidth(2);
pen.setColor(QColor(255,0,0));
painter.setPen(pen);
QRect rect(50-1,50-1,(blockSize)*wCount+2,(blockSize)*hCount+2);
painter.drawRect(rect);
painter.setFont(QFont("default",25));
painter.drawText(rect,tr("暂停"));
updateMap();
}
| [
"xinxinqqts@gmail.com"
] | xinxinqqts@gmail.com |
f5514a1052e5f51f1fcffeb3c4fb663ffd4a7621 | 8afa1e06465eeef8354087293b14c54d42af9cc2 | /src/qt/bitcoingui.cpp | b4d73f94c9b1c90b3e6dfb5e6a8c26670a58eebd | [
"MIT"
] | permissive | ShinDaniel/spon | 20577f0d8f6f884aff45ef6cc2729ecbd8cbeb31 | 9d768d68812028709611f8ffc5c06daf903493a1 | refs/heads/master | 2020-04-08T08:30:09.562087 | 2018-11-26T14:18:53 | 2018-11-26T14:18:53 | 155,554,669 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 52,273 | cpp | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The SPON developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bitcoingui.h"
#include "bitcoinunits.h"
#include "clientmodel.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "miner.h"
#include "networkstyle.h"
#include "notificator.h"
#include "openuridialog.h"
#include "optionsdialog.h"
#include "optionsmodel.h"
#include "rpcconsole.h"
#include "utilitydialog.h"
#ifdef ENABLE_WALLET
#include "blockexplorer.h"
#include "walletframe.h"
#include "walletmodel.h"
#endif // ENABLE_WALLET
#ifdef Q_OS_MAC
#include "macdockiconhandler.h"
#endif
#include "init.h"
#include "masternodelist.h"
#include "ui_interface.h"
#include "util.h"
#include <iostream>
#include <QAction>
#include <QApplication>
#include <QDateTime>
#include <QDesktopWidget>
#include <QDragEnterEvent>
#include <QIcon>
#include <QListWidget>
#include <QMenuBar>
#include <QMessageBox>
#include <QMimeData>
#include <QProgressBar>
#include <QProgressDialog>
#include <QSettings>
#include <QStackedWidget>
#include <QStatusBar>
#include <QStyle>
#include <QTimer>
#include <QToolBar>
#include <QVBoxLayout>
#if QT_VERSION < 0x050000
#include <QTextDocument>
#include <QUrl>
#else
#include <QUrlQuery>
#endif
const QString BitcoinGUI::DEFAULT_WALLET = "~Default";
BitcoinGUI::BitcoinGUI(const NetworkStyle* networkStyle, QWidget* parent) : QMainWindow(parent),
clientModel(0),
walletFrame(0),
unitDisplayControl(0),
labelStakingIcon(0),
labelEncryptionIcon(0),
labelConnectionsIcon(0),
labelBlocksIcon(0),
progressBarLabel(0),
progressBar(0),
progressDialog(0),
appMenuBar(0),
overviewAction(0),
historyAction(0),
masternodeAction(0),
quitAction(0),
sendCoinsAction(0),
usedSendingAddressesAction(0),
usedReceivingAddressesAction(0),
signMessageAction(0),
verifyMessageAction(0),
bip38ToolAction(0),
aboutAction(0),
receiveCoinsAction(0),
optionsAction(0),
toggleHideAction(0),
encryptWalletAction(0),
backupWalletAction(0),
changePassphraseAction(0),
aboutQtAction(0),
openRPCConsoleAction(0),
openAction(0),
showHelpMessageAction(0),
multiSendAction(0),
trayIcon(0),
trayIconMenu(0),
notificator(0),
rpcConsole(0),
explorerWindow(0),
prevBlocks(0),
spinnerFrame(0)
{
/* Open CSS when configured */
this->setStyleSheet(GUIUtil::loadStyleSheet());
GUIUtil::restoreWindowGeometry("nWindow", QSize(850, 550), this);
QString windowTitle = tr("SPON Core") + " - ";
#ifdef ENABLE_WALLET
/* if compiled with wallet support, -disablewallet can still disable the wallet */
enableWallet = !GetBoolArg("-disablewallet", false);
#else
enableWallet = false;
#endif // ENABLE_WALLET
if (enableWallet) {
windowTitle += tr("Wallet");
} else {
windowTitle += tr("Node");
}
QString userWindowTitle = QString::fromStdString(GetArg("-windowtitle", ""));
if (!userWindowTitle.isEmpty()) windowTitle += " - " + userWindowTitle;
windowTitle += " " + networkStyle->getTitleAddText();
#ifndef Q_OS_MAC
QApplication::setWindowIcon(networkStyle->getAppIcon());
setWindowIcon(networkStyle->getAppIcon());
#else
MacDockIconHandler::instance()->setIcon(networkStyle->getAppIcon());
#endif
setWindowTitle(windowTitle);
#if defined(Q_OS_MAC) && QT_VERSION < 0x050000
// This property is not implemented in Qt 5. Setting it has no effect.
// A replacement API (QtMacUnifiedToolBar) is available in QtMacExtras.
setUnifiedTitleAndToolBarOnMac(true);
#endif
rpcConsole = new RPCConsole(enableWallet ? this : 0);
#ifdef ENABLE_WALLET
if (enableWallet) {
/** Create wallet frame*/
walletFrame = new WalletFrame(this);
explorerWindow = new BlockExplorer(this);
} else
#endif // ENABLE_WALLET
{
/* When compiled without wallet or -disablewallet is provided,
* the central widget is the rpc console.
*/
setCentralWidget(rpcConsole);
}
// Accept D&D of URIs
setAcceptDrops(true);
// Create actions for the toolbar, menu bar and tray/dock icon
// Needs walletFrame to be initialized
createActions(networkStyle);
// Create application menu bar
createMenuBar();
// Create the toolbars
createToolBars();
// Create system tray icon and notification
createTrayIcon(networkStyle);
// Create status bar
statusBar();
// Status bar notification icons
QFrame* frameBlocks = new QFrame();
frameBlocks->setContentsMargins(0, 0, 0, 0);
frameBlocks->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);
QHBoxLayout* frameBlocksLayout = new QHBoxLayout(frameBlocks);
frameBlocksLayout->setContentsMargins(3, 0, 3, 0);
frameBlocksLayout->setSpacing(3);
unitDisplayControl = new UnitDisplayStatusBarControl();
labelStakingIcon = new QLabel();
labelEncryptionIcon = new QLabel();
labelConnectionsIcon = new QPushButton();
labelConnectionsIcon->setFlat(true); // Make the button look like a label, but clickable
labelConnectionsIcon->setStyleSheet(".QPushButton { background-color: rgba(255, 255, 255, 0);}");
labelConnectionsIcon->setMaximumSize(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE);
labelBlocksIcon = new QLabel();
if (enableWallet) {
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(unitDisplayControl);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelEncryptionIcon);
}
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelStakingIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelConnectionsIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelBlocksIcon);
frameBlocksLayout->addStretch();
// Progress bar and label for blocks download
progressBarLabel = new QLabel();
progressBarLabel->setVisible(true);
progressBar = new GUIUtil::ProgressBar();
progressBar->setAlignment(Qt::AlignCenter);
progressBar->setVisible(true);
// Override style sheet for progress bar for styles that have a segmented progress bar,
// as they make the text unreadable (workaround for issue #1071)
// See https://qt-project.org/doc/qt-4.8/gallery.html
QString curStyle = QApplication::style()->metaObject()->className();
if (curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle") {
progressBar->setStyleSheet("QProgressBar { background-color: #F8F8F8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #00CCFF, stop: 1 #33CCFF); border-radius: 7px; margin: 0px; }");
}
statusBar()->addWidget(progressBarLabel);
statusBar()->addWidget(progressBar);
statusBar()->addPermanentWidget(frameBlocks);
// Jump directly to tabs in RPC-console
connect(openInfoAction, SIGNAL(triggered()), rpcConsole, SLOT(showInfo()));
connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(showConsole()));
connect(openNetworkAction, SIGNAL(triggered()), rpcConsole, SLOT(showNetwork()));
connect(openPeersAction, SIGNAL(triggered()), rpcConsole, SLOT(showPeers()));
connect(openRepairAction, SIGNAL(triggered()), rpcConsole, SLOT(showRepair()));
connect(openConfEditorAction, SIGNAL(triggered()), rpcConsole, SLOT(showConfEditor()));
connect(openMNConfEditorAction, SIGNAL(triggered()), rpcConsole, SLOT(showMNConfEditor()));
connect(showBackupsAction, SIGNAL(triggered()), rpcConsole, SLOT(showBackups()));
connect(labelConnectionsIcon, SIGNAL(clicked()), rpcConsole, SLOT(showPeers()));
// Get restart command-line parameters and handle restart
connect(rpcConsole, SIGNAL(handleRestart(QStringList)), this, SLOT(handleRestart(QStringList)));
// prevents an open debug window from becoming stuck/unusable on client shutdown
connect(quitAction, SIGNAL(triggered()), rpcConsole, SLOT(hide()));
connect(openBlockExplorerAction, SIGNAL(triggered()), explorerWindow, SLOT(show()));
// prevents an open debug window from becoming stuck/unusable on client shutdown
connect(quitAction, SIGNAL(triggered()), explorerWindow, SLOT(hide()));
// Install event filter to be able to catch status tip events (QEvent::StatusTip)
this->installEventFilter(this);
// Initially wallet actions should be disabled
setWalletActionsEnabled(false);
// Subscribe to notifications from core
subscribeToCoreSignals();
QTimer* timerStakingIcon = new QTimer(labelStakingIcon);
connect(timerStakingIcon, SIGNAL(timeout()), this, SLOT(setStakingStatus()));
timerStakingIcon->start(10000);
setStakingStatus();
}
BitcoinGUI::~BitcoinGUI()
{
// Unsubscribe from notifications from core
unsubscribeFromCoreSignals();
GUIUtil::saveWindowGeometry("nWindow", this);
if (trayIcon) // Hide tray icon, as deleting will let it linger until quit (on Ubuntu)
trayIcon->hide();
#ifdef Q_OS_MAC
delete appMenuBar;
MacDockIconHandler::cleanup();
#endif
}
void BitcoinGUI::createActions(const NetworkStyle* networkStyle)
{
QActionGroup* tabGroup = new QActionGroup(this);
overviewAction = new QAction(QIcon(":/icons/overview"), tr("&Overview"), this);
overviewAction->setStatusTip(tr("Show general overview of wallet"));
overviewAction->setToolTip(overviewAction->statusTip());
overviewAction->setCheckable(true);
#ifdef Q_OS_MAC
overviewAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_1));
#else
overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1));
#endif
tabGroup->addAction(overviewAction);
sendCoinsAction = new QAction(QIcon(":/icons/send"), tr("&Send"), this);
sendCoinsAction->setStatusTip(tr("Send coins to a SPON address"));
sendCoinsAction->setToolTip(sendCoinsAction->statusTip());
sendCoinsAction->setCheckable(true);
#ifdef Q_OS_MAC
sendCoinsAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_2));
#else
sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2));
#endif
tabGroup->addAction(sendCoinsAction);
receiveCoinsAction = new QAction(QIcon(":/icons/receiving_addresses"), tr("&Receive"), this);
receiveCoinsAction->setStatusTip(tr("Request payments (generates QR codes and spon: URIs)"));
receiveCoinsAction->setToolTip(receiveCoinsAction->statusTip());
receiveCoinsAction->setCheckable(true);
#ifdef Q_OS_MAC
receiveCoinsAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_3));
#else
receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3));
#endif
tabGroup->addAction(receiveCoinsAction);
historyAction = new QAction(QIcon(":/icons/history"), tr("&Transactions"), this);
historyAction->setStatusTip(tr("Browse transaction history"));
historyAction->setToolTip(historyAction->statusTip());
historyAction->setCheckable(true);
#ifdef Q_OS_MAC
historyAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_4));
#else
historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4));
#endif
tabGroup->addAction(historyAction);
#ifdef ENABLE_WALLET
QSettings settings;
if (settings.value("fShowMasternodesTab").toBool()) {
masternodeAction = new QAction(QIcon(":/icons/masternodes"), tr("&Masternodes"), this);
masternodeAction->setStatusTip(tr("Browse masternodes"));
masternodeAction->setToolTip(masternodeAction->statusTip());
masternodeAction->setCheckable(true);
#ifdef Q_OS_MAC
masternodeAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_5));
#else
masternodeAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_5));
#endif
tabGroup->addAction(masternodeAction);
connect(masternodeAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(masternodeAction, SIGNAL(triggered()), this, SLOT(gotoMasternodePage()));
}
// These showNormalIfMinimized are needed because Send Coins and Receive Coins
// can be triggered from the tray menu, and need to show the GUI to be useful.
connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage()));
#endif // ENABLE_WALLET
quitAction = new QAction(QIcon(":/icons/quit"), tr("E&xit"), this);
quitAction->setStatusTip(tr("Quit application"));
quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
quitAction->setMenuRole(QAction::QuitRole);
aboutAction = new QAction(networkStyle->getAppIcon(), tr("&About SPON Core"), this);
aboutAction->setStatusTip(tr("Show information about SPON Core"));
aboutAction->setMenuRole(QAction::AboutRole);
#if QT_VERSION < 0x050000
aboutQtAction = new QAction(QIcon(":/trolltech/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this);
#else
aboutQtAction = new QAction(QIcon(":/qt-project.org/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this);
#endif
aboutQtAction->setStatusTip(tr("Show information about Qt"));
aboutQtAction->setMenuRole(QAction::AboutQtRole);
optionsAction = new QAction(QIcon(":/icons/options"), tr("&Options..."), this);
optionsAction->setStatusTip(tr("Modify configuration options for SPON"));
optionsAction->setMenuRole(QAction::PreferencesRole);
toggleHideAction = new QAction(networkStyle->getAppIcon(), tr("&Show / Hide"), this);
toggleHideAction->setStatusTip(tr("Show or hide the main Window"));
encryptWalletAction = new QAction(QIcon(":/icons/lock_closed"), tr("&Encrypt Wallet..."), this);
encryptWalletAction->setStatusTip(tr("Encrypt the private keys that belong to your wallet"));
encryptWalletAction->setCheckable(true);
backupWalletAction = new QAction(QIcon(":/icons/filesave"), tr("&Backup Wallet..."), this);
backupWalletAction->setStatusTip(tr("Backup wallet to another location"));
changePassphraseAction = new QAction(QIcon(":/icons/key"), tr("&Change Passphrase..."), this);
changePassphraseAction->setStatusTip(tr("Change the passphrase used for wallet encryption"));
unlockWalletAction = new QAction(tr("&Unlock Wallet..."), this);
unlockWalletAction->setToolTip(tr("Unlock wallet"));
lockWalletAction = new QAction(tr("&Lock Wallet"), this);
signMessageAction = new QAction(QIcon(":/icons/edit"), tr("Sign &message..."), this);
signMessageAction->setStatusTip(tr("Sign messages with your SPON addresses to prove you own them"));
verifyMessageAction = new QAction(QIcon(":/icons/transaction_0"), tr("&Verify message..."), this);
verifyMessageAction->setStatusTip(tr("Verify messages to ensure they were signed with specified SPON addresses"));
bip38ToolAction = new QAction(QIcon(":/icons/key"), tr("&BIP38 tool"), this);
bip38ToolAction->setToolTip(tr("Encrypt and decrypt private keys using a passphrase"));
multiSendAction = new QAction(QIcon(":/icons/edit"), tr("&MultiSend"), this);
multiSendAction->setToolTip(tr("MultiSend Settings"));
multiSendAction->setCheckable(true);
openInfoAction = new QAction(QApplication::style()->standardIcon(QStyle::SP_MessageBoxInformation), tr("&Information"), this);
openInfoAction->setStatusTip(tr("Show diagnostic information"));
openRPCConsoleAction = new QAction(QIcon(":/icons/debugwindow"), tr("&Debug console"), this);
openRPCConsoleAction->setStatusTip(tr("Open debugging console"));
openNetworkAction = new QAction(QIcon(":/icons/connect_4"), tr("&Network Monitor"), this);
openNetworkAction->setStatusTip(tr("Show network monitor"));
openPeersAction = new QAction(QIcon(":/icons/connect_4"), tr("&Peers list"), this);
openPeersAction->setStatusTip(tr("Show peers info"));
openRepairAction = new QAction(QIcon(":/icons/options"), tr("Wallet &Repair"), this);
openRepairAction->setStatusTip(tr("Show wallet repair options"));
openConfEditorAction = new QAction(QIcon(":/icons/edit"), tr("Open Wallet &Configuration File"), this);
openConfEditorAction->setStatusTip(tr("Open configuration file"));
openMNConfEditorAction = new QAction(QIcon(":/icons/edit"), tr("Open &Masternode Configuration File"), this);
openMNConfEditorAction->setStatusTip(tr("Open Masternode configuration file"));
showBackupsAction = new QAction(QIcon(":/icons/browse"), tr("Show Automatic &Backups"), this);
showBackupsAction->setStatusTip(tr("Show automatically created wallet backups"));
usedSendingAddressesAction = new QAction(QIcon(":/icons/address-book"), tr("&Sending addresses..."), this);
usedSendingAddressesAction->setStatusTip(tr("Show the list of used sending addresses and labels"));
usedReceivingAddressesAction = new QAction(QIcon(":/icons/address-book"), tr("&Receiving addresses..."), this);
usedReceivingAddressesAction->setStatusTip(tr("Show the list of used receiving addresses and labels"));
openAction = new QAction(QApplication::style()->standardIcon(QStyle::SP_FileIcon), tr("Open &URI..."), this);
openAction->setStatusTip(tr("Open a SPON: URI or payment request"));
openBlockExplorerAction = new QAction(QIcon(":/icons/explorer"), tr("&Blockchain explorer"), this);
openBlockExplorerAction->setStatusTip(tr("Block explorer window"));
showHelpMessageAction = new QAction(QApplication::style()->standardIcon(QStyle::SP_MessageBoxInformation), tr("&Command-line options"), this);
showHelpMessageAction->setMenuRole(QAction::NoRole);
showHelpMessageAction->setStatusTip(tr("Show the SPON Core help message to get a list with possible SPON command-line options"));
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked()));
connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked()));
connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHidden()));
connect(showHelpMessageAction, SIGNAL(triggered()), this, SLOT(showHelpMessageClicked()));
#ifdef ENABLE_WALLET
if (walletFrame) {
connect(encryptWalletAction, SIGNAL(triggered(bool)), walletFrame, SLOT(encryptWallet(bool)));
connect(backupWalletAction, SIGNAL(triggered()), walletFrame, SLOT(backupWallet()));
connect(changePassphraseAction, SIGNAL(triggered()), walletFrame, SLOT(changePassphrase()));
connect(unlockWalletAction, SIGNAL(triggered()), walletFrame, SLOT(unlockWallet()));
connect(lockWalletAction, SIGNAL(triggered()), walletFrame, SLOT(lockWallet()));
connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab()));
connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab()));
connect(bip38ToolAction, SIGNAL(triggered()), this, SLOT(gotoBip38Tool()));
connect(usedSendingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedSendingAddresses()));
connect(usedReceivingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedReceivingAddresses()));
connect(openAction, SIGNAL(triggered()), this, SLOT(openClicked()));
connect(multiSendAction, SIGNAL(triggered()), this, SLOT(gotoMultiSendDialog()));
}
#endif // ENABLE_WALLET
}
void BitcoinGUI::createMenuBar()
{
#ifdef Q_OS_MAC
// Create a decoupled menu bar on Mac which stays even if the window is closed
appMenuBar = new QMenuBar();
#else
// Get the main window's menu bar on other platforms
appMenuBar = menuBar();
#endif
// Configure the menus
QMenu* file = appMenuBar->addMenu(tr("&File"));
if (walletFrame) {
file->addAction(openAction);
file->addAction(backupWalletAction);
file->addAction(signMessageAction);
file->addAction(verifyMessageAction);
file->addSeparator();
file->addAction(usedSendingAddressesAction);
file->addAction(usedReceivingAddressesAction);
file->addSeparator();
}
file->addAction(quitAction);
QMenu* settings = appMenuBar->addMenu(tr("&Settings"));
if (walletFrame) {
settings->addAction(encryptWalletAction);
settings->addAction(changePassphraseAction);
settings->addAction(unlockWalletAction);
settings->addAction(lockWalletAction);
settings->addAction(bip38ToolAction);
settings->addAction(multiSendAction);
settings->addSeparator();
}
settings->addAction(optionsAction);
if (walletFrame) {
QMenu* tools = appMenuBar->addMenu(tr("&Tools"));
tools->addAction(openInfoAction);
tools->addAction(openRPCConsoleAction);
tools->addAction(openNetworkAction);
tools->addAction(openPeersAction);
tools->addAction(openRepairAction);
tools->addSeparator();
tools->addAction(openConfEditorAction);
tools->addAction(openMNConfEditorAction);
tools->addAction(showBackupsAction);
tools->addAction(openBlockExplorerAction);
}
QMenu* help = appMenuBar->addMenu(tr("&Help"));
help->addAction(showHelpMessageAction);
help->addSeparator();
help->addAction(aboutAction);
help->addAction(aboutQtAction);
}
void BitcoinGUI::createToolBars()
{
if (walletFrame) {
QToolBar* toolbar = new QToolBar(tr("Tabs toolbar"));
toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
toolbar->addAction(overviewAction);
toolbar->addAction(sendCoinsAction);
toolbar->addAction(receiveCoinsAction);
toolbar->addAction(historyAction);
QSettings settings;
if (settings.value("fShowMasternodesTab").toBool()) {
toolbar->addAction(masternodeAction);
}
toolbar->setMovable(false); // remove unused icon in upper left corner
overviewAction->setChecked(true);
/** Create additional container for toolbar and walletFrame and make it the central widget.
This is a workaround mostly for toolbar styling on Mac OS but should work fine for every other OSes too.
*/
QVBoxLayout* layout = new QVBoxLayout;
layout->addWidget(toolbar);
layout->addWidget(walletFrame);
layout->setSpacing(0);
layout->setContentsMargins(QMargins());
QWidget* containerWidget = new QWidget();
containerWidget->setLayout(layout);
setCentralWidget(containerWidget);
}
}
void BitcoinGUI::setClientModel(ClientModel* clientModel)
{
this->clientModel = clientModel;
if (clientModel) {
// Create system tray menu (or setup the dock menu) that late to prevent users from calling actions,
// while the client has not yet fully loaded
createTrayIconMenu();
// Keep up to date with client
setNumConnections(clientModel->getNumConnections());
connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
setNumBlocks(clientModel->getNumBlocks());
connect(clientModel, SIGNAL(numBlocksChanged(int)), this, SLOT(setNumBlocks(int)));
// Receive and report messages from client model
connect(clientModel, SIGNAL(message(QString, QString, unsigned int)), this, SLOT(message(QString, QString, unsigned int)));
// Show progress dialog
connect(clientModel, SIGNAL(showProgress(QString, int)), this, SLOT(showProgress(QString, int)));
rpcConsole->setClientModel(clientModel);
#ifdef ENABLE_WALLET
if (walletFrame) {
walletFrame->setClientModel(clientModel);
}
#endif // ENABLE_WALLET
unitDisplayControl->setOptionsModel(clientModel->getOptionsModel());
} else {
// Disable possibility to show main window via action
toggleHideAction->setEnabled(false);
if (trayIconMenu) {
// Disable context menu on tray icon
trayIconMenu->clear();
}
}
}
#ifdef ENABLE_WALLET
bool BitcoinGUI::addWallet(const QString& name, WalletModel* walletModel)
{
if (!walletFrame)
return false;
setWalletActionsEnabled(true);
return walletFrame->addWallet(name, walletModel);
}
bool BitcoinGUI::setCurrentWallet(const QString& name)
{
if (!walletFrame)
return false;
return walletFrame->setCurrentWallet(name);
}
void BitcoinGUI::removeAllWallets()
{
if (!walletFrame)
return;
setWalletActionsEnabled(false);
walletFrame->removeAllWallets();
}
#endif // ENABLE_WALLET
void BitcoinGUI::setWalletActionsEnabled(bool enabled)
{
overviewAction->setEnabled(enabled);
sendCoinsAction->setEnabled(enabled);
receiveCoinsAction->setEnabled(enabled);
historyAction->setEnabled(enabled);
QSettings settings;
if (settings.value("fShowMasternodesTab").toBool()) {
masternodeAction->setEnabled(enabled);
}
encryptWalletAction->setEnabled(enabled);
backupWalletAction->setEnabled(enabled);
changePassphraseAction->setEnabled(enabled);
signMessageAction->setEnabled(enabled);
verifyMessageAction->setEnabled(enabled);
bip38ToolAction->setEnabled(enabled);
usedSendingAddressesAction->setEnabled(enabled);
usedReceivingAddressesAction->setEnabled(enabled);
openAction->setEnabled(enabled);
}
void BitcoinGUI::createTrayIcon(const NetworkStyle* networkStyle)
{
#ifndef Q_OS_MAC
trayIcon = new QSystemTrayIcon(this);
QString toolTip = tr("SPON Core client") + " " + networkStyle->getTitleAddText();
trayIcon->setToolTip(toolTip);
trayIcon->setIcon(networkStyle->getAppIcon());
trayIcon->show();
#endif
notificator = new Notificator(QApplication::applicationName(), trayIcon, this);
}
void BitcoinGUI::createTrayIconMenu()
{
#ifndef Q_OS_MAC
// return if trayIcon is unset (only on non-Mac OSes)
if (!trayIcon)
return;
trayIconMenu = new QMenu(this);
trayIcon->setContextMenu(trayIconMenu);
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));
#else
// Note: On Mac, the dock icon is used to provide the tray's functionality.
MacDockIconHandler* dockIconHandler = MacDockIconHandler::instance();
dockIconHandler->setMainWindow((QMainWindow*)this);
trayIconMenu = dockIconHandler->dockMenu();
#endif
// Configuration of the tray icon (or dock icon) icon menu
trayIconMenu->addAction(toggleHideAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(sendCoinsAction);
trayIconMenu->addAction(receiveCoinsAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(signMessageAction);
trayIconMenu->addAction(verifyMessageAction);
trayIconMenu->addAction(bip38ToolAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(optionsAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(openInfoAction);
trayIconMenu->addAction(openRPCConsoleAction);
trayIconMenu->addAction(openNetworkAction);
trayIconMenu->addAction(openPeersAction);
trayIconMenu->addAction(openRepairAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(openConfEditorAction);
trayIconMenu->addAction(openMNConfEditorAction);
trayIconMenu->addAction(showBackupsAction);
trayIconMenu->addAction(openBlockExplorerAction);
#ifndef Q_OS_MAC // This is built-in on Mac
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
#endif
}
#ifndef Q_OS_MAC
void BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
if (reason == QSystemTrayIcon::Trigger) {
// Click on system tray icon triggers show/hide of the main window
toggleHidden();
}
}
#endif
void BitcoinGUI::optionsClicked()
{
if (!clientModel || !clientModel->getOptionsModel())
return;
OptionsDialog dlg(this, enableWallet);
dlg.setModel(clientModel->getOptionsModel());
dlg.exec();
}
void BitcoinGUI::aboutClicked()
{
if (!clientModel)
return;
HelpMessageDialog dlg(this, true);
dlg.exec();
}
void BitcoinGUI::showHelpMessageClicked()
{
HelpMessageDialog* help = new HelpMessageDialog(this, false);
help->setAttribute(Qt::WA_DeleteOnClose);
help->show();
}
#ifdef ENABLE_WALLET
void BitcoinGUI::openClicked()
{
OpenURIDialog dlg(this);
if (dlg.exec()) {
emit receivedURI(dlg.getURI());
}
}
void BitcoinGUI::gotoOverviewPage()
{
overviewAction->setChecked(true);
if (walletFrame) walletFrame->gotoOverviewPage();
}
void BitcoinGUI::gotoHistoryPage()
{
historyAction->setChecked(true);
if (walletFrame) walletFrame->gotoHistoryPage();
}
void BitcoinGUI::gotoMasternodePage()
{
QSettings settings;
if (settings.value("fShowMasternodesTab").toBool()) {
masternodeAction->setChecked(true);
if (walletFrame) walletFrame->gotoMasternodePage();
}
}
void BitcoinGUI::gotoReceiveCoinsPage()
{
receiveCoinsAction->setChecked(true);
if (walletFrame) walletFrame->gotoReceiveCoinsPage();
}
void BitcoinGUI::gotoSendCoinsPage(QString addr)
{
sendCoinsAction->setChecked(true);
if (walletFrame) walletFrame->gotoSendCoinsPage(addr);
}
void BitcoinGUI::gotoSignMessageTab(QString addr)
{
if (walletFrame) walletFrame->gotoSignMessageTab(addr);
}
void BitcoinGUI::gotoVerifyMessageTab(QString addr)
{
if (walletFrame) walletFrame->gotoVerifyMessageTab(addr);
}
void BitcoinGUI::gotoBip38Tool()
{
if (walletFrame) walletFrame->gotoBip38Tool();
}
void BitcoinGUI::gotoMultiSendDialog()
{
multiSendAction->setChecked(true);
if (walletFrame)
walletFrame->gotoMultiSendDialog();
}
void BitcoinGUI::gotoBlockExplorerPage()
{
if (walletFrame) walletFrame->gotoBlockExplorerPage();
}
#endif // ENABLE_WALLET
void BitcoinGUI::setNumConnections(int count)
{
QString icon;
switch (count) {
case 0:
icon = ":/icons/connect_0";
break;
case 1:
case 2:
case 3:
icon = ":/icons/connect_1";
break;
case 4:
case 5:
case 6:
icon = ":/icons/connect_2";
break;
case 7:
case 8:
case 9:
icon = ":/icons/connect_3";
break;
default:
icon = ":/icons/connect_4";
break;
}
QIcon connectionItem = QIcon(icon).pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE);
labelConnectionsIcon->setIcon(connectionItem);
labelConnectionsIcon->setToolTip(tr("%n active connection(s) to SPON network", "", count));
}
void BitcoinGUI::setNumBlocks(int count)
{
if (!clientModel)
return;
// Prevent orphan statusbar messages (e.g. hover Quit in main menu, wait until chain-sync starts -> garbelled text)
statusBar()->clearMessage();
// Acquire current block source
enum BlockSource blockSource = clientModel->getBlockSource();
switch (blockSource) {
case BLOCK_SOURCE_NETWORK:
progressBarLabel->setText(tr("Synchronizing with network..."));
break;
case BLOCK_SOURCE_DISK:
progressBarLabel->setText(tr("Importing blocks from disk..."));
break;
case BLOCK_SOURCE_REINDEX:
progressBarLabel->setText(tr("Reindexing blocks on disk..."));
break;
case BLOCK_SOURCE_NONE:
// Case: not Importing, not Reindexing and no network connection
progressBarLabel->setText(tr("No block source available..."));
break;
}
QString tooltip;
QDateTime lastBlockDate = clientModel->getLastBlockDate();
QDateTime currentDate = QDateTime::currentDateTime();
int secs = lastBlockDate.secsTo(currentDate);
tooltip = tr("Processed %n blocks of transaction history.", "", count);
// Set icon state: spinning if catching up, tick otherwise
// if(secs < 25*60) // 90*60 for bitcoin but we are 4x times faster
if (masternodeSync.IsBlockchainSynced()) {
QString strSyncStatus;
tooltip = tr("Up to date") + QString(".<br>") + tooltip;
if (masternodeSync.IsSynced()) {
progressBarLabel->setVisible(false);
progressBar->setVisible(false);
labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
} else {
int nAttempt;
int progress = 0;
labelBlocksIcon->setPixmap(QIcon(QString(
":/movies/spinner-%1")
.arg(spinnerFrame, 3, 10, QChar('0')))
.pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
spinnerFrame = (spinnerFrame + 1) % SPINNER_FRAMES;
#ifdef ENABLE_WALLET
if (walletFrame)
walletFrame->showOutOfSyncWarning(false);
#endif // ENABLE_WALLET
nAttempt = masternodeSync.RequestedMasternodeAttempt < MASTERNODE_SYNC_THRESHOLD ?
masternodeSync.RequestedMasternodeAttempt + 1 :
MASTERNODE_SYNC_THRESHOLD;
progress = nAttempt + (masternodeSync.RequestedMasternodeAssets - 1) * MASTERNODE_SYNC_THRESHOLD;
progressBar->setMaximum(4 * MASTERNODE_SYNC_THRESHOLD);
progressBar->setFormat(tr("Synchronizing additional data: %p%"));
progressBar->setValue(progress);
}
strSyncStatus = QString(masternodeSync.GetSyncStatus().c_str());
progressBarLabel->setText(strSyncStatus);
tooltip = strSyncStatus + QString("<br>") + tooltip;
} else {
// Represent time from last generated block in human readable text
QString timeBehindText;
const int HOUR_IN_SECONDS = 60 * 60;
const int DAY_IN_SECONDS = 24 * 60 * 60;
const int WEEK_IN_SECONDS = 7 * 24 * 60 * 60;
const int YEAR_IN_SECONDS = 31556952; // Average length of year in Gregorian calendar
if (secs < 2 * DAY_IN_SECONDS) {
timeBehindText = tr("%n hour(s)", "", secs / HOUR_IN_SECONDS);
} else if (secs < 2 * WEEK_IN_SECONDS) {
timeBehindText = tr("%n day(s)", "", secs / DAY_IN_SECONDS);
} else if (secs < YEAR_IN_SECONDS) {
timeBehindText = tr("%n week(s)", "", secs / WEEK_IN_SECONDS);
} else {
int years = secs / YEAR_IN_SECONDS;
int remainder = secs % YEAR_IN_SECONDS;
timeBehindText = tr("%1 and %2").arg(tr("%n year(s)", "", years)).arg(tr("%n week(s)", "", remainder / WEEK_IN_SECONDS));
}
progressBarLabel->setVisible(true);
progressBar->setFormat(tr("%1 behind").arg(timeBehindText));
progressBar->setMaximum(1000000000);
progressBar->setValue(clientModel->getVerificationProgress() * 1000000000.0 + 0.5);
progressBar->setVisible(true);
tooltip = tr("Catching up...") + QString("<br>") + tooltip;
if (count != prevBlocks) {
labelBlocksIcon->setPixmap(QIcon(QString(
":/movies/spinner-%1")
.arg(spinnerFrame, 3, 10, QChar('0')))
.pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
spinnerFrame = (spinnerFrame + 1) % SPINNER_FRAMES;
}
prevBlocks = count;
#ifdef ENABLE_WALLET
if (walletFrame)
walletFrame->showOutOfSyncWarning(true);
#endif // ENABLE_WALLET
tooltip += QString("<br>");
tooltip += tr("Last received block was generated %1 ago.").arg(timeBehindText);
tooltip += QString("<br>");
tooltip += tr("Transactions after this will not yet be visible.");
}
// Don't word-wrap this (fixed-width) tooltip
tooltip = QString("<nobr>") + tooltip + QString("</nobr>");
labelBlocksIcon->setToolTip(tooltip);
progressBarLabel->setToolTip(tooltip);
progressBar->setToolTip(tooltip);
}
void BitcoinGUI::message(const QString& title, const QString& message, unsigned int style, bool* ret)
{
QString strTitle = tr("SPON Core"); // default title
// Default to information icon
int nMBoxIcon = QMessageBox::Information;
int nNotifyIcon = Notificator::Information;
QString msgType;
// Prefer supplied title over style based title
if (!title.isEmpty()) {
msgType = title;
} else {
switch (style) {
case CClientUIInterface::MSG_ERROR:
msgType = tr("Error");
break;
case CClientUIInterface::MSG_WARNING:
msgType = tr("Warning");
break;
case CClientUIInterface::MSG_INFORMATION:
msgType = tr("Information");
break;
default:
break;
}
}
// Append title to "SPON - "
if (!msgType.isEmpty())
strTitle += " - " + msgType;
// Check for error/warning icon
if (style & CClientUIInterface::ICON_ERROR) {
nMBoxIcon = QMessageBox::Critical;
nNotifyIcon = Notificator::Critical;
} else if (style & CClientUIInterface::ICON_WARNING) {
nMBoxIcon = QMessageBox::Warning;
nNotifyIcon = Notificator::Warning;
}
// Display message
if (style & CClientUIInterface::MODAL) {
// Check for buttons, use OK as default, if none was supplied
QMessageBox::StandardButton buttons;
if (!(buttons = (QMessageBox::StandardButton)(style & CClientUIInterface::BTN_MASK)))
buttons = QMessageBox::Ok;
showNormalIfMinimized();
QMessageBox mBox((QMessageBox::Icon)nMBoxIcon, strTitle, message, buttons, this);
int r = mBox.exec();
if (ret != NULL)
*ret = r == QMessageBox::Ok;
} else
notificator->notify((Notificator::Class)nNotifyIcon, strTitle, message);
}
void BitcoinGUI::changeEvent(QEvent* e)
{
QMainWindow::changeEvent(e);
#ifndef Q_OS_MAC // Ignored on Mac
if (e->type() == QEvent::WindowStateChange) {
if (clientModel && clientModel->getOptionsModel() && clientModel->getOptionsModel()->getMinimizeToTray()) {
QWindowStateChangeEvent* wsevt = static_cast<QWindowStateChangeEvent*>(e);
if (!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized()) {
QTimer::singleShot(0, this, SLOT(hide()));
e->ignore();
}
}
}
#endif
}
void BitcoinGUI::closeEvent(QCloseEvent* event)
{
#ifndef Q_OS_MAC // Ignored on Mac
if (clientModel && clientModel->getOptionsModel()) {
if (!clientModel->getOptionsModel()->getMinimizeOnClose()) {
QApplication::quit();
}
}
#endif
QMainWindow::closeEvent(event);
}
#ifdef ENABLE_WALLET
void BitcoinGUI::incomingTransaction(const QString& date, int unit, const CAmount& amount, const QString& type, const QString& address)
{
// On new transaction, make an info balloon
message((amount) < 0 ? (pwalletMain->fMultiSendNotify == true ? tr("Sent MultiSend transaction") : tr("Sent transaction")) : tr("Incoming transaction"),
tr("Date: %1\n"
"Amount: %2\n"
"Type: %3\n"
"Address: %4\n")
.arg(date)
.arg(BitcoinUnits::formatWithUnit(unit, amount, true))
.arg(type)
.arg(address),
CClientUIInterface::MSG_INFORMATION);
pwalletMain->fMultiSendNotify = false;
}
#endif // ENABLE_WALLET
void BitcoinGUI::dragEnterEvent(QDragEnterEvent* event)
{
// Accept only URIs
if (event->mimeData()->hasUrls())
event->acceptProposedAction();
}
void BitcoinGUI::dropEvent(QDropEvent* event)
{
if (event->mimeData()->hasUrls()) {
foreach (const QUrl& uri, event->mimeData()->urls()) {
emit receivedURI(uri.toString());
}
}
event->acceptProposedAction();
}
bool BitcoinGUI::eventFilter(QObject* object, QEvent* event)
{
// Catch status tip events
if (event->type() == QEvent::StatusTip) {
// Prevent adding text from setStatusTip(), if we currently use the status bar for displaying other stuff
if (progressBarLabel->isVisible() || progressBar->isVisible())
return true;
}
return QMainWindow::eventFilter(object, event);
}
void BitcoinGUI::setStakingStatus()
{
if (pwalletMain)
fMultiSend = pwalletMain->isMultiSendEnabled();
if (nLastCoinStakeSearchInterval) {
labelStakingIcon->show();
labelStakingIcon->setPixmap(QIcon(":/icons/staking_active").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
labelStakingIcon->setToolTip(tr("Staking is active\n MultiSend: %1").arg(fMultiSend ? tr("Active") : tr("Not Active")));
} else {
labelStakingIcon->show();
labelStakingIcon->setPixmap(QIcon(":/icons/staking_inactive").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
labelStakingIcon->setToolTip(tr("Staking is not active\n MultiSend: %1").arg(fMultiSend ? tr("Active") : tr("Not Active")));
}
}
#ifdef ENABLE_WALLET
bool BitcoinGUI::handlePaymentRequest(const SendCoinsRecipient& recipient)
{
// URI has to be valid
if (walletFrame && walletFrame->handlePaymentRequest(recipient)) {
showNormalIfMinimized();
gotoSendCoinsPage();
return true;
}
return false;
}
void BitcoinGUI::setEncryptionStatus(int status)
{
switch (status) {
case WalletModel::Unencrypted:
labelEncryptionIcon->hide();
encryptWalletAction->setChecked(false);
changePassphraseAction->setEnabled(false);
unlockWalletAction->setVisible(false);
lockWalletAction->setVisible(false);
encryptWalletAction->setEnabled(true);
break;
case WalletModel::Unlocked:
labelEncryptionIcon->show();
labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
unlockWalletAction->setVisible(false);
lockWalletAction->setVisible(true);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
case WalletModel::UnlockedForAnonymizationOnly:
labelEncryptionIcon->show();
labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b> for anonimization and staking only"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
unlockWalletAction->setVisible(true);
lockWalletAction->setVisible(true);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
case WalletModel::Locked:
labelEncryptionIcon->show();
labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_closed").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
unlockWalletAction->setVisible(true);
lockWalletAction->setVisible(false);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
}
}
#endif // ENABLE_WALLET
void BitcoinGUI::showNormalIfMinimized(bool fToggleHidden)
{
if (!clientModel)
return;
// activateWindow() (sometimes) helps with keyboard focus on Windows
if (isHidden()) {
show();
activateWindow();
} else if (isMinimized()) {
showNormal();
activateWindow();
} else if (GUIUtil::isObscured(this)) {
raise();
activateWindow();
} else if (fToggleHidden)
hide();
}
void BitcoinGUI::toggleHidden()
{
showNormalIfMinimized(true);
}
void BitcoinGUI::detectShutdown()
{
if (ShutdownRequested()) {
if (rpcConsole)
rpcConsole->hide();
qApp->quit();
}
}
void BitcoinGUI::showProgress(const QString& title, int nProgress)
{
if (nProgress == 0) {
progressDialog = new QProgressDialog(title, "", 0, 100);
progressDialog->setWindowModality(Qt::ApplicationModal);
progressDialog->setMinimumDuration(0);
progressDialog->setCancelButton(0);
progressDialog->setAutoClose(false);
progressDialog->setValue(0);
} else if (nProgress == 100) {
if (progressDialog) {
progressDialog->close();
progressDialog->deleteLater();
}
} else if (progressDialog)
progressDialog->setValue(nProgress);
}
static bool ThreadSafeMessageBox(BitcoinGUI* gui, const std::string& message, const std::string& caption, unsigned int style)
{
bool modal = (style & CClientUIInterface::MODAL);
// The SECURE flag has no effect in the Qt GUI.
// bool secure = (style & CClientUIInterface::SECURE);
style &= ~CClientUIInterface::SECURE;
bool ret = false;
// In case of modal message, use blocking connection to wait for user to click a button
QMetaObject::invokeMethod(gui, "message",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(unsigned int, style),
Q_ARG(bool*, &ret));
return ret;
}
void BitcoinGUI::subscribeToCoreSignals()
{
// Connect signals to client
uiInterface.ThreadSafeMessageBox.connect(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3));
}
void BitcoinGUI::unsubscribeFromCoreSignals()
{
// Disconnect signals from client
uiInterface.ThreadSafeMessageBox.disconnect(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3));
}
/** Get restart command-line parameters and request restart */
void BitcoinGUI::handleRestart(QStringList args)
{
if (!ShutdownRequested())
emit requestedRestart(args);
}
UnitDisplayStatusBarControl::UnitDisplayStatusBarControl() : optionsModel(0),
menu(0)
{
createContextMenu();
setToolTip(tr("Unit to show amounts in. Click to select another unit."));
}
/** So that it responds to button clicks */
void UnitDisplayStatusBarControl::mousePressEvent(QMouseEvent* event)
{
onDisplayUnitsClicked(event->pos());
}
/** Creates context menu, its actions, and wires up all the relevant signals for mouse events. */
void UnitDisplayStatusBarControl::createContextMenu()
{
menu = new QMenu();
foreach (BitcoinUnits::Unit u, BitcoinUnits::availableUnits()) {
QAction* menuAction = new QAction(QString(BitcoinUnits::name(u)), this);
menuAction->setData(QVariant(u));
menu->addAction(menuAction);
}
connect(menu, SIGNAL(triggered(QAction*)), this, SLOT(onMenuSelection(QAction*)));
}
/** Lets the control know about the Options Model (and its signals) */
void UnitDisplayStatusBarControl::setOptionsModel(OptionsModel* optionsModel)
{
if (optionsModel) {
this->optionsModel = optionsModel;
// be aware of a display unit change reported by the OptionsModel object.
connect(optionsModel, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit(int)));
// initialize the display units label with the current value in the model.
updateDisplayUnit(optionsModel->getDisplayUnit());
}
}
/** When Display Units are changed on OptionsModel it will refresh the display text of the control on the status bar */
void UnitDisplayStatusBarControl::updateDisplayUnit(int newUnits)
{
if (Params().NetworkID() == CBaseChainParams::MAIN) {
setPixmap(QIcon(":/icons/unit_" + BitcoinUnits::id(newUnits)).pixmap(39, STATUSBAR_ICONSIZE));
} else {
setPixmap(QIcon(":/icons/unit_t" + BitcoinUnits::id(newUnits)).pixmap(39, STATUSBAR_ICONSIZE));
}
}
/** Shows context menu with Display Unit options by the mouse coordinates */
void UnitDisplayStatusBarControl::onDisplayUnitsClicked(const QPoint& point)
{
QPoint globalPos = mapToGlobal(point);
menu->exec(globalPos);
}
/** Tells underlying optionsModel to update its current display unit. */
void UnitDisplayStatusBarControl::onMenuSelection(QAction* action)
{
if (action) {
optionsModel->setDisplayUnit(action->data());
}
}
| [
"sis3719@gmail.com"
] | sis3719@gmail.com |
8c55a2fee42abd7569c14942316464bb6ff980c0 | 5a9e00549b34e729aee373786fd4c8bc26b85670 | /main.cpp | 83e08d26faa9533da9241bdd80f45fe7a56f09fb | [] | no_license | pelikenmag/tetris | 5b11b8513be64e1cc1074845a1661d6ca52b460b | 2bee8cf822df1c4a6e87a975cf8628129793a766 | refs/heads/master | 2021-01-20T04:24:56.948643 | 2014-09-02T17:41:13 | 2014-09-02T17:41:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,700 | cpp | #include "tetris.h"
int main(){
Field gamefield;
Shape myshape;
st_MERGEME mergeme;
SDL_Event event_handle;
gamefield.Init(FIELD_SIZE_N,FIELD_SIZE_M);
int i,j,x=DEFAULT_X,y=DEFAULT_Y,mergeresult,protox=x;
char arrow;
bool quit=false;
myshape.Generate(SHAPE_STICK);
DrawWorld window2D;
window2D.Init();
while (!quit){
while (1){
mergeme.shape=myshape.GetShape();mergeme.sn=myshape.GetShapeN();mergeme.sm=myshape.GetShapeM();
mergeme.x=x;mergeme.y=y;
mergeresult=gamefield.Merge(mergeme);
if (mergeresult==FIELD_OK)
break;
if (mergeresult==FIELD_BORDER || mergeresult==FIELD_BORDER|FIELD_BOTTOM){
std::cout<<"Border!"<<endl;
x=protox;
}
if (mergeresult==FIELD_BOTTOM){
std::cout<<"Bottom!"<<endl;
myshape.Generate(SHAPE_ANGLE);
x=DEFAULT_X;y=DEFAULT_Y;
}
}
int *filled_lines=gamefield.FindFilledLines();
if (filled_lines){
gamefield.DelFilledLines(filled_lines);
gamefield.NormalizeLines(filled_lines);
}
gamefield.CreateShowField(mergeme);
protox=x;
window2D.Draw(gamefield);
while(SDL_PollEvent(&event_handle)!=0){
if (event_handle.type==SDL_QUIT){
quit=true;
break;
}
if(event_handle.type==SDL_KEYDOWN)
switch(event_handle.key.keysym.sym){
case SDLK_LEFT:
x--;
break;
case SDLK_RIGHT:
x++;
break;
case SDLK_DOWN:
y++;
break;
case SDLK_UP:
myshape.Rotate();
break;
default:
break;
}
}
}
return 0;
}
| [
"pelikenmag@gmail.com"
] | pelikenmag@gmail.com |
05b37699a4808e786a867a58d6833c6554d5df4b | ffd9e6bb9e3ceb48f07ad48a9ea5f7816a9db7c0 | /src/primitives/block.h | 9fa1861fe64e638a86067166244d0a49b3a478c6 | [
"MIT"
] | permissive | weigun/MagnaChain-dev-master | 0a26a48cbd617b4a6e2bc610d27b779d4022e18b | a7587b10072cca03a6c7a6a44cba1b6f2a202af6 | refs/heads/master | 2020-05-01T16:21:32.855483 | 2019-03-23T06:42:01 | 2019-03-23T06:42:01 | 175,793,168 | 0 | 0 | MIT | 2019-03-15T09:50:45 | 2019-03-15T09:50:42 | null | UTF-8 | C++ | false | false | 4,601 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Copyright (c) 2016-2019 The MagnaChain Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef MAGNACHAIN_PRIMITIVES_BLOCK_H
#define MAGNACHAIN_PRIMITIVES_BLOCK_H
#include "primitives/transaction.h"
#include "io/serialize.h"
#include "coding/uint256.h"
const int MAX_GROUP_NUM = 16;
/** Nodes collect new transactions into a block, hash them into a hash tree,
* and scan through nonce values to make the block's hash satisfy proof-of-work
* requirements. When they solve the proof-of-work, they broadcast the block
* to everyone and the block is added to the block chain. The first transaction
* in the block is a special one that creates a new coin owned by the creator
* of the block.
*/
class MCBlockHeader
{
public:
// header
int32_t nVersion;
uint256 hashPrevBlock;
uint256 hashMerkleRoot;
uint256 hashMerkleRootWithData;
uint256 hashMerkleRootWithPrevData;
uint32_t nTime;
uint32_t nBits;
uint32_t nNonce; // this value in bitcion are added for make different hash, we use to indicate the amount of miner's address
MCOutPoint prevoutStake;
MCScript vchBlockSig;
MCBlockHeader()
{
SetNull();
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(this->nVersion);
READWRITE(hashPrevBlock);
READWRITE(hashMerkleRoot);
READWRITE(hashMerkleRootWithData);
READWRITE(hashMerkleRootWithPrevData);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
READWRITE(prevoutStake);
if (!(s.GetType() & SER_WITHOUT_SIGN))
READWRITE(vchBlockSig);
}
void SetNull()
{
nVersion = 0;
hashPrevBlock.SetNull();
hashMerkleRoot.SetNull();
hashMerkleRootWithData.SetNull();
hashMerkleRootWithPrevData.SetNull();
nTime = 0;
nBits = 0;
nNonce = 0;
vchBlockSig.clear();
prevoutStake.SetNull();
}
bool IsNull() const
{
return (nBits == 0);
}
uint256 GetHash() const;
uint256 GetHashNoSignData() const;
int64_t GetBlockTime() const
{
return (int64_t)nTime;
}
};
class MCBlock : public MCBlockHeader
{
public:
// network and disk
std::vector<MCTransactionRef> vtx;
std::vector<uint16_t> groupSize;
std::vector<ContractPrevData> prevContractData;
// memory only
mutable bool fChecked;
MCBlock()
{
SetNull();
}
MCBlock(const MCBlockHeader &header)
{
SetNull();
*((MCBlockHeader*)this) = header;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(*(MCBlockHeader*)this);
READWRITE(vtx);
READWRITE(groupSize);
READWRITE(prevContractData);
}
void SetNull()
{
MCBlockHeader::SetNull();
vtx.clear();
groupSize.clear();
prevContractData.clear();
fChecked = false;
}
MCBlockHeader GetBlockHeader() const
{
MCBlockHeader block;
block.nVersion = nVersion;
block.hashPrevBlock = hashPrevBlock;
block.hashMerkleRoot = hashMerkleRoot;
block.hashMerkleRootWithData = hashMerkleRootWithData;
block.hashMerkleRootWithPrevData = hashMerkleRootWithPrevData;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
return block;
}
};
/** Describes a place in the block chain to another node such that if the
* other node doesn't have the same branch, it can find a recent common trunk.
* The further back it is, the further before the fork it may be.
*/
struct MCBlockLocator
{
std::vector<uint256> vHave;
MCBlockLocator() {}
MCBlockLocator(const std::vector<uint256>& vHaveIn) : vHave(vHaveIn) {}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
int nVersion = s.GetVersion();
if (!(s.GetType() & SER_GETHASH))
READWRITE(nVersion);
READWRITE(vHave);
}
void SetNull()
{
vHave.clear();
}
bool IsNull() const
{
return vHave.empty();
}
};
#endif // MAGNACHAIN_PRIMITIVES_BLOCK_H
| [
"weigun@weigun.com"
] | weigun@weigun.com |
26e9b32a0ac602db8e05eda995c6c0f156ce56bc | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/squid/hunk_7122.cpp | 991bdd2b94171fb3b70dab6a4f627fa1a9a37504 | [] | no_license | ccdxc/logSurvey | eaf28e9c2d6307140b17986d5c05106d1fd8e943 | 6b80226e1667c1e0760ab39160893ee19b0e9fb1 | refs/heads/master | 2022-01-07T21:31:55.446839 | 2018-04-21T14:12:43 | 2018-04-21T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 573 | cpp | {
*var = 0;
}
-
+
+static void
+dump_size_t(size_t var)
+{
+ printf("%d bytes", (int) var);
+}
+
+static void
+dump_kb_size_t(size_t var)
+{
+ printf("%d KB", (int) var);
+}
+
+static void
+parse_size_t(size_t *var)
+{
+ parseBytesLine(var, B_BYTES_STR);
+}
+
+static void
+parse_kb_size_t(size_t *var)
+{
+ parseBytesLine(var, B_KBYTES_STR);
+}
+
+static void
+free_size_t(size_t *var)
+{
+ *var = 0;
+}
+
+#define free_kb_size_t free_size_t
+#define free_mb_size_t free_size_t
+#define free_gb_size_t free_size_t
static void
dump_ushort(u_short var)
| [
"993273596@qq.com"
] | 993273596@qq.com |
60ba4e52aa3bb3c4f4a26f8e64dec172f8aca84b | e116d3e1069e483cd60cd2c56765b16cb0c875b0 | /addons/cirkit-addon-reversible/src/cli/commands/lpqx.hpp | 237335ca9725629464d486dc3d76221658046010 | [
"MIT"
] | permissive | alexandrecrsilva/cirkit | 0be24a3157e32a2a44ce042a72ef02f774136fb0 | c88215ffb18c05ff9f56b9b99327834b34054f80 | refs/heads/master | 2020-04-07T09:57:32.149641 | 2018-11-18T03:01:54 | 2018-11-18T03:01:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,927 | hpp | /* CirKit: A circuit toolkit
* Copyright (C) 2009-2015 University of Bremen
* Copyright (C) 2015-2017 EPFL
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @file lpqx.hpp
*
* @brief Formulate the linear programming problem for a ibm qx architecture
*
* @author Alexandre++
* @2
*/
#ifndef CLI_LPQX_COMMAND_HPP
#define CLI_LPQX_COMMAND_HPP
#include <vector>
#include <cli/cirkit_command.hpp>
namespace cirkit
{
class lpqx_command : public cirkit_command
{
public:
lpqx_command( const environment::ptr& env );
log_opt_t log() const;
protected:
rules_t validity_rules() const;
bool execute();
private:
std::string filename;
unsigned int architecture = 4;
unsigned int version = 2;
};
}
#endif
// Local Variables:
// c-basic-offset: 2
// eval: (c-set-offset 'substatement-open 0)
// eval: (c-set-offset 'innamespace 0)
// End:
| [
"aamaralalmeida@gmail.com"
] | aamaralalmeida@gmail.com |
7651a777b05f3ac82a000c321349967ba31183bd | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/squid/gumtree/squid_old_hunk_59.cpp | 214eeec1bee6d6d331677f4aa003915e16dbebda | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 389 | cpp | {
announceInitiatorAbort(theLauncher); // propogate to the transaction
clearInitiator();
mustStop("initiator gone");
}
void Adaptation::Iterator::noteAdaptationQueryAbort(bool final)
{
debugs(93,5, HERE << "final: " << final << " plan: " << thePlan);
clearAdaptation(theLauncher);
updatePlan(false);
// can we replace the failed service (group-level bypass)?
| [
"993273596@qq.com"
] | 993273596@qq.com |
4e6e65085367f2ec055ce29f970ef74d52f007d3 | 5bccf2d2118008c0af6a51a92a042e967e4f2abe | /Support/Modules/GSRoot/Win32GDIPlusInterface.hpp | c0c959e80d8eca39799f2dbc44bbf0e4322f7707 | [
"Apache-2.0"
] | permissive | graphisoft-python/DGLib | fa42fadebedcd8daaddde1e6173bd8c33545041d | 66d8717eb4422b968444614ff1c0c6c1bf50d080 | refs/heads/master | 2020-06-13T21:38:18.089834 | 2020-06-12T07:27:54 | 2020-06-12T07:27:54 | 194,795,808 | 3 | 0 | Apache-2.0 | 2020-06-12T07:27:55 | 2019-07-02T05:45:00 | C++ | UTF-8 | C++ | false | false | 643 | hpp | // *****************************************************************************
// File: Win32GDIPlusInterface.hpp
//
// Description: Includes GDIPlus Headers
//
// Namespace: -
//
// Contact person: MM
//
// SG compatible
// *****************************************************************************
#if !defined (WIN32GDIPLUSINTERFACE_HPP)
#define WIN32GDIPLUSINTERFACE_HPP
#pragma once
// -- Includes -----------------------------------------------------------------
#include "Win32Interface.hpp"
#pragma warning (push)
#pragma warning (disable : 4995)
#include <oleidl.h>
#include <gdiplus.h>
#pragma warning (pop)
#endif
| [
"445212619@qqcom"
] | 445212619@qqcom |
e3651344e542830057edd500b615c6e7531ae04a | 9ab11e1e76fb7654ba1e247d035da873f4256d6a | /Sources/RainbowEngine/UI/include/UI/Widgets/InputFields/InputSingleScalar.h | ddbe95f3f502937f144e804b2adab42db6f632d5 | [] | no_license | Tekh-ops/RainbowEngine | f7e565ddcbdcab0e8fb663d8e51988b73895698f | 5d1dc91d15fc988d7eacdd23900d0d5c398d5f1b | refs/heads/master | 2023-04-03T13:55:10.200479 | 2021-04-01T15:14:48 | 2021-04-01T15:14:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,738 | h |
#pragma once
#include <Tools/Eventing/Event.h>
#include "UI/Widgets/DataWidget.h"
namespace UI::Widgets::InputFields
{
/**
* Input widget of generic type
*/
template <typename T>
class InputSingleScalar : public DataWidget<T>
{
static_assert(std::is_scalar<T>::value, "Invalid InputSingleScalar T (Scalar expected)");
public:
/**
* Constructor
* @param p_dataType
* @param p_defaultValue
* @param p_step
* @param p_fastStep
* @param p_label
* @param p_format
* @param p_selectAllOnClick
*/
InputSingleScalar
(
ImGuiDataType p_dataType,
T p_defaultValue,
T p_step,
T p_fastStep,
const std::string& p_label,
const std::string& p_format,
bool p_selectAllOnClick
) : DataWidget<T>(value), m_dataType(p_dataType), value(p_defaultValue), step(p_step), fastStep(p_fastStep), label(p_label), format(p_format), selectAllOnClick(p_selectAllOnClick) {}
protected:
void _Draw_Impl() override
{
T previousValue = value;
ImGuiInputTextFlags flags = ImGuiInputTextFlags_EnterReturnsTrue;
if (selectAllOnClick)
flags |= ImGuiInputTextFlags_AutoSelectAll;
bool enterPressed = ImGui::InputScalar((label + this->m_widgetID).c_str(), m_dataType, &value, step != 0.0f ? &step : nullptr, fastStep != 0.0f ? &fastStep : nullptr, format.c_str(), flags);
if (previousValue != value)
{
ContentChangedEvent.Invoke(value);
this->NotifyChange();
}
if (enterPressed)
EnterPressedEvent.Invoke(value);
}
public:
T value;
T step;
T fastStep;
std::string label;
std::string format;
bool selectAllOnClick;
Tools::Eventing::Event<T> ContentChangedEvent;
Tools::Eventing::Event<T> EnterPressedEvent;
private:
ImGuiDataType m_dataType;
};
} | [
"43663573+leoandtt@users.noreply.github.com"
] | 43663573+leoandtt@users.noreply.github.com |
3f15420462f9b715113b92dd8748ea6bfad71f4c | 87d9f453831f38ca5dc45b74f8b31cb8093b4da0 | /cppVersion/Maximum Subarray.cpp | 55857c7918256967b3d37cd970d070664d17df6c | [
"MIT"
] | permissive | ChinoMars/LeetCodeSolution | a46cb8ce4690164ca7988232bff726b8740542bd | 604fc5e387582ecec85d0431bbddb542af2b92fa | refs/heads/master | 2020-05-21T00:08:44.124489 | 2015-10-30T02:00:14 | 2015-10-30T02:00:14 | 35,195,112 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 395 | cpp | class Solution
{
public:
int maxSubArray(vector<int>& nums)
{
int len = nums.size();
int fnlsum = INT_MIN, tmpsum = 0;
for(int i = 0; i < len; ++i)
{
tmpsum = tmpsum>=0 ? tmpsum+nums[i] : nums[i];
fnlsum = max(fnlsum,tmpsum);
}
return fnlsum;
}
}; | [
"chinomask@gmail.com"
] | chinomask@gmail.com |
dbec0ae167e90e5023eac29a07e211765f2d5f3e | 9611083d0317ce148f7a007550118cfb347ac845 | /PROJECTS/2016_09_AQUAPHONEIA/Flowsensor_Thibodeau/arduino/old_versions/Aquaphoenia-Flowsensor-0.7/Aquaphoenia-Flowsensor-0.7.ino | 25618609df69484812733addd3d6a32daeaa5029 | [] | no_license | navid/TML-depo | 957f65bfbb9f62c5089ee5396437329f9868fb3e | 08e215db1bd7967de74d5f200a1e4f839cf8d7b9 | refs/heads/master | 2023-02-08T22:04:02.402584 | 2023-02-07T03:28:28 | 2023-02-07T03:28:28 | 45,488,866 | 3 | 4 | null | 2017-11-01T18:21:18 | 2015-11-03T19:02:47 | Max | UTF-8 | C++ | false | false | 2,741 | ino | //--------------------------------------
// DECLARING STUFF
//--------------------------------------
// Timer variables
int ONE_SECOND = 62500;
int TIME_DIV = 4;
//int RESET_COUNT = 65536 - (ONE_SECOND / TIME_DIV);
int RESET_COUNT = 49910; //4Hz
// Testing variables
volatile bool isr_flag = false;
volatile bool test_pin_val = 0;
int count = 0;
int test_pin = 7;
// Flow Sensor Variables
int num_sensors = 5;
volatile int flow_pin[5] = {2,3,4,5,6};
volatile int flow_pin_new_state[5] = {0,0,0,0,0};
volatile int flow_pin_old_state[5] = {0,0,0,0,0};
volatile int flow_pulse_count[5] = {0,0,0,0,0};
//======================================
// SETUP FUNCTION
//======================================
void setup()
{
cli(); //disable interrupts
// test pin setup
pinMode(test_pin,OUTPUT);
digitalWrite(test_pin,LOW);
// setup input pins
for (int p=0;p<num_sensors;p++)
{
pinMode(flow_pin[p],INPUT);
}
// initialize Timer1
TCCR1A = 0; // set entire TCCR1A register to 0
TCCR1B = 0; // set entire TCCR1B register to 0
// (as we do not know the initial values)
// enable Timer1 overflow interrupt:
TIMSK1 |= (1 << TOIE1);
// Preload with value 3036
//use 64886 for 100Hz
//use 64286 for 50 Hz
//use 34286 for 2 Hz
TCNT1=RESET_COUNT;
// Set CS10 bit so timer runs at clock speed: (no prescaling)
TCCR1B |= (1 << CS12); // Sets bit CS12 in TCCR1B
Serial.begin(9600);
Serial.print(0);
sei();
}
//======================================
// TIMER INTERRUPT
//======================================
//This is the timer overflow interrupt
//This is where we will determine the input pulse states
//and keep a count of the number of pulses
ISR(TIMER1_OVF_vect)
{
isr_flag = true;
test_pin_val = HIGH;
digitalWrite(test_pin,test_pin_val);
TCNT1=RESET_COUNT; // reload the timer preload
}
//======================================
// MAIN LOOP
//======================================
void loop()
{
//------this happens when the timer overflows
if (isr_flag == true)
{
for (int p=0;p<num_sensors;p++)
{
Serial.write(flow_pulse_count[p]);
flow_pulse_count[p] = 0;
isr_flag = false;
}
}
//-------this happens all the time as fast as possible
// poll each sensor input
for (int p=0;p<num_sensors;p++)
{
// read the input value
flow_pin_new_state[p] = digitalRead(flow_pin[p]);
//is it different? Looking for a rising edge
if ((flow_pin_new_state[p] == HIGH) && (flow_pin_old_state[p] == LOW))
{
flow_pulse_count[p] += TIME_DIV;
test_pin_val = LOW;
digitalWrite(test_pin,test_pin_val);
}
flow_pin_old_state[p] = flow_pin_new_state[p];
}
}
| [
"navid.nav@gmail.com"
] | navid.nav@gmail.com |
0880399f98ab642e3233fe261d9672cce48e07a3 | b7593b8540740813b210fbec7dca2fe1833d9594 | /Timer.h | 90e98d7ce37858f16c27f434a1d63b1fe27632f2 | [] | no_license | samrbutler/FeyndDiagram | 0193ffe450a5576a3985b49638d087f725e5ea86 | fefd0d991f55feae646bdae9a1f8178012fe8431 | refs/heads/master | 2023-03-10T21:13:09.221548 | 2021-02-17T16:16:09 | 2021-02-17T16:16:09 | 299,690,606 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 414 | h | #pragma once
#include <chrono>
#include <iostream>
#include <string>
class Timer
{
using clock_t = std::chrono::high_resolution_clock;
using second_t = std::chrono::duration<double, std::ratio<1> >;
std::chrono::time_point<clock_t> m_beg;
public:
Timer() : m_beg(clock_t::now()) {};
void reset() { m_beg = clock_t::now(); }
double elapsed() const;
void lap(std::string prefix = "Time elapsed: ");
}; | [
"sam.r.butler@outlook.com"
] | sam.r.butler@outlook.com |
06e81d526f954c6efc67d218631b48b633e80ab1 | 329bf38920ae26cf6699a659d0a875b43cd4764e | /STM8L101F3P6/utils/queue/queue.cpp | ee50db313f29bb51ce231e75e1bb044bb3121a25 | [] | no_license | amitandgithub/STM8L101F3_FW | ae012d6417ca1c11bbab66734529f7fbe07b4957 | 787e802665b199f2183fc8fad19b4189661f613e | refs/heads/master | 2022-01-23T00:12:38.080393 | 2021-12-25T04:42:02 | 2021-12-25T04:42:02 | 199,318,490 | 0 | 0 | null | 2019-09-06T04:57:37 | 2019-07-28T17:39:52 | C | UTF-8 | C++ | false | false | 2,218 | cpp | /******************
** FILE: queue.c
**
** DESCRIPTION:
** queue implementation
**
** CREATED: 8/5/2019, by Amit Chaudhary
******************/
#include"queue.hpp"
queue::Queue_Status_t queue::QueueInit(Queue_t* pQueue)
{
if(pQueue)
{
pQueue->WriteHead = pQueue->Capacity - 1; // rear
pQueue->ReadHead = 0; // front
return QUEUE_OK;
}
return QUEUE_INVALID_PARAMS;
}
queue::Queue_Status_t queue::QueueFull(Queue_t* pQueue)
{
if(pQueue == 0)
return QUEUE_INVALID_PARAMS;
if(pQueue->Size == pQueue->Capacity)
return QUEUE_FULL;
else
return QUEUE_OK;
}
queue::Queue_Status_t queue::QueueEmpty(Queue_t* pQueue)
{
if(pQueue == 0)
return QUEUE_INVALID_PARAMS;
if(pQueue->Size == 0)
return QUEUE_EMPTY;
else
return QUEUE_OK;
}
queue::Queue_Status_t queue::AvailableEnteries(Queue_t* pQueue, QueueSize_t* pAvailableData)
{
if(pQueue == 0)
return QUEUE_INVALID_PARAMS;
*pAvailableData = pQueue->Size;
return QUEUE_OK;
}
/**
* Enqueue/Insert an element to the queue.
*/
queue::Queue_Status_t queue::QueueWrite(Queue_t* pQueue,QueueSize_t data)
{
Queue_Status_t status;
status = QueueFull(pQueue);
if (status != QUEUE_OK)
{
return status;
}
pQueue->WriteHead += 1;// (pQueue->WriteHead + 1) % CAPACITY;
if(pQueue->WriteHead == pQueue->Capacity)
pQueue->WriteHead = 0;
// Increment queue size
pQueue->Size++;
// Enqueue new element to queue
pQueue->Buf[pQueue->WriteHead] = data;
// Successfully enqueued element to queue
return QUEUE_OK;
}
/**
* Dequeue/Remove an element from the queue.
*/
queue::Queue_Status_t queue::QueueRead(Queue_t* pQueue, QueueSize_t* pdata)
{
Queue_Status_t status;
status = QueueEmpty(pQueue);
// Queue is empty, throw Queue underflow error
if (status != QUEUE_OK)
{
return status;
}
// Dequeue element from queue
*pdata = pQueue->Buf[pQueue->ReadHead];
// Ensure front never crosses array bounds
pQueue->ReadHead +=1;// (front + 1) % CAPACITY;
if(pQueue->ReadHead == pQueue->Capacity)
pQueue->ReadHead = 0;
// Decrease queue size
pQueue->Size--;
return QUEUE_OK;
}
| [
"amit4u.com@gmail.com"
] | amit4u.com@gmail.com |
185c576c41ae5ab485510ba6776760d6ef6ddf5a | ae99db8a12c4e22a6e844100144babc5f452a152 | /DSA/Leetcode/121.cc | dfd64d9e69b72d5ec468427340e3af15e6f4cf23 | [
"MIT"
] | permissive | zhmz90/Lan | 6d7591344029b80e16c39b41cddce500bcf32418 | d7bb1b38ecb5a082276efaafdadca8d9700fbc27 | refs/heads/master | 2021-01-21T12:53:58.281744 | 2017-07-21T11:54:45 | 2017-07-21T11:54:45 | 48,616,087 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,359 | cc | /** 121. Best Time to Buy and Sell Stock
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0
In this case, no transaction is done, i.e. max profit = 0.
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int maxProfit(vector<int>& prices) {
int buy=0,sell=0;
if (prices.size() <= 1) return 0;
buy = prices[0], sell = buy;
vector<int> profits{};
for (auto iter=prices.begin()+1,end=prices.end(); iter!=end; iter++){
if (*iter < buy) {
profits.push_back(sell-buy);
buy = *iter;
sell = *iter;
}
if (*iter > sell) sell = *iter;
}
profits.push_back(sell-buy);
// for (auto p: profits) cout<<p<<" "; cout<<endl;
return *max_element(profits.begin(),profits.end());
}
};
int main(){
Solution solu;
vector<int> prices{7,1,5,3,6,4};
for (auto p: prices) cout<<p<<" "; cout<<endl;
cout<<solu.maxProfit(prices)<<endl;
return 0;
}
| [
"zhmz90@gmail.com"
] | zhmz90@gmail.com |
638b97491d2610206cf1d2496e9cf939e7468971 | adfcd15da351a38af5713ea4e138160e1744bc1e | /src/Pool.h | 0f93b6fd913b5d3d93a66a0301c0508420eb9e42 | [
"BSD-2-Clause"
] | permissive | natecollins/vecs | 05ea013a89d4c6a3a5a76bec288212ba797dbc4c | b003b8f856acd20c8d02cfea89baed119b8cd794 | refs/heads/master | 2020-03-23T01:24:48.192243 | 2018-07-14T04:30:55 | 2018-07-14T04:30:55 | 140,915,974 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,793 | h | #ifndef POOL_H_
#define POOL_H_
#include <cstdint>
#include <cstdlib>
#include <deque>
#include <vector>
#include <tuple>
#include <atomic>
#include "entdef.h"
namespace vecs
{
class Pool {
friend class Domain;
private:
// Spinlock for allocations/de-allocations
std::atomic_flag spinlock;
// Assignment allocation size; e.g. 32
const std::size_t block_size;
// Allocation chunk size; e.g. 65536
const std::size_t chunk_size;
// Allocated chunks
std::vector<char*> chunks;
// Freed Blocks availability
std::vector<char*> blocks;
// Top of stack
char* top;
public:
Pool(std::size_t block_size, std::size_t chunk_size=65536);
virtual ~Pool();
void lock();
void unlock();
std::size_t getChunkSize() const;
std::size_t getBlocksPerChunk() const;
std::size_t getBlockSize() const;
std::size_t getCurrentBlockMax() const;
/**
* Allocate more memory chunks
*/
void reserve(std::size_t chunk_count=1, bool bypass_lock=false);
template<typename T>
T* allocate();
template<typename T>
void release(T* ptr);
};
template<typename T>
T* Pool::allocate() {
void* mem = nullptr;
lock();
if (blocks.size() != 0) {
mem = (void*)blocks.back();
blocks.pop_back();
}
else {
if ((top + block_size) > (chunks.back() + chunk_size)) {
reserve(1, true);
top = chunks.back();
}
mem = (void*)top;
top += block_size;
}
unlock();
return static_cast<T*>(mem);
}
template<typename T>
void Pool::release(T *ptr) {
// Call Component virtual deconstructor
ptr->~T();
// Mark memory as available
lock();
blocks.push_back( (char*)ptr );
unlock();
}
}
#endif // POOL_H_
| [
"npcollins@gmail.com"
] | npcollins@gmail.com |
a2a99dd1230df8b2d1eccc32b8378a5b8b3fcd28 | 684c9beb8bd972daeabe5278583195b9e652c0c5 | /src/cobalt/script/mozjs-45/mozjs_data_view.h | 64b0228616e65a49904c4b2918d13a13f8b1bf06 | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | elgamar/cobalt-clone | a7d4e62630218f0d593fa74208456dd376059304 | 8a7c8792318a721e24f358c0403229570da8402b | refs/heads/master | 2022-11-27T11:30:31.314891 | 2018-10-26T15:54:41 | 2018-10-26T15:55:22 | 159,339,577 | 2 | 4 | null | 2022-11-17T01:03:37 | 2018-11-27T13:27:44 | C++ | UTF-8 | C++ | false | false | 4,203 | h | // Copyright 2018 The Cobalt Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef COBALT_SCRIPT_MOZJS_45_MOZJS_DATA_VIEW_H_
#define COBALT_SCRIPT_MOZJS_45_MOZJS_DATA_VIEW_H_
#include "base/logging.h"
#include "cobalt/script/data_view.h"
#include "cobalt/script/mozjs-45/mozjs_array_buffer.h"
#include "cobalt/script/mozjs-45/mozjs_user_object_holder.h"
#include "cobalt/script/mozjs-45/type_traits.h"
#include "cobalt/script/mozjs-45/weak_heap_object.h"
#include "third_party/mozjs-45/js/src/jsapi.h"
#include "third_party/mozjs-45/js/src/jsfriendapi.h"
namespace cobalt {
namespace script {
namespace mozjs {
class MozjsDataView final : public DataView {
public:
using BaseType = DataView;
MozjsDataView(JSContext* context, JS::HandleValue value)
: context_(context), weak_heap_object_(context, value) {
DCHECK(value.isObject());
DCHECK(JS_IsDataViewObject(&value.toObject()));
}
JSObject* handle() const { return weak_heap_object_.GetObject(); }
const JS::Value& value() const { return weak_heap_object_.GetValue(); }
bool WasCollected() const { return weak_heap_object_.WasCollected(); }
void Trace(JSTracer* js_tracer) { weak_heap_object_.Trace(js_tracer); }
Handle<ArrayBuffer> Buffer() const override {
JSAutoRequest auto_request(context_);
JS::RootedObject array_buffer_view(context_, weak_heap_object_.GetObject());
bool is_shared_memory;
JSObject* object = JS_GetArrayBufferViewBuffer(context_, array_buffer_view,
&is_shared_memory);
JS::RootedValue value(context_);
value.setObject(*object);
return Handle<ArrayBuffer>(
new MozjsUserObjectHolder<MozjsArrayBuffer>(context_, value));
}
size_t ByteOffset() const override {
return JS_GetDataViewByteOffset(weak_heap_object_.GetObject());
}
size_t ByteLength() const override {
return JS_GetDataViewByteLength(weak_heap_object_.GetObject());
}
void* RawData() const override {
JS::AutoCheckCannotGC no_gc;
return JS_GetDataViewData(weak_heap_object_.GetObject(), no_gc);
}
protected:
JSContext* context_;
WeakHeapObject weak_heap_object_;
};
template <>
struct TypeTraits<DataView> {
using ConversionType = MozjsUserObjectHolder<MozjsDataView>;
using ReturnType = const ScriptValue<DataView>*;
};
inline void ToJSValue(JSContext* context,
const ScriptValue<DataView>* array_buffer_view_value,
JS::MutableHandleValue out_value) {
TRACK_MEMORY_SCOPE("Javascript");
if (!array_buffer_view_value) {
out_value.set(JS::NullValue());
return;
}
const auto* mozjs_array_buffer_view_value =
base::polymorphic_downcast<const MozjsUserObjectHolder<MozjsDataView>*>(
array_buffer_view_value);
out_value.setObject(*mozjs_array_buffer_view_value->js_object());
}
inline void FromJSValue(
JSContext* context, JS::HandleValue value, int conversion_flags,
ExceptionState* exception_state,
MozjsUserObjectHolder<MozjsDataView>* out_array_buffer_view) {
TRACK_MEMORY_SCOPE("Javascript");
DCHECK_EQ(0, conversion_flags);
DCHECK(out_array_buffer_view);
if (!value.isObject()) {
exception_state->SetSimpleException(kNotObjectType);
return;
}
if (!JS_IsDataViewObject(&value.toObject())) {
exception_state->SetSimpleException(kTypeError,
"Expected object of type DataView");
return;
}
*out_array_buffer_view = MozjsUserObjectHolder<MozjsDataView>(context, value);
}
} // namespace mozjs
} // namespace script
} // namespace cobalt
#endif // COBALT_SCRIPT_MOZJS_45_MOZJS_DATA_VIEW_H_
| [
"aabtop@google.com"
] | aabtop@google.com |
f2ba86b536158bc9c8d8f1536468b0dcddc82612 | 4eb4242f67eb54c601885461bac58b648d91d561 | /algorithm/poj/2337/code.cc | 83707f4d5504837a6677c71b0068c72b069ca86e | [] | no_license | biebipan/coding | 630c873ecedc43a9a8698c0f51e26efb536dabd1 | 7709df7e979f2deb5401d835d0e3b119a7cd88d8 | refs/heads/master | 2022-01-06T18:52:00.969411 | 2018-07-18T04:30:02 | 2018-07-18T04:30:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,088 | cc | // Copyright 2013 Jike Inc. All Rights Reserved.
// Author: Liqiang Guo(guoliqiang@jike.com)
// I just want to GH to hss~
// Date : 2013-11-13 19:10:49
// File : code.cc
// Brief :
/*
* 单词作为边,节点是26个字符,这样的构图才是可以用
* 欧拉路来做的
* Accepted 424K 47MS
* */
#include "base/public/common_ojhead.h"
namespace algorithm {
const int MAXN = 30;
const int MAXM = 1010;
const int N = MAXN;
int M = 0;
int begin = 0;
struct Edge {
int v;
int visited;
std::string str;
bool operator < (const Edge & e2) const {
return str < e2.str;
}
};
std::vector<Edge> head[MAXN];
int in[MAXN];
int out[MAXN];
int root[MAXN];
int used[MAXN];
std::stack<std::string> stack;
int find(int k) {
if (root[k] == k) return root[k];
return root[k] = find(root[k]);
}
void unit(int x, int y) {
int tx = find(x);
int ty = find(y);
root[tx] = root[ty];
}
bool Connect() {
int cnt = 0;
for (int i = 0; i < N; i++) {
if (used[i] && find(i) == i) cnt++;
}
return cnt == 1 ? true : false;
}
bool Key(int & key) {
int in_num = 0;
int out_num = 0;
for (int i = 0; i < N; i++) {
if (used[i]) {
if (in[i] == out[i]) continue;
else if (in[i] - out[i] == 1) in_num++;
else if (out[i] - in[i] == 1) {
out_num++;
key = i;
} else {
return false;
}
}
}
if (in_num == 1 && out_num == 1) return true;
else if (in_num == 0 && out_num == 0) {
for (int i = 0; i < N; i++) {
if (used[i]) {
key = i;
break;
}
}
return true;
} else {
return false;
}
}
// NB
void Fleury(int key) {
for (int i = 0; i < head[key].size(); i++) {
if (head[key][i].visited == 0) {
head[key][i].visited = 1;
Fleury(head[key][i].v);
stack.push(head[key][i].str);
}
}
}
void Path() {
printf("%s", stack.top().c_str());
stack.pop();
while(!stack.empty()) {
printf(".%s", stack.top().c_str());
stack.pop();
}
printf("\n");
}
void Read() {
int c = 0;
scanf("%d", &c);
getchar();
for (int i = 0; i < c; i++) {
int n = 0;
scanf("%d", &n);
getchar();
char temp[25];
memset(in, 0, sizeof(in));
memset(out, 0, sizeof(out));
memset(used, 0, sizeof(used));
for (int i = 0; i < N; i++) {
root[i] = i;
head[i].clear();
}
for (int j = 0; j < n; j++) {
scanf("%s", temp);
getchar();
int len = strlen(temp);
int u = temp[0] - 'a';
int v = temp[len - 1] - 'a';
Edge t;
t.v = v;
t.visited = 0;
t.str = std::string(temp);
head[u].push_back(t);
unit(v, u);
in[v]++;
out[u]++;
used[u] = used[v] = 1;
}
for (int i = 0; i < N; i++) {
if (used[i]) std::sort(head[i].begin(), head[i].end());
}
int key = 0;
if (!Connect() || !Key(key)) {
printf("***\n");
} else {
Fleury(key);
Path();
}
}
}
} // namespace algorithm
using namespace algorithm;
int main(int argc, char** argv) {
FROMFILE;
Read();
return 0;
}
| [
"guoliqiang2006@126.com"
] | guoliqiang2006@126.com |
1271239ec4b48ba565f775e79b0b2770cd71f835 | bc3b19735701983322449ad28281971f5e6a9c6d | /Player.h | c41c50c547c71bd5573de292ea2b6aa844ffbb4f | [] | no_license | ykh09242/TileGame | 5553dd490321ab33c64b71d8c0a1b5d277156087 | 5f1cdd966659cbd8d87f0b5e3a1b9a893d99634f | refs/heads/master | 2020-03-21T21:51:43.327512 | 2018-07-03T08:28:47 | 2018-07-03T08:28:47 | 138,686,034 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 214 | h | #pragma once
class Player
{
public:
string shape;
Vector2 pos;
int move;
bool turnEnd;
private:
bool item;
public:
Player(string shape, Vector2 startPos, int move = 1);
public:
void Moving(Map* map);
};
| [
"phk09242@gmail.com"
] | phk09242@gmail.com |
c687408876c520061be8235999944711d40863c6 | 308f3cb8a30fcacd8851cc2ed979949b643cf1d9 | /bzoj__orzliyicheng/p1237.cpp | 9a552c45fea54165cab3c3206e0ace5591729bc0 | [] | no_license | szh-bash/ACM | 9a49859644d077bcb40f90dbac33d88649e7b0f3 | 3ddab1ab8f9b8a066f012f2978ee9519d00aec54 | refs/heads/master | 2022-08-08T19:20:09.912359 | 2022-07-20T10:43:57 | 2022-07-20T10:43:57 | 98,170,219 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 889 | cpp | #include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const ll inf=10000000000009LL;
#define abs(x) (((x)<0)?(-(x)):(x))
#define A(x,y) ((x==y)?inf:abs((x)-(y)))
ll n,a[100005],b[100005],f[100005];
char buf[2000000],*p=buf;
inline int getint(){
ll r=0; while(*p<'0'||*p>'9')p++; while(*p>='0'&&*p<='9')r=r*10+*p++-48;return r;
}int main(){
fread(p,1,2000000,stdin);
n=getint(); for(ll i=1;i<=n;i++)a[i]=getint(),b[i]=getint();
sort(a+1,a+n+1); sort(b+1,b+n+1);
f[1]=A(a[1],b[1]); f[2]=min(f[1]+A(a[2],b[2]),A(a[1],b[2])+A(a[2],b[1]));
for(ll i=3;i<=n;i++)f[i]=min(f[i-1]+A(a[i],b[i]),min(f[i-2]+A(a[i-1],b[i])+A(a[i],b[i-1]),min(f[i-3]+A(a[i],b[i-1])+A(a[i-1],b[i-2])+A(a[i-2],b[i]),f[i-3]+A(a[i],b[i-2])+A(a[i-1],b[i])+A(a[i-2],b[i-1]))));
printf("%lld\n",f[n]==inf?-1LL:f[n]); return 0;
}
| [
"342333349@qq.com"
] | 342333349@qq.com |
cea0d5569a18a621c0adca0c86705e137e5e9aec | e0548caf7bd8153f8d991b7d7c1bed487402f0bc | /semestr-5/Algorytmy i struktury danych 1/PRO/programy-z-cwiczen/2019/C07/ID03P06/C07_ID03P06_0001/include/TabInt01.h | d35ed144317ad8076de84fd129371b57ff7ed087 | [] | no_license | Ch3shireDev/WIT-Zajecia | 58d9ca03617ba07bd25ce439aeeca79533f0bcb6 | 3cd4f7dea6abdf7126c44a1d856ca5b6002813ca | refs/heads/master | 2023-09-01T11:32:12.636305 | 2023-08-28T16:48:03 | 2023-08-28T16:48:03 | 224,985,239 | 19 | 24 | null | 2023-07-02T20:54:18 | 2019-11-30T08:57:27 | C | UTF-8 | C++ | false | false | 758 | h | #ifndef TABINT01_H
#define TABINT01_H
///213.135.46.21:7070
///\\sz240\temp\PRO
#include <iostream>
#include<ctime>
using std::cout;
using std::cin;
using std::string;
using std::endl;
using std::to_string;
using std::ostream;
///**********************************
///**********************************
class TabInt01{
public:
TabInt01(int=0);
TabInt01(const TabInt01&);
TabInt01& operator=(const TabInt01&);
~TabInt01();
int Length();
int* PT();
int& Value(int);
int& operator[](int);
private:
int sT;
int *pT;
friend ostream& operator<<(ostream&, TabInt01&);
};
///**********************************
#endif // TABINT01_H
| [
"thesmilingcatofcheshire@gmail.com"
] | thesmilingcatofcheshire@gmail.com |
2b085414a8218ce467d66ee7369032148ade9b2f | e1923c6dbede9cf6cca4c95346a2e0544e1d8c12 | /src/main.cpp | 6d081f4c7b2eb9c3c2ced72eb9ee5ad6ae0c1213 | [] | no_license | TolimanStaR/Ex09 | 8015ac669fa8f4fa3520ee2f75a708d690617d57 | 0ef19457137799c4f0ee7a5fb751dfa7c41ccd2b | refs/heads/main | 2023-02-11T17:04:20.500084 | 2021-01-13T20:20:08 | 2021-01-13T20:20:08 | 328,803,915 | 0 | 0 | null | 2021-01-11T22:09:56 | 2021-01-11T22:09:56 | null | UTF-8 | C++ | false | false | 233 | cpp | // Copyright 2021 Toliman
#include "../include/MyStack.h"
signed main() {
MyStack<int> s(3);
s.push(1);
s.push(3);
MyStack<int> t(3);
t.push(8924389);
t.push(89489);
MyStack<int> u(t);
return 0;
}
| [
"dadyryaev@edu.hse.ru"
] | dadyryaev@edu.hse.ru |
3806098444e7b001fa171d3d3fe45ebcafe5df26 | 68843a3957f49255aa0aacd7dc99a541a38e3c72 | /STEP1/Scene.h | 298f4f4e3589fe19d7707b49f0903546f2d58dc8 | [] | no_license | gamorejon/cell-ray | 61fec3e9c7df7146c77ce76ef0cd0df984709208 | 8f567f6c3741cf75d4bb2a0d67b53c0b050cfc6b | refs/heads/master | 2021-01-19T12:12:34.567177 | 2012-08-10T21:47:16 | 2012-08-10T21:47:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,139 | h | #ifndef SCENE_H
#define SCENE_H
#include <vector>
#include <cmath>
using namespace std;
#include <altivec.h>
#include "SceneObject.h"
#include "ColorGroup.h"
#include "Intersection.h"
#include "Light.h"
#include "AltivecUtils.h"
#include "VectorSInt.h"
class Scene
{
private:
SceneObject** objects;
Light** lights;
ColorGroup* ambientColor;
int objectsSize;
int lightsSize;
VertexGroup* lightV;
VertexGroup* reflectionStart;
VertexGroup* centers;
VectorSInt* minIndexVec;
ColorGroup* surfaceColorGroup;
vector float getSpec(int index)
{
if (index == -1)
{
return negativeZero();
}
else
{
return getSceneObject(index)->getSpecularReflection();
}
}
vector float getPt(int index, int number)
{
if (index == -1)
{
return negativeZero();
}
else
{
VertexGroup* center = getSceneObject(index)->getCenter();
switch (number)
{
case 1:
return center->x;
case 2:
return center->y;
case 3:
return center->z;
default:
return negativeZero();
}
}
}
vector float getDiff(int index, int number)
{
if (index == -1)
{
return negativeZero();
}
else
{
ColorGroup* diff = getSceneObject(index)->getDiffusionColor();
switch (number)
{
case 1:
return diff->r;
case 2:
return diff->g;
case 3:
return diff->b;
default:
return negativeZero();
}
}
}
public:
Scene(Light** _lights, int _lightsSize, SceneObject** _objects,
int _objectsSize, Color* _ambientColor)
{
lights = _lights;
lightsSize = _lightsSize;
objects = _objects;
objectsSize = _objectsSize;
ambientColor = new ColorGroup(*_ambientColor);
Color zero = Color();
surfaceColorGroup = new ColorGroup(zero);
lightV = new VertexGroup(Vertex());
reflectionStart = new VertexGroup(Vertex());
centers = new VertexGroup(Vertex());
minIndexVec = new VectorSInt();
delete _ambientColor;
}
~Scene()
{
/* cout << "Beginning scene delete" << endl;
for (int i = 0; i < objectsSize; i++)
{
cout << "Deleting object " << i << endl;
// delete objects[i];
cout << "Deleted object " << i << endl;
}
for (int i = 0; i < lightsSize; i++)
{
cout << "Deleting light " << i << endl;
// delete lights[i];
}
cout << "Deleting[] objects" << endl;
delete[] objects;
delete[] lights;
delete ambientColor;
cout << "After ambientColor" << endl;
delete lightV;
delete reflectionStart;
delete centers;
delete minIndexVec;
delete surfaceColorGroup;
cout << "End scene delete" << endl;*/
}
SceneObject* getSceneObject(int index)
{
return objects[index];
}
Light* getLight(int index)
{
return lights[index];
}
int getSceneObjectsSize()
{
return objectsSize;
}
int getLightsSize()
{
return lightsSize;
}
void getIntersection(Ray* ray, Intersection& intersection)
{
vector float distance = negativeZero();
vector int minIndex = vec_splat_s32(-1);
vector float minDistance = splatScalar(1000.0f);
vector unsigned int boolZero = vec_splat_u32(0);
vector bool int anyHit = (vector bool int)boolZero;
SceneObject* object;
// TODO: keeping the SceneObject is Sphere specific, and not good.
for (int i = 0; i < getSceneObjectsSize(); i++)
{
object = getSceneObject(i);
vector bool int hit = object->isIntersected(ray,
reflectionStart, intersection.hit);
if (vec_all_eq(hit, boolZero))
{
continue;
}
anyHit = vec_or(hit, anyHit);
distance = vec_and(ray->start->distance2(*reflectionStart), hit);
vector bool int distCmp = vec_and(vec_cmplt(distance,
minDistance), hit);
vector int iSplat = splatScalar(i);
minIndex = vec_sel(minIndex, iSplat, distCmp);
minDistance = vec_sel(minDistance, distance, distCmp);
VertexGroup* refStart = intersection.reflection->start;
refStart->x = vec_sel(refStart->x, reflectionStart->x, distCmp);
refStart->y = vec_sel(refStart->y, reflectionStart->y, distCmp);
refStart->z = vec_sel(refStart->z, reflectionStart->z, distCmp);
}
intersection.hit = vec_and(anyHit, intersection.hit);
if (vec_any_gt(intersection.hit, boolZero))
{
minIndexVec->vec = minIndex;
intersection.minIndex = minIndexVec;
int m1 = minIndexVec->points[0];
int m2 = minIndexVec->points[1];
int m3 = minIndexVec->points[2];
int m4 = minIndexVec->points[3];
vector float _13x = vec_mergeh(getPt(m1, 1), getPt(m3, 1));
vector float _13y = vec_mergeh(getPt(m1, 2), getPt(m3, 2));
vector float _13z = vec_mergeh(getPt(m1, 3), getPt(m3, 3));
vector float _24x = vec_mergeh(getPt(m2, 1), getPt(m4, 1));
vector float _24y = vec_mergeh(getPt(m2, 2), getPt(m4, 2));
vector float _24z = vec_mergeh(getPt(m2, 3), getPt(m4, 3));
centers->x = vec_mergeh(_13x, _24x);
centers->y = vec_mergel(_13y, _24y);
centers->z = vec_mergeh(_13z, _24z);
object->getReflection(ray, intersection.reflection,
intersection.normal, centers);
}
}
ColorGroup* surfaceColor(Intersection &intersection)
{
surfaceColorGroup->zero();
for (int i = 0; i < getLightsSize(); i++)
{
Light* light = getLight(i);
updateSurfaceColor(*surfaceColorGroup, light, intersection);
}
return surfaceColorGroup;
}
void updateSurfaceColor(ColorGroup& surfaceColor, Light* light,
Intersection& intersection)
{
VectorSInt* minIndex = intersection.minIndex;
VertexGroup* pos = light->pos;
VertexGroup* start = intersection.reflection->start;
lightV->x = vec_sub(pos->x, start->x);
lightV->y = vec_sub(pos->y, start->y);
lightV->z = vec_sub(pos->z, start->z);
lightV->normalize();
/* Ray lightRay;
Intersection lightIntersection;
lightRay.start->copy(*intersection.reflection->start);
lightRay.direction->copy(*lightV);
getIntersection(&lightRay, lightIntersection);
vector bool int lightObstructed =
vec_nor(lightIntersection.hit, lightIntersection.hit);
if (vec_all_ne(lightIntersection.hit, boolZero()))
{
return;
}*/
vector float negZero = negativeZero();
vector float epsilon = vectorEpsilon();
vector float intensityDiffusion = lightV->dot(*intersection.normal);
if (vec_all_lt(intensityDiffusion, epsilon))
{
// the light and the normal are perpindicular - or worse (?)
return;
}
vector bool int intenseGtZero = vec_cmpgt(intensityDiffusion, epsilon);
vector float ldot = lightV->dot(*intersection.reflection->direction);
vector bool int ldotGtZero = vec_cmpgt(ldot, negativeZero());
vector float intensityReflection = vec_and(pow(ldot,
light->shininess), ldotGtZero);
int m1 = minIndex->points[0];
int m2 = minIndex->points[1];
int m3 = minIndex->points[2];
int m4 = minIndex->points[3];
vector float spec = vec_mergeh(vec_mergeh(getSpec(m1), getSpec(m3)),
vec_mergeh(getSpec(m2), getSpec(m4)));
vector float specResult = vec_madd(intensityReflection,
spec, negZero);
vector float _13r = vec_mergeh(getDiff(m1, 1), getDiff(m3, 1));
vector float _13g = vec_mergeh(getDiff(m1, 2), getDiff(m3, 2));
vector float _13b = vec_mergeh(getDiff(m1, 3), getDiff(m3, 3));
vector float _24r = vec_mergeh(getDiff(m2, 1), getDiff(m4, 1));
vector float _24g = vec_mergeh(getDiff(m2, 2), getDiff(m4, 2));
vector float _24b = vec_mergeh(getDiff(m2, 3), getDiff(m4, 3));
surfaceColor.r = vec_add(vec_and(vec_madd(intensityDiffusion,
vec_madd(vec_mergeh(_13r, _24r), light->rgb->r, negZero),
specResult), intenseGtZero), surfaceColor.r);
surfaceColor.g = vec_add(vec_and(vec_madd(intensityDiffusion,
vec_madd(vec_mergeh(_13g, _24g), light->rgb->g, negZero),
specResult), intenseGtZero), surfaceColor.g);
surfaceColor.b = vec_add(vec_and(vec_madd(intensityDiffusion,
vec_madd(vec_mergeh(_13b, _24b), light->rgb->b, negZero),
specResult), intenseGtZero), surfaceColor.b);
}
ColorGroup* getAmbientColor()
{
return ambientColor;
}
};
#endif
| [
"gamorejon@gmail.com"
] | gamorejon@gmail.com |
8d60a08a5aafdba0384cff343d51e3d838ac3426 | 99143df5e2ef15f8f9b7e90c320a61ce93a1ffe8 | /Burgh/StatDisplay.h | 2fc5f386b9c0a964d2788107856f446490bbb03b | [] | no_license | MrGodin/IceCaves | af55f600cc70277d3b3332b3844966e2f7ec155d | ee6aafc60170b329329ae7918746dfb235610fda | refs/heads/master | 2020-05-30T17:48:44.221679 | 2015-08-11T20:16:53 | 2015-08-11T20:16:53 | 40,512,793 | 0 | 0 | null | 2015-08-11T20:16:53 | 2015-08-11T00:30:06 | C++ | UTF-8 | C++ | false | false | 1,464 | h |
#pragma once
#include "GuiFrame.h"
#include "GuiTextControl.h"
class StatDisplay : public GuiFrame
{
private:
protected:
GuiText* pFps = NULL;
GuiText* pWorldPos = NULL;
public:
StatDisplay(GuiFrameDesc desc)
:
GuiFrame(desc)
{
}
~StatDisplay()
{
SAFE_DELETE(pFps);
SAFE_DELETE(pWorldPos);
}
void Update(float fps,Vec2F pos)
{
TString str = "Fps: ";
str += TString(fps);
pFps->SetText(str.w_char());
str = "Player Pos X :(";
str += TString(pos.x);
str += TString(") - Y :(");
str += TString(pos.y);
str += TString(")");
pWorldPos->SetText(str.w_char());
}
virtual HRESULT Rasterize()override
{
DrawFrame();
pFps->Rasterize();
pWorldPos->Rasterize();
return S_OK;
}
void Create()
{
GuiFrameDesc fpsDesc;
fpsDesc.originX = frameDesc.originX + 16;
fpsDesc.originY = frameDesc.originY + 16;
pFps = new GuiText(fpsDesc, "What", TEXTALIGN_LEFT);
pFps->SetColor(Color(255, 0, 255, 0));
pFps->SetFont(pFont);
pFps->AlignText();
fpsDesc.originX = frameDesc.originX + 16;
fpsDesc.originY = fpsDesc.originY + 18;
pWorldPos = new GuiText(fpsDesc, "What", TEXTALIGN_LEFT);
pWorldPos->SetColor(Color(255, 0, 255, 0));
pWorldPos->SetFont(pFont);
pWorldPos->AlignText();
}
void Resize(long x, long y, long w, long h)
{
frameDesc.originX = x;
frameDesc.originY = y;
frameDesc.width = w;
frameDesc.height = h;
Init();
SAFE_DELETE(pFps);
SAFE_DELETE(pWorldPos);
Create();
}
}; | [
"benwold@telus.net"
] | benwold@telus.net |
f77d99738b9417fca4e9bc674fe5a49d6db9eb81 | 5898d3bd9e4cb58043b40fa58961c7452182db08 | /part4/ch30/30-4-3-5-error_code-mapping/src/my_future_errc.h | bc8df3b4eb69405a5fc5257af02893748e32cead | [] | no_license | sasaki-seiji/ProgrammingLanguageCPP4th | 1e802f3cb15fc2ac51fa70403b95f52878223cff | 2f686b385b485c27068328c6533926903b253687 | refs/heads/master | 2020-04-04T06:10:32.942026 | 2017-08-10T11:35:08 | 2017-08-10T11:35:08 | 53,772,682 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 718 | h | /*
* my_future_errc.h
*
* Created on: 2017/08/06
* Author: sasaki
*/
#ifndef MY_FUTURE_ERRC_H_
#define MY_FUTURE_ERRC_H_
#include <system_error>
#include <string>
using namespace std;
enum class my_future_errc {
broken_promise = 1,
future_already_retrieved,
promise_already_satisfied,
no_state
};
class my_future_cat : public error_category {
public:
const char* name() const noexcept override { return "future"; }
string message(int ec) const override;
};
const error_category& my_future_category() noexcept;
error_code make_error_code(my_future_errc e) noexcept;
namespace std {
template<>
struct is_error_code_enum<my_future_errc> : public true_type { };
}
#endif /* MY_FUTURE_ERRC_H_ */
| [
"sasaki-seiji@msj.biglobe.ne.jp"
] | sasaki-seiji@msj.biglobe.ne.jp |
dbd100284e494eb7106787771442f8c1b84a2ebc | c4979d123ddfd01c3a4251b1d84fd4797684242d | /src/business/management_server/actions/server_list_request_action.h | 0668d4e3c718fa84ff5ca928a70b4e3f59559b30 | [] | no_license | evandropoa/open-carom3d-server | e9a3aedae46610ea062e3a19e785779b13cfdc6e | 9c3d5af8cb9e79c4650f85607d47d9afa0be3f50 | refs/heads/master | 2022-11-07T06:29:12.170550 | 2020-06-09T06:29:46 | 2020-06-09T06:29:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 547 | h | //
// Created by CGR on 15/05/2020.
//
#ifndef __OPEN_CAROM3D_SERVER_SERVER_LIST_REQUEST_H__
#define __OPEN_CAROM3D_SERVER_SERVER_LIST_REQUEST_H__
#include <business/util/abstract_action.h>
namespace business { namespace management {
class ServerListRequestAction : public AbstractAction<void> {
public:
bool validate(const ActionData &action) override { return true; }
void execute(const ActionData &action, User &user, const void *unused) override;
};
}}
#endif //__OPEN_CAROM3D_SERVER_SERVER_LIST_REQUEST_H__
| [
"cesargreche@gmail.com"
] | cesargreche@gmail.com |
5c796659b9b0dc8b7115a2dad76cc117339d68c5 | de984a13290408a3dc42fecdbf65a04c3bc4ccb5 | /shadowmapping-master/ShaderDefault.cpp | 2fd024625ac9de8f10106d853f20db4bc2b4dc8e | [] | no_license | HerrAndersson/3DProject | d39e5243bcb49b896bf3a30955b9479772ca94fc | 7c5254cd3987d53243284d92c382bcbd2129ee5b | refs/heads/master | 2021-01-21T03:29:49.108644 | 2016-04-28T22:45:14 | 2016-04-28T22:45:14 | 57,338,388 | 0 | 0 | null | 2016-04-28T22:43:25 | 2016-04-28T22:43:23 | null | UTF-8 | C++ | false | false | 3,723 | cpp | #include "ShaderDefault.h"
using namespace DirectX;
using namespace std;
ShaderDefault::ShaderDefault(ID3D11Device* device,
LPCWSTR vertexShaderFilename,
LPCWSTR pixelShaderFilename
) : ShaderBase(device)
{
D3D11_INPUT_ELEMENT_DESC inputDesc[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 20, D3D11_INPUT_PER_VERTEX_DATA, 0 }
};
CreateMandatoryShaders(device, vertexShaderFilename, pixelShaderFilename, inputDesc, ARRAYSIZE(inputDesc));
D3D11_BUFFER_DESC matrixBufferDesc;
HRESULT hr;
//Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
matrixBufferDesc.ByteWidth = sizeof(MatrixBuffer);
matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
matrixBufferDesc.MiscFlags = 0;
matrixBufferDesc.StructureByteStride = 0;
//Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
hr = device->CreateBuffer(&matrixBufferDesc, NULL, &matrixBuffer);
if (FAILED(hr))
{
throw std::runtime_error("Shader default matrix buffer failed");
}
//Create texture sampler
D3D11_SAMPLER_DESC samplerDesc;
ZeroMemory(&samplerDesc, sizeof(D3D11_SAMPLER_DESC));
samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_BORDER;
samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_BORDER;
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_BORDER;
samplerDesc.BorderColor[0] = 1.0f;
samplerDesc.BorderColor[1] = 1.0f;
samplerDesc.BorderColor[2] = 1.0f;
samplerDesc.BorderColor[3] = 1.0f;
samplerDesc.MinLOD = 0.f;
samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
samplerDesc.MipLODBias = 0.f;
samplerDesc.MaxAnisotropy = 0;
samplerDesc.ComparisonFunc = D3D11_COMPARISON_LESS_EQUAL;
samplerDesc.Filter = D3D11_FILTER_COMPARISON_MIN_MAG_MIP_POINT;
hr = device->CreateSamplerState(&samplerDesc, &samplerState);
if (FAILED(hr))
{
throw std::runtime_error("Shader default sampler failed");
}
}
ShaderDefault::~ShaderDefault()
{
matrixBuffer->Release();
samplerState->Release();
}
void ShaderDefault::UseShader(ID3D11DeviceContext* deviceContext)
{
deviceContext->VSSetShader(vertexShader, nullptr, 0);
deviceContext->HSSetShader(hullShader, nullptr, 0);
deviceContext->DSSetShader(domainShader, nullptr, 0);
deviceContext->GSSetShader(geometryShader, nullptr, 0);
deviceContext->PSSetShader(pixelShader, nullptr, 0);
deviceContext->PSSetSamplers(0, 1, &samplerState);
}
void ShaderDefault::SetBuffers(ID3D11DeviceContext* deviceContext, XMMATRIX& worldMatrix, XMMATRIX& viewMatrix, XMMATRIX& projectionMatrix, XMMATRIX& lightVP)
{
HRESULT hr;
D3D11_MAPPED_SUBRESOURCE mappedResource;
XMMATRIX wm = XMMatrixTranspose(worldMatrix);
XMMATRIX vm = XMMatrixTranspose(viewMatrix);
XMMATRIX pm = XMMatrixTranspose(projectionMatrix);
XMMATRIX lvp = XMMatrixTranspose(lightVP);
hr = deviceContext->Map(matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
MatrixBuffer* matrixDataBuffer = (MatrixBuffer*)mappedResource.pData;
//Copy the matrices into the constant buffer.
matrixDataBuffer->world = wm;
matrixDataBuffer->view = vm;
matrixDataBuffer->projection = pm;
matrixDataBuffer->lightVP = lvp;
deviceContext->Unmap(matrixBuffer, 0);
int bufferNumber = 0;
deviceContext->VSSetConstantBuffers(bufferNumber, 1, &matrixBuffer);
deviceContext->IASetInputLayout(inputLayout);
}
void* ShaderDefault::operator new(size_t i)
{
return _mm_malloc(i, 16);
}
void ShaderDefault::operator delete(void* p)
{
_mm_free(p);
}
| [
"anderssonjonas94@gmail.com"
] | anderssonjonas94@gmail.com |
845e398f5a8050062ee9de1415d037caf0c5fa41 | c76bca6811a24c4434209bcc0d5736118886e88c | /week8/assignment/Main.cpp | cfc28219387a49af89b199dc4a8106ce0f116684 | [] | no_license | Ellard24/CS162 | bb2c161f844beef11d2306839144854679d2a481 | 8335e6b9c700f467763bf1b230102db3e9b57539 | refs/heads/master | 2021-01-10T17:13:29.458696 | 2016-03-17T17:20:07 | 2016-03-17T17:20:07 | 54,130,981 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,796 | cpp | /*****************************************************************************************************
**Author: Ellard Gerritsen van der Hoop
**Description: This program will ask users to input what fighters they want to put against each other.
** The program will then create these fighters with appropriate stats and put them through
** a combat scenario. Winners stay in the LineUp and losers get moved to the LoserPile.
**Input: All input is taken during runtime
**Output: Displays all actions regarding combat between the fighters to the screen. Displays score and winners as well.
*****************************************************************************************/
#include "Creature.h"
#include "Barbarian.h"
#include "Blue.h"
#include "Goblin.h"
#include "Reptile.h"
#include "Shadow.h"
#include "Game.h"
#include <time.h>
#include <iostream>
#include "Queue.h"
#include "Stack.h"
using namespace std;
void display(Queue &q, int size);
void combat1(Queue &p1, Queue &p2, Stack &sp1, int &total1, int &total2, Combat &game1);
/******************************************************************
**Function: Main
**Description: Sets time seed, initializes options, creates Game, and then
calls other functions that handle the combat. Queue and Stack
is also made that allows fighters to be moved to corresponding
struct
**Parameters: -
**Pre-Conditions:-
**Post-Conditions: Fighters will be created and pitted against each other
********************************************************************/
int main()
{
srand(time(0));
cout << "This program pits a variety of creatures against each other in a Fantasy Combat Game" << endl;
cout << "Two players will have the option to pick their LineUp and then battle it out" << endl;
cout << "Player 1 will decide the size of the LineUp and then both players can pick from 5 monsters" << endl;
cout << endl;
cout << endl;
int lineSize = 0;
int totalP1 = 0;
int totalP2 = 0;
cout << "Player1: Please decide the size of the LineUp" << endl;
cin >> lineSize;
Queue p1LineUp;
Queue p2LineUp;
Stack p1Loser;
Stack p2Loser;
Combat game;
cout << "Player 1 picks first" << endl;
display(p1LineUp, lineSize);
cout << "Player 2 now gets to pick" << endl;
display(p2LineUp, lineSize);
combat1(p1LineUp, p2LineUp, p1Loser, totalP1, totalP2, game);
cout << "Losing Pile" << endl;
p1Loser.display();
cout << endl;
//send rest of winning team to pile and then pick out last 3 to pick first, second , third place
if (p1LineUp.getSize() > 0)
{
while (p1LineUp.getSize() > 0)
{
p1Loser.addFighter(p1LineUp.returnFront());
p1LineUp.removeFighter();
}
}
if (p2LineUp.getSize() > 0)
{
while (p2LineUp.getSize() > 0)
{
p1Loser.addFighter(p2LineUp.returnFront());
p2LineUp.removeFighter();
}
}
//Deletes last 3 nodes from stack
cout << "First Place: " << endl;
cout << p1Loser.returnWinners();
cout << endl;
cout << "Second Place: " << endl;
cout << p1Loser.returnWinners();
cout << endl;
cout << "Third Place: " << endl;
cout << p1Loser.returnWinners();
cout << endl;
//Player 1 total score
cout << "Player 1's total score is " << totalP1 << endl;
//Player 2 total score
cout << "Player 2's total score is " << totalP2 << endl;
if (totalP1 > totalP2)
cout << "Player 1 wins" << endl;
else if (totalP2 > totalP1)
cout << "Player 2 wins" << endl;
else
cout << "Its a tie, which isnt possible" << endl;
return 0;
}
/******************************************************************
**Function: Display
**Description: Displays the instructions and lets user pick fighters
**Parameters: Queue &q, int size
**Pre-Conditions: Queue needs to exist, and size needs to be initialized
**Post-Conditions: Parameters are used to create fighters
********************************************************************/
void display(Queue &q, int size)
{
int count = size;
do
{
int selection = 0;
string displayName;
cout << "Select the fighter type that you want to add (" << count << " fighters remaining):" << endl;
cout << "1. Barbarian" << endl;
cout << "2. BlueMen" << endl;
cout << "3. Reptile Men" << endl;
cout << "4. Goblin" << endl;
cout << "5. The Shadow" << endl;
cout << "Selection: " << endl;
cin >> selection;
if (selection > 0 && selection < 6)
{
if (selection == 1)
{
q.addFighter(new Barbarian);
q.display();
cout << endl;
}
if (selection == 2)
{
q.addFighter(new Blue);
q.display();
cout << endl;
}
if (selection == 3)
{
q.addFighter(new Reptile);
q.display();
cout << endl;
}
if (selection == 4)
{
q.addFighter(new Goblin);
q.display();
cout << endl;
}
if (selection == 5)
{
q.addFighter(new Shadow);
q.display();
cout << endl;
}
count--;
}
} while (count > 0);
}
/**********************************************************
**Function: combat1
**Description: Takes care of the combat. Moves fighters to appropriate
struct based on performance. Keeps track of score
**Parameters: Queue &p1, Queue &p2, Stack &sp1, int &total1, int &total2, Combat &game1
**Pre-Conditions: All Queues and Stack needs to be created, totals initialized, and game initialized
**Post-Conditions: Combat determines which player will win.
****************************************************************/
void combat1(Queue &p1, Queue &p2, Stack &sp1,int &total1, int &total2, Combat &game1)
{
while (p1.getSize() > 0 && p2.getSize() > 0)
{
game1.attack1(p1.returnFront(), p2.returnFront());
if (p1.returnFront()->getStrength() <= 0)
{
cout << p2.returnFront()->getName() << " wins this round" << endl;
sp1.addFighter(p1.returnFront());
p1.removeFighter();
cout << p2.returnFront()->getName() << " drinks a potion" << endl;
p2.returnFront()->drinkPotion();
p2.returnFront()->increaseScore();
total2++;
if (p2.getSize() > 1)
p2.moveBack();
}
else
{
cout << p1.returnFront()->getName() << " wins this round" << endl;
sp1.addFighter(p2.returnFront());
p2.removeFighter();
cout << p1.returnFront()->getName() << " drinks a potion" << endl;
p1.returnFront()->drinkPotion();
p1.returnFront()->increaseScore();
total1++;
if (p1.getSize() > 1)
p1.moveBack();
}
cout << "Do you want to see the current score? Type 'yes' if you want " << endl;
string scoreChoice;
cin >> scoreChoice;
if (scoreChoice == "yes")
{
cout << "Team One's Current Score: " << total1 << endl;
cout << "Team Two's Current Score: " << total2 << endl;
}
else
{
cout << "Next round is starting" << endl;
}
}
}
| [
"egvdh@comcast.net"
] | egvdh@comcast.net |
49d1263a08328d29d957c9eebdd1cdc9bdcce858 | aae79375bee5bbcaff765fc319a799f843b75bac | /atcoder/abc_146/c.cpp | fd9ace2d78b1d2116d12758ede9a195fdda288f5 | [] | no_license | firewood/topcoder | b50b6a709ea0f5d521c2c8870012940f7adc6b19 | 4ad02fc500bd63bc4b29750f97d4642eeab36079 | refs/heads/master | 2023-08-17T18:50:01.575463 | 2023-08-11T10:28:59 | 2023-08-11T10:28:59 | 1,628,606 | 21 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 571 | cpp | // C.
#include <iostream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <cmath>
using namespace std;
typedef long long LL;
int main(int argc, char* argv[]) {
cout.precision(20);
#ifdef _MSC_VER
while (true)
#endif
{
LL a, b, x = -1;
cin >> a >> b >> x;
if (x < 0) return 0;
LL left = 0, right = 1000000001LL;
while (right - left > 1) {
LL mid = (right + left) / 2;
LL cost = a * mid + b * to_string(mid).length();
if (cost > x) {
right = mid;
} else {
left = mid;
}
}
cout << left << endl;
}
return 0;
}
| [
"karamaki@gmail.com"
] | karamaki@gmail.com |
7219bf2a0c913ae407ae363b504d8f6ee6025afa | 5552798e3562cad0b615b6141f8ea33214bba861 | /C++/Codeforces/newyearpermu.cpp | fcb3ea8b95d3e153f8ca3ba46986d22498ea5867 | [] | no_license | YashSharma/C-files | 3922994cf7f0f5947173aa2b26a7dc399919267b | 3d7107e16c428ee056814b33ca9b89ab113b0753 | refs/heads/master | 2016-08-12T09:16:25.499792 | 2015-12-20T08:24:47 | 2015-12-20T08:24:47 | 48,312,664 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,817 | cpp | #include<iostream>
#include<stdio.h>
#include<algorithm>
using namespace std;
static int a[302][302];
bool visited[302]={0};
static int test[302];
static int position[302];
static int p[302];
int pos=0;
void tovisit(int n,int size)
{ int flag=0,i=n,j;
visited[i]=1;
for(j=0;j<size;j++)
{ if(visited[j]==0)
{ if(a[i][j]==1)
{ test[pos]=p[j];
position[pos++]=j;
tovisit(j,size);
}
}
}
}
int bfs(int size)
{ int i,j,flag=0;
sort(position,position+pos);
sort(test,test+pos);
for(i=0;i<pos;i++)
{ p[position[i]]=test[i];
}
for(i=0;i<size;i++)
{ if(!visited[i])
{ for(j=0;j<size;j++)
{ if(!visited[j])
{
if(a[i][j]==1)
{ pos=0;
test[pos]=p[i];
position[pos++]=i;
flag=1;
tovisit(i,size);
break;
}
}
}
if(flag)
return 1;
}
}
return 0;
}
int main()
{ int n,ret=1,i,j,flag=0;
char st[302];
scanf("%d",&n);
for(i=0;i<n;i++)
{ visited[i]=0;
}
for(i=0;i<n;i++)
{ scanf("%d",&p[i]);
}
for(i=0;i<n;i++)
{ cin>>st;
for(j=0;j<n;j++)
{ if(st[j]=='0')
a[i][j]=0;
else
a[i][j]=1;
}
}
for(i=0;i<n;i++)
{ for(j=0;j<n;j++)
{ if(a[i][j]==1)
{ test[pos]=p[i];
position[pos++]=i;
tovisit(i,n);
flag=1;
break;
}
}
if(flag)
break;
visited[i]=1;
}
while(ret)
{
ret=bfs(n);
}
for(i=0;i<n;i++)
{ printf("%d ",p[i]);
}
printf("\n");
return 0;
} | [
"Apple@Yash-MacBook-Air.local"
] | Apple@Yash-MacBook-Air.local |
da6d22d1fc4c47fc7bd7aed4c5dde096d9940929 | 3dbec36a6c62cad3e5c6ec767b13f4038baa5f79 | /cpp-lang/qt/quick/integratingqml/backend.h | 97c13707fa5e68b95fa22e9b37e7f8ab7a9cee83 | [] | no_license | reposhelf/playground | 50a2e54436e77e7e6cad3a44fd74c0acc22a553a | 47ddd204a05ec269e4816c2d45a13e5bc6d3e73a | refs/heads/master | 2022-04-22T13:50:24.222822 | 2020-04-10T15:59:30 | 2020-04-10T15:59:30 | 254,675,772 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 463 | h | #ifndef BACKEND_H
#define BACKEND_H
#include <QObject>
#include <QString>
class BackEnd : public QObject
{
Q_OBJECT
Q_PROPERTY(QString userName READ userName WRITE setUserName NOTIFY userNameChanged)
public:
explicit BackEnd(QObject *parent = nullptr);
QString userName() const { return m_userName; }
void setUserName(const QString &userName);
signals:
void userNameChanged();
private:
QString m_userName;
};
#endif // BACKEND_H
| [
"vladimironiuk@gmail.com"
] | vladimironiuk@gmail.com |
20dfa3809caa970f7b91ddf1dba3b03bbd6e3fb2 | cd7fdd7cca834eb7649973908b8ff7d40580e756 | /Plugins/AdvancedSessions/AdvancedSessions/Intermediate/Build/Win64/UE4/Inc/AdvancedSessions/AdvancedFriendsLibrary.generated.h | 5cdad9e936280f276994de7a57a446b75d39e811 | [
"MIT"
] | permissive | jackychew77/FYP | 09cb03ea326e7aed0ad190bd6f13a38153ff4095 | 4ba57241a1d960f6ff3cb40c375aeb29982efa0d | refs/heads/master | 2022-09-22T22:12:54.900880 | 2020-05-28T08:30:06 | 2020-05-28T08:30:06 | 206,222,682 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,575 | h | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/ObjectMacros.h"
#include "UObject/ScriptMacros.h"
PRAGMA_DISABLE_DEPRECATION_WARNINGS
class APlayerController;
struct FBPUniqueNetId;
struct FBPOnlineRecentPlayer;
struct FBPFriendInfo;
enum class EBlueprintResultSwitch : uint8;
#ifdef ADVANCEDSESSIONS_AdvancedFriendsLibrary_generated_h
#error "AdvancedFriendsLibrary.generated.h already included, missing '#pragma once' in AdvancedFriendsLibrary.h"
#endif
#define ADVANCEDSESSIONS_AdvancedFriendsLibrary_generated_h
#define LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_RPC_WRAPPERS \
\
DECLARE_FUNCTION(execIsAFriend) \
{ \
P_GET_OBJECT(APlayerController,Z_Param_PlayerController); \
P_GET_STRUCT(FBPUniqueNetId,Z_Param_UniqueNetId); \
P_GET_UBOOL_REF(Z_Param_Out_IsFriend); \
P_FINISH; \
P_NATIVE_BEGIN; \
UAdvancedFriendsLibrary::IsAFriend(Z_Param_PlayerController,Z_Param_UniqueNetId,Z_Param_Out_IsFriend); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execGetStoredRecentPlayersList) \
{ \
P_GET_STRUCT(FBPUniqueNetId,Z_Param_UniqueNetId); \
P_GET_TARRAY_REF(FBPOnlineRecentPlayer,Z_Param_Out_PlayersList); \
P_FINISH; \
P_NATIVE_BEGIN; \
UAdvancedFriendsLibrary::GetStoredRecentPlayersList(Z_Param_UniqueNetId,Z_Param_Out_PlayersList); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execGetStoredFriendsList) \
{ \
P_GET_OBJECT(APlayerController,Z_Param_PlayerController); \
P_GET_TARRAY_REF(FBPFriendInfo,Z_Param_Out_FriendsList); \
P_FINISH; \
P_NATIVE_BEGIN; \
UAdvancedFriendsLibrary::GetStoredFriendsList(Z_Param_PlayerController,Z_Param_Out_FriendsList); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execGetFriend) \
{ \
P_GET_OBJECT(APlayerController,Z_Param_PlayerController); \
P_GET_STRUCT(FBPUniqueNetId,Z_Param_FriendUniqueNetId); \
P_GET_STRUCT_REF(FBPFriendInfo,Z_Param_Out_Friend); \
P_FINISH; \
P_NATIVE_BEGIN; \
UAdvancedFriendsLibrary::GetFriend(Z_Param_PlayerController,Z_Param_FriendUniqueNetId,Z_Param_Out_Friend); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execSendSessionInviteToFriend) \
{ \
P_GET_OBJECT(APlayerController,Z_Param_PlayerController); \
P_GET_STRUCT_REF(FBPUniqueNetId,Z_Param_Out_FriendUniqueNetId); \
P_GET_ENUM_REF(EBlueprintResultSwitch,Z_Param_Out_Result); \
P_FINISH; \
P_NATIVE_BEGIN; \
UAdvancedFriendsLibrary::SendSessionInviteToFriend(Z_Param_PlayerController,Z_Param_Out_FriendUniqueNetId,(EBlueprintResultSwitch&)(Z_Param_Out_Result)); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execSendSessionInviteToFriends) \
{ \
P_GET_OBJECT(APlayerController,Z_Param_PlayerController); \
P_GET_TARRAY_REF(FBPUniqueNetId,Z_Param_Out_Friends); \
P_GET_ENUM_REF(EBlueprintResultSwitch,Z_Param_Out_Result); \
P_FINISH; \
P_NATIVE_BEGIN; \
UAdvancedFriendsLibrary::SendSessionInviteToFriends(Z_Param_PlayerController,Z_Param_Out_Friends,(EBlueprintResultSwitch&)(Z_Param_Out_Result)); \
P_NATIVE_END; \
}
#define LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_RPC_WRAPPERS_NO_PURE_DECLS \
\
DECLARE_FUNCTION(execIsAFriend) \
{ \
P_GET_OBJECT(APlayerController,Z_Param_PlayerController); \
P_GET_STRUCT(FBPUniqueNetId,Z_Param_UniqueNetId); \
P_GET_UBOOL_REF(Z_Param_Out_IsFriend); \
P_FINISH; \
P_NATIVE_BEGIN; \
UAdvancedFriendsLibrary::IsAFriend(Z_Param_PlayerController,Z_Param_UniqueNetId,Z_Param_Out_IsFriend); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execGetStoredRecentPlayersList) \
{ \
P_GET_STRUCT(FBPUniqueNetId,Z_Param_UniqueNetId); \
P_GET_TARRAY_REF(FBPOnlineRecentPlayer,Z_Param_Out_PlayersList); \
P_FINISH; \
P_NATIVE_BEGIN; \
UAdvancedFriendsLibrary::GetStoredRecentPlayersList(Z_Param_UniqueNetId,Z_Param_Out_PlayersList); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execGetStoredFriendsList) \
{ \
P_GET_OBJECT(APlayerController,Z_Param_PlayerController); \
P_GET_TARRAY_REF(FBPFriendInfo,Z_Param_Out_FriendsList); \
P_FINISH; \
P_NATIVE_BEGIN; \
UAdvancedFriendsLibrary::GetStoredFriendsList(Z_Param_PlayerController,Z_Param_Out_FriendsList); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execGetFriend) \
{ \
P_GET_OBJECT(APlayerController,Z_Param_PlayerController); \
P_GET_STRUCT(FBPUniqueNetId,Z_Param_FriendUniqueNetId); \
P_GET_STRUCT_REF(FBPFriendInfo,Z_Param_Out_Friend); \
P_FINISH; \
P_NATIVE_BEGIN; \
UAdvancedFriendsLibrary::GetFriend(Z_Param_PlayerController,Z_Param_FriendUniqueNetId,Z_Param_Out_Friend); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execSendSessionInviteToFriend) \
{ \
P_GET_OBJECT(APlayerController,Z_Param_PlayerController); \
P_GET_STRUCT_REF(FBPUniqueNetId,Z_Param_Out_FriendUniqueNetId); \
P_GET_ENUM_REF(EBlueprintResultSwitch,Z_Param_Out_Result); \
P_FINISH; \
P_NATIVE_BEGIN; \
UAdvancedFriendsLibrary::SendSessionInviteToFriend(Z_Param_PlayerController,Z_Param_Out_FriendUniqueNetId,(EBlueprintResultSwitch&)(Z_Param_Out_Result)); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execSendSessionInviteToFriends) \
{ \
P_GET_OBJECT(APlayerController,Z_Param_PlayerController); \
P_GET_TARRAY_REF(FBPUniqueNetId,Z_Param_Out_Friends); \
P_GET_ENUM_REF(EBlueprintResultSwitch,Z_Param_Out_Result); \
P_FINISH; \
P_NATIVE_BEGIN; \
UAdvancedFriendsLibrary::SendSessionInviteToFriends(Z_Param_PlayerController,Z_Param_Out_Friends,(EBlueprintResultSwitch&)(Z_Param_Out_Result)); \
P_NATIVE_END; \
}
#define LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_INCLASS_NO_PURE_DECLS \
private: \
static void StaticRegisterNativesUAdvancedFriendsLibrary(); \
friend struct Z_Construct_UClass_UAdvancedFriendsLibrary_Statics; \
public: \
DECLARE_CLASS(UAdvancedFriendsLibrary, UBlueprintFunctionLibrary, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/AdvancedSessions"), NO_API) \
DECLARE_SERIALIZER(UAdvancedFriendsLibrary)
#define LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_INCLASS \
private: \
static void StaticRegisterNativesUAdvancedFriendsLibrary(); \
friend struct Z_Construct_UClass_UAdvancedFriendsLibrary_Statics; \
public: \
DECLARE_CLASS(UAdvancedFriendsLibrary, UBlueprintFunctionLibrary, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/AdvancedSessions"), NO_API) \
DECLARE_SERIALIZER(UAdvancedFriendsLibrary)
#define LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_STANDARD_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API UAdvancedFriendsLibrary(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UAdvancedFriendsLibrary) \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UAdvancedFriendsLibrary); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UAdvancedFriendsLibrary); \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API UAdvancedFriendsLibrary(UAdvancedFriendsLibrary&&); \
NO_API UAdvancedFriendsLibrary(const UAdvancedFriendsLibrary&); \
public:
#define LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_ENHANCED_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API UAdvancedFriendsLibrary(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()) : Super(ObjectInitializer) { }; \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API UAdvancedFriendsLibrary(UAdvancedFriendsLibrary&&); \
NO_API UAdvancedFriendsLibrary(const UAdvancedFriendsLibrary&); \
public: \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UAdvancedFriendsLibrary); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UAdvancedFriendsLibrary); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UAdvancedFriendsLibrary)
#define LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_PRIVATE_PROPERTY_OFFSET
#define LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_25_PROLOG
#define LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_GENERATED_BODY_LEGACY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_PRIVATE_PROPERTY_OFFSET \
LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_RPC_WRAPPERS \
LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_INCLASS \
LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_STANDARD_CONSTRUCTORS \
public: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#define LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_GENERATED_BODY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_PRIVATE_PROPERTY_OFFSET \
LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_RPC_WRAPPERS_NO_PURE_DECLS \
LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_INCLASS_NO_PURE_DECLS \
LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h_28_ENHANCED_CONSTRUCTORS \
private: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
template<> ADVANCEDSESSIONS_API UClass* StaticClass<class UAdvancedFriendsLibrary>();
#undef CURRENT_FILE_ID
#define CURRENT_FILE_ID LostScroll_v1_0_Plugins_AdvancedSessions_AdvancedSessions_Source_AdvancedSessions_Classes_AdvancedFriendsLibrary_h
PRAGMA_ENABLE_DEPRECATION_WARNINGS
| [
"jacky_chew629@live.com.my"
] | jacky_chew629@live.com.my |
62f2c03046d409d07addc69ef2566f1d59190278 | 5f17573507d160aa087b02d0f00d97be7a603f6c | /319c.cpp | efe802d35c90df985aa1c2bf61c6c3d4fd686578 | [] | no_license | nishnik/Competitive-Programming | 33590ea882e449947befc36594fd20c720c05049 | cab12301ca7343b6e5f4464fcfbb84b437379da8 | refs/heads/master | 2021-01-10T05:43:44.252506 | 2016-02-23T14:14:03 | 2016-02-23T14:14:03 | 52,363,354 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,005 | cpp | #include <bits/stdc++.h>
//usage getline(cin,str_name);
#define rep(i, n) for(__typeof(n) i = 0; i < (n); i++)
#define rrep(i, n) for(__typeof(n) i = (n) - 1; i >= 0; --i)
#define rep1(i, n) for(__typeof(n) i = 1; i <= (n); i++)
#define FOR(i, a, b) for(__typeof(b) i = (a); i <= (b); i++)
#define forstl(i, s) for (__typeof ((s).end ()) i = (s).begin (); i != (s).end (); ++i)
#define all(a) a.begin(),a.end()
#define rall(a) a.rbegin(),a.rend()
#define ll long long
#define vi vector<int>
#define vvi vector<vi >
#define vl vector<long>
#define vvl vector<vl >
#define vll vector<long long>
#define vvll vector<vll >
#define mp make_pair
/*
Usage: Just create an instance of it at the start of the block of
which you want to measure running time. Reliable up to millisecond
scale. You don't need to do anything else, even works with freopen.
*/
class TimeTracker {
clock_t start, end;
public:
TimeTracker() {
start = clock();
}
~TimeTracker() {
end = clock();
//fprintf(stderr, "%.3lf s\n", (double)(end - start) / CLOCKS_PER_SEC);
}
};
using namespace std;
int main()
{
ios::sync_with_stdio(false);
int n;
cin>>n;
vector<int> arr(n+1,0);
int count=0;
for(int i=2;i<n+1;i++)
{
if(arr[i]==0)
{
int flag=-1;
for(int j=i-1;j>=2;j--)
{
/*if(i==16 && j==8)
cout<<"---"<<arr[j]<<
*/
if(i%j==0 && arr[j]!=1 && arr[i/j]==1 )
{
arr[j]=1;
flag=j;
break;
}
}
int q;
if(flag==-1)
{arr[i]=1;q=i;}
else
{q=flag;}
count++;
for(int j=i-1;j>=2;j--)
{
if(q*j<=n && arr[j]==1)
arr[q*j]=2;
}
}
}
cout<<count<<"\n";
for(int i=2;i<=n ;i++)
{
if(arr[i]==1)
cout<<i<<" ";
}
}
| [
"nishantiam@gmail.com"
] | nishantiam@gmail.com |
16152f2e9078375555eae45332d38bc7062b4de0 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/collectd/gumtree/collectd_repos_function_2399_collectd-5.6.3.cpp | a2e27d80cc1731941381a6c20d3e8c9945c6cf98 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 932 | cpp | int parse_identifier_vl(const char *str, value_list_t *vl) /* {{{ */
{
char str_copy[6 * DATA_MAX_NAME_LEN];
char *host = NULL;
char *plugin = NULL;
char *plugin_instance = NULL;
char *type = NULL;
char *type_instance = NULL;
int status;
if ((str == NULL) || (vl == NULL))
return (EINVAL);
sstrncpy(str_copy, str, sizeof(str_copy));
status = parse_identifier(str_copy, &host, &plugin, &plugin_instance, &type,
&type_instance);
if (status != 0)
return (status);
sstrncpy(vl->host, host, sizeof(vl->host));
sstrncpy(vl->plugin, plugin, sizeof(vl->plugin));
sstrncpy(vl->plugin_instance,
(plugin_instance != NULL) ? plugin_instance : "",
sizeof(vl->plugin_instance));
sstrncpy(vl->type, type, sizeof(vl->type));
sstrncpy(vl->type_instance, (type_instance != NULL) ? type_instance : "",
sizeof(vl->type_instance));
return (0);
} | [
"993273596@qq.com"
] | 993273596@qq.com |
4cdaa9370b5fb6d0b40ad7bbfeb3f246dc9ef91b | 16c6035c8b20b58937e527081ddeb10f508e9034 | /ros_ws/devel/include/piksi_rtk_msgs/ImuRawMulti.h | b703ad07c8ffe7ca6086169b170b00d7f24bdfcd | [
"MIT"
] | permissive | njoubert/tgdriver | 77d082ab9a6537327de74276eb81f8cba6ebb323 | e46ce6d89488116136a56805abfafe3b0d979ee1 | refs/heads/master | 2020-07-04T08:46:35.637633 | 2019-08-04T06:15:03 | 2019-08-04T06:15:03 | 192,004,866 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,186 | h | // Generated by gencpp from file piksi_rtk_msgs/ImuRawMulti.msg
// DO NOT EDIT!
#ifndef PIKSI_RTK_MSGS_MESSAGE_IMURAWMULTI_H
#define PIKSI_RTK_MSGS_MESSAGE_IMURAWMULTI_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
#include <std_msgs/Header.h>
namespace piksi_rtk_msgs
{
template <class ContainerAllocator>
struct ImuRawMulti_
{
typedef ImuRawMulti_<ContainerAllocator> Type;
ImuRawMulti_()
: header()
, tow(0)
, tow_f(0)
, acc_x(0)
, acc_y(0)
, acc_z(0)
, gyr_x(0)
, gyr_y(0)
, gyr_z(0) {
}
ImuRawMulti_(const ContainerAllocator& _alloc)
: header(_alloc)
, tow(0)
, tow_f(0)
, acc_x(0)
, acc_y(0)
, acc_z(0)
, gyr_x(0)
, gyr_y(0)
, gyr_z(0) {
(void)_alloc;
}
typedef ::std_msgs::Header_<ContainerAllocator> _header_type;
_header_type header;
typedef uint32_t _tow_type;
_tow_type tow;
typedef uint8_t _tow_f_type;
_tow_f_type tow_f;
typedef int16_t _acc_x_type;
_acc_x_type acc_x;
typedef int16_t _acc_y_type;
_acc_y_type acc_y;
typedef int16_t _acc_z_type;
_acc_z_type acc_z;
typedef int16_t _gyr_x_type;
_gyr_x_type gyr_x;
typedef int16_t _gyr_y_type;
_gyr_y_type gyr_y;
typedef int16_t _gyr_z_type;
_gyr_z_type gyr_z;
typedef boost::shared_ptr< ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator> const> ConstPtr;
}; // struct ImuRawMulti_
typedef ::piksi_rtk_msgs::ImuRawMulti_<std::allocator<void> > ImuRawMulti;
typedef boost::shared_ptr< ::piksi_rtk_msgs::ImuRawMulti > ImuRawMultiPtr;
typedef boost::shared_ptr< ::piksi_rtk_msgs::ImuRawMulti const> ImuRawMultiConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace piksi_rtk_msgs
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': True}
// {'sensor_msgs': ['/opt/ros/melodic/share/sensor_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/melodic/share/geometry_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/melodic/share/std_msgs/cmake/../msg'], 'piksi_rtk_msgs': ['/home/gecko/Code/tgdriver/ros_ws/src/ethz_piksi_ros/piksi_rtk_msgs/msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator> const>
: FalseType
{ };
template <class ContainerAllocator>
struct IsMessage< ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator> const>
: TrueType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator> >
{
static const char* value()
{
return "e32f07f6279690082bb3d37f42a5fc90";
}
static const char* value(const ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0xe32f07f627969008ULL;
static const uint64_t static_value2 = 0x2bb3d37f42a5fc90ULL;
};
template<class ContainerAllocator>
struct DataType< ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator> >
{
static const char* value()
{
return "piksi_rtk_msgs/ImuRawMulti";
}
static const char* value(const ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator> >
{
static const char* value()
{
return "# Raw data from the Inertial Measurement Unit, containing accelerometer and gyroscope readings.\n"
"\n"
"Header header\n"
"\n"
"uint32 tow # Milliseconds since start of GPS week. If the high bit is set, the time is unknown or invalid.\n"
"uint8 tow_f # Milliseconds since start of GPS week, fractional part.\n"
"int16 acc_x # Acceleration in the body frame X axis.\n"
"int16 acc_y # Acceleration in the body frame Y axis.\n"
"int16 acc_z # Acceleration in the body frame Z axis.\n"
"int16 gyr_x # Angular rate around the body frame X axis.\n"
"int16 gyr_y # Angular rate around the body frame Y axis.\n"
"int16 gyr_z # Angular rate around the body frame Z axis.\n"
"\n"
"================================================================================\n"
"MSG: std_msgs/Header\n"
"# Standard metadata for higher-level stamped data types.\n"
"# This is generally used to communicate timestamped data \n"
"# in a particular coordinate frame.\n"
"# \n"
"# sequence ID: consecutively increasing ID \n"
"uint32 seq\n"
"#Two-integer timestamp that is expressed as:\n"
"# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n"
"# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n"
"# time-handling sugar is provided by the client library\n"
"time stamp\n"
"#Frame this data is associated with\n"
"string frame_id\n"
;
}
static const char* value(const ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.header);
stream.next(m.tow);
stream.next(m.tow_f);
stream.next(m.acc_x);
stream.next(m.acc_y);
stream.next(m.acc_z);
stream.next(m.gyr_x);
stream.next(m.gyr_y);
stream.next(m.gyr_z);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct ImuRawMulti_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::piksi_rtk_msgs::ImuRawMulti_<ContainerAllocator>& v)
{
s << indent << "header: ";
s << std::endl;
Printer< ::std_msgs::Header_<ContainerAllocator> >::stream(s, indent + " ", v.header);
s << indent << "tow: ";
Printer<uint32_t>::stream(s, indent + " ", v.tow);
s << indent << "tow_f: ";
Printer<uint8_t>::stream(s, indent + " ", v.tow_f);
s << indent << "acc_x: ";
Printer<int16_t>::stream(s, indent + " ", v.acc_x);
s << indent << "acc_y: ";
Printer<int16_t>::stream(s, indent + " ", v.acc_y);
s << indent << "acc_z: ";
Printer<int16_t>::stream(s, indent + " ", v.acc_z);
s << indent << "gyr_x: ";
Printer<int16_t>::stream(s, indent + " ", v.gyr_x);
s << indent << "gyr_y: ";
Printer<int16_t>::stream(s, indent + " ", v.gyr_y);
s << indent << "gyr_z: ";
Printer<int16_t>::stream(s, indent + " ", v.gyr_z);
}
};
} // namespace message_operations
} // namespace ros
#endif // PIKSI_RTK_MSGS_MESSAGE_IMURAWMULTI_H
| [
"ottotechnogecko@gmail.com"
] | ottotechnogecko@gmail.com |
0e4b2a0a52ae40c1f56ea562c0f94d4041e84553 | 801f7ed77fb05b1a19df738ad7903c3e3b302692 | /refactoringOptimisation/differentiatedCAD/occt-min-topo-src/src/BRepAlgo/BRepAlgo_Tool.cxx | 8d2110caae2643d9b6070da561c56dbf30523c1a | [] | no_license | salvAuri/optimisationRefactoring | 9507bdb837cabe10099d9481bb10a7e65331aa9d | e39e19da548cb5b9c0885753fe2e3a306632d2ba | refs/heads/master | 2021-01-20T03:47:54.825311 | 2017-04-27T11:31:24 | 2017-04-27T11:31:24 | 89,588,404 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,850 | cxx | // Created on: 1995-10-23
// Created by: Yves FRICAUD
// Copyright (c) 1995-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.
#include <BRep_Builder.hxx>
#include <BRep_Tool.hxx>
#include <BRepAlgo_Tool.hxx>
#include <TopExp.hxx>
#include <TopoDS.hxx>
#include <TopoDS_Edge.hxx>
#include <TopoDS_Iterator.hxx>
#include <TopoDS_Shape.hxx>
#include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
#include <TopTools_ListOfShape.hxx>
//=======================================================================
//function : Deboucle3D
//purpose :
//=======================================================================
TopoDS_Shape BRepAlgo_Tool::Deboucle3D(const TopoDS_Shape& S,
const TopTools_MapOfShape& Boundary)
{
TopoDS_Shape SS;
switch ( S.ShapeType()) {
case TopAbs_FACE:
{
}
break;
case TopAbs_SHELL:
{
// if the shell contains free borders that do not belong to the
// free borders of caps ( Boundary) it is removed.
TopTools_IndexedDataMapOfShapeListOfShape Map;
TopExp::MapShapesAndAncestors(S,TopAbs_EDGE,TopAbs_FACE,Map);
Standard_Boolean JeGarde = Standard_True;
for ( Standard_Integer i = 1; i <= Map.Extent() && JeGarde; i++) {
if (Map(i).Extent() < 2) {
const TopoDS_Edge& anEdge = TopoDS::Edge(Map.FindKey(i));
if (!Boundary.Contains(anEdge) &&
!BRep_Tool::Degenerated(anEdge) )
JeGarde = Standard_False;
}
}
if ( JeGarde) SS = S;
}
break;
case TopAbs_COMPOUND:
case TopAbs_SOLID:
{
// iterate on sub-shapes and add non-empty.
TopoDS_Iterator it(S);
TopoDS_Shape SubShape;
Standard_Boolean NbSub = 0;
BRep_Builder B;
if (S.ShapeType() == TopAbs_COMPOUND) {
B.MakeCompound(TopoDS::Compound(SS));
}
else {
B.MakeSolid(TopoDS::Solid(SS));
}
for ( ; it.More(); it.Next()) {
const TopoDS_Shape& CurS = it.Value();
SubShape = Deboucle3D(CurS,Boundary);
if ( !SubShape.IsNull()) {
B.Add(SS, SubShape);
NbSub++;
}
}
if (NbSub == 0)
{
#ifdef OCCT_DEBUG
cout << "No subhape in shape!" << endl;
#endif
SS = TopoDS_Shape();
}
}
break;
default:
break;
}
return SS;
}
| [
"salvatore.auriemma@opencascade.com"
] | salvatore.auriemma@opencascade.com |
875d556f40fc399e6c1c5e0ad045babc620e15db | 42707f98a26a505aac0286e5e95a29d2f68646fa | /Array/Rotations/Pair in sorted and rotated array.cpp | 6e935427b19b9e6b5560c1132529c3948c0795de | [] | no_license | binarydevelop/GeeksforGeeks_Data-Structures | c323b5d070305ab30565bd775841640871c9c206 | 88b2352912017485ba88c2c7c9814efb5b2b52b8 | refs/heads/master | 2023-01-13T22:50:26.701023 | 2020-11-12T03:31:52 | 2020-11-12T03:31:52 | 266,951,840 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 999 | cpp | #include<iostream>
using namespace std;
bool pairInSortedRotated(int arr[], int n, int x)
{
// Find the pivot element
int i;
for (i=0; i<n-1; i++) // 18 here is the pivot as arr[i](68)>arr[i+1](18)
if (arr[i] > arr[i+1]) // 20 43 68 18
break;
int l = (i+1)%n; //mod n because if the value is less thhan n then it will return the same number else if it's greater than n then the remainder will be the result
int r = i;
while (l != r)
{
if (arr[l] + arr[r] == x)
return true;
// move to the higher sum
if (arr[l] + arr[r] < x)
l = (l + 1)%n;
else // Move to the lower sum side
r = (n + r - 1)%n; // we are adding n because once r gets to 0 it will go to negative indexes but when we add n and %n it is confirmed that it will be in range of 0 to n-1 and hence not going out of the bound;
}
return false;
} | [
"binarydevelop@gmail.com"
] | binarydevelop@gmail.com |
6b97bd0d6558c838bc2f760509df9b9e4320190f | ea86bc50922e5d96a78575e400aadaf7f888590e | /ds/chap3/decode_string/solu.cpp | 9d6d92eee0a7cfd929fcb80e2a6d619baa282ee2 | [] | no_license | EvergreenHZ/See-Let-Pointer-Fly | 527d5d6ae35fc26d298bc07dd921c53c3307d082 | 68c088995f1a8ea951b6144bdbd1a0923c0be90c | refs/heads/master | 2020-03-07T04:42:58.077212 | 2018-10-22T11:56:21 | 2018-10-22T11:56:21 | 127,274,299 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,715 | cpp | #include <string>
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
class Solution {
public:
string decodeString(string s) {
if (!isValid(s)) return "";
stack<string> _stack;
stack<int> _nstack;
string result;
string tmp;
int n=0;
for (int i=0; i<s.size(); i++) {
if ( isNum(s[i]) ) {
n = 0;
for(; isNum(s[i]); i++ ) {
n = n*10 + s[i] - '0';
}
}
if (s[i] == '[') {
tmp="";
_stack.push(tmp);
_nstack.push(n);
} else if (s[i] == ']') {
n = _nstack.top();
tmp="";
for (; n>0; n--) {
tmp += _stack.top(); // cat n times
}
_stack.pop();
_nstack.pop();
if ( ! _stack.empty() ) {
_stack.top() += tmp;
}else {
result += tmp;
}
} else {
if ( ! _stack.empty() ) { // collect chars
_stack.top() += s[i];
} else {
result += s[i]; // deal with char directly
}
}
}
return result;
}
private:
//only check the following rules:
// 1) the number must be followed by '['
// 2) the '[' and ']' must be matched.
bool isValid(string& s) {
stack<char> _stack;
for (int i=0; i<s.size(); i++) {
if ( isNum(s[i]) ) {
for(; isNum(s[i]); i++);
if (s[i] != '[') {
return false;
}
_stack.push('[');
continue;
} else if (s[i] == ']' ) {
if ( _stack.top() != '[' ) return false;
_stack.pop();
}
}
return (_stack.size() == 0);
}
bool isNum(char ch) {
return (ch>='0' && ch<='9');
}
};
int main()
{
Solution solu;
cout << solu.decodeString(string("3[a]2[bc]")) << endl; // 输出 aaabcbc
cout << solu.decodeString(string("3[a2[c]]")) << endl; // 输出 accaccacc
cout << solu.decodeString(string("2[abc]3[cd]ef")) << endl; // 输出 abcabccdcdcdef
}
| [
"huaizhixtp@163.com"
] | huaizhixtp@163.com |
2100826e4ac5369f09a0893aa300609afd0d9d03 | 93574cdfec6227131bda78ec7c2a687f7bb43edf | /c++/balanced-binary-tree.cpp | 0c3a50cee9f6131b85306f35db5688f2ffa18af4 | [] | no_license | fyang26/leetcode | 642cd051fe29fb26c8c24921c5fc1504554bbe67 | 2f7d2aa174a719d93bd42790f3c216f6f0173d5b | refs/heads/master | 2021-01-10T11:08:33.920393 | 2016-04-27T00:59:05 | 2016-04-27T00:59:05 | 43,520,536 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 618 | cpp | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
if (!root) return true;
int diff = abs(getdepth(root->left) - getdepth(root->right));
if (diff>1) return false;
else return isBalanced(root->left) && isBalanced(root->right);
}
int getdepth(TreeNode *root) {
if (!root) return 0;
return max(getdepth(root->left), getdepth(root->right)) + 1;
}
}; | [
"fyang@umiacs.umd.edu"
] | fyang@umiacs.umd.edu |
f295d6c4d31e87a46505c3bbe1f2dabcf80787ab | b76289396b22eda191f25744a600fac2abaf8850 | /third-party/fizz/src/fizz/protocol/BrotliCertificateCompressor.cpp | 9aeb6cb4c6d10a37b0b0b89543aeb60898e27b4c | [
"BSD-3-Clause",
"MIT",
"PHP-3.01",
"Zend-2.0"
] | permissive | fengjixuchui/hhvm | cb8cece7afd025fb8cdf8479c2a0696f38730949 | bbbb1782fa258b8dd526ffc7e8ba0f6115931bff | refs/heads/master | 2023-03-15T15:55:46.355422 | 2023-01-27T13:59:08 | 2023-01-27T13:59:08 | 175,142,159 | 0 | 1 | NOASSERTION | 2021-11-03T11:22:20 | 2019-03-12T05:34:16 | C++ | UTF-8 | C++ | false | false | 2,151 | cpp | /*
* Copyright (c) 2018-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <brotli/encode.h>
#include <fizz/protocol/BrotliCertificateCompressor.h>
using namespace folly;
namespace fizz {
BrotliCertificateCompressor::BrotliCertificateCompressor(
int compressLevel,
int windowSize)
: level_(compressLevel), windowSize_(windowSize) {}
BrotliCertificateCompressor::BrotliCertificateCompressor()
: level_(kDefaultCompressionLevel), windowSize_(kDefaultWindowSize) {}
CertificateCompressionAlgorithm BrotliCertificateCompressor::getAlgorithm()
const {
return CertificateCompressionAlgorithm::brotli;
}
namespace {
namespace brotli1 {
std::unique_ptr<IOBuf>
brotliCompressImpl(int level, int windowSize, folly::ByteRange input) {
size_t upperBound = ::BrotliEncoderMaxCompressedSize(input.size());
if (upperBound == 0) {
throw std::runtime_error(
"Failed to compress certificate: could not calculate upper bound");
}
size_t size = input.size();
auto compressed = IOBuf::create(upperBound);
if (!BrotliEncoderCompress(
level,
windowSize,
BROTLI_MODE_GENERIC,
input.size(),
input.data(),
&size,
compressed->writableTail())) {
throw std::runtime_error("Failed to compress certificate");
}
// |size|, if the BrotliEncoderCompress call succeeds, is modified to contain
// the compressed size.
compressed->append(size);
return compressed;
}
} // namespace brotli1
using brotli1::brotliCompressImpl;
} // namespace
CompressedCertificate BrotliCertificateCompressor::compress(
const CertificateMsg& cert) {
auto encoded = encode(cert);
auto encodedRange = encoded->coalesce();
auto compressedCert = brotliCompressImpl(level_, windowSize_, encodedRange);
CompressedCertificate cc;
cc.uncompressed_length = encodedRange.size();
cc.algorithm = getAlgorithm();
cc.compressed_certificate_message = std::move(compressedCert);
return cc;
}
} // namespace fizz
| [
"atry@fb.com"
] | atry@fb.com |
10ab0c981932fc9421d1b8118993572b0913b8fa | 64cb681c4430d699035e24bdc6e29019c72b0f94 | /renderdoc/driver/d3d8/d3d8_resources.cpp | 23fb32d1bb2a8cbe2bfff48418351fa004f8b524 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | new-TonyWang/renderdoc | ebd7d0e338b0e56164930915ebce4c0f411f2977 | ac9c37e2e9ba4b9ab6740c020e65681eceba45dd | refs/heads/v1.x | 2023-07-09T17:03:11.345913 | 2021-08-18T02:54:41 | 2021-08-18T02:54:41 | 379,597,382 | 0 | 0 | MIT | 2021-08-18T03:15:31 | 2021-06-23T12:35:00 | C++ | UTF-8 | C++ | false | false | 3,245 | cpp | /******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2019-2021 Baldur Karlsson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
#include "d3d8_resources.h"
#undef D3D8_TYPE_MACRO
#define D3D8_TYPE_MACRO(iface) WRAPPED_POOL_INST(CONCAT(Wrapped, iface));
ALL_D3D8_TYPES;
std::map<ResourceId, WrappedIDirect3DVertexBuffer8::BufferEntry>
WrappedD3DBuffer8<IDirect3DVertexBuffer8, D3DVERTEXBUFFER_DESC>::m_BufferList;
std::map<ResourceId, WrappedIDirect3DIndexBuffer8::BufferEntry>
WrappedD3DBuffer8<IDirect3DIndexBuffer8, D3DINDEXBUFFER_DESC>::m_BufferList;
D3D8ResourceType IdentifyTypeByPtr(IUnknown *ptr)
{
if(ptr == NULL)
return Resource_Unknown;
#undef D3D8_TYPE_MACRO
#define D3D8_TYPE_MACRO(iface) \
if(UnwrapHelper<iface>::IsAlloc(ptr)) \
return UnwrapHelper<iface>::GetTypeEnum();
ALL_D3D8_TYPES;
RDCERR("Unknown type for ptr 0x%p", ptr);
return Resource_Unknown;
}
TrackedResource8 *GetTracked(IUnknown *ptr)
{
if(ptr == NULL)
return NULL;
#undef D3D8_TYPE_MACRO
#define D3D8_TYPE_MACRO(iface) \
if(UnwrapHelper<iface>::IsAlloc(ptr)) \
return (TrackedResource8 *)GetWrapped((iface *)ptr);
ALL_D3D8_TYPES;
return NULL;
}
template <>
IUnknown *Unwrap(IUnknown *ptr)
{
if(ptr == NULL)
return NULL;
#undef D3D8_TYPE_MACRO
#define D3D8_TYPE_MACRO(iface) \
if(UnwrapHelper<iface>::IsAlloc(ptr)) \
return (IUnknown *)GetWrapped((iface *)ptr)->GetReal();
ALL_D3D8_TYPES;
RDCERR("Unknown type of ptr 0x%p", ptr);
return NULL;
}
template <>
ResourceId GetResID(IUnknown *ptr)
{
if(ptr == NULL)
return ResourceId();
TrackedResource8 *res = GetTracked(ptr);
if(res == NULL)
{
RDCERR("Unknown type of ptr 0x%p", ptr);
return ResourceId();
}
return res->GetResourceID();
}
template <>
D3D8ResourceRecord *GetRecord(IUnknown *ptr)
{
if(ptr == NULL)
return NULL;
TrackedResource8 *res = GetTracked(ptr);
if(res == NULL)
{
RDCERR("Unknown type of ptr 0x%p", ptr);
return NULL;
}
return res->GetResourceRecord();
}
| [
"baldurk@baldurk.org"
] | baldurk@baldurk.org |
f1335a743daadbbbd90c1fa57d3644f0ff223907 | 7e6aac751bb9c43f53785134b3b6c1f9c603f37d | /generator/booking_dataset.cpp | caeaff88d181c86f12f10e36849a59d5099c8236 | [
"Apache-2.0"
] | permissive | psokol/omim | cc2e95bb21d9ebe453e83517ec96cd5b3d383306 | 8c0c85aac64841c08ed8892b55022bcc69300f4d | refs/heads/master | 2020-12-25T17:45:18.633298 | 2016-06-30T22:14:03 | 2016-06-30T22:14:03 | 60,401,992 | 0 | 0 | null | 2016-06-04T08:59:57 | 2016-06-04T08:59:57 | null | UTF-8 | C++ | false | false | 7,769 | cpp | #include "generator/booking_dataset.hpp"
#include "indexer/search_delimiters.hpp"
#include "indexer/search_string_utils.hpp"
#include "geometry/distance_on_sphere.hpp"
#include "base/logging.hpp"
#include "base/string_utils.hpp"
#include "std/fstream.hpp"
#include "std/iostream.hpp"
#include "std/sstream.hpp"
namespace generator
{
namespace
{
bool CheckForValues(string const & value)
{
for (char const * val :
{"hotel", "apartment", "camp_site", "chalet", "guest_house", "hostel", "motel", "resort"})
{
if (value == val)
return true;
}
return false;
}
} // namespace
BookingDataset::Hotel::Hotel(string const & src)
{
vector<string> rec(FieldsCount());
strings::SimpleTokenizer token(src, "\t");
for (size_t i = 0; token && i < rec.size(); ++i, ++token)
rec[i] = *token;
strings::to_uint(rec[Index(Fields::Id)], id);
strings::to_double(rec[Index(Fields::Latitude)], lat);
strings::to_double(rec[Index(Fields::Longtitude)], lon);
name = rec[Index(Fields::Name)];
address = rec[Index(Fields::Address)];
strings::to_uint(rec[Index(Fields::Stars)], stars);
strings::to_uint(rec[Index(Fields::PriceCategory)], priceCategory);
strings::to_double(rec[Index(Fields::RatingBooking)], ratingBooking);
strings::to_double(rec[Index(Fields::RatingUsers)], ratingUser);
descUrl = rec[Index(Fields::DescUrl)];
strings::to_uint(rec[Index(Fields::Type)], type);
}
ostream & operator<<(ostream & s, BookingDataset::Hotel const & h)
{
return s << "Name: " << h.name << "\t Address: " << h.address << "\t lat: " << h.lat
<< " lon: " << h.lon;
}
BookingDataset::BookingDataset(string const & dataPath)
{
LoadHotels(dataPath);
size_t counter = 0;
for (auto const & hotel : m_hotels)
{
TBox b(TPoint(hotel.lat, hotel.lon), TPoint(hotel.lat, hotel.lon));
m_rtree.insert(std::make_pair(b, counter));
++counter;
}
}
bool BookingDataset::BookingFilter(OsmElement const & e) const
{
return Filter(e, [&](OsmElement const & e)
{
return MatchWithBooking(e);
});
}
bool BookingDataset::TourismFilter(OsmElement const & e) const
{
return Filter(e, [&](OsmElement const & e)
{
return true;
});
}
BookingDataset::Hotel const & BookingDataset::GetHotel(size_t index) const
{
ASSERT_GREATER(m_hotels.size(), index, ());
return m_hotels[index];
}
vector<size_t> BookingDataset::GetNearestHotels(double lat, double lon, size_t limit,
double maxDistance /* = 0.0 */) const
{
namespace bgi = boost::geometry::index;
vector<size_t> indexes;
for_each(bgi::qbegin(m_rtree, bgi::nearest(TPoint(lat, lon), limit)), bgi::qend(m_rtree),
[&](TValue const & v)
{
auto const & hotel = m_hotels[v.second];
double const dist = ms::DistanceOnEarth(lat, lon, hotel.lat, hotel.lon);
if (maxDistance != 0.0 && dist > maxDistance /* max distance in meters */)
return;
indexes.emplace_back(v.second);
});
return indexes;
}
bool BookingDataset::MatchByName(string const & osmName,
vector<size_t> const & bookingIndexes) const
{
return false;
// Match name.
// vector<strings::UniString> osmTokens;
// NormalizeAndTokenizeString(name, osmTokens, search::Delimiters());
//
// cout << "\n------------- " << name << endl;
//
// bool matched = false;
// for (auto const & index : indexes)
// {
// vector<strings::UniString> bookingTokens;
// NormalizeAndTokenizeString(m_hotels[index].name, bookingTokens, search::Delimiters());
//
// map<size_t, vector<pair<size_t, size_t>>> weightPair;
//
// for (size_t j = 0; j < osmTokens.size(); ++j)
// {
// for (size_t i = 0; i < bookingTokens.size(); ++i)
// {
// size_t distance = strings::EditDistance(osmTokens[j].begin(), osmTokens[j].end(),
// bookingTokens[i].begin(),
// bookingTokens[i].end());
// if (distance < 3)
// weightPair[distance].emplace_back(i, j);
// }
// }
//
// if (!weightPair.empty())
// {
// cout << m_hotels[e.second] << endl;
// matched = true;
// }
// }
}
void BookingDataset::BuildFeatures(function<void(OsmElement *)> const & fn) const
{
for (auto const & hotel : m_hotels)
{
OsmElement e;
e.type = OsmElement::EntityType::Node;
e.id = 1;
e.lat = hotel.lat;
e.lon = hotel.lon;
e.AddTag("name", hotel.name);
e.AddTag("ref:sponsored", strings::to_string(hotel.id));
e.AddTag("website", hotel.descUrl);
e.AddTag("rating:sponsored", strings::to_string(hotel.ratingUser));
e.AddTag("stars", strings::to_string(hotel.stars));
e.AddTag("price_rate", strings::to_string(hotel.priceCategory));
e.AddTag("addr:full", hotel.address);
switch (hotel.type)
{
case 19:
case 205: e.AddTag("tourism", "motel"); break;
case 21:
case 206:
case 212: e.AddTag("tourism", "resort"); break;
case 3:
case 23:
case 24:
case 25:
case 202:
case 207:
case 208:
case 209:
case 210:
case 216:
case 220:
case 223: e.AddTag("tourism", "guest_house"); break;
case 14:
case 204:
case 213:
case 218:
case 219:
case 226:
case 222: e.AddTag("tourism", "hotel"); break;
case 211:
case 224:
case 228: e.AddTag("tourism", "chalet"); break;
case 13:
case 225:
case 203: e.AddTag("tourism", "hostel"); break;
case 215:
case 221:
case 227:
case 2:
case 201: e.AddTag("tourism", "apartment"); break;
case 214: e.AddTag("tourism", "camp_site"); break;
default: e.AddTag("tourism", "hotel"); break;
}
fn(&e);
}
}
// static
double BookingDataset::ScoreByLinearNormDistance(double distance)
{
distance = my::clamp(distance, 0, kDistanceLimitInMeters);
return 1.0 - distance / kDistanceLimitInMeters;
}
void BookingDataset::LoadHotels(string const & path)
{
m_hotels.clear();
if (path.empty())
return;
ifstream src(path);
if (!src.is_open())
{
LOG(LERROR, ("Error while opening", path, ":", strerror(errno)));
return;
}
for (string line; getline(src, line);)
m_hotels.emplace_back(line);
}
bool BookingDataset::MatchWithBooking(OsmElement const & e) const
{
string name;
for (auto const & tag : e.Tags())
{
if (tag.key == "name")
{
name = tag.value;
break;
}
}
if (name.empty())
return false;
// Find |kMaxSelectedElements| nearest values to a point.
auto const bookingIndexes = GetNearestHotels(e.lat, e.lon, kMaxSelectedElements, kDistanceLimitInMeters);
bool matched = false;
for (size_t const j : bookingIndexes)
{
auto const & hotel = GetHotel(j);
double const distanceMeters = ms::DistanceOnEarth(e.lat, e.lon, hotel.lat, hotel.lon);
double score = ScoreByLinearNormDistance(distanceMeters);
matched = score > kOptimalThreshold;
if (matched)
break;
}
return matched;
}
bool BookingDataset::Filter(OsmElement const & e,
function<bool(OsmElement const &)> const & fn) const
{
if (e.type != OsmElement::EntityType::Node)
return false;
if (e.Tags().empty())
return false;
bool matched = false;
for (auto const & tag : e.Tags())
{
if (tag.key == "tourism" && CheckForValues(tag.value))
{
matched = fn(e);
break;
}
}
// TODO: Need to write file with dropped osm features.
return matched;
}
} // namespace generator
| [
"yershov@corp.mail.ru"
] | yershov@corp.mail.ru |
959cc315edc842a06c3bc56a5f9f2e5010d28558 | 25fa0e6825f56a140aaaaf9ebe43dccbc7d31a0b | /CPP_SimpleGames/Guess_My_Number/BackgroundInfo/forLoopCounters.cpp | 174ebdbcbc0367fee4a2df192d10484bf98cea27 | [] | no_license | JoshuaTPierce/Learning_Repo1 | 0342e42d6db846dd1be74ead4116d4fc247c590a | 9a5a34bf04bfe6699420976dedcd295ca79335b4 | refs/heads/master | 2020-03-25T02:48:29.923672 | 2018-08-31T13:11:54 | 2018-08-31T13:11:54 | 143,308,470 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 737 | cpp | // Counter
// Demonstrates for loops
#include <iostream>
using namespace std;
int main(){
cout << "Counting forward:\n";
for (int i = 0; i < 10; ++i) {
cout << i << " ";
}
cout << "\n\nCounting backward:\n";
for (int i = 9; i >= 0; --i) {
cout << i << " ";
}
cout << "\n\nCounting by fives:\n";
for (int i = 0; i <= 50; i += 5){
cout << i << " ";
}
cout << "\n\nCounting with null statements:\n";
int count = 0;
for ( ; count < 10; ) {
cout << count << " ";
++count;
}
cout << "\n\nCounting with nested for loops:\n";
const int ROWS = 5;
const int COLUMNS = 3;
for (int i = 0; i < ROWS; ++i) {
for (int j = 0; j < COLUMNS; ++j) {
cout << i << "," << j << " ";
}
}
cout << endl;
return 0;
}
| [
"joshua.pierce@licor.com"
] | joshua.pierce@licor.com |
fcf5c0a3f82b704b3266ded483a7d5d8eae8d7cd | 74e7667ad65cbdaa869c6e384fdd8dc7e94aca34 | /MicroFrameworkPK_v4_1/BuildOutput/public/debug/Client/stubs/spot_net_security_native_Microsoft_SPOT_Net_Security_SslNative.h | 0767fe1527105eabf5fcfb4f2a0f65bd3dcbed2c | [
"BSD-3-Clause",
"OpenSSL",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | gezidan/NETMF-LPC | 5093ab223eb9d7f42396344ea316cbe50a2f784b | db1880a03108db6c7f611e6de6dbc45ce9b9adce | refs/heads/master | 2021-01-18T10:59:42.467549 | 2011-06-28T08:11:24 | 2011-06-28T08:11:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,534 | h | //-----------------------------------------------------------------------------
//
// ** WARNING! **
// This file was generated automatically by a tool.
// Re-running the tool will overwrite this file.
// You should copy this file to a custom location
// before adding any customization in the copy to
// prevent loss of your changes when the tool is
// re-run.
//
//-----------------------------------------------------------------------------
#ifndef _SPOT_NET_SECURITY_NATIVE_MICROSOFT_SPOT_NET_SECURITY_SSLNATIVE_H_
#define _SPOT_NET_SECURITY_NATIVE_MICROSOFT_SPOT_NET_SECURITY_SSLNATIVE_H_
namespace Microsoft
{
namespace SPOT
{
namespace Net
{
namespace Security
{
struct SslNative
{
// Helper Functions to access fields of managed object
// Declaration of stubs. These functions are implemented by Interop code developers
static INT32 SecureServerInit( INT32 param0, INT32 param1, UNSUPPORTED_TYPE param2, double param3, HRESULT &hr );
static INT32 SecureClientInit( INT32 param0, INT32 param1, UNSUPPORTED_TYPE param2, double param3, HRESULT &hr );
static void UpdateCertificates( INT32 param0, UNSUPPORTED_TYPE param1, double param2, HRESULT &hr );
static void SecureAccept( INT32 param0, UNSUPPORTED_TYPE param1, HRESULT &hr );
static void SecureConnect( INT32 param0, LPCSTR param1, UNSUPPORTED_TYPE param2, HRESULT &hr );
static INT32 SecureRead( UNSUPPORTED_TYPE param0, CLR_RT_TypedArray_UINT8 param1, INT32 param2, INT32 param3, INT32 param4, HRESULT &hr );
static INT32 SecureWrite( UNSUPPORTED_TYPE param0, CLR_RT_TypedArray_UINT8 param1, INT32 param2, INT32 param3, INT32 param4, HRESULT &hr );
static INT32 SecureCloseSocket( UNSUPPORTED_TYPE param0, HRESULT &hr );
static INT32 ExitSecureContext( INT32 param0, HRESULT &hr );
static void ParseCertificate( CLR_RT_TypedArray_UINT8 param0, LPCSTR param1, LPCSTR * param2, LPCSTR * param3, UNSUPPORTED_TYPE * param4, float param5, HRESULT &hr );
static INT32 DataAvailable( UNSUPPORTED_TYPE param0, HRESULT &hr );
};
}
}
}
}
#endif //_SPOT_NET_SECURITY_NATIVE_MICROSOFT_SPOT_NET_SECURITY_SSLNATIVE_H_
| [
"psampaio.isel@gmail.com"
] | psampaio.isel@gmail.com |
9020bc876f3e0a79c3fb260e519cafb3e59fd191 | 530822b710300825d0395b10feaa067a0236e3b4 | /C++_Primer_Exercises/Dealing_with_Data/SecondsToHoursMinutesAndSecondsConverter.h | 826dd4c1c7e79de7562f204c43be07d3df1ede7f | [] | no_license | Rick-Addiction/CPlusPlus_Studies | b29ebdbefd588e099bc69346de6dd3678f33772f | 491d94eeae4d33481ece8046729c7c69bab98836 | refs/heads/master | 2020-08-05T20:57:38.730135 | 2020-07-04T18:24:19 | 2020-07-04T18:24:19 | 212,707,313 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 184 | h | #ifndef SECONDSTOHOURSMINUTESANDSECONDS_H
#define SECONDSTOHOURSMINUTESANDSECONDS_H
#include <iostream>
#include <string>
void SecondsToHoursMinutesAndSecondsConverter();
#endif | [
"henrique.rachti@gmail.com"
] | henrique.rachti@gmail.com |
fb20e5b5f06ae8930e678e73feb40274709ded12 | ef620e1a2c22758ffc835ebb12e9d1a7a9b7fb0d | /connect4solver/Constants.MoveData.h | f4fd778c8f1e66810b2644ebae7bf58c879d9254 | [] | no_license | dfoverdx/connect4solver | e3eb3f0fc12b6419cda50634cb53c0dad01b7f0b | 036b0b953af618b45fd933ce0f5417e38321cc11 | refs/heads/master | 2021-08-06T14:57:48.939912 | 2017-11-01T20:57:32 | 2017-11-01T20:57:32 | 107,034,998 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,205 | h | #pragma once
#include "Constants.h"
#include "Helpers.h"
#include "MoveData.CompilerFlagTypedefs.h"
namespace connect4solver {
namespace moveDataConstants {
constexpr MoveDataBase MOVES_TO_WIN_MASK_BITS = RequiredBits<BOARD_SIZE>::value;
constexpr MoveDataBase IS_FINISHED_MASK_BITS = 1;
constexpr MoveDataBase IS_SYMMETRIC_MASK_BITS = 1;
constexpr MoveDataBase REF_COUNT_MASK_BITS = RequiredBits<BOARD_WIDTH>::value;
constexpr MoveDataBase WORKER_THREAD_ID_MASK_BITS = 4;
#define makeIndex(prevMask) prevMask##_MASK_INDEX + prevMask##_MASK_BITS
constexpr MoveDataBase MOVES_TO_WIN_MASK_INDEX = 0;
constexpr MoveDataBase IS_SYMMETRIC_MASK_INDEX = makeIndex(MOVES_TO_WIN);
constexpr MoveDataBase IS_FINISHED_MASK_INDEX = makeIndex(IS_SYMMETRIC);
constexpr MoveDataBase REF_COUNT_MASK_INDEX = makeIndex(IS_FINISHED);
constexpr MoveDataBase WORKER_THREAD_ID_MASK_INDEX = makeIndex(REF_COUNT);
#undef makeIndex
#if !BF
#define makeMask(maskName) constexpr MoveDataBase maskName##_MASK = ((1 << maskName##_MASK_BITS) - 1) << maskName##_MASK_INDEX
makeMask(MOVES_TO_WIN); // ---- ---- --11 1111
makeMask(IS_SYMMETRIC); // ---- ---- -1-- ----
makeMask(IS_FINISHED); // ---- ---- 1--- ----
makeMask(REF_COUNT); // ---- -111 ---- ----
makeMask(WORKER_THREAD_ID); // -111 1--- ---- ----
constexpr MoveDataBase REF_COUNT_1 = 0x1 << REF_COUNT_MASK_INDEX; // ---- ---1 ---- ----
constexpr MoveDataBase FINISH_MASK = // -111 1--- 1111 1111
IS_FINISHED_MASK |
WORKER_THREAD_ID_MASK |
MOVES_TO_WIN_MASK;
constexpr MoveDataBase BLACK_LOST_MASK = // -111 1--- 111- 1-1-
IS_FINISHED_MASK |
WORKER_THREAD_ID_MASK |
BLACK_LOST << MOVES_TO_WIN_MASK_INDEX;
#undef makeMask
#endif
}
} | [
"thinkin.arbys@gmail.com"
] | thinkin.arbys@gmail.com |
e3f09a6e12cf874ccd86c0ebf2aae36398d78c32 | 12043db0f57f5d9402a99507648bcbb4d9417452 | /Programming_Abstractions/Chapter_10/Exercise_01/Exercise_01/editor_test.cpp | bca7a401e559b6f5574d89bd617f8a866165e029 | [] | no_license | daniellozuz/CPP | a8afb1ae3353bd483cf953fac8a70b0b1446023c | fdc8957158522fc27aa55a44b3e45333157b843f | refs/heads/master | 2021-05-12T08:31:17.581023 | 2018-03-07T23:41:45 | 2018-03-07T23:41:45 | 117,283,294 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 906 | cpp | #include "EditorBuffer.h"
#include <iostream>
#include <string>
using namespace std;
void execute_command(EditorBuffer &buffer, string line);
int main(void) {
EditorBuffer buffer;
while (true) {
cout << "*";
string command;
getline(cin, command);
if (command != "")
execute_command(buffer, command);
buffer.display();
}
return 0;
}
void execute_command(EditorBuffer &buffer, string line) {
switch (toupper(line[0])) {
case 'I':
for (int i = 1; i < line.length(); i++)
buffer.insert_character(line[i]);
break;
case 'D':
buffer.delete_character();
break;
case 'F':
buffer.move_cursor_forward();
break;
case 'B':
buffer.move_cursor_backward();
break;
case 'J':
buffer.move_cursor_to_start();
break;
case 'E':
buffer.move_cursor_to_end();
break;
case 'Q':
exit(0);
default:
cout << "Illegal command" << endl;
break;
}
}
| [
"daniel.zuziak@gmail.com"
] | daniel.zuziak@gmail.com |
b9f57c0639e3cc260af0bdeffb3e5207d7908338 | 2de9e70c7b44b05f9029d8966bc2491378ed805f | /indie/object/IPowerUp.hpp | 315a5733f773c0ab79af18a035e6be9e3506032a | [] | no_license | Zoryi/indie_studio | 67cf3ffec17e71982642aeb6ebdd481565ec4e9d | bd2931d55bf09a8ae45c59e74b5a25e27daa873a | refs/heads/master | 2020-04-07T17:10:11.940514 | 2018-11-21T14:25:17 | 2018-11-21T14:25:17 | 158,558,080 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 238 | hpp | //
// EPITECH PROJECT, 2018
// indie_studio
// File description:
// IPowerUp.hpp
//
#ifndef POWERUP_HPP_
#define POWERUP_HPP_
# include "IObject.hpp"
class IPowerUp : public IObject
{
public:
virtual ~IPowerUp() = default;
};
#endif
| [
"romain.devalle@epitech.eu"
] | romain.devalle@epitech.eu |
94ab6f6f037184890b6fdae9e8ad06e216f77de8 | da4cc98ed821ec4c41a0a29c926c0a97df3c0bff | /demo/framework-dx11/unorderedaccessiblebatch.h | 20c7875ec7b68b7ec4a038af80cc9eed7654b74d | [
"MIT"
] | permissive | rokuz/GraphicsDemo | 514d308ad147214480b53e58c47cfccb558a9cbd | 41300287cc9d2f7e4e0656348809db5b3c939ced | refs/heads/master | 2023-04-06T20:15:11.159235 | 2023-03-31T21:32:13 | 2023-03-31T21:32:13 | 17,832,703 | 11 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,642 | h | /*
* Copyright (c) 2014 Roman Kuznetsov
*
* 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 (including the next
* paragraph) 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
namespace framework
{
class UnorderedAccessBuffer;
class RenderTarget;
struct UnorderedAccessibleBatch
{
ID3D11UnorderedAccessView* elements[D3D11_PS_CS_UAV_REGISTER_COUNT];
unsigned int initialValues[D3D11_PS_CS_UAV_REGISTER_COUNT];
int elementsNumber;
UnorderedAccessibleBatch();
void add(std::shared_ptr<UnorderedAccessBuffer> buffer, unsigned int initialValue = -1);
void add(std::shared_ptr<RenderTarget> renderTarget, unsigned int initialValue = -1);
};
} | [
"r.kuznetsow@gmail.com"
] | r.kuznetsow@gmail.com |
5608a9b97c922f6b022755c0efbe466851850b70 | a45067a48af5e720dc6144b39685d3b1fba0432f | /offer/3.cpp | 9887a24e63a104e17a8908f64453cccfff5a1619 | [] | no_license | lihao779/linuxsys | b8cb1d5a42a2a32fb648a094c4332e68ca501f71 | c445ff7d11ae546f3ca71aa430c7f788cf7e2e39 | refs/heads/master | 2023-05-29T17:28:54.924952 | 2021-06-15T14:26:03 | 2021-06-15T14:26:03 | 305,936,508 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,052 | cpp | #include <stdio.h>
#if 0
bool IsHavenum(int array[3][3], int row, int col, int num)
{
int temprow = 0;
int tempcol = col - 1;
int temp = -1;
while(temprow <= row - 1 && tempcol >= 0)
{
temp = array[temprow][tempcol];
if(temp == num)
return true;
else if(temp > num)
tempcol--;
else
temprow++;
}
return false;
}
#endif
bool IsHavenum(int array[][3], int row, int col, int num)
{
int temprow = row - 1;
int tempcol = 0;
while(array != NULL && temprow >= 0 && tempcol <= col - 1)
{
int temp = array[temprow][tempcol];
if(temp == num)
return true;
else if(temp > num)
temprow--;
else
tempcol++;
}
return false;
}
int main()
{
int array[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
int row , col;
row = col = 3;
if(IsHavenum(array, row, col, 7))
{
printf("have 7\n");
}
else
printf("not have 7\n");
return 0;
}
| [
"3024978915@qq.com"
] | 3024978915@qq.com |
fe78a0dae67da977156383ae71393014e60bda8c | aaf04ff1e0ec94e769103faf6b74e4f3570337c5 | /sdks/spirit/boost/mpl/iter_fold_if.hpp | dc3791f7d882293b1bff07abb3da13eb455f4e91 | [] | no_license | jacob-meacham/Ego | 815ac6cb63f2fbf28e924f66729ca36147881000 | 682ae352fde6e08ad728899d81ab9a2039ccc27c | refs/heads/master | 2021-01-01T05:36:49.656269 | 2015-12-27T19:40:11 | 2015-12-27T19:40:11 | 10,834,409 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,131 | hpp |
#ifndef BOOST_MPL_ITER_FOLD_IF_HPP_INCLUDED
#define BOOST_MPL_ITER_FOLD_IF_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2003-2004
// Copyright Eric Friedman 2003
//
// 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)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Source$
// $Date: 2004-09-02 17:41:37 +0200 (gio, 02 set 2004) $
// $Revision: 24874 $
#include <boost/mpl/begin_end.hpp>
#include <boost/mpl/logical.hpp>
#include <boost/mpl/always.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/pair.hpp>
#include <boost/mpl/apply.hpp>
#include <boost/mpl/aux_/iter_fold_if_impl.hpp>
#include <boost/mpl/aux_/na_spec.hpp>
#include <boost/mpl/aux_/lambda_support.hpp>
#include <boost/mpl/aux_/config/forwarding.hpp>
#include <boost/mpl/aux_/config/workaround.hpp>
#include <boost/type_traits/is_same.hpp>
namespace boost { namespace mpl {
namespace aux {
template< typename Predicate, typename LastIterator >
struct iter_fold_if_pred
{
template< typename State, typename Iterator > struct apply
#if !defined(BOOST_MPL_CFG_NO_NESTED_FORWARDING)
: and_<
not_< is_same<Iterator,LastIterator> >
, apply1<Predicate,Iterator>
>
{
#else
{
typedef and_<
not_< is_same<Iterator,LastIterator> >
, apply1<Predicate,Iterator>
> type;
#endif
};
};
} // namespace aux
template<
typename BOOST_MPL_AUX_NA_PARAM(Sequence)
, typename BOOST_MPL_AUX_NA_PARAM(State)
, typename BOOST_MPL_AUX_NA_PARAM(ForwardOp)
, typename BOOST_MPL_AUX_NA_PARAM(ForwardPredicate)
, typename BOOST_MPL_AUX_NA_PARAM(BackwardOp)
, typename BOOST_MPL_AUX_NA_PARAM(BackwardPredicate)
>
struct iter_fold_if
{
typedef typename begin<Sequence>::type first_;
typedef typename end<Sequence>::type last_;
typedef typename eval_if<
is_na<BackwardPredicate>
, if_< is_na<BackwardOp>, always<false_>, always<true_> >
, identity<BackwardPredicate>
>::type backward_pred_;
// cwpro8 doesn't like 'cut-off' type here (use typedef instead)
#if !BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3003)) && !BOOST_WORKAROUND(__IBMCPP__, BOOST_TESTED_AT(600))
struct result_ :
#else
typedef
#endif
aux::iter_fold_if_impl<
first_
, State
, ForwardOp
, protect< aux::iter_fold_if_pred< ForwardPredicate,last_ > >
, BackwardOp
, backward_pred_
>
#if !BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3003)) && !BOOST_WORKAROUND(__IBMCPP__, BOOST_TESTED_AT(600))
{ };
#else
result_;
#endif
public:
typedef pair<
typename result_::state
, typename result_::iterator
> type;
BOOST_MPL_AUX_LAMBDA_SUPPORT(
6
, iter_fold_if
, (Sequence,State,ForwardOp,ForwardPredicate,BackwardOp,BackwardPredicate)
)
};
BOOST_MPL_AUX_NA_SPEC(6, iter_fold_if)
}}
#endif // BOOST_MPL_ITER_FOLD_IF_HPP_INCLUDED
| [
"jmeacham@palantir.com"
] | jmeacham@palantir.com |
dcbd68892c41f860cf6f1ae91a48bd16bccf7391 | bb6ebff7a7f6140903d37905c350954ff6599091 | /ui/app_list/views/apps_grid_view.cc | d7da61bd4191ed9c8d016eb58df39c7834f90923 | [
"BSD-3-Clause"
] | permissive | PDi-Communication-Systems-Inc/lollipop_external_chromium_org | faa6602bd6bfd9b9b6277ce3cd16df0bd26e7f2f | ccadf4e63dd34be157281f53fe213d09a8c66d2c | refs/heads/master | 2022-12-23T18:07:04.568931 | 2016-04-11T16:03:36 | 2016-04-11T16:03:36 | 53,677,925 | 0 | 1 | BSD-3-Clause | 2022-12-09T23:46:46 | 2016-03-11T15:49:07 | C++ | UTF-8 | C++ | false | false | 73,690 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/app_list/views/apps_grid_view.h"
#include <algorithm>
#include <set>
#include <string>
#include "base/guid.h"
#include "ui/app_list/app_list_constants.h"
#include "ui/app_list/app_list_folder_item.h"
#include "ui/app_list/app_list_item.h"
#include "ui/app_list/app_list_switches.h"
#include "ui/app_list/views/app_list_drag_and_drop_host.h"
#include "ui/app_list/views/app_list_folder_view.h"
#include "ui/app_list/views/app_list_item_view.h"
#include "ui/app_list/views/apps_grid_view_delegate.h"
#include "ui/app_list/views/page_switcher.h"
#include "ui/app_list/views/pulsing_block_view.h"
#include "ui/app_list/views/top_icon_animation_view.h"
#include "ui/compositor/scoped_layer_animation_settings.h"
#include "ui/events/event.h"
#include "ui/gfx/animation/animation.h"
#include "ui/views/border.h"
#include "ui/views/view_model_utils.h"
#include "ui/views/widget/widget.h"
#if defined(USE_AURA)
#include "ui/aura/window.h"
#include "ui/aura/window_event_dispatcher.h"
#if defined(OS_WIN)
#include "ui/views/win/hwnd_util.h"
#endif // defined(OS_WIN)
#endif // defined(USE_AURA)
#if defined(OS_WIN)
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/win/shortcut.h"
#include "ui/base/dragdrop/drag_utils.h"
#include "ui/base/dragdrop/drop_target_win.h"
#include "ui/base/dragdrop/os_exchange_data.h"
#include "ui/base/dragdrop/os_exchange_data_provider_win.h"
#include "ui/gfx/win/dpi.h"
#endif
namespace app_list {
namespace {
// Distance a drag needs to be from the app grid to be considered 'outside', at
// which point we rearrange the apps to their pre-drag configuration, as a drop
// then would be canceled. We have a buffer to make it easier to drag apps to
// other pages.
const int kDragBufferPx = 20;
// Padding space in pixels for fixed layout.
const int kLeftRightPadding = 20;
const int kTopPadding = 1;
// Padding space in pixels between pages.
const int kPagePadding = 40;
// Preferred tile size when showing in fixed layout.
const int kPreferredTileWidth = 88;
const int kPreferredTileHeight = 98;
// Width in pixels of the area on the sides that triggers a page flip.
const int kPageFlipZoneSize = 40;
// Delay in milliseconds to do the page flip.
const int kPageFlipDelayInMs = 1000;
// How many pages on either side of the selected one we prerender.
const int kPrerenderPages = 1;
// The drag and drop proxy should get scaled by this factor.
const float kDragAndDropProxyScale = 1.5f;
// Delays in milliseconds to show folder dropping preview circle.
const int kFolderDroppingDelay = 150;
// Delays in milliseconds to show re-order preview.
const int kReorderDelay = 120;
// Delays in milliseconds to show folder item reparent UI.
const int kFolderItemReparentDelay = 50;
// Radius of the circle, in which if entered, show folder dropping preview
// UI.
const int kFolderDroppingCircleRadius = 15;
// RowMoveAnimationDelegate is used when moving an item into a different row.
// Before running the animation, the item's layer is re-created and kept in
// the original position, then the item is moved to just before its target
// position and opacity set to 0. When the animation runs, this delegate moves
// the layer and fades it out while fading in the item at the same time.
class RowMoveAnimationDelegate : public gfx::AnimationDelegate {
public:
RowMoveAnimationDelegate(views::View* view,
ui::Layer* layer,
const gfx::Rect& layer_target)
: view_(view),
layer_(layer),
layer_start_(layer ? layer->bounds() : gfx::Rect()),
layer_target_(layer_target) {
}
virtual ~RowMoveAnimationDelegate() {}
// gfx::AnimationDelegate overrides:
virtual void AnimationProgressed(const gfx::Animation* animation) OVERRIDE {
view_->layer()->SetOpacity(animation->GetCurrentValue());
view_->layer()->ScheduleDraw();
if (layer_) {
layer_->SetOpacity(1 - animation->GetCurrentValue());
layer_->SetBounds(animation->CurrentValueBetween(layer_start_,
layer_target_));
layer_->ScheduleDraw();
}
}
virtual void AnimationEnded(const gfx::Animation* animation) OVERRIDE {
view_->layer()->SetOpacity(1.0f);
view_->SchedulePaint();
}
virtual void AnimationCanceled(const gfx::Animation* animation) OVERRIDE {
view_->layer()->SetOpacity(1.0f);
view_->SchedulePaint();
}
private:
// The view that needs to be wrapped. Owned by views hierarchy.
views::View* view_;
scoped_ptr<ui::Layer> layer_;
const gfx::Rect layer_start_;
const gfx::Rect layer_target_;
DISALLOW_COPY_AND_ASSIGN(RowMoveAnimationDelegate);
};
// ItemRemoveAnimationDelegate is used to show animation for removing an item.
// This happens when user drags an item into a folder. The dragged item will
// be removed from the original list after it is dropped into the folder.
class ItemRemoveAnimationDelegate : public gfx::AnimationDelegate {
public:
explicit ItemRemoveAnimationDelegate(views::View* view)
: view_(view) {
}
virtual ~ItemRemoveAnimationDelegate() {
}
// gfx::AnimationDelegate overrides:
virtual void AnimationProgressed(const gfx::Animation* animation) OVERRIDE {
view_->layer()->SetOpacity(1 - animation->GetCurrentValue());
view_->layer()->ScheduleDraw();
}
private:
scoped_ptr<views::View> view_;
DISALLOW_COPY_AND_ASSIGN(ItemRemoveAnimationDelegate);
};
// ItemMoveAnimationDelegate observes when an item finishes animating when it is
// not moving between rows. This is to ensure an item is repainted for the
// "zoom out" case when releasing an item being dragged.
class ItemMoveAnimationDelegate : public gfx::AnimationDelegate {
public:
ItemMoveAnimationDelegate(views::View* view) : view_(view) {}
virtual void AnimationEnded(const gfx::Animation* animation) OVERRIDE {
view_->SchedulePaint();
}
virtual void AnimationCanceled(const gfx::Animation* animation) OVERRIDE {
view_->SchedulePaint();
}
private:
views::View* view_;
DISALLOW_COPY_AND_ASSIGN(ItemMoveAnimationDelegate);
};
// Gets the distance between the centers of the |rect_1| and |rect_2|.
int GetDistanceBetweenRects(gfx::Rect rect_1,
gfx::Rect rect_2) {
return (rect_1.CenterPoint() - rect_2.CenterPoint()).Length();
}
// Returns true if the |item| is an folder item.
bool IsFolderItem(AppListItem* item) {
return (item->GetItemType() == AppListFolderItem::kItemType);
}
bool IsOEMFolderItem(AppListItem* item) {
return IsFolderItem(item) &&
(static_cast<AppListFolderItem*>(item))->folder_type() ==
AppListFolderItem::FOLDER_TYPE_OEM;
}
} // namespace
#if defined(OS_WIN)
// Interprets drag events sent from Windows via the drag/drop API and forwards
// them to AppsGridView.
// On Windows, in order to have the OS perform the drag properly we need to
// provide it with a shortcut file which may or may not exist at the time the
// drag is started. Therefore while waiting for that shortcut to be located we
// just do a regular "internal" drag and transition into the synchronous drag
// when the shortcut is found/created. Hence a synchronous drag is an optional
// phase of a regular drag and non-Windows platforms drags are equivalent to a
// Windows drag that never enters the synchronous drag phase.
class SynchronousDrag : public ui::DragSourceWin {
public:
SynchronousDrag(AppsGridView* grid_view,
AppListItemView* drag_view,
const gfx::Point& drag_view_offset)
: grid_view_(grid_view),
drag_view_(drag_view),
drag_view_offset_(drag_view_offset),
has_shortcut_path_(false),
running_(false),
canceled_(false) {}
void set_shortcut_path(const base::FilePath& shortcut_path) {
has_shortcut_path_ = true;
shortcut_path_ = shortcut_path;
}
bool running() { return running_; }
bool CanRun() {
return has_shortcut_path_ && !running_;
}
void Run() {
DCHECK(CanRun());
// Prevent the synchronous dragger being destroyed while the drag is
// running.
scoped_refptr<SynchronousDrag> this_ref = this;
running_ = true;
ui::OSExchangeData data;
SetupExchangeData(&data);
// Hide the dragged view because the OS is going to create its own.
drag_view_->SetVisible(false);
// Blocks until the drag is finished. Calls into the ui::DragSourceWin
// methods.
DWORD effects;
DoDragDrop(ui::OSExchangeDataProviderWin::GetIDataObject(data),
this, DROPEFFECT_MOVE | DROPEFFECT_LINK, &effects);
// If |drag_view_| is NULL the drag was ended by some reentrant code.
if (drag_view_) {
// Make the drag view visible again.
drag_view_->SetVisible(true);
drag_view_->OnSyncDragEnd();
grid_view_->EndDrag(canceled_ || !IsCursorWithinGridView());
}
}
void EndDragExternally() {
CancelDrag();
drag_view_ = NULL;
}
private:
// Overridden from ui::DragSourceWin.
virtual void OnDragSourceCancel() OVERRIDE {
canceled_ = true;
}
virtual void OnDragSourceDrop() OVERRIDE {
}
virtual void OnDragSourceMove() OVERRIDE {
grid_view_->UpdateDrag(AppsGridView::MOUSE, GetCursorInGridViewCoords());
}
void SetupExchangeData(ui::OSExchangeData* data) {
data->SetFilename(shortcut_path_);
gfx::ImageSkia image(drag_view_->GetDragImage());
gfx::Size image_size(image.size());
drag_utils::SetDragImageOnDataObject(
image,
drag_view_offset_ - drag_view_->GetDragImageOffset(),
data);
}
HWND GetGridViewHWND() {
return views::HWNDForView(grid_view_);
}
bool IsCursorWithinGridView() {
POINT p;
GetCursorPos(&p);
return GetGridViewHWND() == WindowFromPoint(p);
}
gfx::Point GetCursorInGridViewCoords() {
POINT p;
GetCursorPos(&p);
ScreenToClient(GetGridViewHWND(), &p);
gfx::Point grid_view_pt(p.x, p.y);
grid_view_pt = gfx::win::ScreenToDIPPoint(grid_view_pt);
views::View::ConvertPointFromWidget(grid_view_, &grid_view_pt);
return grid_view_pt;
}
AppsGridView* grid_view_;
AppListItemView* drag_view_;
gfx::Point drag_view_offset_;
bool has_shortcut_path_;
base::FilePath shortcut_path_;
bool running_;
bool canceled_;
DISALLOW_COPY_AND_ASSIGN(SynchronousDrag);
};
#endif // defined(OS_WIN)
AppsGridView::AppsGridView(AppsGridViewDelegate* delegate)
: model_(NULL),
item_list_(NULL),
delegate_(delegate),
folder_delegate_(NULL),
page_switcher_view_(NULL),
cols_(0),
rows_per_page_(0),
selected_view_(NULL),
drag_view_(NULL),
drag_start_page_(-1),
#if defined(OS_WIN)
use_synchronous_drag_(true),
#endif
drag_pointer_(NONE),
drop_attempt_(DROP_FOR_NONE),
drag_and_drop_host_(NULL),
forward_events_to_drag_and_drop_host_(false),
page_flip_target_(-1),
page_flip_delay_in_ms_(kPageFlipDelayInMs),
bounds_animator_(this),
activated_folder_item_view_(NULL),
dragging_for_reparent_item_(false) {
SetPaintToLayer(true);
// Clip any icons that are outside the grid view's bounds. These icons would
// otherwise be visible to the user when the grid view is off screen.
layer()->SetMasksToBounds(true);
SetFillsBoundsOpaquely(false);
pagination_model_.SetTransitionDurations(kPageTransitionDurationInMs,
kOverscrollPageTransitionDurationMs);
pagination_model_.AddObserver(this);
page_switcher_view_ = new PageSwitcher(&pagination_model_);
AddChildView(page_switcher_view_);
}
AppsGridView::~AppsGridView() {
// Coming here |drag_view_| should already be canceled since otherwise the
// drag would disappear after the app list got animated away and closed,
// which would look odd.
DCHECK(!drag_view_);
if (drag_view_)
EndDrag(true);
if (model_)
model_->RemoveObserver(this);
pagination_model_.RemoveObserver(this);
if (item_list_)
item_list_->RemoveObserver(this);
// Make sure |page_switcher_view_| is deleted before |pagination_model_|.
view_model_.Clear();
RemoveAllChildViews(true);
}
void AppsGridView::SetLayout(int icon_size, int cols, int rows_per_page) {
icon_size_.SetSize(icon_size, icon_size);
cols_ = cols;
rows_per_page_ = rows_per_page;
SetBorder(views::Border::CreateEmptyBorder(
kTopPadding, kLeftRightPadding, 0, kLeftRightPadding));
}
void AppsGridView::ResetForShowApps() {
activated_folder_item_view_ = NULL;
ClearDragState();
layer()->SetOpacity(1.0f);
SetVisible(true);
// Set all views to visible in case they weren't made visible again by an
// incomplete animation.
for (int i = 0; i < view_model_.view_size(); ++i) {
view_model_.view_at(i)->SetVisible(true);
}
CHECK_EQ(item_list_->item_count(),
static_cast<size_t>(view_model_.view_size()));
}
void AppsGridView::SetModel(AppListModel* model) {
if (model_)
model_->RemoveObserver(this);
model_ = model;
if (model_)
model_->AddObserver(this);
Update();
}
void AppsGridView::SetItemList(AppListItemList* item_list) {
if (item_list_)
item_list_->RemoveObserver(this);
item_list_ = item_list;
if (item_list_)
item_list_->AddObserver(this);
Update();
}
void AppsGridView::SetSelectedView(views::View* view) {
if (IsSelectedView(view) || IsDraggedView(view))
return;
Index index = GetIndexOfView(view);
if (IsValidIndex(index))
SetSelectedItemByIndex(index);
}
void AppsGridView::ClearSelectedView(views::View* view) {
if (view && IsSelectedView(view)) {
selected_view_->SchedulePaint();
selected_view_ = NULL;
}
}
void AppsGridView::ClearAnySelectedView() {
if (selected_view_) {
selected_view_->SchedulePaint();
selected_view_ = NULL;
}
}
bool AppsGridView::IsSelectedView(const views::View* view) const {
return selected_view_ == view;
}
void AppsGridView::EnsureViewVisible(const views::View* view) {
if (pagination_model_.has_transition())
return;
Index index = GetIndexOfView(view);
if (IsValidIndex(index))
pagination_model_.SelectPage(index.page, false);
}
void AppsGridView::InitiateDrag(AppListItemView* view,
Pointer pointer,
const ui::LocatedEvent& event) {
DCHECK(view);
if (drag_view_ || pulsing_blocks_model_.view_size())
return;
drag_view_ = view;
drag_view_init_index_ = GetIndexOfView(drag_view_);
drag_view_offset_ = event.location();
drag_start_page_ = pagination_model_.selected_page();
ExtractDragLocation(event, &drag_start_grid_view_);
drag_view_start_ = gfx::Point(drag_view_->x(), drag_view_->y());
}
void AppsGridView::StartSettingUpSynchronousDrag() {
#if defined(OS_WIN)
if (!delegate_ || !use_synchronous_drag_)
return;
// Folders can't be integrated with the OS.
if (IsFolderItem(drag_view_->item()))
return;
// Favor the drag and drop host over native win32 drag. For the Win8/ash
// launcher we want to have ashes drag and drop over win32's.
if (drag_and_drop_host_)
return;
// Never create a second synchronous drag if the drag started in a folder.
if (IsDraggingForReparentInRootLevelGridView())
return;
synchronous_drag_ = new SynchronousDrag(this, drag_view_, drag_view_offset_);
delegate_->GetShortcutPathForApp(drag_view_->item()->id(),
base::Bind(&AppsGridView::OnGotShortcutPath,
base::Unretained(this),
synchronous_drag_));
#endif
}
bool AppsGridView::RunSynchronousDrag() {
#if defined(OS_WIN)
if (!synchronous_drag_)
return false;
if (synchronous_drag_->CanRun()) {
if (IsDraggingForReparentInHiddenGridView())
folder_delegate_->SetRootLevelDragViewVisible(false);
synchronous_drag_->Run();
synchronous_drag_ = NULL;
return true;
} else if (!synchronous_drag_->running()) {
// The OS drag is not ready yet. If the root grid has a drag view because
// a reparent has started, ensure it is visible.
if (IsDraggingForReparentInHiddenGridView())
folder_delegate_->SetRootLevelDragViewVisible(true);
}
#endif
return false;
}
void AppsGridView::CleanUpSynchronousDrag() {
#if defined(OS_WIN)
if (synchronous_drag_)
synchronous_drag_->EndDragExternally();
synchronous_drag_ = NULL;
#endif
}
#if defined(OS_WIN)
void AppsGridView::OnGotShortcutPath(
scoped_refptr<SynchronousDrag> synchronous_drag,
const base::FilePath& path) {
// Drag may have ended before we get the shortcut path or a new drag may have
// begun.
if (synchronous_drag_ != synchronous_drag)
return;
// Setting the shortcut path here means the next time we hit UpdateDrag()
// we'll enter the synchronous drag.
// NOTE we don't Run() the drag here because that causes animations not to
// update for some reason.
synchronous_drag_->set_shortcut_path(path);
DCHECK(synchronous_drag_->CanRun());
}
#endif
bool AppsGridView::UpdateDragFromItem(Pointer pointer,
const ui::LocatedEvent& event) {
DCHECK(drag_view_);
gfx::Point drag_point_in_grid_view;
ExtractDragLocation(event, &drag_point_in_grid_view);
UpdateDrag(pointer, drag_point_in_grid_view);
if (!dragging())
return false;
// If a drag and drop host is provided, see if the drag operation needs to be
// forwarded.
gfx::Point location_in_screen = drag_point_in_grid_view;
views::View::ConvertPointToScreen(this, &location_in_screen);
DispatchDragEventToDragAndDropHost(location_in_screen);
if (drag_and_drop_host_)
drag_and_drop_host_->UpdateDragIconProxy(location_in_screen);
return true;
}
void AppsGridView::UpdateDrag(Pointer pointer, const gfx::Point& point) {
if (folder_delegate_)
UpdateDragStateInsideFolder(pointer, point);
// EndDrag was called before if |drag_view_| is NULL.
if (!drag_view_)
return;
if (RunSynchronousDrag())
return;
gfx::Vector2d drag_vector(point - drag_start_grid_view_);
if (!dragging() && ExceededDragThreshold(drag_vector)) {
drag_pointer_ = pointer;
// Move the view to the front so that it appears on top of other views.
ReorderChildView(drag_view_, -1);
bounds_animator_.StopAnimatingView(drag_view_);
// Stopping the animation may have invalidated our drag view due to the
// view hierarchy changing.
if (!drag_view_)
return;
StartSettingUpSynchronousDrag();
if (!dragging_for_reparent_item_)
StartDragAndDropHostDrag(point);
}
if (drag_pointer_ != pointer)
return;
last_drag_point_ = point;
const Index last_drop_target = drop_target_;
DropAttempt last_drop_attempt = drop_attempt_;
CalculateDropTarget(last_drag_point_, false);
if (IsPointWithinDragBuffer(last_drag_point_))
MaybeStartPageFlipTimer(last_drag_point_);
else
StopPageFlipTimer();
gfx::Point page_switcher_point(last_drag_point_);
views::View::ConvertPointToTarget(this, page_switcher_view_,
&page_switcher_point);
page_switcher_view_->UpdateUIForDragPoint(page_switcher_point);
if (!EnableFolderDragDropUI()) {
if (last_drop_target != drop_target_)
AnimateToIdealBounds();
drag_view_->SetPosition(drag_view_start_ + drag_vector);
return;
}
// Update drag with folder UI enabled.
if (last_drop_target != drop_target_ ||
last_drop_attempt != drop_attempt_) {
if (drop_attempt_ == DROP_FOR_REORDER) {
folder_dropping_timer_.Stop();
reorder_timer_.Start(FROM_HERE,
base::TimeDelta::FromMilliseconds(kReorderDelay),
this, &AppsGridView::OnReorderTimer);
} else if (drop_attempt_ == DROP_FOR_FOLDER) {
reorder_timer_.Stop();
folder_dropping_timer_.Start(FROM_HERE,
base::TimeDelta::FromMilliseconds(kFolderDroppingDelay),
this, &AppsGridView::OnFolderDroppingTimer);
}
// Reset the previous drop target.
SetAsFolderDroppingTarget(last_drop_target, false);
}
drag_view_->SetPosition(drag_view_start_ + drag_vector);
}
void AppsGridView::EndDrag(bool cancel) {
// EndDrag was called before if |drag_view_| is NULL.
if (!drag_view_)
return;
// Coming here a drag and drop was in progress.
bool landed_in_drag_and_drop_host = forward_events_to_drag_and_drop_host_;
if (forward_events_to_drag_and_drop_host_) {
DCHECK(!IsDraggingForReparentInRootLevelGridView());
forward_events_to_drag_and_drop_host_ = false;
drag_and_drop_host_->EndDrag(cancel);
if (IsDraggingForReparentInHiddenGridView()) {
folder_delegate_->DispatchEndDragEventForReparent(
true /* events_forwarded_to_drag_drop_host */,
cancel /* cancel_drag */);
}
} else {
if (IsDraggingForReparentInHiddenGridView()) {
// Forward the EndDrag event to the root level grid view.
folder_delegate_->DispatchEndDragEventForReparent(
false /* events_forwarded_to_drag_drop_host */,
cancel /* cancel_drag */);
EndDragForReparentInHiddenFolderGridView();
return;
}
if (!cancel && dragging()) {
// Regular drag ending path, ie, not for reparenting.
CalculateDropTarget(last_drag_point_, true);
if (IsValidIndex(drop_target_)) {
if (!EnableFolderDragDropUI()) {
MoveItemInModel(drag_view_, drop_target_);
} else {
if (drop_attempt_ == DROP_FOR_REORDER)
MoveItemInModel(drag_view_, drop_target_);
else if (drop_attempt_ == DROP_FOR_FOLDER)
MoveItemToFolder(drag_view_, drop_target_);
}
}
}
}
if (drag_and_drop_host_) {
// If we had a drag and drop proxy icon, we delete it and make the real
// item visible again.
drag_and_drop_host_->DestroyDragIconProxy();
if (landed_in_drag_and_drop_host) {
// Move the item directly to the target location, avoiding the "zip back"
// animation if the user was pinning it to the shelf.
int i = drop_target_.slot;
gfx::Rect bounds = view_model_.ideal_bounds(i);
drag_view_->SetBoundsRect(bounds);
}
// Fade in slowly if it landed in the shelf.
SetViewHidden(drag_view_,
false /* show */,
!landed_in_drag_and_drop_host /* animate */);
}
// The drag can be ended after the synchronous drag is created but before it
// is Run().
CleanUpSynchronousDrag();
SetAsFolderDroppingTarget(drop_target_, false);
ClearDragState();
AnimateToIdealBounds();
StopPageFlipTimer();
// If user releases mouse inside a folder's grid view, burst the folder
// container ink bubble.
if (folder_delegate_ && !IsDraggingForReparentInHiddenGridView())
folder_delegate_->UpdateFolderViewBackground(false);
}
void AppsGridView::StopPageFlipTimer() {
page_flip_timer_.Stop();
page_flip_target_ = -1;
}
AppListItemView* AppsGridView::GetItemViewAt(int index) const {
DCHECK(index >= 0 && index < view_model_.view_size());
return static_cast<AppListItemView*>(view_model_.view_at(index));
}
void AppsGridView::SetTopItemViewsVisible(bool visible) {
int top_item_count = std::min(static_cast<int>(kNumFolderTopItems),
view_model_.view_size());
for (int i = 0; i < top_item_count; ++i)
GetItemViewAt(i)->SetVisible(visible);
}
void AppsGridView::ScheduleShowHideAnimation(bool show) {
// Stop any previous animation.
layer()->GetAnimator()->StopAnimating();
// Set initial state.
SetVisible(true);
layer()->SetOpacity(show ? 0.0f : 1.0f);
ui::ScopedLayerAnimationSettings animation(layer()->GetAnimator());
animation.AddObserver(this);
animation.SetTweenType(
show ? kFolderFadeInTweenType : kFolderFadeOutTweenType);
animation.SetTransitionDuration(base::TimeDelta::FromMilliseconds(
show ? kFolderTransitionInDurationMs : kFolderTransitionOutDurationMs));
layer()->SetOpacity(show ? 1.0f : 0.0f);
}
void AppsGridView::InitiateDragFromReparentItemInRootLevelGridView(
AppListItemView* original_drag_view,
const gfx::Rect& drag_view_rect,
const gfx::Point& drag_point) {
DCHECK(original_drag_view && !drag_view_);
DCHECK(!dragging_for_reparent_item_);
// Create a new AppListItemView to duplicate the original_drag_view in the
// folder's grid view.
AppListItemView* view = new AppListItemView(this, original_drag_view->item());
AddChildView(view);
drag_view_ = view;
drag_view_->SetPaintToLayer(true);
// Note: For testing purpose, SetFillsBoundsOpaquely can be set to true to
// show the gray background.
drag_view_->SetFillsBoundsOpaquely(false);
drag_view_->SetIconSize(icon_size_);
drag_view_->SetBoundsRect(drag_view_rect);
drag_view_->SetDragUIState(); // Hide the title of the drag_view_.
// Hide the drag_view_ for drag icon proxy.
SetViewHidden(drag_view_,
true /* hide */,
true /* no animate */);
// Add drag_view_ to the end of the view_model_.
view_model_.Add(drag_view_, view_model_.view_size());
drag_start_page_ = pagination_model_.selected_page();
drag_start_grid_view_ = drag_point;
drag_view_start_ = gfx::Point(drag_view_->x(), drag_view_->y());
// Set the flag in root level grid view.
dragging_for_reparent_item_ = true;
}
void AppsGridView::UpdateDragFromReparentItem(Pointer pointer,
const gfx::Point& drag_point) {
DCHECK(drag_view_);
DCHECK(IsDraggingForReparentInRootLevelGridView());
UpdateDrag(pointer, drag_point);
}
bool AppsGridView::IsDraggedView(const views::View* view) const {
return drag_view_ == view;
}
void AppsGridView::ClearDragState() {
drop_attempt_ = DROP_FOR_NONE;
drag_pointer_ = NONE;
drop_target_ = Index();
drag_start_grid_view_ = gfx::Point();
drag_start_page_ = -1;
drag_view_offset_ = gfx::Point();
if (drag_view_) {
drag_view_->OnDragEnded();
if (IsDraggingForReparentInRootLevelGridView()) {
const int drag_view_index = view_model_.GetIndexOfView(drag_view_);
CHECK_EQ(view_model_.view_size() - 1, drag_view_index);
DeleteItemViewAtIndex(drag_view_index);
}
}
drag_view_ = NULL;
dragging_for_reparent_item_ = false;
}
void AppsGridView::SetDragViewVisible(bool visible) {
DCHECK(drag_view_);
SetViewHidden(drag_view_, !visible, true);
}
void AppsGridView::SetDragAndDropHostOfCurrentAppList(
ApplicationDragAndDropHost* drag_and_drop_host) {
drag_and_drop_host_ = drag_and_drop_host;
}
void AppsGridView::Prerender(int page_index) {
Layout();
int start = std::max(0, (page_index - kPrerenderPages) * tiles_per_page());
int end = std::min(view_model_.view_size(),
(page_index + 1 + kPrerenderPages) * tiles_per_page());
for (int i = start; i < end; i++) {
AppListItemView* v = static_cast<AppListItemView*>(view_model_.view_at(i));
v->Prerender();
}
}
bool AppsGridView::IsAnimatingView(views::View* view) {
return bounds_animator_.IsAnimating(view);
}
gfx::Size AppsGridView::GetPreferredSize() const {
const gfx::Insets insets(GetInsets());
const gfx::Size tile_size = gfx::Size(kPreferredTileWidth,
kPreferredTileHeight);
const int page_switcher_height =
page_switcher_view_->GetPreferredSize().height();
return gfx::Size(
tile_size.width() * cols_ + insets.width(),
tile_size.height() * rows_per_page_ +
page_switcher_height + insets.height());
}
bool AppsGridView::GetDropFormats(
int* formats,
std::set<OSExchangeData::CustomFormat>* custom_formats) {
// TODO(koz): Only accept a specific drag type for app shortcuts.
*formats = OSExchangeData::FILE_NAME;
return true;
}
bool AppsGridView::CanDrop(const OSExchangeData& data) {
return true;
}
int AppsGridView::OnDragUpdated(const ui::DropTargetEvent& event) {
return ui::DragDropTypes::DRAG_MOVE;
}
void AppsGridView::Layout() {
if (bounds_animator_.IsAnimating())
bounds_animator_.Cancel();
CalculateIdealBounds();
for (int i = 0; i < view_model_.view_size(); ++i) {
views::View* view = view_model_.view_at(i);
if (view != drag_view_)
view->SetBoundsRect(view_model_.ideal_bounds(i));
}
views::ViewModelUtils::SetViewBoundsToIdealBounds(pulsing_blocks_model_);
const int page_switcher_height =
page_switcher_view_->GetPreferredSize().height();
gfx::Rect rect(GetContentsBounds());
rect.set_y(rect.bottom() - page_switcher_height);
rect.set_height(page_switcher_height);
page_switcher_view_->SetBoundsRect(rect);
}
bool AppsGridView::OnKeyPressed(const ui::KeyEvent& event) {
bool handled = false;
if (selected_view_)
handled = selected_view_->OnKeyPressed(event);
if (!handled) {
const int forward_dir = base::i18n::IsRTL() ? -1 : 1;
switch (event.key_code()) {
case ui::VKEY_LEFT:
MoveSelected(0, -forward_dir, 0);
return true;
case ui::VKEY_RIGHT:
MoveSelected(0, forward_dir, 0);
return true;
case ui::VKEY_UP:
MoveSelected(0, 0, -1);
return true;
case ui::VKEY_DOWN:
MoveSelected(0, 0, 1);
return true;
case ui::VKEY_PRIOR: {
MoveSelected(-1, 0, 0);
return true;
}
case ui::VKEY_NEXT: {
MoveSelected(1, 0, 0);
return true;
}
default:
break;
}
}
return handled;
}
bool AppsGridView::OnKeyReleased(const ui::KeyEvent& event) {
bool handled = false;
if (selected_view_)
handled = selected_view_->OnKeyReleased(event);
return handled;
}
void AppsGridView::ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) {
if (!details.is_add && details.parent == this) {
// The view being delete should not have reference in |view_model_|.
CHECK_EQ(-1, view_model_.GetIndexOfView(details.child));
if (selected_view_ == details.child)
selected_view_ = NULL;
if (activated_folder_item_view_ == details.child)
activated_folder_item_view_ = NULL;
if (drag_view_ == details.child)
EndDrag(true);
bounds_animator_.StopAnimatingView(details.child);
}
}
void AppsGridView::Update() {
DCHECK(!selected_view_ && !drag_view_);
view_model_.Clear();
if (!item_list_ || !item_list_->item_count())
return;
for (size_t i = 0; i < item_list_->item_count(); ++i) {
views::View* view = CreateViewForItemAtIndex(i);
view_model_.Add(view, i);
AddChildView(view);
}
UpdatePaging();
UpdatePulsingBlockViews();
Layout();
SchedulePaint();
}
void AppsGridView::UpdatePaging() {
int total_page = view_model_.view_size() && tiles_per_page()
? (view_model_.view_size() - 1) / tiles_per_page() + 1
: 0;
pagination_model_.SetTotalPages(total_page);
}
void AppsGridView::UpdatePulsingBlockViews() {
const int existing_items = item_list_ ? item_list_->item_count() : 0;
const int available_slots =
tiles_per_page() - existing_items % tiles_per_page();
const int desired = model_->status() == AppListModel::STATUS_SYNCING ?
available_slots : 0;
if (pulsing_blocks_model_.view_size() == desired)
return;
while (pulsing_blocks_model_.view_size() > desired) {
views::View* view = pulsing_blocks_model_.view_at(0);
pulsing_blocks_model_.Remove(0);
delete view;
}
while (pulsing_blocks_model_.view_size() < desired) {
views::View* view = new PulsingBlockView(
gfx::Size(kPreferredTileWidth, kPreferredTileHeight), true);
pulsing_blocks_model_.Add(view, 0);
AddChildView(view);
}
}
views::View* AppsGridView::CreateViewForItemAtIndex(size_t index) {
// The drag_view_ might be pending for deletion, therefore view_model_
// may have one more item than item_list_.
DCHECK_LE(index, item_list_->item_count());
AppListItemView* view = new AppListItemView(this,
item_list_->item_at(index));
view->SetIconSize(icon_size_);
view->SetPaintToLayer(true);
view->SetFillsBoundsOpaquely(false);
return view;
}
AppsGridView::Index AppsGridView::GetIndexFromModelIndex(
int model_index) const {
return Index(model_index / tiles_per_page(), model_index % tiles_per_page());
}
int AppsGridView::GetModelIndexFromIndex(const Index& index) const {
return index.page * tiles_per_page() + index.slot;
}
void AppsGridView::SetSelectedItemByIndex(const Index& index) {
if (GetIndexOfView(selected_view_) == index)
return;
views::View* new_selection = GetViewAtIndex(index);
if (!new_selection)
return; // Keep current selection.
if (selected_view_)
selected_view_->SchedulePaint();
EnsureViewVisible(new_selection);
selected_view_ = new_selection;
selected_view_->SchedulePaint();
selected_view_->NotifyAccessibilityEvent(
ui::AX_EVENT_FOCUS, true);
}
bool AppsGridView::IsValidIndex(const Index& index) const {
return index.page >= 0 && index.page < pagination_model_.total_pages() &&
index.slot >= 0 && index.slot < tiles_per_page() &&
GetModelIndexFromIndex(index) < view_model_.view_size();
}
AppsGridView::Index AppsGridView::GetIndexOfView(
const views::View* view) const {
const int model_index = view_model_.GetIndexOfView(view);
if (model_index == -1)
return Index();
return GetIndexFromModelIndex(model_index);
}
views::View* AppsGridView::GetViewAtIndex(const Index& index) const {
if (!IsValidIndex(index))
return NULL;
const int model_index = GetModelIndexFromIndex(index);
return view_model_.view_at(model_index);
}
void AppsGridView::MoveSelected(int page_delta,
int slot_x_delta,
int slot_y_delta) {
if (!selected_view_)
return SetSelectedItemByIndex(Index(pagination_model_.selected_page(), 0));
const Index& selected = GetIndexOfView(selected_view_);
int target_slot = selected.slot + slot_x_delta + slot_y_delta * cols_;
if (selected.slot % cols_ == 0 && slot_x_delta == -1) {
if (selected.page > 0) {
page_delta = -1;
target_slot = selected.slot + cols_ - 1;
} else {
target_slot = selected.slot;
}
}
if (selected.slot % cols_ == cols_ - 1 && slot_x_delta == 1) {
if (selected.page < pagination_model_.total_pages() - 1) {
page_delta = 1;
target_slot = selected.slot - cols_ + 1;
} else {
target_slot = selected.slot;
}
}
// Clamp the target slot to the last item if we are moving to the last page
// but our target slot is past the end of the item list.
if (page_delta &&
selected.page + page_delta == pagination_model_.total_pages() - 1) {
int last_item_slot = (view_model_.view_size() - 1) % tiles_per_page();
if (last_item_slot < target_slot) {
target_slot = last_item_slot;
}
}
int target_page = std::min(pagination_model_.total_pages() - 1,
std::max(selected.page + page_delta, 0));
SetSelectedItemByIndex(Index(target_page, target_slot));
}
void AppsGridView::CalculateIdealBounds() {
gfx::Rect rect(GetContentsBounds());
if (rect.IsEmpty())
return;
gfx::Size tile_size(kPreferredTileWidth, kPreferredTileHeight);
gfx::Rect grid_rect(gfx::Size(tile_size.width() * cols_,
tile_size.height() * rows_per_page_));
grid_rect.Intersect(rect);
// Page width including padding pixels. A tile.x + page_width means the same
// tile slot in the next page.
const int page_width = grid_rect.width() + kPagePadding;
// If there is a transition, calculates offset for current and target page.
const int current_page = pagination_model_.selected_page();
const PaginationModel::Transition& transition =
pagination_model_.transition();
const bool is_valid = pagination_model_.is_valid_page(transition.target_page);
// Transition to right means negative offset.
const int dir = transition.target_page > current_page ? -1 : 1;
const int transition_offset = is_valid ?
transition.progress * page_width * dir : 0;
const int total_views =
view_model_.view_size() + pulsing_blocks_model_.view_size();
int slot_index = 0;
for (int i = 0; i < total_views; ++i) {
if (i < view_model_.view_size() && view_model_.view_at(i) == drag_view_) {
if (EnableFolderDragDropUI() && drop_attempt_ == DROP_FOR_FOLDER)
++slot_index;
continue;
}
Index view_index = GetIndexFromModelIndex(slot_index);
if (drop_target_ == view_index) {
if (EnableFolderDragDropUI() && drop_attempt_ == DROP_FOR_FOLDER) {
view_index = GetIndexFromModelIndex(slot_index);
} else if (!EnableFolderDragDropUI() ||
drop_attempt_ == DROP_FOR_REORDER) {
++slot_index;
view_index = GetIndexFromModelIndex(slot_index);
}
}
// Decides an x_offset for current item.
int x_offset = 0;
if (view_index.page < current_page)
x_offset = -page_width;
else if (view_index.page > current_page)
x_offset = page_width;
if (is_valid) {
if (view_index.page == current_page ||
view_index.page == transition.target_page) {
x_offset += transition_offset;
}
}
const int row = view_index.slot / cols_;
const int col = view_index.slot % cols_;
gfx::Rect tile_slot(
gfx::Point(grid_rect.x() + col * tile_size.width() + x_offset,
grid_rect.y() + row * tile_size.height()),
tile_size);
if (i < view_model_.view_size()) {
view_model_.set_ideal_bounds(i, tile_slot);
} else {
pulsing_blocks_model_.set_ideal_bounds(i - view_model_.view_size(),
tile_slot);
}
++slot_index;
}
}
void AppsGridView::AnimateToIdealBounds() {
const gfx::Rect visible_bounds(GetVisibleBounds());
CalculateIdealBounds();
for (int i = 0; i < view_model_.view_size(); ++i) {
views::View* view = view_model_.view_at(i);
if (view == drag_view_)
continue;
const gfx::Rect& target = view_model_.ideal_bounds(i);
if (bounds_animator_.GetTargetBounds(view) == target)
continue;
const gfx::Rect& current = view->bounds();
const bool current_visible = visible_bounds.Intersects(current);
const bool target_visible = visible_bounds.Intersects(target);
const bool visible = current_visible || target_visible;
const int y_diff = target.y() - current.y();
if (visible && y_diff && y_diff % kPreferredTileHeight == 0) {
AnimationBetweenRows(view,
current_visible,
current,
target_visible,
target);
} else if (visible || bounds_animator_.IsAnimating(view)) {
bounds_animator_.AnimateViewTo(view, target);
bounds_animator_.SetAnimationDelegate(
view,
scoped_ptr<gfx::AnimationDelegate>(
new ItemMoveAnimationDelegate(view)));
} else {
view->SetBoundsRect(target);
}
}
}
void AppsGridView::AnimationBetweenRows(views::View* view,
bool animate_current,
const gfx::Rect& current,
bool animate_target,
const gfx::Rect& target) {
// Determine page of |current| and |target|. -1 means in the left invisible
// page, 0 is the center visible page and 1 means in the right invisible page.
const int current_page = current.x() < 0 ? -1 :
current.x() >= width() ? 1 : 0;
const int target_page = target.x() < 0 ? -1 :
target.x() >= width() ? 1 : 0;
const int dir = current_page < target_page ||
(current_page == target_page && current.y() < target.y()) ? 1 : -1;
scoped_ptr<ui::Layer> layer;
if (animate_current) {
layer = view->RecreateLayer();
layer->SuppressPaint();
view->SetFillsBoundsOpaquely(false);
view->layer()->SetOpacity(0.f);
}
gfx::Rect current_out(current);
current_out.Offset(dir * kPreferredTileWidth, 0);
gfx::Rect target_in(target);
if (animate_target)
target_in.Offset(-dir * kPreferredTileWidth, 0);
view->SetBoundsRect(target_in);
bounds_animator_.AnimateViewTo(view, target);
bounds_animator_.SetAnimationDelegate(
view,
scoped_ptr<gfx::AnimationDelegate>(
new RowMoveAnimationDelegate(view, layer.release(), current_out)));
}
void AppsGridView::ExtractDragLocation(const ui::LocatedEvent& event,
gfx::Point* drag_point) {
#if defined(USE_AURA) && !defined(OS_WIN)
// Use root location of |event| instead of location in |drag_view_|'s
// coordinates because |drag_view_| has a scale transform and location
// could have integer round error and causes jitter.
*drag_point = event.root_location();
// GetWidget() could be NULL for tests.
if (GetWidget()) {
aura::Window::ConvertPointToTarget(
GetWidget()->GetNativeWindow()->GetRootWindow(),
GetWidget()->GetNativeWindow(),
drag_point);
}
views::View::ConvertPointFromWidget(this, drag_point);
#else
// For non-aura, root location is not clearly defined but |drag_view_| does
// not have the scale transform. So no round error would be introduced and
// it's okay to use View::ConvertPointToTarget.
*drag_point = event.location();
views::View::ConvertPointToTarget(drag_view_, this, drag_point);
#endif
}
void AppsGridView::CalculateDropTarget(const gfx::Point& drag_point,
bool use_page_button_hovering) {
if (EnableFolderDragDropUI()) {
CalculateDropTargetWithFolderEnabled(drag_point, use_page_button_hovering);
return;
}
int current_page = pagination_model_.selected_page();
gfx::Point point(drag_point);
if (!IsPointWithinDragBuffer(drag_point)) {
point = drag_start_grid_view_;
current_page = drag_start_page_;
}
if (use_page_button_hovering &&
page_switcher_view_->bounds().Contains(point)) {
gfx::Point page_switcher_point(point);
views::View::ConvertPointToTarget(this, page_switcher_view_,
&page_switcher_point);
int page = page_switcher_view_->GetPageForPoint(page_switcher_point);
if (pagination_model_.is_valid_page(page)) {
drop_target_.page = page;
drop_target_.slot = tiles_per_page() - 1;
}
} else {
gfx::Rect bounds(GetContentsBounds());
const int drop_row = (point.y() - bounds.y()) / kPreferredTileHeight;
const int drop_col = std::min(cols_ - 1,
(point.x() - bounds.x()) / kPreferredTileWidth);
drop_target_.page = current_page;
drop_target_.slot = std::max(0, std::min(
tiles_per_page() - 1,
drop_row * cols_ + drop_col));
}
// Limits to the last possible slot on last page.
if (drop_target_.page == pagination_model_.total_pages() - 1) {
drop_target_.slot = std::min(
(view_model_.view_size() - 1) % tiles_per_page(),
drop_target_.slot);
}
}
void AppsGridView::CalculateDropTargetWithFolderEnabled(
const gfx::Point& drag_point,
bool use_page_button_hovering) {
gfx::Point point(drag_point);
if (!IsPointWithinDragBuffer(drag_point)) {
point = drag_start_grid_view_;
}
if (use_page_button_hovering &&
page_switcher_view_->bounds().Contains(point)) {
gfx::Point page_switcher_point(point);
views::View::ConvertPointToTarget(this, page_switcher_view_,
&page_switcher_point);
int page = page_switcher_view_->GetPageForPoint(page_switcher_point);
if (pagination_model_.is_valid_page(page))
drop_attempt_ = DROP_FOR_NONE;
} else {
DCHECK(drag_view_);
// Try to find the nearest target for folder dropping or re-ordering.
drop_target_ = GetNearestTileForDragView();
}
}
void AppsGridView::OnReorderTimer() {
if (drop_attempt_ == DROP_FOR_REORDER)
AnimateToIdealBounds();
}
void AppsGridView::OnFolderItemReparentTimer() {
DCHECK(folder_delegate_);
if (drag_out_of_folder_container_ && drag_view_) {
folder_delegate_->ReparentItem(drag_view_, last_drag_point_);
// Set the flag in the folder's grid view.
dragging_for_reparent_item_ = true;
// Do not observe any data change since it is going to be hidden.
item_list_->RemoveObserver(this);
item_list_ = NULL;
}
}
void AppsGridView::OnFolderDroppingTimer() {
if (drop_attempt_ == DROP_FOR_FOLDER)
SetAsFolderDroppingTarget(drop_target_, true);
}
void AppsGridView::UpdateDragStateInsideFolder(Pointer pointer,
const gfx::Point& drag_point) {
if (IsUnderOEMFolder())
return;
if (IsDraggingForReparentInHiddenGridView()) {
// Dispatch drag event to root level grid view for re-parenting folder
// folder item purpose.
DispatchDragEventForReparent(pointer, drag_point);
return;
}
// Regular drag and drop in a folder's grid view.
folder_delegate_->UpdateFolderViewBackground(true);
// Calculate if the drag_view_ is dragged out of the folder's container
// ink bubble.
gfx::Rect bounds_to_folder_view = ConvertRectToParent(drag_view_->bounds());
gfx::Point pt = bounds_to_folder_view.CenterPoint();
bool is_item_dragged_out_of_folder =
folder_delegate_->IsPointOutsideOfFolderBoundary(pt);
if (is_item_dragged_out_of_folder) {
if (!drag_out_of_folder_container_) {
folder_item_reparent_timer_.Start(
FROM_HERE,
base::TimeDelta::FromMilliseconds(kFolderItemReparentDelay),
this,
&AppsGridView::OnFolderItemReparentTimer);
drag_out_of_folder_container_ = true;
}
} else {
folder_item_reparent_timer_.Stop();
drag_out_of_folder_container_ = false;
}
}
bool AppsGridView::IsDraggingForReparentInRootLevelGridView() const {
return (!folder_delegate_ && dragging_for_reparent_item_);
}
bool AppsGridView::IsDraggingForReparentInHiddenGridView() const {
return (folder_delegate_ && dragging_for_reparent_item_);
}
gfx::Rect AppsGridView::GetTargetIconRectInFolder(
AppListItemView* drag_item_view,
AppListItemView* folder_item_view) {
gfx::Rect view_ideal_bounds = view_model_.ideal_bounds(
view_model_.GetIndexOfView(folder_item_view));
gfx::Rect icon_ideal_bounds =
folder_item_view->GetIconBoundsForTargetViewBounds(view_ideal_bounds);
AppListFolderItem* folder_item =
static_cast<AppListFolderItem*>(folder_item_view->item());
return folder_item->GetTargetIconRectInFolderForItem(
drag_item_view->item(), icon_ideal_bounds);
}
bool AppsGridView::IsUnderOEMFolder() {
if (!folder_delegate_)
return false;
return folder_delegate_->IsOEMFolder();
}
void AppsGridView::DispatchDragEventForReparent(Pointer pointer,
const gfx::Point& drag_point) {
folder_delegate_->DispatchDragEventForReparent(pointer, drag_point);
}
void AppsGridView::EndDragFromReparentItemInRootLevel(
bool events_forwarded_to_drag_drop_host,
bool cancel_drag) {
// EndDrag was called before if |drag_view_| is NULL.
if (!drag_view_)
return;
DCHECK(IsDraggingForReparentInRootLevelGridView());
bool cancel_reparent = cancel_drag || drop_attempt_ == DROP_FOR_NONE;
if (!events_forwarded_to_drag_drop_host && !cancel_reparent) {
CalculateDropTarget(last_drag_point_, true);
if (IsValidIndex(drop_target_)) {
if (drop_attempt_ == DROP_FOR_REORDER) {
ReparentItemForReorder(drag_view_, drop_target_);
} else if (drop_attempt_ == DROP_FOR_FOLDER) {
ReparentItemToAnotherFolder(drag_view_, drop_target_);
}
}
SetViewHidden(drag_view_, false /* show */, true /* no animate */);
}
// The drag can be ended after the synchronous drag is created but before it
// is Run().
CleanUpSynchronousDrag();
SetAsFolderDroppingTarget(drop_target_, false);
if (cancel_reparent) {
CancelFolderItemReparent(drag_view_);
} else {
// By setting |drag_view_| to NULL here, we prevent ClearDragState() from
// cleaning up the newly created AppListItemView, effectively claiming
// ownership of the newly created drag view.
drag_view_->OnDragEnded();
drag_view_ = NULL;
}
ClearDragState();
AnimateToIdealBounds();
StopPageFlipTimer();
}
void AppsGridView::EndDragForReparentInHiddenFolderGridView() {
if (drag_and_drop_host_) {
// If we had a drag and drop proxy icon, we delete it and make the real
// item visible again.
drag_and_drop_host_->DestroyDragIconProxy();
}
// The drag can be ended after the synchronous drag is created but before it
// is Run().
CleanUpSynchronousDrag();
SetAsFolderDroppingTarget(drop_target_, false);
ClearDragState();
}
void AppsGridView::OnFolderItemRemoved() {
DCHECK(folder_delegate_);
item_list_ = NULL;
}
void AppsGridView::StartDragAndDropHostDrag(const gfx::Point& grid_location) {
// When a drag and drop host is given, the item can be dragged out of the app
// list window. In that case a proxy widget needs to be used.
// Note: This code has very likely to be changed for Windows (non metro mode)
// when a |drag_and_drop_host_| gets implemented.
if (!drag_view_ || !drag_and_drop_host_)
return;
gfx::Point screen_location = grid_location;
views::View::ConvertPointToScreen(this, &screen_location);
// Determine the mouse offset to the center of the icon so that the drag and
// drop host follows this layer.
gfx::Vector2d delta = drag_view_offset_ -
drag_view_->GetLocalBounds().CenterPoint();
delta.set_y(delta.y() + drag_view_->title()->size().height() / 2);
// We have to hide the original item since the drag and drop host will do
// the OS dependent code to "lift off the dragged item".
DCHECK(!IsDraggingForReparentInRootLevelGridView());
drag_and_drop_host_->CreateDragIconProxy(screen_location,
drag_view_->item()->icon(),
drag_view_,
delta,
kDragAndDropProxyScale);
SetViewHidden(drag_view_,
true /* hide */,
true /* no animation */);
}
void AppsGridView::DispatchDragEventToDragAndDropHost(
const gfx::Point& location_in_screen_coordinates) {
if (!drag_view_ || !drag_and_drop_host_)
return;
if (GetLocalBounds().Contains(last_drag_point_)) {
// The event was issued inside the app menu and we should get all events.
if (forward_events_to_drag_and_drop_host_) {
// The DnD host was previously called and needs to be informed that the
// session returns to the owner.
forward_events_to_drag_and_drop_host_ = false;
drag_and_drop_host_->EndDrag(true);
}
} else {
if (IsFolderItem(drag_view_->item()))
return;
// The event happened outside our app menu and we might need to dispatch.
if (forward_events_to_drag_and_drop_host_) {
// Dispatch since we have already started.
if (!drag_and_drop_host_->Drag(location_in_screen_coordinates)) {
// The host is not active any longer and we cancel the operation.
forward_events_to_drag_and_drop_host_ = false;
drag_and_drop_host_->EndDrag(true);
}
} else {
if (drag_and_drop_host_->StartDrag(drag_view_->item()->id(),
location_in_screen_coordinates)) {
// From now on we forward the drag events.
forward_events_to_drag_and_drop_host_ = true;
// Any flip operations are stopped.
StopPageFlipTimer();
}
}
}
}
void AppsGridView::MaybeStartPageFlipTimer(const gfx::Point& drag_point) {
if (!IsPointWithinDragBuffer(drag_point))
StopPageFlipTimer();
int new_page_flip_target = -1;
if (page_switcher_view_->bounds().Contains(drag_point)) {
gfx::Point page_switcher_point(drag_point);
views::View::ConvertPointToTarget(this, page_switcher_view_,
&page_switcher_point);
new_page_flip_target =
page_switcher_view_->GetPageForPoint(page_switcher_point);
}
// TODO(xiyuan): Fix this for RTL.
if (new_page_flip_target == -1 && drag_point.x() < kPageFlipZoneSize)
new_page_flip_target = pagination_model_.selected_page() - 1;
if (new_page_flip_target == -1 &&
drag_point.x() > width() - kPageFlipZoneSize) {
new_page_flip_target = pagination_model_.selected_page() + 1;
}
if (new_page_flip_target == page_flip_target_)
return;
StopPageFlipTimer();
if (pagination_model_.is_valid_page(new_page_flip_target)) {
page_flip_target_ = new_page_flip_target;
if (page_flip_target_ != pagination_model_.selected_page()) {
page_flip_timer_.Start(FROM_HERE,
base::TimeDelta::FromMilliseconds(page_flip_delay_in_ms_),
this, &AppsGridView::OnPageFlipTimer);
}
}
}
void AppsGridView::OnPageFlipTimer() {
DCHECK(pagination_model_.is_valid_page(page_flip_target_));
pagination_model_.SelectPage(page_flip_target_, true);
}
void AppsGridView::MoveItemInModel(views::View* item_view,
const Index& target) {
int current_model_index = view_model_.GetIndexOfView(item_view);
DCHECK_GE(current_model_index, 0);
int target_model_index = GetModelIndexFromIndex(target);
if (target_model_index == current_model_index)
return;
item_list_->RemoveObserver(this);
item_list_->MoveItem(current_model_index, target_model_index);
view_model_.Move(current_model_index, target_model_index);
item_list_->AddObserver(this);
if (pagination_model_.selected_page() != target.page)
pagination_model_.SelectPage(target.page, false);
}
void AppsGridView::MoveItemToFolder(views::View* item_view,
const Index& target) {
const std::string& source_item_id =
static_cast<AppListItemView*>(item_view)->item()->id();
AppListItemView* target_view =
static_cast<AppListItemView*>(GetViewAtSlotOnCurrentPage(target.slot));
const std::string& target_view_item_id = target_view->item()->id();
// Make change to data model.
item_list_->RemoveObserver(this);
std::string folder_item_id =
model_->MergeItems(target_view_item_id, source_item_id);
item_list_->AddObserver(this);
if (folder_item_id.empty()) {
LOG(ERROR) << "Unable to merge into item id: " << target_view_item_id;
return;
}
if (folder_item_id != target_view_item_id) {
// New folder was created, change the view model to replace the old target
// view with the new folder item view.
size_t folder_item_index;
if (item_list_->FindItemIndex(folder_item_id, &folder_item_index)) {
int target_view_index = view_model_.GetIndexOfView(target_view);
gfx::Rect target_view_bounds = target_view->bounds();
DeleteItemViewAtIndex(target_view_index);
views::View* target_folder_view =
CreateViewForItemAtIndex(folder_item_index);
target_folder_view->SetBoundsRect(target_view_bounds);
view_model_.Add(target_folder_view, target_view_index);
AddChildView(target_folder_view);
} else {
LOG(ERROR) << "Folder no longer in item_list: " << folder_item_id;
}
}
// Fade out the drag_view_ and delete it when animation ends.
int drag_view_index = view_model_.GetIndexOfView(drag_view_);
view_model_.Remove(drag_view_index);
bounds_animator_.AnimateViewTo(drag_view_, drag_view_->bounds());
bounds_animator_.SetAnimationDelegate(
drag_view_,
scoped_ptr<gfx::AnimationDelegate>(
new ItemRemoveAnimationDelegate(drag_view_)));
UpdatePaging();
}
void AppsGridView::ReparentItemForReorder(views::View* item_view,
const Index& target) {
item_list_->RemoveObserver(this);
model_->RemoveObserver(this);
AppListItem* reparent_item = static_cast<AppListItemView*>(item_view)->item();
DCHECK(reparent_item->IsInFolder());
const std::string source_folder_id = reparent_item->folder_id();
AppListFolderItem* source_folder =
static_cast<AppListFolderItem*>(item_list_->FindItem(source_folder_id));
int target_model_index = GetModelIndexFromIndex(target);
// Remove the source folder view if there is only 1 item in it, since the
// source folder will be deleted after its only child item removed from it.
if (source_folder->ChildItemCount() == 1u) {
const int deleted_folder_index =
view_model_.GetIndexOfView(activated_folder_item_view());
DeleteItemViewAtIndex(deleted_folder_index);
// Adjust |target_model_index| if it is beyond the deleted folder index.
if (target_model_index > deleted_folder_index)
--target_model_index;
}
// Move the item from its parent folder to top level item list.
// Must move to target_model_index, the location we expect the target item
// to be, not the item location we want to insert before.
int current_model_index = view_model_.GetIndexOfView(item_view);
syncer::StringOrdinal target_position;
if (target_model_index < static_cast<int>(item_list_->item_count()))
target_position = item_list_->item_at(target_model_index)->position();
model_->MoveItemToFolderAt(reparent_item, "", target_position);
view_model_.Move(current_model_index, target_model_index);
RemoveLastItemFromReparentItemFolderIfNecessary(source_folder_id);
item_list_->AddObserver(this);
model_->AddObserver(this);
UpdatePaging();
}
void AppsGridView::ReparentItemToAnotherFolder(views::View* item_view,
const Index& target) {
DCHECK(IsDraggingForReparentInRootLevelGridView());
AppListItemView* target_view =
static_cast<AppListItemView*>(GetViewAtSlotOnCurrentPage(target.slot));
if (!target_view)
return;
// Make change to data model.
item_list_->RemoveObserver(this);
AppListItem* reparent_item = static_cast<AppListItemView*>(item_view)->item();
DCHECK(reparent_item->IsInFolder());
const std::string source_folder_id = reparent_item->folder_id();
AppListFolderItem* source_folder =
static_cast<AppListFolderItem*>(item_list_->FindItem(source_folder_id));
// Remove the source folder view if there is only 1 item in it, since the
// source folder will be deleted after its only child item merged into the
// target item.
if (source_folder->ChildItemCount() == 1u)
DeleteItemViewAtIndex(
view_model_.GetIndexOfView(activated_folder_item_view()));
AppListItem* target_item = target_view->item();
// Move item to the target folder.
std::string target_id_after_merge =
model_->MergeItems(target_item->id(), reparent_item->id());
if (target_id_after_merge.empty()) {
LOG(ERROR) << "Unable to reparent to item id: " << target_item->id();
item_list_->AddObserver(this);
return;
}
if (target_id_after_merge != target_item->id()) {
// New folder was created, change the view model to replace the old target
// view with the new folder item view.
const std::string& new_folder_id = reparent_item->folder_id();
size_t new_folder_index;
if (item_list_->FindItemIndex(new_folder_id, &new_folder_index)) {
int target_view_index = view_model_.GetIndexOfView(target_view);
DeleteItemViewAtIndex(target_view_index);
views::View* new_folder_view =
CreateViewForItemAtIndex(new_folder_index);
view_model_.Add(new_folder_view, target_view_index);
AddChildView(new_folder_view);
} else {
LOG(ERROR) << "Folder no longer in item_list: " << new_folder_id;
}
}
RemoveLastItemFromReparentItemFolderIfNecessary(source_folder_id);
item_list_->AddObserver(this);
// Fade out the drag_view_ and delete it when animation ends.
int drag_view_index = view_model_.GetIndexOfView(drag_view_);
view_model_.Remove(drag_view_index);
bounds_animator_.AnimateViewTo(drag_view_, drag_view_->bounds());
bounds_animator_.SetAnimationDelegate(
drag_view_,
scoped_ptr<gfx::AnimationDelegate>(
new ItemRemoveAnimationDelegate(drag_view_)));
UpdatePaging();
}
// After moving the re-parenting item out of the folder, if there is only 1 item
// left, remove the last item out of the folder, delete the folder and insert it
// to the data model at the same position. Make the same change to view_model_
// accordingly.
void AppsGridView::RemoveLastItemFromReparentItemFolderIfNecessary(
const std::string& source_folder_id) {
AppListFolderItem* source_folder =
static_cast<AppListFolderItem*>(item_list_->FindItem(source_folder_id));
if (!source_folder || source_folder->ChildItemCount() != 1u)
return;
// Delete view associated with the folder item to be removed.
DeleteItemViewAtIndex(
view_model_.GetIndexOfView(activated_folder_item_view()));
// Now make the data change to remove the folder item in model.
AppListItem* last_item = source_folder->item_list()->item_at(0);
model_->MoveItemToFolderAt(last_item, "", source_folder->position());
// Create a new item view for the last item in folder.
size_t last_item_index;
if (!item_list_->FindItemIndex(last_item->id(), &last_item_index) ||
last_item_index > static_cast<size_t>(view_model_.view_size())) {
NOTREACHED();
return;
}
views::View* last_item_view = CreateViewForItemAtIndex(last_item_index);
view_model_.Add(last_item_view, last_item_index);
AddChildView(last_item_view);
}
void AppsGridView::CancelFolderItemReparent(AppListItemView* drag_item_view) {
// The icon of the dragged item must target to its final ideal bounds after
// the animation completes.
CalculateIdealBounds();
gfx::Rect target_icon_rect =
GetTargetIconRectInFolder(drag_item_view, activated_folder_item_view_);
gfx::Rect drag_view_icon_to_grid =
drag_item_view->ConvertRectToParent(drag_item_view->GetIconBounds());
drag_view_icon_to_grid.ClampToCenteredSize(
gfx::Size(kPreferredIconDimension, kPreferredIconDimension));
TopIconAnimationView* icon_view = new TopIconAnimationView(
drag_item_view->item()->icon(),
target_icon_rect,
false); /* animate like closing folder */
AddChildView(icon_view);
icon_view->SetBoundsRect(drag_view_icon_to_grid);
icon_view->TransformView();
}
void AppsGridView::CancelContextMenusOnCurrentPage() {
int start = pagination_model_.selected_page() * tiles_per_page();
int end = std::min(view_model_.view_size(), start + tiles_per_page());
for (int i = start; i < end; ++i) {
AppListItemView* view =
static_cast<AppListItemView*>(view_model_.view_at(i));
view->CancelContextMenu();
}
}
void AppsGridView::DeleteItemViewAtIndex(int index) {
views::View* item_view = view_model_.view_at(index);
view_model_.Remove(index);
if (item_view == drag_view_)
drag_view_ = NULL;
delete item_view;
}
bool AppsGridView::IsPointWithinDragBuffer(const gfx::Point& point) const {
gfx::Rect rect(GetLocalBounds());
rect.Inset(-kDragBufferPx, -kDragBufferPx, -kDragBufferPx, -kDragBufferPx);
return rect.Contains(point);
}
void AppsGridView::ButtonPressed(views::Button* sender,
const ui::Event& event) {
if (dragging())
return;
if (strcmp(sender->GetClassName(), AppListItemView::kViewClassName))
return;
if (delegate_) {
// Always set the previous activated_folder_item_view_ to be visible. This
// prevents a case where the item would remain hidden due the
// |activated_folder_item_view_| changing during the animation. We only
// need to track |activated_folder_item_view_| in the root level grid view.
if (!folder_delegate_) {
if (activated_folder_item_view_)
activated_folder_item_view_->SetVisible(true);
AppListItemView* pressed_item_view =
static_cast<AppListItemView*>(sender);
if (IsFolderItem(pressed_item_view->item()))
activated_folder_item_view_ = pressed_item_view;
else
activated_folder_item_view_ = NULL;
}
delegate_->ActivateApp(static_cast<AppListItemView*>(sender)->item(),
event.flags());
}
}
void AppsGridView::OnListItemAdded(size_t index, AppListItem* item) {
EndDrag(true);
views::View* view = CreateViewForItemAtIndex(index);
view_model_.Add(view, index);
AddChildView(view);
UpdatePaging();
UpdatePulsingBlockViews();
Layout();
SchedulePaint();
}
void AppsGridView::OnListItemRemoved(size_t index, AppListItem* item) {
EndDrag(true);
DeleteItemViewAtIndex(index);
UpdatePaging();
UpdatePulsingBlockViews();
Layout();
SchedulePaint();
}
void AppsGridView::OnListItemMoved(size_t from_index,
size_t to_index,
AppListItem* item) {
EndDrag(true);
view_model_.Move(from_index, to_index);
UpdatePaging();
AnimateToIdealBounds();
}
void AppsGridView::TotalPagesChanged() {
}
void AppsGridView::SelectedPageChanged(int old_selected, int new_selected) {
if (dragging()) {
CalculateDropTarget(last_drag_point_, true);
Layout();
MaybeStartPageFlipTimer(last_drag_point_);
} else {
ClearSelectedView(selected_view_);
Layout();
}
}
void AppsGridView::TransitionStarted() {
CancelContextMenusOnCurrentPage();
}
void AppsGridView::TransitionChanged() {
// Update layout for valid page transition only since over-scroll no longer
// animates app icons.
const PaginationModel::Transition& transition =
pagination_model_.transition();
if (pagination_model_.is_valid_page(transition.target_page))
Layout();
}
void AppsGridView::OnAppListModelStatusChanged() {
UpdatePulsingBlockViews();
Layout();
SchedulePaint();
}
void AppsGridView::SetViewHidden(views::View* view, bool hide, bool immediate) {
ui::ScopedLayerAnimationSettings animator(view->layer()->GetAnimator());
animator.SetPreemptionStrategy(
immediate ? ui::LayerAnimator::IMMEDIATELY_SET_NEW_TARGET :
ui::LayerAnimator::BLEND_WITH_CURRENT_ANIMATION);
view->layer()->SetOpacity(hide ? 0 : 1);
}
void AppsGridView::OnImplicitAnimationsCompleted() {
if (layer()->opacity() == 0.0f)
SetVisible(false);
}
bool AppsGridView::EnableFolderDragDropUI() {
// Enable drag and drop folder UI only if it is at the app list root level
// and the switch is on and the target folder can still accept new items.
return model_->folders_enabled() && !folder_delegate_ &&
CanDropIntoTarget(drop_target_);
}
bool AppsGridView::CanDropIntoTarget(const Index& drop_target) {
views::View* target_view = GetViewAtSlotOnCurrentPage(drop_target.slot);
if (!target_view)
return true;
AppListItem* target_item =
static_cast<AppListItemView*>(target_view)->item();
// Items can be dropped into non-folders (which have no children) or folders
// that have fewer than the max allowed items.
// OEM folder does not allow to drag/drop other items in it.
return target_item->ChildItemCount() < kMaxFolderItems &&
!IsOEMFolderItem(target_item);
}
// TODO(jennyz): Optimize the calculation for finding nearest tile.
AppsGridView::Index AppsGridView::GetNearestTileForDragView() {
Index nearest_tile;
nearest_tile.page = -1;
nearest_tile.slot = -1;
int d_min = -1;
// Calculate the top left tile |drag_view| intersects.
gfx::Point pt = drag_view_->bounds().origin();
CalculateNearestTileForVertex(pt, &nearest_tile, &d_min);
// Calculate the top right tile |drag_view| intersects.
pt = drag_view_->bounds().top_right();
CalculateNearestTileForVertex(pt, &nearest_tile, &d_min);
// Calculate the bottom left tile |drag_view| intersects.
pt = drag_view_->bounds().bottom_left();
CalculateNearestTileForVertex(pt, &nearest_tile, &d_min);
// Calculate the bottom right tile |drag_view| intersects.
pt = drag_view_->bounds().bottom_right();
CalculateNearestTileForVertex(pt, &nearest_tile, &d_min);
const int d_folder_dropping =
kFolderDroppingCircleRadius + kPreferredIconDimension / 2;
const int d_reorder =
kReorderDroppingCircleRadius + kPreferredIconDimension / 2;
// If user drags an item across pages to the last page, and targets it
// to the last empty slot on it, push the last item for re-ordering.
if (IsLastPossibleDropTarget(nearest_tile) && d_min < d_reorder) {
drop_attempt_ = DROP_FOR_REORDER;
nearest_tile.slot = nearest_tile.slot - 1;
return nearest_tile;
}
if (IsValidIndex(nearest_tile)) {
if (d_min < d_folder_dropping) {
views::View* target_view = GetViewAtSlotOnCurrentPage(nearest_tile.slot);
if (target_view &&
!IsFolderItem(static_cast<AppListItemView*>(drag_view_)->item())) {
// If a non-folder item is dragged to the target slot with an item
// sitting on it, attempt to drop the dragged item into the folder
// containing the item on nearest_tile.
drop_attempt_ = DROP_FOR_FOLDER;
return nearest_tile;
} else {
// If the target slot is blank, or the dragged item is a folder, attempt
// to re-order.
drop_attempt_ = DROP_FOR_REORDER;
return nearest_tile;
}
} else if (d_min < d_reorder) {
// Entering the re-order circle of the slot.
drop_attempt_ = DROP_FOR_REORDER;
return nearest_tile;
}
}
// If |drag_view| is not entering the re-order or fold dropping region of
// any items, cancel any previous re-order or folder dropping timer, and
// return itself.
drop_attempt_ = DROP_FOR_NONE;
reorder_timer_.Stop();
folder_dropping_timer_.Stop();
// When dragging for reparent a folder item, it should go back to its parent
// folder item if there is no drop target.
if (IsDraggingForReparentInRootLevelGridView()) {
DCHECK(activated_folder_item_view_);
return GetIndexOfView(activated_folder_item_view_);
}
return GetIndexOfView(drag_view_);
}
void AppsGridView::CalculateNearestTileForVertex(const gfx::Point& vertex,
Index* nearest_tile,
int* d_min) {
Index target_index;
gfx::Rect target_bounds = GetTileBoundsForPoint(vertex, &target_index);
if (target_bounds.IsEmpty() || target_index == *nearest_tile)
return;
// Do not count the tile, where drag_view_ used to sit on and is still moving
// on top of it, in calculating nearest tile for drag_view_.
views::View* target_view = GetViewAtSlotOnCurrentPage(target_index.slot);
if (target_index == drag_view_init_index_ && !target_view &&
!IsDraggingForReparentInRootLevelGridView()) {
return;
}
int d_center = GetDistanceBetweenRects(drag_view_->bounds(), target_bounds);
if (*d_min < 0 || d_center < *d_min) {
*d_min = d_center;
*nearest_tile = target_index;
}
}
gfx::Rect AppsGridView::GetTileBoundsForPoint(const gfx::Point& point,
Index *tile_index) {
// Check if |point| is outside of contents bounds.
gfx::Rect bounds(GetContentsBounds());
if (!bounds.Contains(point))
return gfx::Rect();
// Calculate which tile |point| is enclosed in.
int x = point.x();
int y = point.y();
int col = (x - bounds.x()) / kPreferredTileWidth;
int row = (y - bounds.y()) / kPreferredTileHeight;
gfx::Rect tile_rect = GetTileBounds(row, col);
// Check if |point| is outside a valid item's tile.
Index index(pagination_model_.selected_page(), row * cols_ + col);
*tile_index = index;
return tile_rect;
}
gfx::Rect AppsGridView::GetTileBounds(int row, int col) const {
gfx::Rect bounds(GetContentsBounds());
gfx::Size tile_size(kPreferredTileWidth, kPreferredTileHeight);
gfx::Rect grid_rect(gfx::Size(tile_size.width() * cols_,
tile_size.height() * rows_per_page_));
grid_rect.Intersect(bounds);
gfx::Rect tile_rect(
gfx::Point(grid_rect.x() + col * tile_size.width(),
grid_rect.y() + row * tile_size.height()),
tile_size);
return tile_rect;
}
bool AppsGridView::IsLastPossibleDropTarget(const Index& index) const {
int last_possible_slot = view_model_.view_size() % tiles_per_page();
return (index.page == pagination_model_.total_pages() - 1 &&
index.slot == last_possible_slot + 1);
}
views::View* AppsGridView::GetViewAtSlotOnCurrentPage(int slot) {
if (slot < 0)
return NULL;
// Calculate the original bound of the tile at |index|.
int row = slot / cols_;
int col = slot % cols_;
gfx::Rect tile_rect = GetTileBounds(row, col);
for (int i = 0; i < view_model_.view_size(); ++i) {
views::View* view = view_model_.view_at(i);
if (view->bounds() == tile_rect && view != drag_view_)
return view;
}
return NULL;
}
void AppsGridView::SetAsFolderDroppingTarget(const Index& target_index,
bool is_target_folder) {
AppListItemView* target_view =
static_cast<AppListItemView*>(
GetViewAtSlotOnCurrentPage(target_index.slot));
if (target_view)
target_view->SetAsAttemptedFolderTarget(is_target_folder);
}
} // namespace app_list
| [
"mrobbeloth@pdiarm.com"
] | mrobbeloth@pdiarm.com |
bc4ccf67679f8c45dcf9ad364da3b32ec2050bf9 | ed5669151a0ebe6bcc8c4b08fc6cde6481803d15 | /test/magma-1.6.0/src/dpotrf_panel_batched.cpp | e64f1fb9539f78834c00c86f9eb55a16ac12c48b | [] | no_license | JieyangChen7/DVFS-MAGMA | 1c36344bff29eeb0ce32736cadc921ff030225d4 | e7b83fe3a51ddf2cad0bed1d88a63f683b006f54 | refs/heads/master | 2021-09-26T09:11:28.772048 | 2018-05-27T01:45:43 | 2018-05-27T01:45:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,424 | cpp | /*
-- MAGMA (version 1.6.0) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
November 2013
@author Azzam Haidar
@author Tingxing Dong
@generated from zpotrf_panel_batched.cpp normal z -> d, Sat Nov 15 19:54:09 2014
*/
#include "common_magma.h"
#include "batched_kernel_param.h"
////////////////////////////////////////////////////////////////////////////////////////
extern "C" magma_int_t
magma_dpotrf_panel_batched(
magma_uplo_t uplo, magma_int_t n, magma_int_t nb,
double** dA_array, magma_int_t ldda,
double** dX_array, magma_int_t dX_length,
double** dinvA_array, magma_int_t dinvA_length,
double** dW0_displ, double** dW1_displ,
double** dW2_displ, double** dW3_displ,
double** dW4_displ,
magma_int_t *info_array, magma_int_t gbstep,
magma_int_t batchCount, cublasHandle_t myhandle)
{
//===============================================
// panel factorization
//===============================================
if(n<nb){
printf("magma_dpotrf_panel error n < nb %d < %d \n",(int) n, (int) nb);
return -101;
}
#if 0
magma_dpotf2_batched(
uplo, n, nb,
dA_array, ldda,
dW1_displ, dW2_displ,
dW3_displ, dW4_displ,
info_array, gbstep,
batchCount, myhandle);
#else
magma_dpotf2_batched(
uplo, nb, nb,
dA_array, ldda,
dW1_displ, dW2_displ,
dW3_displ, dW4_displ,
info_array, gbstep,
batchCount, myhandle);
if((n-nb) > 0){
magma_ddisplace_pointers(dW0_displ, dA_array, ldda, nb, 0, batchCount);
magmablas_dtrsm_work_batched(MagmaRight, MagmaLower, MagmaConjTrans, MagmaNonUnit,
1, n-nb, nb,
MAGMA_D_ONE,
dA_array, ldda,
dW0_displ, ldda,
dX_array, n-nb,
dinvA_array, dinvA_length,
dW1_displ, dW2_displ,
dW3_displ, dW4_displ,
0, batchCount);
}
#endif
return 0;
}
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
extern "C" magma_int_t
magma_dpotrf_recpanel_batched(
magma_uplo_t uplo, magma_int_t m, magma_int_t n,
magma_int_t min_recpnb,
double** dA_array, magma_int_t ldda,
double** dX_array, magma_int_t dX_length,
double** dinvA_array, magma_int_t dinvA_length,
double** dW0_displ, double** dW1_displ,
double** dW2_displ, double** dW3_displ,
double** dW4_displ,
magma_int_t *info_array, magma_int_t gbstep,
magma_int_t batchCount, cublasHandle_t myhandle)
{
// Quick return if possible
if (m ==0 || n == 0) {
return 1;
}
if (uplo == MagmaUpper) {
printf("Upper side is unavailable \n");
return -100;
}
if(m<n){
printf("error m < n %d < %d \n", (int) m, (int) n);
return -101;
}
double **dA_displ = NULL;
magma_malloc((void**)&dA_displ, batchCount * sizeof(*dA_displ));
double alpha = MAGMA_D_NEG_ONE;
double beta = MAGMA_D_ONE;
magma_int_t panel_nb = n;
if(panel_nb <= min_recpnb){
//printf("calling bottom panel recursive with m=%d nb=%d\n",m,n);
// panel factorization
magma_ddisplace_pointers(dA_displ, dA_array, ldda, 0, 0, batchCount);
//magma_dpotrf_rectile_batched(uplo, m, panel_nb, 16,
magma_dpotrf_panel_batched( uplo, m, panel_nb,
dA_displ, ldda,
dX_array, dX_length,
dinvA_array, dinvA_length,
dW0_displ, dW1_displ, dW2_displ,
dW3_displ, dW4_displ,
info_array, gbstep,
batchCount, myhandle);
}
else{
// split A over two [A A2]
// panel on A1, update on A2 then panel on A1
magma_int_t n1 = n/2;
magma_int_t n2 = n-n1;
magma_int_t m1 = m;
magma_int_t m2 = m-n1;
magma_int_t p1 = 0;
magma_int_t p2 = n1;
// panel on A1
//printf("calling recursive panel on A1 with m=%d nb=%d min_recpnb %d\n",m1,n1,min_recpnb);
magma_ddisplace_pointers(dA_displ, dA_array, ldda, p1, p1, batchCount);
magma_dpotrf_recpanel_batched(
uplo, m1, n1, min_recpnb,
dA_displ, ldda,
dX_array, dX_length,
dinvA_array, dinvA_length,
dW0_displ, dW1_displ, dW2_displ,
dW3_displ, dW4_displ,
info_array, gbstep,
batchCount, myhandle);
// update A2
//printf("calling update A2 with m=%d n=%d k=%d\n",m2,n2,n1);
magma_ddisplace_pointers(dA_displ, dA_array, ldda, p1+n1, p1, batchCount);
magma_ddisplace_pointers(dW0_displ, dA_array, ldda, p1+n1, p2, batchCount);
magmablas_dgemm_batched(MagmaNoTrans, MagmaConjTrans, m2, n2, n1,
alpha, dA_displ, ldda,
dA_displ, ldda,
beta, dW0_displ, ldda,
batchCount);
// panel on A2
//printf("calling recursive panel on A2 with m=%d nb=%d min_recpnb %d\n",m2,n2,min_recpnb);
magma_ddisplace_pointers(dA_displ, dA_array, ldda, p2, p2, batchCount);
magma_dpotrf_recpanel_batched(
uplo, m2, n2, min_recpnb,
dA_displ, ldda,
dX_array, dX_length,
dinvA_array, dinvA_length,
dW0_displ, dW1_displ, dW2_displ,
dW3_displ, dW4_displ,
info_array, gbstep,
batchCount, myhandle);
}
magma_free(dA_displ);
return 0;
}
////////////////////////////////////////////////////////////////////////////////////////
extern "C" magma_int_t
magma_dpotrf_rectile_batched(
magma_uplo_t uplo, magma_int_t m, magma_int_t n,
magma_int_t min_recpnb,
double** dA_array, magma_int_t ldda,
double** dX_array, magma_int_t dX_length,
double** dinvA_array, magma_int_t dinvA_length,
double** dW0_displ, double** dW1_displ,
double** dW2_displ, double** dW3_displ,
double** dW4_displ,
magma_int_t *info_array, magma_int_t gbstep,
magma_int_t batchCount, cublasHandle_t myhandle)
{
//magma_int_t DEBUG=0;
// Quick return if possible
if (m ==0 || n == 0) {
return 1;
}
if (uplo == MagmaUpper) {
printf("Upper side is unavailable \n");
return -100;
}
if(m<n){
printf("error m < n %d < %d \n", (int) m, (int) n);
return -101;
}
double **dA_displ = NULL;
magma_malloc((void**)&dA_displ, batchCount * sizeof(*dA_displ));
double alpha = MAGMA_D_NEG_ONE;
double beta = MAGMA_D_ONE;
magma_int_t panel_nb = n;
if(panel_nb <= min_recpnb){
// if(DEBUG==1) printf("calling bottom panel recursive with n=%d\n",(int) panel_nb);
// panel factorization
magma_ddisplace_pointers(dA_displ, dA_array, ldda, 0, 0, batchCount);
magma_dpotrf_panel_batched(
uplo, m, panel_nb,
dA_displ, ldda,
dX_array, dX_length,
dinvA_array, dinvA_length,
dW0_displ, dW1_displ, dW2_displ,
dW3_displ, dW4_displ,
info_array, gbstep,
batchCount, myhandle);
}
else{
// split A over two [A11 A12; A21 A22; A31 A32]
// panel on tile A11,
// trsm on A21, using A11
// update on A22 then panel on A22.
// finally a trsm on [A31 A32] using the whole [A11 A12; A21 A22]
magma_int_t n1 = n/2;
magma_int_t n2 = n-n1;
magma_int_t p1 = 0;
magma_int_t p2 = n1;
// panel on A11
//if(DEBUG==1) printf("calling recursive panel on A11=A(%d,%d) with n=%d min_recpnb %d\n",(int) p1, (int) p1, (int) n1, (int) min_recpnb);
magma_ddisplace_pointers(dA_displ, dA_array, ldda, p1, p1, batchCount);
magma_dpotrf_rectile_batched(
uplo, n1, n1, min_recpnb,
dA_displ, ldda,
dX_array, dX_length,
dinvA_array, dinvA_length,
dW0_displ, dW1_displ, dW2_displ,
dW3_displ, dW4_displ,
info_array, gbstep,
batchCount, myhandle);
// TRSM on A21
//if(DEBUG==1) printf("calling trsm on A21=A(%d,%d) using A11==A(%d,%d) with m=%d k=%d \n",p2,p1,p1,p1,n2,n1);
magma_ddisplace_pointers(dA_displ, dA_array, ldda, p1, p1, batchCount);
magma_ddisplace_pointers(dW0_displ, dA_array, ldda, p2, p1, batchCount);
magmablas_dtrsm_work_batched(MagmaRight, MagmaLower, MagmaConjTrans, MagmaNonUnit,
1, n2, n1,
MAGMA_D_ONE,
dA_displ, ldda,
dW0_displ, ldda,
dX_array, n2,
dinvA_array, dinvA_length,
dW1_displ, dW2_displ,
dW3_displ, dW4_displ,
0, batchCount);
// update A22
//if(DEBUG==1) printf("calling update A22=A(%d,%d) using A21==A(%d,%d) with m=%d n=%d k=%d\n",p2,p2,p2,p1,n2,n2,n1);
magma_ddisplace_pointers(dA_displ, dA_array, ldda, p2, p1, batchCount);
magma_ddisplace_pointers(dW0_displ, dA_array, ldda, p2, p2, batchCount);
magmablas_dgemm_batched(MagmaNoTrans, MagmaConjTrans, n2, n2, n1,
alpha, dA_displ, ldda,
dA_displ, ldda,
beta, dW0_displ, ldda,
batchCount);
// panel on A22
//if(DEBUG==1) printf("calling recursive panel on A22=A(%d,%d) with n=%d min_recpnb %d\n",p2,p2,n2,min_recpnb);
magma_ddisplace_pointers(dA_displ, dA_array, ldda, p2, p2, batchCount);
magma_dpotrf_rectile_batched(
uplo, n2, n2, min_recpnb,
dA_displ, ldda,
dX_array, dX_length,
dinvA_array, dinvA_length,
dW0_displ, dW1_displ, dW2_displ,
dW3_displ, dW4_displ,
info_array, gbstep,
batchCount, myhandle);
}
if(m>n){
// TRSM on A3:
//if(DEBUG==1) printf("calling trsm AT THE END on A3=A(%d,%d): using A1222==A(%d,%d) with m=%d k=%d \n",n,0,0,0,m-n,n);
magma_ddisplace_pointers(dA_displ, dA_array, ldda, 0, 0, batchCount);
magma_ddisplace_pointers(dW0_displ, dA_array, ldda, n, 0, batchCount);
magmablas_dtrsm_work_batched(MagmaRight, MagmaLower, MagmaConjTrans, MagmaNonUnit,
1, m-n, n,
MAGMA_D_ONE,
dA_displ, ldda,
dW0_displ, ldda,
dX_array, m-n,
dinvA_array, dinvA_length,
dW1_displ, dW2_displ,
dW3_displ, dW4_displ,
0, batchCount);
}
magma_free(dA_displ);
return 0;
}
| [
"cjy7117@gmail.com"
] | cjy7117@gmail.com |
8533a4336175f9ee5d1e6bed19a9c3cb8da6e237 | 10377d9a5b1e2d451d07bb64d3981e936e1035d7 | /include/NumCpp/Functions/greater_equal.hpp | 4dc88fa5a4259b16380c0ef78614bc69fa62a6c5 | [
"MIT"
] | permissive | faichele/NumCpp | 03ac79cde618d6dfe08c3352fff7d235527a130f | 7c8fc50fbe44b80eaa105f0f9258120abddfcec2 | refs/heads/master | 2020-12-29T16:25:21.426391 | 2020-01-20T05:23:34 | 2020-01-20T05:23:34 | 238,668,660 | 0 | 0 | MIT | 2020-02-06T11:02:13 | 2020-02-06T11:02:12 | null | UTF-8 | C++ | false | false | 2,004 | hpp | /// @file
/// @author David Pilger <dpilger26@gmail.com>
/// [GitHub Repository](https://github.com/dpilger26/NumCpp)
/// @version 1.2
///
/// @section License
/// Copyright 2019 David Pilger
///
/// 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.
///
/// @section Description
/// Functions for working with NdArrays
///
#pragma once
#include "NumCpp/NdArray.hpp"
namespace nc
{
//============================================================================
// Method Description:
/// Return the truth value of (x1 >= x2) element-wise.
///
/// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.greater_equal.html
///
///
/// @param inArray1
/// @param inArray2
/// @return
/// NdArray
///
template<typename dtype>
NdArray<bool> greater_equal(const NdArray<dtype>& inArray1, const NdArray<dtype>& inArray2)
{
return inArray1 >= inArray2;
}
}
| [
"dpilger26@gmail.com"
] | dpilger26@gmail.com |
c4335096b953f9efeeea3d64b018ea0722800ac8 | 452cd2da6d866568579e8f82477295bb44ea03d6 | /Example/main_writer.cc | 96e0a87353f22dc15e37532e111bb566846610d9 | [] | no_license | nlurkin/XMLPreProcessor | 7cfd57cd3d1811aa5fcb329f401c6c47c7a796e8 | f45c19e498e907d4d9ac7161df3975d53c7b00ea | refs/heads/master | 2021-05-16T02:49:11.190499 | 2015-06-25T11:43:44 | 2015-06-25T11:43:44 | 34,051,860 | 1 | 1 | null | 2020-02-29T21:39:51 | 2015-04-16T11:26:01 | Python | UTF-8 | C++ | false | false | 628 | cc | /*
* main_writer.cc
*
* Created on: 18 Apr 2015
* Author: nlurkin
*/
#include "XMLConfWriter.h"
#include "ex_struct.h"
#include <iostream>
#include <cstring>
using namespace std;
int main(){
XMLConfWriter writer;
exampleStruct test;
test.version = 42;
strcpy(test.name, "my_example");
test.my_substruct.my_double = 5.5;
writer.createDocument("exampleStruct");
writer.addPathAsHex("exampleStruct.version", test.version);
writer.addPath("exampleStruct.name", test.name);
writer.addPath("exampleStruct.my_substruct.my_double", test.my_substruct.my_double);
writer.writeDocument("example_writer.xml");
}
| [
"nlurkin@debian"
] | nlurkin@debian |
351201f6c09a3c555bb0219e57cd5624c1ff0d71 | 1588f7002ebfaceb9c382c73fce67ab435d0e840 | /utils/src/PointNormal/NormalEstimator.h | e040ed5a8875721e368acf837d85a25e21cf37b6 | [] | no_license | akosiorek/Tagger3D | ff04ac94a7f3bc9c0a189cc972e7cd3dcdb900ae | 6459f41517710168080badbfc09e3ea1625c6a09 | refs/heads/master | 2016-09-05T19:47:32.612709 | 2014-10-14T18:46:44 | 2014-10-14T18:46:44 | 12,671,025 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 890 | h | /*
* Tagger3D : NormalEstimator.h
*
* Created on: 28 lip 2013
* Author: Adam Kosiorek
* Description:
*/
#ifndef NORMALESTIMATOR_H_
#define NORMALESTIMATOR_H_
#include "PointNormal.h"
#include <pcl/features/normal_3d_omp.h>
namespace Tagger3D {
class NormalEstimator: public PointNormal {
public:
NormalEstimator() = delete;
NormalEstimator(const std::map<std::string, std::string> &configMap);
virtual ~NormalEstimator() = default;
NormalCloud::Ptr computeNormals(const ColorCloud::Ptr &cloud);
NormalVec computeNormals(const ColorVec &clouds);
private:
void createNormalEstimator();
std::unique_ptr<pcl::NormalEstimationOMP<pcl::PointXYZRGB, pcl::Normal>> normalEstimator;
// Config keys
const std::string normalRadius = moduleName + "normalRadius";
const std::string kNN = moduleName + "kNN";
};
} /* namespace Tagger3D */
#endif /* NORMALESTIMATOR_H_ */
| [
"Kosiorek.Adam@gmail.com"
] | Kosiorek.Adam@gmail.com |
6e4bd73023694c8ba3f433e67544c9c54efccb04 | dd129fb6461d1b44dceb196caaa220e9f8398d18 | /topics/shared-memory/cat-mmap.cc | 442112c34208b3b218af5ab20f37f266448cde09 | [] | no_license | jfasch/jf-linux-trainings | 3af777b4c603dd5c3f6832c0034be44a062b493a | aebff2e6e0f98680aa14e1b7ad4a22e73a6f31b4 | refs/heads/master | 2020-04-29T19:13:33.398276 | 2020-03-29T20:45:33 | 2020-03-29T20:45:33 | 176,347,614 | 0 | 1 | null | 2019-10-01T06:02:49 | 2019-03-18T18:35:28 | C++ | UTF-8 | C++ | false | false | 683 | cc | #include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <cassert>
int main(int argc, char** argv)
{
if (argc != 2) {
std::cerr << "Usage: " << argv[0] << " <filename>" << std::endl;
exit(1);
}
int fd = open(argv[1], O_RDONLY);
if (fd == -1) {
perror("open");
exit(1);
}
// determine file size, mmap, and finally output
off_t len = lseek(fd, 0, SEEK_END);
void *mem = mmap(NULL, len, PROT_READ, MAP_PRIVATE, fd, 0);
ssize_t nwritten = write(STDOUT_FILENO, mem, len);
assert(nwritten == len);
return 0;
}
| [
"jf@faschingbauer.co.at"
] | jf@faschingbauer.co.at |
05e3a0a1e6de3db461fa4c0fe23f100de76a3ee1 | 45a26f28a29ab6dd9d3bcf315117d814f50808b1 | /src/AppleSMBIOS/AppleSMBIOS-41/AppleSMBIOS.cpp | a26a5c96df9e4f1d39bf1ffb5388ce011f6669e8 | [] | no_license | zeborrego/opensource.apple.com | 0eb9161029ce8440dbdc4b5157b3927a6e381f8d | 88cbaab4a42e97cbbfe6b660f2f0945536821be6 | refs/heads/master | 2021-07-06T17:16:28.241638 | 2017-10-02T11:58:56 | 2017-10-02T11:58:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 34,266 | cpp | /*
* Copyright (c) 1998-2009 Apple Computer, Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* The contents of this file constitute Original Code as defined in and
* are subject to the Apple Public Source License Version 2.0 (the
* "License"). You may not use this file except in compliance with the
* License. Please obtain a copy of the License at
* http://www.apple.com/publicsource and read it before using this file.
*
* This Original Code and all software distributed under the License are
* distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
* License for the specific language governing rights and limitations
* under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#include <i386/cpuid.h>
#include <IOKit/IOPlatformExpert.h>
#include <IOKit/IOMemoryDescriptor.h>
#include <IOKit/IODeviceTreeSupport.h>
#include <IOKit/pci/IOPCIBridge.h> // IOPCIAddressSpace
#include <IOKit/acpi/IOACPIPlatformDevice.h>
#include <string.h>
#include <libkern/version.h>
#include "AppleSMBIOS.h"
#if DEBUG
#define DEBUG_LOG(args...) IOLog(args)
#else
#define DEBUG_LOG(args...)
#endif
//---------------------------------------------------------------------------
// SMBPackedStrings class
class SMBPackedStrings
{
protected:
const char * _start;
const char * _limit;
public:
SMBPackedStrings( const SMBStructHeader * header, const void * limit );
SMBPackedStrings( const SMBStructHeader * header );
const char * stringAtIndex( UInt8 index, UInt8 * length = 0 ) const;
void setDataProperty( IORegistryEntry * entry,
const char * key,
UInt8 index ) const;
void setStringProperty( IORegistryEntry * entry,
const char * key,
UInt8 index ) const;
};
SMBPackedStrings::SMBPackedStrings( const SMBStructHeader * header,
const void * limit )
{
_start = (const char *) header + header->length;
_limit = (const char *) limit;
}
SMBPackedStrings::SMBPackedStrings( const SMBStructHeader * header )
{
_start = (const char *) header + header->length;
const char * cp = _start;
// Find the double null at the end of the record
while( cp[0] || cp[1]) cp++;
_limit = &cp[1];
}
const char * SMBPackedStrings::stringAtIndex( UInt8 index, UInt8 * length ) const
{
const char * last = 0;
const char * next = _start;
if ( length ) *length = 0;
while ( index-- )
{
last = 0;
for ( const char * cp = next; cp < _limit; cp++ )
{
if ( *cp == '\0' )
{
last = next;
next = cp + 1;
break;
}
}
if ( last == 0 ) break;
}
if ( last )
{
while (*last == ' ') last++;
if (length)
{
UInt8 len;
for ( len = next - last - 1; len && last[len - 1] == ' '; len-- )
;
*length = len; // number of chars not counting the terminating NULL
}
}
return last ? last : "";
}
void SMBPackedStrings::setDataProperty( IORegistryEntry * entry,
const char * key,
UInt8 index ) const
{
UInt8 length;
const char * string = SMBPackedStrings::stringAtIndex(index, &length);
if (length)
{
OSData * data = OSData::withCapacity(length + 1);
if (data)
{
data->appendBytes(string, length);
data->appendByte('\0', 1);
entry->setProperty(key, data);
data->release();
}
}
}
void SMBPackedStrings::setStringProperty( IORegistryEntry * entry,
const char * key,
UInt8 index ) const
{
UInt8 length;
const char * string = SMBPackedStrings::stringAtIndex(index, &length);
if (length)
{
OSString * strObj = OSString::withCString(string);
if (strObj)
{
entry->setProperty(key, strObj);
strObj->release();
}
}
}
#define super IOService
OSDefineMetaClassAndStructors( AppleSMBIOS, IOService )
//---------------------------------------------------------------------------
bool AppleSMBIOS::start( IOService * provider )
{
OSSerializer * serializer;
if (super::start(provider) != true ||
IOService::getResourceService() == 0 ||
IOService::getResourceService()->getProperty("SMBIOS"))
{
return false;
}
SMBIOSTable = NULL;
SMBIOSTableLength = 0;
fSlotQueueHead = IONew(queue_head_t, 1);
if (!fSlotQueueHead)
return false;
queue_init(fSlotQueueHead);
// Get the IOPlatformExpertDevice
fRoot = getServiceRoot();
if (!provider || !fRoot)
return false;
// Serialize SMBIOS structures to user-space on demand
serializer = OSSerializer::forTarget((void *) this, &serializeSMBIOS);
if (!serializer)
return false;
setProperty("SMBIOS", serializer);
memInfoSource = kNoMemoryInfo;
memSlotsData = OSData::withCapacity(kMemDataSize);
memTypesData = OSData::withCapacity(kMemDataSize);
memSizesData = OSData::withCapacity(kMemDataSize);
memSpeedData = OSData::withCapacity(kMemDataSize);
memInfoData = OSData::withCapacity(kMemDataSize);
memManufData = OSData::withCapacity(kMemDataSize);
memSerialData = OSData::withCapacity(kMemDataSize);
memPartData = OSData::withCapacity(kMemDataSize);
memSizeTotal = 0;
if (!memSlotsData || !memTypesData || !memSizesData || !memSpeedData ||
!memInfoData || !memManufData || !memSerialData || !memPartData)
return false;
if (!findSMBIOSTableEFI())
{
return false;
}
// Update device tree
updateDeviceTree();
publishResource("SMBIOS");
registerService();
return true;
}
//---------------------------------------------------------------------------
#define RELEASE(x) do { if (x) { (x)->release(); (x) = 0; } } while(0)
void AppleSMBIOS::free( void )
{
RELEASE( memSlotsData );
RELEASE( memTypesData );
RELEASE( memSizesData );
RELEASE( memSpeedData );
RELEASE( memInfoData );
RELEASE( memManufData );
RELEASE( memSerialData );
RELEASE( memPartData );
RELEASE( fDMIMemoryMap );
if (fSlotQueueHead)
{
SystemSlotEntry * slotEntry;
while (!queue_empty(fSlotQueueHead))
{
queue_remove_first(fSlotQueueHead, slotEntry, SystemSlotEntry *,
chain);
IODelete(slotEntry, SystemSlotEntry, 1);
}
IODelete(fSlotQueueHead, queue_head_t, 1);
fSlotQueueHead = 0;
}
super::free();
}
//---------------------------------------------------------------------------
bool AppleSMBIOS::
serializeSMBIOS( void * target, void * refcon, OSSerialize * s )
{
AppleSMBIOS * me = (AppleSMBIOS *) target;
OSData * data;
IOMemoryMap * map;
bool ok = false;
map = me->fDMIMemoryMap;
if (map)
{
data = OSData::withBytesNoCopy(
(void *) map->getVirtualAddress(), map->getLength());
if (data)
{
ok = data->serialize(s);
data->release();
}
}
return ok;
}
//---------------------------------------------------------------------------
static UInt8 checksum8( void * start, UInt length )
{
UInt8 csum = 0;
UInt8 * cp = (UInt8 *) start;
for (UInt i = 0; i < length; i++)
csum += *cp++;
return csum;
}
#define kGenericPCISlotName "PCI Slot"
//---------------------------------------------------------------------------
OSData * AppleSMBIOS::
getSlotNameWithSlotId( int slotId )
{
char name[80];
SystemSlotEntry * slot = 0;
SystemSlotEntry * iter;
queue_iterate(fSlotQueueHead, iter, SystemSlotEntry *, chain)
{
if ((iter->slotID & 0xff) == slotId)
{
slot = iter;
break;
}
}
if (slot && slot->slotName)
{
strncpy(name, slot->slotName, sizeof(name));
}
else
{
// No matching SlotId, return a generic PCI slot name
snprintf(name, sizeof(name), "%s %u", kGenericPCISlotName, slotId);
}
name[sizeof(name) - 1] = '\0';
return OSData::withBytes(name, strlen(name) + 1);
}
#define EFI_SMBIOS_TABLE \
"/efi/configuration-table/EB9D2D31-2D88-11D3-9A16-0090273FC14D"
//---------------------------------------------------------------------------
bool AppleSMBIOS::findSMBIOSTableEFI( void )
{
IORegistryEntry * tableEntry;
OSData * tableData;
UInt64 tableAddr;
IOMemoryDescriptor * epsMemory;
SMBEntryPoint eps;
IOMemoryDescriptor * dmiMemory = 0;
IOItemCount dmiStructureCount = 0;
tableEntry = fromPath(EFI_SMBIOS_TABLE, gIODTPlane);
if (tableEntry)
{
tableAddr = 0;
tableData = OSDynamicCast(OSData, tableEntry->getProperty("table"));
if (tableData && (tableData->getLength() <= sizeof(tableAddr)))
{
bcopy(tableData->getBytesNoCopy(), &tableAddr, tableData->getLength());
// For SnowLeopard and beyond include the kIOMemoryMapperNone option.
#if VERSION_MAJOR >= 10
IOOptionBits options = kIODirectionOutIn | kIOMemoryMapperNone;
#else
IOOptionBits options = kIODirectionOutIn;
#endif
epsMemory = IOMemoryDescriptor::withAddressRange(
(mach_vm_address_t) tableAddr,
(mach_vm_size_t) sizeof(eps),
options,
NULL );
if (epsMemory)
{
bzero(&eps, sizeof(eps));
epsMemory->readBytes(0, &eps, sizeof(eps));
setProperty("SMBIOS-EPS", (void *) &eps, sizeof(eps));
if (memcmp(eps.anchor, "_SM_", 4) == 0)
{
UInt8 csum;
csum = checksum8(&eps, sizeof(eps));
DEBUG_LOG("DMI checksum = 0x%x\n", csum);
DEBUG_LOG("DMI tableLength = %d\n",
eps.dmi.tableLength);
DEBUG_LOG("DMI tableAddress = 0x%x\n",
(uint32_t) eps.dmi.tableAddress);
DEBUG_LOG("DMI structureCount = %d\n",
eps.dmi.structureCount);
DEBUG_LOG("DMI bcdRevision = %x\n",
eps.dmi.bcdRevision);
if (csum == 0 && eps.dmi.tableLength &&
eps.dmi.structureCount)
{
dmiStructureCount = eps.dmi.structureCount;
dmiMemory = IOMemoryDescriptor::withPhysicalAddress(
eps.dmi.tableAddress, eps.dmi.tableLength,
kIODirectionOutIn );
}
else
{
DEBUG_LOG("No DMI structure found\n");
}
}
epsMemory->release();
epsMemory = 0;
}
}
tableEntry->release();
}
if ( dmiMemory )
{
fDMIMemoryMap = dmiMemory->map();
if (fDMIMemoryMap)
{
SMBIOSTable = (void *) fDMIMemoryMap->getVirtualAddress();
SMBIOSTableLength = fDMIMemoryMap->getLength();
decodeSMBIOSTable((void *) fDMIMemoryMap->getVirtualAddress(),
fDMIMemoryMap->getLength(), dmiStructureCount );
}
dmiMemory->release();
dmiMemory = 0;
}
return (fDMIMemoryMap != 0);
}
//---------------------------------------------------------------------------
void AppleSMBIOS::
adjustPCIDeviceEFI( IOService * pciDevice )
{
IOACPIPlatformDevice * acpiDevice;
UInt32 slotNum;
OSString * acpiPath;
IORegistryEntry * acpiEntry = NULL;
// Does PCI device have an ACPI alias?
// N : not built-in, no slot name, exit
// Y : goto next
//
// Does ACPI device have a _SUN object?
// N : it's a built in PCI device
// Y : indicates a slot (not built-in), goto next
//
// Match _SUN value against SlotId in SMBIOS PCI slot structures
do {
acpiPath = OSDynamicCast(OSString, pciDevice->getProperty("acpi-path"));
if (!acpiPath)
break;
acpiEntry = fromPath(acpiPath->getCStringNoCopy());
if (!acpiEntry)
break;
if (!acpiEntry->metaCast("IOACPIPlatformDevice"))
break;
acpiDevice = (IOACPIPlatformDevice *) acpiEntry;
if (acpiDevice->evaluateInteger("_SUN", &slotNum) == kIOReturnSuccess)
{
OSObject * name = getSlotNameWithSlotId(slotNum);
if (name)
{
pciDevice->setProperty("AAPL,slot-name", name);
name->release();
}
}
else if (acpiDevice->validateObject("_RMV") == kIOReturnSuccess)
{
// no slot name?
}
else
{
char dummy = '\0';
pciDevice->setProperty("built-in", &dummy, 1);
}
} while (false);
if (acpiEntry)
acpiEntry->release();
}
//---------------------------------------------------------------------------
IOReturn AppleSMBIOS::
callPlatformFunction( const char * functionName,
bool waitForFunction,
void * param1, void * param2,
void * param3, void * param4 )
{
if (!functionName)
return kIOReturnBadArgument;
// AdjustPCIBridge function is called by the ACPI
// platform driver, but is not useful on EFI systems.
if (!strcmp(functionName, "AdjustPCIDevice"))
{
IOService * device = (IOService *) param1;
if (device)
{
adjustPCIDeviceEFI(device);
return kIOReturnSuccess;
}
}
return kIOReturnUnsupported;
}
//---------------------------------------------------------------------------
void AppleSMBIOS::decodeSMBIOSTable( const void * tableData,
UInt16 tableLength,
UInt16 structureCount )
{
const SMBStructHeader * header;
const UInt8 * next = (const UInt8 *) tableData;
const UInt8 * end = next + tableLength;
while ( structureCount-- && (end > next + sizeof(SMBStructHeader)) )
{
header = (const SMBStructHeader *) next;
if (header->length > end - next) break;
decodeSMBIOSStructure( header, end );
// Skip the formatted area of the structure.
next += header->length;
// Skip the unformatted structure area at the end (strings).
// Look for a terminating double NULL.
for ( ; end > next + sizeof(SMBStructHeader); next++ )
{
if ( next[0] == 0 && next[1] == 0 )
{
next += 2; break;
}
}
}
}
//---------------------------------------------------------------------------
void AppleSMBIOS::
decodeSMBIOSStructure( const SMBStructHeader * structureHeader,
const void * tableBoundary )
{
const union SMBStructUnion {
SMBBIOSInformation bios;
SMBSystemInformation system;
SMBBaseBoard baseBoard;
SMBMemoryModule memoryModule;
SMBSystemSlot slot;
SMBPhysicalMemoryArray memoryArray;
SMBMemoryDevice memoryDevice;
SMBFirmwareVolume fv;
SMBMemorySPD spd;
} * u = (const SMBStructUnion *) structureHeader;
SMBPackedStrings strings = SMBPackedStrings( structureHeader,
tableBoundary );
switch ( structureHeader->type )
{
case kSMBTypeBIOSInformation:
processSMBIOSStructureType0( &u->bios, &strings );
break;
case kSMBTypeSystemInformation:
processSMBIOSStructureType1( &u->system, &strings );
break;
case kSMBTypeBaseBoard:
processSMBIOSStructureType2( &u->baseBoard, &strings );
break;
case kSMBTypeMemoryModule:
processSMBIOSStructureType6( &u->memoryModule, &strings );
break;
case kSMBTypeSystemSlot:
processSMBIOSStructureType9( &u->slot, &strings );
break;
case kSMBTypePhysicalMemoryArray:
processSMBIOSStructureType16( &u->memoryArray, &strings );
break;
case kSMBTypeMemoryDevice:
processSMBIOSStructureType17( &u->memoryDevice, &strings );
break;
case kSMBTypeFirmwareVolume:
processSMBIOSStructureType128( &u->fv, &strings );
break;
case kSMBTypeMemorySPD:
processSMBIOSStructureType130( &u->spd, &strings );
break;
}
}
//---------------------------------------------------------------------------
bool AppleSMBIOS::findSMBIOSStructure(
SMBAnchor * anchor, uint8_t inType, uint32_t minSize )
{
const SMBStructHeader * header;
const uint8_t * next;
const uint8_t * end;
bool found = false;
if (!fDMIMemoryMap || !anchor)
return false;
if (anchor->next == NULL)
next = (const UInt8 *) fDMIMemoryMap->getVirtualAddress();
else
next = anchor->next;
end = (const UInt8 *) fDMIMemoryMap->getVirtualAddress() +
fDMIMemoryMap->getLength();
while (end > next + sizeof(SMBStructHeader))
{
header = (const SMBStructHeader *) next;
if (header->length > end - next) break;
// Skip the formatted area of the structure
next += header->length;
// Skip the unformatted structure area at the end (strings).
// Look for a terminating double NULL.
for ( ; end > next + sizeof(SMBStructHeader); next++ )
{
if ( next[0] == 0 && next[1] == 0 )
{
next += 2;
break;
}
}
if ((header->type == inType) && (header->length >= minSize))
{
anchor->header = header;
anchor->next = next;
anchor->end = end;
found = true;
break;
}
}
return found;
}
//---------------------------------------------------------------------------
void AppleSMBIOS::processSMBIOSStructureType0(
const SMBBIOSInformation * bios,
SMBPackedStrings * strings )
{
char location[9];
if (bios->header.length < sizeof(SMBBIOSInformation))
return;
if (!fROMNode)
{
fROMNode = OSTypeAlloc( IOService );
if (fROMNode && (false == fROMNode->init()))
{
fROMNode->release();
fROMNode = 0;
}
}
if (fROMNode)
{
snprintf(location, sizeof(location), "%x", bios->startSegment << 4);
fROMNode->setLocation(location);
strings->setDataProperty(fROMNode, "vendor", bios->vendor);
strings->setDataProperty(fROMNode, "version", bios->version);
strings->setDataProperty(fROMNode, "release-date", bios->releaseDate);
strings->setDataProperty(fROMNode, "characteristics",
bios->characteristics);
fROMNode->setProperty("rom-size", (bios->romSize + 1) * 0x10000, 32 );
}
}
//---------------------------------------------------------------------------
void AppleSMBIOS::processSMBIOSStructureType1(
const SMBSystemInformation * sys,
SMBPackedStrings * strings )
{
UInt8 serialNumberLength;
if (sys->header.length < 8)
return;
strings->setDataProperty(fRoot, "manufacturer", sys->manufacturer);
strings->setDataProperty(fRoot, "product-name", sys->productName);
strings->setDataProperty(fRoot, "version", sys->version);
// Platform driver took care of this.
if (fRoot->getProperty(kIOPlatformSerialNumberKey))
return;
const char *serialNumberString = strings->stringAtIndex(
sys->serialNumber, &serialNumberLength);
if ((serialNumberLength >= 3) && (serialNumberLength < 30))
{
// Map 11 or 12 digit serial number string read from SMBIOS to a
// 43-byte "serial-number" data object. Must also handle systems
// without a valid serial number string, e.g. "System Serial#".
OSData * data = OSData::withCapacity(43);
if (data)
{
int clen = (12 == serialNumberLength) ? 4 : 3;
data->appendBytes(serialNumberString + (serialNumberLength - clen), clen);
data->appendBytes('\0', 13 - clen);
data->appendBytes(serialNumberString, serialNumberLength);
data->appendBytes('\0', 43 - 13 - serialNumberLength);
fRoot->setProperty("serial-number", data);
data->release();
}
}
strings->setStringProperty(fRoot, kIOPlatformSerialNumberKey, sys->serialNumber);
}
//---------------------------------------------------------------------------
void AppleSMBIOS::processSMBIOSStructureType2(
const SMBBaseBoard * baseBoard,
SMBPackedStrings * strings )
{
if (baseBoard->header.length < sizeof(SMBBaseBoard))
{
kprintf("AppleSMBIOS: invalid type 2 record size: %d, expected %ld\n",
baseBoard->header.length, sizeof(SMBBaseBoard)+1);
return;
}
// If this type 2 record is for the processor and memory board then it is
// a riser card. Grab the serial number and publish it to the registry.
if ((baseBoard->boardType & kSMBBaseBoardProcessorMemoryModule) == kSMBBaseBoardProcessorMemoryModule)
{
UInt8 length = 0;
strings->stringAtIndex(baseBoard->serialNumber, &length);
if (length == 0)
IOLog("AppleSMBIOS: processor/memory board serial number is empty\n");
else
strings->setStringProperty(fRoot, "processor-memory-board-serial-number", baseBoard->serialNumber);
}
}
//---------------------------------------------------------------------------
void AppleSMBIOS::processSMBIOSStructureType6(
const SMBMemoryModule * memory,
SMBPackedStrings * strings )
{
UInt8 socketLength;
const char * socketString;
UInt8 memorySize;
union {
UInt64 ull;
UInt32 ul[2];
} memoryBytes;
if (memory->header.length < sizeof(SMBMemoryModule))
return;
if (memInfoSource == kMemoryDeviceInfo)
return;
memInfoSource = kMemoryModuleInfo;
// update memSlotsData
socketString = strings->stringAtIndex( memory->socketDesignation,
&socketLength );
if ( socketString )
{
if (memSlotsData->getLength() == 0)
memSlotsData->appendBytes(" ", 4);
if (socketLength)
memSlotsData->appendBytes( socketString, socketLength );
memSlotsData->appendByte('\0', 1);
}
// update memTypesData
memTypesData->appendBytes("DRAM", 5);
// update memSizesData
memorySize = memory->enabledSize & 0x7F;
if (memorySize >= kSMBMemoryModuleSizeNotDeterminable)
memoryBytes.ull = 0;
else
memoryBytes.ull = (1ULL << memorySize) * (1024 * 1024);
memSizeTotal += memoryBytes.ull;
memSizesData->appendBytes( &memoryBytes.ul[1], 4 );
memSizesData->appendBytes( &memoryBytes.ul[0], 4 );
}
//---------------------------------------------------------------------------
void AppleSMBIOS::processSMBIOSStructureType9(
const SMBSystemSlot * slot,
SMBPackedStrings * strings )
{
SystemSlotEntry * slotEntry;
if (slot->header.length < 12)
return;
slotEntry = IONew(SystemSlotEntry, 1);
if (slotEntry)
{
memset(slotEntry, 0, sizeof(*slotEntry));
slotEntry->slotID = slot->slotID;
slotEntry->slotType = slot->slotType;
slotEntry->slotUsage = slot->currentUsage;
slotEntry->slotName = strings->stringAtIndex(slot->slotDesignation);
queue_enter(fSlotQueueHead, slotEntry, SystemSlotEntry *, chain);
}
DEBUG_LOG("Slot type %x, width %x, usage %x, ID %x, char1 %x\n",
slot->slotType, slot->slotDataBusWidth, slot->currentUsage,
slot->slotID, slot->slotCharacteristics1);
}
//---------------------------------------------------------------------------
void AppleSMBIOS::processSMBIOSStructureType16(
const SMBPhysicalMemoryArray * memory,
SMBPackedStrings * strings )
{
if (memory->header.length < sizeof(SMBPhysicalMemoryArray))
return;
if ((memory->arrayUse == kSMBMemoryArrayUseSystemMemory) &&
((memory->errorCorrection == kSMBMemoryArrayErrorCorrectionTypeSingleBitECC) ||
(memory->errorCorrection == kSMBMemoryArrayErrorCorrectionTypeMultiBitECC)))
{
memECCEnabled = true;
}
}
//---------------------------------------------------------------------------
void AppleSMBIOS::processSMBIOSStructureType17(
const SMBMemoryDevice * memory,
SMBPackedStrings * strings )
{
UInt8 deviceLocatorLength;
const char * deviceLocatorString;
UInt8 bankLocatorLength;
const char * bankLocatorString;
UInt8 stringLength;
const char * string;
UInt8 memoryType;
union {
UInt64 ull;
UInt32 ul[2];
} memoryBytes;
if (memory->header.length < 21)
return;
if (memInfoSource == kMemoryModuleInfo)
{
memSlotsData->initWithCapacity(kMemDataSize);
memTypesData->initWithCapacity(kMemDataSize);
memSizesData->initWithCapacity(kMemDataSize);
memSpeedData->initWithCapacity(kMemDataSize);
memManufData->initWithCapacity(kMemDataSize);
memSerialData->initWithCapacity(kMemDataSize);
memPartData->initWithCapacity(kMemDataSize);
memSizeTotal = 0;
}
memInfoSource = kMemoryDeviceInfo;
// update memSlotsData
deviceLocatorString = strings->stringAtIndex( memory->deviceLocator,
&deviceLocatorLength );
bankLocatorString = strings->stringAtIndex( memory->bankLocator,
&bankLocatorLength );
// Device location is mandatory, but bank location is optional.
if (!memory->deviceLocator || !deviceLocatorLength )
{
// Dummy device location string
deviceLocatorString = "Location";
deviceLocatorLength = strlen(deviceLocatorString);
}
if ( deviceLocatorLength )
{
if ( memSlotsData->getLength() == 0 )
memSlotsData->appendBytes(" ", 4);
if ( bankLocatorLength )
{
memSlotsData->appendBytes( bankLocatorString, bankLocatorLength );
memSlotsData->appendByte('/', 1);
}
memSlotsData->appendBytes( deviceLocatorString, deviceLocatorLength );
memSlotsData->appendByte('\0', 1);
}
// update memTypesData
memoryType = memory->memoryType;
if ( memoryType > kSMBMemoryDeviceTypeCount - 1 )
memoryType = 0x02; // unknown type
memTypesData->appendBytes( SMBMemoryDeviceTypes[memoryType],
strlen(SMBMemoryDeviceTypes[memoryType]) + 1 );
// update memSizesData
memoryBytes.ull = (memory->memorySize & 0x7fff) * 1024;
if ((memory->memorySize & 0x8000) == 0)
memoryBytes.ull *= 1024;
memSizeTotal += memoryBytes.ull;
memSizesData->appendBytes( &memoryBytes.ul[1], 4 );
memSizesData->appendBytes( &memoryBytes.ul[0], 4 );
if (memory->header.length >= 27)
{
char speedText[16];
snprintf(speedText, sizeof(speedText), "%u MHz", memory->memorySpeed);
memSpeedData->appendBytes(speedText, strlen(speedText) + 1);
}
string = strings->stringAtIndex( memory->manufacturer, &stringLength );
memManufData->appendBytes( string, stringLength + 1 );
string = strings->stringAtIndex( memory->serialNumber, &stringLength );
memSerialData->appendBytes( string, stringLength + 1 );
string = strings->stringAtIndex( memory->partNumber, &stringLength );
memPartData->appendBytes( string, stringLength + 1 );
// What about "available", "mem-info" prop?
}
//---------------------------------------------------------------------------
void AppleSMBIOS::processSMBIOSStructureType128(
const SMBFirmwareVolume * fv,
SMBPackedStrings * strings )
{
const FW_REGION_INFO * regionInfo = NULL;
if (fv->header.length < sizeof(SMBFirmwareVolume))
return;
for (int i = 0; i < fv->RegionCount; i++)
{
if (fv->RegionType[i] == FW_REGION_MAIN)
{
regionInfo = &fv->FlashMap[i];
break;
}
}
if (regionInfo && (regionInfo->EndAddress > regionInfo->StartAddress))
{
if (!fROMNode)
{
fROMNode = OSTypeAlloc( IOService );
if (fROMNode && (false == fROMNode->init()))
{
fROMNode->release();
fROMNode = 0;
}
}
if (fROMNode)
{
fROMNode->setProperty("fv-main-address",
regionInfo->StartAddress, 32 );
fROMNode->setProperty("fv-main-size",
regionInfo->EndAddress - regionInfo->StartAddress + 1, 32 );
}
}
}
//---------------------------------------------------------------------------
void AppleSMBIOS::processSMBIOSStructureType130(
const SMBMemorySPD * spd,
SMBPackedStrings * strings )
{
unsigned int dataSize;
if(spd->Offset > 127) return; // Only care about the first 128 bytes of spd data
dataSize = (spd->Size + spd->Offset) > 128 ? 128 - spd->Offset : spd->Size;
memInfoData->appendBytes(spd->Data, dataSize);
}
//---------------------------------------------------------------------------
void AppleSMBIOS::updateDeviceTree( void )
{
SMBAnchor anchor;
uint32_t busSpeedMTs = 0;
uint32_t itcSpeedMTs = 0;
uint32_t cpuSpeedMHz = 0;
SMBWord cpuType = 0;
IOService * memoryNode = OSTypeAlloc( IOService );
if (memoryNode && (false == memoryNode->init()))
{
memoryNode->release();
memoryNode = 0;
}
if (memoryNode)
{
memoryNode->setName("memory");
//memoryNode->setLocation("0");
memoryNode->setProperty( "slot-names", memSlotsData );
memoryNode->setProperty( "dimm-types", memTypesData );
memoryNode->setProperty( "reg", memSizesData );
if (memSpeedData->getLength())
{
memoryNode->setProperty( "dimm-speeds", memSpeedData );
}
if (memInfoData->getLength() == 0)
{
memInfoData->appendBytes(0, (memSizesData->getLength() / 8) * 128);
}
memoryNode->setProperty( "dimm-info", memInfoData );
if (memManufData->getLength())
memoryNode->setProperty( "dimm-manufacturer", memManufData );
if (memSerialData->getLength())
memoryNode->setProperty( "dimm-serial-number", memSerialData );
if (memPartData->getLength())
memoryNode->setProperty( "dimm-part-number", memPartData );
memoryNode->setProperty( "ecc-enabled",
memECCEnabled ? kOSBooleanTrue : kOSBooleanFalse );
memoryNode->attachToParent( fRoot, gIODTPlane );
memoryNode->release();
}
// Update max_mem kernel variable with the total size of installed RAM
if (memSizeTotal && (memSizeTotal > max_mem))
{
UInt32 bootMaxMem = 0;
if (PE_parse_boot_argn("maxmem", &bootMaxMem, sizeof(bootMaxMem)) && bootMaxMem)
{
UInt64 limit = ((UInt64) bootMaxMem) * 1024ULL * 1024ULL;
if (memSizeTotal > limit)
memSizeTotal = limit;
}
max_mem = memSizeTotal;
}
if (fROMNode)
{
fROMNode->setName("rom");
fROMNode->attachToParent( fRoot, gIODTPlane );
fROMNode->release();
fROMNode = 0;
}
// Fetch Processor Type from Type 131 structure (optional).
SMB_ANCHOR_RESET(&anchor);
if (findSMBIOSStructure(&anchor, kSMBTypeOemProcessorType,
sizeof(SMBOemProcessorType)))
{
const SMBOemProcessorType * processorType =
(const SMBOemProcessorType *) anchor.header;
cpuType = processorType->ProcessorType;
DEBUG_LOG("SMBIOS: processor type = 0x%04x\n", cpuType);
}
// Fetch bus transfer rate from Type 132 structure (optional).
SMB_ANCHOR_RESET(&anchor);
if (findSMBIOSStructure(&anchor, kSMBTypeOemProcessorBusSpeed,
sizeof(SMBOemProcessorBusSpeed)))
{
const SMBOemProcessorBusSpeed * speed =
(const SMBOemProcessorBusSpeed *) anchor.header;
busSpeedMTs = itcSpeedMTs = speed->ProcessorBusSpeed;
DEBUG_LOG("SMBIOS: Bus speed (MT/s) = %u\n", busSpeedMTs);
}
// Fetch cpu and bus nominal frequencies.
SMB_ANCHOR_RESET(&anchor);
if (findSMBIOSStructure(&anchor, kSMBTypeProcessorInformation,
kSMBProcessorInformationMinSize))
{
const SMBProcessorInformation * cpuInfo =
(const SMBProcessorInformation *) anchor.header;
cpuSpeedMHz = cpuInfo->maximumClock;
DEBUG_LOG("SMBIOS: CPU speed (MHz) = %u\n", cpuSpeedMHz);
if (busSpeedMTs == 0)
{
busSpeedMTs = cpuInfo->externalClock;
busSpeedMTs *= 4; // Assume quad-pumped FSB
DEBUG_LOG("SMBIOS: FSB speed (MT/s) = %u\n", busSpeedMTs);
}
}
if (busSpeedMTs)
{
uint64_t rateInTs = ((uint64_t) busSpeedMTs) * 1000000ULL;
gPEClockFrequencyInfo.bus_frequency_hz = rateInTs;
gPEClockFrequencyInfo.bus_frequency_min_hz = rateInTs;
gPEClockFrequencyInfo.bus_frequency_max_hz = rateInTs;
gPEClockFrequencyInfo.bus_clock_rate_hz =
(rateInTs < (1ULL << 32)) ? (uint32_t) rateInTs : 0xFFFFFFFF;
}
if (cpuSpeedMHz)
{
uint64_t rateInHz = ((uint64_t) cpuSpeedMHz) * 1000000ULL;
gPEClockFrequencyInfo.cpu_frequency_max_hz = rateInHz;
gPEClockFrequencyInfo.cpu_frequency_min_hz = rateInHz;
gPEClockFrequencyInfo.cpu_frequency_hz = rateInHz;
gPEClockFrequencyInfo.cpu_clock_rate_hz = rateInHz;
}
if (cpuType || itcSpeedMTs)
{
IORegistryEntry * cpus;
IORegistryEntry * child;
IORegistryIterator * iter;
cpus = IORegistryEntry::fromPath("/cpus", gIODTPlane);
if (cpus && itcSpeedMTs)
{
uint64_t rateInTs = ((uint64_t) itcSpeedMTs) * 1000000ULL;
cpus->setProperty(
"interconnect-speed", &rateInTs,
sizeof(rateInTs));
}
if (cpus && cpuType)
{
iter = IORegistryIterator::iterateOver( cpus, gIODTPlane );
if (iter)
{
while ((child = iter->getNextObject()))
{
child->setProperty(
"cpu-type", (void *) &cpuType,
sizeof(cpuType));
}
iter->release();
}
}
if (cpus)
cpus->release();
}
}
| [
"mattl@cnuk.org"
] | mattl@cnuk.org |
7b8642e5d85671ce529dcac2a3788cd258953f5b | e2df82085ac658a7ca7c974919f3809e89d646bb | /LibWebRtcUsingExample/Include/rtc_base/signalthread.h | 2c11da4507c4eece4f18dae6e93aaa9f879d5cd7 | [
"Apache-2.0",
"MIT"
] | permissive | HATTER-LONG/NoteBook_WebRtcLearning | 7c846cf548804361123ff9cd6017cc05b3b9a559 | 834c94c82646e57d53fa5f1cc8210dda3799b78f | refs/heads/master | 2023-06-30T21:45:56.672079 | 2021-08-07T08:46:34 | 2021-08-07T08:46:34 | 338,822,304 | 3 | 2 | null | 2021-02-14T14:33:08 | 2021-02-14T14:22:12 | null | UTF-8 | C++ | false | false | 5,398 | h | /*
* Copyright 2004 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef RTC_BASE_SIGNALTHREAD_H_
#define RTC_BASE_SIGNALTHREAD_H_
#include <string>
#include "rtc_base/checks.h"
#include "rtc_base/constructormagic.h"
#include "rtc_base/nullsocketserver.h"
#include "rtc_base/sigslot.h"
#include "rtc_base/thread.h"
namespace rtc {
///////////////////////////////////////////////////////////////////////////////
// SignalThread - Base class for worker threads. The main thread should call
// Start() to begin work, and then follow one of these models:
// Normal: Wait for SignalWorkDone, and then call Release to destroy.
// Cancellation: Call Release(true), to abort the worker thread.
// Fire-and-forget: Call Release(false), which allows the thread to run to
// completion, and then self-destruct without further notification.
// Periodic tasks: Wait for SignalWorkDone, then eventually call Start()
// again to repeat the task. When the instance isn't needed anymore,
// call Release. DoWork, OnWorkStart and OnWorkStop are called again,
// on a new thread.
// The subclass should override DoWork() to perform the background task. By
// periodically calling ContinueWork(), it can check for cancellation.
// OnWorkStart and OnWorkDone can be overridden to do pre- or post-work
// tasks in the context of the main thread.
///////////////////////////////////////////////////////////////////////////////
class SignalThread
: public sigslot::has_slots<>,
protected MessageHandler {
public:
SignalThread();
// Context: Main Thread. Call before Start to change the worker's name.
bool SetName(const std::string& name, const void* obj);
// Context: Main Thread. Call to begin the worker thread.
void Start();
// Context: Main Thread. If the worker thread is not running, deletes the
// object immediately. Otherwise, asks the worker thread to abort processing,
// and schedules the object to be deleted once the worker exits.
// SignalWorkDone will not be signalled. If wait is true, does not return
// until the thread is deleted.
void Destroy(bool wait);
// Context: Main Thread. If the worker thread is complete, deletes the
// object immediately. Otherwise, schedules the object to be deleted once
// the worker thread completes. SignalWorkDone will be signalled.
void Release();
// Context: Main Thread. Signalled when work is complete.
sigslot::signal1<SignalThread *> SignalWorkDone;
enum { ST_MSG_WORKER_DONE, ST_MSG_FIRST_AVAILABLE };
protected:
~SignalThread() override;
Thread* worker() { return &worker_; }
// Context: Main Thread. Subclass should override to do pre-work setup.
virtual void OnWorkStart() { }
// Context: Worker Thread. Subclass should override to do work.
virtual void DoWork() = 0;
// Context: Worker Thread. Subclass should call periodically to
// dispatch messages and determine if the thread should terminate.
bool ContinueWork();
// Context: Worker Thread. Subclass should override when extra work is
// needed to abort the worker thread.
virtual void OnWorkStop() { }
// Context: Main Thread. Subclass should override to do post-work cleanup.
virtual void OnWorkDone() { }
// Context: Any Thread. If subclass overrides, be sure to call the base
// implementation. Do not use (message_id < ST_MSG_FIRST_AVAILABLE)
void OnMessage(Message* msg) override;
private:
enum State {
kInit, // Initialized, but not started
kRunning, // Started and doing work
kReleasing, // Same as running, but to be deleted when work is done
kComplete, // Work is done
kStopping, // Work is being interrupted
};
class Worker : public Thread {
public:
explicit Worker(SignalThread* parent)
: Thread(std::unique_ptr<SocketServer>(new NullSocketServer())),
parent_(parent) {}
~Worker() override;
void Run() override;
bool IsProcessingMessages() override;
private:
SignalThread* parent_;
RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(Worker);
};
class RTC_SCOPED_LOCKABLE EnterExit {
public:
explicit EnterExit(SignalThread* t) RTC_EXCLUSIVE_LOCK_FUNCTION(t->cs_)
: t_(t) {
t_->cs_.Enter();
// If refcount_ is zero then the object has already been deleted and we
// will be double-deleting it in ~EnterExit()! (shouldn't happen)
RTC_DCHECK_NE(0, t_->refcount_);
++t_->refcount_;
}
~EnterExit() RTC_UNLOCK_FUNCTION() {
bool d = (0 == --t_->refcount_);
t_->cs_.Leave();
if (d)
delete t_;
}
private:
SignalThread* t_;
RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(EnterExit);
};
void Run();
void OnMainThreadDestroyed();
Thread* main_;
Worker worker_;
CriticalSection cs_;
State state_;
int refcount_;
RTC_DISALLOW_COPY_AND_ASSIGN(SignalThread);
};
///////////////////////////////////////////////////////////////////////////////
} // namespace rtc
#endif // RTC_BASE_SIGNALTHREAD_H_
| [
"caolei6767@gmail.com"
] | caolei6767@gmail.com |
7e701d07e3a6c36f5795c283e7e071080c91083c | 79901169d636e19ca57096af214d73a2922e6b86 | /Marvel vs Capcom/Helper/VectorHelper.cpp | 1f3acf81bcd15ea06f9a4ada75405106285bc415 | [] | no_license | delpinor/taller7542 | d46ac3dabdfb4f35ad93cddf1f90ad913df4e2b1 | 36930692fe62cd2ee86d080aee2e29ad156079e5 | refs/heads/master | 2022-04-22T02:26:18.830009 | 2019-04-30T13:17:29 | 2019-04-30T13:17:29 | 257,655,906 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 344 | cpp | /*
* VectorHelper.cpp
*
* Created on: Apr 12, 2019
* Author: dev73
*/
#include "VectorHelper.h"
#include "StringHelper.h"
bool VectorHelper::contiene(std::vector<string> *vec, std::string valor){
if (std::find(vec->begin(), vec->end(), StringHelper::toLower(valor)) != vec->end()){
return true;
}
else{
return false;
}
}
| [
"rodrigo.sluciano1988@gmail.com"
] | rodrigo.sluciano1988@gmail.com |
a24d659b48edceb135204aaf79f01278ec2a4a61 | 01a2c436a1b8c9f2518ae2b0165b69603a6d8c52 | /date/main.cpp | c14536bc9ea8c0826b211c031c563d6f6b6969fa | [] | no_license | 0x81-sh/cpp-composition-article | 5c50905b6a76f05d528aaa84cad01f9af85e4bfb | 88de3e072798ab86c0fc788091b418afedaa65f7 | refs/heads/master | 2023-06-01T09:10:00.210917 | 2021-06-17T15:12:35 | 2021-06-17T15:12:35 | 377,873,192 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,188 | cpp | #include <iostream>
#include <cassert>
#include "Date.h"
void testIsLeapYear(const Date &date, bool expected);
void testAdd(Date &source, int days, const Date &expected);
void testDiff(Date &source, const Date &comparison, int expected);
int main() {
testIsLeapYear(Date(1, 1, 0), true);
testIsLeapYear(Date(1, 1, 420), true);
testIsLeapYear(Date(1, 1, 1000), false);
testIsLeapYear(Date(1, 1, 2001), false);
Date *testDate = new Date();
testAdd(*testDate, 366, Date(1, 1, 2001));
testAdd(*testDate, 1, Date(2, 1, 2001));
testAdd(*testDate, 30, Date(1, 2, 2001));
delete(testDate);
Date *testDiffDate = new Date(1, 1, 2020);
testDiff(*testDiffDate, Date(1, 1, 2019), 365);
testDiff(*testDiffDate, Date(1, 2, 2020), 31);
testDiff(*testDiffDate, Date(2, 1, 2020), 1);
delete(testDiffDate);
}
void testIsLeapYear(const Date &date, bool expected) {
assert(date.isLeapYear() == expected);
}
void testAdd(Date &source, int days, const Date &expected) {
source.add(days);
assert(source == expected);
}
void testDiff(Date &source, const Date &comparison, int expected) {
assert(source.diff(comparison) == expected);
} | [
"ulrich.barnstedt@gmail.com"
] | ulrich.barnstedt@gmail.com |
85099beff0ad7fc2c14257bcd30f2f0dac5e2c5e | 81cfe1dbd19df9e1dcb944bb9fec44238af153fc | /contest_grafos/ga.cpp | 4d9cbcbdb81c2daaa7beac941cf6294df100d700 | [] | no_license | weirdfish23/icpc | a3807bd4d93e8546ed818c0a0627e7ac405c1477 | 5464f928bca6e38cbb6fec945899af0f1d97ee90 | refs/heads/master | 2020-07-07T20:41:11.012953 | 2019-09-28T03:25:27 | 2019-09-28T03:25:27 | 203,472,187 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 186 | cpp | #include <iostream>
using namespace std;
int main (){
cout << 200000 << endl;
for(int i=1; i<=200000; ++i){
cout << i << " ";
}
cout << endl;
return 0;
}
| [
"jjcabrerarios@gmail.com"
] | jjcabrerarios@gmail.com |
7af69f5df3114533e65f12e0f9063824674a974c | f481aeb897c81095bf5bc544f9368aa78457694b | /1103.cpp | 5a0178fa188414437eb8e1355b5127cc39ca30a6 | [] | no_license | channyHuang/leetcodeOJ | 78b10f31f9a6c6571124208efe85201a3690f2da | b41e9c3c076074b6ab9349455b0cf40c270df41f | refs/heads/master | 2023-01-28T15:31:29.346320 | 2023-01-18T03:43:10 | 2023-01-18T03:43:10 | 221,703,848 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 438 | cpp | class Solution {
public:
vector<int> distributeCandies(int candies, int num_people) {
vector<int> res;
res.resize(num_people);
int n = 1, pos = 0;
while (candies >= n) {
res[pos++] += n;
if (pos >= num_people) pos -= num_people;
candies -= n;
n++;
}
if (candies == 0) return res;
res[pos] += candies;
return res;
}
};
| [
"349117102@qq.com"
] | 349117102@qq.com |
1609244a1ad6c2cde27161dc0aac7fd20ea32d1c | b289812c11c6847107fe07066e7a5e09133f4245 | /Candy/candy.cpp | e8be4caae1df9da5188146fee7c51c85e16bef39 | [
"MIT"
] | permissive | somnusfish/leetcode | ccff146ac84eed6a92dabc600e7d4fd3f8981234 | eae387efd76159bc63948235fd1cb7d56f45335e | refs/heads/master | 2020-12-24T16:25:04.543885 | 2016-04-27T02:13:50 | 2016-04-27T02:13:50 | 35,150,389 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,296 | cpp | class Solution {
public:
int candy(vector<int>& ratings) {
if(ratings.size()==0){
return 0;
}
if(ratings.size()==1){
return 1;
}
int * candyArray = new int[ratings.size()];
int peak = 0;
int nadir = 0;
candyArray[0] = 1;
for(int i=0; i<ratings.size(); i++){
if(ratings[i] == ratings[i-1]){
candyArray[i] = 1;
}
else if(ratings[i] > ratings[i-1]){
candyArray[i] = candyArray[i-1]+1;
}
else{
candyArray[i] = candyArray[i-1]-1;
}
if(((i!=ratings.size()-1) && (ratings[i]<=ratings[i+1]))
|| (i==ratings.size()-1)){
int j=i;
int shift = 1-candyArray[i];
while((j>=0) && (ratings[j] < ratings[j-1])){
candyArray[j] += shift;
j--;
}
if(shift>0){
candyArray[j] += shift;
}
}
}
int sum = 0;
for(int i=0; i<ratings.size(); i++){
cout << candyArray[i] << " ";
sum += candyArray[i];
}
return sum;
}
};
| [
"somnusfish@gmail.com"
] | somnusfish@gmail.com |
060031cfc46e091203d2239c3131a08e473d4555 | 6d763845a081a6c5c372a304c3bae1ccd949e6fa | /day04/ex00/Cow.hpp | eb9ae99ba327530b7b9a000213f3313dc4ce3aad | [] | no_license | hmiso/CPP_modules | cc5539764b10d9005aea0ccdf894c0fd2562a649 | e0608a810ef6bbb7cb29461721f6248e0c3b88eb | refs/heads/master | 2023-02-28T09:12:49.284788 | 2021-02-06T14:40:33 | 2021-02-06T14:40:33 | 322,648,779 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,093 | hpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Cow.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: hmiso <hmiso@student.21-school.ru> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/11 13:34:41 by hmiso #+# #+# */
/* Updated: 2021/01/11 13:35:32 by hmiso ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef COW_HPP
#define COW_HPP
#include "Victim.hpp"
class Cow : public Victim {
private:
std::string name;
public:
Cow(std::string name);
void getPolymorphed() const;
virtual ~Cow();
};
#endif | [
"macbook@MacBook-Pro-MacBook.local"
] | macbook@MacBook-Pro-MacBook.local |
36e33e9f80f6ad5f240e4953e0f367be28da17ba | ef87493adfa9386136dcf007c7f9e2bf131553a6 | /CGJ_Team/CGJ_Team/Object.h | 975ddc6837be6bc1d5abfdd23ef7ddca370dbec6 | [] | no_license | megax37/Tanks | b3ec17b75cb5430cae96af6243428ac0b3b3adaa | 74270618ca3424c201adde1b9f88b716d0e9a33c | refs/heads/master | 2020-06-16T13:03:09.580438 | 2017-01-21T02:23:34 | 2017-01-21T02:23:34 | 75,099,604 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 138 | h | #ifndef _OBJECT_
#define _OBJECT_
class Object
{
public:
void virtual update(int elapsedTime) = 0;
void virtual move() = 0;
};
#endif | [
"velkan14@gmail.com"
] | velkan14@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.