blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
sequencelengths
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
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 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
122 values
content
stringlengths
3
10.4M
authors
sequencelengths
1
1
author_id
stringlengths
0
158
e39853dfe874d4b2333ebf6d5d33c6b52df5eeaf
7150de89552eb732d3791ea698cfcfa2762ec569
/COMPI/functor.hpp
0304db635f31e88e5402b53f6161f9e94b241e9c
[]
no_license
tenkjm/optimisation
1b6434a4872e3ce79994ed84c6e815bd140d2fd4
0398401e02c33d4d4d217bafdb901ead459ea230
refs/heads/master
2021-01-13T11:09:22.633957
2017-02-08T07:54:44
2017-02-08T07:54:44
81,301,633
0
0
null
null
null
null
UTF-8
C++
false
false
1,012
hpp
/* * File: functor.hpp * Author: medved * * Created on February 17, 2016, 3:51 PM */ #ifndef FUNCTOR_HPP #define FUNCTOR_HPP #include <common/sgerrcheck.hpp> namespace COMPI { /** * Abstract class for storing functional objectives and constraints */ template <class FT> class Functor { public: /** * Compute function * @param x argument * @return function value * */ virtual FT func(const FT* x) = 0; /** * Compute gradient (optional) * @param x argument * @param g gradient */ virtual void grad(const FT* x, FT* g) { SG_ERROR_REPORT("Gradient not implemented"); } /** * Compute Hessian (optional) * @param x point * @param H hessian */ virtual void hess(const FT* x, FT* H) { SG_ERROR_REPORT("Hessian not implemented"); } }; } #endif /* FUNCTOR_HPP */
427f10adef92603cfb1de2c8116718fbbce6d425
d4254d0a4206a6b15a670d94d0f554b26dc67487
/year2/COS2614/Assignment 2/question1/conferencepaper.cpp
31eeb0ff048defced0cb68cba79dadfdb9747e42
[]
no_license
luyandamncube/UNISA
0c0378bedc2de72f4e478b8c4635b204ee3cc1e4
770647e583f6c786449729bb7ed096206136f346
refs/heads/master
2022-02-12T02:20:11.762040
2022-01-31T02:27:29
2022-01-31T02:27:29
244,408,008
0
0
null
null
null
null
UTF-8
C++
false
false
444
cpp
#include "conferencepaper.h" //QString Reference::refType = "Conference"; //ConferencePaper::ConferencePaper( // QString _title, QStringList _authors, int _year, QString _refID, QString _confName, int _month): // Reference(_title, _authors, _year, _refID), // confName(_confName), // month(_month) //{ //} QString ConferencePaper::getConfName(){ return(confName); } int ConferencePaper::getMonth(){ return(month); }
2817fe53f4c7df37ba073940ac1d2a6ae9fd68db
f9de594b762b68bd7d5045d46efc92b87a743361
/step4_bi/4.2_fastsensing/4.2.2/4.2.2.ino
8f77096ad592898ef21eb21b356e02b1f3584212
[]
no_license
n0bisuke/20180307_tokyo
e7772e7f82e770cb8868eb0b46d2df60a0f44891
cadb9ebbea1914f6acd1643fa324b4096b618329
refs/heads/master
2021-04-26T23:28:25.521132
2018-03-13T07:40:38
2018-03-13T07:40:38
124,000,583
1
0
null
null
null
null
UTF-8
C++
false
false
1,550
ino
#include <WiFiClientSecure.h> // HTTPS通信のために必要 #define LIGHT_SIG A1 String TARGET_HOST = "f-io.net"; //ファストセンシングのホスト名 String DEVICE_TOKEN = "metjeb44meqxgz6d"; //デバイストークンを指定 String CHANNEL = "5o2bc524"; //利用するチャンネルを指定 void setup() { Serial.begin(115200); } void loop() { int analog = analogRead(LIGHT_SIG); String trainDelayJson = getTrainDelayJson(analog); // JSONを取得する Serial.print(trainDelayJson); delay(5000); } String getTrainDelayJson(int sendData) { WiFiClientSecure client; // 変数を宣言 // サーバーにHTTPSのデフォルトポート(443)でアクセスしてみる if ( !client.connect(TARGET_HOST.c_str(), 443) ) { Serial.println("接続失敗"); return ""; } Serial.print("data: "); Serial.println(sendData); client.print(String("GET /d1/"+DEVICE_TOKEN+"/?"+CHANNEL+"="+(String)sendData+" HTTP/1.1\r\n") + "Content-type: application/json \r\n" + "Host: "+TARGET_HOST.c_str()+"\r\n" + "Connection: close\r\n\r\n"); // HTTP-GETのリクエストメッセージを書く // レスポンスが来るまでちょっと待つ delay(1000); // HTTP-GETのレスポンスを保存しておく変数 String response = ""; // レスポンスを変数に格納する while (client.available()) { response += client.readStringUntil('\r'); } Serial.println("接続成功"); Serial.println(response); return response; }
2811a582407e36307c4422ce831cf83e961c41a9
0e4cbcbf444f70e864c463f28be4f9f9b60de12b
/d05/ex05/RobotomyRequestForm.cpp
0592a9c8f1e88e15148278948626e1e4a34fc643
[]
no_license
ibotha/cpp_bootcamp
25c7552f6fe0755f87b1d6465ef0ff1b95c3665b
909b4dd4e457b55367f35e789d5655230f5f2376
refs/heads/master
2020-05-17T23:19:35.013238
2019-06-13T12:02:17
2019-06-13T12:02:17
184,027,924
0
0
null
null
null
null
UTF-8
C++
false
false
919
cpp
#include "RobotomyRequestForm.hpp" #include <string> #include <iostream> #include <random> RobotomyRequestForm::RobotomyRequestForm(std::string target) :Form("Robotomy Request Form", target, 72, 45) { } RobotomyRequestForm::RobotomyRequestForm(RobotomyRequestForm const &f) :Form(f) { } RobotomyRequestForm::~RobotomyRequestForm() { } RobotomyRequestForm &RobotomyRequestForm::operator=(RobotomyRequestForm const &src) { if (&src != this) { *this = src; } return *this; } RobotomyRequestForm::RobotomyRequestForm() :Form("Robotomy Request Form", "PNP", 72, 45) { } bool RobotomyRequestForm::action(Bureaucrat const &executor) { (void)executor; while(std::rand() % 3) { std::cout << "* bzzzzzt *" << std::endl; } if (std::rand() % 2) std::cout << getTarget() << " has been robotomized" << std::endl; else std::cout << getTarget() << " could not be robotomized" << std::endl; return true; }
ea4f41a2e337c46c6aa69ae8098bb46adfa26ead
82646fb7fe40db6dcdf238548128f7b633de94c0
/akoj/1020.cpp
9a435fe5e446f1c57603ae71207dd05f8c898bb0
[]
no_license
jtahstu/iCode
a7873618fe98e502c1e0e2fd0769d71b3adac756
42d0899945dbc1bab98092d21a1d946137a1795e
refs/heads/master
2021-01-10T22:55:47.677615
2016-10-23T12:42:38
2016-10-23T12:42:38
70,316,051
1
0
null
null
null
null
UTF-8
C++
false
false
305
cpp
#include<iostream> using namespace std; int t() int main() { int n,t; cin>>n; string a; while(n--) { cin>>a; t=a[0]-'0'; for(int i=1;i<a.length();i++) { s=a[i]-'0'; tt(s,t); } } return 0; }
1257e01919f4d56c25938ffc19b8673d0cc907e4
c9b02ab1612c8b436c1de94069b139137657899b
/server/app/data/DBCSimpleTemplate.h
98eb60df409cb38ff9102b2f6c56c72feb6b7748
[]
no_license
colinblack/game_server
a7ee95ec4e1def0220ab71f5f4501c9a26ab61ab
a7724f93e0be5c43e323972da30e738e5fbef54f
refs/heads/master
2020-03-21T19:25:02.879552
2020-03-01T08:57:07
2020-03-01T08:57:07
138,948,382
1
1
null
null
null
null
UTF-8
C++
false
false
2,635
h
/* * DBCSimpleTemplate.h * * Created on: 2016-11-22 * Author: dawx62fac */ #ifndef DBCSIMPLETEMPLATE_H_ #define DBCSIMPLETEMPLATE_H_ /** * 适用于每个用户对应一条记录,且以uid为主键的表 */ #include "Kernel.h" template<class _DBC, int _ID, class _HANDLE> class DBCSimpleTemplate : public DataSingleton<_DBC, _ID , DB_BASE_BUFF*DB_BASE_FULL, _HANDLE, DB_BASE_FULL> { typedef DataSingleton<_DBC, _ID , DB_BASE_BUFF*DB_BASE_FULL, _HANDLE, DB_BASE_FULL> base; protected: int FreeIndex() { int index = base::GetFreeIndex(); if (index < 0) { error_log("Name: %s, index: %d", name(), index); throw std::runtime_error("Get_free_index_error"); } return index; } void NewItem(unsigned uid, int index) { _DBC data; data.uid = uid; if(Add(index, data)) { m_map[uid] = index; } else { error_log("Name: %s, add_error.uid=%u,", name(), uid); throw std::runtime_error("add_item_error"); } } public: virtual const char* name() const = 0; virtual ~DBCSimpleTemplate() {} int OnInit() { for(unsigned i=0; i < DB_BASE_BUFF*DB_BASE_FULL; ++i) { if(! base::m_data->Empty(i)) { const _DBC& item = base::m_data->data[i]; m_map[item.uid] = i; } } return 0; } void DoClear(unsigned uid) { std::map<unsigned, unsigned>::iterator it = m_map.find(uid); if (it != m_map.end()) { unsigned idx = it->second; base::Clear(idx); m_map.erase(uid); } } void DoSave(unsigned uid) { std::map<unsigned, unsigned>::iterator it = m_map.find(uid); if (it != m_map.end()) { unsigned idx = it->second; base::AddSave(idx); } } int GetIndex(unsigned uid) { std::map<unsigned, unsigned>::iterator it = m_map.find(uid); if (it != m_map.end()) { return it->second; } else { return this->LoadBuffer(uid); } } int LoadBuffer(unsigned uid) { if (m_map.count(uid) > 0) { throw std::runtime_error("already_load_data"); } if (base::IsFull()) { error_log("Name: %s, uid:%u, load_data_error", name(), uid); throw std::runtime_error("data_is_full"); } int index = FreeIndex(); base::m_data->data[index].uid = uid; int ret = base::Load(index); if (R_ERR_NO_DATA == ret) { NewItem(uid, index); } else { if (ret != 0) { error_log("Name: %s, uid:%u, load_data_error, ret:%d", name(), uid, ret); throw std::runtime_error("load_data_error"); } m_map[uid] = index; } return index; } bool IsExist(unsigned uid) { return (m_map.count(uid) > 0); } protected: std::map<unsigned, unsigned> m_map; }; #endif /* DBCSIMPLETEMPLATE_H_ */
07775371fb6da2143f354f70fecccf70f635e972
cf8ddfc720bf6451c4ef4fa01684327431db1919
/SDK/ARKSurvivalEvolved_PrimalItemConsumable_Soup_ShadowSteak_functions.cpp
c325c5d4128fb8210b2f8a9f7508f42a2d714030
[ "MIT" ]
permissive
git-Charlie/ARK-SDK
75337684b11e7b9f668da1f15e8054052a3b600f
c38ca9925309516b2093ad8c3a70ed9489e1d573
refs/heads/master
2023-06-20T06:30:33.550123
2021-07-11T13:41:45
2021-07-11T13:41:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,236
cpp
// ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_PrimalItemConsumable_Soup_ShadowSteak_parameters.hpp" namespace sdk { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function PrimalItemConsumable_Soup_ShadowSteak.PrimalItemConsumable_Soup_ShadowSteak_C.ExecuteUbergraph_PrimalItemConsumable_Soup_ShadowSteak // () // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void UPrimalItemConsumable_Soup_ShadowSteak_C::ExecuteUbergraph_PrimalItemConsumable_Soup_ShadowSteak(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function PrimalItemConsumable_Soup_ShadowSteak.PrimalItemConsumable_Soup_ShadowSteak_C.ExecuteUbergraph_PrimalItemConsumable_Soup_ShadowSteak"); UPrimalItemConsumable_Soup_ShadowSteak_C_ExecuteUbergraph_PrimalItemConsumable_Soup_ShadowSteak_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
c3ace9630f624753d9e46b85f49a25da5838a7b5
bc7651210ee5a59ba79f95e038185fe235418c4f
/interaction+hyunjeong.cpp
a920fba24d7aac0c34291f7b6a4522d05bd37a2d
[]
no_license
seoyh0812/TeamLaunge2
3f81b2eed4ee32c771d979e77c84fdd6b9e6080f
e1498ee31dde3cfc8e853ca97f273b390551f009
refs/heads/master
2023-03-21T09:38:27.688056
2021-03-22T01:11:02
2021-03-22T01:11:02
332,584,817
0
0
null
null
null
null
UTF-8
C++
false
false
165
cpp
#include "stdafx.h" #include "interaction.h" void interaction::hyunjeongInit() { } void interaction::hyunjeongUpdate() { } void interaction::hyunjeongRender() { }
5b9692b1721096d47840eee0c874b4064b114320
f16204094cef905fd2f314adbe199b04b04c6dbc
/src/Player.cpp
9357f49d3f38f2185f2e34830a9a94a2f91e38d1
[]
no_license
danielaz1/sgd_game
11cb50d86e251919c1d45600d232f29d60ef63e3
ce97069cf94ec09538fa6be2b2c473979a0b8a2b
refs/heads/master
2020-05-17T16:16:22.030006
2019-05-04T21:50:50
2019-05-04T21:50:50
183,813,134
0
0
null
null
null
null
UTF-8
C++
false
false
2,889
cpp
// // Created by daniela on 15.04.19. // #include "Player.h" std::shared_ptr<SDL_Texture> Player::loadTexture(SDL_Renderer *renderer, const std::string fname) { std::vector<unsigned char> image; unsigned width=20, height=20; errcheck(lodepng::decode(image, width, height, fname)); SDL_Surface *bitmap = SDL_CreateRGBSurfaceWithFormat(0, width, height, 32, SDL_PIXELFORMAT_RGBA32); std::copy(image.begin(), image.end(), (unsigned char *) bitmap->pixels); errcheck(bitmap == nullptr); SDL_Texture *tex = SDL_CreateTextureFromSurface(renderer, bitmap); errcheck(tex == nullptr); SDL_SetTextureBlendMode(tex, SDL_BLENDMODE_BLEND); std::shared_ptr<SDL_Texture> texture( tex, [](SDL_Texture *ptr) { SDL_DestroyTexture(ptr); }); SDL_FreeSurface(bitmap); return texture; } int Player::throwRectangle(int angle, double power, SDL_Renderer *renderer, ObstacleGenerator *obstacleGenerator) { if (power+powerFactor < 0) { power = 0; } else { power += powerFactor; } int distance = calculateX(angle, power, distance_x); int position_y = calculateY(angle, power, distance_y); int position_x; float newPowerFactor = obstacleGenerator->detectCollision(distance, position_y); powerFactor+=newPowerFactor; if (newPowerFactor != 0) { distance_x = distance; distance_y = position_y; time = 0; } position_x = distance; if (position_x > GameConstants::WINDOW_WIDTH / 2) { position_x = GameConstants::WINDOW_WIDTH / 2; } SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL_Rect rectangle; rectangle.x = position_x; rectangle.y = position_y; rectangle.w = GameConstants::PLAYER_WIDTH; rectangle.h = GameConstants::PLAYER_HEIGHT; // SDL_RenderFillRect(renderer, &rectangle); SDL_RenderCopy(renderer, texture.get(), NULL, &rectangle); return distance; } double Player::toRadians(int angle) { return (angle * M_PI) / 180; } int Player::calculateX(int angle, double power, int start_x) { double vx = power * cos(toRadians(angle)); int position_x = start_x + vx * time; return position_x; } int Player::calculateY(int angle, double power, int start_y) { double vy = power * sin(toRadians(angle)); int position_y = start_y - (vy * time - (gravity / 2) * time * time); return position_y; } float Player::increaseTime() { return time += TIME_INTERVAL; } void Player::calculateCollision(int position_y, int distance) { if (position_y >= GameConstants::PLAYER_MIN_Y) { //ground time = 0; distance_x = distance; distance_y = GameConstants::PLAYER_MIN_Y; counter++; } } Player::Player(SDL_Renderer *renderer) { texture = loadTexture(renderer, "data/kula.png"); }
2adcda15ae14156174a844109851e885153e9250
1e28cdcb4c96ce4afecffcb2683e59bbd6c5afaf
/Stacks/946. Validate Stack Sequences.cpp
5def179b2efb287e7df0a5acba6ac01ec27cb4e3
[]
no_license
ankitsharma1530/Sliding-window_leetcode
3c32e1a7e75b89157c9f74816a1c1c710a8b74d1
66183b47f96f8bf96251c1c4e620d251894d42cf
refs/heads/main
2023-06-30T20:03:18.439449
2021-08-07T06:56:53
2021-08-07T06:56:53
330,183,370
1
0
null
null
null
null
UTF-8
C++
false
false
451
cpp
class Solution { public: bool validateStackSequences(vector<int>& pushed, vector<int>& popped) { int j=0; int size = pushed.size(); stack<int>s; int i = 0; while(j<size) { s.push(pushed[j]); while(!s.empty() && i<size && s.top()==popped[i]) { s.pop(); i++; } j++; } return i==size; } };
878d36bd734d7bed24b99f8d1af2d099427b8273
46990b0e1570284b17bc413665e0f19594aeb473
/racetrack/a.cpp
ad8889685692596ef68e74139a2925e50e196352
[]
no_license
varunragu23/USACO-CF-Varun
878ee68e6268c509766deebf1a1c0af505010669
2a9646f919ca2af2432f73a85e6d1578259e8ad2
refs/heads/master
2020-09-03T01:26:16.838307
2019-11-03T18:50:39
2019-11-03T18:50:39
219,350,285
0
0
null
null
null
null
UTF-8
C++
false
false
1,227
cpp
/* ID: varunra2 LANG: C++ TASK: racetrack */ #pragma region Headers, define, typedef #include<bits/stdc++.h> using namespace std; #ifdef DEBUG #include <debug.h> #endif #define EPS 1e-9 #define IN(A, B, C) assert(B <= A && A <= C) #define INF (int)1e9 #define MEM(a, b) memset(a, (b), sizeof(a)) #define MOD 1000000007 #define MP make_pair #define PB push_back #define all(cont) cont.begin(), cont.end() #define rall(cont) cont.end(), cont.begin() #define x first #define y second const double PI = acos(-1.0); typedef long long ll; typedef long double ld; typedef pair<int, int> PII; typedef map<int, int> MPII; typedef multiset<int> MSETI; typedef set<int> SETI; typedef set<string> SETS; typedef vector<int> VI; typedef vector<PII> VII; typedef vector<VI> VVI; typedef vector<string> VS; #ifdef DEBUG #define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__) #else #define debug(...) 42 #endif // util functions #pragma endregion int main(int argc, char const *argv[]) { #ifndef ONLINE_JUDGE freopen("racetrack.in", "r", stdin); freopen("racetrack.out", "w", stdout); #endif cin.sync_with_stdio(0); cin.tie(0); return 0; }
4b58ac99ec9a21b39646a176df8f6a23cbeba875
dd0cafca11c990626b55d3460b225ac5acf1619d
/Strings/PrettyJson.cpp
72c0dd1dad1be9142e9ab77bd563240fc936ac96
[]
no_license
VenkataAnilKumar/InterviewBit-CPlusPlus
5439642fd316f06879f992c2f57de1ce5be8be4f
65cba3a7c9844a84547c1a6faa327d5614a2d234
refs/heads/master
2022-01-29T15:17:41.994010
2019-07-20T18:34:18
2019-07-20T18:34:18
197,962,915
1
0
null
null
null
null
UTF-8
C++
false
false
1,709
cpp
vector<string> kirp(string str){ vector<string> result; if (str.length() == 0) return result; str.erase(remove(str.begin(), str.end(), ' '), str.end()); string indent = ""; string curr = ""; int i = 0, len = str.length(); while (i < len){ curr.push_back(str[i]); switch(str[i]){ case ',': result.push_back(curr); curr = indent; i++; break; case ':': i++; if (str[i] == '{' || str[i] == '['){ result.push_back(curr); curr = indent; } break; case '{': case '[': i++; result.push_back(curr); if (i < len && (str[i] != '}' || str[i] != ']')){ indent.push_back('\t'); } curr = indent; break; case '}': case ']': i++; if (i < len && str[i] == ',') break; result.push_back(curr); if (i < len && (str[i] == '}' || str[i] == ']')){ if (!indent.empty()) indent.pop_back(); } curr = indent; break; default : i++; if (i < len && (str[i] == '}' || str[i] == ']')){ result.push_back(curr); if (!indent.empty()) indent.pop_back(); curr = indent; } } } return result; } vector<string> Solution::prettyJSON(string A) { return kirp(A); }
301fd8f3fbb2d15522422dc4f72f77e1192e14d0
6f376bd4f5755539a19a20fdd2cbd4cb9e6ab0f9
/CtpTraderApi/CtpTrader.h
c7337db4d926d4bf4937bce8b6b595ce7285af27
[ "MIT" ]
permissive
alexfordc/InterPlatformTradingMaster
d40f6f1bf392ed8b435601c0ab92d78b9843e34a
ab09fd0d53e53103b8ddb56b1e295d193b1c909e
refs/heads/master
2022-01-10T12:01:04.512994
2019-07-08T03:26:04
2019-07-08T03:26:04
null
0
0
null
null
null
null
GB18030
C++
false
false
46,689
h
#pragma once #define TRADEAPI_API __declspec(dllexport) #define WINAPI __stdcall #define WIN32_LEAN_AND_MEAN // 从 Windows 头文件中排除极少使用的信息 #include "stdafx.h" #include ".\api\ThostFtdcTraderApi.h" #include ".\api\ThostFtdcUserApiDataType.h" #include ".\api\ThostFtdcUserApiStruct.h" // UserApi对象 CThostFtdcTraderApi* pUserApi; //回调函数 void* _OnFrontConnected; ///当客户端与交易后台建立起通信连接时(还未登录前),该方法被调用。 void* _OnFrontDisconnected; ///当客户端与交易后台通信连接断开时,该方法被调用。当发生这个情况后,API会自动重新连接,客户端可不做处理。 void* _OnHeartBeatWarning; ///心跳超时警告。当长时间未收到报文时,该方法被调用。 void* _OnRspUserLogin;///登录请求响应 void* _OnRspAuthenticate;///客户端认证响应 void* _OnRspUserLogout;///登出请求响应 void* _OnRspUserPasswordUpdate;///用户口令更新请求响应 void* _OnRspTradingAccountPasswordUpdate;///资金账户口令更新请求响应 void* _OnRspOrderInsert;///报单录入请求响应 void* _OnRspParkedOrderInsert;///预埋单录入请求响应 void* _OnRspParkedOrderAction;///预埋撤单录入请求响应 void* _OnRspOrderAction;///报单操作请求响应 void* _OnRspQueryMaxOrderVolume;///查询最大报单数量响应 void* _OnRspSettlementInfoConfirm;///投资者结算结果确认响应 void* _OnRspRemoveParkedOrder;///删除预埋单响应 void* _OnRspRemoveParkedOrderAction;///删除预埋撤单响应 void* _OnRspQryOrder;///请求查询报单响应 void* _OnRspQryTrade;///请求查询成交响应 void* _OnRspQryInvestorPosition;///请求查询投资者持仓响应 void* _OnRspQryTradingAccount;///请求查询资金账户响应 void* _OnRspQryInvestor;///请求查询投资者响应 void* _OnRspQryTradingCode;///请求查询交易编码响应 void* _OnRspQryInstrumentMarginRate;///请求查询合约保证金率响应 void* _OnRspQryInstrumentCommissionRate;///请求查询合约手续费率响应 void* _OnRspQryExchange;///请求查询交易所响应 void* _OnRspQryInstrument;///请求查询合约响应 void* _OnRspQryDepthMarketData;///请求查询行情响应 void* _OnRspQrySettlementInfo;///请求查询投资者结算结果响应 void* _OnRspQryTransferBank;///请求查询转帐银行响应 void* _OnRspQryInvestorPositionDetail;///请求查询投资者持仓明细响应 void* _OnRspQryNotice;///请求查询客户通知响应 void* _OnRspQrySettlementInfoConfirm;///请求查询结算信息确认响应 void* _OnRspQryInvestorPositionCombineDetail;///请求查询投资者持仓明细响应 void* _OnRspQryCFMMCTradingAccountKey;///查询保证金监管系统经纪公司资金账户密钥响应 void* _OnRspQryAccountregister;///请求查询银期签约关系响应 void* _OnRspQryTransferSerial;///请求查询转帐流水响应 void* _OnRspError;///错误应答 void* _OnRtnOrder;///报单通知 void* _OnRtnTrade;///成交通知 void* _OnErrRtnOrderInsert;///报单录入错误回报 void* _OnErrRtnOrderAction;///报单操作错误回报 void* _OnRtnInstrumentStatus;///合约交易状态通知 void* _OnRtnTradingNotice;///交易通知 void* _OnRtnErrorConditionalOrder;///提示条件单校验错误 void* _OnRspQryContractBank;///请求查询签约银行响应 void* _OnRspQryParkedOrder;///请求查询预埋单响应 void* _OnRspQryParkedOrderAction;///请求查询预埋撤单响应 void* _OnRspQryTradingNotice;///请求查询交易通知响应 void* _OnRspQryBrokerTradingParams;///请求查询经纪公司交易参数响应 void* _OnRspQryBrokerTradingAlgos;///请求查询经纪公司交易算法响应 void* _OnRtnFromBankToFutureByBank;///银行发起银行资金转期货通知 void* _OnRtnFromFutureToBankByBank;///银行发起期货资金转银行通知 void* _OnRtnRepealFromBankToFutureByBank;///银行发起冲正银行转期货通知 void* _OnRtnRepealFromFutureToBankByBank;///银行发起冲正期货转银行通知 void* _OnRtnFromBankToFutureByFuture;///期货发起银行资金转期货通知 void* _OnRtnFromFutureToBankByFuture;///期货发起期货资金转银行通知 void* _OnRtnRepealFromBankToFutureByFutureManual;///系统运行时期货端手工发起冲正银行转期货请求,银行处理完毕后报盘发回的通知 void* _OnRtnRepealFromFutureToBankByFutureManual;///系统运行时期货端手工发起冲正期货转银行请求,银行处理完毕后报盘发回的通知 void* _OnRtnQueryBankBalanceByFuture;///期货发起查询银行余额通知 void* _OnErrRtnBankToFutureByFuture;///期货发起银行资金转期货错误回报 void* _OnErrRtnFutureToBankByFuture;///期货发起期货资金转银行错误回报 void* _OnErrRtnRepealBankToFutureByFutureManual;///系统运行时期货端手工发起冲正银行转期货错误回报 void* _OnErrRtnRepealFutureToBankByFutureManual;///系统运行时期货端手工发起冲正期货转银行错误回报 void* _OnErrRtnQueryBankBalanceByFuture;///期货发起查询银行余额错误回报 void* _OnRtnRepealFromBankToFutureByFuture;///期货发起冲正银行转期货请求,银行处理完毕后报盘发回的通知 void* _OnRtnRepealFromFutureToBankByFuture;///期货发起冲正期货转银行请求,银行处理完毕后报盘发回的通知 void* _OnRspFromBankToFutureByFuture;///期货发起银行资金转期货应答 void* _OnRspFromFutureToBankByFuture;///期货发起期货资金转银行应答 void* _OnRspQueryBankAccountMoneyByFuture;///期货发起查询银行余额应答 void* _OnRspQryOptionInstrCommRate;///请求查询期权合约手续费响应 void* _OnRspQryOptionInstrTradeCost;///请求查询期权交易成本响应 void* _OnRspQryForQuote;///请求查询询价响应 void* _OnRspForQuoteInsert;///询价录入请求响应 void* _OnRspQryQuote;///请求查询报价响应 void* _OnRspQuoteInsert;///报价录入请求响应 void* _OnRspQuoteAction;///报价操作请求响应 void* _OnRspQryExecOrder;///请求查询执行宣告响应 void* _OnRtnExecOrder;///执行宣告通知 void* _OnRspExecOrderInsert;///执行宣告录入请求响应 void* _OnErrRtnExecOrderInsert;///执行宣告录入错误回报 void* _OnRspExecOrderAction;///执行宣告操作请求响应 void* _OnErrRtnExecOrderAction;///执行宣告操作错误回报 void* _OnRtnForQuoteRsp;///询价通知 void* _OnErrRtnForQuoteInsert;///询价录入错误回报 void* _OnRtnQuote;///报价通知 void* _OnErrRtnQuoteInsert;///报价录入错误回报 void* _OnErrRtnQuoteAction;///报价操作错误回报 void* _OnRspCombActionInsert;///申请组合录入请求响应 void* _OnRspQryCombInstrumentGuard;///请求查询组合合约安全系数响应 void* _OnRspQryCombAction;///请求查询申请组合响应 void* _OnRtnCombAction;///申请组合通知 void* _OnErrRtnCombActionInsert;///申请组合录入错误回报 void* _OnRspQryInvestorProductGroupMargin;///请求查询投资者品种/跨品种保证金响应 void* _OnRspQryExchangeMarginRateAdjust;///请求查询交易所调整保证金率响应 void* _OnRspQryExchangeRate;///请求查询汇率响应 void* _OnRspQryProductExchRate;///请求查询产品报价汇率 void* _OnRspBatchOrderAction;///批量报单操作请求响应 void* _OnRspQryProductGroup;///请求查询产品组 void* _OnRspQryMMInstrumentCommissionRate;///请求查询做市商合约手续费率响应 void* _OnRspQryMMOptionInstrCommRate;///请求查询做市商期权合约手续费响应 void* _OnRspQryInstrumentOrderCommRate;///请求查询报单手续费响应 void* _OnRtnBulletin;///交易所公告通知 void* _OnErrRtnBatchOrderAction;///批量报单操作错误回报 ///当客户端与交易后台建立起通信连接时(还未登录前),该方法被调用。 typedef int (WINAPI *DefOnFrontConnected)(); ///当客户端与交易后台通信连接断开时,该方法被调用。当发生这个情况后,API会自动重新连接,客户端可不做处理。 typedef int (WINAPI *DefOnFrontDisconnected)(int nReason); ///心跳超时警告。当长时间未收到报文时,该方法被调用。 typedef int (WINAPI *DefOnHeartBeatWarning)(int nTimeLapse); ///登录请求响应 typedef int (WINAPI *DefOnRspAuthenticate)(CThostFtdcRspAuthenticateField *pRspAuthenticateField, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///登录请求响应 typedef int (WINAPI *DefOnRspUserLogin)(CThostFtdcRspUserLoginField *pRspUserLogin, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///登出请求响应 typedef int (WINAPI *DefOnRspUserLogout)(CThostFtdcUserLogoutField *pUserLogout, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///用户口令更新请求响应 typedef int (WINAPI *DefOnRspUserPasswordUpdate)(CThostFtdcUserPasswordUpdateField *pUserPasswordUpdate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///资金账户口令更新请求响应 typedef int (WINAPI *DefOnRspTradingAccountPasswordUpdate)(CThostFtdcTradingAccountPasswordUpdateField *pTradingAccountPasswordUpdate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///报单录入请求响应 typedef int (WINAPI *DefOnRspOrderInsert)(CThostFtdcInputOrderField *pInputOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///预埋单录入请求响应 typedef int (WINAPI *DefOnRspParkedOrderInsert)(CThostFtdcParkedOrderField *pParkedOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///预埋撤单录入请求响应 typedef int (WINAPI *DefOnRspParkedOrderAction)(CThostFtdcParkedOrderActionField *pParkedOrderAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///报单操作请求响应 typedef int (WINAPI *DefOnRspOrderAction)(CThostFtdcInputOrderActionField *pInputOrderAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///查询最大报单数量响应 typedef int (WINAPI *DefOnRspQueryMaxOrderVolume)(CThostFtdcQueryMaxOrderVolumeField *pQueryMaxOrderVolume, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///投资者结算结果确认响应 typedef int (WINAPI *DefOnRspSettlementInfoConfirm)(CThostFtdcSettlementInfoConfirmField *pSettlementInfoConfirm, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///删除预埋单响应 typedef int (WINAPI *DefOnRspRemoveParkedOrder)(CThostFtdcRemoveParkedOrderField *pRemoveParkedOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///删除预埋撤单响应 typedef int (WINAPI *DefOnRspRemoveParkedOrderAction)(CThostFtdcRemoveParkedOrderActionField *pRemoveParkedOrderAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///请求查询报单响应 typedef int (WINAPI *DefOnRspQryOrder)(CThostFtdcOrderField *pOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///请求查询成交响应 typedef int (WINAPI *DefOnRspQryTrade)(CThostFtdcTradeField *pTrade, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///请求查询投资者持仓响应 typedef int (WINAPI *DefOnRspQryInvestorPosition)(CThostFtdcInvestorPositionField *pInvestorPosition, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///请求查询资金账户响应 typedef int (WINAPI *DefOnRspQryTradingAccount)(CThostFtdcTradingAccountField *pTradingAccount, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///请求查询投资者响应 typedef int (WINAPI *DefOnRspQryInvestor)(CThostFtdcInvestorField *pInvestor, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///请求查询交易编码响应 typedef int (WINAPI *DefOnRspQryTradingCode)(CThostFtdcTradingCodeField *pTradingCode, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///请求查询合约保证金率响应 typedef int (WINAPI *DefOnRspQryInstrumentMarginRate)(CThostFtdcInstrumentMarginRateField *pInstrumentMarginRate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///请求查询合约手续费率响应 typedef int (WINAPI *DefOnRspQryInstrumentCommissionRate)(CThostFtdcInstrumentCommissionRateField *pInstrumentCommissionRate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///请求查询期权合约手续费率响应 typedef int (WINAPI *DefOnRspQryQryOptionInstrCommRate)(CThostFtdcOptionInstrCommRateField *pOptionInstrCommRate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///请求查询交易所响应 typedef int (WINAPI *DefOnRspQryExchange)(CThostFtdcExchangeField *pExchange, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///请求查询合约响应 typedef int (WINAPI *DefOnRspQryInstrument)(CThostFtdcInstrumentField *pInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///请求查询行情响应 typedef int (WINAPI *DefOnRspQryDepthMarketData)(CThostFtdcDepthMarketDataField *pDepthMarketData, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///请求查询投资者结算结果响应 typedef int (WINAPI *DefOnRspQrySettlementInfo)(CThostFtdcSettlementInfoField *pSettlementInfo, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///请求查询银期签约关系响应 typedef int (WINAPI *DefOnRspQryAccountregister)(CThostFtdcAccountregisterField *pAccountregister, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///请求查询转帐银行响应 typedef int (WINAPI *DefOnRspQryTransferBank)(CThostFtdcTransferBankField *pTransferBank, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///请求查询投资者持仓明细响应 typedef int (WINAPI *DefOnRspQryInvestorPositionDetail)(CThostFtdcInvestorPositionDetailField *pInvestorPositionDetail, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///请求查询客户通知响应 typedef int (WINAPI *DefOnRspQryNotice)(CThostFtdcNoticeField *pNotice, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///请求查询结算信息确认响应 typedef int (WINAPI *DefOnRspQrySettlementInfoConfirm)(CThostFtdcSettlementInfoConfirmField *pSettlementInfoConfirm, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///请求查询投资者持仓明细响应 typedef int (WINAPI *DefOnRspQryInvestorPositionCombineDetail)(CThostFtdcInvestorPositionCombineDetailField *pInvestorPositionCombineDetail, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///查询保证金监管系统经纪公司资金账户密钥响应 typedef int (WINAPI *DefOnRspQryCFMMCTradingAccountKey)(CThostFtdcCFMMCTradingAccountKeyField *pCFMMCTradingAccountKey, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///请求查询转帐流水响应 typedef int (WINAPI *DefOnRspQryTransferSerial)(CThostFtdcTransferSerialField *pTransferSerial, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///错误应答 typedef int (WINAPI *DefOnRspError)(CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///报单通知 typedef int (WINAPI *DefOnRtnOrder)(CThostFtdcOrderField *pOrder) ; ///成交通知 typedef int (WINAPI *DefOnRtnTrade)(CThostFtdcTradeField *pTrade) ; ///报单录入错误回报 typedef int (WINAPI *DefOnErrRtnOrderInsert)(CThostFtdcInputOrderField *pInputOrder, CThostFtdcRspInfoField *pRspInfo) ; ///报单操作错误回报 typedef int (WINAPI *DefOnErrRtnOrderAction)(CThostFtdcOrderActionField *pOrderAction, CThostFtdcRspInfoField *pRspInfo) ; ///合约交易状态通知 typedef int (WINAPI *DefOnRtnInstrumentStatus)(CThostFtdcInstrumentStatusField *pInstrumentStatus) ; ///交易通知 typedef int (WINAPI *DefOnRtnTradingNotice)(CThostFtdcTradingNoticeInfoField *pTradingNoticeInfo) ; ///提示条件单校验错误 typedef int (WINAPI *DefOnRtnErrorConditionalOrder)(CThostFtdcErrorConditionalOrderField *pErrorConditionalOrder) ; ///请求查询签约银行响应 typedef int (WINAPI *DefOnRspQryContractBank)(CThostFtdcContractBankField *pContractBank, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///请求查询预埋单响应 typedef int (WINAPI *DefOnRspQryParkedOrder)(CThostFtdcParkedOrderField *pParkedOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///请求查询预埋撤单响应 typedef int (WINAPI *DefOnRspQryParkedOrderAction)(CThostFtdcParkedOrderActionField *pParkedOrderAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///请求查询交易通知响应 typedef int (WINAPI *DefOnRspQryTradingNotice)(CThostFtdcTradingNoticeField *pTradingNotice, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///请求查询经纪公司交易参数响应 typedef int (WINAPI *DefOnRspQryBrokerTradingParams)(CThostFtdcBrokerTradingParamsField *pBrokerTradingParams, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///请求查询经纪公司交易算法响应 typedef int (WINAPI *DefOnRspQryBrokerTradingAlgos)(CThostFtdcBrokerTradingAlgosField *pBrokerTradingAlgos, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///银行发起银行资金转期货通知 typedef int (WINAPI *DefOnRtnFromBankToFutureByBank)(CThostFtdcRspTransferField *pRspTransfer) ; ///银行发起期货资金转银行通知 typedef int (WINAPI *DefOnRtnFromFutureToBankByBank)(CThostFtdcRspTransferField *pRspTransfer) ; ///银行发起冲正银行转期货通知 typedef int (WINAPI *DefOnRtnRepealFromBankToFutureByBank)(CThostFtdcRspRepealField *pRspRepeal) ; ///银行发起冲正期货转银行通知 typedef int (WINAPI *DefOnRtnRepealFromFutureToBankByBank)(CThostFtdcRspRepealField *pRspRepeal) ; ///期货发起银行资金转期货通知 typedef int (WINAPI *DefOnRtnFromBankToFutureByFuture)(CThostFtdcRspTransferField *pRspTransfer) ; ///期货发起期货资金转银行通知 typedef int (WINAPI *DefOnRtnFromFutureToBankByFuture)(CThostFtdcRspTransferField *pRspTransfer) ; ///系统运行时期货端手工发起冲正银行转期货请求,银行处理完毕后报盘发回的通知 typedef int (WINAPI *DefOnRtnRepealFromBankToFutureByFutureManual)(CThostFtdcRspRepealField *pRspRepeal) ; ///系统运行时期货端手工发起冲正期货转银行请求,银行处理完毕后报盘发回的通知 typedef int (WINAPI *DefOnRtnRepealFromFutureToBankByFutureManual)(CThostFtdcRspRepealField *pRspRepeal) ; ///期货发起查询银行余额通知 typedef int (WINAPI *DefOnRtnQueryBankBalanceByFuture)(CThostFtdcNotifyQueryAccountField *pNotifyQueryAccount) ; ///期货发起银行资金转期货错误回报 typedef int (WINAPI *DefOnErrRtnBankToFutureByFuture)(CThostFtdcReqTransferField *pReqTransfer, CThostFtdcRspInfoField *pRspInfo) ; ///期货发起期货资金转银行错误回报 typedef int (WINAPI *DefOnErrRtnFutureToBankByFuture)(CThostFtdcReqTransferField *pReqTransfer, CThostFtdcRspInfoField *pRspInfo) ; ///系统运行时期货端手工发起冲正银行转期货错误回报 typedef int (WINAPI *DefOnErrRtnRepealBankToFutureByFutureManual)(CThostFtdcReqRepealField *pReqRepeal, CThostFtdcRspInfoField *pRspInfo) ; ///系统运行时期货端手工发起冲正期货转银行错误回报 typedef int (WINAPI *DefOnErrRtnRepealFutureToBankByFutureManual)(CThostFtdcReqRepealField *pReqRepeal, CThostFtdcRspInfoField *pRspInfo) ; ///期货发起查询银行余额错误回报 typedef int (WINAPI *DefOnErrRtnQueryBankBalanceByFuture)(CThostFtdcReqQueryAccountField *pReqQueryAccount, CThostFtdcRspInfoField *pRspInfo) ; ///期货发起冲正银行转期货请求,银行处理完毕后报盘发回的通知 typedef int (WINAPI *DefOnRtnRepealFromBankToFutureByFuture)(CThostFtdcRspRepealField *pRspRepeal) ; ///期货发起冲正期货转银行请求,银行处理完毕后报盘发回的通知 typedef int (WINAPI *DefOnRtnRepealFromFutureToBankByFuture)(CThostFtdcRspRepealField *pRspRepeal) ; ///期货发起银行资金转期货应答 typedef int (WINAPI *DefOnRspFromBankToFutureByFuture)(CThostFtdcReqTransferField *pReqTransfer, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///期货发起期货资金转银行应答 typedef int (WINAPI *DefOnRspFromFutureToBankByFuture)(CThostFtdcReqTransferField *pReqTransfer, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///期货发起查询银行余额应答 typedef int (WINAPI *DefOnRspQueryBankAccountMoneyByFuture)(CThostFtdcReqQueryAccountField *pReqQueryAccount, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) ; ///请求查询期权合约手续费响应 typedef int (WINAPI *DefOnRspQryOptionInstrCommRate)(CThostFtdcOptionInstrCommRateField *pOptionInstrCommRate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询期权交易成本响应 typedef int (WINAPI *DefOnRspQryOptionInstrTradeCost)(CThostFtdcOptionInstrTradeCostField *pOptionInstrTradeCost, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询询价响应 typedef int (WINAPI *DefOnRspQryForQuote)(CThostFtdcForQuoteField *pForQuote, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///询价通知 typedef int (WINAPI *DefOnRtnForQuoteRsp)(CThostFtdcForQuoteRspField *pForQuoteRsp); ///询价录入请求响应 typedef int (WINAPI *DefOnRspForQuoteInsert)(CThostFtdcInputForQuoteField *pInputForQuote, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///询价录入错误回报 typedef int (WINAPI *DefOnErrRtnForQuoteInsert)(CThostFtdcInputForQuoteField *pInputForQuote, CThostFtdcRspInfoField *pRspInfo); ///请求查询报价响应 typedef int (WINAPI *DefOnRspQryQuote)(CThostFtdcQuoteField *pQuote, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///报价通知 typedef int (WINAPI *DefOnRtnQuote)(CThostFtdcQuoteField *pQuote); ///报价录入请求响应 typedef int (WINAPI *DefOnRspQuoteInsert)(CThostFtdcInputQuoteField *pInputQuote, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///报价录入错误回报 typedef int (WINAPI *DefOnErrRtnQuoteInsert)(CThostFtdcInputQuoteField *pInputQuote, CThostFtdcRspInfoField *pRspInfo); ///报价操作请求响应 typedef int (WINAPI *DefOnRspQuoteAction)(CThostFtdcInputQuoteActionField *pInputQuoteAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///报价操作错误回报 typedef int (WINAPI *DefOnErrRtnQuoteAction)(CThostFtdcQuoteActionField *pQuoteAction, CThostFtdcRspInfoField *pRspInfo); ///请求查询执行宣告响应 typedef int (WINAPI *DefOnRspQryExecOrder)(CThostFtdcExecOrderField *pExecOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///执行宣告通知 typedef int (WINAPI *DefOnRtnExecOrder)(CThostFtdcExecOrderField *pExecOrder); ///执行宣告录入请求响应 typedef int (WINAPI *DefOnRspExecOrderInsert)(CThostFtdcInputExecOrderField *pInputExecOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///执行宣告录入错误回报 typedef int (WINAPI *DefOnErrRtnExecOrderInsert)(CThostFtdcInputExecOrderField *pInputExecOrder, CThostFtdcRspInfoField *pRspInfo); ///执行宣告操作请求响应 typedef int (WINAPI *DefOnRspExecOrderAction)(CThostFtdcInputExecOrderActionField *pInputExecOrderAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///执行宣告操作错误回报 typedef int (WINAPI *DefOnErrRtnExecOrderAction)(CThostFtdcExecOrderActionField *pExecOrderAction, CThostFtdcRspInfoField *pRspInfo); ///申请组合录入请求响应 typedef int (WINAPI *DefOnRspCombActionInsert) (CThostFtdcInputCombActionField *pInputCombAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询组合合约安全系数响应 typedef int (WINAPI *DefOnRspQryCombInstrumentGuard) (CThostFtdcCombInstrumentGuardField *pCombInstrumentGuard, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询申请组合响应 typedef int (WINAPI *DefOnRspQryCombAction) (CThostFtdcCombActionField *pCombAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///申请组合通知 typedef int (WINAPI *DefOnRtnCombAction) (CThostFtdcCombActionField *pCombAction); ///申请组合录入错误回报 typedef int (WINAPI *DefOnErrRtnCombActionInsert) (CThostFtdcInputCombActionField *pInputCombAction, CThostFtdcRspInfoField *pRspInfo); ///请求查询投资者品种/跨品种保证金响应 typedef int (WINAPI *DefOnRspQryInvestorProductGroupMargin)(CThostFtdcInvestorProductGroupMarginField *pInvestorProductGroupMargin, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询交易所调整保证金率响应 typedef int (WINAPI *DefOnRspQryExchangeMarginRateAdjust)(CThostFtdcExchangeMarginRateAdjustField *pExchangeMarginRateAdjust, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询汇率响应 typedef int (WINAPI *DefOnRspQryExchangeRate)(CThostFtdcExchangeRateField *pExchangeRate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询产品报价汇率 typedef int (WINAPI *DefOnRspQryProductExchRate)(CThostFtdcProductExchRateField *pProductExchRate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///批量报单操作请求响应 typedef int (WINAPI *DefOnRspBatchOrderAction)(CThostFtdcInputBatchOrderActionField *pInputBatchOrderAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询产品组 typedef int (WINAPI *DefOnRspQryProductGroup)(CThostFtdcProductGroupField *pProductGroup, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询做市商合约手续费率响应 typedef int (WINAPI *DefOnRspQryMMInstrumentCommissionRate)(CThostFtdcMMInstrumentCommissionRateField *pMMInstrumentCommissionRate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询做市商期权合约手续费响应 typedef int (WINAPI *DefOnRspQryMMOptionInstrCommRate)(CThostFtdcMMOptionInstrCommRateField *pMMOptionInstrCommRate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询报单手续费响应 typedef int (WINAPI *DefOnRspQryInstrumentOrderCommRate)(CThostFtdcInstrumentOrderCommRateField *pInstrumentOrderCommRate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///交易所公告通知 typedef int (WINAPI *DefOnRtnBulletin)(CThostFtdcBulletinField *pBulletin); ///批量报单操作错误回报 typedef int (WINAPI *DefOnErrRtnBatchOrderAction)(CThostFtdcBatchOrderActionField *pBatchOrderAction, CThostFtdcRspInfoField *pRspInfo); class CTraderSpi : public CThostFtdcTraderSpi { public: ///当客户端与交易后台建立起通信连接时(还未登录前),该方法被调用。 virtual void OnFrontConnected(); ///当客户端与交易后台通信连接断开时,该方法被调用。当发生这个情况后,API会自动重新连接,客户端可不做处理。 ///@param nReason 错误原因 /// 0x1001 网络读失败 /// 0x1002 网络写失败 /// 0x2001 接收心跳超时 /// 0x2002 发送心跳失败 /// 0x2003 收到错误报文 virtual void OnFrontDisconnected(int nReason); ///心跳超时警告。当长时间未收到报文时,该方法被调用。 ///@param nTimeLapse 距离上次接收报文的时间 virtual void OnHeartBeatWarning(int nTimeLapse); ///客户端认证响应 virtual void OnRspAuthenticate(CThostFtdcRspAuthenticateField *pRspAuthenticateField, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///登录请求响应 virtual void OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///登出请求响应 virtual void OnRspUserLogout(CThostFtdcUserLogoutField *pUserLogout, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///用户口令更新请求响应 virtual void OnRspUserPasswordUpdate(CThostFtdcUserPasswordUpdateField *pUserPasswordUpdate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///资金账户口令更新请求响应 virtual void OnRspTradingAccountPasswordUpdate(CThostFtdcTradingAccountPasswordUpdateField *pTradingAccountPasswordUpdate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///报单录入请求响应 virtual void OnRspOrderInsert(CThostFtdcInputOrderField *pInputOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///预埋单录入请求响应 virtual void OnRspParkedOrderInsert(CThostFtdcParkedOrderField *pParkedOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///预埋撤单录入请求响应 virtual void OnRspParkedOrderAction(CThostFtdcParkedOrderActionField *pParkedOrderAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///报单操作请求响应 virtual void OnRspOrderAction(CThostFtdcInputOrderActionField *pInputOrderAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///查询最大报单数量响应 virtual void OnRspQueryMaxOrderVolume(CThostFtdcQueryMaxOrderVolumeField *pQueryMaxOrderVolume, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///投资者结算结果确认响应 virtual void OnRspSettlementInfoConfirm(CThostFtdcSettlementInfoConfirmField *pSettlementInfoConfirm, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///删除预埋单响应 virtual void OnRspRemoveParkedOrder(CThostFtdcRemoveParkedOrderField *pRemoveParkedOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///删除预埋撤单响应 virtual void OnRspRemoveParkedOrderAction(CThostFtdcRemoveParkedOrderActionField *pRemoveParkedOrderAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///执行宣告录入请求响应 virtual void OnRspExecOrderInsert(CThostFtdcInputExecOrderField *pInputExecOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///执行宣告操作请求响应 virtual void OnRspExecOrderAction(CThostFtdcInputExecOrderActionField *pInputExecOrderAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///询价录入请求响应 virtual void OnRspForQuoteInsert(CThostFtdcInputForQuoteField *pInputForQuote, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///报价录入请求响应 virtual void OnRspQuoteInsert(CThostFtdcInputQuoteField *pInputQuote, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///报价操作请求响应 virtual void OnRspQuoteAction(CThostFtdcInputQuoteActionField *pInputQuoteAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///批量报单操作请求响应 virtual void OnRspBatchOrderAction(CThostFtdcInputBatchOrderActionField *pInputBatchOrderAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///申请组合录入请求响应 virtual void OnRspCombActionInsert(CThostFtdcInputCombActionField *pInputCombAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询报单响应 virtual void OnRspQryOrder(CThostFtdcOrderField *pOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询成交响应 virtual void OnRspQryTrade(CThostFtdcTradeField *pTrade, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询投资者持仓响应 virtual void OnRspQryInvestorPosition(CThostFtdcInvestorPositionField *pInvestorPosition, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询资金账户响应 virtual void OnRspQryTradingAccount(CThostFtdcTradingAccountField *pTradingAccount, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询投资者响应 virtual void OnRspQryInvestor(CThostFtdcInvestorField *pInvestor, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询交易编码响应 virtual void OnRspQryTradingCode(CThostFtdcTradingCodeField *pTradingCode, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询合约保证金率响应 virtual void OnRspQryInstrumentMarginRate(CThostFtdcInstrumentMarginRateField *pInstrumentMarginRate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询合约手续费率响应 virtual void OnRspQryInstrumentCommissionRate(CThostFtdcInstrumentCommissionRateField *pInstrumentCommissionRate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询交易所响应 virtual void OnRspQryExchange(CThostFtdcExchangeField *pExchange, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询产品响应 virtual void OnRspQryProduct(CThostFtdcProductField *pProduct, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询合约响应 virtual void OnRspQryInstrument(CThostFtdcInstrumentField *pInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询行情响应 virtual void OnRspQryDepthMarketData(CThostFtdcDepthMarketDataField *pDepthMarketData, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询投资者结算结果响应 virtual void OnRspQrySettlementInfo(CThostFtdcSettlementInfoField *pSettlementInfo, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询转帐银行响应 virtual void OnRspQryTransferBank(CThostFtdcTransferBankField *pTransferBank, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询投资者持仓明细响应 virtual void OnRspQryInvestorPositionDetail(CThostFtdcInvestorPositionDetailField *pInvestorPositionDetail, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询客户通知响应 virtual void OnRspQryNotice(CThostFtdcNoticeField *pNotice, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询结算信息确认响应 virtual void OnRspQrySettlementInfoConfirm(CThostFtdcSettlementInfoConfirmField *pSettlementInfoConfirm, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询投资者持仓明细响应 virtual void OnRspQryInvestorPositionCombineDetail(CThostFtdcInvestorPositionCombineDetailField *pInvestorPositionCombineDetail, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///查询保证金监管系统经纪公司资金账户密钥响应 virtual void OnRspQryCFMMCTradingAccountKey(CThostFtdcCFMMCTradingAccountKeyField *pCFMMCTradingAccountKey, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询仓单折抵信息响应 virtual void OnRspQryEWarrantOffset(CThostFtdcEWarrantOffsetField *pEWarrantOffset, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询投资者品种/跨品种保证金响应 virtual void OnRspQryInvestorProductGroupMargin(CThostFtdcInvestorProductGroupMarginField *pInvestorProductGroupMargin, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询交易所保证金率响应 virtual void OnRspQryExchangeMarginRate(CThostFtdcExchangeMarginRateField *pExchangeMarginRate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询交易所调整保证金率响应 virtual void OnRspQryExchangeMarginRateAdjust(CThostFtdcExchangeMarginRateAdjustField *pExchangeMarginRateAdjust, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询汇率响应 virtual void OnRspQryExchangeRate(CThostFtdcExchangeRateField *pExchangeRate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询二级代理操作员银期权限响应 virtual void OnRspQrySecAgentACIDMap(CThostFtdcSecAgentACIDMapField *pSecAgentACIDMap, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询产品报价汇率 virtual void OnRspQryProductExchRate(CThostFtdcProductExchRateField *pProductExchRate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询产品组 virtual void OnRspQryProductGroup(CThostFtdcProductGroupField *pProductGroup, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询做市商合约手续费率响应 virtual void OnRspQryMMInstrumentCommissionRate(CThostFtdcMMInstrumentCommissionRateField *pMMInstrumentCommissionRate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询做市商期权合约手续费响应 virtual void OnRspQryMMOptionInstrCommRate(CThostFtdcMMOptionInstrCommRateField *pMMOptionInstrCommRate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询报单手续费响应 virtual void OnRspQryInstrumentOrderCommRate(CThostFtdcInstrumentOrderCommRateField *pInstrumentOrderCommRate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询期权交易成本响应 virtual void OnRspQryOptionInstrTradeCost(CThostFtdcOptionInstrTradeCostField *pOptionInstrTradeCost, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询期权合约手续费响应 virtual void OnRspQryOptionInstrCommRate(CThostFtdcOptionInstrCommRateField *pOptionInstrCommRate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询执行宣告响应 virtual void OnRspQryExecOrder(CThostFtdcExecOrderField *pExecOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询询价响应 virtual void OnRspQryForQuote(CThostFtdcForQuoteField *pForQuote, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询报价响应 virtual void OnRspQryQuote(CThostFtdcQuoteField *pQuote, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询组合合约安全系数响应 virtual void OnRspQryCombInstrumentGuard(CThostFtdcCombInstrumentGuardField *pCombInstrumentGuard, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询申请组合响应 virtual void OnRspQryCombAction(CThostFtdcCombActionField *pCombAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询转帐流水响应 virtual void OnRspQryTransferSerial(CThostFtdcTransferSerialField *pTransferSerial, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询银期签约关系响应 virtual void OnRspQryAccountregister(CThostFtdcAccountregisterField *pAccountregister, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///错误应答 virtual void OnRspError(CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///报单通知 virtual void OnRtnOrder(CThostFtdcOrderField *pOrder); ///成交通知 virtual void OnRtnTrade(CThostFtdcTradeField *pTrade); ///报单录入错误回报 virtual void OnErrRtnOrderInsert(CThostFtdcInputOrderField *pInputOrder, CThostFtdcRspInfoField *pRspInfo); ///报单操作错误回报 virtual void OnErrRtnOrderAction(CThostFtdcOrderActionField *pOrderAction, CThostFtdcRspInfoField *pRspInfo); ///合约交易状态通知 virtual void OnRtnInstrumentStatus(CThostFtdcInstrumentStatusField *pInstrumentStatus); ///交易所公告通知 virtual void OnRtnBulletin(CThostFtdcBulletinField *pBulletin); ///交易通知 virtual void OnRtnTradingNotice(CThostFtdcTradingNoticeInfoField *pTradingNoticeInfo); ///提示条件单校验错误 virtual void OnRtnErrorConditionalOrder(CThostFtdcErrorConditionalOrderField *pErrorConditionalOrder); ///执行宣告通知 virtual void OnRtnExecOrder(CThostFtdcExecOrderField *pExecOrder); ///执行宣告录入错误回报 virtual void OnErrRtnExecOrderInsert(CThostFtdcInputExecOrderField *pInputExecOrder, CThostFtdcRspInfoField *pRspInfo); ///执行宣告操作错误回报 virtual void OnErrRtnExecOrderAction(CThostFtdcExecOrderActionField *pExecOrderAction, CThostFtdcRspInfoField *pRspInfo); ///询价录入错误回报 virtual void OnErrRtnForQuoteInsert(CThostFtdcInputForQuoteField *pInputExecOrder, CThostFtdcRspInfoField *pRspInfo); ///报价通知 virtual void OnRtnQuote(CThostFtdcQuoteField *pQuote); ///报价录入错误回报 virtual void OnErrRtnQuoteInsert(CThostFtdcInputQuoteField *pInputQuote, CThostFtdcRspInfoField *pRspInfo); ///报价操作错误回报 virtual void OnErrRtnQuoteAction(CThostFtdcQuoteActionField *pQuoteAction, CThostFtdcRspInfoField *pRspInfo); ///询价通知 virtual void OnRtnForQuoteRsp(CThostFtdcForQuoteRspField *pForQuoteRsp); ///保证金监控中心用户令牌 virtual void OnRtnCFMMCTradingAccountToken(CThostFtdcCFMMCTradingAccountTokenField *pCFMMCTradingAccountToken); ///批量报单操作错误回报 virtual void OnErrRtnBatchOrderAction(CThostFtdcBatchOrderActionField *pBatchOrderAction, CThostFtdcRspInfoField *pRspInfo); ///申请组合通知 virtual void OnRtnCombAction(CThostFtdcCombActionField *pCombAction); ///申请组合录入错误回报 virtual void OnErrRtnCombActionInsert(CThostFtdcInputCombActionField *pInputCombAction, CThostFtdcRspInfoField *pRspInfo); ///请求查询签约银行响应 virtual void OnRspQryContractBank(CThostFtdcContractBankField *pContractBank, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询预埋单响应 virtual void OnRspQryParkedOrder(CThostFtdcParkedOrderField *pParkedOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询预埋撤单响应 virtual void OnRspQryParkedOrderAction(CThostFtdcParkedOrderActionField *pParkedOrderAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询交易通知响应 virtual void OnRspQryTradingNotice(CThostFtdcTradingNoticeField *pTradingNotice, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询经纪公司交易参数响应 virtual void OnRspQryBrokerTradingParams(CThostFtdcBrokerTradingParamsField *pBrokerTradingParams, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询经纪公司交易算法响应 virtual void OnRspQryBrokerTradingAlgos(CThostFtdcBrokerTradingAlgosField *pBrokerTradingAlgos, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///请求查询监控中心用户令牌 virtual void OnRspQueryCFMMCTradingAccountToken(CThostFtdcQueryCFMMCTradingAccountTokenField *pQueryCFMMCTradingAccountToken, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///银行发起银行资金转期货通知 virtual void OnRtnFromBankToFutureByBank(CThostFtdcRspTransferField *pRspTransfer); ///银行发起期货资金转银行通知 virtual void OnRtnFromFutureToBankByBank(CThostFtdcRspTransferField *pRspTransfer); ///银行发起冲正银行转期货通知 virtual void OnRtnRepealFromBankToFutureByBank(CThostFtdcRspRepealField *pRspRepeal); ///银行发起冲正期货转银行通知 virtual void OnRtnRepealFromFutureToBankByBank(CThostFtdcRspRepealField *pRspRepeal); ///期货发起银行资金转期货通知 virtual void OnRtnFromBankToFutureByFuture(CThostFtdcRspTransferField *pRspTransfer); ///期货发起期货资金转银行通知 virtual void OnRtnFromFutureToBankByFuture(CThostFtdcRspTransferField *pRspTransfer); ///系统运行时期货端手工发起冲正银行转期货请求,银行处理完毕后报盘发回的通知 virtual void OnRtnRepealFromBankToFutureByFutureManual(CThostFtdcRspRepealField *pRspRepeal); ///系统运行时期货端手工发起冲正期货转银行请求,银行处理完毕后报盘发回的通知 virtual void OnRtnRepealFromFutureToBankByFutureManual(CThostFtdcRspRepealField *pRspRepeal); ///期货发起查询银行余额通知 virtual void OnRtnQueryBankBalanceByFuture(CThostFtdcNotifyQueryAccountField *pNotifyQueryAccount); ///期货发起银行资金转期货错误回报 virtual void OnErrRtnBankToFutureByFuture(CThostFtdcReqTransferField *pReqTransfer, CThostFtdcRspInfoField *pRspInfo); ///期货发起期货资金转银行错误回报 virtual void OnErrRtnFutureToBankByFuture(CThostFtdcReqTransferField *pReqTransfer, CThostFtdcRspInfoField *pRspInfo); ///系统运行时期货端手工发起冲正银行转期货错误回报 virtual void OnErrRtnRepealBankToFutureByFutureManual(CThostFtdcReqRepealField *pReqRepeal, CThostFtdcRspInfoField *pRspInfo); ///系统运行时期货端手工发起冲正期货转银行错误回报 virtual void OnErrRtnRepealFutureToBankByFutureManual(CThostFtdcReqRepealField *pReqRepeal, CThostFtdcRspInfoField *pRspInfo); ///期货发起查询银行余额错误回报 virtual void OnErrRtnQueryBankBalanceByFuture(CThostFtdcReqQueryAccountField *pReqQueryAccount, CThostFtdcRspInfoField *pRspInfo); ///期货发起冲正银行转期货请求,银行处理完毕后报盘发回的通知 virtual void OnRtnRepealFromBankToFutureByFuture(CThostFtdcRspRepealField *pRspRepeal); ///期货发起冲正期货转银行请求,银行处理完毕后报盘发回的通知 virtual void OnRtnRepealFromFutureToBankByFuture(CThostFtdcRspRepealField *pRspRepeal); ///期货发起银行资金转期货应答 virtual void OnRspFromBankToFutureByFuture(CThostFtdcReqTransferField *pReqTransfer, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///期货发起期货资金转银行应答 virtual void OnRspFromFutureToBankByFuture(CThostFtdcReqTransferField *pReqTransfer, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///期货发起查询银行余额应答 virtual void OnRspQueryBankAccountMoneyByFuture(CThostFtdcReqQueryAccountField *pReqQueryAccount, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast); ///银行发起银期开户通知 virtual void OnRtnOpenAccountByBank(CThostFtdcOpenAccountField *pOpenAccount); ///银行发起银期销户通知 virtual void OnRtnCancelAccountByBank(CThostFtdcCancelAccountField *pCancelAccount); ///银行发起变更银行账号通知 virtual void OnRtnChangeAccountByBank(CThostFtdcChangeAccountField *pChangeAccount); private: CThostFtdcRspInfoField* repareInfo(CThostFtdcRspInfoField *pRspInfo); // 是否收到成功的响应 bool IsErrorRspInfo(CThostFtdcRspInfoField *pRspInfo); // 是否我的报单回报 bool IsMyOrder(CThostFtdcOrderField *pOrder); // 是否正在交易的报单 bool IsTradingOrder(CThostFtdcOrderField *pOrder); };
9a156b97ae7226278c39c347f1702a157db3dc9a
9ab3f1c2c44cd8221dddd0261296a3860fee4649
/src/lifish/GameContext.cpp
bc08dfa51eade2e86df25ee31ca3f1a9f77f57ad
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-other-permissive" ]
permissive
DrSh4dow/lifish
42d020a6751509fc6159e66fee12fe7f214209e1
8bffe917306ab5c1029f81eea6a8d24e4d6c721c
refs/heads/master
2022-11-17T14:19:03.474089
2020-07-09T05:46:02
2020-07-09T05:46:02
278,274,696
1
0
NOASSERTION
2020-07-09T05:48:38
2020-07-09T05:48:37
null
UTF-8
C++
false
false
9,530
cpp
#include "GameContext.hpp" #include "BaseEventHandler.hpp" #include "Bonusable.hpp" #include "Controllable.hpp" #include "Killable.hpp" #include "Music.hpp" #include "MusicManager.hpp" #include "Options.hpp" #include "Player.hpp" #include "SHCollisionDetector.hpp" #include "save_load.hpp" #include "bonus_type.hpp" #include "contexts.hpp" #include "core.hpp" #include "input_utils.hpp" #include "CameraShake.hpp" #include "CameraShakeRequest.hpp" #include "GlobalDataPipe.hpp" #ifndef RELEASE # include <iostream> # include <iomanip> # include "DebugRenderer.hpp" # include "DebugEventHandler.hpp" # include "game_logic.hpp" # include "DebugPainter.hpp" #endif using lif::GameContext; GameContext::GameContext(sf::Window& window, const std::string& levelsetName, short startLv) : lif::WindowContext() , window(window) , lm() , sidePanel(lm) , wlHandler(lm, sidePanel) { _addHandler<lif::BaseEventHandler>(); #ifndef RELEASE _addHandler<lif::debug::DebugEventHandler>(std::ref(*this)); #endif gameRenderTex.create(lif::GAME_WIDTH, lif::GAME_HEIGHT); sidePanelRenderTex.create(lif::SIDE_PANEL_WIDTH, lif::GAME_HEIGHT); levelSetGood = ls.loadFromFile(levelsetName); if (levelSetGood) _initLM(window, startLv); } void GameContext::_initLM(const sf::Window& window, short lvnum) { if (lvnum > ls.getLevelsNum()) lvnum %= ls.getLevelsNum(); else while (lvnum <= 0) lvnum += ls.getLevelsNum(); // Create the players lm.reset(); lm.createNewPlayers(lif::options.nPlayers); for (unsigned i = 0; i < lif::MAX_PLAYERS; ++i) { auto p = lm.getPlayer(i + 1); if (p != nullptr) p->get<lif::Controllable>()->setWindow(window); } lm.setLevel(ls, lvnum); if (lm.getLevel() == nullptr) throw std::invalid_argument("Level " + lif::to_string(lvnum) + " not found in levelset!"); } void GameContext::onLevelStart() { // Setup the music lif::musicManager->set(lm.getLevel()->get<lif::Music>()->getMusic()) .setVolume(lif::options.musicVolume) .play(); // Ensure lm is not paused lm.resume(); } void GameContext::loadGame(const lif::SaveData& saveData) { levelSetGood = ls.loadFromFile(std::string(lif::pwd) + DIRSEP + saveData.levelSet); if (!levelSetGood) return; lif::options.nPlayers = saveData.nPlayers; _initLM(window, saveData.level); lm.loadGame(saveData); } void GameContext::setActive(bool b) { lif::Activable::setActive(b); if (active) lm.resume(); } void GameContext::update() { #ifndef RELEASE if (!((debug >> DBG_NO_PAINT_CLEAR) & 1)) lif::debugPainter->clear(); #endif // Handle win / loss cases wlHandler.handleWinLose(); switch (wlHandler.getState()) { using S = lif::WinLoseHandler::State; case S::ADVANCING_LEVEL: // Handle cutscenePost if (lm.getLevel()->getInfo().cutscenePost.length() > 0) newContext = lif::CTX_CUTSCENE; else newContext = lif::CTX_INTERLEVEL; return; case S::ADVANCED_LEVEL: _advanceLevel(); onLevelStart(); break; case S::RETRY_LEVEL: retryingLevel = true; newContext = lif::CTX_INTERLEVEL; break; case S::EXIT_GAME: newContext = lif::CTX_UI; break; default: break; } // Check for pending CameraShakes and add them to entities auto& cameraShakeRequests = lif::GlobalDataPipe<lif::CameraShakeRequest>::getInstance(); while (cameraShakeRequests.hasData()) lm.getEntities().add(new lif::CameraShake(gameRenderTex, cameraShakeRequests.pop())); // Update level if (!lm.isPaused()) { lm.update(); sidePanel.update(); } #ifndef RELEASE if (cycle % 50 == 0 && (debug >> DBG_PRINT_CD_STATS) & 1) _printCDStats(); if (cycle % 50 == 0 && (debug >> DBG_PRINT_GAME_STATS) & 1) _printGameStats(); ++cycle; #endif } bool GameContext::handleEvent(sf::Window&, sf::Event event) { const auto pause_game = [this] () { lm.pause(); newContext = lif::CTX_UI; }; switch (event.type) { case sf::Event::JoystickButtonPressed: { const auto btn = event.joystickButton; if (lif::joystick::isButton(lif::joystick::ButtonType::START, btn.joystickId, btn.button)) pause_game(); return true; } case sf::Event::KeyPressed: switch (event.key.code) { case sf::Keyboard::P: pause_game(); return true; case sf::Keyboard::Escape: for (unsigned i = 0; i < lif::MAX_PLAYERS; ++i) { auto player = lm.getPlayer(i + 1); if (player != nullptr) { player->setRemainingLives(0); player->get<lif::Killable>()->kill(); } } return true; default: break; } default: break; } return false; } void GameContext::draw(sf::RenderTarget& window, sf::RenderStates states) const { // Draw the LevelManager in its render texture gameRenderTex.clear(); if (newContext == lif::CTX_CUTSCENE) return; gameRenderTex.draw(lm, states); #ifndef RELEASE if ((debug >> DBG_DRAW_COLLIDERS) & 1) lif::debug::DebugRenderer::drawColliders(lm.getEntities()); if ((debug >> DBG_DRAW_SH_CELLS) & 1) { const auto sh = dynamic_cast<const lif::SHCollisionDetector*>(&lm.getCollisionDetector()); if (sh != nullptr) lif::debug::DebugRenderer::drawSHCells(*sh); } gameRenderTex.draw(*lif::debugPainter, states); #endif gameRenderTex.display(); // Draw the SidePanel in its render texture sidePanelRenderTex.clear(); sidePanelRenderTex.draw(sidePanel, states); sidePanelRenderTex.display(); // Draw both textures to window sf::Sprite gameSprite(gameRenderTex.getTexture()); gameSprite.setOrigin(origin); window.draw(gameSprite, states); sf::Sprite sidePanelSprite(sidePanelRenderTex.getTexture()); window.draw(sidePanelSprite, states); } void GameContext::_advanceLevel() { const auto *level = lm.getLevel(); if (level == nullptr) throw std::logic_error("Called _advanceLevel on null level!"); short lvnum = level->getInfo().levelnum; const auto& ls = level->getLevelSet(); if (lvnum == ls.getLevelsNum()) { // TODO game won //return; } _resurrectDeadPlayers(); if (retryingLevel) { lm.resetLevel(); retryingLevel = false; } else { lm.setNextLevel(); } level = lm.getLevel(); if (level == nullptr) throw std::logic_error("No levels found after " + lif::to_string(lvnum) + " but end game not triggered!"); //lif::musicManager->set(level->get<lif::Music>()->getMusic()) //.setVolume(lif::options.musicVolume) //.play(); // If level has a cutscene, play it if (level->getInfo().cutscenePre.length() > 0) newContext = lif::CTX_CUTSCENE; } void GameContext::_resurrectDeadPlayers() { // Resurrect any dead player which has a 'continue' left and // remove temporary effects for (unsigned i = 0; i < lif::MAX_PLAYERS; ++i) { auto player = lm.getPlayer(i + 1); if ((player == nullptr || player->get<lif::Killable>()->isKilled())) { if (lm.getPlayerContinues(i + 1) > 0) { lm.decPlayerContinues(i + 1); auto player = std::make_shared<Player>(sf::Vector2f(0, 0), i + 1); player->get<lif::Controllable>()->setWindow(window); lm.setPlayer(i + 1, player); } else { lm.removePlayer(i + 1); } } else if (player != nullptr) { auto bns = player->get<lif::Bonusable>(); bns->expireTemporaryBonuses(); } } } #ifndef RELEASE void GameContext::toggleDebug(unsigned int flag) { debug ^= 1 << flag; } void GameContext::_printCDStats() const { const auto& dbgStats = lm.getCollisionDetector().getStats(); std::stringstream ss; ss << std::setfill(' ') << std::scientific << std::setprecision(2) << "#checked: " << std::setw(5) << dbgStats.counter.safeGet("checked") << " | tot: " << std::setw(6) << dbgStats.timer.safeGet("tot") * 1000 << " | tot_narrow: " << std::setw(6) << dbgStats.timer.safeGet("tot_narrow") * 1000 << " | setup: " << std::setw(6) << dbgStats.timer.safeGet("setup") * 1000 << " | average: " << std::setw(6) << dbgStats.timer.safeGet("tot_narrow")/dbgStats.counter.safeGet("checked") * 1000 << " (ms)" << std::endl; std::cout << ss.str(); } static float getPercentage(const lif::debug::Stats& stats, const char *totn, const char *name, char *percentage) { const auto tot = stats.timer.safeGet(totn); if (tot < 0) return -1; const float ratio = stats.timer.safeGet(name) / tot; if (ratio < 0) return -1; for (unsigned i = 0; i < 20; ++i) { if (ratio < i/20.) break; percentage[i] = '|'; } return ratio; } void GameContext::_printGameStats() const { const auto& dbgStats = lm.getStats(); static const auto timers = { "tot", "reset_align", "validate", "cd", "logic", "ent_update", "checks" }; std::stringstream ss; ss << "-------------"; ss << std::setfill(' ') << std::setprecision(3); for (const auto& t : timers) { char percentage[21] = {0}; const float ratio = getPercentage(dbgStats, "tot", t, percentage); ss << "\r\n | " << std::left << std::setw(12) << t << ": " << std::setw(7) << dbgStats.timer.safeGet(t) * 1000 << "ms " << percentage << (ratio >= 0 ? " " + lif::to_string(static_cast<int>(ratio*100)) + "%" : ""); } ss << "\r\n\r\n-- logic: --"; static const std::array<const char*, 4> logicName = {{ "bombDeploy", "bonusGrab", "scoredKlb", "spawning" }}; for (unsigned i = 0; i < lif::game_logic::functions.size(); ++i) { std::stringstream t; t << "logic_" << i; char percentage[21] = {0}; const float ratio = getPercentage(dbgStats, "logic", t.str().c_str(), percentage); ss << "\r\n | " << std::left << std::setw(12) << logicName[i] << ": " << std::setw(7) << dbgStats.timer.safeGet(t.str()) * 1000 << "ms " << percentage << (ratio >= 0 ? " " + lif::to_string(static_cast<int>(ratio*100)) + "%" : ""); } ss << std::endl; std::cout << ss.str(); } #endif
819668f71fda1570dcc30cfc02f068efcfc333ae
9f97c42310f47505eda2b5d6be28294dee7f0f15
/src/qt/csvmodelwriter.cpp
400e94fecab236f39b4c14231ed673d9077609d7
[ "MIT" ]
permissive
Madurajaya/cicoin
b7bc3cd65ef665e8c23d6787bb732d211b46e4f3
b48b11574ae38ae063670a755b9d50ef6960e1e8
refs/heads/master
2022-04-13T21:04:57.846103
2020-04-01T05:30:32
2020-04-01T05:30:32
296,742,986
1
0
MIT
2020-09-18T22:37:12
2020-09-18T22:37:12
null
UTF-8
C++
false
false
1,888
cpp
// Copyright (c) 2011-2018 The Cicoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <qt/csvmodelwriter.h> #include <QAbstractItemModel> #include <QFile> #include <QTextStream> CSVModelWriter::CSVModelWriter(const QString &_filename, QObject *parent) : QObject(parent), filename(_filename), model(nullptr) { } void CSVModelWriter::setModel(const QAbstractItemModel *_model) { this->model = _model; } void CSVModelWriter::addColumn(const QString &title, int column, int role) { Column col; col.title = title; col.column = column; col.role = role; columns.append(col); } static void writeValue(QTextStream &f, const QString &value) { QString escaped = value; escaped.replace('"', "\"\""); f << "\"" << escaped << "\""; } static void writeSep(QTextStream &f) { f << ","; } static void writeNewline(QTextStream &f) { f << "\n"; } bool CSVModelWriter::write() { QFile file(filename); if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) return false; QTextStream out(&file); int numRows = 0; if(model) { numRows = model->rowCount(); } // Header row for(int i=0; i<columns.size(); ++i) { if(i!=0) { writeSep(out); } writeValue(out, columns[i].title); } writeNewline(out); // Data rows for(int j=0; j<numRows; ++j) { for(int i=0; i<columns.size(); ++i) { if(i!=0) { writeSep(out); } QVariant data = model->index(j, columns[i].column).data(columns[i].role); writeValue(out, data.toString()); } writeNewline(out); } file.close(); return file.error() == QFile::NoError; }
3b085f00a83ff9c0cb08098ebf0f6d0b4274aad5
1cfb67f9b6e885fdcf80d555dde3fd373a1e4643
/Finding-Frequent-Items/CM/Sketchpheap.h
d0f184d3121b49e4804a4273e8cbe98855d2f8f6
[]
no_license
Finding-Significant-Items/Finding-Significant-Items
464303ed4ab8dae5ce55ed8bc4308ff0aada7cf7
b9510d751964b5a6f9f6733851ed9ad0dfd60451
refs/heads/master
2020-03-19T03:13:59.127175
2018-10-31T02:04:53
2018-10-31T02:04:53
135,707,633
4
6
null
null
null
null
UTF-8
C++
false
false
3,246
h
#ifndef _Sketchpheap_H #define _Sketchpheap_H #include <cmath> #include <cstdio> #include <cstdlib> #include <iostream> #include <algorithm> #include <string> #include <cstring> #include "params.h" #include "BOBHASH32.h" #define Total 10000005 #define Count 4 using namespace std; class Sketchpheap { private: BOBHash32 * bobhash[Count+2]; struct node {int val,idx; string ID;} Heap[Total]; int tot[Count][MAX_MEM],head[N],next[Total],m,k,WZ,Q,p,cnt,o,MIN,M2,K,NUM; struct Node {int wz; string ID;} ID_index[Total]; public: Sketchpheap(int NUM,int K):NUM(NUM),K(K) { M2=1000000; for (int i=0; i<=Count; i++) bobhash[i]=new BOBHash32(i+1000); } int Find(int x,string y) { int now=head[x]; while (ID_index[now].ID!=y && now) now=next[now]; if (ID_index[now].ID==y) return ID_index[now].wz; return -1; } void Delete(int x,string y) { if (ID_index[head[x]].ID==y) {head[x]=next[head[x]]; return;} int now=head[x],Last; while (ID_index[now].ID!=y && now) {Last=now; now=next[now];} if (!head[x]) return; next[Last]=next[next[Last]]; } void Change(int x,int y) { swap(ID_index[Heap[x].idx].wz,ID_index[Heap[y].idx].wz); swap(Heap[x].val,Heap[y].val); swap(Heap[x].idx,Heap[y].idx); swap(Heap[x].ID,Heap[y].ID); } void Insert(string A) { MIN=1000000000; for (int i=0; i<Count; i++) { WZ=(bobhash[i]->run(A.c_str(),A.size()))%NUM; tot[i][WZ]++; MIN=min(MIN,tot[i][WZ]); } Q=(bobhash[Count]->run(A.c_str(),A.size()))%M2; p=Find(Q,A); if (p==-1) { Heap[++cnt].val=MIN; Heap[cnt].ID=A; o++; ID_index[o].ID=A; ID_index[o].wz=cnt; next[o]=head[Q]; head[Q]=o; Heap[cnt].idx=o; int now=cnt; while (now>1 && Heap[now].val<Heap[now/2].val) {Change(now,now/2); now/=2;} if (cnt>K) { Change(1,cnt); Delete((bobhash[Count]->run(Heap[cnt].ID.c_str(),Heap[cnt].ID.size()))%M2,Heap[cnt].ID); int now=1; cnt--; while (now*2<=cnt && Heap[now].val>Heap[now*2].val || now*2+1<=cnt && Heap[now].val>Heap[now*2+1].val) { if (Heap[now*2].val<Heap[now*2+1].val || now*2==cnt) {Change(now,now*2); now*=2;} else { Change(now,now*2+1); now=now*2+1; } } } } else { Heap[p].val=MIN; int now=p; while (now>1 && Heap[now].val<Heap[now/2].val) {Change(now,now/2); now/=2;} while (now*2<=cnt && Heap[now].val>Heap[now*2].val || now*2+1<=cnt && Heap[now].val>Heap[now*2+1].val) { if (Heap[now*2].val<Heap[now*2+1].val || now*2==cnt) {Change(now,now*2); now*=2;} else { Change(now,now*2+1); now=now*2+1; } } } } pair<string,int> Query(int k) { return make_pair(Heap[k+1].ID,Heap[k+1].val); } }; #endif
ea14c14e3de66ab68701a2b7ceddec9e6c113b81
9b45098814220b1b9be2abc687c36a941a88d29d
/game_engine/camera.cpp
3c9e75fb2834774d4b0d2b05455beb227c41fad1
[]
no_license
chiquanhuo/game_engine
62c10636fd4f60490c38e7198820f4845ca3c5e4
8fa5eb512bddb35baa4a623f096f6704511c1620
refs/heads/master
2020-03-19T06:31:00.209193
2018-07-12T03:09:43
2018-07-12T03:09:43
136,027,852
0
0
null
null
null
null
UTF-8
C++
false
false
2,049
cpp
// // camera.cpp // game_engine // // Created by 霍志权 on 2018/7/12. // Copyright © 2018年 霍志权. All rights reserved. // #include <stdio.h> #include "camera.hpp" mat4 Camera::GetViewMatrix() { return lookAt(this->Position, this->Position + this->Front, this->Up); } void Camera::ProcessKeyboard(Camera_Movement direction, GLfloat deltaTime) { GLfloat velocity = this->MovementSpeed * deltaTime; if (direction == FORWARD) this->Position += this->Front * velocity; if (direction == BACKWARD) this->Position -= this->Front * velocity; if (direction == LEFT) this->Position -= this->Right * velocity; if (direction == RIGHT) this->Position += this->Right * velocity; } void Camera::ProcessMouseMovement(GLfloat xoffset, GLfloat yoffset, GLboolean constrainPitch) { xoffset *= this->MouseSensitivity; yoffset *= this->MouseSensitivity; this->Yaw += xoffset; this->Pitch += yoffset; // Make sure that when pitch is out of bounds, screen doesn't get flipped if (constrainPitch) { if (this->Pitch > 89.0f) this->Pitch = 89.0f; if (this->Pitch < -89.0f) this->Pitch = -89.0f; } // Update Front, Right and Up Vectors using the updated Eular angles this->updateCameraVectors(); } void Camera::ProcessMouseScroll(GLfloat yoffset) { if (this->Zoom >= 1.0f && this->Zoom <= 45.0f) this->Zoom -= yoffset; if (this->Zoom <= 1.0f) this->Zoom = 1.0f; if (this->Zoom >= 45.0f) this->Zoom = 45.0f; } // angle 计算 front void Camera::updateCameraVectors() { // Calculate the new Front vector vec3 front; front.x = cos(radians(this->Yaw)) * cos(radians(this->Pitch)); front.y = sin(radians(this->Pitch)); front.z = sin(radians(this->Yaw)) * cos(radians(this->Pitch)); this->Front = normalize(front); this->Right = normalize(cross(this->Front, this->WorldUp)); this->Up = normalize(cross(this->Right, this->Front)); }
423ff264b2019e3dd7c92553cd98a46c48a47cac
e99304acf642cdcf258c87a79b49362d3135b296
/PenguinV/example_function_pool/example_function_pool.cpp
91e2be7ae2e98a08d7202d6b6a3e815546e617de
[ "BSD-3-Clause" ]
permissive
bryonglodencissp/penguinV
022b1d34dbf9ddbf088d14b811b51cabd24e5d80
964c1881059bbb5266929a96ba2236f4c6476b1f
refs/heads/master
2021-06-14T17:06:59.570550
2016-09-30T01:08:29
2016-09-30T01:08:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,260
cpp
// Example application of library's function pool utilization #include <iostream> #include "../Library/image_exception.h" #include "../Library/image_function.h" #include "../Library/function_pool.h" #include "../Library/thread_pool.h" void basic(const std::vector < Bitmap_Image::Image > & frame); void multithreaded(const std::vector < Bitmap_Image::Image > & frame); double getElapsedTime( std::chrono::time_point < std::chrono::system_clock > start ); int main() { try // <---- do not forget to put your code into try.. catch block! { // This example is more technical and it shows the difference in software development using // basic functions and using functions with thread pool support. // Plus it evaluates the speed of calculations between two examples. // Please take a note that speed as well as thread count depends on your CPU and // overall system so do not think that this comparison is fully accurate // Conditions: // We have 60 big images (frames) with 1920 x 1080 pixels (60 fps fullHD :) ) // Our aim is pretty simple: we have to find some suspicious objects on frames and highlight them // What we need to do is: // 1. get a difference between two neighbour frames // 2. Find optimum threshold value // 3. Compare threshold value with known value of background // 4. threshold image with threshold // 5. put result on the map // Create a set of 60 frames std::vector < Bitmap_Image::Image > frame(60, Bitmap_Image::Image(1920, 1080) ); // Fill background. Let's assume that background varies from 0 to 15 gray scale values std::for_each( frame.begin(), frame.end(), []( Bitmap_Image::Image & image ) { image.fill( static_cast<uint8_t>(rand() % 16) ); } ); // Then add some 'suspicious' objects on some random images std::for_each( frame.begin(), frame.end(), []( Bitmap_Image::Image & image ) { if( rand() % 10 == 0 ) { // at least ~6 of 60 images would have objects // generate random place of object, in our case is rectangle uint32_t x = static_cast<uint32_t>(rand()) % (image.width() * 2 / 3); uint32_t y = static_cast<uint32_t>(rand()) % (image.height() * 2 / 3); uint32_t width = static_cast<uint32_t>(rand()) % (image.width() - x); uint32_t height = static_cast<uint32_t>(rand()) % (image.height() - y); // fill an area with some random value what is bigger than background value Image_Function::Fill( image, x, y, width, height, static_cast<uint8_t>(rand() % 128) + 64 ); } } ); std::cout << "----------" << std::endl << "Basic functions. Evaluating time..." << std::endl << "----------" << std::endl; std::chrono::time_point < std::chrono::system_clock > startTime = std::chrono::system_clock::now(); basic(frame); std::cout << "Total time is " << getElapsedTime(startTime) << " seconds" << std::endl; std::cout << "----------" << std::endl << "Functions with thread pool support. Evaluating time..." << std::endl << "----------" << std::endl; startTime = std::chrono::system_clock::now(); multithreaded(frame); std::cout << "Total time is " << getElapsedTime(startTime) << " seconds" << std::endl; } catch(imageException & ex) { // uh-oh, something went wrong! std::cout << "Exception " << ex.what() << " raised. Do your black magic to recover..." << std::endl; // your magic code must be here to recover from bad things return 0; } catch(std::exception & ex) { // uh-oh, something terrible happen! // it might be that you compiled code in linux without threading parameters std::cout << "Something terrible happen (" << ex.what() << "). Do your black magic to recover..." << std::endl; // your magic code must be here to recover from terrible things return 0; } catch(...) { // uh-oh, something really terrible happen! std::cout << "Something really terrible happen. No idea what it is. Do your black magic to recover..." << std::endl; // your magic code must be here to recover from terrible things return 0; } std::cout << "Everything went fine." << std::endl; return 0; } double getElapsedTime( std::chrono::time_point < std::chrono::system_clock > start ) { std::chrono::time_point < std::chrono::system_clock > end = std::chrono::system_clock::now(); std::chrono::duration < double > time = end - start; return time.count(); }; void basic(const std::vector < Bitmap_Image::Image > & frame) { // Prepare image map Bitmap_Image::Image map( frame.front().width(), frame.front().height() ); map.fill( 0 ); Bitmap_Image::Image result( map.width(), map.height() ); for( size_t i = 0; i + 1 < frame.size(); ++i ) { // subtract one image from another Image_Function::Subtract( frame[i + 1], frame[i], result ); // find optimal threshold uint8_t threshold = Image_Function::GetThreshold( Image_Function::Histogram(result) ); if( threshold > 0 ) { // there is something more than just background! // threshold image Image_Function::Threshold( result, result, threshold ); // add result to the map Image_Function::BitwiseOr( map, result, map ); } } // here we have to save the image map but don't do this in the example } void multithreaded(const std::vector < Bitmap_Image::Image > & frame) { // okay we setup 4 thread in global thread pool Thread_Pool::ThreadPoolMonoid::instance().resize( 4 ); // Prepare image map Bitmap_Image::Image map( frame.front().width(), frame.front().height() ); map.fill( 0 ); Bitmap_Image::Image result( map.width(), map.height() ); // As you see the only difference in this loop is different namespace usage for( size_t i = 0; i + 1 < frame.size(); ++i ) { // subtract one image from another Function_Pool::Subtract( frame[i + 1], frame[i], result ); // find optimal threshold uint8_t threshold = Image_Function::GetThreshold( Function_Pool::Histogram(result) ); if( threshold > 0 ) { // there is something more than just background! // threshold image Function_Pool::Threshold( result, result, threshold ); // add result to the map Function_Pool::BitwiseOr( map, result, map ); } } // here we have to save the image map but don't do this in the example // We stop all threads in thread pool Thread_Pool::ThreadPoolMonoid::instance().stop(); }
618ca3bb25d00c47fbe76aef8d1bf479709a4b35
013caff69e41c36c4efe9359c8ce2ecfb5f659ab
/To the Max-dp.cpp
4dbb1cf4d36c4d4e60d01adc07eee5681b9082bd
[]
no_license
iamsile/ACM
cbe5754bed56b1abb3cfaed6b25b9bffa1ec04a5
d51e43780e33b51c70007ba0702448909f9d0553
refs/heads/master
2016-08-04T02:31:51.523885
2013-09-09T05:36:35
2013-09-09T05:36:35
12,693,702
9
5
null
null
null
null
UTF-8
C++
false
false
3,737
cpp
#include<iostream> using namespace::std; int MaxSum(int *a,int n) { int i,sum,b; sum=a[0]; b=0; for(i=0;i<n;i++) { if(b>0) b+=a[i]; else b=a[i]; if(b>sum) sum=b; } return sum; } int main() { int n; int a[100][100]; int max,lab,sum[102],o,i,j,k; while(cin >> n&&n) { memset(a,0,sizeof(a)); for(i=0;i<n;i++) for(j=0;j<n;j++) cin >> a[i][j]; max=0; for(i=0;i<n;i++) { for(j=i;j<n;j++) { memset(sum,0,sizeof(sum)); for(o=0;o<n;o++) for(k=i; k<=j; k++) sum[o]+=a[k][o]; lab=MaxSum(sum,n); if(lab>max) max=lab; } } cout << max << '\n'; } } /* #include <iostream> #include <stdio.h> using namespace std; int main() { int n; while (~scanf("%d",&n)) { int i,j,k,maxn=0,a[110][110]={0},b[110][110]={0},dp[110]={0}; for (i=1; i<=n; i++) for (j=1; j<=n; j++) cin >> a[i][j]; for (i=1; i<=n; i++) b[1][i]=a[1][i]; for (i=2; i<=n; i++) for (j=1; j<=n; j++) b[i][j]=b[i-1][j]+a[i][j]; for (i=1; i<=n; i++) for (j=i; j<=n; j++) { dp[1]=b[j][1]-b[i-1][1]; for (k=2; k<=n; k++) { if (dp[k-1]>0) dp[k]=dp[k-1]+b[j][k]-b[i-1][k]; else dp[k]=b[j][k]-b[i-1][k]; if (dp[k]>maxn) maxn=dp[k]; } } cout << maxn << '\n'; } return 0; } */ /*这个问题可以看做一维的延伸,求子矩阵的元素和的最大值,就是求二维中几列连续元素和的最大值; 思路:在这里的N行中先选定对应的行 for(i=0;i<n;i++) for(j=i;j<n;j++) 选定了行之后,将一列中的元素全部相加,作为一个数字看待,这时就是一维求最大值的问题了; 例子: 2 5 6 3 5 6 9 1 2 -5 -9 6 4 -1 6 8 假设选定了第一到三行:则简化为:11(5+2+4),0(6-5-1),6(9-9+6),15(1+6+8) 则求这一列的最大连续元素和的最大值,(此处可以有很多方法求解,我这里采用了函数法,方便以后重用。)其余行同方法可解; */ /* Problem description Given a two-dimensional array of positive and negative integers, a sub-rectangle is any contiguous sub-array of size 1*1 or greater located within the whole array. The sum of a rectangle is the sum of all the elements in that rectangle. In this problem the sub-rectangle with the largest sum is referred to as the maximal sub-rectangle. As an example, the maximal sub-rectangle of the array: 0 -2 -7 0 9 2 -6 2 -4 1 -4 1 -1 8 0 -2 is in the lower left corner: 9 2 -4 1 -1 8 and has a sum of 15. Input The input consists of an N * N array of integers. The input begins with a single positive integer N on a line by itself, indicating the size of the square two-dimensional array. This is followed by N^2 integers separated by whitespace (spaces and newlines). These are the N^2 integers of the array, presented in row-major order. That is, all numbers in the first row, left to right, then all numbers in the second row, left to right, etc. N may be as large as 100. The numbers in the array will be in the range [-127,127]. Output Output the sum of the maximal sub-rectangle. Sample Input 4 0 -2 -7 0 9 2 -6 2 -4 1 -4 1 -1 8 0 -2 Sample Output 15 */
a58c0b29986c262b59432ce79146d3b01f57c576
78918391a7809832dc486f68b90455c72e95cdda
/boost_lib/boost/python/detail/msvc_typeinfo.hpp
529258a63d4ecc65234fb98e1a43854851f7a4b8
[ "BSL-1.0", "MIT" ]
permissive
kyx0r/FA_Patcher
50681e3e8bb04745bba44a71b5fd04e1004c3845
3f539686955249004b4483001a9e49e63c4856ff
refs/heads/master
2022-03-28T10:03:28.419352
2020-01-02T09:16:30
2020-01-02T09:16:30
141,066,396
2
0
null
null
null
null
UTF-8
C++
false
false
2,207
hpp
// Copyright David Abrahams 2002. // 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) #ifndef MSVC_TYPEINFO_DWA200222_HPP # define MSVC_TYPEINFO_DWA200222_HPP #include <typeinfo> #include <boost/type.hpp> // // Fix for icc's broken typeid() implementation which doesn't strip // decoration. This fix doesn't handle cv-qualified array types. It // could probably be done, but I haven't figured it out yet. // // Note: This file is badly named. It initially was MSVC specific, but was // extended to cover intel too. Now the old version of MSVC is no longer // supported, but the intel version is still supported. # if defined(BOOST_INTEL_CXX_VERSION) && BOOST_INTEL_CXX_VERSION <= 700 namespace boost { namespace python { namespace detail { typedef std::type_info const& typeinfo; template <class T> static typeinfo typeid_nonref(T const volatile*) { return typeid(T); } template <class T> inline typeinfo typeid_ref_1(T&(*)()) { return detail::typeid_nonref((T*)0); } // A non-reference template <class T> inline typeinfo typeid_ref(type<T>*, T&(*)(type<T>)) { return detail::typeid_nonref((T*)0); } // A reference template <class T> inline typeinfo typeid_ref(type<T>*, ...) { return detail::typeid_ref_1((T(*)())0); } #if defined(BOOST_MSVC) || (defined(__BORLANDC__) && !defined(BOOST_DISABLE_WIN32)) # define BOOST_PYTT_DECL __cdecl #else # define BOOST_PYTT_DECL /**/ #endif template< typename T > T&(* is_ref_tester1(type<T>) )(type<T>) { return 0; } inline char BOOST_PYTT_DECL is_ref_tester1(...) { return 0; } template <class T> inline typeinfo msvc_typeid(boost::type<T>*) { return detail::typeid_ref( (boost::type<T>*)0, detail::is_ref_tester1(type<T>()) ); } template <> inline typeinfo msvc_typeid<void>(boost::type<void>*) { return typeid(void); } # ifndef NDEBUG inline typeinfo assert_array_typeid_compiles() { return msvc_typeid((boost::type<char const[3]>*)0) , msvc_typeid((boost::type<char[3]>*)0); } # endif } } } // namespace boost::python::detail # endif // BOOST_INTEL_CXX_VERSION #endif // MSVC_TYPEINFO_DWA200222_HPP
f09ebcb7efe79064c9148e56667be89020b543ef
3c78677066d2dba7be0478acf8cd8562bc9a4f86
/src/inspur_cmds.cpp
d0feb4eeef4527612d0e445088d2be29374050ee
[ "Apache-2.0" ]
permissive
zhuysh1988/inspur-ipmi-oem
41fa25426a14c0eb3bbf948466bd344b622c605b
9e76053414a9cb3eb516efc5b7826829da609369
refs/heads/master
2020-04-16T09:48:36.587046
2019-04-07T13:20:31
2019-04-07T13:20:31
165,477,774
0
0
null
null
null
null
UTF-8
C++
false
false
5,870
cpp
#include <ipmid/api.h> #include "inspur_cmds.hpp" #include <string> #include <stdio.h> #include<iostream> #include<fstream> #include <phosphor-logging/elog-errors.hpp> #include <phosphor-logging/log.hpp> #include <sdbusplus/message/types.hpp> #include <set> #include <xyz/openbmc_project/Common/error.hpp> #include <xyz/openbmc_project/Sensor/Value/server.hpp> #include "ipmid/utils.hpp" using namespace phosphor::logging; using InternalFailure = sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure; using namespace std; void register_netfn_inspur_cmds_functions() __attribute__((constructor)); extern const ipmi::sensor::IdInfoMap sensors; FILE *fp = NULL; uint8_t getFanMode() { string get_fan_mode_cmd = "cat /usr/bin/fan_mode"; char buffer[10] = {0}; uint8_t rc = 1; fp = popen(get_fan_mode_cmd.c_str(),"r"); if(fp != NULL) { fgets(buffer,10,fp); pclose(fp); fp = NULL; } rc = buffer[0]-'0'; return rc; } uint8_t setFanMode(uint8_t mode) { char set_fan_mode_cmd[100]={0}; uint8_t rc = 1; sprintf(set_fan_mode_cmd,"echo %d > /usr/bin/fan_mode",mode); rc = system(set_fan_mode_cmd); return rc; } ipmi_ret_t setFan(void *request) { ipmi::sensor::SetSensorReadingReq cmdData ; memset(&cmdData,0x00,sizeof(ipmi::sensor::SetSensorReadingReq)); auto reqptr = static_cast<SetFanReq*>(request); cmdData.number = reqptr->sensor_num; cmdData.reading = reqptr->value; // Check if the Sensor Number is present const auto iter = sensors.find(cmdData.number); if (iter == sensors.end()) { return IPMI_CC_SENSOR_INVALID; } try { if(setFanMode(reqptr->mode) != 0) { return IPMI_CC_UNSPECIFIED_ERROR; } //set fan speed when mode is manual if(reqptr->mode != auto_mode) { const auto iter = sensors.find(cmdData.number); if (iter == sensors.end()) { return IPMI_CC_SENSOR_INVALID; } if (ipmi::sensor::Mutability::Write != (iter->second.mutability & ipmi::sensor::Mutability::Write)) { log<level::ERR>("Sensor Set operation is not allowed", entry("SENSOR_NUM=%d", cmdData.number)); return IPMI_CC_ILLEGAL_COMMAND; } if(iter->second.sensorType == fan_type && iter->second.propertyInterfaces.begin()->first != ipmiValueInf) { return iter->second.updateFunc(cmdData, iter->second); } else { return IPMI_CC_ILLEGAL_COMMAND; } } return IPMI_CC_OK; } catch (InternalFailure& e) { log<level::ERR>("Set sensor failed", entry("SENSOR_NUM=%d", cmdData.number)); commit<InternalFailure>(); } catch (const std::runtime_error& e) { log<level::ERR>(e.what()); } return IPMI_CC_UNSPECIFIED_ERROR; } ipmi_ret_t getFan(void *request,void *response) { auto reqptr = static_cast<GetFanReq*>(request); auto resptr = static_cast<GetFanRes*>(response); const auto iter = sensors.find(reqptr->sensor_num); ipmi::sensor::GetSensorResponse getResponse{}; if (iter == sensors.end()) { return IPMI_CC_SENSOR_INVALID; } if (ipmi::sensor::Mutability::Read != (iter->second.mutability & ipmi::sensor::Mutability::Read)) { return IPMI_CC_ILLEGAL_COMMAND; } if(iter->second.sensorType != fan_type) { return IPMI_CC_SENSOR_INVALID; } try { getResponse = iter->second.getFunc(iter->second); resptr->mode = getFanMode(); resptr->value = getResponse[0]; return IPMI_CC_OK; } catch (const std::exception& e) { log<level::ERR>(e.what()); return IPMI_CC_UNSPECIFIED_ERROR; } } ipmi_ret_t ipmi_set_fan(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, ipmi_response_t response, ipmi_data_len_t data_len, ipmi_context_t context) { auto reqptr = static_cast<SetFanReq*>(request); if((reqptr->mode >> 1) != 0x0) { *data_len = 0; return IPMI_CC_ILLEGAL_COMMAND; } if(reqptr->mode == auto_mode) { if (*data_len != sizeof(SetFanReq)-1) { *data_len = 0; return IPMI_CC_ILLEGAL_COMMAND; } } else { if(*data_len != sizeof(SetFanReq)) { *data_len = 0; return IPMI_CC_ILLEGAL_COMMAND; } } auto rc = setFan(request); *data_len = 0; return rc; } ipmi_ret_t ipmi_get_fan(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, ipmi_response_t response, ipmi_data_len_t data_len, ipmi_context_t context) { if(*data_len != sizeof(GetFanReq) ) { *data_len = 0; return IPMI_CC_REQ_DATA_LEN_INVALID; } auto rc = getFan(request,response); if(rc == IPMI_CC_OK) { *data_len = sizeof(GetFanRes); } else { *data_len = 0; } return rc; } void register_netfn_inspur_cmds_functions() { // get bmc version info ipmiPrintAndRegister(netfunInspurAppOEM, cmdSetFan, NULL, ipmi_set_fan, PRIVILEGE_ADMIN); ipmiPrintAndRegister(netfunInspurAppOEM, cmdGetFan, NULL, ipmi_get_fan, PRIVILEGE_ADMIN); }
8a0a3e54f37f5faad8d135dba1a6cabbf5cb9217
a7764174fb0351ea666faa9f3b5dfe304390a011
/inc/WNT_ListOfMFTFonts.hxx
0ea4ae52c0681ff6442e4493cce8c28662b5a93d
[]
no_license
uel-dataexchange/Opencascade_uel
f7123943e9d8124f4fa67579e3cd3f85cfe52d91
06ec93d238d3e3ea2881ff44ba8c21cf870435cd
refs/heads/master
2022-11-16T07:40:30.837854
2020-07-08T01:56:37
2020-07-08T01:56:37
276,290,778
0
0
null
null
null
null
UTF-8
C++
false
false
3,251
hxx
// This file is generated by WOK (CPPExt). // Please do not edit this file; modify original file instead. // The copyright and license terms as defined for the original file apply to // this header file considered to be the "object code" form of the original source. #ifndef _WNT_ListOfMFTFonts_HeaderFile #define _WNT_ListOfMFTFonts_HeaderFile #ifndef _Standard_HeaderFile #include <Standard.hxx> #endif #ifndef _Standard_Macro_HeaderFile #include <Standard_Macro.hxx> #endif #ifndef _Standard_Integer_HeaderFile #include <Standard_Integer.hxx> #endif #ifndef _Standard_Address_HeaderFile #include <Standard_Address.hxx> #endif #ifndef _Standard_Boolean_HeaderFile #include <Standard_Boolean.hxx> #endif #ifndef _Handle_MFT_FontManager_HeaderFile #include <Handle_MFT_FontManager.hxx> #endif class Standard_RangeError; class Standard_DimensionMismatch; class Standard_OutOfRange; class Standard_OutOfMemory; class MFT_FontManager; class WNT_ListOfMFTFonts { public: void* operator new(size_t,void* anAddress) { return anAddress; } void* operator new(size_t size) { return Standard::Allocate(size); } void operator delete(void *anAddress) { if (anAddress) Standard::Free((Standard_Address&)anAddress); } Standard_EXPORT WNT_ListOfMFTFonts(const Standard_Integer Low,const Standard_Integer Up); Standard_EXPORT WNT_ListOfMFTFonts(const Handle(MFT_FontManager)& Item,const Standard_Integer Low,const Standard_Integer Up); Standard_EXPORT void Init(const Handle(MFT_FontManager)& V) ; Standard_EXPORT void Destroy() ; ~WNT_ListOfMFTFonts() { Destroy(); } Standard_Boolean IsAllocated() const; Standard_EXPORT const WNT_ListOfMFTFonts& Assign(const WNT_ListOfMFTFonts& Other) ; const WNT_ListOfMFTFonts& operator =(const WNT_ListOfMFTFonts& Other) { return Assign(Other); } Standard_Integer Length() const; Standard_Integer Lower() const; Standard_Integer Upper() const; void SetValue(const Standard_Integer Index,const Handle(MFT_FontManager)& Value) ; const Handle_MFT_FontManager& Value(const Standard_Integer Index) const; const Handle_MFT_FontManager& operator ()(const Standard_Integer Index) const { return Value(Index); } Handle_MFT_FontManager& ChangeValue(const Standard_Integer Index) ; Handle_MFT_FontManager& operator ()(const Standard_Integer Index) { return ChangeValue(Index); } protected: private: Standard_EXPORT WNT_ListOfMFTFonts(const WNT_ListOfMFTFonts& AnArray); Standard_Integer myLowerBound; Standard_Integer myUpperBound; Standard_Address myStart; Standard_Boolean isAllocated; }; #define Array1Item Handle_MFT_FontManager #define Array1Item_hxx <MFT_FontManager.hxx> #define TCollection_Array1 WNT_ListOfMFTFonts #define TCollection_Array1_hxx <WNT_ListOfMFTFonts.hxx> #include <TCollection_Array1.lxx> #undef Array1Item #undef Array1Item_hxx #undef TCollection_Array1 #undef TCollection_Array1_hxx // other Inline functions and methods (like "C++: function call" methods) #endif
bb191a5ed49b78bd6c03925fb35bf57b69e732c2
3cae667175b2d6aac6d7f3d8189e9a02c38ea1cf
/AtCoder/ABC0/ABC026/A.cpp
43437fe44cba9bd71ecad1737ab52228a1257f6b
[]
no_license
kokorinosoba/contests
3ee14acf729eda872ebec9ec7fe3431f50ae23c2
6e0dcd7c8ee086650d89fc65616981361b9b20b9
refs/heads/master
2022-08-04T13:45:29.722075
2022-07-24T08:50:11
2022-07-24T08:50:11
149,092,111
0
0
null
null
null
null
UTF-8
C++
false
false
110
cpp
#include <bits/stdc++.h> using namespace std; int main() { int a; cin >> a; cout << a * a / 4 << endl; }
f498193c50c8819939e4933604db1d33f0bfebc6
d0fb46aecc3b69983e7f6244331a81dff42d9595
/alikafka/src/model/DeleteAclResult.cc
4ca85ad8fea7f117bda72f37c3fc4aba9c5cf31d
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-cpp-sdk
3d8d051d44ad00753a429817dd03957614c0c66a
e862bd03c844bcb7ccaa90571bceaa2802c7f135
refs/heads/master
2023-08-29T11:54:00.525102
2023-08-29T03:32:48
2023-08-29T03:32:48
115,379,460
104
82
NOASSERTION
2023-09-14T06:13:33
2017-12-26T02:53:27
C++
UTF-8
C++
false
false
1,601
cc
/* * Copyright 2009-2017 Alibaba Cloud 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. */ #include <alibabacloud/alikafka/model/DeleteAclResult.h> #include <json/json.h> using namespace AlibabaCloud::Alikafka; using namespace AlibabaCloud::Alikafka::Model; DeleteAclResult::DeleteAclResult() : ServiceResult() {} DeleteAclResult::DeleteAclResult(const std::string &payload) : ServiceResult() { parse(payload); } DeleteAclResult::~DeleteAclResult() {} void DeleteAclResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); if(!value["Code"].isNull()) code_ = std::stoi(value["Code"].asString()); if(!value["Message"].isNull()) message_ = value["Message"].asString(); if(!value["Success"].isNull()) success_ = value["Success"].asString() == "true"; } std::string DeleteAclResult::getMessage()const { return message_; } int DeleteAclResult::getCode()const { return code_; } bool DeleteAclResult::getSuccess()const { return success_; }
9823cfdd57e961bcc4aed95e0f04aab223d54415
dc66632dac12081000da3c8fe551431e4239c413
/viewer-development/indra/llcommon/llindexedqueue.h
f30656510794a89ad806aabed624c8cf4ef57d64
[]
no_license
MAPSWorks/GIS
ea115b1d4f68fefe42aef91482d440f6c6407d7f
6bd74a125a35d33a763046a7cc506bdd7a629919
refs/heads/master
2020-04-07T16:34:38.952498
2012-02-06T20:25:34
2012-02-06T20:25:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,452
h
/** * @file llindexedqueue.h * @brief An indexed FIFO queue, where only one element with each key * can be in the queue. * * $LicenseInfo:firstyear=2003&license=viewerlgpl$ * GIS Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #ifndef LL_LLINDEXEDQUEUE_H #define LL_LLINDEXEDQUEUE_H // An indexed FIFO queue, where only one element with each key can be in the queue. // This is ONLY used in the interest list, you'll probably want to review this code // carefully if you want to use it elsewhere - Doug template <typename Type> class LLIndexedQueue { protected: typedef std::deque<Type> type_deque; type_deque mQueue; std::set<Type> mKeySet; public: LLIndexedQueue() {} // move_if_there is an O(n) operation bool push_back(const Type &value, bool move_if_there = false) { if (mKeySet.find(value) != mKeySet.end()) { // Already on the queue if (move_if_there) { // Remove the existing entry. typename type_deque::iterator it; for (it = mQueue.begin(); it != mQueue.end(); ++it) { if (*it == value) { break; } } // This HAS to succeed, otherwise there's a serious bug in the keyset implementation // (although this isn't thread safe, at all) mQueue.erase(it); } else { // We're not moving it, leave it alone return false; } } else { // Doesn't exist, add it to the key set mKeySet.insert(value); } mQueue.push_back(value); // We succeeded in adding the new element. return true; } bool push_front(const Type &value, bool move_if_there = false) { if (mKeySet.find(value) != mKeySet.end()) { // Already on the queue if (move_if_there) { // Remove the existing entry. typename type_deque::iterator it; for (it = mQueue.begin(); it != mQueue.end(); ++it) { if (*it == value) { break; } } // This HAS to succeed, otherwise there's a serious bug in the keyset implementation // (although this isn't thread safe, at all) mQueue.erase(it); } else { // We're not moving it, leave it alone return false; } } else { // Doesn't exist, add it to the key set mKeySet.insert(value); } mQueue.push_front(value); return true; } void pop() { Type value = mQueue.front(); mKeySet.erase(value); mQueue.pop_front(); } Type &front() { return mQueue.front(); } S32 size() const { return mQueue.size(); } bool empty() const { return mQueue.empty(); } void clear() { // Clear out all elements on the queue mQueue.clear(); mKeySet.clear(); } }; #endif // LL_LLINDEXEDQUEUE_H
a33819af1c811ac88fe3ed7db7c274fe8c22d54c
ba96d7f21540bd7504e61954f01a6d77f88dea6f
/build/Android/Preview/app/src/main/include/_root.fa_truck.h
f72e71ee7ee2a149b6e9f73db54c11ccf0b3c8f7
[]
no_license
GetSomefi/haslaamispaivakirja
096ff35fe55e3155293e0030c91b4bbeafd512c7
9ba6766987da4af3b662e33835231b5b88a452b3
refs/heads/master
2020-03-21T19:54:24.148074
2018-11-09T06:44:18
2018-11-09T06:44:18
138,976,977
0
0
null
null
null
null
UTF-8
C++
false
false
1,371
h
// This file was generated based on '/Users/petervirtanen/OneDrive/Fuse projektit/Häsläämispäiväkirja/build/Android/Preview/cache/ux15/fa_truck.g.uno'. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Fuse.Animations.IResize.h> #include <Fuse.Binding.h> #include <Fuse.Controls.Text.h> #include <Fuse.IActualPlacement.h> #include <Fuse.INotifyUnrooted.h> #include <Fuse.IProperties.h> #include <Fuse.ISourceLocation.h> #include <Fuse.ITemplateSource.h> #include <Fuse.Node.h> #include <Fuse.Scripting.IScriptObject.h> #include <Fuse.Triggers.Actions.IHide.h> #include <Fuse.Triggers.Actions.IShow.h> #include <Fuse.Triggers.Actions-ea70af1f.h> #include <Fuse.Triggers.IValue-1.h> #include <Fuse.Visual.h> #include <Uno.Collections.ICollection-1.h> #include <Uno.Collections.IEnumerable-1.h> #include <Uno.Collections.IList-1.h> #include <Uno.String.h> #include <Uno.UX.IPropertyListener.h> namespace g{struct fa_truck;} namespace g{ // public partial sealed class fa_truck :2 // { ::g::Fuse::Controls::TextControl_type* fa_truck_typeof(); void fa_truck__ctor_8_fn(fa_truck* __this); void fa_truck__InitializeUX1_fn(fa_truck* __this); void fa_truck__New4_fn(fa_truck** __retval); struct fa_truck : ::g::Fuse::Controls::Text { void ctor_8(); void InitializeUX1(); static fa_truck* New4(); }; // } } // ::g
d17c56fa2f2330169fd8ecc22880597bdccbd845
cc0b7d50a3c6e6b329aab5b0aa0a349580bddbdd
/constant/cs9/polyMesh/pointRegionAddressing
6e78a115ae46fbd5d7c2685aded24e5ad6661cfe
[]
no_license
AndrewLindsay/OpenFoamFieldJoint
32eede3593516b550358673a01b7b442f69eb706
7940373dcc021225f2a7ff88e850a1dd51c62e36
refs/heads/master
2020-09-25T16:59:18.478368
2019-12-05T08:16:14
2019-12-05T08:16:14
226,048,923
0
0
null
null
null
null
UTF-8
C++
false
false
32,109
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: v1906 | | \\ / A nd | Web: www.OpenFOAM.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class labelList; location "constant/cs9/polyMesh"; object pointRegionAddressing; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // 5202 ( 25349 25400 30301 30302 30303 30304 30305 30306 30307 30308 30309 30310 30311 30312 30313 30314 30315 30316 30317 30318 30319 30320 30321 30322 30323 30324 30325 30326 30327 30328 30329 30330 30331 30332 30333 30334 30335 30336 30337 30338 30339 30340 30341 30342 30343 30344 30345 30346 30347 30348 30349 30350 30351 30352 30353 30354 30355 30356 30357 30358 30359 30360 30361 30362 30363 30364 30365 30366 30367 30368 30369 30370 30371 30372 30373 30374 30375 30376 30377 30378 30379 30380 30381 30382 30383 30384 30385 30386 30387 30388 30389 30390 30391 30392 30393 30394 30395 30396 30397 30398 30399 30400 40451 40502 40553 40604 40655 40706 40757 40808 40859 40910 40961 41012 41063 41114 41165 41216 41267 41318 41369 41420 41471 41522 41573 41624 41675 41726 41777 41828 41879 41930 41981 42032 42083 42134 42185 42236 42287 42338 42389 42440 42491 42542 42593 42644 42695 42746 42797 42848 42899 42950 43001 43052 43103 43154 43205 43256 43307 43358 43409 43460 43511 43562 43613 43664 43715 43766 43817 43868 43919 43970 44021 44072 44123 44174 44225 44276 44327 44378 44429 44480 44531 44582 44633 44684 44735 44786 44837 44888 44939 44990 45041 45092 45143 45194 45245 45296 45347 45398 45449 45500 45501 45502 45503 45504 45505 45506 45507 45508 45509 45510 45511 45512 45513 45514 45515 45516 45517 45518 45519 45520 45521 45522 45523 45524 45525 45526 45527 45528 45529 45530 45531 45532 45533 45534 45535 45536 45537 45538 45539 45540 45541 45542 45543 45544 45545 45546 45547 45548 45549 45550 45551 45552 45553 45554 45555 45556 45557 45558 45559 45560 45561 45562 45563 45564 45565 45566 45567 45568 45569 45570 45571 45572 45573 45574 45575 45576 45577 45578 45579 45580 45581 45582 45583 45584 45585 45586 45587 45588 45589 45590 45591 45592 45593 45594 45595 45596 45597 45598 45599 45600 45601 45602 45603 45604 45605 45606 45607 45608 45609 45610 45611 45612 45613 45614 45615 45616 45617 45618 45619 45620 45621 45622 45623 45624 45625 45626 45627 45628 45629 45630 45631 45632 45633 45634 45635 45636 45637 45638 45639 45640 45641 45642 45643 45644 45645 45646 45647 45648 45649 45650 45651 45652 45653 45654 45655 45656 45657 45658 45659 45660 45661 45662 45663 45664 45665 45666 45667 45668 45669 45670 45671 45672 45673 45674 45675 45676 45677 45678 45679 45680 45681 45682 45683 45684 45685 45686 45687 45688 45689 45690 45691 45692 45693 45694 45695 45696 45697 45698 45699 45700 45701 45702 45703 45704 45705 45706 45707 45708 45709 45710 45711 45712 45713 45714 45715 45716 45717 45718 45719 45720 45721 45722 45723 45724 45725 45726 45727 45728 45729 45730 45731 45732 45733 45734 45735 45736 45737 45738 45739 45740 45741 45742 45743 45744 45745 45746 45747 45748 45749 45750 45751 45752 45753 45754 45755 45756 45757 45758 45759 45760 45761 45762 45763 45764 45765 45766 45767 45768 45769 45770 45771 45772 45773 45774 45775 45776 45777 45778 45779 45780 45781 45782 45783 45784 45785 45786 45787 45788 45789 45790 45791 45792 45793 45794 45795 45796 45797 45798 45799 45800 45801 45802 45803 45804 45805 45806 45807 45808 45809 45810 45811 45812 45813 45814 45815 45816 45817 45818 45819 45820 45821 45822 45823 45824 45825 45826 45827 45828 45829 45830 45831 45832 45833 45834 45835 45836 45837 45838 45839 45840 45841 45842 45843 45844 45845 45846 45847 45848 45849 45850 45851 45852 45853 45854 45855 45856 45857 45858 45859 45860 45861 45862 45863 45864 45865 45866 45867 45868 45869 45870 45871 45872 45873 45874 45875 45876 45877 45878 45879 45880 45881 45882 45883 45884 45885 45886 45887 45888 45889 45890 45891 45892 45893 45894 45895 45896 45897 45898 45899 45900 45901 45902 45903 45904 45905 45906 45907 45908 45909 45910 45911 45912 45913 45914 45915 45916 45917 45918 45919 45920 45921 45922 45923 45924 45925 45926 45927 45928 45929 45930 45931 45932 45933 45934 45935 45936 45937 45938 45939 45940 45941 45942 45943 45944 45945 45946 45947 45948 45949 45950 45951 45952 45953 45954 45955 45956 45957 45958 45959 45960 45961 45962 45963 45964 45965 45966 45967 45968 45969 45970 45971 45972 45973 45974 45975 45976 45977 45978 45979 45980 45981 45982 45983 45984 45985 45986 45987 45988 45989 45990 45991 45992 45993 45994 45995 45996 45997 45998 45999 46000 46001 46002 46003 46004 46005 46006 46007 46008 46009 46010 46011 46012 46013 46014 46015 46016 46017 46018 46019 46020 46021 46022 46023 46024 46025 46026 46027 46028 46029 46030 46031 46032 46033 46034 46035 46036 46037 46038 46039 46040 46041 46042 46043 46044 46045 46046 46047 46048 46049 46050 46051 46052 46053 46054 46055 46056 46057 46058 46059 46060 46061 46062 46063 46064 46065 46066 46067 46068 46069 46070 46071 46072 46073 46074 46075 46076 46077 46078 46079 46080 46081 46082 46083 46084 46085 46086 46087 46088 46089 46090 46091 46092 46093 46094 46095 46096 46097 46098 46099 46100 46101 46102 46103 46104 46105 46106 46107 46108 46109 46110 46111 46112 46113 46114 46115 46116 46117 46118 46119 46120 46121 46122 46123 46124 46125 46126 46127 46128 46129 46130 46131 46132 46133 46134 46135 46136 46137 46138 46139 46140 46141 46142 46143 46144 46145 46146 46147 46148 46149 46150 46151 46152 46153 46154 46155 46156 46157 46158 46159 46160 46161 46162 46163 46164 46165 46166 46167 46168 46169 46170 46171 46172 46173 46174 46175 46176 46177 46178 46179 46180 46181 46182 46183 46184 46185 46186 46187 46188 46189 46190 46191 46192 46193 46194 46195 46196 46197 46198 46199 46200 46201 46202 46203 46204 46205 46206 46207 46208 46209 46210 46211 46212 46213 46214 46215 46216 46217 46218 46219 46220 46221 46222 46223 46224 46225 46226 46227 46228 46229 46230 46231 46232 46233 46234 46235 46236 46237 46238 46239 46240 46241 46242 46243 46244 46245 46246 46247 46248 46249 46250 46251 46252 46253 46254 46255 46256 46257 46258 46259 46260 46261 46262 46263 46264 46265 46266 46267 46268 46269 46270 46271 46272 46273 46274 46275 46276 46277 46278 46279 46280 46281 46282 46283 46284 46285 46286 46287 46288 46289 46290 46291 46292 46293 46294 46295 46296 46297 46298 46299 46300 46301 46302 46303 46304 46305 46306 46307 46308 46309 46310 46311 46312 46313 46314 46315 46316 46317 46318 46319 46320 46321 46322 46323 46324 46325 46326 46327 46328 46329 46330 46331 46332 46333 46334 46335 46336 46337 46338 46339 46340 46341 46342 46343 46344 46345 46346 46347 46348 46349 46350 46351 46352 46353 46354 46355 46356 46357 46358 46359 46360 46361 46362 46363 46364 46365 46366 46367 46368 46369 46370 46371 46372 46373 46374 46375 46376 46377 46378 46379 46380 46381 46382 46383 46384 46385 46386 46387 46388 46389 46390 46391 46392 46393 46394 46395 46396 46397 46398 46399 46400 46401 46402 46403 46404 46405 46406 46407 46408 46409 46410 46411 46412 46413 46414 46415 46416 46417 46418 46419 46420 46421 46422 46423 46424 46425 46426 46427 46428 46429 46430 46431 46432 46433 46434 46435 46436 46437 46438 46439 46440 46441 46442 46443 46444 46445 46446 46447 46448 46449 46450 46451 46452 46453 46454 46455 46456 46457 46458 46459 46460 46461 46462 46463 46464 46465 46466 46467 46468 46469 46470 46471 46472 46473 46474 46475 46476 46477 46478 46479 46480 46481 46482 46483 46484 46485 46486 46487 46488 46489 46490 46491 46492 46493 46494 46495 46496 46497 46498 46499 46500 46501 46502 46503 46504 46505 46506 46507 46508 46509 46510 46511 46512 46513 46514 46515 46516 46517 46518 46519 46520 46521 46522 46523 46524 46525 46526 46527 46528 46529 46530 46531 46532 46533 46534 46535 46536 46537 46538 46539 46540 46541 46542 46543 46544 46545 46546 46547 46548 46549 46550 46551 46552 46553 46554 46555 46556 46557 46558 46559 46560 46561 46562 46563 46564 46565 46566 46567 46568 46569 46570 46571 46572 46573 46574 46575 46576 46577 46578 46579 46580 46581 46582 46583 46584 46585 46586 46587 46588 46589 46590 46591 46592 46593 46594 46595 46596 46597 46598 46599 46600 46601 46602 46603 46604 46605 46606 46607 46608 46609 46610 46611 46612 46613 46614 46615 46616 46617 46618 46619 46620 46621 46622 46623 46624 46625 46626 46627 46628 46629 46630 46631 46632 46633 46634 46635 46636 46637 46638 46639 46640 46641 46642 46643 46644 46645 46646 46647 46648 46649 46650 46651 46652 46653 46654 46655 46656 46657 46658 46659 46660 46661 46662 46663 46664 46665 46666 46667 46668 46669 46670 46671 46672 46673 46674 46675 46676 46677 46678 46679 46680 46681 46682 46683 46684 46685 46686 46687 46688 46689 46690 46691 46692 46693 46694 46695 46696 46697 46698 46699 46700 46701 46702 46703 46704 46705 46706 46707 46708 46709 46710 46711 46712 46713 46714 46715 46716 46717 46718 46719 46720 46721 46722 46723 46724 46725 46726 46727 46728 46729 46730 46731 46732 46733 46734 46735 46736 46737 46738 46739 46740 46741 46742 46743 46744 46745 46746 46747 46748 46749 46750 46751 46752 46753 46754 46755 46756 46757 46758 46759 46760 46761 46762 46763 46764 46765 46766 46767 46768 46769 46770 46771 46772 46773 46774 46775 46776 46777 46778 46779 46780 46781 46782 46783 46784 46785 46786 46787 46788 46789 46790 46791 46792 46793 46794 46795 46796 46797 46798 46799 46800 46801 46802 46803 46804 46805 46806 46807 46808 46809 46810 46811 46812 46813 46814 46815 46816 46817 46818 46819 46820 46821 46822 46823 46824 46825 46826 46827 46828 46829 46830 46831 46832 46833 46834 46835 46836 46837 46838 46839 46840 46841 46842 46843 46844 46845 46846 46847 46848 46849 46850 46851 46852 46853 46854 46855 46856 46857 46858 46859 46860 46861 46862 46863 46864 46865 46866 46867 46868 46869 46870 46871 46872 46873 46874 46875 46876 46877 46878 46879 46880 46881 46882 46883 46884 46885 46886 46887 46888 46889 46890 46891 46892 46893 46894 46895 46896 46897 46898 46899 46900 46901 46902 46903 46904 46905 46906 46907 46908 46909 46910 46911 46912 46913 46914 46915 46916 46917 46918 46919 46920 46921 46922 46923 46924 46925 46926 46927 46928 46929 46930 46931 46932 46933 46934 46935 46936 46937 46938 46939 46940 46941 46942 46943 46944 46945 46946 46947 46948 46949 46950 46951 46952 46953 46954 46955 46956 46957 46958 46959 46960 46961 46962 46963 46964 46965 46966 46967 46968 46969 46970 46971 46972 46973 46974 46975 46976 46977 46978 46979 46980 46981 46982 46983 46984 46985 46986 46987 46988 46989 46990 46991 46992 46993 46994 46995 46996 46997 46998 46999 47000 47001 47002 47003 47004 47005 47006 47007 47008 47009 47010 47011 47012 47013 47014 47015 47016 47017 47018 47019 47020 47021 47022 47023 47024 47025 47026 47027 47028 47029 47030 47031 47032 47033 47034 47035 47036 47037 47038 47039 47040 47041 47042 47043 47044 47045 47046 47047 47048 47049 47050 47051 47052 47053 47054 47055 47056 47057 47058 47059 47060 47061 47062 47063 47064 47065 47066 47067 47068 47069 47070 47071 47072 47073 47074 47075 47076 47077 47078 47079 47080 47081 47082 47083 47084 47085 47086 47087 47088 47089 47090 47091 47092 47093 47094 47095 47096 47097 47098 47099 47100 47101 47102 47103 47104 47105 47106 47107 47108 47109 47110 47111 47112 47113 47114 47115 47116 47117 47118 47119 47120 47121 47122 47123 47124 47125 47126 47127 47128 47129 47130 47131 47132 47133 47134 47135 47136 47137 47138 47139 47140 47141 47142 47143 47144 47145 47146 47147 47148 47149 47150 47151 47152 47153 47154 47155 47156 47157 47158 47159 47160 47161 47162 47163 47164 47165 47166 47167 47168 47169 47170 47171 47172 47173 47174 47175 47176 47177 47178 47179 47180 47181 47182 47183 47184 47185 47186 47187 47188 47189 47190 47191 47192 47193 47194 47195 47196 47197 47198 47199 47200 47201 47202 47203 47204 47205 47206 47207 47208 47209 47210 47211 47212 47213 47214 47215 47216 47217 47218 47219 47220 47221 47222 47223 47224 47225 47226 47227 47228 47229 47230 47231 47232 47233 47234 47235 47236 47237 47238 47239 47240 47241 47242 47243 47244 47245 47246 47247 47248 47249 47250 47251 47252 47253 47254 47255 47256 47257 47258 47259 47260 47261 47262 47263 47264 47265 47266 47267 47268 47269 47270 47271 47272 47273 47274 47275 47276 47277 47278 47279 47280 47281 47282 47283 47284 47285 47286 47287 47288 47289 47290 47291 47292 47293 47294 47295 47296 47297 47298 47299 47300 47301 47302 47303 47304 47305 47306 47307 47308 47309 47310 47311 47312 47313 47314 47315 47316 47317 47318 47319 47320 47321 47322 47323 47324 47325 47326 47327 47328 47329 47330 47331 47332 47333 47334 47335 47336 47337 47338 47339 47340 47341 47342 47343 47344 47345 47346 47347 47348 47349 47350 47351 47352 47353 47354 47355 47356 47357 47358 47359 47360 47361 47362 47363 47364 47365 47366 47367 47368 47369 47370 47371 47372 47373 47374 47375 47376 47377 47378 47379 47380 47381 47382 47383 47384 47385 47386 47387 47388 47389 47390 47391 47392 47393 47394 47395 47396 47397 47398 47399 47400 47401 47402 47403 47404 47405 47406 47407 47408 47409 47410 47411 47412 47413 47414 47415 47416 47417 47418 47419 47420 47421 47422 47423 47424 47425 47426 47427 47428 47429 47430 47431 47432 47433 47434 47435 47436 47437 47438 47439 47440 47441 47442 47443 47444 47445 47446 47447 47448 47449 47450 47451 47452 47453 47454 47455 47456 47457 47458 47459 47460 47461 47462 47463 47464 47465 47466 47467 47468 47469 47470 47471 47472 47473 47474 47475 47476 47477 47478 47479 47480 47481 47482 47483 47484 47485 47486 47487 47488 47489 47490 47491 47492 47493 47494 47495 47496 47497 47498 47499 47500 47501 47502 47503 47504 47505 47506 47507 47508 47509 47510 47511 47512 47513 47514 47515 47516 47517 47518 47519 47520 47521 47522 47523 47524 47525 47526 47527 47528 47529 47530 47531 47532 47533 47534 47535 47536 47537 47538 47539 47540 47541 47542 47543 47544 47545 47546 47547 47548 47549 47550 47551 47552 47553 47554 47555 47556 47557 47558 47559 47560 47561 47562 47563 47564 47565 47566 47567 47568 47569 47570 47571 47572 47573 47574 47575 47576 47577 47578 47579 47580 47581 47582 47583 47584 47585 47586 47587 47588 47589 47590 47591 47592 47593 47594 47595 47596 47597 47598 47599 47600 47601 47602 47603 47604 47605 47606 47607 47608 47609 47610 47611 47612 47613 47614 47615 47616 47617 47618 47619 47620 47621 47622 47623 47624 47625 47626 47627 47628 47629 47630 47631 47632 47633 47634 47635 47636 47637 47638 47639 47640 47641 47642 47643 47644 47645 47646 47647 47648 47649 47650 47651 47652 47653 47654 47655 47656 47657 47658 47659 47660 47661 47662 47663 47664 47665 47666 47667 47668 47669 47670 47671 47672 47673 47674 47675 47676 47677 47678 47679 47680 47681 47682 47683 47684 47685 47686 47687 47688 47689 47690 47691 47692 47693 47694 47695 47696 47697 47698 47699 47700 47701 47702 47703 47704 47705 47706 47707 47708 47709 47710 47711 47712 47713 47714 47715 47716 47717 47718 47719 47720 47721 47722 47723 47724 47725 47726 47727 47728 47729 47730 47731 47732 47733 47734 47735 47736 47737 47738 47739 47740 47741 47742 47743 47744 47745 47746 47747 47748 47749 47750 47751 47752 47753 47754 47755 47756 47757 47758 47759 47760 47761 47762 47763 47764 47765 47766 47767 47768 47769 47770 47771 47772 47773 47774 47775 47776 47777 47778 47779 47780 47781 47782 47783 47784 47785 47786 47787 47788 47789 47790 47791 47792 47793 47794 47795 47796 47797 47798 47799 47800 47801 47802 47803 47804 47805 47806 47807 47808 47809 47810 47811 47812 47813 47814 47815 47816 47817 47818 47819 47820 47821 47822 47823 47824 47825 47826 47827 47828 47829 47830 47831 47832 47833 47834 47835 47836 47837 47838 47839 47840 47841 47842 47843 47844 47845 47846 47847 47848 47849 47850 47851 47852 47853 47854 47855 47856 47857 47858 47859 47860 47861 47862 47863 47864 47865 47866 47867 47868 47869 47870 47871 47872 47873 47874 47875 47876 47877 47878 47879 47880 47881 47882 47883 47884 47885 47886 47887 47888 47889 47890 47891 47892 47893 47894 47895 47896 47897 47898 47899 47900 47901 47902 47903 47904 47905 47906 47907 47908 47909 47910 47911 47912 47913 47914 47915 47916 47917 47918 47919 47920 47921 47922 47923 47924 47925 47926 47927 47928 47929 47930 47931 47932 47933 47934 47935 47936 47937 47938 47939 47940 47941 47942 47943 47944 47945 47946 47947 47948 47949 47950 47951 47952 47953 47954 47955 47956 47957 47958 47959 47960 47961 47962 47963 47964 47965 47966 47967 47968 47969 47970 47971 47972 47973 47974 47975 47976 47977 47978 47979 47980 47981 47982 47983 47984 47985 47986 47987 47988 47989 47990 47991 47992 47993 47994 47995 47996 47997 47998 47999 48000 48001 48002 48003 48004 48005 48006 48007 48008 48009 48010 48011 48012 48013 48014 48015 48016 48017 48018 48019 48020 48021 48022 48023 48024 48025 48026 48027 48028 48029 48030 48031 48032 48033 48034 48035 48036 48037 48038 48039 48040 48041 48042 48043 48044 48045 48046 48047 48048 48049 48050 48051 48052 48053 48054 48055 48056 48057 48058 48059 48060 48061 48062 48063 48064 48065 48066 48067 48068 48069 48070 48071 48072 48073 48074 48075 48076 48077 48078 48079 48080 48081 48082 48083 48084 48085 48086 48087 48088 48089 48090 48091 48092 48093 48094 48095 48096 48097 48098 48099 48100 48101 48102 48103 48104 48105 48106 48107 48108 48109 48110 48111 48112 48113 48114 48115 48116 48117 48118 48119 48120 48121 48122 48123 48124 48125 48126 48127 48128 48129 48130 48131 48132 48133 48134 48135 48136 48137 48138 48139 48140 48141 48142 48143 48144 48145 48146 48147 48148 48149 48150 48151 48152 48153 48154 48155 48156 48157 48158 48159 48160 48161 48162 48163 48164 48165 48166 48167 48168 48169 48170 48171 48172 48173 48174 48175 48176 48177 48178 48179 48180 48181 48182 48183 48184 48185 48186 48187 48188 48189 48190 48191 48192 48193 48194 48195 48196 48197 48198 48199 48200 48201 48202 48203 48204 48205 48206 48207 48208 48209 48210 48211 48212 48213 48214 48215 48216 48217 48218 48219 48220 48221 48222 48223 48224 48225 48226 48227 48228 48229 48230 48231 48232 48233 48234 48235 48236 48237 48238 48239 48240 48241 48242 48243 48244 48245 48246 48247 48248 48249 48250 48251 48252 48253 48254 48255 48256 48257 48258 48259 48260 48261 48262 48263 48264 48265 48266 48267 48268 48269 48270 48271 48272 48273 48274 48275 48276 48277 48278 48279 48280 48281 48282 48283 48284 48285 48286 48287 48288 48289 48290 48291 48292 48293 48294 48295 48296 48297 48298 48299 48300 48301 48302 48303 48304 48305 48306 48307 48308 48309 48310 48311 48312 48313 48314 48315 48316 48317 48318 48319 48320 48321 48322 48323 48324 48325 48326 48327 48328 48329 48330 48331 48332 48333 48334 48335 48336 48337 48338 48339 48340 48341 48342 48343 48344 48345 48346 48347 48348 48349 48350 48351 48352 48353 48354 48355 48356 48357 48358 48359 48360 48361 48362 48363 48364 48365 48366 48367 48368 48369 48370 48371 48372 48373 48374 48375 48376 48377 48378 48379 48380 48381 48382 48383 48384 48385 48386 48387 48388 48389 48390 48391 48392 48393 48394 48395 48396 48397 48398 48399 48400 48401 48402 48403 48404 48405 48406 48407 48408 48409 48410 48411 48412 48413 48414 48415 48416 48417 48418 48419 48420 48421 48422 48423 48424 48425 48426 48427 48428 48429 48430 48431 48432 48433 48434 48435 48436 48437 48438 48439 48440 48441 48442 48443 48444 48445 48446 48447 48448 48449 48450 48451 48452 48453 48454 48455 48456 48457 48458 48459 48460 48461 48462 48463 48464 48465 48466 48467 48468 48469 48470 48471 48472 48473 48474 48475 48476 48477 48478 48479 48480 48481 48482 48483 48484 48485 48486 48487 48488 48489 48490 48491 48492 48493 48494 48495 48496 48497 48498 48499 48500 48501 48502 48503 48504 48505 48506 48507 48508 48509 48510 48511 48512 48513 48514 48515 48516 48517 48518 48519 48520 48521 48522 48523 48524 48525 48526 48527 48528 48529 48530 48531 48532 48533 48534 48535 48536 48537 48538 48539 48540 48541 48542 48543 48544 48545 48546 48547 48548 48549 48550 48551 48552 48553 48554 48555 48556 48557 48558 48559 48560 48561 48562 48563 48564 48565 48566 48567 48568 48569 48570 48571 48572 48573 48574 48575 48576 48577 48578 48579 48580 48581 48582 48583 48584 48585 48586 48587 48588 48589 48590 48591 48592 48593 48594 48595 48596 48597 48598 48599 48600 48601 48602 48603 48604 48605 48606 48607 48608 48609 48610 48611 48612 48613 48614 48615 48616 48617 48618 48619 48620 48621 48622 48623 48624 48625 48626 48627 48628 48629 48630 48631 48632 48633 48634 48635 48636 48637 48638 48639 48640 48641 48642 48643 48644 48645 48646 48647 48648 48649 48650 48651 48652 48653 48654 48655 48656 48657 48658 48659 48660 48661 48662 48663 48664 48665 48666 48667 48668 48669 48670 48671 48672 48673 48674 48675 48676 48677 48678 48679 48680 48681 48682 48683 48684 48685 48686 48687 48688 48689 48690 48691 48692 48693 48694 48695 48696 48697 48698 48699 48700 48701 48702 48703 48704 48705 48706 48707 48708 48709 48710 48711 48712 48713 48714 48715 48716 48717 48718 48719 48720 48721 48722 48723 48724 48725 48726 48727 48728 48729 48730 48731 48732 48733 48734 48735 48736 48737 48738 48739 48740 48741 48742 48743 48744 48745 48746 48747 48748 48749 48750 48751 48752 48753 48754 48755 48756 48757 48758 48759 48760 48761 48762 48763 48764 48765 48766 48767 48768 48769 48770 48771 48772 48773 48774 48775 48776 48777 48778 48779 48780 48781 48782 48783 48784 48785 48786 48787 48788 48789 48790 48791 48792 48793 48794 48795 48796 48797 48798 48799 48800 48801 48802 48803 48804 48805 48806 48807 48808 48809 48810 48811 48812 48813 48814 48815 48816 48817 48818 48819 48820 48821 48822 48823 48824 48825 48826 48827 48828 48829 48830 48831 48832 48833 48834 48835 48836 48837 48838 48839 48840 48841 48842 48843 48844 48845 48846 48847 48848 48849 48850 48851 48852 48853 48854 48855 48856 48857 48858 48859 48860 48861 48862 48863 48864 48865 48866 48867 48868 48869 48870 48871 48872 48873 48874 48875 48876 48877 48878 48879 48880 48881 48882 48883 48884 48885 48886 48887 48888 48889 48890 48891 48892 48893 48894 48895 48896 48897 48898 48899 48900 48901 48902 48903 48904 48905 48906 48907 48908 48909 48910 48911 48912 48913 48914 48915 48916 48917 48918 48919 48920 48921 48922 48923 48924 48925 48926 48927 48928 48929 48930 48931 48932 48933 48934 48935 48936 48937 48938 48939 48940 48941 48942 48943 48944 48945 48946 48947 48948 48949 48950 48951 48952 48953 48954 48955 48956 48957 48958 48959 48960 48961 48962 48963 48964 48965 48966 48967 48968 48969 48970 48971 48972 48973 48974 48975 48976 48977 48978 48979 48980 48981 48982 48983 48984 48985 48986 48987 48988 48989 48990 48991 48992 48993 48994 48995 48996 48997 48998 48999 49000 49001 49002 49003 49004 49005 49006 49007 49008 49009 49010 49011 49012 49013 49014 49015 49016 49017 49018 49019 49020 49021 49022 49023 49024 49025 49026 49027 49028 49029 49030 49031 49032 49033 49034 49035 49036 49037 49038 49039 49040 49041 49042 49043 49044 49045 49046 49047 49048 49049 49050 49051 49052 49053 49054 49055 49056 49057 49058 49059 49060 49061 49062 49063 49064 49065 49066 49067 49068 49069 49070 49071 49072 49073 49074 49075 49076 49077 49078 49079 49080 49081 49082 49083 49084 49085 49086 49087 49088 49089 49090 49091 49092 49093 49094 49095 49096 49097 49098 49099 49100 49101 49102 49103 49104 49105 49106 49107 49108 49109 49110 49111 49112 49113 49114 49115 49116 49117 49118 49119 49120 49121 49122 49123 49124 49125 49126 49127 49128 49129 49130 49131 49132 49133 49134 49135 49136 49137 49138 49139 49140 49141 49142 49143 49144 49145 49146 49147 49148 49149 49150 49151 49152 49153 49154 49155 49156 49157 49158 49159 49160 49161 49162 49163 49164 49165 49166 49167 49168 49169 49170 49171 49172 49173 49174 49175 49176 49177 49178 49179 49180 49181 49182 49183 49184 49185 49186 49187 49188 49189 49190 49191 49192 49193 49194 49195 49196 49197 49198 49199 49200 49201 49202 49203 49204 49205 49206 49207 49208 49209 49210 49211 49212 49213 49214 49215 49216 49217 49218 49219 49220 49221 49222 49223 49224 49225 49226 49227 49228 49229 49230 49231 49232 49233 49234 49235 49236 49237 49238 49239 49240 49241 49242 49243 49244 49245 49246 49247 49248 49249 49250 49251 49252 49253 49254 49255 49256 49257 49258 49259 49260 49261 49262 49263 49264 49265 49266 49267 49268 49269 49270 49271 49272 49273 49274 49275 49276 49277 49278 49279 49280 49281 49282 49283 49284 49285 49286 49287 49288 49289 49290 49291 49292 49293 49294 49295 49296 49297 49298 49299 49300 49301 49302 49303 49304 49305 49306 49307 49308 49309 49310 49311 49312 49313 49314 49315 49316 49317 49318 49319 49320 49321 49322 49323 49324 49325 49326 49327 49328 49329 49330 49331 49332 49333 49334 49335 49336 49337 49338 49339 49340 49341 49342 49343 49344 49345 49346 49347 49348 49349 49350 49351 49352 49353 49354 49355 49356 49357 49358 49359 49360 49361 49362 49363 49364 49365 49366 49367 49368 49369 49370 49371 49372 49373 49374 49375 49376 49377 49378 49379 49380 49381 49382 49383 49384 49385 49386 49387 49388 49389 49390 49391 49392 49393 49394 49395 49396 49397 49398 49399 49400 49401 49402 49403 49404 49405 49406 49407 49408 49409 49410 49411 49412 49413 49414 49415 49416 49417 49418 49419 49420 49421 49422 49423 49424 49425 49426 49427 49428 49429 49430 49431 49432 49433 49434 49435 49436 49437 49438 49439 49440 49441 49442 49443 49444 49445 49446 49447 49448 49449 49450 49451 49452 49453 49454 49455 49456 49457 49458 49459 49460 49461 49462 49463 49464 49465 49466 49467 49468 49469 49470 49471 49472 49473 49474 49475 49476 49477 49478 49479 49480 49481 49482 49483 49484 49485 49486 49487 49488 49489 49490 49491 49492 49493 49494 49495 49496 49497 49498 49499 49500 49501 49502 49503 49504 49505 49506 49507 49508 49509 49510 49511 49512 49513 49514 49515 49516 49517 49518 49519 49520 49521 49522 49523 49524 49525 49526 49527 49528 49529 49530 49531 49532 49533 49534 49535 49536 49537 49538 49539 49540 49541 49542 49543 49544 49545 49546 49547 49548 49549 49550 49551 49552 49553 49554 49555 49556 49557 49558 49559 49560 49561 49562 49563 49564 49565 49566 49567 49568 49569 49570 49571 49572 49573 49574 49575 49576 49577 49578 49579 49580 49581 49582 49583 49584 49585 49586 49587 49588 49589 49590 49591 49592 49593 49594 49595 49596 49597 49598 49599 49600 49601 49602 49603 49604 49605 49606 49607 49608 49609 49610 49611 49612 49613 49614 49615 49616 49617 49618 49619 49620 49621 49622 49623 49624 49625 49626 49627 49628 49629 49630 49631 49632 49633 49634 49635 49636 49637 49638 49639 49640 49641 49642 49643 49644 49645 49646 49647 49648 49649 49650 49651 49652 49653 49654 49655 49656 49657 49658 49659 49660 49661 49662 49663 49664 49665 49666 49667 49668 49669 49670 49671 49672 49673 49674 49675 49676 49677 49678 49679 49680 49681 49682 49683 49684 49685 49686 49687 49688 49689 49690 49691 49692 49693 49694 49695 49696 49697 49698 49699 49700 49701 49702 49703 49704 49705 49706 49707 49708 49709 49710 49711 49712 49713 49714 49715 49716 49717 49718 49719 49720 49721 49722 49723 49724 49725 49726 49727 49728 49729 49730 49731 49732 49733 49734 49735 49736 49737 49738 49739 49740 49741 49742 49743 49744 49745 49746 49747 49748 49749 49750 49751 49752 49753 49754 49755 49756 49757 49758 49759 49760 49761 49762 49763 49764 49765 49766 49767 49768 49769 49770 49771 49772 49773 49774 49775 49776 49777 49778 49779 49780 49781 49782 49783 49784 49785 49786 49787 49788 49789 49790 49791 49792 49793 49794 49795 49796 49797 49798 49799 49800 49801 49802 49803 49804 49805 49806 49807 49808 49809 49810 49811 49812 49813 49814 49815 49816 49817 49818 49819 49820 49821 49822 49823 49824 49825 49826 49827 49828 49829 49830 49831 49832 49833 49834 49835 49836 49837 49838 49839 49840 49841 49842 49843 49844 49845 49846 49847 49848 49849 49850 49851 49852 49853 49854 49855 49856 49857 49858 49859 49860 49861 49862 49863 49864 49865 49866 49867 49868 49869 49870 49871 49872 49873 49874 49875 49876 49877 49878 49879 49880 49881 49882 49883 49884 49885 49886 49887 49888 49889 49890 49891 49892 49893 49894 49895 49896 49897 49898 49899 49900 49901 49902 49903 49904 49905 49906 49907 49908 49909 49910 49911 49912 49913 49914 49915 49916 49917 49918 49919 49920 49921 49922 49923 49924 49925 49926 49927 49928 49929 49930 49931 49932 49933 49934 49935 49936 49937 49938 49939 49940 49941 49942 49943 49944 49945 49946 49947 49948 49949 49950 49951 49952 49953 49954 49955 49956 49957 49958 49959 49960 49961 49962 49963 49964 49965 49966 49967 49968 49969 49970 49971 49972 49973 49974 49975 49976 49977 49978 49979 49980 49981 49982 49983 49984 49985 49986 49987 49988 49989 49990 49991 49992 49993 49994 49995 49996 49997 49998 49999 50000 50001 50002 50003 50004 50005 50006 50007 50008 50009 50010 50011 50012 50013 50014 50015 50016 50017 50018 50019 50020 50021 50022 50023 50024 50025 50026 50027 50028 50029 50030 50031 50032 50033 50034 50035 50036 50037 50038 50039 50040 50041 50042 50043 50044 50045 50046 50047 50048 50049 50050 50051 50052 50053 50054 50055 50056 50057 50058 50059 50060 50061 50062 50063 50064 50065 50066 50067 50068 50069 50070 50071 50072 50073 50074 50075 50076 50077 50078 50079 50080 50081 50082 50083 50084 50085 50086 50087 50088 50089 50090 50091 50092 50093 50094 50095 50096 50097 50098 50099 50100 50101 50102 50103 50104 50105 50106 50107 50108 50109 50110 50111 50112 50113 50114 50115 50116 50117 50118 50119 50120 50121 50122 50123 50124 50125 50126 50127 50128 50129 50130 50131 50132 50133 50134 50135 50136 50137 50138 50139 50140 50141 50142 50143 50144 50145 50146 50147 50148 50149 50150 50151 50152 50153 50154 50155 50156 50157 50158 50159 50160 50161 50162 50163 50164 50165 50166 50167 50168 50169 50170 50171 50172 50173 50174 50175 50176 50177 50178 50179 50180 50181 50182 50183 50184 50185 50186 50187 50188 50189 50190 50191 50192 50193 50194 50195 50196 50197 50198 50199 50200 50201 50202 50203 50204 50205 50206 50207 50208 50209 50210 50211 50212 50213 50214 50215 50216 50217 50218 50219 50220 50221 50222 50223 50224 50225 50226 50227 50228 50229 50230 50231 50232 50233 50234 50235 50236 50237 50238 50239 50240 50241 50242 50243 50244 50245 50246 50247 50248 50249 50250 50251 50252 50253 50254 50255 50256 50257 50258 50259 50260 50261 50262 50263 50264 50265 50266 50267 50268 50269 50270 50271 50272 50273 50274 50275 50276 50277 50278 50279 50280 50281 50282 50283 50284 50285 50286 50287 50288 50289 50290 50291 50292 50293 50294 50295 50296 50297 50298 50299 50300 50301 50302 50303 50304 50305 50306 50307 50308 50309 50310 50311 50312 50313 50314 50315 50316 50317 50318 50319 50320 50321 50322 50323 50324 50325 50326 50327 50328 50329 50330 50331 50332 50333 50334 50335 50336 50337 50338 50339 50340 50341 50342 50343 50344 50345 50346 50347 50348 50349 50350 50351 50352 50353 50354 50355 50356 50357 50358 50359 50360 50361 50362 50363 50364 50365 50366 50367 50368 50369 50370 50371 50372 50373 50374 50375 50376 50377 50378 50379 50380 50381 50382 50383 50384 50385 50386 50387 50388 50389 50390 50391 50392 50393 50394 50395 50396 50397 50398 50399 50400 50401 50402 50403 50404 50405 50406 50407 50408 50409 50410 50411 50412 50413 50414 50415 50416 50417 50418 50419 50420 50421 50422 50423 50424 50425 50426 50427 50428 50429 50430 50431 50432 50433 50434 50435 50436 50437 50438 50439 50440 50441 50442 50443 50444 50445 50446 50447 50448 50449 50450 50451 50452 50453 50454 50455 50456 50457 50458 50459 50460 50461 50462 50463 50464 50465 50466 50467 50468 50469 50470 50471 50472 50473 50474 50475 50476 50477 50478 50479 50480 50481 50482 50483 50484 50485 50486 50487 50488 50489 50490 50491 50492 50493 50494 50495 50496 50497 50498 50499 50500 ) // ************************************************************************* //
15d82feb6f1f1227c6b18f5473ced0c601f66673
96d04ae54bc636669d0ce663e7f9777478548104
/TP3/Juego/Main.cpp
997f6b1c938d63f018c6126bcd5e51d5416ee0f7
[]
no_license
DiegoFioretti/Graficos-TP3-Parte2
015b312b79bd6d72add55fe84eb1eb5a6f14d421
2ba4536747a81171f14c0a8ed4dc5e30bbc40b12
refs/heads/master
2020-03-18T22:24:38.513843
2018-05-22T20:46:51
2018-05-22T20:46:51
135,343,772
0
0
null
null
null
null
UTF-8
C++
false
false
484
cpp
#include <stdio.h> #include <allegro5\allegro.h> int main(int argc, char **argv) { ALLEGRO_DISPLAY *display = NULL; if (!al_init()) { fprintf(stderr, "failed to initialize allegro!\n"); return -1; } display = al_create_display(640, 480); if (!display) { fprintf(stderr, "failed to create display!\n"); return -1; } al_clear_to_color(al_map_rgb(0, 0, 0)); al_flip_display(); al_rest(10.0); al_destroy_display(display); return 0; }
acd414beb335f4eb2bf5ae7dff35fed879d8f92d
be824dfd115590f7840d26bdcea4ca88e6e178b3
/src/ResourceManger/Resources.h
4cc7e29891dca8290e7ccb97edf5d955d3006ebb
[]
no_license
Brankec/Super-mario
674e1be2d4cb90c55773760018703242c0fff09b
c6cb1441d5bd7aa37c7a3f744cbc9ba73edad7dc
refs/heads/master
2021-09-16T03:59:02.298858
2018-06-15T18:40:37
2018-06-15T18:40:37
119,116,414
1
0
null
null
null
null
UTF-8
C++
false
false
228
h
#pragma once #include <SFML/Graphics/Texture.hpp> namespace res { void loadResources(); sf::Texture getPlayerTexture(); sf::Texture getNPCTexture(); sf::Texture getTilesTexture(); static sf::Texture NPC, Player, Tiles; }
eaf6f67fb00e2a432aeaabf621e50d1fcbf0dbf3
36c2ee16365ac3501ef3b7ff0e811e2398ffa641
/src/glog/src/logging.cc
47b09360ebf3bd68885e7ecddd204bd9ace294ea
[ "BSD-3-Clause" ]
permissive
AndThenYou/JZLog
fa99cb2e10c23d84a816feeba885b9244bcad6d6
069a9170b8438240c485d12b9658fc5df088a466
refs/heads/master
2023-08-22T05:48:35.124872
2021-09-10T08:05:19
2021-09-10T08:05:19
298,715,634
2
0
null
null
null
null
UTF-8
C++
false
false
87,074
cc
// Copyright (c) 1999, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define _GNU_SOURCE 1 // needed for O_NOFOLLOW and pread()/pwrite() #include "utilities.h" #include <algorithm> #include <assert.h> #include <iomanip> #include <string> #ifdef HAVE_UNISTD_H # include <unistd.h> // For _exit. #endif #include <climits> #include <sys/types.h> #include <sys/stat.h> #ifdef HAVE_SYS_UTSNAME_H # include <sys/utsname.h> // For uname. #endif #include <time.h> #include <fcntl.h> #include <cstdio> #include <iostream> #include <stdarg.h> #include <stdlib.h> #ifdef HAVE_PWD_H # include <pwd.h> #endif #ifdef HAVE_SYSLOG_H # include <syslog.h> #endif #include <vector> #include <errno.h> // for errno #include <sstream> #ifdef OS_WINDOWS #include "windows/dirent.h" #else #include <dirent.h> // for automatic removal of old logs #endif #include "base/commandlineflags.h" // to get the program name #include "glog/logging.h" #include "glog/raw_logging.h" #include "base/googleinit.h" #ifdef HAVE_STACKTRACE # include "stacktrace.h" #endif #include <map> using std::string; using std::vector; using std::setw; using std::setfill; using std::hex; using std::dec; using std::min; using std::ostream; using std::ostringstream; using std::FILE; using std::fwrite; using std::fclose; using std::fflush; using std::fprintf; using std::perror; using std::map; #ifdef __QNX__ using std::fdopen; #endif #ifdef _WIN32 #define fdopen _fdopen #endif // There is no thread annotation support. #define EXCLUSIVE_LOCKS_REQUIRED(mu) static bool BoolFromEnv(const char *varname, bool defval) { const char* const valstr = getenv(varname); if (!valstr) { return defval; } return memchr("tTyY1\0", valstr[0], 6) != NULL; } GLOG_DEFINE_bool(timestamp_in_logfile_name, BoolFromEnv("GOOGLE_TIMESTAMP_IN_LOGFILE_NAME", true), "put a timestamp at the end of the log file name"); GLOG_DEFINE_bool(logtostderr, BoolFromEnv("GOOGLE_LOGTOSTDERR", false), "log messages go to stderr instead of logfiles"); GLOG_DEFINE_bool(alsologtostderr, BoolFromEnv("GOOGLE_ALSOLOGTOSTDERR", false), "log messages go to stderr in addition to logfiles"); GLOG_DEFINE_bool(colorlogtostderr, false, "color messages logged to stderr (if supported by terminal)"); #ifdef OS_LINUX GLOG_DEFINE_bool(drop_log_memory, true, "Drop in-memory buffers of log contents. " "Logs can grow very quickly and they are rarely read before they " "need to be evicted from memory. Instead, drop them from memory " "as soon as they are flushed to disk."); #endif // By default, errors (including fatal errors) get logged to stderr as // well as the file. // // The default is ERROR instead of FATAL so that users can see problems // when they run a program without having to look in another file. DEFINE_int32(stderrthreshold, GOOGLE_NAMESPACE::GLOG_ERROR, "log messages at or above this level are copied to stderr in " "addition to logfiles. This flag obsoletes --alsologtostderr."); GLOG_DEFINE_string(alsologtoemail, "", "log messages go to these email addresses " "in addition to logfiles"); GLOG_DEFINE_bool(log_prefix, true, "Prepend the log prefix to the start of each log line"); GLOG_DEFINE_int32(minloglevel, 0, "Messages logged at a lower level than this don't " "actually get logged anywhere"); GLOG_DEFINE_int32(logbuflevel, 0, "Buffer log messages logged at this level or lower" " (-1 means don't buffer; 0 means buffer INFO only;" " ...)"); GLOG_DEFINE_int32(logbufsecs, 30, "Buffer log messages for at most this many seconds"); GLOG_DEFINE_int32(logemaillevel, 999, "Email log messages logged at this level or higher" " (0 means email all; 3 means email FATAL only;" " ...)"); GLOG_DEFINE_string(logmailer, "/bin/mail", "Mailer used to send logging email"); GLOG_DEFINE_int32(log_level_to_file, 0, "The lowest level to log file"); GLOG_DEFINE_bool(servitysinglelog, true, "Do not write high-level logs to low-level log files"); GLOG_DEFINE_bool(create_new_log, true, "When the log file exceeds the specified size, a new file is generated"); // Compute the default value for --log_dir static const char* DefaultLogDir() { const char* env; env = getenv("GOOGLE_LOG_DIR"); if (env != NULL && env[0] != '\0') { return env; } env = getenv("TEST_TMPDIR"); if (env != NULL && env[0] != '\0') { return env; } return ""; } GLOG_DEFINE_int32(logfile_mode, 0664, "Log file mode/permissions."); GLOG_DEFINE_string(log_dir, DefaultLogDir(), "If specified, logfiles are written into this directory instead " "of the default logging directory."); GLOG_DEFINE_string(log_link, "", "Put additional links to the log " "files in this directory"); GLOG_DEFINE_int32(max_log_size, 1800, "approx. maximum log file size (in MB). A value of 0 will " "be silently overridden to 1."); GLOG_DEFINE_bool(stop_logging_if_full_disk, false, "Stop attempting to log to disk if the disk is full."); GLOG_DEFINE_string(log_backtrace_at, "", "Emit a backtrace when logging at file:linenum."); // TODO(hamaji): consider windows #define PATH_SEPARATOR '/' #ifndef HAVE_PREAD #if defined(OS_WINDOWS) #include <basetsd.h> #define ssize_t SSIZE_T #endif static ssize_t pread(int fd, void* buf, size_t count, off_t offset) { off_t orig_offset = lseek(fd, 0, SEEK_CUR); if (orig_offset == (off_t)-1) return -1; if (lseek(fd, offset, SEEK_CUR) == (off_t)-1) return -1; ssize_t len = read(fd, buf, count); if (len < 0) return len; if (lseek(fd, orig_offset, SEEK_SET) == (off_t)-1) return -1; return len; } #endif // !HAVE_PREAD #ifndef HAVE_PWRITE static ssize_t pwrite(int fd, void* buf, size_t count, off_t offset) { off_t orig_offset = lseek(fd, 0, SEEK_CUR); if (orig_offset == (off_t)-1) return -1; if (lseek(fd, offset, SEEK_CUR) == (off_t)-1) return -1; ssize_t len = write(fd, buf, count); if (len < 0) return len; if (lseek(fd, orig_offset, SEEK_SET) == (off_t)-1) return -1; return len; } #endif // !HAVE_PWRITE static void GetHostName(string* hostname) { #if defined(HAVE_SYS_UTSNAME_H) struct utsname buf; if (0 != uname(&buf)) { // ensure null termination on failure *buf.nodename = '\0'; } *hostname = buf.nodename; #elif defined(OS_WINDOWS) char buf[MAX_COMPUTERNAME_LENGTH + 1]; DWORD len = MAX_COMPUTERNAME_LENGTH + 1; if (GetComputerNameA(buf, &len)) { *hostname = buf; } else { hostname->clear(); } #else # warning There is no way to retrieve the host name. *hostname = "(unknown)"; #endif } // Returns true iff terminal supports using colors in output. static bool TerminalSupportsColor() { bool term_supports_color = false; #ifdef OS_WINDOWS // on Windows TERM variable is usually not set, but the console does // support colors. term_supports_color = true; #else // On non-Windows platforms, we rely on the TERM variable. const char* const term = getenv("TERM"); if (term != NULL && term[0] != '\0') { term_supports_color = !strcmp(term, "xterm") || !strcmp(term, "xterm-color") || !strcmp(term, "xterm-256color") || !strcmp(term, "screen-256color") || !strcmp(term, "konsole") || !strcmp(term, "konsole-16color") || !strcmp(term, "konsole-256color") || !strcmp(term, "screen") || !strcmp(term, "linux") || !strcmp(term, "cygwin"); } #endif return term_supports_color; } _START_GOOGLE_NAMESPACE_ enum GLogColor { COLOR_DEFAULT, COLOR_RED, COLOR_GREEN, COLOR_YELLOW }; static GLogColor SeverityToColor(LogSeverity severity) { assert(severity >= 0 && severity < NUM_SEVERITIES); GLogColor color = COLOR_DEFAULT; switch (severity) { case GLOG_INFO: color = COLOR_DEFAULT; break; case GLOG_WARNING: color = COLOR_YELLOW; break; case GLOG_ERROR: case GLOG_FATAL: color = COLOR_RED; break; default: // should never get here. assert(false); } return color; } #ifdef OS_WINDOWS // Returns the character attribute for the given color. static WORD GetColorAttribute(GLogColor color) { switch (color) { case COLOR_RED: return FOREGROUND_RED; case COLOR_GREEN: return FOREGROUND_GREEN; case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN; default: return 0; } } #else // Returns the ANSI color code for the given color. static const char* GetAnsiColorCode(GLogColor color) { switch (color) { case COLOR_RED: return "1"; case COLOR_GREEN: return "2"; case COLOR_YELLOW: return "3"; case COLOR_DEFAULT: return ""; }; return NULL; // stop warning about return type. } #endif // OS_WINDOWS // Safely get max_log_size, overriding to 1 if it somehow gets defined as 0 static int32 MaxLogSize() { return (FLAGS_max_log_size > 0 ? FLAGS_max_log_size : 1); } // An arbitrary limit on the length of a single log message. This // is so that streaming can be done more efficiently. const size_t LogMessage::kMaxLogMessageLen = 30000; struct LogMessage::LogMessageData { LogMessageData(); int preserved_errno_; // preserved errno // Buffer space; contains complete message text. char message_text_[LogMessage::kMaxLogMessageLen+1]; LogStream stream_; char severity_; // What level is this LogMessage logged at? int line_; // line number where logging call is. void (LogMessage::*send_method_)(); // Call this in destructor to send union { // At most one of these is used: union to keep the size low. LogSink* sink_; // NULL or sink to send message to std::vector<std::string>* outvec_; // NULL or vector to push message onto std::string* message_; // NULL or string to write message into }; time_t timestamp_; // Time of creation of LogMessage struct ::tm tm_time_; // Time of creation of LogMessage int32 usecs_; // Time of creation of LogMessage - microseconds part size_t num_prefix_chars_; // # of chars of prefix in this message size_t num_chars_to_log_; // # of chars of msg to send to log size_t num_chars_to_syslog_; // # of chars of msg to send to syslog const char* basename_; // basename of file that called LOG const char* fullname_; // fullname of file that called LOG bool has_been_flushed_; // false => data has not been flushed bool first_fatal_; // true => this was first fatal msg private: LogMessageData(const LogMessageData&); void operator=(const LogMessageData&); }; // A mutex that allows only one thread to log at a time, to keep things from // getting jumbled. Some other very uncommon logging operations (like // changing the destination file for log messages of a given severity) also // lock this mutex. Please be sure that anybody who might possibly need to // lock it does so. static Mutex log_mutex; // Number of messages sent at each severity. Under log_mutex. int64 LogMessage::num_messages_[NUM_SEVERITIES] = {0, 0, 0, 0, 0}; // Globally disable log writing (if disk is full) static bool stop_writing = false; const char*const LogSeverityNames[NUM_SEVERITIES] = { "DEBUG", "INFO", "WARNING", "ERROR", "FATAL" }; // Has the user called SetExitOnDFatal(true)? static bool exit_on_dfatal = true; const char* GetLogSeverityName(LogSeverity severity) { return LogSeverityNames[severity]; } static bool SendEmailInternal(const char*dest, const char *subject, const char*body, bool use_logging); base::Logger::~Logger() { } namespace { // Encapsulates all file-system related state class LogFileObject : public base::Logger { public: LogFileObject(LogSeverity severity, const char* base_filename); ~LogFileObject(); virtual void Write(bool force_flush, // Should we force a flush here? time_t timestamp, // Timestamp for this entry const char* message, int message_len); // Configuration options void SetBasename(const char* basename); void SetExtension(const char* ext); void SetSymlinkBasename(const char* symlink_basename); // Normal flushing routine virtual void Flush(); // It is the actual file length for the system loggers, // i.e., INFO, ERROR, etc. virtual uint32 LogSize() { MutexLock l(&lock_); return file_length_; } // Internal flush routine. Exposed so that FlushLogFilesUnsafe() // can avoid grabbing a lock. Usually Flush() calls it after // acquiring lock_. void FlushUnlocked(); //add by fuxingzhong std::string log_dir_; //日志路径 uint32 max_size_; //文件最大值 M bool is_create_newlog_; //是否创建新日志 int log_level_; //写入日志文件等级 int screen_level_; //控制台输出等级 private: static const uint32 kRolloverAttemptFrequency = 0x20; Mutex lock_; bool base_filename_selected_; string base_filename_; string symlink_basename_; string filename_extension_; // option users can specify (eg to add port#) FILE* file_; LogSeverity severity_; uint32 bytes_since_flush_; uint32 dropped_mem_length_; uint32 file_length_; unsigned int rollover_attempt_; int64 next_flush_time_; // cycle count at which to flush log //add by fuxingzhong bool day_haschange_; std::string full_file_name_; //完整的日志文件名称 std::string stripped_filename_; int32 main_day_; bool DayHasChanged(); bool CreateLogDir(std::string& strDir); // Actually create a logfile using the value of base_filename_ and the // optional argument time_pid_string // REQUIRES: lock_ is held bool CreateLogfile(const string& time_pid_string); }; } // namespace class LogDestination { public: friend class LogMessage; friend void ReprintFatalMessage(); friend base::Logger* base::GetLogger(LogSeverity); friend void base::SetLogger(LogSeverity, base::Logger*); //add by fuxingzhong static void AddLogDestination(const char* base_filename, const char* dir); static void DelLogDestination(const char* base_filename); static void ChangeLogDestination(const char* base_filename, bool is_create_newlog, int max_log_size, int file_level, int screan_level); // These methods are just forwarded to by their global versions. static void SetLogDestination(LogSeverity severity, const char* base_filename); static void SetLogSymlink(LogSeverity severity, const char* symlink_basename); static void AddLogSink(LogSink *destination); static void RemoveLogSink(LogSink *destination); static void SetLogFilenameExtension(const char* filename_extension); static void SetStderrLogging(LogSeverity min_severity); static void SetEmailLogging(LogSeverity min_severity, const char* addresses); static void LogToStderr(); // Flush all log files that are at least at the given severity level static void FlushLogFiles(int min_severity); static void FlushLogFilesUnsafe(int min_severity); // we set the maximum size of our packet to be 1400, the logic being // to prevent fragmentation. // Really this number is arbitrary. static const int kNetworkBytes = 1400; static const string& hostname(); static const bool& terminal_supports_color() { return terminal_supports_color_; } static void DeleteLogDestinations(); private: LogDestination(LogSeverity severity, const char* base_filename); ~LogDestination(); // Take a log message of a particular severity and log it to stderr // iff it's of a high enough severity to deserve it. static void MaybeLogToStderr(LogSeverity severity, const char* message, size_t len); // Take a log message of a particular severity and log it to email // iff it's of a high enough severity to deserve it. static void MaybeLogToEmail(LogSeverity severity, const char* message, size_t len); // Take a log message of a particular severity and log it to a file // iff the base filename is not "" (which means "don't log to me") static void MaybeLogToLogfile(LogSeverity severity, time_t timestamp, const char* message, size_t len); // Take a log message of a particular severity and log it to the file // for that severity and also for all files with severity less than // this severity. static void LogToAllLogfiles(LogSeverity severity, time_t timestamp, const char* message, size_t len); //add by fuxingzhong static void MyToLogfiles(const char* filename, LogSeverity severity, time_t timestamp, const char* message, size_t len); // Send logging info to all registered sinks. static void LogToSinks(LogSeverity severity, const char *full_filename, const char *base_filename, int line, const struct ::tm* tm_time, const char* message, size_t message_len, int32 usecs); // Wait for all registered sinks via WaitTillSent // including the optional one in "data". static void WaitForSinks(LogMessage::LogMessageData* data); static LogDestination* log_destination(LogSeverity severity); LogFileObject fileobject_; base::Logger* logger_; // Either &fileobject_, or wrapper around it //add by fuxingzhong static std::map<std::string, LogDestination*>map_destinations_; static LogDestination* log_destinations_[NUM_SEVERITIES]; static LogSeverity email_logging_severity_; static string addresses_; static string hostname_; static bool terminal_supports_color_; // arbitrary global logging destinations. static vector<LogSink*>* sinks_; // Protects the vector sinks_, // but not the LogSink objects its elements reference. static Mutex sink_mutex_; // Disallow LogDestination(const LogDestination&); LogDestination& operator=(const LogDestination&); }; // Errors do not get logged to email by default. LogSeverity LogDestination::email_logging_severity_ = 99999; string LogDestination::addresses_; string LogDestination::hostname_; vector<LogSink*>* LogDestination::sinks_ = NULL; Mutex LogDestination::sink_mutex_; bool LogDestination::terminal_supports_color_ = TerminalSupportsColor(); /* static */ const string& LogDestination::hostname() { if (hostname_.empty()) { GetHostName(&hostname_); if (hostname_.empty()) { hostname_ = "(unknown)"; } } return hostname_; } LogDestination::LogDestination(LogSeverity severity, const char* base_filename) : fileobject_(severity, base_filename), logger_(&fileobject_) { } LogDestination::~LogDestination() { if (logger_ && logger_ != &fileobject_) { // Delete user-specified logger set via SetLogger(). delete logger_; } } inline void LogDestination::FlushLogFilesUnsafe(int min_severity) { // assume we have the log_mutex or we simply don't care // about it for (int i = min_severity; i < NUM_SEVERITIES; i++) { LogDestination* log = log_destinations_[i]; if (log != NULL) { // Flush the base fileobject_ logger directly instead of going // through any wrappers to reduce chance of deadlock. log->fileobject_.FlushUnlocked(); } } } inline void LogDestination::FlushLogFiles(int min_severity) { // Prevent any subtle race conditions by wrapping a mutex lock around // all this stuff. MutexLock l(&log_mutex); for (int i = min_severity; i < NUM_SEVERITIES; i++) { LogDestination* log = log_destination(i); if (log != NULL) { log->logger_->Flush(); } } } //add by fuxingzhong inline void LogDestination::AddLogDestination(const char* base_filename, const char* dir) { MutexLock l(&log_mutex); LogDestination* pDstLog = NULL; std::map<std::string, LogDestination*>::iterator itor = map_destinations_.find(base_filename); if(itor == map_destinations_.end()) { pDstLog = new LogDestination(0, base_filename); pDstLog->fileobject_.log_dir_ = dir; map_destinations_[base_filename] = pDstLog; } return; } inline void LogDestination::DelLogDestination(const char* base_filename) { MutexLock l(&log_mutex); std::map<std::string, LogDestination*>::iterator itor = map_destinations_.find(base_filename); if(itor != map_destinations_.end()) { delete itor->second; map_destinations_.erase(itor); } return; } inline void LogDestination::ChangeLogDestination(const char* base_filename, bool is_create_newlog, int max_log_size, int file_level, int screen_level) { MutexLock l(&log_mutex); LogDestination* pDstLog = NULL; std::map<std::string, LogDestination*>::iterator itor = map_destinations_.find(base_filename); if(itor != map_destinations_.end()) { pDstLog = itor->second; pDstLog->fileobject_.max_size_ = max_log_size; pDstLog->fileobject_.is_create_newlog_ = is_create_newlog; pDstLog->fileobject_.log_level_ = file_level; pDstLog->fileobject_.screen_level_ = screen_level; } return; } inline void LogDestination::SetLogDestination(LogSeverity severity, const char* base_filename) { assert(severity >= 0 && severity < NUM_SEVERITIES); // Prevent any subtle race conditions by wrapping a mutex lock around // all this stuff. MutexLock l(&log_mutex); log_destination(severity)->fileobject_.SetBasename(base_filename); } inline void LogDestination::SetLogSymlink(LogSeverity severity, const char* symlink_basename) { CHECK_GE(severity, 0); CHECK_LT(severity, NUM_SEVERITIES); MutexLock l(&log_mutex); log_destination(severity)->fileobject_.SetSymlinkBasename(symlink_basename); } inline void LogDestination::AddLogSink(LogSink *destination) { // Prevent any subtle race conditions by wrapping a mutex lock around // all this stuff. MutexLock l(&sink_mutex_); if (!sinks_) sinks_ = new vector<LogSink*>; sinks_->push_back(destination); } inline void LogDestination::RemoveLogSink(LogSink *destination) { // Prevent any subtle race conditions by wrapping a mutex lock around // all this stuff. MutexLock l(&sink_mutex_); // This doesn't keep the sinks in order, but who cares? if (sinks_) { for (int i = sinks_->size() - 1; i >= 0; i--) { if ((*sinks_)[i] == destination) { (*sinks_)[i] = (*sinks_)[sinks_->size() - 1]; sinks_->pop_back(); break; } } } } inline void LogDestination::SetLogFilenameExtension(const char* ext) { // Prevent any subtle race conditions by wrapping a mutex lock around // all this stuff. MutexLock l(&log_mutex); for ( int severity = 0; severity < NUM_SEVERITIES; ++severity ) { log_destination(severity)->fileobject_.SetExtension(ext); } } inline void LogDestination::SetStderrLogging(LogSeverity min_severity) { assert(min_severity >= 0 && min_severity < NUM_SEVERITIES); // Prevent any subtle race conditions by wrapping a mutex lock around // all this stuff. MutexLock l(&log_mutex); FLAGS_stderrthreshold = min_severity; } inline void LogDestination::LogToStderr() { // *Don't* put this stuff in a mutex lock, since SetStderrLogging & // SetLogDestination already do the locking! SetStderrLogging(0); // thus everything is "also" logged to stderr for ( int i = 0; i < NUM_SEVERITIES; ++i ) { SetLogDestination(i, ""); // "" turns off logging to a logfile } } inline void LogDestination::SetEmailLogging(LogSeverity min_severity, const char* addresses) { assert(min_severity >= 0 && min_severity < NUM_SEVERITIES); // Prevent any subtle race conditions by wrapping a mutex lock around // all this stuff. MutexLock l(&log_mutex); LogDestination::email_logging_severity_ = min_severity; LogDestination::addresses_ = addresses; } static void ColoredWriteToStderr(LogSeverity severity, const char* message, size_t len) { const GLogColor color = (LogDestination::terminal_supports_color() && FLAGS_colorlogtostderr) ? SeverityToColor(severity) : COLOR_DEFAULT; // Avoid using cerr from this module since we may get called during // exit code, and cerr may be partially or fully destroyed by then. if (COLOR_DEFAULT == color) { fwrite(message, len, 1, stderr); return; } #ifdef OS_WINDOWS const HANDLE stderr_handle = GetStdHandle(STD_ERROR_HANDLE); // Gets the current text color. CONSOLE_SCREEN_BUFFER_INFO buffer_info; GetConsoleScreenBufferInfo(stderr_handle, &buffer_info); const WORD old_color_attrs = buffer_info.wAttributes; // We need to flush the stream buffers into the console before each // SetConsoleTextAttribute call lest it affect the text that is already // printed but has not yet reached the console. fflush(stderr); SetConsoleTextAttribute(stderr_handle, GetColorAttribute(color) | FOREGROUND_INTENSITY); fwrite(message, len, 1, stderr); fflush(stderr); // Restores the text color. SetConsoleTextAttribute(stderr_handle, old_color_attrs); #else fprintf(stderr, "\033[0;3%sm", GetAnsiColorCode(color)); fwrite(message, len, 1, stderr); fprintf(stderr, "\033[m"); // Resets the terminal to default. #endif // OS_WINDOWS } static void WriteToStderr(const char* message, size_t len) { // Avoid using cerr from this module since we may get called during // exit code, and cerr may be partially or fully destroyed by then. fwrite(message, len, 1, stderr); } inline void LogDestination::MaybeLogToStderr(LogSeverity severity, const char* message, size_t len) { if ((severity >= FLAGS_stderrthreshold) || FLAGS_alsologtostderr) { ColoredWriteToStderr(severity, message, len); #ifdef OS_WINDOWS // On Windows, also output to the debugger ::OutputDebugStringA(string(message,len).c_str()); #endif } } inline void LogDestination::MaybeLogToEmail(LogSeverity severity, const char* message, size_t len) { if (severity >= email_logging_severity_ || severity >= FLAGS_logemaillevel) { string to(FLAGS_alsologtoemail); if (!addresses_.empty()) { if (!to.empty()) { to += ","; } to += addresses_; } const string subject(string("[LOG] ") + LogSeverityNames[severity] + ": " + glog_internal_namespace_::ProgramInvocationShortName()); string body(hostname()); body += "\n\n"; body.append(message, len); // should NOT use SendEmail(). The caller of this function holds the // log_mutex and SendEmail() calls LOG/VLOG which will block trying to // acquire the log_mutex object. Use SendEmailInternal() and set // use_logging to false. SendEmailInternal(to.c_str(), subject.c_str(), body.c_str(), false); } } inline void LogDestination::MaybeLogToLogfile(LogSeverity severity, time_t timestamp, const char* message, size_t len) { const bool should_flush = severity > FLAGS_logbuflevel; LogDestination* destination = log_destination(severity); destination->logger_->Write(should_flush, timestamp, message, len); } inline void LogDestination::LogToAllLogfiles(LogSeverity severity, time_t timestamp, const char* message, size_t len) { if ( FLAGS_logtostderr ) { // global flag: never log to file ColoredWriteToStderr(severity, message, len); } else { for (int i = severity; i >= 0; --i) LogDestination::MaybeLogToLogfile(i, timestamp, message, len); } } //add by fuxingzhong static void LogToScreen(LogSeverity severity, const char* message, size_t len) { ColoredWriteToStderr(severity, message, len); #ifdef OS_WINDOWS ::OutputDebugStringA(string(message, len).c_str()); #endif } inline void LogDestination::MyToLogfiles(const char* filename, LogSeverity severity, time_t timestamp, const char* message, size_t len) { if(FLAGS_logtostderr) { ColoredWriteToStderr(severity, message, len); } else{ if( severity < FLAGS_log_level_to_file ) return; const bool should_flush = severity > FLAGS_logbuflevel; LogDestination* pDstLog = NULL; std::map<string, LogDestination*>::iterator itor = map_destinations_.find(filename); if(itor == map_destinations_.end()) { assert(0); return; } else pDstLog = itor->second; if(pDstLog) { if(severity >= pDstLog->fileobject_.log_level_) pDstLog->logger_->Write(should_flush, timestamp, message, len); if(severity >= pDstLog->fileobject_.screen_level_) LogToScreen(severity, message, len); } } return; } inline void LogDestination::LogToSinks(LogSeverity severity, const char *full_filename, const char *base_filename, int line, const struct ::tm* tm_time, const char* message, size_t message_len, int32 usecs) { ReaderMutexLock l(&sink_mutex_); if (sinks_) { for (int i = sinks_->size() - 1; i >= 0; i--) { (*sinks_)[i]->send(severity, full_filename, base_filename, line, tm_time, message, message_len, usecs); } } } inline void LogDestination::WaitForSinks(LogMessage::LogMessageData* data) { ReaderMutexLock l(&sink_mutex_); if (sinks_) { for (int i = sinks_->size() - 1; i >= 0; i--) { (*sinks_)[i]->WaitTillSent(); } } const bool send_to_sink = (data->send_method_ == &LogMessage::SendToSink) || (data->send_method_ == &LogMessage::SendToSinkAndLog); if (send_to_sink && data->sink_ != NULL) { data->sink_->WaitTillSent(); } } LogDestination* LogDestination::log_destinations_[NUM_SEVERITIES]; //add by fuxingzhong std::map<std::string, LogDestination*> LogDestination::map_destinations_; inline LogDestination* LogDestination::log_destination(LogSeverity severity) { assert(severity >=0 && severity < NUM_SEVERITIES); if (!log_destinations_[severity]) { log_destinations_[severity] = new LogDestination(severity, NULL); } return log_destinations_[severity]; } void LogDestination::DeleteLogDestinations() { for (int severity = 0; severity < NUM_SEVERITIES; ++severity) { delete log_destinations_[severity]; log_destinations_[severity] = NULL; } MutexLock l(&sink_mutex_); delete sinks_; sinks_ = NULL; } namespace { bool IsGlogLog(const string& filename) { // Check if filename matches the pattern of a glog file: // "<program name>.<hostname>.<user name>.log...". const int kKeywordCount = 4; std::string keywords[kKeywordCount] = { glog_internal_namespace_::ProgramInvocationShortName(), LogDestination::hostname(), MyUserName(), "log" }; int start_pos = 0; for (int i = 0; i < kKeywordCount; i++) { if (filename.find(keywords[i], start_pos) == filename.npos) { return false; } start_pos += keywords[i].size() + 1; } return true; } bool LastModifiedOver(const string& filepath, int days) { // Try to get the last modified time of this file. struct stat file_stat; if (stat(filepath.c_str(), &file_stat) == 0) { // A day is 86400 seconds, so 7 days is 86400 * 7 = 604800 seconds. time_t last_modified_time = file_stat.st_mtime; time_t current_time = time(NULL); return difftime(current_time, last_modified_time) > days * 86400; } // If failed to get file stat, don't return true! return false; } vector<string> GetOverdueLogNames(string log_directory, int days) { // The names of overdue logs. vector<string> overdue_log_names; // Try to get all files within log_directory. DIR *dir; struct dirent *ent; char dir_delim = '/'; #ifdef OS_WINDOWS dir_delim = '\\'; #endif // If log_directory doesn't end with a slash, append a slash to it. if (log_directory.at(log_directory.size() - 1) != dir_delim) { log_directory += dir_delim; } if ((dir=opendir(log_directory.c_str()))) { while ((ent=readdir(dir))) { if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, "..")) { continue; } string filepath = log_directory + ent->d_name; if (IsGlogLog(ent->d_name) && LastModifiedOver(filepath, days)) { overdue_log_names.push_back(filepath); } } closedir(dir); } return overdue_log_names; } // Is log_cleaner enabled? // This option can be enabled by calling google::EnableLogCleaner(days) bool log_cleaner_enabled_; int log_cleaner_overdue_days_ = 7; } // namespace namespace { LogFileObject::LogFileObject(LogSeverity severity, const char* base_filename) : base_filename_selected_(base_filename != NULL), base_filename_((base_filename != NULL) ? base_filename : ""), symlink_basename_(glog_internal_namespace_::ProgramInvocationShortName()), filename_extension_(), file_(NULL), severity_(severity), bytes_since_flush_(0), dropped_mem_length_(0), file_length_(0), rollover_attempt_(kRolloverAttemptFrequency-1), next_flush_time_(0) { assert(severity >= 0); assert(severity < NUM_SEVERITIES); main_day_ = -1; if(base_filename != NULL) stripped_filename_ = base_filename; max_size_ = 1; is_create_newlog_ = true; log_level_ = 0; screen_level_ = 0; } LogFileObject::~LogFileObject() { MutexLock l(&lock_); if (file_ != NULL) { fclose(file_); file_ = NULL; } } void LogFileObject::SetBasename(const char* basename) { MutexLock l(&lock_); base_filename_selected_ = true; if (base_filename_ != basename) { // Get rid of old log file since we are changing names if (file_ != NULL) { fclose(file_); file_ = NULL; rollover_attempt_ = kRolloverAttemptFrequency-1; } base_filename_ = basename; } } void LogFileObject::SetExtension(const char* ext) { MutexLock l(&lock_); if (filename_extension_ != ext) { // Get rid of old log file since we are changing names if (file_ != NULL) { fclose(file_); file_ = NULL; rollover_attempt_ = kRolloverAttemptFrequency-1; } filename_extension_ = ext; } } void LogFileObject::SetSymlinkBasename(const char* symlink_basename) { MutexLock l(&lock_); symlink_basename_ = symlink_basename; } void LogFileObject::Flush() { MutexLock l(&lock_); FlushUnlocked(); } void LogFileObject::FlushUnlocked(){ if (file_ != NULL) { fflush(file_); bytes_since_flush_ = 0; } // Figure out when we are due for another flush. const int64 next = (FLAGS_logbufsecs * static_cast<int64>(1000000)); // in usec next_flush_time_ = CycleClock_Now() + UsecToCycles(next); } bool LogFileObject::CreateLogfile(const string& time_pid_string) { string string_filename = base_filename_+filename_extension_; if (FLAGS_timestamp_in_logfile_name) { string_filename += time_pid_string; } const char* filename = string_filename.c_str(); //only write to files, create if non-existant. int flags = O_WRONLY | O_CREAT; if (FLAGS_timestamp_in_logfile_name) { //demand that the file is unique for our timestamp (fail if it exists). flags = flags | O_EXCL; } int fd = open(filename, flags, FLAGS_logfile_mode); if (fd == -1) return false; #ifdef HAVE_FCNTL // Mark the file close-on-exec. We don't really care if this fails fcntl(fd, F_SETFD, FD_CLOEXEC); // Mark the file as exclusive write access to avoid two clients logging to the // same file. This applies particularly when !FLAGS_timestamp_in_logfile_name // (otherwise open would fail because the O_EXCL flag on similar filename). // locks are released on unlock or close() automatically, only after log is // released. // This will work after a fork as it is not inherited (not stored in the fd). // Lock will not be lost because the file is opened with exclusive lock (write) // and we will never read from it inside the process. // TODO windows implementation of this (as flock is not available on mingw). static struct flock w_lock; w_lock.l_type = F_WRLCK; w_lock.l_start = 0; w_lock.l_whence = SEEK_SET; w_lock.l_len = 0; int wlock_ret = fcntl(fd, F_SETLK, &w_lock); if (wlock_ret == -1) { close(fd); //as we are failing already, do not check errors here return false; } #endif //fdopen in append mode so if the file exists it will fseek to the end file_ = fdopen(fd, "a"); // Make a FILE*. if (file_ == NULL) { // Man, we're screwed! close(fd); if (FLAGS_timestamp_in_logfile_name) { unlink(filename); // Erase the half-baked evidence: an unusable log file, only if we just created it. } return false; } #ifdef OS_WINDOWS // https://github.com/golang/go/issues/27638 - make sure we seek to the end to append // empirically replicated with wine over mingw build if (!FLAGS_timestamp_in_logfile_name) { if (fseek(file_, 0, SEEK_END) != 0) { return false; } } #endif // We try to create a symlink called <program_name>.<severity>, // which is easier to use. (Every time we create a new logfile, // we destroy the old symlink and create a new one, so it always // points to the latest logfile.) If it fails, we're sad but it's // no error. if (!symlink_basename_.empty()) { // take directory from filename const char* slash = strrchr(filename, PATH_SEPARATOR); const string linkname = symlink_basename_ + '.' + LogSeverityNames[severity_]; string linkpath; if ( slash ) linkpath = string(filename, slash-filename+1); // get dirname linkpath += linkname; unlink(linkpath.c_str()); // delete old one if it exists #if defined(OS_WINDOWS) // TODO(hamaji): Create lnk file on Windows? #elif defined(HAVE_UNISTD_H) // We must have unistd.h. // Make the symlink be relative (in the same dir) so that if the // entire log directory gets relocated the link is still valid. const char *linkdest = slash ? (slash + 1) : filename; if (symlink(linkdest, linkpath.c_str()) != 0) { // silently ignore failures } // Make an additional link to the log file in a place specified by // FLAGS_log_link, if indicated if (!FLAGS_log_link.empty()) { linkpath = FLAGS_log_link + "/" + linkname; unlink(linkpath.c_str()); // delete old one if it exists if (symlink(filename, linkpath.c_str()) != 0) { // silently ignore failures } } #endif } return true; // Everything worked } //add by fuxingzhong 判断日期改变 bool LogFileObject::DayHasChanged() { #ifdef OS_WINDOWS SYSTEMTIME sysTime; GetLocalTime(&sysTime); if(sysTime.wDay != main_day_) { main_day_ = sysTime.wDay; return true; } return false; #else time_t raw_time; struct tm* tm_info; time(&raw_time); tm_info = localtime(&raw_time); if( !tm_info ) return false; if(tm_info->tm_mday != main_day_) { main_day_ = tm_info->tm_mday; return true; } return false; #endif } #ifdef OS_WINDOWS #define ACCESS _access #define MKDIR(a) _mkdir((a)) #else #define ACCESS access #define MKDIR(a) mkdir((a), 0755) #endif //生成新文件 bool LogFileObject::CreateLogDir(std::string& strDir) { char szDir[2048] = {0}; char szDateDir[64+1] = {0}; memcpy(szDir, strDir.c_str(), strDir.length()); int32 nLen = strlen(szDir); if(szDir[nLen-1] != '\\' && szDir[nLen-1] != '/') szDir[nLen] = '/'; time_t nTime; struct tm* pstTime; WallTime now = WallTime_Now(); nTime = static_cast<time_t>(now); pstTime = localtime(&nTime); if( pstTime ) strftime(szDateDir, 64, "log%Y-%m-%d", pstTime); else strcpy(szDateDir, "log1900-01-01"); strcat(szDir, szDateDir); strcat(szDir, "/"); nLen = strlen(szDir); int32 i = 0; int32 nRet = 0; for(i = 0;i < nLen;i++) { if(szDir[i] == '\\' || szDir[i] == '/') { if(i == 0) continue; szDir[i] = '\0'; //不存在则创建 nRet = ACCESS(szDir, 0); if(nRet != 0) { nRet = MKDIR(szDir); if(nRet != 0) return false; } szDir[i] = '/'; } } strDir = szDir; return true; } void LogFileObject::Write(bool force_flush, time_t timestamp, const char* message, int message_len) { MutexLock l(&lock_); // We don't log if the base_name_ is "" (which means "don't write") if (base_filename_selected_ && base_filename_.empty()) { return; } //增加天数改变判断 day_haschange_ = DayHasChanged(); if (static_cast<int>(file_length_ >> 20) >= MaxLogSize() || PidHasChanged() || day_haschange_) { if (file_ != NULL) fclose(file_); file_ = NULL; file_length_ = bytes_since_flush_ = dropped_mem_length_ = 0; rollover_attempt_ = kRolloverAttemptFrequency-1; } // If there's no destination file, make one before outputting if (file_ == NULL) { // Try to rollover the log file every 32 log messages. The only time // this could matter would be when we have trouble creating the log // file. If that happens, we'll lose lots of log messages, of course! if (++rollover_attempt_ != kRolloverAttemptFrequency) return; rollover_attempt_ = 0; struct ::tm tm_time; localtime_r(&timestamp, &tm_time); // The logfile's filename will have the date/time & pid in it ostringstream time_pid_stream; time_pid_stream.fill('0'); time_pid_stream << 1900+tm_time.tm_year << setw(2) << 1+tm_time.tm_mon << setw(2) << tm_time.tm_mday << '-' << setw(2) << tm_time.tm_hour << setw(2) << tm_time.tm_min << setw(2) << tm_time.tm_sec << ".log"; //<< GetMainThreadPid(); const string& time_pid_string = time_pid_stream.str(); if (base_filename_selected_) { //修改文件名 std::string strDir = log_dir_; if( !CreateLogDir(strDir) ) return; base_filename_ = strDir + stripped_filename_ + "_"; if (!CreateLogfile(time_pid_string)) { perror("Could not create log file"); fprintf(stderr, "COULD NOT CREATE LOGFILE '%s'!\n", time_pid_string.c_str()); return; } } else { // If no base filename for logs of this severity has been set, use a // default base filename of // "<program name>.<hostname>.<user name>.log.<severity level>.". So // logfiles will have names like // webserver.examplehost.root.log.INFO.19990817-150000.4354, where // 19990817 is a date (1999 August 17), 150000 is a time (15:00:00), // and 4354 is the pid of the logging process. The date & time reflect // when the file was created for output. // // Where does the file get put? Successively try the directories // "/tmp", and "." string stripped_filename( glog_internal_namespace_::ProgramInvocationShortName()); string hostname; GetHostName(&hostname); string uidname = MyUserName(); // We should not call CHECK() here because this function can be // called after holding on to log_mutex. We don't want to // attempt to hold on to the same mutex, and get into a // deadlock. Simply use a name like invalid-user. if (uidname.empty()) uidname = "invalid-user"; //注释 /*stripped_filename = stripped_filename+'.'+hostname+'.' +uidname+".log." +LogSeverityNames[severity_]+'.';*/ // We're going to (potentially) try to put logs in several different dirs const vector<string> & log_dirs = GetLoggingDirectories(); // Go through the list of dirs, and try to create the log file in each // until we succeed or run out of options bool success = false; for (vector<string>::const_iterator dir = log_dirs.begin(); dir != log_dirs.end(); ++dir) { //修改文件名 string logDir = *dir; CreateLogDir(logDir); base_filename_ = logDir + stripped_filename + "_"; //base_filename_ = *dir + "/" + stripped_filename; if ( CreateLogfile(time_pid_string) ) { success = true; break; } } // If we never succeeded, we have to give up if ( success == false ) { perror("Could not create logging file"); fprintf(stderr, "COULD NOT CREATE A LOGGINGFILE %s!", time_pid_string.c_str()); return; } } // Write a header message into the log file ostringstream file_header_stream; file_header_stream.fill('0'); file_header_stream << "Log file created at: " << 1900+tm_time.tm_year << '/' << setw(2) << 1+tm_time.tm_mon << '/' << setw(2) << tm_time.tm_mday << ' ' << setw(2) << tm_time.tm_hour << ':' << setw(2) << tm_time.tm_min << ':' << setw(2) << tm_time.tm_sec << '\n' << "Running on machine: " << LogDestination::hostname() << '\n' << "Log line format: yyyymmdd hh:mm:ss.uuuuuu [log-level]" << "[threadid] msg" << '\n'; const string& file_header_string = file_header_stream.str(); const int header_len = file_header_string.size(); fwrite(file_header_string.data(), 1, header_len, file_); file_length_ += header_len; bytes_since_flush_ += header_len; } // Write to LOG file if ( !stop_writing ) { // fwrite() doesn't return an error when the disk is full, for // messages that are less than 4096 bytes. When the disk is full, // it returns the message length for messages that are less than // 4096 bytes. fwrite() returns 4096 for message lengths that are // greater than 4096, thereby indicating an error. errno = 0; fwrite(message, 1, message_len, file_); if ( FLAGS_stop_logging_if_full_disk && errno == ENOSPC ) { // disk full, stop writing to disk stop_writing = true; // until the disk is return; } else { file_length_ += message_len; bytes_since_flush_ += message_len; } } else { if ( CycleClock_Now() >= next_flush_time_ ) stop_writing = false; // check to see if disk has free space. return; // no need to flush } // See important msgs *now*. Also, flush logs at least every 10^6 chars, // or every "FLAGS_logbufsecs" seconds. if ( force_flush || (bytes_since_flush_ >= 1000000) || (CycleClock_Now() >= next_flush_time_) ) { FlushUnlocked(); #ifdef OS_LINUX // Only consider files >= 3MiB if (FLAGS_drop_log_memory && file_length_ >= (3 << 20)) { // Don't evict the most recent 1-2MiB so as not to impact a tailer // of the log file and to avoid page rounding issue on linux < 4.7 uint32 total_drop_length = (file_length_ & ~((1 << 20) - 1)) - (1 << 20); uint32 this_drop_length = total_drop_length - dropped_mem_length_; if (this_drop_length >= (2 << 20)) { // Only advise when >= 2MiB to drop # if defined(__ANDROID__) && defined(__ANDROID_API__) && (__ANDROID_API__ < 21) // 'posix_fadvise' introduced in API 21: // * https://android.googlesource.com/platform/bionic/+/6880f936173081297be0dc12f687d341b86a4cfa/libc/libc.map.txt#732 # else posix_fadvise(fileno(file_), dropped_mem_length_, this_drop_length, POSIX_FADV_DONTNEED); # endif dropped_mem_length_ = total_drop_length; } } #endif // Perform clean up for old logs if (log_cleaner_enabled_) { const vector<string>& dirs = GetLoggingDirectories(); for (size_t i = 0; i < dirs.size(); i++) { vector<string> logs = GetOverdueLogNames(dirs[i], log_cleaner_overdue_days_); for (size_t j = 0; j < logs.size(); j++) { static_cast<void>(unlink(logs[j].c_str())); } } } } } } // namespace // Static log data space to avoid alloc failures in a LOG(FATAL) // // Since multiple threads may call LOG(FATAL), and we want to preserve // the data from the first call, we allocate two sets of space. One // for exclusive use by the first thread, and one for shared use by // all other threads. static Mutex fatal_msg_lock; static CrashReason crash_reason; static bool fatal_msg_exclusive = true; static LogMessage::LogMessageData fatal_msg_data_exclusive; static LogMessage::LogMessageData fatal_msg_data_shared; #ifdef GLOG_THREAD_LOCAL_STORAGE // Static thread-local log data space to use, because typically at most one // LogMessageData object exists (in this case glog makes zero heap memory // allocations). static GLOG_THREAD_LOCAL_STORAGE bool thread_data_available = true; #ifdef HAVE_ALIGNED_STORAGE static GLOG_THREAD_LOCAL_STORAGE std::aligned_storage<sizeof(LogMessage::LogMessageData), alignof(LogMessage::LogMessageData)>::type thread_msg_data; #else static GLOG_THREAD_LOCAL_STORAGE char thread_msg_data[sizeof(void*) + sizeof(LogMessage::LogMessageData)]; #endif // HAVE_ALIGNED_STORAGE #endif // defined(GLOG_THREAD_LOCAL_STORAGE) LogMessage::LogMessageData::LogMessageData() : stream_(message_text_, LogMessage::kMaxLogMessageLen, 0) { } LogMessage::LogMessage(const char* file, int line, LogSeverity severity, int ctr, void (LogMessage::*send_method)()) : allocated_(NULL) { Init(file, line, severity, send_method); data_->stream_.set_ctr(ctr); } LogMessage::LogMessage(const char* file, int line, const CheckOpString& result) : allocated_(NULL) { Init(file, line, GLOG_FATAL, &LogMessage::SendToLog); stream() << "Check failed: " << (*result.str_) << " "; } LogMessage::LogMessage(const char* file, int line) : allocated_(NULL) { Init(file, line, GLOG_INFO, &LogMessage::SendToLog); } LogMessage::LogMessage(const char* file, int line, LogSeverity severity) : allocated_(NULL) { Init(file, line, severity, &LogMessage::SendToLog); } LogMessage::LogMessage(const char* file, int line, LogSeverity severity, LogSink* sink, bool also_send_to_log) : allocated_(NULL) { Init(file, line, severity, also_send_to_log ? &LogMessage::SendToSinkAndLog : &LogMessage::SendToSink); data_->sink_ = sink; // override Init()'s setting to NULL } LogMessage::LogMessage(const char* file, int line, LogSeverity severity, vector<string> *outvec) : allocated_(NULL) { Init(file, line, severity, &LogMessage::SaveOrSendToLog); data_->outvec_ = outvec; // override Init()'s setting to NULL } LogMessage::LogMessage(const char* file, int line, LogSeverity severity, string *message) : allocated_(NULL) { Init(file, line, severity, &LogMessage::WriteToStringAndLog); data_->message_ = message; // override Init()'s setting to NULL } void LogMessage::Init(const char* file, int line, LogSeverity severity, void (LogMessage::*send_method)()) { allocated_ = NULL; if (severity != GLOG_FATAL || !exit_on_dfatal) { #ifdef GLOG_THREAD_LOCAL_STORAGE // No need for locking, because this is thread local. if (thread_data_available) { thread_data_available = false; #ifdef HAVE_ALIGNED_STORAGE data_ = new (&thread_msg_data) LogMessageData; #else const uintptr_t kAlign = sizeof(void*) - 1; char* align_ptr = reinterpret_cast<char*>(reinterpret_cast<uintptr_t>(thread_msg_data + kAlign) & ~kAlign); data_ = new (align_ptr) LogMessageData; assert(reinterpret_cast<uintptr_t>(align_ptr) % sizeof(void*) == 0); #endif } else { allocated_ = new LogMessageData(); data_ = allocated_; } #else // !defined(GLOG_THREAD_LOCAL_STORAGE) allocated_ = new LogMessageData(); data_ = allocated_; #endif // defined(GLOG_THREAD_LOCAL_STORAGE) data_->first_fatal_ = false; } else { MutexLock l(&fatal_msg_lock); if (fatal_msg_exclusive) { fatal_msg_exclusive = false; data_ = &fatal_msg_data_exclusive; data_->first_fatal_ = true; } else { data_ = &fatal_msg_data_shared; data_->first_fatal_ = false; } } file_name = ""; stream().fill('0'); data_->preserved_errno_ = errno; data_->severity_ = severity; data_->line_ = line; data_->send_method_ = send_method; data_->sink_ = NULL; data_->outvec_ = NULL; WallTime now = WallTime_Now(); data_->timestamp_ = static_cast<time_t>(now); localtime_r(&data_->timestamp_, &data_->tm_time_); data_->usecs_ = static_cast<int32>((now - data_->timestamp_) * 1000000); data_->num_chars_to_log_ = 0; data_->num_chars_to_syslog_ = 0; data_->basename_ = const_basename(file); data_->fullname_ = file; data_->has_been_flushed_ = false; // If specified, prepend a prefix to each line. For example: // I20201018 160715 f5d4fbb0 logging.cc:1153] // (log level, GMT year, month, date, time, thread_id, file basename, line) // We exclude the thread_id for the default thread. // if (FLAGS_log_prefix && (line != kNoLogPrefix)) { // stream() << LogSeverityNames[severity][0] // << setw(4) << 1900+data_->tm_time_.tm_year // << setw(2) << 1+data_->tm_time_.tm_mon // << setw(2) << data_->tm_time_.tm_mday // << ' ' // << setw(2) << data_->tm_time_.tm_hour << ':' // << setw(2) << data_->tm_time_.tm_min << ':' // << setw(2) << data_->tm_time_.tm_sec << "." // << setw(6) << data_->usecs_ // << ' ' // << setfill(' ') << setw(5) // << static_cast<unsigned int>(GetTID()) << setfill('0') // << ' ' // << data_->basename_ << ':' << data_->line_ << "] "; // } // data_->num_prefix_chars_ = data_->stream_.pcount(); //change by fuxingzhong,to modify logging pattern if (FLAGS_log_prefix && (line != kNoLogPrefix)) { stream() << setw(4) << 1900+data_->tm_time_.tm_year << setw(2) << 1+data_->tm_time_.tm_mon << setw(2) << data_->tm_time_.tm_mday << 'T' << setw(2) << data_->tm_time_.tm_hour << ':' << setw(2) << data_->tm_time_.tm_min << ':' << setw(2) << data_->tm_time_.tm_sec << "." << setw(6) << data_->usecs_ << ' ' << LogSeverityNames[severity] << ' ' << " [" << setfill(' ') << setw(5) << static_cast<unsigned int>(GetTID()) << setfill('0') << "] "; } data_->num_prefix_chars_ = data_->stream_.pcount(); if (!FLAGS_log_backtrace_at.empty()) { char fileline[128]; snprintf(fileline, sizeof(fileline), "%s:%d", data_->basename_, line); #ifdef HAVE_STACKTRACE if (!strcmp(FLAGS_log_backtrace_at.c_str(), fileline)) { string stacktrace; DumpStackTraceToString(&stacktrace); stream() << " (stacktrace:\n" << stacktrace << ") "; } #endif } } LogMessage::~LogMessage() { Flush(); #ifdef GLOG_THREAD_LOCAL_STORAGE if (data_ == static_cast<void*>(&thread_msg_data)) { data_->~LogMessageData(); thread_data_available = true; } else { delete allocated_; } #else // !defined(GLOG_THREAD_LOCAL_STORAGE) delete allocated_; #endif // defined(GLOG_THREAD_LOCAL_STORAGE) } int LogMessage::preserved_errno() const { return data_->preserved_errno_; } ostream& LogMessage::stream() { return data_->stream_; /*if(data_ && data_->stream_alloc_ && data_buf_) //防止内存分配失败 return *(data_stream_); else return std::cerr;*/ } ostream& LogMessage::stream(const char* arg) { if(arg) file_name = arg; else file_name = ""; if(data_) return data_->stream_; else return std::cerr; } // Flush buffered message, called by the destructor, or any other function // that needs to synchronize the log. void LogMessage::Flush() { if (data_->has_been_flushed_ || data_->severity_ < FLAGS_minloglevel) return; data_->num_chars_to_log_ = data_->stream_.pcount(); data_->num_chars_to_syslog_ = data_->num_chars_to_log_ - data_->num_prefix_chars_; // Do we need to add a \n to the end of this message? bool append_newline = (data_->message_text_[data_->num_chars_to_log_-1] != '\n'); char original_final_char = '\0'; // If we do need to add a \n, we'll do it by violating the memory of the // ostrstream buffer. This is quick, and we'll make sure to undo our // modification before anything else is done with the ostrstream. It // would be preferable not to do things this way, but it seems to be // the best way to deal with this. if (append_newline) { original_final_char = data_->message_text_[data_->num_chars_to_log_]; data_->message_text_[data_->num_chars_to_log_++] = '\n'; } // Prevent any subtle race conditions by wrapping a mutex lock around // the actual logging action per se. { MutexLock l(&log_mutex); (this->*(data_->send_method_))(); ++num_messages_[static_cast<int>(data_->severity_)]; } LogDestination::WaitForSinks(data_); if (append_newline) { // Fix the ostrstream back how it was before we screwed with it. // It's 99.44% certain that we don't need to worry about doing this. data_->message_text_[data_->num_chars_to_log_-1] = original_final_char; } // If errno was already set before we enter the logging call, we'll // set it back to that value when we return from the logging call. // It happens often that we log an error message after a syscall // failure, which can potentially set the errno to some other // values. We would like to preserve the original errno. if (data_->preserved_errno_ != 0) { errno = data_->preserved_errno_; } // Note that this message is now safely logged. If we're asked to flush // again, as a result of destruction, say, we'll do nothing on future calls. data_->has_been_flushed_ = true; } // Copy of first FATAL log message so that we can print it out again // after all the stack traces. To preserve legacy behavior, we don't // use fatal_msg_data_exclusive. static time_t fatal_time; static char fatal_message[256]; void ReprintFatalMessage() { if (fatal_message[0]) { const int n = strlen(fatal_message); if (!FLAGS_logtostderr) { // Also write to stderr (don't color to avoid terminal checks) WriteToStderr(fatal_message, n); } LogDestination::LogToAllLogfiles(GLOG_ERROR, fatal_time, fatal_message, n); } } // L >= log_mutex (callers must hold the log_mutex). void LogMessage::SendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) { static bool already_warned_before_initgoogle = false; log_mutex.AssertHeld(); RAW_DCHECK(data_->num_chars_to_log_ > 0 && data_->message_text_[data_->num_chars_to_log_-1] == '\n', ""); // Messages of a given severity get logged to lower severity logs, too if (!already_warned_before_initgoogle && !IsGoogleLoggingInitialized()) { const char w[] = "WARNING: Logging before InitGoogleLogging() is " "written to STDERR\n"; WriteToStderr(w, strlen(w)); already_warned_before_initgoogle = true; } // global flag: never log to file if set. Also -- don't log to a // file if we haven't parsed the command line flags to get the // program name. if (FLAGS_logtostderr || !IsGoogleLoggingInitialized()) { ColoredWriteToStderr(data_->severity_, data_->message_text_, data_->num_chars_to_log_); // this could be protected by a flag if necessary. LogDestination::LogToSinks(data_->severity_, data_->fullname_, data_->basename_, data_->line_, &data_->tm_time_, data_->message_text_ + data_->num_prefix_chars_, (data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1), data_->usecs_); } else { if(file_name != "") { LogDestination::MyToLogfiles(file_name.c_str(), data_->severity_, data_->timestamp_, data_->message_text_, data_->num_chars_to_log_); } else { // log this message to all log files of severity <= severity_ LogDestination::LogToAllLogfiles(data_->severity_, data_->timestamp_, data_->message_text_, data_->num_chars_to_log_); LogDestination::MaybeLogToStderr(data_->severity_, data_->message_text_, data_->num_chars_to_log_); LogDestination::MaybeLogToEmail(data_->severity_, data_->message_text_, data_->num_chars_to_log_); LogDestination::LogToSinks(data_->severity_, data_->fullname_, data_->basename_, data_->line_, &data_->tm_time_, data_->message_text_ + data_->num_prefix_chars_, (data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1), data_->usecs_); // NOTE: -1 removes trailing \n } } // If we log a FATAL message, flush all the log destinations, then toss // a signal for others to catch. We leave the logs in a state that // someone else can use them (as long as they flush afterwards) if (data_->severity_ == GLOG_FATAL && exit_on_dfatal) { if (data_->first_fatal_) { // Store crash information so that it is accessible from within signal // handlers that may be invoked later. RecordCrashReason(&crash_reason); SetCrashReason(&crash_reason); // Store shortened fatal message for other logs and GWQ status const int copy = min<int>(data_->num_chars_to_log_, sizeof(fatal_message)-1); memcpy(fatal_message, data_->message_text_, copy); fatal_message[copy] = '\0'; fatal_time = data_->timestamp_; } if (!FLAGS_logtostderr) { for (int i = 0; i < NUM_SEVERITIES; ++i) { if ( LogDestination::log_destinations_[i] ) LogDestination::log_destinations_[i]->logger_->Write(true, 0, "", 0); } } // release the lock that our caller (directly or indirectly) // LogMessage::~LogMessage() grabbed so that signal handlers // can use the logging facility. Alternately, we could add // an entire unsafe logging interface to bypass locking // for signal handlers but this seems simpler. log_mutex.Unlock(); LogDestination::WaitForSinks(data_); const char* message = "*** Check failure stack trace: ***\n"; if (write(STDERR_FILENO, message, strlen(message)) < 0) { // Ignore errors. } Fail(); } } void LogMessage::RecordCrashReason( glog_internal_namespace_::CrashReason* reason) { reason->filename = fatal_msg_data_exclusive.fullname_; reason->line_number = fatal_msg_data_exclusive.line_; reason->message = fatal_msg_data_exclusive.message_text_ + fatal_msg_data_exclusive.num_prefix_chars_; #ifdef HAVE_STACKTRACE // Retrieve the stack trace, omitting the logging frames that got us here. reason->depth = GetStackTrace(reason->stack, ARRAYSIZE(reason->stack), 4); #else reason->depth = 0; #endif } #ifdef HAVE___ATTRIBUTE__ # define ATTRIBUTE_NORETURN __attribute__((noreturn)) #else # define ATTRIBUTE_NORETURN #endif #if defined(OS_WINDOWS) __declspec(noreturn) #endif static void logging_fail() ATTRIBUTE_NORETURN; static void logging_fail() { abort(); } typedef void (*logging_fail_func_t)() ATTRIBUTE_NORETURN; GOOGLE_GLOG_DLL_DECL logging_fail_func_t g_logging_fail_func = &logging_fail; void InstallFailureFunction(void (*fail_func)()) { g_logging_fail_func = (logging_fail_func_t)fail_func; } void LogMessage::Fail() { g_logging_fail_func(); } // L >= log_mutex (callers must hold the log_mutex). void LogMessage::SendToSink() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) { if (data_->sink_ != NULL) { RAW_DCHECK(data_->num_chars_to_log_ > 0 && data_->message_text_[data_->num_chars_to_log_-1] == '\n', ""); data_->sink_->send(data_->severity_, data_->fullname_, data_->basename_, data_->line_, &data_->tm_time_, data_->message_text_ + data_->num_prefix_chars_, (data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1), data_->usecs_); } } // L >= log_mutex (callers must hold the log_mutex). void LogMessage::SendToSinkAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) { SendToSink(); SendToLog(); } // L >= log_mutex (callers must hold the log_mutex). void LogMessage::SaveOrSendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) { if (data_->outvec_ != NULL) { RAW_DCHECK(data_->num_chars_to_log_ > 0 && data_->message_text_[data_->num_chars_to_log_-1] == '\n', ""); // Omit prefix of message and trailing newline when recording in outvec_. const char *start = data_->message_text_ + data_->num_prefix_chars_; int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1; data_->outvec_->push_back(string(start, len)); } else { SendToLog(); } } void LogMessage::WriteToStringAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) { if (data_->message_ != NULL) { RAW_DCHECK(data_->num_chars_to_log_ > 0 && data_->message_text_[data_->num_chars_to_log_-1] == '\n', ""); // Omit prefix of message and trailing newline when writing to message_. const char *start = data_->message_text_ + data_->num_prefix_chars_; int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1; data_->message_->assign(start, len); } SendToLog(); } // L >= log_mutex (callers must hold the log_mutex). void LogMessage::SendToSyslogAndLog() { #ifdef HAVE_SYSLOG_H // Before any calls to syslog(), make a single call to openlog() static bool openlog_already_called = false; if (!openlog_already_called) { openlog(glog_internal_namespace_::ProgramInvocationShortName(), LOG_CONS | LOG_NDELAY | LOG_PID, LOG_USER); openlog_already_called = true; } // This array maps Google severity levels to syslog levels const int SEVERITY_TO_LEVEL[] = { LOG_INFO, LOG_WARNING, LOG_ERR, LOG_EMERG }; syslog(LOG_USER | SEVERITY_TO_LEVEL[static_cast<int>(data_->severity_)], "%.*s", int(data_->num_chars_to_syslog_), data_->message_text_ + data_->num_prefix_chars_); SendToLog(); #else LOG(ERROR) << "No syslog support: message=" << data_->message_text_; #endif } base::Logger* base::GetLogger(LogSeverity severity) { MutexLock l(&log_mutex); return LogDestination::log_destination(severity)->logger_; } void base::SetLogger(LogSeverity severity, base::Logger* logger) { MutexLock l(&log_mutex); LogDestination::log_destination(severity)->logger_ = logger; } // L < log_mutex. Acquires and releases mutex_. int64 LogMessage::num_messages(int severity) { MutexLock l(&log_mutex); return num_messages_[severity]; } // Output the COUNTER value. This is only valid if ostream is a // LogStream. ostream& operator<<(ostream &os, const PRIVATE_Counter&) { #ifdef DISABLE_RTTI LogMessage::LogStream *log = static_cast<LogMessage::LogStream*>(&os); #else LogMessage::LogStream *log = dynamic_cast<LogMessage::LogStream*>(&os); #endif CHECK(log && log == log->self()) << "You must not use COUNTER with non-glog ostream"; os << log->ctr(); return os; } ErrnoLogMessage::ErrnoLogMessage(const char* file, int line, LogSeverity severity, int ctr, void (LogMessage::*send_method)()) : LogMessage(file, line, severity, ctr, send_method) { } ErrnoLogMessage::~ErrnoLogMessage() { // Don't access errno directly because it may have been altered // while streaming the message. stream() << ": " << StrError(preserved_errno()) << " [" << preserved_errno() << "]"; } void FlushLogFiles(LogSeverity min_severity) { LogDestination::FlushLogFiles(min_severity); } void FlushLogFilesUnsafe(LogSeverity min_severity) { LogDestination::FlushLogFilesUnsafe(min_severity); } void SetLogDestination(LogSeverity severity, const char* base_filename) { LogDestination::SetLogDestination(severity, base_filename); } void AddLogDestination(const char* base_filename, const char* dir) { LogDestination::AddLogDestination(base_filename, dir); } void DelLogDestination(const char* base_filename) { LogDestination::DelLogDestination(base_filename); } void ChangeLogDestination(const char* base_filename, bool is_create_new_log, int maxlogsize, int loglevel, int screenlevel) { LogDestination::ChangeLogDestination(base_filename, is_create_new_log, maxlogsize, loglevel, screenlevel); } void SetLogSymlink(LogSeverity severity, const char* symlink_basename) { LogDestination::SetLogSymlink(severity, symlink_basename); } LogSink::~LogSink() { } void LogSink::WaitTillSent() { // noop default } string LogSink::ToString(LogSeverity severity, const char* file, int line, const struct ::tm* tm_time, const char* message, size_t message_len, int32 usecs) { ostringstream stream(string(message, message_len)); stream.fill('0'); stream << LogSeverityNames[severity][0] << setw(4) << 1900+tm_time->tm_year << setw(2) << 1+tm_time->tm_mon << setw(2) << tm_time->tm_mday << ' ' << setw(2) << tm_time->tm_hour << ':' << setw(2) << tm_time->tm_min << ':' << setw(2) << tm_time->tm_sec << '.' << setw(6) << usecs << ' ' << setfill(' ') << setw(5) << GetTID() << setfill('0') << ' ' << file << ':' << line << "] "; stream << string(message, message_len); return stream.str(); } void AddLogSink(LogSink *destination) { LogDestination::AddLogSink(destination); } void RemoveLogSink(LogSink *destination) { LogDestination::RemoveLogSink(destination); } void SetLogFilenameExtension(const char* ext) { LogDestination::SetLogFilenameExtension(ext); } void SetStderrLogging(LogSeverity min_severity) { LogDestination::SetStderrLogging(min_severity); } void SetEmailLogging(LogSeverity min_severity, const char* addresses) { LogDestination::SetEmailLogging(min_severity, addresses); } void LogToStderr() { LogDestination::LogToStderr(); } namespace base { namespace internal { bool GetExitOnDFatal(); bool GetExitOnDFatal() { MutexLock l(&log_mutex); return exit_on_dfatal; } // Determines whether we exit the program for a LOG(DFATAL) message in // debug mode. It does this by skipping the call to Fail/FailQuietly. // This is intended for testing only. // // This can have some effects on LOG(FATAL) as well. Failure messages // are always allocated (rather than sharing a buffer), the crash // reason is not recorded, the "gwq" status message is not updated, // and the stack trace is not recorded. The LOG(FATAL) *will* still // exit the program. Since this function is used only in testing, // these differences are acceptable. void SetExitOnDFatal(bool value); void SetExitOnDFatal(bool value) { MutexLock l(&log_mutex); exit_on_dfatal = value; } } // namespace internal } // namespace base // Shell-escaping as we need to shell out ot /bin/mail. static const char kDontNeedShellEscapeChars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+-_.=/:,@"; static string ShellEscape(const string& src) { string result; if (!src.empty() && // empty string needs quotes src.find_first_not_of(kDontNeedShellEscapeChars) == string::npos) { // only contains chars that don't need quotes; it's fine result.assign(src); } else if (src.find_first_of('\'') == string::npos) { // no single quotes; just wrap it in single quotes result.assign("'"); result.append(src); result.append("'"); } else { // needs double quote escaping result.assign("\""); for (size_t i = 0; i < src.size(); ++i) { switch (src[i]) { case '\\': case '$': case '"': case '`': result.append("\\"); } result.append(src, i, 1); } result.append("\""); } return result; } // use_logging controls whether the logging functions LOG/VLOG are used // to log errors. It should be set to false when the caller holds the // log_mutex. static bool SendEmailInternal(const char*dest, const char *subject, const char*body, bool use_logging) { if (dest && *dest) { if ( use_logging ) { VLOG(1) << "Trying to send TITLE:" << subject << " BODY:" << body << " to " << dest; } else { fprintf(stderr, "Trying to send TITLE: %s BODY: %s to %s\n", subject, body, dest); } string cmd = FLAGS_logmailer + " -s" + ShellEscape(subject) + " " + ShellEscape(dest); VLOG(4) << "Mailing command: " << cmd; FILE* pipe = popen(cmd.c_str(), "w"); if (pipe != NULL) { // Add the body if we have one if (body) fwrite(body, sizeof(char), strlen(body), pipe); bool ok = pclose(pipe) != -1; if ( !ok ) { if ( use_logging ) { LOG(ERROR) << "Problems sending mail to " << dest << ": " << StrError(errno); } else { fprintf(stderr, "Problems sending mail to %s: %s\n", dest, StrError(errno).c_str()); } } return ok; } else { if ( use_logging ) { LOG(ERROR) << "Unable to send mail to " << dest; } else { fprintf(stderr, "Unable to send mail to %s\n", dest); } } } return false; } bool SendEmail(const char*dest, const char *subject, const char*body){ return SendEmailInternal(dest, subject, body, true); } static void GetTempDirectories(vector<string>* list) { list->clear(); #ifdef OS_WINDOWS // On windows we'll try to find a directory in this order: // C:/Documents & Settings/whomever/TEMP (or whatever GetTempPath() is) // C:/TMP/ // C:/TEMP/ // C:/WINDOWS/ or C:/WINNT/ // . char tmp[MAX_PATH]; if (GetTempPathA(MAX_PATH, tmp)) list->push_back(tmp); list->push_back("C:\\tmp\\"); list->push_back("C:\\temp\\"); #else // Directories, in order of preference. If we find a dir that // exists, we stop adding other less-preferred dirs const char * candidates[] = { // Non-null only during unittest/regtest getenv("TEST_TMPDIR"), // Explicitly-supplied temp dirs getenv("TMPDIR"), getenv("TMP"), // If all else fails "/tmp", }; for (size_t i = 0; i < ARRAYSIZE(candidates); i++) { const char *d = candidates[i]; if (!d) continue; // Empty env var // Make sure we don't surprise anyone who's expecting a '/' string dstr = d; if (dstr[dstr.size() - 1] != '/') { dstr += "/"; } list->push_back(dstr); struct stat statbuf; if (!stat(d, &statbuf) && S_ISDIR(statbuf.st_mode)) { // We found a dir that exists - we're done. return; } } #endif } static vector<string>* logging_directories_list; const vector<string>& GetLoggingDirectories() { // Not strictly thread-safe but we're called early in InitGoogle(). if (logging_directories_list == NULL) { logging_directories_list = new vector<string>; if ( !FLAGS_log_dir.empty() ) { // A dir was specified, we should use it logging_directories_list->push_back(FLAGS_log_dir.c_str()); } else { GetTempDirectories(logging_directories_list); #ifdef OS_WINDOWS char tmp[MAX_PATH]; if (GetWindowsDirectoryA(tmp, MAX_PATH)) logging_directories_list->push_back(tmp); logging_directories_list->push_back(".\\"); #else logging_directories_list->push_back("./"); #endif } } return *logging_directories_list; } void TestOnly_ClearLoggingDirectoriesList() { fprintf(stderr, "TestOnly_ClearLoggingDirectoriesList should only be " "called from test code.\n"); delete logging_directories_list; logging_directories_list = NULL; } void GetExistingTempDirectories(vector<string>* list) { GetTempDirectories(list); vector<string>::iterator i_dir = list->begin(); while( i_dir != list->end() ) { // zero arg to access means test for existence; no constant // defined on windows if ( access(i_dir->c_str(), 0) ) { i_dir = list->erase(i_dir); } else { ++i_dir; } } } void TruncateLogFile(const char *path, int64 limit, int64 keep) { #ifdef HAVE_UNISTD_H struct stat statbuf; const int kCopyBlockSize = 8 << 10; char copybuf[kCopyBlockSize]; int64 read_offset, write_offset; // Don't follow symlinks unless they're our own fd symlinks in /proc int flags = O_RDWR; // TODO(hamaji): Support other environments. #ifdef OS_LINUX const char *procfd_prefix = "/proc/self/fd/"; if (strncmp(procfd_prefix, path, strlen(procfd_prefix))) flags |= O_NOFOLLOW; #endif int fd = open(path, flags); if (fd == -1) { if (errno == EFBIG) { // The log file in question has got too big for us to open. The // real fix for this would be to compile logging.cc (or probably // all of base/...) with -D_FILE_OFFSET_BITS=64 but that's // rather scary. // Instead just truncate the file to something we can manage if (truncate(path, 0) == -1) { PLOG(ERROR) << "Unable to truncate " << path; } else { LOG(ERROR) << "Truncated " << path << " due to EFBIG error"; } } else { PLOG(ERROR) << "Unable to open " << path; } return; } if (fstat(fd, &statbuf) == -1) { PLOG(ERROR) << "Unable to fstat()"; goto out_close_fd; } // See if the path refers to a regular file bigger than the // specified limit if (!S_ISREG(statbuf.st_mode)) goto out_close_fd; if (statbuf.st_size <= limit) goto out_close_fd; if (statbuf.st_size <= keep) goto out_close_fd; // This log file is too large - we need to truncate it LOG(INFO) << "Truncating " << path << " to " << keep << " bytes"; // Copy the last "keep" bytes of the file to the beginning of the file read_offset = statbuf.st_size - keep; write_offset = 0; int bytesin, bytesout; while ((bytesin = pread(fd, copybuf, sizeof(copybuf), read_offset)) > 0) { bytesout = pwrite(fd, copybuf, bytesin, write_offset); if (bytesout == -1) { PLOG(ERROR) << "Unable to write to " << path; break; } else if (bytesout != bytesin) { LOG(ERROR) << "Expected to write " << bytesin << ", wrote " << bytesout; } read_offset += bytesin; write_offset += bytesout; } if (bytesin == -1) PLOG(ERROR) << "Unable to read from " << path; // Truncate the remainder of the file. If someone else writes to the // end of the file after our last read() above, we lose their latest // data. Too bad ... if (ftruncate(fd, write_offset) == -1) { PLOG(ERROR) << "Unable to truncate " << path; } out_close_fd: close(fd); #else LOG(ERROR) << "No log truncation support."; #endif } void TruncateStdoutStderr() { #ifdef HAVE_UNISTD_H int64 limit = MaxLogSize() << 20; int64 keep = 1 << 20; TruncateLogFile("/proc/self/fd/1", limit, keep); TruncateLogFile("/proc/self/fd/2", limit, keep); #else LOG(ERROR) << "No log truncation support."; #endif } // Helper functions for string comparisons. #define DEFINE_CHECK_STROP_IMPL(name, func, expected) \ string* Check##func##expected##Impl(const char* s1, const char* s2, \ const char* names) { \ bool equal = s1 == s2 || (s1 && s2 && !func(s1, s2)); \ if (equal == expected) return NULL; \ else { \ ostringstream ss; \ if (!s1) s1 = ""; \ if (!s2) s2 = ""; \ ss << #name " failed: " << names << " (" << s1 << " vs. " << s2 << ")"; \ return new string(ss.str()); \ } \ } DEFINE_CHECK_STROP_IMPL(CHECK_STREQ, strcmp, true) DEFINE_CHECK_STROP_IMPL(CHECK_STRNE, strcmp, false) DEFINE_CHECK_STROP_IMPL(CHECK_STRCASEEQ, strcasecmp, true) DEFINE_CHECK_STROP_IMPL(CHECK_STRCASENE, strcasecmp, false) #undef DEFINE_CHECK_STROP_IMPL int posix_strerror_r(int err, char *buf, size_t len) { // Sanity check input parameters if (buf == NULL || len <= 0) { errno = EINVAL; return -1; } // Reset buf and errno, and try calling whatever version of strerror_r() // is implemented by glibc buf[0] = '\000'; int old_errno = errno; errno = 0; char *rc = reinterpret_cast<char *>(strerror_r(err, buf, len)); // Both versions set errno on failure if (errno) { // Should already be there, but better safe than sorry buf[0] = '\000'; return -1; } errno = old_errno; // POSIX is vague about whether the string will be terminated, although // is indirectly implies that typically ERANGE will be returned, instead // of truncating the string. This is different from the GNU implementation. // We play it safe by always terminating the string explicitly. buf[len-1] = '\000'; // If the function succeeded, we can use its exit code to determine the // semantics implemented by glibc if (!rc) { return 0; } else { // GNU semantics detected if (rc == buf) { return 0; } else { buf[0] = '\000'; #if defined(OS_MACOSX) || defined(OS_FREEBSD) || defined(OS_OPENBSD) if (reinterpret_cast<intptr_t>(rc) < sys_nerr) { // This means an error on MacOSX or FreeBSD. return -1; } #endif strncat(buf, rc, len-1); return 0; } } } string StrError(int err) { char buf[100]; int rc = posix_strerror_r(err, buf, sizeof(buf)); if ((rc < 0) || (buf[0] == '\000')) { snprintf(buf, sizeof(buf), "Error number %d", err); } return buf; } LogMessageFatal::LogMessageFatal(const char* file, int line) : LogMessage(file, line, GLOG_FATAL) {} LogMessageFatal::LogMessageFatal(const char* file, int line, const CheckOpString& result) : LogMessage(file, line, result) {} LogMessageFatal::~LogMessageFatal() { Flush(); LogMessage::Fail(); } namespace base { CheckOpMessageBuilder::CheckOpMessageBuilder(const char *exprtext) : stream_(new ostringstream) { *stream_ << exprtext << " ("; } CheckOpMessageBuilder::~CheckOpMessageBuilder() { delete stream_; } ostream* CheckOpMessageBuilder::ForVar2() { *stream_ << " vs. "; return stream_; } string* CheckOpMessageBuilder::NewString() { *stream_ << ")"; return new string(stream_->str()); } } // namespace base template <> void MakeCheckOpValueString(std::ostream* os, const char& v) { if (v >= 32 && v <= 126) { (*os) << "'" << v << "'"; } else { (*os) << "char value " << (short)v; } } template <> void MakeCheckOpValueString(std::ostream* os, const signed char& v) { if (v >= 32 && v <= 126) { (*os) << "'" << v << "'"; } else { (*os) << "signed char value " << (short)v; } } template <> void MakeCheckOpValueString(std::ostream* os, const unsigned char& v) { if (v >= 32 && v <= 126) { (*os) << "'" << v << "'"; } else { (*os) << "unsigned char value " << (unsigned short)v; } } void InitGoogleLogging(const char* argv0) { glog_internal_namespace_::InitGoogleLoggingUtilities(argv0); } void ShutdownGoogleLogging() { glog_internal_namespace_::ShutdownGoogleLoggingUtilities(); LogDestination::DeleteLogDestinations(); delete logging_directories_list; logging_directories_list = NULL; } void EnableLogCleaner(int overdue_days) { log_cleaner_enabled_ = true; // Setting overdue_days to 0 day should not be allowed! // Since all logs will be deleted immediately, which will cause troubles. if (overdue_days > 0) { log_cleaner_overdue_days_ = overdue_days; } } void DisableLogCleaner() { log_cleaner_enabled_ = false; } _END_GOOGLE_NAMESPACE_
5b5c03fbe7b75a87b7b8189e24f1b96bd9825f7c
d92304badb95993099633c5989f6cd8af57f9b1f
/Rough/Naima.cpp
1508216129fe2d91695c4a2fbcd47d1da48a2201
[]
no_license
tajirhas9/Problem-Solving-and-Programming-Practice
c5e2b77c7ac69982a53d5320cebe874a7adec750
00c298233a9cde21a1cdca1f4a2b6146d0107e73
refs/heads/master
2020-09-25T22:52:00.716014
2019-12-05T13:04:40
2019-12-05T13:04:40
226,103,342
0
0
null
null
null
null
UTF-8
C++
false
false
240
cpp
#include <stdio.h> #include <math.h> int main () { double x1,y1,d,d1; double x2,y2; scanf("%lf %lf %lf %lf",&x1,&y1,&x2,&y2); d1 = (((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1))); d = sqrt(d1); printf("%0.4lf\n",d); return 0; }
a111f95da6e8b1097c6027de2757510dc17e61db
6fdda77279d92ab2562a61635f8de170ae7af689
/nplus1/include/np1/rel/unique.hpp
be058c6fd09a29c1acb23c30984464fd681ee692
[ "Apache-2.0" ]
permissive
ppayne/r17
fe60ccfe5d2de33d0c1acffdaa29fcfa3d365cd1
ba8dba10a74e60e105a5538d66426754d443d1b4
refs/heads/master
2021-01-24T02:06:38.724594
2012-05-18T21:09:53
2012-05-18T21:09:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,723
hpp
// Copyright 2012 Matthew Nourse and n plus 1 computing pty limited unless otherwise noted. // Please see LICENSE file for details. #ifndef NP1_REL_UNIQUE_HPP #define NP1_REL_UNIQUE_HPP namespace np1 { namespace rel { class unique { public: template <typename Input_Stream, typename Output_Stream> void operator()(Input_Stream &input, Output_Stream &output, const std::vector<rel::rlang::token> &tokens) { // Read the headings from stdin. record headings(input.parse_headings()); // Make the map that will hold the groupings. detail::compare_specs specs(headings); validate_specs(specs); detail::record_multihashmap<empty_type> unique_map(specs); // Parse the stream and output only the first instance of each record. headings.write(output); input.parse_records(record_callback<Output_Stream>(output, unique_map)); } private: //TODO: put the empty type in one place. struct empty_type {}; static void validate_specs(const detail::compare_specs &specs) { NP1_ASSERT( !specs.has_double(), "Unique on floating-point columns is not supported because floating-point equality comparison is unreliable."); } // The callback for all records. template <typename Output> struct record_callback { record_callback(Output &output, detail::record_multihashmap<empty_type> &m) : m_output(output), m_map(m) {} bool operator()(const record_ref &r) const { if (!m_map.find(r)) { m_map.insert(r, empty_type()); r.write(m_output); } return true; } Output &m_output; detail::record_multihashmap<empty_type> &m_map; }; }; } // namespaces } #endif
7bbf9d0233d87bc18336a362b8f7701bbd019f7c
8e84ad1b1e00ee8526b682e73a786ea82445df4f
/archive/Demo_File_IO.cpp
7bfad2ce7c003a0b4c2b114221455376aa3bcb97
[ "CC-BY-4.0", "CC-BY-3.0" ]
permissive
dbraunsc/programming-fundamentals
74c28a51319d267d3a001f3bde348711f13c2211
0c8cb6e2f0c8881d23df6794da7b2a1356a947db
refs/heads/master
2020-03-20T22:52:52.406577
2019-06-08T13:52:32
2019-06-08T13:52:32
137,819,400
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
3,308
cpp
//****************************************************** // Filename: Demo_File_IO.cpp // Purpose: File I/O - text file // Comments: The input file contains several integer and // floating-point values. This program will // open the input file, read the values and // total them. When it runs out of input data, // the program will write the total to the // output file. // Author: Ken Busbee; © 2009 Kenneth Leroy Busbee // Date: Apr 6, 2009 // Licensed by: Kenneth Leroy Busbee under a // Creative Commons Attribution License (CC-BY 3.0) // http://creativecommons.org/licenses/by/3.0/ //****************************************************** // Headers and Other Technical Items #include <iostream> #include <fstream> // For file I/O using namespace std; // Function Prototypes void pause(void); // Variables double next_number; double total = 0; // Initialize to zero fstream inData; // device token for the input stream fstream outData; // device token for the output stream // Place the Demo_File_IO_Input.txt file in a folder on your // drive. We suggest that you create a folder named: // Data_Files on the root level of your C: (hard disk) drive // or flash drive as appropriate. // The output file will also be stored at this location. // File Specifications for the // input file and the output file // A file specificatoin includes a // drive, path, filename and file extention char input_filename[] = "C:\\Data_Files\\Demo_File_IO_Input.txt"; char output_filename[] = "C:\\Data_Files\\Demo_File_IO_Output.txt"; //****************************************************** // main //****************************************************** int main(void) { // Open the files inData.open(input_filename, ios::in); //Open input file if (!inData) { cout << "\n\nError opening input data file: " << input_filename << "\n\n"; pause(); exit(EXIT_FAILURE); } outData.open(output_filename, ios::out); //Open output file if (!outData) { cout << "\n\nError opening output data file: " << output_filename << "\n\n"; pause(); exit(EXIT_FAILURE); } // Get data values and total them while (inData >> next_number) { total += next_number; } // Send the total to the output file outData << "Total is: " << total << endl; // Close the files inData.close(); //Close input file outData.close(); //Close output file // Message to the User cout << "\n\nThe program worked correctly."; pause(); return 0; } //****************************************************** // pause //****************************************************** void pause(void) { cout << "\n\n"; system("PAUSE"); cout << "\n\n"; return; } //****************************************************** // End of Program //******************************************************
3cbf3a8af31eaee850a695cb49f1d4b04d7b9796
03cc93dd20f1ebd1e41f61bdeb9c3b87deea1e80
/src/Magnum/MeshTools/sceneconverter.cpp
379d59325d75e8cc48b150c2d76e2c9767efd8f9
[ "MIT" ]
permissive
Tubbz-alt/magnum
497333251f4d4a0e457c7c89942aaae806703ae6
c74e49b3f4ffb97816bc0c96df607714c1dac126
refs/heads/master
2022-11-11T17:03:41.993849
2020-06-24T09:08:40
2020-06-24T09:09:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
22,149
cpp
/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Vladimír Vondruš <[email protected]> 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 <algorithm> #include <chrono> #include <set> #include <Corrade/Containers/Optional.h> #include <Corrade/Utility/Arguments.h> #include <Corrade/Utility/DebugStl.h> #include <Corrade/Utility/Directory.h> #include <Corrade/Utility/FormatStl.h> #include <Corrade/Utility/String.h> #include "Magnum/PixelFormat.h" #include "Magnum/MeshTools/RemoveDuplicates.h" #include "Magnum/Trade/AbstractImporter.h" #include "Magnum/Trade/MeshData.h" #include "Magnum/Trade/MeshObjectData3D.h" #include "Magnum/Trade/AbstractSceneConverter.h" #include "Magnum/Trade/Implementation/converterUtilities.h" namespace Magnum { /** @page magnum-sceneconverter Scene conversion utility @brief Converts scenes of different formats @m_since_latest @m_footernavigation @m_keywords{magnum-sceneconverter sceneconverter} This utility is built if both `WITH_TRADE` and `WITH_SCENECONVERTER` is enabled when building Magnum. To use this utility with CMake, you need to request the `sceneconverter` component of the `Magnum` package and use the `Magnum::sceneconverter` target for example in a custom command: @code{.cmake} find_package(Magnum REQUIRED imageconverter) add_custom_command(OUTPUT ... COMMAND Magnum::sceneconverter ...) @endcode See @ref building, @ref cmake and the @ref Trade namespace for more information. @section magnum-sceneconverter-usage Usage @code{.sh} magnum-sceneconverter [-h|--help] [--importer IMPORTER] [--converter CONVERTER]... [--plugin-dir DIR] [--remove-duplicates] [--remove-duplicates-fuzzy EPSILON] [-i|--importer-options key=val,key2=val2,…] [-c|--converter-options key=val,key2=val2,…]... [--mesh MESH] [--level LEVEL][--info] [-v|--verbose] [--profile] [--] input output @endcode Arguments: - `input` --- input file - `output` --- output file - `-h`, `--help` --- display this help message and exit - `--importer IMPORTER` --- scene importer plugin (default: @ref Trade::AnySceneImporter "AnySceneImporter") - `--converter CONVERTER` --- scene converter plugin(s) - `--plugin-dir DIR` --- override base plugin dir - `--only-attributes "i j …"` --- include only attributes of given IDs in the output - `--remove-duplicates` --- remove duplicate vertices using @ref MeshTools::removeDuplicates(const Trade::MeshData&) after import - `--remove-duplicates-fuzzy EPSILON` --- remove duplicate vertices using @ref MeshTools::removeDuplicatesFuzzy(const Trade::MeshData&, Float, Double) after import - `-i`, `--importer-options key=val,key2=val2,…` --- configuration options to pass to the importer - `-c`, `--converter-options key=val,key2=val2,…` --- configuration options to pass to the converter(s) - `--mesh MESH` --- mesh to import (default: `0`) - `--level LEVEL` --- mesh level to import (default: `0`) - `--info` --- print info about the input file and exit - `-v`, `--verbose` --- verbose output from importer and converter plugins - `--profile` --- measure import and conversion time If `--info` is given, the utility will print information about all meshes and images present in the file. The `-i` / `--importer-options` and `-c` / `--converter-options` arguments accept a comma-separated list of key/value pairs to set in the importer / converter plugin configuration. If the `=` character is omitted, it's equivalent to saying `key=true`; configuration subgroups are delimited with `/`. It's possible to specify the `--converter` option (and correspondingly also `-c` / `--converter-options`) multiple times in order to chain more converters together. All converters in the chain have to support the @ref Trade::SceneConverterFeature::ConvertMesh feature, the last converter either @ref Trade::SceneConverterFeature::ConvertMesh or @ref Trade::SceneConverterFeature::ConvertMeshToFile. If the last converter doesn't support conversion to a file, @ref Trade::AnySceneConverter "AnySceneConverter" is used to save its output; if no `--converter` is specified, @ref Trade::AnySceneConverter "AnySceneConverter" is used. @section magnum-sceneconverter-example Example usage Printing info about all meshes in a glTF file: @code{.sh} magnum-sceneconverter --info scene.gltf @endcode Converting an OBJ file to a PLY, using @ref Trade::StanfordSceneConverter "StanfordSceneConverter" picked by @ref Trade::AnySceneConverter "AnySceneConverter": @code{.sh} magnum-sceneconverter chair.obj chair.ply @endcode @see @ref magnum-imageconverter */ } using namespace Magnum; namespace { struct Duration { explicit Duration(std::chrono::high_resolution_clock::duration& output): _output(output), _t{std::chrono::high_resolution_clock::now()} {} ~Duration() { _output += std::chrono::high_resolution_clock::now() - _t; } private: std::chrono::high_resolution_clock::duration& _output; std::chrono::high_resolution_clock::time_point _t; }; } int main(int argc, char** argv) { Utility::Arguments args; args.addArgument("input").setHelp("input", "input file") .addArgument("output").setHelp("output", "output file") .addOption("importer", "AnySceneImporter").setHelp("importer", "scene importer plugin") .addArrayOption("converter").setHelp("converter", "scene converter plugin(s)") .addOption("plugin-dir").setHelp("plugin-dir", "override base plugin dir", "DIR") .addOption("only-attributes").setHelp("only-attributes", "include only attributes of given IDs in the output", "\"i j …\"") .addBooleanOption("remove-duplicates").setHelp("remove-duplicates", "remove duplicate vertices in the mesh after import") .addOption("remove-duplicates-fuzzy").setHelp("remove-duplicates-fuzzy", "remove duplicate vertices with fuzzy comparison in the mesh after import", "EPSILON") .addOption('i', "importer-options").setHelp("importer-options", "configuration options to pass to the importer", "key=val,key2=val2,…") .addArrayOption('c', "converter-options").setHelp("converter-options", "configuration options to pass to the converter(s)", "key=val,key2=val2,…") .addOption("mesh", "0").setHelp("mesh", "mesh to import") .addOption("level", "0").setHelp("level", "mesh level to import") .addBooleanOption("info").setHelp("info", "print info about the input file and exit") .addBooleanOption('v', "verbose").setHelp("verbose", "verbose output from importer and converter plugins") .addBooleanOption("profile").setHelp("profile", "measure import and conversion time") .setParseErrorCallback([](const Utility::Arguments& args, Utility::Arguments::ParseError error, const std::string& key) { /* If --info is passed, we don't need the output argument */ if(error == Utility::Arguments::ParseError::MissingArgument && key == "output" && args.isSet("info")) return true; /* Handle all other errors as usual */ return false; }) .setGlobalHelp(R"(Converts scenes of different formats. If --info is given, the utility will print information about all meshes and images present in the file. The -i / --importer-options and -c / --converter-options arguments accept a comma-separated list of key/value pairs to set in the importer / converter plugin configuration. If the = character is omitted, it's equivalent to saying key=true; configuration subgroups are delimited with /. It's possible to specify the --converter option (and correspondingly also -c / --converter-options) multiple times in order to chain more converters together. All converters in the chain have to support the ConvertMesh feature, the last converter either ConvertMesh or ConvertMeshToFile. If the last converter doesn't support conversion to a file, AnySceneConverter is used to save its output; if no --converter is specified, AnySceneConverter is used.)") .parse(argc, argv); PluginManager::Manager<Trade::AbstractImporter> importerManager{ args.value("plugin-dir").empty() ? std::string{} : Utility::Directory::join(args.value("plugin-dir"), Trade::AbstractImporter::pluginSearchPaths()[0])}; Containers::Pointer<Trade::AbstractImporter> importer = importerManager.loadAndInstantiate(args.value("importer")); if(!importer) { Debug{} << "Available importer plugins:" << Utility::String::join(importerManager.aliasList(), ", "); return 1; } /* Set options, if passed */ if(args.isSet("verbose")) importer->setFlags(Trade::ImporterFlag::Verbose); Trade::Implementation::setOptions(*importer, args.value("importer-options")); std::chrono::high_resolution_clock::duration importTime; /* Open the file */ { Duration d{importTime}; if(!importer->openFile(args.value("input"))) { Error() << "Cannot open file" << args.value("input"); return 3; } } /* Print file info, if requested */ if(args.isSet("info")) { if(!importer->meshCount() && !importer->image1DCount() && !importer->image2DCount() && !importer->image2DCount()) { Debug{} << "No meshes or images found."; return 0; } struct MeshAttributeInfo { std::size_t offset; UnsignedInt stride, arraySize; Trade::MeshAttribute name; std::string customName; VertexFormat format; }; struct MeshInfo { UnsignedInt mesh, level; UnsignedInt references; MeshPrimitive primitive; UnsignedInt indexCount, vertexCount; MeshIndexType indexType; Containers::Array<MeshAttributeInfo> attributes; std::size_t indexDataSize, vertexDataSize; std::string name; }; /* Parse everything first to avoid errors interleaved with output */ /* Scene properties. Currently just counting how much is each mesh shared. */ Containers::Array<UnsignedInt> meshReferenceCount{importer->meshCount()}; for(UnsignedInt i = 0; i != importer->object3DCount(); ++i) { Containers::Pointer<Trade::ObjectData3D> object = importer->object3D(i); if(object && object->instanceType() == Trade::ObjectInstanceType3D::Mesh && std::size_t(object->instance()) < meshReferenceCount.size()) ++meshReferenceCount[object->instance()]; } /* Mesh properties */ bool error = false; Containers::Array<MeshInfo> meshInfos; for(UnsignedInt i = 0; i != importer->meshCount(); ++i) { for(UnsignedInt j = 0; j != importer->meshLevelCount(i); ++j) { Containers::Optional<Trade::MeshData> mesh; { Duration d{importTime}; if(!(mesh = importer->mesh(i, j))) { error = true; continue; } } MeshInfo info{}; info.mesh = i; info.level = j; info.primitive = mesh->primitive(); info.vertexCount = mesh->vertexCount(); info.vertexDataSize = mesh->vertexData().size(); if(!j) { info.name = importer->meshName(i); info.references = meshReferenceCount[i]; } if(mesh->isIndexed()) { info.indexCount = mesh->indexCount(); info.indexType = mesh->indexType(); info.indexDataSize = mesh->indexData().size(); } for(UnsignedInt k = 0; k != mesh->attributeCount(); ++k) { const Trade::MeshAttribute name = mesh->attributeName(k); arrayAppend(info.attributes, Containers::InPlaceInit, mesh->attributeOffset(k), mesh->attributeStride(k), mesh->attributeArraySize(k), name, Trade::isMeshAttributeCustom(name) ? importer->meshAttributeName(name) : "", mesh->attributeFormat(k)); } std::sort(info.attributes.begin(), info.attributes.end(), [](const MeshAttributeInfo& a, const MeshAttributeInfo& b) { return a.offset < b.offset; }); arrayAppend(meshInfos, std::move(info)); } } Containers::Array<Trade::Implementation::ImageInfo> imageInfos = Trade::Implementation::imageInfo(*importer, error); for(const MeshInfo& info: meshInfos) { Debug d; if(info.level == 0) { d << "Mesh" << info.mesh; /* Print reference count only if there actually is a scene, otherwise this information is useless */ if(importer->object3DCount()) d << Utility::formatString("(referenced by {} objects)", info.references); d << Debug::nospace << ":"; if(!info.name.empty()) d << info.name; d << Debug::newline; } d << " Level" << info.level << Debug::nospace << ":" << info.primitive << Debug::nospace << "," << info.vertexCount << "vertices (" << Debug::nospace << Utility::formatString("{:.1f}", info.vertexDataSize/1024.0f) << "kB)"; if(info.indexType != MeshIndexType{}) { d << Debug::newline << " " << info.indexCount << "indices @" << info.indexType << "(" << Debug::nospace << Utility::formatString("{:.1f}", info.indexDataSize/1024.0f) << "kB)"; } for(const MeshAttributeInfo& attribute: info.attributes) { d << Debug::newline << " Offset" << attribute.offset << Debug::nospace << ":" << attribute.name; if(Trade::isMeshAttributeCustom(attribute.name)) { d << "(" << Debug::nospace << attribute.customName << Debug::nospace << ")"; } d << "@" << attribute.format << Debug::nospace << ", stride" << attribute.stride; } } for(const Trade::Implementation::ImageInfo& info: imageInfos) { Debug d; if(info.level == 0) { d << "Image" << info.image << Debug::nospace << ":"; if(!info.name.empty()) d << info.name; d << Debug::newline; } d << " Level" << info.level << Debug::nospace << ":"; if(info.compressed) d << info.compressedFormat; else d << info.format; if(info.size.z()) d << info.size; else if(info.size.y()) d << info.size.xy(); else d << Math::Vector<1, Int>(info.size.x()); } if(args.isSet("profile")) { Debug{} << "Import took" << UnsignedInt(std::chrono::duration_cast<std::chrono::milliseconds>(importTime).count())/1.0e3f << "seconds"; } return error ? 1 : 0; } Containers::Optional<Trade::MeshData> mesh; { Duration d{importTime}; if(!importer->meshCount() || !(mesh = importer->mesh(args.value<UnsignedInt>("mesh"), args.value<UnsignedInt>("level")))) { Error{} << "Cannot import the mesh"; return 4; } } std::chrono::high_resolution_clock::duration conversionTime; /* Filter attributes, if requested */ if(!args.value("only-attributes").empty()) { std::set<UnsignedInt> only; for(const std::string& i: Utility::String::split(args.value("only-attributes"), ' ')) only.insert(std::stoi(i)); Containers::Array<Trade::MeshAttributeData> attributes; for(UnsignedInt i = 0; i != mesh->attributeCount(); ++i) { if(only.find(i) != only.end()) arrayAppend(attributes, mesh->attributeData(i)); } const Trade::MeshIndexData indices{mesh->indices()}; const UnsignedInt vertexCount = mesh->vertexCount(); mesh = Trade::MeshData{mesh->primitive(), mesh->releaseIndexData(), indices, mesh->releaseVertexData(), std::move(attributes), vertexCount}; } /* Remove duplicates, if requested */ if(args.isSet("remove-duplicates")) { const UnsignedInt beforeVertexCount = mesh->vertexCount(); { Duration d{conversionTime}; mesh = MeshTools::removeDuplicates(*std::move(mesh)); } if(args.isSet("verbose")) Debug{} << "Duplicate removal:" << beforeVertexCount << "->" << mesh->vertexCount() << "vertices"; } /* Remove duplicates with fuzzy comparison, if requested */ /** @todo accept two values for float and double fuzzy comparison */ if(!args.value("remove-duplicates-fuzzy").empty()) { const UnsignedInt beforeVertexCount = mesh->vertexCount(); { Duration d{conversionTime}; mesh = MeshTools::removeDuplicatesFuzzy(*std::move(mesh), args.value<Float>("remove-duplicates-fuzzy")); } if(args.isSet("verbose")) Debug{} << "Fuzzy duplicate removal:" << beforeVertexCount << "->" << mesh->vertexCount() << "vertices"; } /* Load converter plugin */ PluginManager::Manager<Trade::AbstractSceneConverter> converterManager{ args.value("plugin-dir").empty() ? std::string{} : Utility::Directory::join(args.value("plugin-dir"), Trade::AbstractSceneConverter::pluginSearchPaths()[0])}; /* Assume there's always one passed --converter option less, and the last is implicitly AnySceneConverter. All converters except the last one are expected to support ConvertMesh and the mesh is "piped" from one to the other. If the last converter supports ConvertMeshToFile instead of ConvertMesh, it's used instead of the last implicit AnySceneConverter. */ for(std::size_t i = 0, converterCount = args.arrayValueCount("converter"); i <= converterCount; ++i) { const std::string converterName = i == converterCount ? "AnySceneConverter" : args.arrayValue("converter", i); Containers::Pointer<Trade::AbstractSceneConverter> converter = converterManager.loadAndInstantiate(converterName); if(!converter) { Debug{} << "Available converter plugins:" << Utility::String::join(converterManager.aliasList(), ", "); return 2; } /* Set options, if passed */ if(args.isSet("verbose")) converter->setFlags(Trade::SceneConverterFlag::Verbose); if(i < args.arrayValueCount("converter-options")) Trade::Implementation::setOptions(*converter, args.arrayValue("converter-options", i)); /* This is the last --converter (or the implicit AnySceneConverter at the end), output to a file and exit the loop */ if(i + 1 >= converterCount && (converter->features() & Trade::SceneConverterFeature::ConvertMeshToFile)) { if(converterCount > 1 && args.isSet("verbose")) Debug{} << "Saving output with" << converterName << Debug::nospace << "..."; Duration d{conversionTime}; if(!converter->convertToFile(args.value("output"), *mesh)) { Error{} << "Cannot save file" << args.value("output"); return 5; } break; /* This is not the last converter, expect that it's capable of ConvertMesh */ } else { CORRADE_INTERNAL_ASSERT(i < converterCount); if(converterCount > 1 && args.isSet("verbose")) Debug{} << "Processing (" << Debug::nospace << (i+1) << Debug::nospace << "/" << Debug::nospace << converterCount << Debug::nospace << ") with" << converterName << Debug::nospace << "..."; if(!(converter->features() & Trade::SceneConverterFeature::ConvertMesh)) { Error{} << converterName << "doesn't support mesh conversion, only" << converter->features(); return 6; } Duration d{conversionTime}; if(!(mesh = converter->convert(*mesh))) { Error{} << converterName << "cannot convert the mesh"; return 7; } } } if(args.isSet("profile")) { Debug{} << "Import took" << UnsignedInt(std::chrono::duration_cast<std::chrono::milliseconds>(importTime).count())/1.0e3f << "seconds, conversion" << UnsignedInt(std::chrono::duration_cast<std::chrono::milliseconds>(conversionTime).count())/1.0e3f << "seconds"; } }
fc9eb38dfe83a2dcad2151014bc92d35869c0201
e5a75731bf787d83db939eba8b13f859fd7c8cd4
/cppDay00/ex01/PhoneBook.cpp
0b66e0477dc3feef4cf9ada052882e930a0e6aaf
[]
no_license
ekiriche/cppPool
cf74f15534f82e86ad13e4287910e83f0a14535b
6ed66d1be410320aaedf420f04f722624fdbecad
refs/heads/master
2020-07-25T20:22:42.742159
2019-11-07T08:23:33
2019-11-07T08:23:33
208,412,631
0
0
null
null
null
null
UTF-8
C++
false
false
299
cpp
// // Created by Evgeniy KIRICHENKO on 2019-06-24. // #include "PhoneBook.hpp" PhoneBook::PhoneBook() { contactsLength = 0; return ; } PhoneBook::~PhoneBook() { return ; } void PhoneBook::addContact(Contact *contact) { contacts[contactsLength] = *contact; contactsLength++; }
559936d3866ba1ad3e14b06f226e2e54f7e1b562
f620b7174435d91cd8785062122a89b1882d1e49
/liczby/main.cpp
d0a1515012ff1f9ad2a732ede6904b0d1e91bc79
[]
no_license
Michal2002/gitrepo1a
f853bc3e0b9602355f3296237c3c63849aa2ddc0
c279cb415fb7fc0f10207d8e37f34d60c0c03cf1
refs/heads/master
2020-03-28T12:29:55.136878
2020-03-04T08:29:03
2020-03-04T08:29:03
148,304,208
0
0
null
null
null
null
UTF-8
C++
false
false
851
cpp
#include <iostream> using namespace std; int main() { float a, b, c; cout<<"podaj pierwsza:"; cin>>a; cout<<"podaj druga:"; cin>>b; cout<<"podaj trzecia:"; cin>>c; if(a<b);{ if(b<c);{ cout<<'najmniejsza jest',a ;} if(c<a);{ cout<<'najmniejsza jest',c ;}} if(b<a);{ if(a<c);{ cout<<'najmniejsza jest',b ;} if(c<b);{ cout<<'najmniejsza jest',c ;}} if(a==b);{ if(c<a);{ cout<<'najmniejsza jest',c ;} if(c>a);{ cout<<'najmniejsza jest',a ;} if(a==c);{ cout<<'najmniejsza jest',a ,"=", b , "=" , c;}} if(a==c);{ if(a<b);{ cout<<'najmniejsza jest',a ,"=", c ;} if(a>b);{ cout<<'najmniejsza jest',a , "=" , c;}} return 0; }
07c2debf64dccd4d5ba1cf7d5a40752c9f389870
0c58ff601d765bd4b6ca64f00bdf864a3d26b080
/src/math/FixedPoint.h
f1fd44d50db4c04acc7426e345a2e1841dad86e3
[ "MIT" ]
permissive
leetnz/Bittleet
0174f98bc96be15943a4da35a42cb9193c7a337a
08e38e78cbc9ace83e494b53a7dba0979d2107e1
refs/heads/main
2023-09-04T19:42:42.297679
2021-11-12T04:25:40
2021-11-12T04:25:40
405,613,253
1
0
NOASSERTION
2021-11-12T04:25:42
2021-09-12T10:39:14
C++
UTF-8
C++
false
false
443
h
#ifndef _BITTLEET_FIXEDPOINT_H_ #define _BITTLEET_FIXEDPOINT_H_ #include <stdint.h> template <typename T, int BITS> class FixedPoint { public: FixedPoint() = default; FixedPoint(float value) : _value(value * _denominator) {} float toF32() { return ((float)_value)/_denominator;} private: T _value = 0; static constexpr float _denominator = (float)(1 << BITS); }; #endif // _BITTLEET_FIXEDPOINT_H_
744f879ccfddf3c56ae14b1147071579066a59f4
50aa142ec35e6764bf012d9dc67c4fd70d570b5b
/Nodo.cpp
c5a05c648bf4753c9d8a310406926cacf8573ce8
[]
no_license
DavidEdgardon/ArbolB_ED2
c4e32da93cd7a45949ca0bef0be6ca65849536db
de6416d7730a1d073734a809d9ec115f66bf050f
refs/heads/master
2020-04-30T20:49:24.066915
2019-03-22T05:54:50
2019-03-22T05:54:50
177,079,046
0
0
null
null
null
null
UTF-8
C++
false
false
792
cpp
// // Created by ASUS on 3/14/2019. // #include "Nodo.h" Nodo::Nodo() : mes(-1), siguiente(0) { } Nodo::Nodo(int d, int m) : mes{m}, dia(d), siguiente(0) { } /* void Nodo::setValor(int v) { this->valor=v; } void Nodo::setSiguiente(Nodo *sig) { this->siguiente=sig; } int Nodo::getValor() { return this->valor; } Nodo * Nodo::getSiguiente() { return this->siguiente; }*/ bool ListaEnlazadaSimple::esVacia() { return primero==0; } void ListaEnlazadaSimple::agregar(int d ,int m) { Nodo *nuevo=new Nodo; // nuevo->setValor(valor); if(esVacia()){ primero=nuevo; ultimo=nuevo; }else{ // ultimo->setSiguiente(nuevo); ultimo=nuevo; } }
c190a86630fe30c01bcc4c39541f2852a2c8656d
565a1a95a343a01e43aa3026a46da677cb05b4a1
/2016_fall_semester/windows_programing/Ch09_1122/KYGImageToolDoc.h
7bbf8f0d22fbdc771ca02250493ca0f8a9aab18a
[]
no_license
younggyu0906/koreatech_class_projects
af31ed35eaa14a1a4977a39cf00603265acaa049
b97dedcb0bf4a459bbe0b6bb9cf9828552951921
refs/heads/master
2021-07-11T07:13:08.184777
2019-02-26T09:14:55
2019-02-26T09:14:55
102,804,792
0
0
null
null
null
null
UHC
C++
false
false
1,300
h
// KYGImageToolDoc.h : CKYGImageToolDoc 클래스의 인터페이스 // #pragma once #include "dib.h" class CKYGImageToolDoc : public CDocument { protected: // serialization에서만 만들어집니다. CKYGImageToolDoc(); DECLARE_DYNCREATE(CKYGImageToolDoc) // 특성입니다. public: // 작업입니다. public: // 재정의입니다. public: virtual BOOL OnNewDocument(); virtual void Serialize(CArchive& ar); // 구현입니다. public: virtual ~CKYGImageToolDoc(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // 생성된 메시지 맵 함수 protected: DECLARE_MESSAGE_MAP() public: // 이미지 객체 CDib m_Dib; // 파일 불러오기 & 저장하기 virtual BOOL OnOpenDocument(LPCTSTR lpszPathName); virtual BOOL OnSaveDocument(LPCTSTR lpszPathName); public: afx_msg void OnWindowDuplicate(); afx_msg void OnEditCopy(); afx_msg void OnImageBrightness(); afx_msg void OnImageBrightnessContrast(); afx_msg void OnHistogram(); afx_msg void OnHistoEqualization(); afx_msg void OnArithmeticLogical(); afx_msg void OnFilterMean(); afx_msg void OnFilterWeightedMean(); afx_msg void OnGaussian(); afx_msg void OnAddNoise(); afx_msg void OnImageTranslation(); afx_msg void OnImageInverse(); };
8b653331790e1a6301446b955ee1e9758d21179c
18160bde2a220ede76608d4ebdcdddd212f3199e
/caravoidance.cpp
05ef65bd7f32c0ef519dbd16f6bb57c506a1b231
[]
no_license
bluejazzCHN/STMduino-smartCar
d12db68f92e9e82a275343fd39248d0bb9f312be
37b131eb9c5dc29826efd7dc7b2730a13e55f528
refs/heads/master
2023-07-30T14:55:59.969427
2020-03-11T05:57:58
2020-03-11T05:57:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,782
cpp
/* * @文件: \caravoidance.cpp * @作者:零知实验室 * -^^- 零知开源,让电子制作变得更简单! -^^- * @时间: 2019-12-05 15:46:50 * @说明: */ #include "caravoidance.h" CarAvoidance::CarAvoidance() { //超声波 pinMode(UltraEchoPin, INPUT); pinMode(UltraTrigPin, OUTPUT); //超声波舵机 UltraServo.attach(ServoPWM1); UltraServo.write(ServoDefaultPos); //正中间 } int CarAvoidance::getDistance() { digitalWrite(UltraTrigPin, LOW); delayMicroseconds(2); digitalWrite(UltraTrigPin, HIGH); delayMicroseconds(10); digitalWrite(UltraTrigPin, LOW); // int distance = pulseIn(UltraEchoPin, HIGH); int previousMicros = 0; int timeout = 40000; previousMicros = micros(); while(!digitalRead(UltraEchoPin) && (micros() - previousMicros) <= timeout); // wait for the echo pin HIGH or timeout previousMicros = micros(); while(digitalRead(UltraEchoPin) && (micros() - previousMicros) <= timeout); // wait for the echo pin LOW or timeout int durat = micros() - previousMicros; // duration int distance = durat / 58.0; return distance; } void CarAvoidance::servoRun(int from, int to, int time) { if (from < to) { for (int i = from; i <= to; i++) { UltraServo.write(i); delay(time); } }else if (from > to) { for (int i = from; i >= to; i--) { UltraServo.write(i); delay(time); } } else{ UltraServo.write(from); } } void CarAvoidance::getIRAvoidData(bool *isLeftAvoid, bool *isRightAvoid) { if(digitalRead(ServoPWM3) == 0){ *isLeftAvoid = true; }else{ *isLeftAvoid = false; } if(digitalRead(ServoPWM4) == 0){ *isRightAvoid = true; }else{ *isRightAvoid = false; } } CarAvoidance::~CarAvoidance() { }
c80f07639ab075123528d6ce4f3007862c03b196
7581db0625dfe7ca8b7e829c7f95dfc2503e5e00
/fboss/agent/MacTableUtils.cpp
aa6fd6205d6b64d29fae89ed294729b966de9cef
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
midopooler/fboss
53e8e33693116356b1ac35bc3ff0d87d3e378dd3
c8d08dd4255e97e5977f53712e7c91a7d045a0cb
refs/heads/master
2022-09-22T13:54:44.231859
2020-05-31T18:56:46
2020-05-31T18:58:34
268,364,523
0
0
NOASSERTION
2020-05-31T21:08:39
2020-05-31T21:08:39
null
UTF-8
C++
false
false
3,331
cpp
/* * Copyright (c) 2004-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. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "fboss/agent/MacTableUtils.h" namespace { using facebook::fboss::MacEntry; using facebook::fboss::SwitchState; using facebook::fboss::VlanID; using facebook::fboss::cfg::AclLookupClass; std::shared_ptr<SwitchState> modifyClassIDForEntry( const std::shared_ptr<SwitchState>& state, VlanID vlanID, const std::shared_ptr<MacEntry>& macEntry, std::optional<AclLookupClass> classID = std::nullopt) { auto classIDStr = classID.has_value() ? folly::to<std::string>(static_cast<int>(classID.value())) : "None"; auto mac = macEntry->getMac(); auto portDescr = macEntry->getPort(); auto vlan = state->getVlans()->getVlanIf(vlanID).get(); std::shared_ptr<SwitchState> newState{state}; auto* macTable = vlan->getMacTable().get(); auto node = macTable->getNodeIf(mac); if (node) { // Mac Entry is present, associate/disassociate classID macTable = macTable->modify(&vlan, &newState); macTable->updateEntry(mac, portDescr, classID); } else { // if MAC is not present, if classID is valid, create an entry and // associate it, if the classID is null, do nothing. if (classID.has_value()) { auto newMacEntry = std::make_shared<MacEntry>(mac, portDescr, classID); macTable = macTable->modify(&vlan, &newState); macTable->addEntry(newMacEntry); } } return newState; } } // namespace namespace facebook::fboss { std::shared_ptr<SwitchState> MacTableUtils::updateMacTable( const std::shared_ptr<SwitchState>& state, L2Entry l2Entry, L2EntryUpdateType l2EntryUpdateType) { auto vlanID = l2Entry.getVlanID(); auto mac = l2Entry.getMac(); auto portDescr = l2Entry.getPort(); auto vlan = state->getVlans()->getVlanIf(vlanID).get(); std::shared_ptr<SwitchState> newState{state}; auto* macTable = vlan->getMacTable().get(); auto node = macTable->getNodeIf(mac); // Delete if the entry to delete exists, otherwise do nothing. if (node && l2EntryUpdateType == L2EntryUpdateType::L2_ENTRY_UPDATE_TYPE_DELETE) { macTable = macTable->modify(&vlan, &newState); macTable->removeEntry(mac); } // Add if the entry to add does not exist, otherwise do nothing. if (!node && l2EntryUpdateType == L2EntryUpdateType::L2_ENTRY_UPDATE_TYPE_ADD) { auto macEntry = std::make_shared<MacEntry>(mac, portDescr); macTable = macTable->modify(&vlan, &newState); macTable->addEntry(macEntry); } return newState; } std::shared_ptr<SwitchState> MacTableUtils::updateOrAddEntryWithClassID( const std::shared_ptr<SwitchState>& state, VlanID vlanID, const std::shared_ptr<MacEntry>& macEntry, cfg::AclLookupClass classID) { return modifyClassIDForEntry(state, vlanID, macEntry, classID); } std::shared_ptr<SwitchState> MacTableUtils::removeClassIDForEntry( const std::shared_ptr<SwitchState>& state, VlanID vlanID, const std::shared_ptr<MacEntry>& macEntry) { return modifyClassIDForEntry(state, vlanID, macEntry); } } // namespace facebook::fboss
f08b318c331edc57ba4177793716aa5365be1fc5
0934782cc900ef32616d3c5204bca05b2aa34032
/SDK/RC_ReloadOnDodgeRollModInst_parameters.hpp
3d5bd6471346054c2297844aa6e515d783943645
[]
no_license
igromanru/RogueCompany-SDK-9-24-2020
da959376e5464e505486cf0df01fff71dde212cf
fcab8fd45cf256c6f521d94f295e2a76701c411d
refs/heads/master
2022-12-18T05:30:30.039119
2020-09-25T01:12:25
2020-09-25T01:12:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,131
hpp
#pragma once // RogueCompany (4.24) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function ReloadOnDodgeRollModInst.ReloadOnDodgeRollModInst_C.MagDropForDodgeReload struct UReloadOnDodgeRollModInst_C_MagDropForDodgeReload_Params { class UKSWeaponComponent** Master_Weapon_Ref; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData) }; // Function ReloadOnDodgeRollModInst.ReloadOnDodgeRollModInst_C.StopAnimationFromEvent struct UReloadOnDodgeRollModInst_C_StopAnimationFromEvent_Params { struct FName* AnimEventName; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class UKSCharacterAnimInst** CharAnimInstance; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function ReloadOnDodgeRollModInst.ReloadOnDodgeRollModInst_C.ReactsToAnimationEvent struct UReloadOnDodgeRollModInst_C_ReactsToAnimationEvent_Params { struct FName* AnimEventName; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) int Priority; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function ReloadOnDodgeRollModInst.ReloadOnDodgeRollModInst_C.OnDodgeRoll struct UReloadOnDodgeRollModInst_C_OnDodgeRoll_Params { float* RollDuration; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) }; // Function ReloadOnDodgeRollModInst.ReloadOnDodgeRollModInst_C.RemotePlayerAudio struct UReloadOnDodgeRollModInst_C_RemotePlayerAudio_Params { }; // Function ReloadOnDodgeRollModInst.ReloadOnDodgeRollModInst_C.Dodge Reload Mod Notified struct UReloadOnDodgeRollModInst_C_Dodge_Reload_Mod_Notified_Params { }; // Function ReloadOnDodgeRollModInst.ReloadOnDodgeRollModInst_C.ExecuteUbergraph_ReloadOnDodgeRollModInst struct UReloadOnDodgeRollModInst_C_ExecuteUbergraph_ReloadOnDodgeRollModInst_Params { int* EntryPoint; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
5e12365c892338ab91e0c929e19fd6f9dcad7fd1
d0cc94c5c10ee77f41b190a605d3f120679e7c24
/inc/Task.hpp
39222de8b552f237f1d0b5946a5b736692d575b7
[]
no_license
TinfoilPancakes/DD
5874f812357227c17cfc17ef0f14a2b1707e3990
8d7817d91dfce516d34ae0d101b039acc4c203b2
refs/heads/master
2021-01-06T04:05:48.842430
2017-08-07T00:46:25
2017-08-07T00:46:25
99,522,008
0
0
null
null
null
null
UTF-8
C++
false
false
2,301
hpp
/* ************************************************************************** */ /* */ /* __ */ /* Task.hpp <(o )___ */ /* ( ._> / - Weh. */ /* By: prp <[email protected]> --`---'------------- */ /* 54 69 6E 66 6F 69 6C */ /* Created: 2017/08/05 09:50:04 by prp 2E 54 65 63 68 */ /* Updated: 2017/08/05 20:09:20 by prp 50 2E 52 2E 50 */ /* */ /* ************************************************************************** */ #ifndef DD_TASK_HPP #define DD_TASK_HPP #include <atomic> #include <functional> namespace DD { class Task { public: enum Result { Finished, FinishedNoDestroy, Continue, ContinueReInit }; private: using TaskInit = std::function<void()>; using TaskRun = std::function<Result()>; using TaskDestroy = std::function<void()>; const TaskInit to_init; const TaskRun to_run; const TaskDestroy to_destroy; size_t iter_count; bool run_init; public: Task(const TaskInit to_init, const TaskRun to_run, const TaskDestroy to_destroy); inline Result run() const { return this->to_run != nullptr ? this->to_run() : Result::Finished; } inline void destroy() const { if (this->to_destroy != nullptr) this->to_destroy(); } inline void init() const { if (this->to_init != nullptr) this->to_init(); } inline const TaskRun& get_run() const { return this->to_run; } inline const TaskInit& get_init() const { return this->to_init; } inline const TaskDestroy& get_destroy() const { return this->to_destroy; } inline bool get_should_init() const { return this->run_init; } inline void set_should_init(bool should_init) { this->run_init = should_init; } inline void increment_iter_count() { this->iter_count++; } inline size_t get_iter_count() const { return this->iter_count; } inline void clear_iter_count() { this->iter_count = 0; } }; } #endif
5186ac3c84d66a0b9afb7dc8001612056bd46f7d
012af030d3de64ae7f2ce257be592a9c7114c4d5
/core.h
285c65bd8f55eb0d6bfca3b7a0983bd2392243f6
[]
no_license
jordelucas/ARQ-Simulador-Multicore
6633296591008f84b11ded770ab6271e2ec2cee2
dc8f41a575849543fa32208ec903e61912a70639
refs/heads/master
2020-06-03T02:04:16.764512
2019-06-21T13:07:10
2019-06-21T13:07:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
444
h
#ifndef CORE_H #define CORE_H #include "cache.h" #include "dado.h" class Core { private: Cache cache; Cache * nivelInferior; public: Core(); Core(Cache * nivelInferior); bool leitura(int endereco); bool escrita(int endereco, int novoValor); void setCache(Dado * dado); void setL1(Dado * dado); void setL2(Dado * dado); void listarDados(); }; #endif
117d6798dc542aa9a8718ac754cda4ec5d3596c6
d1dc30ab429eec50de00f6d41c81fa5a4c7301e0
/tcpserveur.cpp
2429a6834194ca417643b6754bb5a2a593476394
[]
no_license
lehouxouelleta/cll12-GestionnaireAgile-Serveur
4a01d81cf15d5a29857ca402e42cf8d32304bd50
bf376a0be056c8b7e493dc58429543076bf4fc19
refs/heads/master
2020-06-01T00:41:18.232169
2012-05-16T18:30:14
2012-05-16T18:30:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,839
cpp
#include "tcpserveur.h" TCPServeur::TCPServeur(QObject *parent) : QTcpServer(parent) { } void TCPServeur::incomingConnection(int socketDescriptor) { ThreadServeur *thServeur =new ThreadServeur(socketDescriptor); connect(thServeur,SIGNAL(siRecoieConnection(QString)),this,SLOT(slRecoieConnection(QString))); connect(thServeur,SIGNAL(siTermineConnection(QString)),this,SLOT(slTermineConnection(QString))); connect(this,SIGNAL(siNouvelleTache(QStringList)),thServeur,SLOT(slNouvelleTache(QStringList))); connect(thServeur,SIGNAL(siTacheTerminee(QString,QString)),this,SLOT(slTacheTerminee(QString,QString))); connect(this,SIGNAL(siDeconnection()),thServeur,SLOT(slDeconnection())); connect(thServeur,SIGNAL(siFermeture()),this,SLOT(slFermeture())); connect(thServeur,SIGNAL(siPrendreTache(QString,QString)),this,SLOT(slPrendreTache(QString,QString))); connect(thServeur,SIGNAL(siAbandon(QString,QString)),this,SLOT(slAbandon(QString,QString))); connect(this,SIGNAL(siRepondu(QString)),thServeur,SLOT(slRepondu(QString))); thServeur->start(); } void TCPServeur::slRecoieConnection(QString ba) { emit(siRecoieNom(ba)); } void TCPServeur::slTermineConnection(QString ba) { emit(siFin(ba)); } void TCPServeur::slEnvoieTache(QStringList qsl) { emit(siNouvelleTache(qsl)); } void TCPServeur::slTacheTerminee(QString str,QString nom) { emit(siEnleverTache(str,nom)); } void TCPServeur::slDeconnecter() { emit(siDeconnection()); } void TCPServeur::slFermeture() { this->close(); emit(siFermer()); } void TCPServeur::slPrendreTache(QString tache, QString nom) { emit(siTachePrise(tache,nom)); } void TCPServeur::slAbandon(QString tache, QString nom) { emit(siAbandonnee(tache,nom)); } void TCPServeur::slReponse(QString str) { emit(siRepondu(str)); }
6a3c50234cb791093c0332221aade2f6259605bd
bcb99ebc90b2d3edff1ed3da15bac7c34c36c483
/following/src/myPoint.cpp
86f984ce3d31f97b13df4007c5a59b18b8ada6f0
[]
no_license
cuili259291/rosintrodution
843f3e214c4cb011f521bf8f1566ac45ef3c72ac
0a50f47c37290621ec565ec43353b27a561e521b
refs/heads/master
2020-05-19T12:09:45.607015
2017-11-27T11:18:22
2017-11-27T11:18:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
750
cpp
#include "myPoint.h" MyPoint::MyPoint(double xPos, double yPos) { x = xPos; y = yPos; } MyPoint::~MyPoint() { } double MyPoint::getAngle(MyPoint* target) { return atan2((target->y - y),(target->x - x)); } double MyPoint::getDistance(MyPoint* target) { return sqrt((pow(target->y - y,2.0)) + (pow(target->x - x,2.0))); } MyPoint MyPoint::operator+(const MyPoint &other) const { MyPoint result = *(new MyPoint(x+other.x, y+other.y)); return result; } MyPoint MyPoint::operator-(const MyPoint &other) const { MyPoint result = *(new MyPoint(x-other.x, y-other.y)); return result; } MyPoint MyPoint::times(double r){ return *(new MyPoint(r*x, r*y)); } double MyPoint::getAbs() { return sqrt((pow(y,2.0)) + (pow(x,2.0))); }
813713164191434f1894c1719eb633b4bd3c9512
4114a7a685fab1857534da0885320c6724ba35d7
/libraries/led/led.h
6013075d11e1147f743244bbb825f2f53f71026d
[]
no_license
mz1951/Arduino
387a3859bbd00291f13af1e96871e845d4ae1a32
57d3911d4b0152e562a394bb6f727abdf66528f1
refs/heads/master
2022-03-31T08:22:12.324066
2015-12-27T15:38:44
2015-12-27T15:38:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
257
h
#ifndef LED_H #define LED_H #include "Arduino.h" class Led { public: Led(int pinNr); ~Led(); void init(); void setOn(); void setOff(); void toggle(); boolean isOn(); private: int pin; boolean ledIsOn; }; #endif // LED_H
784b55abeb92f326c35f4b9f22c5e80e31484636
a69995a1e8894db6fc3217a4b47929b923b9f5d0
/stable/0.4/xmcml/xmcmlLauncher/xmcmlLauncher/launcher_omp.cpp
49140d7eda59f8efaa8de5e8734e87b2f2c4f79c
[]
no_license
avgorshk/xmcml
f81d3a5849d350b76bbac17ef26ec52b4488f070
3b0f981bb2e8a7472a29dbd00f1906c53fed9926
refs/heads/master
2021-01-17T10:09:00.805481
2016-04-29T16:28:01
2016-04-29T16:28:01
32,270,361
1
0
null
null
null
null
UTF-8
C++
false
false
1,999
cpp
#include "launcher_omp.h" #include <memory.h> #include <omp.h> #include "..\..\xmcml\xmcml\mcml_kernel.h" void InitOutput(InputInfo* input, OutputInfo* output) { int gridSize = input->area->partitionNumber.x * input->area->partitionNumber.y * input->area->partitionNumber.z; output->gridSize = gridSize; output->absorption = new double[gridSize]; memset(output->absorption, 0, gridSize * sizeof(double)); int numberOfDetectors = input->numberOfDetectors; output->numberOfDetectors = numberOfDetectors; output->weightInDetector = new double[numberOfDetectors]; memset(output->weightInDetector, 0, numberOfDetectors * sizeof(double)); output->detectorTrajectory = new DetectorTrajectory[numberOfDetectors]; for (int i = 0; i < numberOfDetectors; ++i) { output->detectorTrajectory[i].numberOfPhotons = 0; output->detectorTrajectory[i].trajectorySize = gridSize; output->detectorTrajectory[i].trajectory = new double[gridSize]; memset(output->detectorTrajectory[i].trajectory, 0, gridSize * sizeof(double)); } } int GetMaxThreads() { return omp_get_max_threads(); } void LaunchOMP(InputInfo* input, OutputInfo* output, MCG59* randomGenerator, int numThreads) { omp_set_num_threads(numThreads); InitOutput(input, output); output->specularReflectance = ComputeSpecularReflectance(input->layerInfo); #pragma omp parallel { int gridSize = input->area->partitionNumber.x * input->area->partitionNumber.y * input->area->partitionNumber.z; double* trajectory = new double[gridSize]; int threadId = omp_get_thread_num(); for (int i = threadId; i < input->numberOfPhotons; i += numThreads) { ComputePhoton(output->specularReflectance, input, output, &(randomGenerator[threadId]), trajectory); } delete[] trajectory; } }
1dacbfbe27c9d6e15bf12fa5eb7418759288a3c2
b8bd6677cca02eaeb55c5399bb64114e45b16d4d
/headers/jni_helper.cpp
4ddd42288811368b5263d8a537c24ba1549386b4
[ "BSD-3-Clause" ]
permissive
Laxen/object_identification_localization
510e67ab2fb1e67b3ccbe57588f1420542aab412
658aad68c6e93386a6c49a810bd8620215a54440
refs/heads/master
2021-05-09T13:00:04.687994
2018-03-07T14:32:35
2018-03-07T14:32:35
119,023,703
6
2
null
2019-04-03T12:32:56
2018-01-26T08:05:24
C++
UTF-8
C++
false
false
1,882
cpp
#include "jni_helper.hpp" JNI_Helper::JNI_Helper() { } /** Initialize the class_path to the VM @param class_path The class path */ JNI_Helper::JNI_Helper(std::string class_path) { initialize(class_path); } void JNI_Helper::initialize(std::string class_path) { std::string jvm_command = "-Djava.class.path=" + class_path; const int kNumOptions = 1; JavaVMOption options[kNumOptions] = { { const_cast<char*>(jvm_command.c_str()), NULL } }; JavaVMInitArgs vm_args; vm_args.version = JNI_VERSION_1_6; vm_args.nOptions = kNumOptions; vm_args.options = options; int res = JNI_CreateJavaVM(&jvm, reinterpret_cast<void**>(&env), &vm_args); if (res != JNI_OK) { throw std::runtime_error("JNI_Helper::JNI_Helper : JNI_CreateJavaVM failed!"); } else { std::cerr << "JVM created!" << std::endl; } } JNI_Helper::~JNI_Helper() { jvm->DestroyJavaVM(); std::cout << "JVM destroyed!" << std::endl; } /* Get a class from a program in the JVM @param class_name The name of the class @return The jclass object */ jclass JNI_Helper::get_class(std::string class_name) { jclass c = env->FindClass(class_name.c_str()); if (c == NULL) { throw std::runtime_error("get_class : Class \"" + class_name + "\" not found!"); } } /* Get a method ID from a class in the JVM @param class_j The jclass object to find the method in @param method_name The name of the method @param signature The method signature @return The jmethodID object */ jmethodID JNI_Helper::get_static_mid(jclass class_j, std::string method_name, std::string signature) { jmethodID mid = env->GetStaticMethodID(class_j, method_name.c_str(), signature.c_str()); if (mid == NULL) { throw std::runtime_error("get_static_mid : Method \"" + method_name + "\" not found!"); } } jstring JNI_Helper::create_string(std::string str) { jstring jstr = env->NewStringUTF(str.c_str()); return jstr; }
37dd2b5ba991d79a59515321393120c4c0642b58
c5b93a9b23b4ddec0913ae41e60223877c0b65a0
/code/swc_addnoisesaltandpepper.h
82ccc5dcfb0f281ccae13cdc6f64397d24e936b8
[]
no_license
PamirGhimire/seeWithCpp
593f276a63382335fe9a7c9f27c313149894baa2
c9d8088e72af5aa534367b94e928f6f564279aa4
refs/heads/master
2021-01-19T23:14:25.068259
2017-06-07T17:53:33
2017-06-07T17:53:33
88,941,638
0
0
null
null
null
null
UTF-8
C++
false
false
689
h
#ifndef SWC_ADDNOISESALTANDPEPPER_H #define SWC_ADDNOISESALTANDPEPPER_H // opencv headers #include<opencv2/core/core.hpp> #include<opencv2/imgproc/imgproc.hpp> class swc_addNoiseSaltAndPepper { private: // number of pixels to which salt and pepper noise is to be added int mv_nPixels2Corrupt; public: // default constructor swc_addNoiseSaltAndPepper(); // add salt and pepper noise to inputim and write the result to outputim void mf_addSaltAndPepper(const cv::Mat &inputim, cv::Mat& outputim); // get& set number of pixels to corrupt int mf_getNPixels2Corrput() const; void mf_setNPixels2Corrupt(int n); }; #endif // SWC_ADDNOISESALTANDPEPPER_H
b82c98c5de48935b7dc0d847877151d581b76722
21ae20bd54b92d9f6a7d2771949524b50b3648dc
/src/sound/OpenALAudioSource.h
b26db2133ef9c7e5050f9b02790ffd21193534d9
[ "MIT" ]
permissive
pjohalloran/gameframework
a94b981bdeb94427e55c50c57cfc265ed2472f2a
b3ad64dc8f9a8129c1ee5b4d1a797150f0216682
refs/heads/master
2021-01-25T10:29:17.629501
2013-09-01T21:44:12
2013-09-01T21:44:12
5,521,387
5
2
null
2013-09-01T21:44:02
2012-08-23T08:01:19
C
UTF-8
C++
false
false
27,430
h
#pragma once #ifndef __GF_OPEN_AL_AUDIO_SOURCE_H #define __GF_OPEN_AL_AUDIO_SOURCE_H // //////////////////////////////////////////////////////////////////// // @file OpenALAudioSource.h // @author PJ O Halloran // @date 12/10/2010 // // File contains the header for the OpenALAudioSource class. // // //////////////////////////////////////////////////////////////////// #include <vector> #include <boost/shared_ptr.hpp> #include <boost/optional.hpp> #if defined(_WINDOWS) || defined(WIN32) #include <al.h> #include <alc.h> #elif defined (TARGET_OS_MAC) #include <OpenAL/al.h> #include <OpenAL/alc.h> #else #error "Target not supported yet!" #endif #include "OpenALAudioBuffer.h" #include "Vector.h" namespace GameHalloran { // //////////////////////////////////////////////////////////////////// // @class OpenALAudioSource // @author PJ O Halloran // // An C++ wrapper to encapsulate the OpenAL source of a sound. // Many OpenAL sound buffers may be attached to a source to be played // one after the other. // // //////////////////////////////////////////////////////////////////// class OpenALAudioSource { private: ALuint m_id; ///< Handle/ID of the OpenAL source. boost::optional<ALfloat> m_totalDuration; ///< Total duration of the buffer(s) attached to the source in seconds. F32 m_lastUpdateTime; ///< Timestamp of the last update call. // //////////////////////////////////////////////////////////////////// // Get a human readable string of the ALenum param (for logging errors). // // //////////////////////////////////////////////////////////////////// std::string GetALEnumString(const ALenum param) const; // //////////////////////////////////////////////////////////////////// // Get a single OpenAL F32 value. // // @param param The ID of the parameter. // @param value Will hold the value retrieved on success. // // @return bool True on success or false on failure. // // //////////////////////////////////////////////////////////////////// bool GetFloatParam(const ALenum param, ALfloat &value) const; // //////////////////////////////////////////////////////////////////// // Set a single OpenAL F32 value. // // @param param The ID of the parameter. // @param value The new value of the parameter. // // @return bool True on success or false on failure. // // //////////////////////////////////////////////////////////////////// bool SetFloatParam(const ALenum param, const ALfloat value) const; // //////////////////////////////////////////////////////////////////// // Get an array OpenAL F32 value. // // @param param The ID of the parameter. // @param arrSize The size of the array. // @param arr Will hold the values retrieved on success. // // @return bool True on success or false on failure. // // //////////////////////////////////////////////////////////////////// bool GetFloatArrayParam(const ALenum param, const ALuint arrSize, ALfloat *arr) const; // //////////////////////////////////////////////////////////////////// // Set an array OpenAL F32 value. // // @param param The ID of the parameter. // @param arrSize The size of the array. // @param arr The new value of the array parameter. // // @return bool True on success or false on failure. // // //////////////////////////////////////////////////////////////////// bool SetFloatArrayParam(const ALenum param, const ALuint arrSize, const ALfloat * const arr) const; // //////////////////////////////////////////////////////////////////// // Get a single OpenAL int value. // // @param param The ID of the parameter. // @param value Will hold the value retrieved on success. // // @return bool True on success or false on failure. // // //////////////////////////////////////////////////////////////////// bool GetIntParam(const ALenum param, ALint &value) const; // //////////////////////////////////////////////////////////////////// // Set a single OpenAL int value. // // @param param The ID of the parameter. // @param value The new value of the parameter. // // @return bool True on success or false on failure. // // //////////////////////////////////////////////////////////////////// bool SetIntParam(const ALenum param, const ALint value) const; // //////////////////////////////////////////////////////////////////// // Get an array OpenAL I32 value. // // @param param The ID of the parameter. // @param arrSize The size of the array. // @param arr Will hold the values retrieved on success. // // @return bool True on success or false on failure. // // //////////////////////////////////////////////////////////////////// bool GetIntArrayParam(const ALenum param, const ALuint arrSize, ALint *arr) const; // //////////////////////////////////////////////////////////////////// // Set an array OpenAL int value. // // @param param The ID of the parameter. // @param arrSize The size of the array. // @param arr The new value of the array parameter. // // @return bool True on success or false on failure. // // //////////////////////////////////////////////////////////////////// bool SetIntArrayParam(const ALenum param, const ALuint arrSize, const ALint * const arr) const; public: // //////////////////////////////////////////////////////////////////// // Constructor. // // Check if the source is valid after creation with IsValid() to ensure // it was created correctly. // // @param positionRef The initial position of the source. // @param velRef The initial velocity of the source. // @param directionRef The initial direction the source is facing. // // //////////////////////////////////////////////////////////////////// OpenALAudioSource(const Point3 &positionRef, const Vector3 &velRef, const Vector3 &directionRef); // //////////////////////////////////////////////////////////////////// // Destructor. // // //////////////////////////////////////////////////////////////////// virtual ~OpenALAudioSource(); // //////////////////////////////////////////////////////////////////// // Is the source a valid OpenAL source. // // //////////////////////////////////////////////////////////////////// inline bool IsValid() const { return (alIsSource(m_id) == AL_TRUE ? true : false); }; // //////////////////////////////////////////////////////////////////// // Return the ID of the OpenAL source so you can use the OpenAL C API // directly if you wish. Do not call alDeleteSource on this ID as the // source class will do that when instances goes out of scope. // // //////////////////////////////////////////////////////////////////// inline ALuint GetId() const { return (m_id); }; // //////////////////////////////////////////////////////////////////// // Get the current position of the source. // // @param position The object which will contain the sources current // position on success. // // @param bool True if we got the position. // // //////////////////////////////////////////////////////////////////// bool GetPosition(Point3 &position) const; // //////////////////////////////////////////////////////////////////// // Set the position of the source. // // @param positionRef The initial position of the source. // // //////////////////////////////////////////////////////////////////// inline bool SetPosition(const Point3 &positionRef) const { return (SetFloatArrayParam(AL_POSITION, 3, positionRef.GetComponentsConst())); }; // //////////////////////////////////////////////////////////////////// // Get the current velocity of the source. // // @param velocity The current velocity. // // @param bool True if we got the velocity. // // //////////////////////////////////////////////////////////////////// bool GetVelocity(Vector3 &velocity) const; // //////////////////////////////////////////////////////////////////// // Set the velocity of the source. // // @param velRef The initial velocity of the source. // // //////////////////////////////////////////////////////////////////// inline bool SetVelocity(const Vector3 &velRef) const { return (SetFloatArrayParam(AL_VELOCITY, 3, velRef.GetComponentsConst())); }; // //////////////////////////////////////////////////////////////////// // Get the current direction of the source. // // @param direction The current velocity. // // @param bool True if we got the velocity. // // //////////////////////////////////////////////////////////////////// bool GetDirection(Vector3 &direction) const; // //////////////////////////////////////////////////////////////////// // Set the direction of the source. // // As per OpenAL documentation, if you set the direction to (0,0,0) // the source will be a directionless sound source. This can speed up // sound calculations as attenuation and the doppler effect // will be factored out. // // @param directionRef The initial direction the source is facing. // // //////////////////////////////////////////////////////////////////// inline bool SetDirection(const Vector3 &directionRef) const { return (SetFloatArrayParam(AL_DIRECTION, 3, directionRef.GetComponentsConst())); }; // //////////////////////////////////////////////////////////////////// // Is the sound source a directional one? // // //////////////////////////////////////////////////////////////////// inline bool IsDirectional() const { Vector3 dir; GetDirection(dir); if(dir != Vector3(0, 0, 0)) { return (true); } return (false); }; // //////////////////////////////////////////////////////////////////// // Convienience function that updates the sources position, facing // direction and velocity all at once. // // The velocity is calculated using the formula V = (Pn - Po) / (Tn - To). // V = new velocity. // Pn = New position. // Po = Old position. // Tn = Time of this position change. // To = Time of last position change. // // @param newPosition The new position of the source. // @param newDirection New facing direction of the source. // @param timestamp The time when the sources position changed. // // @return bool True on success or false on failure. // // //////////////////////////////////////////////////////////////////// bool Update(const Point3 &newPosition, const Vector3 &newDirection, const F32 timestamp); // //////////////////////////////////////////////////////////////////// // Attach a single buffer to the source. // // @param oalAudioBufferPtr Pointer to the audio buffer to attach to the // source. // // @return bool True on success. // @return bool False if the pointer is NULL. // @return bool False if OpenAL fails to attach the buffer to the source // (check error log). // // //////////////////////////////////////////////////////////////////// bool AttachBuffer(boost::shared_ptr<OpenALAudioBuffer> oalAudioBufferPtr); // //////////////////////////////////////////////////////////////////// // Attach a queue of buffers to the source. // // @param oalAudioBufferQueue Queue of audio buffers to attach to the // source. // // @return bool True on success. // @return bool False if the queue is empty or any elements are NULL. // @return bool False if OpenAL fails to attach the queue to the source // (check error log). // // //////////////////////////////////////////////////////////////////// bool AttachBufferList(const OpenALAudioBufferQueue &oalAudioBufferQueue); // //////////////////////////////////////////////////////////////////// // Detach the source from all buffers. // // //////////////////////////////////////////////////////////////////// bool DetachBuffers(); // //////////////////////////////////////////////////////////////////// // Check if an audio buffer is attached to the source. // // @param audioBufferPtr Pointer to the audio buffer. // // @return bool True if the audio buffer is attached and false if not. // // //////////////////////////////////////////////////////////////////// bool IsBufferAttached(boost::shared_ptr<OpenALAudioBuffer> audioBufferPtr) const; // //////////////////////////////////////////////////////////////////// // Get the number of buffers attached. // // //////////////////////////////////////////////////////////////////// inline U32 GetBufferQueueSize() const { ALint size(0); GetIntParam(AL_BUFFERS_QUEUED, size); return (U32(size)); }; // //////////////////////////////////////////////////////////////////// // Get the number of buffers processed. // // //////////////////////////////////////////////////////////////////// inline U32 GetNumberBuffersProcessed() const { ALint size(0); GetIntParam(AL_BUFFERS_PROCESSED, size); return (U32(size)); }; // //////////////////////////////////////////////////////////////////// // Get the pitch. // // //////////////////////////////////////////////////////////////////// inline bool GetPitch(F32 &pitch) const { return (GetFloatParam(AL_PITCH, pitch)); }; // //////////////////////////////////////////////////////////////////// // Set the pitch. // // //////////////////////////////////////////////////////////////////// inline bool SetPitch(const F32 pitch) const { return (SetFloatParam(AL_PITCH, pitch)); }; // //////////////////////////////////////////////////////////////////// // Get the 3D gain/volume attributes. // // @param maxAttDistance Distance where there will be no further attenuation. // @param rolloffFactor Rollof rate. // @param refDistance Distance where the volume will drop by half (before // influence by rolloff or attenuation kicks in). // // //////////////////////////////////////////////////////////////////// inline bool Get3dVolumeAttributes(F32 &maxAttDistance, F32 &rolloffFactor, F32 &refDistance) const { return (GetFloatParam(AL_MAX_DISTANCE, maxAttDistance) && \ GetFloatParam(AL_ROLLOFF_FACTOR, rolloffFactor) && \ GetFloatParam(AL_REFERENCE_DISTANCE, refDistance)); }; // //////////////////////////////////////////////////////////////////// // Set all 3D gain/volume attributes. // // @param maxAttDistance Distance where there will be no further attenuation. // @param rolloffFactor Rollof rate. // @param refDistance Distance where the volume will drop by half (before // influence by rolloff or attenuation kicks in). // // //////////////////////////////////////////////////////////////////// inline bool Set3dVolumeAttributes(const F32 maxAttDistance, const F32 rolloffFactor, const F32 refDistance) const { return (SetFloatParam(AL_MAX_DISTANCE, maxAttDistance) && \ SetFloatParam(AL_ROLLOFF_FACTOR, rolloffFactor) && \ SetFloatParam(AL_REFERENCE_DISTANCE, refDistance)); }; // //////////////////////////////////////////////////////////////////// // Get the min and max source gain/volume. // // //////////////////////////////////////////////////////////////////// inline bool GetVolumeLimits(F32 &minVolume, F32 &maxVolume) const { return (GetFloatParam(AL_MIN_GAIN, minVolume) && \ GetFloatParam(AL_MAX_GAIN, maxVolume)); }; // //////////////////////////////////////////////////////////////////// // Set the min and max source gain/volume. // // //////////////////////////////////////////////////////////////////// inline bool SetVolumeLimits(const F32 minVolume, const F32 maxVolume) const { return (SetFloatParam(AL_MIN_GAIN, minVolume) && \ SetFloatParam(AL_MAX_GAIN, maxVolume)); }; // //////////////////////////////////////////////////////////////////// // Get the directional sound cone attributes. // // @param outerGain Gain/Volume when outside the sound cone. // @param innerAngle Inner sound cone angle. // @param outerAngle Outer sound cone angle. // // //////////////////////////////////////////////////////////////////// inline bool GetAudibleConeAttributes(F32 &outerGain, F32 &innerAngle, F32 &outerAngle) const { return (GetFloatParam(AL_CONE_OUTER_GAIN, outerGain) && \ GetFloatParam(AL_CONE_INNER_ANGLE, innerAngle) && \ GetFloatParam(AL_CONE_OUTER_ANGLE, outerAngle)); }; // //////////////////////////////////////////////////////////////////// // Set the directional sound cone attributes. // // @param outerGain Gain/Volume when outside the sound cone. // @param innerAngle Inner sound cone angle. // @param outerAngle Outer sound cone angle. // // //////////////////////////////////////////////////////////////////// inline bool SetAudibleConeAttributes(const F32 outerGain, const F32 innerAngle, const F32 outerAngle) const { return (SetFloatParam(AL_CONE_OUTER_GAIN, outerGain) && \ SetFloatParam(AL_CONE_INNER_ANGLE, innerAngle) && \ SetFloatParam(AL_CONE_OUTER_ANGLE, outerAngle)); }; // //////////////////////////////////////////////////////////////////// // Is the source streaming multiple buffers? // // //////////////////////////////////////////////////////////////////// inline bool IsStreaming() const { ALint st; return (GetIntParam(AL_SOURCE_TYPE, st) && (st == AL_STREAMING)); }; // //////////////////////////////////////////////////////////////////// // Is the source playing only one buffer? // // //////////////////////////////////////////////////////////////////// bool IsStatic() const { ALint st; return (GetIntParam(AL_SOURCE_TYPE, st) && (st == AL_STATIC)); }; // //////////////////////////////////////////////////////////////////// // Set the current playback position in seconds. // // //////////////////////////////////////////////////////////////////// inline bool SetPlaybackPositionTime(const F32 seconds) const { return (SetFloatParam(AL_SEC_OFFSET, seconds)); }; // //////////////////////////////////////////////////////////////////// // Set the current playback position in samples. // // //////////////////////////////////////////////////////////////////// inline bool SetPlaybackPositionSamples(const F32 samples) const { return (SetFloatParam(AL_SAMPLE_OFFSET, samples)); }; // //////////////////////////////////////////////////////////////////// // Set the current playback position in byte offset from the beginning // of the buffer. // // //////////////////////////////////////////////////////////////////// inline bool SetPlaybackPositionByteOffset(const F32 byteOffset) const { return (SetFloatParam(AL_BYTE_OFFSET, byteOffset)); }; // //////////////////////////////////////////////////////////////////// // Get the current playback position. // // @param seconds Current playback time. // @param samples Current buffer sample. // @param byteOffset Current buffer byte offset. // // //////////////////////////////////////////////////////////////////// inline bool GetPlaybackPosition(F32 &seconds, F32 &samples, F32 &byteOffset) const { return (SetFloatParam(AL_SEC_OFFSET, seconds) && \ SetFloatParam(AL_SAMPLE_OFFSET, samples) && \ SetFloatParam(AL_BYTE_OFFSET, byteOffset)); }; // //////////////////////////////////////////////////////////////////// // Is the sources position relative to the listener? // // //////////////////////////////////////////////////////////////////// inline bool IsRelativePosition() const { ALint r; return (GetIntParam(AL_SOURCE_RELATIVE, r) && (r == AL_TRUE)); }; // //////////////////////////////////////////////////////////////////// // Make the sources position either relative or not relative to the // listeners position. // // //////////////////////////////////////////////////////////////////// inline bool UseRelativePosition(const bool relative) const { return (SetIntParam(AL_SOURCE_RELATIVE, relative ? AL_TRUE : AL_FALSE)); }; // //////////////////////////////////////////////////////////////////// // Play the sound buffer the source is attached to from the // beginning. // // @param volume The volume of the sound (between 0.0 and 1.0). // @param looping Should the sound loop when played? // // @return bool True on success and false on failure. // // //////////////////////////////////////////////////////////////////// bool Play(const F32 volume, const bool looping) const; // //////////////////////////////////////////////////////////////////// // Pause the sound buffer(s) the source is attached to. // // @return bool True on success and false on failure. // // //////////////////////////////////////////////////////////////////// bool Pause() const; // //////////////////////////////////////////////////////////////////// // Stop the sound buffer the source is attached to. // // @return bool True on success and false on failure. // // //////////////////////////////////////////////////////////////////// bool Stop() const; // //////////////////////////////////////////////////////////////////// // Resume playing the sound buffer the source is attached to. // // @return bool True on success and false on failure. // // //////////////////////////////////////////////////////////////////// bool Resume() const; // //////////////////////////////////////////////////////////////////// // Toggle on/off pausing the sound buffer the source is attached to. // // @return bool True on success and false on failure. // // //////////////////////////////////////////////////////////////////// bool TogglePause() const; // //////////////////////////////////////////////////////////////////// // Check if the sound buffer is playing the source is attached to. // // //////////////////////////////////////////////////////////////////// inline bool IsPlaying() const { ALint state; return (GetIntParam(AL_SOURCE_STATE, state) && state == AL_PLAYING); }; // //////////////////////////////////////////////////////////////////// // Check if the source state is currently stopped. // // //////////////////////////////////////////////////////////////////// inline bool IsStopped() const { ALint state; return (GetIntParam(AL_SOURCE_STATE, state) && state == AL_STOPPED); }; // //////////////////////////////////////////////////////////////////// // Check if the source state is currently paused. // // //////////////////////////////////////////////////////////////////// inline bool IsPaused() const { ALint state; return (GetIntParam(AL_SOURCE_STATE, state) && state == AL_PAUSED); }; // //////////////////////////////////////////////////////////////////// // Set the volume/gain of the sound the source is attached to. // // @param volume The new volume of the sound. // // //////////////////////////////////////////////////////////////////// inline bool SetVolume(const F32 volume) const { return (SetFloatParam(AL_GAIN, volume)); }; // //////////////////////////////////////////////////////////////////// // Get the volume/gain of the sound the source is attached to. // // //////////////////////////////////////////////////////////////////// inline bool GetVolume(F32 &volume) const { return (GetFloatParam(AL_GAIN, volume)); }; // //////////////////////////////////////////////////////////////////// // Get the progress of the playback the source is attached to. // // @return F32 A number between 0.0 and 1.0 indicating how much of // the sound has been played. // // //////////////////////////////////////////////////////////////////// F32 GetProgress() const; }; // List of OpenAL sources. typedef std::vector<boost::shared_ptr<OpenALAudioSource> > OpenALAudioSourceList; } #endif
8d608e4b57c69dcbf53c2c901227d4c07c76a29d
23c90f4f7879974404acaed76ada7b0b65210c3d
/My-ACM-Template/05_Computational Geometry/02_Convex_hull.cpp
f71b03cc3be9ce9d6b5697026324b63e6f9759a6
[]
no_license
superkunn/qy
77275a1d0ca1391fde60b0a09f28bffe9a227bcf
b96675186e650e4cb8ef0b85cab01649c8ec2038
refs/heads/master
2020-04-03T21:10:43.634920
2018-10-31T14:06:30
2018-10-31T14:06:30
155,565,437
0
0
null
null
null
null
UTF-8
C++
false
false
6,555
cpp
const double eps=1e-8; struct point { double x,y; point(){} point(double a,double b){x=a;y=b;} point operator -(const point &a)const{return point(x-a.x,y-a.y);} double operator ^(const point &a)const{return x*a.y-y*a.x;} double operator *(const point &a)const{return x*a.x+y*a.y;} }p[MAX],b[MAX]; int top,n; double cross(point a,point b,point c){return (b-a)^(c-a);}//Triangle'Area*Area double dis(point a,point b){return (a-b)*(a-b);}//Point Dis bool cmp(point a,point b) { double tmp=cross(p[0],a,b); if(tmp>eps||(fabs(tmp)<eps&&dis(p[0],a)-dis(p[0],b)>eps)) return 1; return 0; } void graham() { int u=0;top=0; for(int k=1;k<n;k++) if(p[u].y-p[k].y>eps||(fabs(p[u].y-p[k].y)<eps&&p[u].x-p[k].x>eps)) u=k; swap(p[u],p[0]); sort(p+1,p+n,cmp); if(n>0) {b[0]=p[0];top++;} if(n>1) {b[1]=p[1];top++;} if(n<3) return ; for(int i=2;i<n;i++) { while(top>1&&cross(b[top-2],b[top-1],p[i])<eps) top--; b[top++]=p[i]; } } /*Zhou Chang*/ int main() { double sum=0; scanf("%d",&n); for(int k=0;k<n;k++) scanf("%lf%lf",&p[k].x,&p[k].y); graham();b[top]=b[0]; for(int k=1;k<=top;k++) sum+=sqrt(dis(b[k],b[k-1])); printf("%.2f\n",sum); return 0; } /* Area */ int main() { double sum=0; scanf("%d",&n); for(int k=0;k<n;k++) scanf("%lf%lf",&p[k].x,&p[k].y); graham(); for(int k=1;k<top-1;k++) sum+=fabs(cross(b[0],b[k],b[k+1]));//Sum of Triangle Area printf("%d\n",(int)(sum/100)); return 0; } /*Farthest point Dis*/ double rotating() { double ans=0; b[top]=b[0]; for(int k=0,i=1;k<=top;k++) { while(fabs(cross(b[k],b[i+1],b[k+1]))-fabs(cross(b[k],b[i],b[k+1]))>eps) i=(i+1)%top; ans=max(ans,dis(b[i],b[k])); } return ans; } /*Minimum width*/ double rotating() { double ans=0x3f3f3f3f; b[top]=b[0]; for(int k=0,i=1;k<=top;k++) { while(fabs(cross(b[k],b[i+1],b[k+1]))-fabs(cross(b[k],b[i],b[k+1]))>eps) i=(i+1)%top; ans=min(ans,fabs(cross(b[k],b[k+1],b[i])/sqrt(dis(b[k],b[k+1])))); } return ans; } /* Max Area of Triangle*/ double rotating() { double ans=0; for(int k=0;k<top;k++) { int i=(k+1)%top,j=(i+1)%top; while(i!=k&&j!=k) { ans=max(ans,fabs(cross(b[k],b[i],b[j]))); while(fabs(cross(b[k],b[i+1],b[j]))-fabs(cross(b[k],b[i],b[j]))>eps) i=(i+1)%top; j=(j+1)%top; } } return ans; } /* The max/min Dis of two convex hull */ const double eps=1e-8; const double INF=1e99; struct point{}p[MAX],b1[MAX],b2[MAX]; int top1,top2; double min(double a,double b){return a-b<-eps?a:b;} double cross(point a,point b,point c){return (b-a)^(c-a);} double multi(point a,point b,point c){return (b-a)*(c-a);} double dis(point a,point b){return (a-b)*(a-b);} double dist(point a,point b,point c)//Line Dis { point d; double t=multi(b,a,c)/dis(b,c); if(t>-eps&&t-1<eps) d=point(b.x+(c.x-b.x)*t,b.y+(c.y-b.y)*t); else { if(dis(a,b)-dis(a,c)<-eps) d=b; else d=c; } return dis(a,d); } double distence(point a,point b,point c,point d){return min(min(dist(a,c,d),dist(b,c,d)),min(dist(c,a,b),dist(d,a,b)));}//Two Line bool cmp(point a,point b) { double tmp=cross(p[0],a,b); if(tmp>eps||(fabs(tmp)<eps&&dis(p[0],a)-dis(p[0],b)>eps)) return 1; return 0; } void graham(point *b,int n,int &top) { int u=0;top=0; for(int k=1;k<n;k++) if(p[u].y-p[k].y>eps||(fabs(p[u].y-p[k].y)<eps&&p[u].x-p[k].x>eps)) u=k; swap(p[u],p[0]); sort(p+1,p+n,cmp); if(n>0) {b[0]=p[0];top++;} if(n>1) {b[1]=p[1];top++;} if(n<3) return ; for(int i=2;i<n;i++) { while(top>1&&cross(b[top-2],b[top-1],p[i])<eps) top--; b[top++]=p[i]; } } double rotating(point *a,int n,point *b,int m) { int i1=0,i2=0; for(int k=0;k<n;k++) if(a[k].y-a[i1].y<-eps) i1=k; for(int k=0;k<m;k++) if(b[k].y-b[i2].y>eps) i2=k; a[n]=a[0];b[m]=b[0]; double tmp,ans=INF; for(int k=0;k<n;k++) { while((tmp=cross(a[i1+1],b[i2+1],a[i1])-cross(a[i1+1],b[i2],a[i1]))>eps) i2=(i2+1)%m; if(tmp<-eps) ans=min(ans,dist(b[i2],a[i1],a[i1+1])); else ans=min(ans,distence(a[i1],a[i1+1],b[i2],b[i2+1])); i1=(i1+1)%n; } return ans; } int main() { int n,m; while(~scanf("%d%d",&n,&m)&&(n||m)) { for(int k=0;k<n;k++) scanf("%lf%lf",&p[k].x,&p[k].y); graham(b1,n,top1); for(int k=0;k<m;k++) scanf("%lf%lf",&p[k].x,&p[k].y); graham(b2,m,top2); printf("%0.5f\n",sqrt(min(rotating(b1,top1,b2,top2),rotating(b2,top2,b1,top1)))); } return 0; } /* Minest rectangle contain convex hull*/ const double eps=1e-8; const double INF=1e99; struct point{}p[MAX],b[MAX]; int top,n; double min(double a,double b){return a-b<-eps?a:b;} double cross(point a,point b,point c){return (b-a)^(c-a);} double multi(point a,point b,point c){return (b-a)*(c-a);} double dis(point a,point b){return (a-b)*(a-b);} bool cmp(point a,point b) { double tmp=cross(p[0],a,b); if(tmp>eps||(fabs(tmp)<eps&&dis(p[0],a)-dis(p[0],b)>eps)) return 1; return 0; } void graham() { int u=0;top=0; for(int k=1;k<n;k++) if(p[u].y-p[k].y>eps||(fabs(p[u].y-p[k].y)<eps&&p[u].x-p[k].x>eps)) u=k; swap(p[u],p[0]); sort(p+1,p+n,cmp); if(n>0) {b[0]=p[0];top++;} if(n>1) {b[1]=p[1];top++;} if(n<3) return ; for(int i=2;i<n;i++) { while(top>1&&cross(b[top-2],b[top-1],p[i])<eps) top--; b[top++]=p[i]; } } double rotating() { int r=1,u=1,l; double ans=INF; b[top]=b[0]; for(int k=0;k<top;k++) { while(cross(b[k],b[k+1],b[u+1])-cross(b[k],b[k+1],b[u])>-eps) u=(u+1)%top; while(multi(b[k],b[k+1],b[r+1])-multi(b[k],b[k+1],b[r])>eps) r=(r+1)%top; l=k==0?r:l; while(multi(b[k],b[k+1],b[l+1])-multi(b[k],b[k+1],b[l])<eps) l=(l+1)%top; ans=min(ans,fabs(cross(b[k],b[k+1],b[u]))*fabs(multi(b[k],b[k+1],b[r])-multi(b[k],b[k+1],b[l]))/dis(b[k],b[k+1])); } return ans; } int main() { int t;scanf("%d",&t); for(int tc=1;tc<=t;tc++) { scanf("%d",&n);n*=4; for(int k=0;k<n;k++) scanf("%lf%lf",&p[k].x,&p[k].y); graham(); printf("Case #%d:\n%d\n",tc,(int)(rotating()+0.5)); } return 0; }
b2df27e8e04956f034a8f1800fa6dd24dddd2016
53941182efdc9905526afed5aa516943b8263fcb
/cpp/open3d/ml/PyTorch/Misc/FixedRadiusSearchOpKernel.cpp
ae19b16077140087beba640381181f95f4786597
[ "MIT" ]
permissive
wwll/Open3D
c67988cefdf562b75ba36d1392747d6e896b8300
39ca2a926dfcf401deb600bae876a1eff004552b
refs/heads/master
2022-12-06T23:46:24.223073
2020-08-26T01:48:41
2020-08-26T01:48:41
290,524,830
0
1
NOASSERTION
2020-08-26T14:50:46
2020-08-26T14:50:45
null
UTF-8
C++
false
false
4,430
cpp
// ---------------------------------------------------------------------------- // - Open3D: www.open3d.org - // ---------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2020 www.open3d.org // // 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 "open3d/ml/PyTorch/Misc/NeighborSearchAllocator.h" #include "open3d/ml/PyTorch/TorchHelper.h" #include "open3d/ml/impl/misc/FixedRadiusSearch.h" #include "torch/script.h" using namespace open3d::ml::impl; template <class T> void FixedRadiusSearchCPU(const torch::Tensor& points, const torch::Tensor& queries, double radius, const torch::Tensor& points_row_splits, const torch::Tensor& queries_row_splits, const torch::Tensor& hash_table_splits, const torch::Tensor& hash_table_index, const torch::Tensor& hash_table_cell_splits, const Metric metric, const bool ignore_query_point, const bool return_distances, torch::Tensor& neighbors_index, torch::Tensor& neighbors_row_splits, torch::Tensor& neighbors_distance) { NeighborSearchAllocator<T> output_allocator(points.device().type(), points.device().index()); FixedRadiusSearchCPU( neighbors_row_splits.data_ptr<int64_t>(), points.size(0), points.data_ptr<T>(), queries.size(0), queries.data_ptr<T>(), T(radius), points_row_splits.size(0), points_row_splits.data_ptr<int64_t>(), queries_row_splits.size(0), queries_row_splits.data_ptr<int64_t>(), (uint32_t*)hash_table_splits.data_ptr<int32_t>(), hash_table_cell_splits.size(0), (uint32_t*)hash_table_cell_splits.data_ptr<int32_t>(), (uint32_t*)hash_table_index.data_ptr<int32_t>(), metric, ignore_query_point, return_distances, output_allocator); neighbors_index = output_allocator.NeighborsIndex(); neighbors_distance = output_allocator.NeighborsDistance(); } #define INSTANTIATE(T) \ template void FixedRadiusSearchCPU<T>( \ const torch::Tensor& points, const torch::Tensor& queries, \ double radius, const torch::Tensor& points_row_splits, \ const torch::Tensor& queries_row_splits, \ const torch::Tensor& hash_table_splits, \ const torch::Tensor& hash_table_index, \ const torch::Tensor& hash_table_cell_splits, const Metric metric, \ const bool ignore_query_point, const bool return_distances, \ torch::Tensor& neighbors_index, \ torch::Tensor& neighbors_row_splits, \ torch::Tensor& neighbors_distance); INSTANTIATE(float) INSTANTIATE(double)
a5f5d5066a64ac82d95954661f5995cbbe5b0bf3
1c41afe53cc0ceb58e8a3ae409a7b8abb9a7071e
/modules/demonblade.hpp
29e550c5b239e26aa4688bd1da178c7732ea3743
[ "LicenseRef-scancode-happy-bunny", "LicenseRef-scancode-warranty-disclaimer", "MIT", "Apache-2.0" ]
permissive
rubot813/demonblade_engine
645b11dd1f11442934a93f8bfb0d430fc0b30e7d
c09f93b0170da0f0ab8f3425f3c64b79a2c1cbfa
refs/heads/main
2023-02-12T13:04:22.605439
2021-01-05T18:00:25
2021-01-05T18:00:41
310,410,531
1
0
null
null
null
null
UTF-8
C++
false
false
345
hpp
/* Хэдер для подключения модулей движка demonblade */ #ifndef DEMONBLADE_HPP_INCLUDED #define DEMONBLADE_HPP_INCLUDED // modules #include "./core/core.hpp" #include "./render/render.hpp" #include "./utils/utils.hpp" // live fast, die young! |:> namespace db = demonblade; #endif // DEMONBLADE_HPP_INCLUDED
b829fe492bef19bfab14ccfdbd9b8929f17bdab1
693d93174f43a81d8a65041553282a8872e3a6ff
/src/index/txindex.cpp
8cb188cd698646730335e61ab488cd5366b6d03e
[ "MIT" ]
permissive
eleccoin/eleccoin
c075719d5ee676fc2bb9a21f3711d75d673655bd
963f6d4a069e40ab2e46217e5d49bc94adda2c5c
refs/heads/master
2022-11-13T02:38:36.662655
2022-10-30T08:56:57
2022-10-30T08:56:57
238,475,897
3
7
MIT
2022-01-10T07:29:19
2020-02-05T14:56:34
C++
UTF-8
C++
false
false
3,209
cpp
// Copyright (c) 2020-2022 The Eleccoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <index/txindex.h> #include <index/disktxpos.h> #include <node/blockstorage.h> #include <util/system.h> #include <validation.h> using node::OpenBlockFile; constexpr uint8_t DB_TXINDEX{'t'}; std::unique_ptr<TxIndex> g_txindex; /** Access to the txindex database (indexes/txindex/) */ class TxIndex::DB : public BaseIndex::DB { public: explicit DB(size_t n_cache_size, bool f_memory = false, bool f_wipe = false); /// Read the disk location of the transaction data with the given hash. Returns false if the /// transaction hash is not indexed. bool ReadTxPos(const uint256& txid, CDiskTxPos& pos) const; /// Write a batch of transaction positions to the DB. bool WriteTxs(const std::vector<std::pair<uint256, CDiskTxPos>>& v_pos); }; TxIndex::DB::DB(size_t n_cache_size, bool f_memory, bool f_wipe) : BaseIndex::DB(gArgs.GetDataDirNet() / "indexes" / "txindex", n_cache_size, f_memory, f_wipe) {} bool TxIndex::DB::ReadTxPos(const uint256 &txid, CDiskTxPos& pos) const { return Read(std::make_pair(DB_TXINDEX, txid), pos); } bool TxIndex::DB::WriteTxs(const std::vector<std::pair<uint256, CDiskTxPos>>& v_pos) { CDBBatch batch(*this); for (const auto& tuple : v_pos) { batch.Write(std::make_pair(DB_TXINDEX, tuple.first), tuple.second); } return WriteBatch(batch); } TxIndex::TxIndex(size_t n_cache_size, bool f_memory, bool f_wipe) : m_db(std::make_unique<TxIndex::DB>(n_cache_size, f_memory, f_wipe)) {} TxIndex::~TxIndex() {} bool TxIndex::WriteBlock(const CBlock& block, const CBlockIndex* pindex) { // Exclude genesis block transaction because outputs are not spendable. if (pindex->nHeight == 0) return true; CDiskTxPos pos{ WITH_LOCK(::cs_main, return pindex->GetBlockPos()), GetSizeOfCompactSize(block.vtx.size())}; std::vector<std::pair<uint256, CDiskTxPos>> vPos; vPos.reserve(block.vtx.size()); for (const auto& tx : block.vtx) { vPos.emplace_back(tx->GetHash(), pos); pos.nTxOffset += ::GetSerializeSize(*tx, CLIENT_VERSION); } return m_db->WriteTxs(vPos); } BaseIndex::DB& TxIndex::GetDB() const { return *m_db; } bool TxIndex::FindTx(const uint256& tx_hash, uint256& block_hash, CTransactionRef& tx) const { CDiskTxPos postx; if (!m_db->ReadTxPos(tx_hash, postx)) { return false; } CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION); if (file.IsNull()) { return error("%s: OpenBlockFile failed", __func__); } CBlockHeader header; try { file >> header; if (fseek(file.Get(), postx.nTxOffset, SEEK_CUR)) { return error("%s: fseek(...) failed", __func__); } file >> tx; } catch (const std::exception& e) { return error("%s: Deserialize or I/O error - %s", __func__, e.what()); } if (tx->GetHash() != tx_hash) { return error("%s: txid mismatch", __func__); } block_hash = header.GetHash(); return true; }
0bebdb89df77be53a013a7846fb3a758a53a166c
71e1fa4ba9826eba88d0e452b7e73ec8e600147c
/Examen2Clase/Album.cpp
e82635c1aa15aa4384aad70e88a93e3d3c87aef7
[]
no_license
edwincabrera2001/EjerciciosProgramacion3-P42020
3354550ecc9ef521f61b38ca610ca168fc6f59d9
6cd21eee49a090dd9fa56c523cfb6d41c328a7e5
refs/heads/master
2023-02-02T09:23:09.542710
2020-12-18T22:16:54
2020-12-18T22:16:54
307,506,102
0
0
null
null
null
null
UTF-8
C++
false
false
1,851
cpp
#include "Album.h" Album::Album() : nombreAlbum(nullptr), anioPublicacion(0), genero(nullptr), primerSencillo(nullptr), siguienteAlbum(nullptr) { } Album::Album(const char* _nombre, int _anio, const char* _genero) : nombreAlbum(_nombre), anioPublicacion(_anio), genero(_genero) { } void Album::setNombre(char* _nombre) { this->nombreAlbum = _nombre; } void Album::setAnio(int _anio) { this->anioPublicacion = _anio; } void Album::setGenero(char* _genero) { this->genero = _genero; } void Album::setPrimer(Sencillo* _primer) { this->primerSencillo = _primer; } void Album::setSiguiente(Album* _siguiente) { this->siguienteAlbum = _siguiente; } const char* Album::getNombre() { return this->nombreAlbum; } int Album::getAnio() { return this->anioPublicacion; } const char* Album::getGenero() { return this->genero; } Sencillo* Album::getPrimer() { return this->primerSencillo; } Album* Album::getSiguiente() { return this->siguienteAlbum; } bool Album::estaVacia() { return primerSencillo == nullptr; } int Album::duracion() { int total = 0; Sencillo* actual = primerSencillo; while (actual->getSiguiente() != nullptr) { total = total + actual->getDuracion(); } return total; } int Album::cantidadSencillos() { int totalSencillos = 0; Sencillo* actual = primerSencillo; if (estaVacia()) { return 0; } else { while (actual->getSiguiente() != nullptr) { totalSencillos++; } return totalSencillos; } return 0; } void Album::agregarSencillo(char* _nombre, int _duracion) { Sencillo* nuevo = new Sencillo(_nombre, _duracion, nullptr); if (estaVacia()) { primerSencillo = nuevo; } else { Sencillo* actual = primerSencillo; while (actual->getSiguiente() != nullptr) { actual = actual->getSiguiente(); } actual->setSiguiente(nuevo); } }
[ "edwin@DESKTOP-B8EJJCG" ]
edwin@DESKTOP-B8EJJCG
07a0e9d5cc7b3b3c377e10e5a0cfa8b4c6223ab3
1fe69a9c7870d258cf27e784c129bb7b697e7fbb
/src/qt/test/moc_trafficgraphdatatests.cpp
5e79ffe12d985998d7ae350b35334733dbdf2e42
[ "MIT" ]
permissive
defland/aither
465084f03cc31608d2ea1dde5a86645a87a328b2
35c7cef0aef09253bec92ce961463533cbf22fc1
refs/heads/master
2020-03-27T10:44:26.100722
2018-08-28T13:07:26
2018-08-28T13:07:26
146,441,645
0
0
MIT
2018-08-28T13:17:11
2018-08-28T12:06:51
C++
UTF-8
C++
false
false
4,759
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'trafficgraphdatatests.h' ** ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "qt/test/trafficgraphdatatests.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'trafficgraphdatatests.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.5.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_TrafficGraphDataTests_t { QByteArrayData data[9]; char stringdata0[184]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_TrafficGraphDataTests_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_TrafficGraphDataTests_t qt_meta_stringdata_TrafficGraphDataTests = { { QT_MOC_LITERAL(0, 0, 21), // "TrafficGraphDataTests" QT_MOC_LITERAL(1, 22, 29), // "simpleCurrentSampleQueueTests" QT_MOC_LITERAL(2, 52, 0), // "" QT_MOC_LITERAL(3, 53, 35), // "accumulationCurrentSampleQueu..." QT_MOC_LITERAL(4, 89, 13), // "getRangeTests" QT_MOC_LITERAL(5, 103, 16), // "switchRangeTests" QT_MOC_LITERAL(6, 120, 10), // "clearTests" QT_MOC_LITERAL(7, 131, 20), // "averageBandwidthTest" QT_MOC_LITERAL(8, 152, 31) // "averageBandwidthEvery2EmptyTest" }, "TrafficGraphDataTests\0" "simpleCurrentSampleQueueTests\0\0" "accumulationCurrentSampleQueueTests\0" "getRangeTests\0switchRangeTests\0" "clearTests\0averageBandwidthTest\0" "averageBandwidthEvery2EmptyTest" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_TrafficGraphDataTests[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 7, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 49, 2, 0x08 /* Private */, 3, 0, 50, 2, 0x08 /* Private */, 4, 0, 51, 2, 0x08 /* Private */, 5, 0, 52, 2, 0x08 /* Private */, 6, 0, 53, 2, 0x08 /* Private */, 7, 0, 54, 2, 0x08 /* Private */, 8, 0, 55, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, 0 // eod }; void TrafficGraphDataTests::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { TrafficGraphDataTests *_t = static_cast<TrafficGraphDataTests *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->simpleCurrentSampleQueueTests(); break; case 1: _t->accumulationCurrentSampleQueueTests(); break; case 2: _t->getRangeTests(); break; case 3: _t->switchRangeTests(); break; case 4: _t->clearTests(); break; case 5: _t->averageBandwidthTest(); break; case 6: _t->averageBandwidthEvery2EmptyTest(); break; default: ; } } Q_UNUSED(_a); } const QMetaObject TrafficGraphDataTests::staticMetaObject = { { &QObject::staticMetaObject, qt_meta_stringdata_TrafficGraphDataTests.data, qt_meta_data_TrafficGraphDataTests, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *TrafficGraphDataTests::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *TrafficGraphDataTests::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_TrafficGraphDataTests.stringdata0)) return static_cast<void*>(const_cast< TrafficGraphDataTests*>(this)); return QObject::qt_metacast(_clname); } int TrafficGraphDataTests::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 7) qt_static_metacall(this, _c, _id, _a); _id -= 7; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 7) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 7; } return _id; } QT_END_MOC_NAMESPACE
c5353f6de4006432d3af3ada2c58f35bf13c826a
7a36a0652fe0704b4b27f644653e7b0f7e72060f
/TianShan/StreamService/StreamPumper/SsStreamEventCenter.cpp
ead59cc000b12b93bcbda44f4c9d42715d68d550
[]
no_license
darcyg/CXX
1ee13c1765f1987e293c15b9cbc51ae625ac3a2e
ef288ad0e1624ed0582839f2a5a0ef66073d415e
refs/heads/master
2020-04-06T04:27:11.940141
2016-12-29T03:49:56
2016-12-29T03:49:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,135
cpp
#include <math.h> #include <TianShanIceHelper.h> #include "SsStreamImpl.h" #include "EventSender.h" #include "SsServiceImpl.h" #ifdef ZQ_OS_MSWIN #include "memoryDebug.h" #endif #if defined ZQ_OS_MSWIN #define PLFMT(x,y) "%s/%08X/SsPlaylist[%16s]\t"##y,ident.name.c_str(),GetCurrentThreadId(),#x #else #define PLFMT(x,y) "%s/%08X/SsPlaylist[%16s] "y,ident.name.c_str(),pthread_self(),#x #endif namespace ZQ { namespace StreamService { void SsStreamImpl::fillEventData( EventData& data , Ice::Int seq , Ice::Int type ) { data.playlistId = ident; TianShanIce::Streamer::PlaylistExPrx plPrx = UCKGETOBJECT(TianShanIce::Streamer::PlaylistExPrx,ident); data.playlistProxyString = env->getCommunicator()->proxyToString(plPrx); data.eventSeq = seq; data.eventType = type; } void SsStreamImpl::fireItemSteppedMsg( constIter itFrom , constIter itTo , Ice::Int curItemOffset ,const TianShanIce::Properties& props ) {//because every time this method invoked , SsStreamImpl must be locked // so no new lock is needed if( itFrom == itTo ) return; ENVLOG(ZQ::common::Log::L_INFO,PLFMT(fireItemSteppedMsg, "firing ItemStepped from [%s][%u] to [%s][%d]: %s"), iterValid(itFrom) ? itFrom->setupInfo.contentName.c_str() :"", iterValid(itFrom) ? itFrom->userCtrlNum : TianShanIce::Streamer::InvalidCtrlNum , iterValid(itTo) ? itTo->setupInfo.contentName.c_str() :"", iterValid(itTo) ? itTo->userCtrlNum : TianShanIce::Streamer::InvalidCtrlNum , ZQTianShan::Util::dumpStringMap(props).c_str()); Ice::Int itemSteppedSeq = 0 ; ZQTianShan::Util::getPropertyDataWithDefault( property , EVENT_ITEMSTEP_EVENT_SEQ , -1 , itemSteppedSeq ); ++itemSteppedSeq; ZQTianShan::Util::updatePropertyData(property , EVENT_ITEMSTEP_EVENT_SEQ , itemSteppedSeq ); EventData data; data.eventProp = props; fillEventData( data , itemSteppedSeq , ICE_EVENT_TYPE_ITEMSETPPED); ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_ITEMSTEP_EVENT_SEQ , itemSteppedSeq ); ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_ITEMSTEP_ITEM_PREV_CTRLNUM , (iterValid(itFrom) ? itFrom->userCtrlNum : TianShanIce::Streamer::InvalidCtrlNum) ); ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_ITEMSTEP_ITEM_CUR_CTRLNUM , iterValid(itTo) ? itTo->userCtrlNum : TianShanIce::Streamer::InvalidCtrlNum ); ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_ITEMSTEP_PREV_ITEM_NAME , iterValid(itFrom) ? itFrom->setupInfo.contentName : "" ); ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_ITEMSTEP_NEXT_ITEM_NAME , iterValid(itTo) ? itTo->setupInfo.contentName : "" ); ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_ITEMSTEP_TIME_STAMP_UTC , ZQTianShan::Util::getNowOfUTC() ); //if( iterValid(itFrom)) { ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_ITEMSTEP_PREV_ITEM_PID , getPID(itFrom) ); ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_ITEMSTEP_PREV_ITEM_PAID , getPAID(itFrom) ); ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_ITEMSTEP_PREV_STREAMSOURCE , getLastURL(itFrom)); } //if( iterValid(itTo)) { ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_ITEMSTEP_CUR_ITEM_PID , getPID( itTo )); ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_ITEMSTEP_CUR_ITEM_PAID , getPAID(itTo) ); ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_ITEMSTEP_CUR_STREAMSOURCE , getLastURL(itTo)); } ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_ITEMSTEP_CLSUTERID , env->getConfig().iClusterId ); ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_ITEMSTEP_ITEM_CUR_TIMEOFFSET , curItemOffset ); #pragma message(__MSGLOC__"TODO: how to generate a cluster ID ?") serviceImpl.getEventSender().postEvent(data); } void SsStreamImpl::firePlaylistDoneMsg( const TianShanIce::Properties& props ) { ENVLOG(ZQ::common::Log::L_INFO,PLFMT(firePlaylistDoneMsg,"firing StreamCompleted: %s"), ZQTianShan::Util::dumpStringMap(props).c_str()); Ice::Int itemStreamCompletedSeq = 0 ; ZQTianShan::Util::getPropertyDataWithDefault( property , EVENT_STREAM_COMPLETE_EVENT_SEQ , -1 , itemStreamCompletedSeq ); ++itemStreamCompletedSeq; ZQTianShan::Util::updatePropertyData( property , EVENT_STREAM_COMPLETE_EVENT_SEQ , itemStreamCompletedSeq ); EventData data; data.eventProp = props; ZQTianShan::Util::updateValueMapData( data.eventData , EVENT_STREAM_COMPLETE_EVENT_SEQ , itemStreamCompletedSeq ); #pragma message(__MSGLOC__"TODO: get the sender and send out the event") if( isReverseStreaming() ) { fillEventData( data , itemStreamCompletedSeq , ICE_EVENT_TYPE_BEGINOFSTREAM); } else { //get total time duration Ice::Long lTotal = calculateDuration( iterFirstItem() , iterLastItem() ); std::ostringstream oss;oss<<lTotal; ZQTianShan::Util::updateValueMapData( data.eventData ,EVENT_STREAM_COMPLETE_TIMEOFFSET , oss.str() ); fillEventData( data , itemStreamCompletedSeq , ICE_EVENT_TYPE_ENDOFSTREAM); } serviceImpl.getEventSender().postEvent(data); } void SsStreamImpl::fireScaleChangedMsg( const Ice::Float& scaleOld , const Ice::Float& scaleNew ,const TianShanIce::Properties& props ) { if( fabs(scaleNew - scaleOld ) < 0.001) { if( !( (env->getConfig().iSupportPlaylist != LIB_SUPPORT_NORMAL_PLAYLIST) && env->getConfig().iPassSGScaleChangeEvent ) ) return; } ENVLOG(ZQ::common::Log::L_INFO, PLFMT(fireScaleChangedMsg,"firing ScaleChanged from [%f]to [%f]: %s"), scaleOld , scaleNew , ZQTianShan::Util::dumpStringMap(props).c_str()); Ice::Int itemScaleChangedSeq = 0 ; ZQTianShan::Util::getPropertyDataWithDefault( property , EVENT_SPEEDCHANGE_EVENT_SEQ , -1 , itemScaleChangedSeq ); ++itemScaleChangedSeq; ZQTianShan::Util::updatePropertyData( property , EVENT_SPEEDCHANGE_EVENT_SEQ , itemScaleChangedSeq ); EventData data; data.eventProp = props; fillEventData(data,itemScaleChangedSeq,ICE_EVENT_TYPE_SPEEDCHANGE); ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_SPEEDCHANGE_PREV_SPEED , scaleOld ); ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_SPEEDCHANGE_CUR_SPEED , scaleNew ); serviceImpl.getEventSender().postEvent(data); } void SsStreamImpl::fireStateChangedMsg( const TianShanIce::Streamer::StreamState& stateOld , const TianShanIce::Streamer::StreamState& stateNew, const TianShanIce::Properties& props ) { if( (stateOld == stateNew )) { if( !( (env->getConfig().iSupportPlaylist != LIB_SUPPORT_NORMAL_PLAYLIST) && env->getConfig().iPassSGStateChangeEvent ) ) return; } ENVLOG(ZQ::common::Log::L_INFO, PLFMT(fireStateChangedMsg, "firing StateChanged from [%s] to [%s]: %s"), ZQTianShan::Util::dumpTianShanStreamState( stateOld ), ZQTianShan::Util::dumpTianShanStreamState( stateNew ), ZQTianShan::Util::dumpStringMap(props).c_str() ); Ice::Int itemStateChangedSeq = 0 ; ZQTianShan::Util::getPropertyDataWithDefault( property , EVENT_STATECHANGE_EVENTSEQ , -1 , itemStateChangedSeq ); ++itemStateChangedSeq; ZQTianShan::Util::updatePropertyData(property , EVENT_STATECHANGE_EVENTSEQ , itemStateChangedSeq ); EventData data; data.eventProp = props; fillEventData(data , itemStateChangedSeq , ICE_EVENT_TYPE_STATECHANGE ); ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_STATECHANGE_PREV_STATE , static_cast<Ice::Int>(stateOld)); ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_STATECHANGE_CUR_STATE , static_cast<Ice::Int>(stateNew)); serviceImpl.getEventSender().postEvent(data); } void SsStreamImpl::fireProgressMsg( constIter it , const Ice::Long& curTimeOffset , const Ice::Long& totalDuration ,const TianShanIce::Properties& props ) { if( !iterValid(it)) return; #ifdef _DEBUG ENVLOG(ZQ::common::Log::L_DEBUG,PLFMT(fireProgressMsg, "ctrlNum[%d] current[%lld] total[%lld]"), it->userCtrlNum, curTimeOffset , totalDuration ); #endif EventData data; data.eventProp = props; Ice::Int itemProgressSeq = 0 ; ZQTianShan::Util::getPropertyDataWithDefault( property , EVENT_SPEEDCHANGE_EVENT_SEQ , -1 , itemProgressSeq ); ++itemProgressSeq; fillEventData(data, itemProgressSeq , ICE_EVENT_TYPE_PROGRESS ); ZQTianShan::Util::updatePropertyData( property , EVENT_SPEEDCHANGE_EVENT_SEQ , itemProgressSeq ); ZQTianShan::Util::updateValueMapData( data.eventData , EVENT_PROGRESS_ITEM_EVENT_SEQ , itemProgressSeq ); ZQTianShan::Util::updateValueMapData( data.eventData , EVENT_PROGRESS_ITEM_NAME , it->setupInfo.contentName ); ZQTianShan::Util::updateValueMapData( data.eventData , EVENT_PROGRESS_ITEM_CTRL_NUM , it->userCtrlNum ); ZQTianShan::Util::updateValueMapData( data.eventData , EVENT_PROGRESS_ITEM_STEP_TOTAL , size() ); ZQTianShan::Util::updateValueMapData( data.eventData , EVENT_PROGRESS_ITEM_STEP_CURRENT , static_cast<Ice::Int>( it - iterFirstItem() ) ); ZQTianShan::Util::updateValueMapData( data.eventData , EVENT_PROGRESS_ITEM_PROGRESS_TOTAL , static_cast<Ice::Int>(totalDuration)); ZQTianShan::Util::updateValueMapData( data.eventData , EVENT_PROGRESS_ITEM_PROGRESS_DONE , static_cast<Ice::Int>(curTimeOffset) ); serviceImpl.getEventSender().postEvent(data); } void SsStreamImpl::firePlaylistDestroyMsg( constIter it , const Ice::Int& code , const std::string& reason ,const TianShanIce::Properties& props ) { ENVLOG(ZQ::common::Log::L_INFO,PLFMT(firePlaylistDestroyMsg,"firing PlaylistDestroyed: %s"), ZQTianShan::Util::dumpStringMap(props).c_str()); EventData data; data.eventProp = props; fillEventData(data, 0 , ICE_EVENT_TYPE_PLAYLISTDESTROY ); ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_PLDESTROY_EXITCODE , code ); ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_PLDESTROY_EXIT_REASON , reason ); ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_PLDESTROY_CLUSTERID , env->getConfig().iClusterId ); if( iterValid(it) && isItemStreaming(it) ) { ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_PLDESTROY_EXITONPLAYING , static_cast<Ice::Int>(1) ); ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_PLDESTROY_EXIT_PID , getPID(it)); ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_PLDESTROY_EXIT_PAID , getPAID(it)); ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_PLDESTROY_EXIT_STREAMINGSOURCE , getLastURL(it)); ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_PLDESTROY_EVENT_TIMESTAMP , ZQTianShan::Util::getNowOfUTC()); } else { ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_PLDESTROY_EXITONPLAYING , static_cast<Ice::Int>(0) ); ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_PLDESTROY_EXIT_PID , std::string("")); ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_PLDESTROY_EXIT_PAID , std::string("")); ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_PLDESTROY_EXIT_STREAMINGSOURCE , std::string("")); ZQTianShan::Util::updateValueMapData(data.eventData , EVENT_PLDESTROY_EVENT_TIMESTAMP , ZQTianShan::Util::getNowOfUTC()); } #pragma message(__MSGLOC__"TODO: how to generate a cluster ID ?") serviceImpl.getEventSender().postEvent(data); } } }
9f2b1408637748cb7e737e077653dcd181c4c1d3
13f78c34e80a52442d72e0aa609666163233e7e0
/Codeforces/Practice/1466 - Goodbye 2020/E.cpp
325980f24ffb7dcb55703ce0a9e53e1084939454
[]
no_license
Giantpizzahead/comp-programming
0d16babe49064aee525d78a70641ca154927af20
232a19fdd06ecef7be845c92db38772240a33e41
refs/heads/master
2023-08-17T20:23:28.693280
2023-08-11T22:18:26
2023-08-11T22:18:26
252,904,746
2
0
null
null
null
null
UTF-8
C++
false
false
1,402
cpp
#include <bits/stdc++.h> #define rep(i, a, b) for (int i = (a); i < (b); i++) #define all(x) x.begin(), x.end() #define sz(x) (int) (x.size()) using namespace std; using ll = long long; using vi = vector<int>; const int MAXN = 5e5+5; const int MAXB = 61; const ll MOD = 1e9+7; int N; int onBits[MAXB]; ll X[MAXN]; void solve() { rep(i, 0, MAXB) onBits[i] = 0; cin >> N; rep(i, 0, N) { cin >> X[i]; rep(j, 0, MAXB) { if (X[i] & (1LL << j)) onBits[j]++; } } ll ans = 0; rep(i, 0, N) { ll sumAnd = 0, sumOr = 0; rep(j, 0, MAXB) { bool currOn = X[i] & (1LL << j); if (currOn) { // Update AND sum ll toAdd = (1LL << j) % MOD * onBits[j] % MOD; sumAnd = (sumAnd + toAdd) % MOD; } // Update OR sum if (!currOn) { ll toAdd = (1LL << j) % MOD * onBits[j] % MOD; sumOr = (sumOr + toAdd) % MOD; } else { // This makes everything work ll toAdd = (1LL << j) % MOD * N % MOD; sumOr = (sumOr + toAdd) % MOD; } } ans = (ans + sumAnd * sumOr) % MOD; } cout << ans << endl; } int main() { ios::sync_with_stdio(false); cin.tie(NULL); int T; cin >> T; rep(i, 0, T) solve(); return 0; }
88588468273c5a6cded249c2cde6d2f058427301
f3548c394c87e21167c25d66add239b48ad71236
/N64 Programs/BTImageMods/AssemblyInfo.cpp
58c8c526dd80d89182c1facbdb9b52cabe1ff570
[]
no_license
petermuller/old-google-code-projects
10248ab69f56565174f7a7e9e586c68a5256b57b
995dbc1080ec5951c5ca4a58bbd5ada62c2f2883
refs/heads/master
2021-01-16T18:30:41.152202
2015-04-17T14:20:16
2015-04-17T14:20:16
34,120,159
0
0
null
null
null
null
UTF-8
C++
false
false
1,362
cpp
#include "stdafx.h" using namespace System; using namespace System::Reflection; using namespace System::Runtime::CompilerServices; using namespace System::Runtime::InteropServices; using namespace System::Security::Permissions; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly:AssemblyTitleAttribute("banjotooieimagemods")]; [assembly:AssemblyDescriptionAttribute("")]; [assembly:AssemblyConfigurationAttribute("")]; [assembly:AssemblyCompanyAttribute("Room")]; [assembly:AssemblyProductAttribute("banjotooieimagemods")]; [assembly:AssemblyCopyrightAttribute("Copyright (c) Room 2011")]; [assembly:AssemblyTrademarkAttribute("")]; [assembly:AssemblyCultureAttribute("")]; // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the value or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly:AssemblyVersionAttribute("1.0.*")]; [assembly:ComVisible(false)]; [assembly:CLSCompliantAttribute(true)]; [assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)];
986480275851d5f00ec3e5c32b7770f2facba622
ccecc4b46f6e678be6dade0755c26a5cabe68691
/baseOOP.cpp
add1360da02f1505ef0112709d648ccfcbbfea3e
[]
no_license
macovv/basicOOP
f20ebb24ee34686e70ea65548660f6d9b75dc9a9
52f5cc56a16769538dc2ff9d7c38c9ab7398a264
refs/heads/master
2021-09-01T20:19:13.796054
2017-12-28T15:26:27
2017-12-28T15:26:27
115,634,069
0
0
null
null
null
null
UTF-8
C++
false
false
482
cpp
//============================================================================ // Name : heloCPP.cpp // Author : szymon // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include "animal.h" int main() { Animal a("meow meow", "cat", 3, 10, 2); Animal *x = new Monkey(a,2); x->getInfo(); delete x; return 0; }
70704fbaa3529b33d85eb2184be2ff21983834bc
e897d4e94cbb3a982ee249422950a3f6926f433c
/Lab/Lab 1 - June 20, 2016/HelloWorld/main.cpp
78a3d91f84e08c35e7a65d5c17299a489965c68a
[]
no_license
L-Elyse/csc5_2016
61344a201378deacd98ccd7a40061d11517a173a
10ec3627142d8b4a650c1c90faf08ede8a434759
refs/heads/master
2021-01-20T18:28:50.706767
2016-07-31T06:36:04
2016-07-31T06:36:04
61,777,500
0
0
null
null
null
null
UTF-8
C++
false
false
547
cpp
/* * File: main.cpp * Author: Laurie Guimont * Created on June 20, 2016, 12:27 PM * Purpose: First Program */ //System Libraries #include <iostream>//Input/Output Stream Library using namespace std;//Iostream uses the standard namespace //User Libraries //Global Constants //Function Prototypes //Execution Begins Here! int main(int argc, char** argv) { //Declare variables, no doubles //Input data //Process data //Output data cout<<"Hello World"<<endl; //Exit Stage Right! return 0; }
651525cf265c6ff438063a2a4cec8dbf55d0c8f9
e52e582103083884bbb4df04ebe93662dd68f754
/src/integral.h
f37c9bbfc010c8ee226fb3d7dfc017f27073c349
[]
no_license
vanever/mainode
07fbb51d88897be282d765f994a2e247f2b2b4ba
4e5194fa51de8e3676ef2cd273c45eefbc35873f
refs/heads/master
2020-06-02T01:02:15.766757
2013-12-15T13:30:06
2013-12-15T13:30:06
15,203,223
1
0
null
null
null
null
GB18030
C++
false
false
3,270
h
/*********************************************************** * --- OpenSURF --- * * This library is distributed under the GNU GPL. Please * * use the contact form at http://www.chrisevansdev.com * * for more information. * * * * C. Evans, Research Into Robust Visual Features, * * MSc University of Bristol, 2008. * * * ************************************************************/ #ifndef INTEGRAL_H #define INTEGRAL_H //#include <algorithm> // std::min/max //#include <boost/move/move.hpp> // GrayImage提供了move支持,需要编译器支持C++11 //#include "utils.h" // undefine VS macros #ifdef min #undef min #endif #ifdef max #undef max #endif static const int INTSCALE = 256; template<typename T> class Image { public: Image() : width_(0), height_(0), data_(0) {} Image(int w, int h) : width_(w), height_(h), data_(new T[w*h]) {} // Image(Image&& x) : data_(x.data_), width_(x.width_), height_(x.height_) // { x.data_ = 0; } ~Image() { delete[] data_; } // Image& operator = (Image&& x) { // if (&x == this) return *this; // delete[] data_; // width_ = x.width_; // height_ = x.height_; // data_ = x.data_; // x.data_ = 0; // } void reset(int w, int h) { width_ = w; height_ = h; delete[] data_; data_ = new T[w*h]; } int width() const { return width_; } int height() const { return height_; } int size() const { return width_ * height_; } bool operator!() const { return size() == 0; } // test image validation T operator()(int row, int col) const { return pixel(row, col); } // get the pixel T& operator()(int row, int col) { return pixel(row, col); } // get/set the pixel protected: T pixel(int row, int col) const { return data_[row * width_ + col]; } // get the pixel T& pixel(int row, int col) { return data_[row * width_ + col]; } // get/set the pixel T* data_; // Pointer to image data private: int width_; // Image width in pixels int height_; // Image height in pixels }; struct _IplImage; typedef struct _IplImage IplImage; class GrayImage : public Image<unsigned char> { public: GrayImage() {} GrayImage(const IplImage* img) { init(img); } GrayImage(const char* file_name) { load(file_name); } void init(const IplImage* img); void load(const char* file_name); }; struct IntImage : Image<int> { // Integral image IntImage() {} IntImage(const GrayImage& src) { init(src); } void init(const GrayImage& src); int at(int r, int c) const { // get the pixel with bound check if (r < 0 || c < 0) return 0; if (r >= height()) r = height() - 1; if (c >= width()) c = width() - 1; return pixel(r, c); } int BoxIntegral(int row, int col, int rows, int cols) const { // The subtraction by one for row/col is because row/col is inclusive. int r1 = row - 1; int c1 = col - 1; int r2 = row + rows - 1; int c2 = col + cols - 1; return at(r1, c1) - at(r1, c2) - at(r2, c1) + at(r2, c2); } }; #endif
[ "fudan@n047.(none)" ]
fudan@n047.(none)
a7700aa085122fd73113924730e182f3b654083d
24ce9871325e27a64e2abb1de59b433a5d5a84f9
/Palindrome.cpp
35033cf8231f5b61a7a81a1b95c3fb6a528fea1a
[]
no_license
s0gek1ng/Recursion_Practice
f67b29adaf4423909954477e6168f9e4826b5c62
770c6a44edade49fa6e04316e27911a416361171
refs/heads/master
2020-08-27T21:09:28.197392
2019-11-15T10:24:45
2019-11-15T10:24:45
217,488,628
0
0
null
null
null
null
UTF-8
C++
false
false
726
cpp
#include<bits/stdc++.h> using namespace std; int pow(int a,int b){ int x; if(b==1) return a; if(b==0) return 1; if(b%2==0){ int x=pow(a,b/2); return x*x; } else{ x=pow(a,b/2); return a*x*x; } } int length(int n){ int r=n,len=0; while(r){ r=r/10; len++; } return len; } bool isPalin(int n,int len){ if(len==0||len==1) return true; int x=n%10; int y=n/pow(10,len-1); if(x==y) return isPalin((n/10)%pow(10,len-2),len-2); else return false; } int main(){ int n ; cin>>n; int len=length(n); cout<<isPalin(n,len); return 0; }
036e2361f313a3a0a3fa37a674c72259437c1e74
c9182868337b71d3d4a7eb9726ff729cdc95be9c
/Mines/tests/main.cpp
46d427f7e2dc7fe480463e6bf26676c9d6898c39
[]
no_license
mtripsky/Mines-commandLine
dbb951d4d93ca7cc61379cae99841d50598b9499
f14adfb9ef9c8708074ae6968b71a884accc590c
refs/heads/master
2020-05-05T12:09:36.405029
2019-04-20T08:55:56
2019-04-20T08:55:56
180,016,266
0
0
null
2019-04-20T08:55:57
2019-04-07T19:55:40
C++
UTF-8
C++
false
false
425
cpp
// // main.cpp // MinesTests // // Created by Matej Tripsky on 06/04/2019. // Copyright © 2019 Matej Tripsky. All rights reserved. // #define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file #include "libs/catch.hpp" #include "Board/BoardStateTests.cpp" #include "Board/MinesGeneratorTests.cpp" #include "Board/BoardUpdaterTests.cpp" #include "Game/AvalancheGeneratorTests.cpp"
523d2bf148acfbee42f99b1b437e87a651fe05d6
474ca3fbc2b3513d92ed9531a9a99a2248ec7f63
/ThirdParty/boost_1_63_0/libs/hana/example/not_equal.cpp
9499730bced6fdd831f6d1a9c6237de6612ac35f
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
LazyPlanet/MX-Architecture
17b7b2e6c730409b22b7f38633e7b1f16359d250
732a867a5db3ba0c716752bffaeb675ebdc13a60
refs/heads/master
2020-12-30T15:41:18.664826
2018-03-02T00:59:12
2018-03-02T00:59:12
91,156,170
4
0
null
2018-02-04T03:29:46
2017-05-13T07:05:52
C++
UTF-8
C++
false
false
680
cpp
// Copyright Louis Dionne 2013-2016 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) #include <boost/hana/all_of.hpp> #include <boost/hana/assert.hpp> #include <boost/hana/not_equal.hpp> #include <boost/hana/tuple.hpp> namespace hana = boost::hana; int main() { static_assert(hana::not_equal(hana::make_tuple(1, 2), hana::make_tuple(3)), ""); static_assert(hana::not_equal('x', 'y'), ""); BOOST_HANA_CONSTANT_CHECK(hana::not_equal(hana::make_tuple(1, 2), 'y')); static_assert(hana::all_of(hana::make_tuple(1, 2, 3), hana::not_equal.to(5)), ""); }
4d5e59f5c73dbd8e16971b1060ec99e37c453961
fae79bd82acc883def6505b1bbc1c6ccae7a5114
/main.cpp
c16be246f09d81ea1112ecbf53391ca02479ae52
[]
no_license
ITCarlow-ElecEng-CompProg/assignment-14-tyglik
550fb9015f47cb519b006d388bee6823480ba517
c01d94306c9a8378f294ac6194d50c9fe12f0490
refs/heads/master
2021-09-05T06:28:22.349266
2018-01-24T20:15:27
2018-01-24T20:15:27
112,204,240
0
0
null
null
null
null
UTF-8
C++
false
false
5,646
cpp
/** Lab 14 - File Processing * Martina Nunvarova * 24/01/2018 * * * To process input file, calculate and display min,max,avg,sdev to user * To allow user to specify to sort data in ascending or descending order (not specified how) * To save sorted data in a file. * * User input through command line - parametre: * file.exe ASC * file.exe dEScendingDont care what follows the first letter */ ///includes #include <iostream> #include <fstream> #include <math.h> ///sqrt ///namespace using namespace std; ///compare function for ascending choice bool isGreaterThan(double a,double b) { return a>b; } ///compare function for descending choice bool isLeserThan(double a,double b) { return isGreaterThan(b,a); } ///main function - expects parametres int main(int argc, char *argv[]) { ///variables ofstream oF; ifstream iF; int nrCount=0,i,j; string line; double *nrList; ///need dynamic array - don't know the size of input - not given! double n,minN,maxN,avgN=0,stdD=0; bool (*compare)(double a, double b); ///pointer to sorting function - faster than "if (choice='A') else" ///inform user: 1) you can run this with a parametre; if (argc<2) cout <<"To change the sorting, run this program with a parametre."<<endl <<"None or incorrect choice defaults to Ascending order."<<endl<<endl << ":/> Lab14-FileSort.exe [ A(scending) | D(escending) ]"<<endl<<endl <<"**********************************************************"<<endl; ///inform user: 2) I'm working on it cout <<"Processing file:"<<endl; ///open input file; iF.open("rawValues.txt"); ///find how many numbers (lines) we deal with while (getline(iF,line)) { ///let the user know about the progress if (! (nrCount%100000)) ///every 100000 records display a dot cout <<"."; nrCount++; ///while counting the rows (numerical entries) } // iF.seekg(0); ///reset position in fire - return to beginning - does not seem to work iF.close(); ///close the file iF.open("rawValues.txt"); ///and open again (alternative to iF.seekg()) nrList=new double[nrCount]; ///create an array of required size if (nrList == NULL) { ///If you failed cout <<endl<< "Error creating the array!"<<endl<<endl; ///let the user know return 1; ///and exit to OS with return code 1 } ///find min, max, avg i=0; while (!iF.eof() && i<nrCount) { /// repeat until you hit the end of file, but no more than the space in the array iF >>nrList[i]; ///and read in all the numbers if (i==0) { minN=nrList[i]; ///just assign the >>first<< number to be both min and max maxN=nrList[i]; } else { if (minN>nrList[i]) ///any other number is compared and if min or max then remembered as such minN=nrList[i]; if (maxN<nrList[i]) maxN=nrList[i]; } avgN+=nrList[i]; ///sum the numbers for average if (! (i%100000)) ///Let the user know something is happening cout <<"."; ///every 100000 records display a dot i++; } iF.close(); ///finished with the input file, close it. avgN/=nrCount; ///turn sum into average for (i=0;i<nrCount-1;i++) stdD+=(nrList[i]-avgN)*(nrList[i]-avgN); /// SUM( (x - xbar)^2 ) stdD=sqrt(stdD/(nrCount-1)); ///last step to obtain std deviation ///inform the user and print the statistical values - on screen only cout <<endl<< "Input file is processed. "<<endl <<"**********************************************************"<<endl<<endl << "Statistics:"<<endl <<"Min: "<<minN<<" Max: "<<maxN<<" Avg: "<<avgN<<endl <<"Std.Dev.: "<<stdD<<endl<<endl; ///find out if user made a choice in sorting, and if it d if (argc>1 && argv[1] && (argv[1][0]=='d' ||argv[1][0]=='D')) compare = &isLeserThan; ///select the sorting function according to user choice else compare = &isGreaterThan; ///sort the array for (i=0;i<nrCount-1;i++) for (j=i+1;j<nrCount;j++) if (compare(nrList[i],nrList[j])) { ///number in beginning is larger than the one near end? n=nrList[i]; ///so SWAP THEM nrList[i]=nrList[j]; nrList[j]=n; } ///print the sorted array into file oF.open("sortedValues.txt"); ///open the output file for (i=0;i<nrCount;i++) { oF<<nrList[i]<<endl; ///write all the array (numbers) into it // cout << nrList[i]<<endl; ///and on screen for debug } oF.close(); ///then close the file delete [] nrList; ///free the array from memory return 0; ///return to OS, no errors }
3d7087facb607b6085df7ed4fb656437378fd2c7
394b3d93cfa9c17fd6f63b2a7e9e5e7b5d7da006
/Range Queries/Sparse Table/lcm_of_array.cpp
13a955ac6eac05071ab3fad1c51967f5a8e7ef97
[]
no_license
RavinderChoudhary/Practice
8daa2205b05dbf31c518f1812e7673a97529171d
535e31d2854b675d03160779fd145f76c7b74835
refs/heads/main
2023-02-27T14:42:13.002571
2021-01-24T10:28:37
2021-01-24T10:28:37
324,501,875
0
0
null
null
null
null
UTF-8
C++
false
false
929
cpp
#include <bits/stdc++.h> using namespace std; const int k = 16; const int N = 1e5; long long table[N][k + 1]; int lcm(int a,int b){ return (a*b)/__gcd(a,b); } void buildSparseTable(vector<int> arr, int n) { for (int j = 0; j < n; j++) table[0][j] = arr[j]; for (int ws = 1; ws <= k; ws++) { for (int j = 0; j <= n - (1 << ws); j++) { int window_size = 1 << (ws - 1); table[ws][j] = lcm(table[ws-1][j],table[ws - 1][j + window_size]); } } } long long query(int L, int R) { long long answer = 1; for (int i = k; i >= 0; i--) { if (L + pow(2,i) - 1 <= R) { answer = lcm(answer,table[i][L]); L += 1 << i; } } return answer; } int main() { vector<int> arr = {5, 7, 5, 2, 10, 12 ,11, 17, 14, 1, 44 }; int n = arr.size(); buildSparseTable(arr, n); cout << query(2, 5) << endl; cout << query(5, 10) << endl; cout << query(0, 10) << endl; return 0; }
f5618efc4d15fe4530af7300380590f5615adbbf
7902ccb347ede9ca064eb35aa6685a1eb23cc50e
/mainwindow.h
5f081dd46ae4971c904afeca17bfb89fb2a61659
[]
no_license
rubencg195/TecsysImportacion
2a560ec765b8e15ee16e1bf53e7f6adeb2797daf
9de5f4f2034b5949360618dcf0612cdf87239e07
refs/heads/master
2021-01-17T07:40:04.444611
2017-06-24T17:31:22
2017-06-24T17:31:22
95,312,821
0
0
null
null
null
null
UTF-8
C++
false
false
1,859
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QMessageBox> #include <QDebug> #include <QDir> #include <QFile> #include <QStringList> #include <QGroupBox> #include <QHBoxLayout> #include <QList> #include <QTextEdit> #include <QLabel> #include <QListView> #include <QStringListModel> #include <QModelIndex> #include <QTime> #include <QEventLoop> #include <QCoreApplication> #include <QAxObject> #include <QStandardItemModel> #include <QStandardItem> #include "generictype.h" #include <QMapIterator> //NETWORK #include <QObject> #include <QByteArray> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> //BASE DE DATOS #include <QSqlDatabase> #include <QSqlQuery> #include <QSqlRecord> #include <QSqlError> #include <QMap> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); void msg(QString title, QString msg); void import(QString fileName, int sheetNumber); const static int KG = 0; const static int PDS = 1; const static int CM3 = 2; const static int M3 = 3; const static int P3 = 4; const static int AIR = 0; const static int SEA = 1; void calcVol(bool modular, int noParts, float d, float w, float h, int typeDimension,int typeInput, int typeOutput, int transport, QWidget *output); float conVol(int typeInput, int typeOutput, float value); //DATABASE bool createConnection(); QSqlDatabase m_db; QStringListModel *model_add; QStringListModel *model_ignore; QString DBdir = "tecsys.sqlite"; QStandardItemModel *model; static int getKG(); static void setKG(int value); private slots: void on_pushButton_config_clicked(); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
459204e4b920e56248fa39581d370b81dedc9033
72ca3c783d4946c361c7adc1ee0e728a46337d5b
/configs/RscTrafficLight.cpp
1eda14f5ff8d212e353220071f731a59fb1ae9ae
[]
no_license
pennyworth12345/ContactConfigCompare
bedad3c99a097509aa2fe676a07f6e3850b62aec
e871366e36c80ad339aaab512b87b69bfe323040
refs/heads/master
2020-07-03T17:49:12.394661
2019-08-12T19:15:33
2019-08-12T19:15:33
201,992,619
2
1
null
null
null
null
UTF-8
C++
false
false
681
cpp
class RscTrafficLight: RscActiveText { color[] = {1, 1, 1, 0.7}; colorActive[] = {1, 1, 1, 1}; colorText[] = {1, 1, 1, 0.7}; h = "1 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)"; style = 48; text = "\A3\Ui_f\data\GUI\RscCommon\RscTrafficLight\TrafficLight_ca.paa"; tooltip = "You are running a modded version of the game. Click to see the list of active mods."; w = "1 * ( ((safezoneW / safezoneH) min 1.2) / 40)"; x = "SafezoneX + SafezoneW - (2 * ( ((safezoneW / safezoneH) min 1.2) / 40))"; y = "23 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) + (safezoneY + safezoneH - ( ((safezoneW / safezoneH) min 1.2) / 1.2))"; };
6df2296c6357984a4a91c7c8c1f3bd182e6a9cd6
c74da5fcb9ca1460752078375e48a4ce8562e7d1
/src/utils/SkShadowUtils.cpp
8374aef68f164843f48a8ee3adb6c2663f5c092c
[ "BSD-3-Clause" ]
permissive
rikxqd/skia
850c86c7cad93789bdbe518e45fe036afe83ce60
ef653b86b2a9cf9e0793a647e5990806bdbd6934
refs/heads/master
2021-01-20T14:10:27.421143
2017-02-21T18:50:00
2017-02-21T22:56:00
82,746,385
1
0
null
2017-02-22T01:30:45
2017-02-22T01:30:45
null
UTF-8
C++
false
false
20,785
cpp
/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkShadowUtils.h" #include "SkCanvas.h" #include "SkColorFilter.h" #include "SkPath.h" #include "SkRandom.h" #include "SkResourceCache.h" #include "SkShadowTessellator.h" #include "SkTLazy.h" #include "SkVertices.h" #if SK_SUPPORT_GPU #include "GrShape.h" #include "effects/GrBlurredEdgeFragmentProcessor.h" #endif /** * Gaussian color filter -- produces a Gaussian ramp based on the color's B value, * then blends with the color's G value. * Final result is black with alpha of Gaussian(B)*G. * The assumption is that the original color's alpha is 1. */ class SK_API SkGaussianColorFilter : public SkColorFilter { public: static sk_sp<SkColorFilter> Make() { return sk_sp<SkColorFilter>(new SkGaussianColorFilter); } void filterSpan(const SkPMColor src[], int count, SkPMColor dst[]) const override; #if SK_SUPPORT_GPU sk_sp<GrFragmentProcessor> asFragmentProcessor(GrContext*, SkColorSpace*) const override; #endif SK_TO_STRING_OVERRIDE() SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkGaussianColorFilter) protected: void flatten(SkWriteBuffer&) const override {} private: SkGaussianColorFilter() : INHERITED() {} typedef SkColorFilter INHERITED; }; void SkGaussianColorFilter::filterSpan(const SkPMColor src[], int count, SkPMColor dst[]) const { for (int i = 0; i < count; ++i) { SkPMColor c = src[i]; SkScalar factor = SK_Scalar1 - SkGetPackedB32(c) / 255.f; factor = SkScalarExp(-factor * factor * 4) - 0.018f; SkScalar a = factor * SkGetPackedG32(c); dst[i] = SkPackARGB32(a, a, a, a); } } sk_sp<SkFlattenable> SkGaussianColorFilter::CreateProc(SkReadBuffer&) { return Make(); } #ifndef SK_IGNORE_TO_STRING void SkGaussianColorFilter::toString(SkString* str) const { str->append("SkGaussianColorFilter "); } #endif #if SK_SUPPORT_GPU sk_sp<GrFragmentProcessor> SkGaussianColorFilter::asFragmentProcessor(GrContext*, SkColorSpace*) const { return GrBlurredEdgeFP::Make(GrBlurredEdgeFP::kGaussian_Mode); } #endif /////////////////////////////////////////////////////////////////////////////////////////////////// namespace { /** Factory for an ambient shadow mesh with particular shadow properties. */ struct AmbientVerticesFactory { SkScalar fRadius = SK_ScalarNaN; // NaN so that isCompatible will always fail until init'ed. SkColor fUmbraColor; SkColor fPenumbraColor; bool fTransparent; bool isCompatible(const AmbientVerticesFactory& that, SkVector* translate) const { if (fRadius != that.fRadius || fUmbraColor != that.fUmbraColor || fPenumbraColor != that.fPenumbraColor || fTransparent != that.fTransparent) { return false; } translate->set(0, 0); return true; } sk_sp<SkVertices> makeVertices(const SkPath& path, const SkMatrix& ctm) const { return SkShadowTessellator::MakeAmbient(path, ctm, fRadius, fUmbraColor, fPenumbraColor, fTransparent); } }; /** Factory for an spot shadow mesh with particular shadow properties. */ struct SpotVerticesFactory { enum class OccluderType { // The umbra cannot be dropped out because the occluder is not opaque. kTransparent, // The umbra can be dropped where it is occluded. kOpaque, // It is known that the entire umbra is occluded. kOpaqueCoversUmbra }; SkScalar fRadius = SK_ScalarNaN; // NaN so that isCompatible will always fail until init'ed. SkColor fUmbraColor; SkColor fPenumbraColor; SkScalar fScale; SkVector fOffset; OccluderType fOccluderType; bool isCompatible(const SpotVerticesFactory& that, SkVector* translate) const { if (fRadius != that.fRadius || fUmbraColor != that.fUmbraColor || fPenumbraColor != that.fPenumbraColor || fOccluderType != that.fOccluderType || fScale != that.fScale) { return false; } switch (fOccluderType) { case OccluderType::kTransparent: case OccluderType::kOpaqueCoversUmbra: // 'this' and 'that' will either both have no umbra removed or both have all the // umbra removed. *translate = that.fOffset - fOffset; return true; case OccluderType::kOpaque: // In this case we partially remove the umbra differently for 'this' and 'that' // if the offsets don't match. if (fOffset == that.fOffset) { translate->set(0, 0); return true; } return false; } SkFAIL("Uninitialized occluder type?"); return false; } sk_sp<SkVertices> makeVertices(const SkPath& path, const SkMatrix& ctm) const { bool transparent = OccluderType::kTransparent == fOccluderType; return SkShadowTessellator::MakeSpot(path, ctm, fScale, fOffset, fRadius, fUmbraColor, fPenumbraColor, transparent); } }; /** * This manages a set of tessellations for a given shape in the cache. Because SkResourceCache * records are immutable this is not itself a Rec. When we need to update it we return this on * the FindVisitor and let the cache destory the Rec. We'll update the tessellations and then add * a new Rec with an adjusted size for any deletions/additions. */ class CachedTessellations : public SkRefCnt { public: size_t size() const { return fAmbientSet.size() + fSpotSet.size(); } sk_sp<SkVertices> find(const AmbientVerticesFactory& ambient, const SkMatrix& matrix, SkVector* translate) const { return fAmbientSet.find(ambient, matrix, translate); } sk_sp<SkVertices> add(const SkPath& devPath, const AmbientVerticesFactory& ambient, const SkMatrix& matrix) { return fAmbientSet.add(devPath, ambient, matrix); } sk_sp<SkVertices> find(const SpotVerticesFactory& spot, const SkMatrix& matrix, SkVector* translate) const { return fSpotSet.find(spot, matrix, translate); } sk_sp<SkVertices> add(const SkPath& devPath, const SpotVerticesFactory& spot, const SkMatrix& matrix) { return fSpotSet.add(devPath, spot, matrix); } private: template <typename FACTORY, int MAX_ENTRIES> class Set { public: size_t size() const { return fSize; } sk_sp<SkVertices> find(const FACTORY& factory, const SkMatrix& matrix, SkVector* translate) const { for (int i = 0; i < MAX_ENTRIES; ++i) { if (fEntries[i].fFactory.isCompatible(factory, translate)) { const SkMatrix& m = fEntries[i].fMatrix; if (matrix.hasPerspective() || m.hasPerspective()) { if (matrix != fEntries[i].fMatrix) { continue; } } else if (matrix.getScaleX() != m.getScaleX() || matrix.getSkewX() != m.getSkewX() || matrix.getScaleY() != m.getScaleY() || matrix.getSkewY() != m.getSkewY()) { continue; } *translate += SkVector{matrix.getTranslateX() - m.getTranslateX(), matrix.getTranslateY() - m.getTranslateY()}; return fEntries[i].fVertices; } } return nullptr; } sk_sp<SkVertices> add(const SkPath& path, const FACTORY& factory, const SkMatrix& matrix) { sk_sp<SkVertices> vertices = factory.makeVertices(path, matrix); if (!vertices) { return nullptr; } int i; if (fCount < MAX_ENTRIES) { i = fCount++; } else { i = gRandom.nextULessThan(MAX_ENTRIES); fSize -= fEntries[i].fVertices->size(); } fEntries[i].fFactory = factory; fEntries[i].fVertices = vertices; fEntries[i].fMatrix = matrix; fSize += vertices->size(); return vertices; } private: struct Entry { FACTORY fFactory; sk_sp<SkVertices> fVertices; SkMatrix fMatrix; }; Entry fEntries[MAX_ENTRIES]; int fCount = 0; size_t fSize = 0; }; Set<AmbientVerticesFactory, 4> fAmbientSet; Set<SpotVerticesFactory, 4> fSpotSet; static SkRandom gRandom; }; SkRandom CachedTessellations::gRandom; /** * A record of shadow vertices stored in SkResourceCache of CachedTessellations for a particular * path. The key represents the path's geometry and not any shadow params. */ class CachedTessellationsRec : public SkResourceCache::Rec { public: CachedTessellationsRec(const SkResourceCache::Key& key, sk_sp<CachedTessellations> tessellations) : fTessellations(std::move(tessellations)) { fKey.reset(new uint8_t[key.size()]); memcpy(fKey.get(), &key, key.size()); } const Key& getKey() const override { return *reinterpret_cast<SkResourceCache::Key*>(fKey.get()); } size_t bytesUsed() const override { return fTessellations->size(); } const char* getCategory() const override { return "tessellated shadow masks"; } sk_sp<CachedTessellations> refTessellations() const { return fTessellations; } template <typename FACTORY> sk_sp<SkVertices> find(const FACTORY& factory, const SkMatrix& matrix, SkVector* translate) const { return fTessellations->find(factory, matrix, translate); } private: std::unique_ptr<uint8_t[]> fKey; sk_sp<CachedTessellations> fTessellations; }; /** * Used by FindVisitor to determine whether a cache entry can be reused and if so returns the * vertices and a translation vector. If the CachedTessellations does not contain a suitable * mesh then we inform SkResourceCache to destroy the Rec and we return the CachedTessellations * to the caller. The caller will update it and reinsert it back into the cache. */ template <typename FACTORY> struct FindContext { FindContext(const SkMatrix* viewMatrix, const FACTORY* factory) : fViewMatrix(viewMatrix), fFactory(factory) {} const SkMatrix* const fViewMatrix; // If this is valid after Find is called then we found the vertices and they should be drawn // with fTranslate applied. sk_sp<SkVertices> fVertices; SkVector fTranslate = {0, 0}; // If this is valid after Find then the caller should add the vertices to the tessellation set // and create a new CachedTessellationsRec and insert it into SkResourceCache. sk_sp<CachedTessellations> fTessellationsOnFailure; const FACTORY* fFactory; }; /** * Function called by SkResourceCache when a matching cache key is found. The FACTORY and matrix of * the FindContext are used to determine if the vertices are reusable. If so the vertices and * necessary translation vector are set on the FindContext. */ template <typename FACTORY> bool FindVisitor(const SkResourceCache::Rec& baseRec, void* ctx) { FindContext<FACTORY>* findContext = (FindContext<FACTORY>*)ctx; const CachedTessellationsRec& rec = static_cast<const CachedTessellationsRec&>(baseRec); findContext->fVertices = rec.find(*findContext->fFactory, *findContext->fViewMatrix, &findContext->fTranslate); if (findContext->fVertices) { return true; } // We ref the tessellations and let the cache destroy the Rec. Once the tessellations have been // manipulated we will add a new Rec. findContext->fTessellationsOnFailure = rec.refTessellations(); return false; } class ShadowedPath { public: ShadowedPath(const SkPath* path, const SkMatrix* viewMatrix) : fPath(path) , fViewMatrix(viewMatrix) #if SK_SUPPORT_GPU , fShapeForKey(*path, GrStyle::SimpleFill()) #endif {} const SkPath& path() const { return *fPath; } const SkMatrix& viewMatrix() const { return *fViewMatrix; } #if SK_SUPPORT_GPU /** Negative means the vertices should not be cached for this path. */ int keyBytes() const { return fShapeForKey.unstyledKeySize() * sizeof(uint32_t); } void writeKey(void* key) const { fShapeForKey.writeUnstyledKey(reinterpret_cast<uint32_t*>(key)); } bool isRRect(SkRRect* rrect) { return fShapeForKey.asRRect(rrect, nullptr, nullptr, nullptr); } #else int keyBytes() const { return -1; } void writeKey(void* key) const { SkFAIL("Should never be called"); } bool isRRect(SkRRect* rrect) { return false; } #endif private: const SkPath* fPath; const SkMatrix* fViewMatrix; #if SK_SUPPORT_GPU GrShape fShapeForKey; #endif }; // This creates a domain of keys in SkResourceCache used by this file. static void* kNamespace; /** * Draws a shadow to 'canvas'. The vertices used to draw the shadow are created by 'factory' unless * they are first found in SkResourceCache. */ template <typename FACTORY> void draw_shadow(const FACTORY& factory, SkCanvas* canvas, ShadowedPath& path, SkColor color) { FindContext<FACTORY> context(&path.viewMatrix(), &factory); SkResourceCache::Key* key = nullptr; SkAutoSTArray<32 * 4, uint8_t> keyStorage; int keyDataBytes = path.keyBytes(); if (keyDataBytes >= 0) { keyStorage.reset(keyDataBytes + sizeof(SkResourceCache::Key)); key = new (keyStorage.begin()) SkResourceCache::Key(); path.writeKey((uint32_t*)(keyStorage.begin() + sizeof(*key))); key->init(&kNamespace, 0, keyDataBytes); SkResourceCache::Find(*key, FindVisitor<FACTORY>, &context); } sk_sp<SkVertices> vertices; const SkVector* translate; static constexpr SkVector kZeroTranslate = {0, 0}; bool foundInCache = SkToBool(context.fVertices); if (foundInCache) { vertices = std::move(context.fVertices); translate = &context.fTranslate; } else { // TODO: handle transforming the path as part of the tessellator if (key) { // Update or initialize a tessellation set and add it to the cache. sk_sp<CachedTessellations> tessellations; if (context.fTessellationsOnFailure) { tessellations = std::move(context.fTessellationsOnFailure); } else { tessellations.reset(new CachedTessellations()); } vertices = tessellations->add(path.path(), factory, path.viewMatrix()); if (!vertices) { return; } SkResourceCache::Add(new CachedTessellationsRec(*key, std::move(tessellations))); } else { vertices = factory.makeVertices(path.path(), path.viewMatrix()); if (!vertices) { return; } } translate = &kZeroTranslate; } SkPaint paint; // Run the vertex color through a GaussianColorFilter and then modulate the grayscale result of // that against our 'color' param. paint.setColorFilter(SkColorFilter::MakeComposeFilter( SkColorFilter::MakeModeFilter(color, SkBlendMode::kModulate), SkGaussianColorFilter::Make())); if (translate->fX || translate->fY) { canvas->save(); canvas->translate(translate->fX, translate->fY); } canvas->drawVertices(vertices, SkBlendMode::kModulate, paint); if (translate->fX || translate->fY) { canvas->restore(); } } } static const float kHeightFactor = 1.0f / 128.0f; static const float kGeomFactor = 64.0f; // Draw an offset spot shadow and outlining ambient shadow for the given path. void SkShadowUtils::DrawShadow(SkCanvas* canvas, const SkPath& path, SkScalar occluderHeight, const SkPoint3& devLightPos, SkScalar lightRadius, SkScalar ambientAlpha, SkScalar spotAlpha, SkColor color, uint32_t flags) { SkAutoCanvasRestore acr(canvas, true); SkMatrix viewMatrix = canvas->getTotalMatrix(); canvas->resetMatrix(); ShadowedPath shadowedPath(&path, &viewMatrix); bool transparent = SkToBool(flags & SkShadowFlags::kTransparentOccluder_ShadowFlag); if (ambientAlpha > 0) { ambientAlpha = SkTMin(ambientAlpha, 1.f); AmbientVerticesFactory factory; factory.fRadius = occluderHeight * kHeightFactor * kGeomFactor; SkScalar umbraAlpha = SkScalarInvert((1.0f + SkTMax(occluderHeight*kHeightFactor, 0.0f))); // umbraColor is the interior value, penumbraColor the exterior value. // umbraAlpha is the factor that is linearly interpolated from outside to inside, and // then "blurred" by the GrBlurredEdgeFP. It is then multiplied by fAmbientAlpha to get // the final alpha. factory.fUmbraColor = SkColorSetARGB(255, 0, ambientAlpha * 255.9999f, umbraAlpha * 255.9999f); factory.fPenumbraColor = SkColorSetARGB(255, 0, ambientAlpha * 255.9999f, 0); factory.fTransparent = transparent; draw_shadow(factory, canvas, shadowedPath, color); } if (spotAlpha > 0) { spotAlpha = SkTMin(spotAlpha, 1.f); SpotVerticesFactory factory; float zRatio = SkTPin(occluderHeight / (devLightPos.fZ - occluderHeight), 0.0f, 0.95f); factory.fRadius = lightRadius * zRatio; // Compute the scale and translation for the spot shadow. factory.fScale = devLightPos.fZ / (devLightPos.fZ - occluderHeight); SkPoint center = SkPoint::Make(path.getBounds().centerX(), path.getBounds().centerY()); viewMatrix.mapPoints(&center, 1); factory.fOffset = SkVector::Make(zRatio * (center.fX - devLightPos.fX), zRatio * (center.fY - devLightPos.fY)); factory.fUmbraColor = SkColorSetARGB(255, 0, spotAlpha * 255.9999f, 255); factory.fPenumbraColor = SkColorSetARGB(255, 0, spotAlpha * 255.9999f, 0); SkRRect rrect; if (transparent) { factory.fOccluderType = SpotVerticesFactory::OccluderType::kTransparent; } else { factory.fOccluderType = SpotVerticesFactory::OccluderType::kOpaque; if (shadowedPath.isRRect(&rrect)) { SkRRect devRRect; if (rrect.transform(viewMatrix, &devRRect)) { SkScalar s = 1.f - factory.fScale; SkScalar w = devRRect.width(); SkScalar h = devRRect.height(); SkScalar hw = w / 2.f; SkScalar hh = h / 2.f; SkScalar umbraInsetX = s * hw + factory.fRadius; SkScalar umbraInsetY = s * hh + factory.fRadius; // The umbra is inset by radius along the diagonal, so adjust for that. SkScalar d = 1.f / SkScalarSqrt(hw * hw + hh * hh); umbraInsetX *= hw * d; umbraInsetY *= hh * d; if (umbraInsetX > hw || umbraInsetY > hh) { // There is no umbra to occlude. factory.fOccluderType = SpotVerticesFactory::OccluderType::kTransparent; } else if (fabsf(factory.fOffset.fX) < umbraInsetX && fabsf(factory.fOffset.fY) < umbraInsetY) { factory.fOccluderType = SpotVerticesFactory::OccluderType::kOpaqueCoversUmbra; } else if (factory.fOffset.fX > w - umbraInsetX || factory.fOffset.fY > h - umbraInsetY) { // There umbra is fully exposed, there is nothing to omit. factory.fOccluderType = SpotVerticesFactory::OccluderType::kTransparent; } } } } if (factory.fOccluderType == SpotVerticesFactory::OccluderType::kOpaque) { factory.fOccluderType = SpotVerticesFactory::OccluderType::kTransparent; } draw_shadow(factory, canvas, shadowedPath, color); } }
644992a30b7591f976f3c46d6f7bf54dbbb696ef
51cafea84e0e2c2e6c28ac5fe80f2f6e5154f86c
/Classes/MiscSupport.h
3388db9d6f83d03f185850789d295b50e1fc12e7
[]
no_license
khibong/Tech4_StickHeroGo
3468ac6248a253435290489c0ba0bcba3290f840
e68a83f4e2cd98f0087b132979e44c4ecb6d4156
refs/heads/master
2020-07-10T22:34:49.551766
2019-07-31T10:38:31
2019-07-31T10:38:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
266
h
#pragma once #include"cocos2d.h" USING_NS_CC; class MiscSupport { protected: Size m_visibleSize; Vec2 m_origin; public: MiscSupport() { m_visibleSize = Director::getInstance()->getVisibleSize(); m_origin = Director::getInstance()->getVisibleOrigin(); } };
5d402e53803f2c4d09071f413249b5a7ca80577f
f30c0e27de2a45621d4e7dd9432c64923eaf3775
/src/core/SkLiteRecorder.cpp
93251f9e627c72cefc32e8e693f7f0a46abca6ea
[ "BSD-3-Clause" ]
permissive
ruscur/skia
b4892c5ddd2ed42fd94c732168954c28efa69a4f
af1d050dcd74aed9c96428d8b37a2a5c38107883
refs/heads/master
2021-01-17T20:56:00.387119
2016-09-08T04:12:02
2016-09-12T05:07:26
67,666,849
0
0
null
2016-09-08T03:57:48
2016-09-08T03:57:47
null
UTF-8
C++
false
false
8,927
cpp
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkLiteDL.h" #include "SkLiteRecorder.h" #include "SkSurface.h" SkLiteRecorder::SkLiteRecorder() : SkCanvas({0,0,1,1}, SkCanvas::kConservativeRasterClip_InitFlag) , fDL(nullptr) {} void SkLiteRecorder::reset(SkLiteDL* dl) { this->resetForNextPicture(dl->getBounds().roundOut()); fDL = dl; } sk_sp<SkSurface> SkLiteRecorder::onNewSurface(const SkImageInfo&, const SkSurfaceProps&) { return nullptr; } #ifdef SK_SUPPORT_LEGACY_DRAWFILTER SkDrawFilter* SkLiteRecorder::setDrawFilter(SkDrawFilter* df) { fDL->setDrawFilter(df); return SkCanvas::setDrawFilter(df); } #endif void SkLiteRecorder::willSave() { fDL->save(); } SkCanvas::SaveLayerStrategy SkLiteRecorder::getSaveLayerStrategy(const SaveLayerRec& rec) { fDL->saveLayer(rec.fBounds, rec.fPaint, rec.fBackdrop, rec.fSaveLayerFlags); return SkCanvas::kNoLayer_SaveLayerStrategy; } void SkLiteRecorder::willRestore() { fDL->restore(); } void SkLiteRecorder::didConcat (const SkMatrix& matrix) { fDL-> concat(matrix); } void SkLiteRecorder::didSetMatrix(const SkMatrix& matrix) { fDL->setMatrix(matrix); } void SkLiteRecorder::didTranslate(SkScalar dx, SkScalar dy) { fDL->translate(dx, dy); } void SkLiteRecorder::onClipRect(const SkRect& rect, SkRegion::Op op, ClipEdgeStyle style) { fDL->clipRect(rect, op, style==kSoft_ClipEdgeStyle); } void SkLiteRecorder::onClipRRect(const SkRRect& rrect, SkRegion::Op op, ClipEdgeStyle style) { fDL->clipRRect(rrect, op, style==kSoft_ClipEdgeStyle); } void SkLiteRecorder::onClipPath(const SkPath& path, SkRegion::Op op, ClipEdgeStyle style) { fDL->clipPath(path, op, style==kSoft_ClipEdgeStyle); } void SkLiteRecorder::onClipRegion(const SkRegion& region, SkRegion::Op op) { fDL->clipRegion(region, op); } void SkLiteRecorder::onDrawPaint(const SkPaint& paint) { fDL->drawPaint(paint); } void SkLiteRecorder::onDrawPath(const SkPath& path, const SkPaint& paint) { fDL->drawPath(path, paint); } void SkLiteRecorder::onDrawRect(const SkRect& rect, const SkPaint& paint) { fDL->drawRect(rect, paint); } void SkLiteRecorder::onDrawRegion(const SkRegion& region, const SkPaint& paint) { fDL->drawRegion(region, paint); } void SkLiteRecorder::onDrawOval(const SkRect& oval, const SkPaint& paint) { fDL->drawOval(oval, paint); } void SkLiteRecorder::onDrawArc(const SkRect& oval, SkScalar startAngle, SkScalar sweepAngle, bool useCenter, const SkPaint& paint) { fDL->drawArc(oval, startAngle, sweepAngle, useCenter, paint); } void SkLiteRecorder::onDrawRRect(const SkRRect& rrect, const SkPaint& paint) { fDL->drawRRect(rrect, paint); } void SkLiteRecorder::onDrawDRRect(const SkRRect& out, const SkRRect& in, const SkPaint& paint) { fDL->drawDRRect(out, in, paint); } void SkLiteRecorder::onDrawDrawable(SkDrawable* drawable, const SkMatrix* matrix) { fDL->drawDrawable(drawable, matrix); } void SkLiteRecorder::onDrawPicture(const SkPicture* picture, const SkMatrix* matrix, const SkPaint* paint) { fDL->drawPicture(picture, matrix, paint); } void SkLiteRecorder::onDrawAnnotation(const SkRect& rect, const char key[], SkData* val) { fDL->drawAnnotation(rect, key, val); } void SkLiteRecorder::onDrawText(const void* text, size_t bytes, SkScalar x, SkScalar y, const SkPaint& paint) { fDL->drawText(text, bytes, x, y, paint); } void SkLiteRecorder::onDrawPosText(const void* text, size_t bytes, const SkPoint pos[], const SkPaint& paint) { fDL->drawPosText(text, bytes, pos, paint); } void SkLiteRecorder::onDrawPosTextH(const void* text, size_t bytes, const SkScalar xs[], SkScalar y, const SkPaint& paint) { fDL->drawPosTextH(text, bytes, xs, y, paint); } void SkLiteRecorder::onDrawTextOnPath(const void* text, size_t bytes, const SkPath& path, const SkMatrix* matrix, const SkPaint& paint) { fDL->drawTextOnPath(text, bytes, path, matrix, paint); } void SkLiteRecorder::onDrawTextRSXform(const void* text, size_t bytes, const SkRSXform xform[], const SkRect* cull, const SkPaint& paint) { fDL->drawTextRSXform(text, bytes, xform, cull, paint); } void SkLiteRecorder::onDrawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y, const SkPaint& paint) { fDL->drawTextBlob(blob, x,y, paint); } void SkLiteRecorder::onDrawBitmap(const SkBitmap& bm, SkScalar x, SkScalar y, const SkPaint* paint) { fDL->drawBitmap(bm, x,y, paint); } void SkLiteRecorder::onDrawBitmapNine(const SkBitmap& bm, const SkIRect& center, const SkRect& dst, const SkPaint* paint) { fDL->drawBitmapNine(bm, center, dst, paint); } void SkLiteRecorder::onDrawBitmapRect(const SkBitmap& bm, const SkRect* src, const SkRect& dst, const SkPaint* paint, SrcRectConstraint constraint) { fDL->drawBitmapRect(bm, src, dst, paint, constraint); } void SkLiteRecorder::onDrawBitmapLattice(const SkBitmap& bm, const SkCanvas::Lattice& lattice, const SkRect& dst, const SkPaint* paint) { fDL->drawBitmapLattice(bm, lattice, dst, paint); } void SkLiteRecorder::onDrawImage(const SkImage* img, SkScalar x, SkScalar y, const SkPaint* paint) { fDL->drawImage(img, x,y, paint); } void SkLiteRecorder::onDrawImageNine(const SkImage* img, const SkIRect& center, const SkRect& dst, const SkPaint* paint) { fDL->drawImageNine(img, center, dst, paint); } void SkLiteRecorder::onDrawImageRect(const SkImage* img, const SkRect* src, const SkRect& dst, const SkPaint* paint, SrcRectConstraint constraint) { fDL->drawImageRect(img, src, dst, paint, constraint); } void SkLiteRecorder::onDrawImageLattice(const SkImage* img, const SkCanvas::Lattice& lattice, const SkRect& dst, const SkPaint* paint) { fDL->drawImageLattice(img, lattice, dst, paint); } void SkLiteRecorder::onDrawPatch(const SkPoint cubics[12], const SkColor colors[4], const SkPoint texCoords[4], SkXfermode* xfermode, const SkPaint& paint) { fDL->drawPatch(cubics, colors, texCoords, xfermode, paint); } void SkLiteRecorder::onDrawPoints(SkCanvas::PointMode mode, size_t count, const SkPoint pts[], const SkPaint& paint) { fDL->drawPoints(mode, count, pts, paint); } void SkLiteRecorder::onDrawVertices(SkCanvas::VertexMode mode, int count, const SkPoint vertices[], const SkPoint texs[], const SkColor colors[], SkXfermode* xfermode, const uint16_t indices[], int indexCount, const SkPaint& paint) { fDL->drawVertices(mode, count, vertices, texs, colors, xfermode, indices, indexCount, paint); } void SkLiteRecorder::onDrawAtlas(const SkImage* atlas, const SkRSXform xforms[], const SkRect texs[], const SkColor colors[], int count, SkXfermode::Mode xfermode, const SkRect* cull, const SkPaint* paint) { fDL->drawAtlas(atlas, xforms, texs, colors, count, xfermode, cull, paint); } void SkLiteRecorder::didTranslateZ(SkScalar dz) { fDL->translateZ(dz); } void SkLiteRecorder::onDrawShadowedPicture(const SkPicture* picture, const SkMatrix* matrix, const SkPaint* paint, const SkShadowParams& params) { fDL->drawShadowedPicture(picture, matrix, paint, params); }
fa6e03d93bba42bca2229377c95283491f17e52b
27fbce7c075cd9f4cee7e1250e82cd56a7699c02
/tao/x11/object_loader.cpp
49adc1e6f7e5f6a6e4bc6cdbf0607ad05556b9bb
[ "MIT" ]
permissive
jwillemsen/taox11
fe11af6a7185c25d0f236b80c608becbdbf3c8c3
f16805cfdd5124d93d2426094191f15e10f53123
refs/heads/master
2023-09-04T18:23:46.570811
2023-08-14T19:50:01
2023-08-14T19:50:01
221,247,177
0
0
MIT
2023-09-04T14:53:28
2019-11-12T15:14:26
C++
UTF-8
C++
false
false
262
cpp
/** * @file object_loader.cpp * @author Marcel Smit * * @brief CORBA C++11 ORB core * * @copyright Copyright (c) Remedy IT Expertise BV */ #include "tao/x11/object_loader.h" namespace TAOX11_NAMESPACE { Object_Loader::~Object_Loader () { } }
3fbd82e7dafcc08cb845f31ca3b8af572840685e
f6f0f87647e23507dca538760ab70e26415b8313
/6.3.1/msvc2022_64/include/QtCore/6.3.1/QtCore/private/qwindowspipewriter_p.h
3d0cf264e30fb64553db24ee66d79c5302270ff4
[]
no_license
stenzek/duckstation-ext-qt-minimal
a942c62adc5654c03d90731a8266dc711546b268
e5c412efffa3926f7a4d5bf0ae0333e1d6784f30
refs/heads/master
2023-08-17T16:50:21.478373
2023-08-15T14:53:43
2023-08-15T14:53:43
233,179,313
3
1
null
2021-11-16T15:34:28
2020-01-11T05:05:34
C++
UTF-8
C++
false
false
4,206
h
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Copyright (C) 2021 Alex Trotsenko <[email protected]> ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QWINDOWSPIPEWRITER_P_H #define QWINDOWSPIPEWRITER_P_H // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists purely as an // implementation detail. This header file may change from version to // version without notice, or even be removed. // // We mean it. // #include <qobject.h> #include <qmutex.h> #include <private/qringbuffer_p.h> #include <qt_windows.h> QT_BEGIN_NAMESPACE class Q_CORE_EXPORT QWindowsPipeWriter : public QObject { Q_OBJECT public: explicit QWindowsPipeWriter(HANDLE pipeWriteEnd, QObject *parent = nullptr); ~QWindowsPipeWriter(); void setHandle(HANDLE hPipeWriteEnd); void write(const QByteArray &ba); void write(const char *data, qint64 size); void stop(); bool checkForWrite() { return consumePendingAndEmit(false); } qint64 bytesToWrite() const; bool isWriteOperationActive() const; HANDLE syncEvent() const { return syncHandle; } Q_SIGNALS: void bytesWritten(qint64 bytes); void writeFailed(); protected: bool event(QEvent *e) override; private: enum CompletionState { NoError, ErrorDetected, WriteDisabled }; template <typename... Args> inline void writeImpl(Args... args); void startAsyncWriteHelper(QMutexLocker<QMutex> *locker); void startAsyncWriteLocked(); static void CALLBACK waitCallback(PTP_CALLBACK_INSTANCE instance, PVOID context, PTP_WAIT wait, TP_WAIT_RESULT waitResult); bool writeCompleted(DWORD errorCode, DWORD numberOfBytesWritten); void notifyCompleted(QMutexLocker<QMutex> *locker); bool consumePendingAndEmit(bool allowWinActPosting); HANDLE handle; HANDLE eventHandle; HANDLE syncHandle; PTP_WAIT waitObject; OVERLAPPED overlapped; QRingBuffer writeBuffer; qint64 pendingBytesWrittenValue; mutable QMutex mutex; DWORD lastError; CompletionState completionState; bool stopped; bool writeSequenceStarted; bool bytesWrittenPending; bool winEventActPosted; }; QT_END_NAMESPACE #endif // QWINDOWSPIPEWRITER_P_H
55e72bf7bec5a79b8cbfb8a5d78821c873c9deed
e0aeb17e0f04857509b251fe5075f45010383a96
/daemon/daemon-main.hpp
02231258b660ba0a7013cdeee171e0f453083132
[ "MIT" ]
permissive
skatsaounis/dht-chord-simulator
7ddb029ef743ea7c5b2a6926ce542835a51d021c
b8ebcbc58a7e5c39d54c5aaff97f621a90114c2d
refs/heads/master
2021-01-21T07:10:17.630268
2017-03-13T20:49:31
2017-03-13T20:49:31
83,327,286
0
0
null
2017-03-12T15:00:25
2017-02-27T15:46:38
C++
UTF-8
C++
false
false
133
hpp
#ifndef _DSEMU_DAEMON_MAIN_HPP_ #define _DSEMU_DAEMON_MAIN_HPP_ void daemon_main(bool verbose); #endif // _DSEMU_DAEMON_MAIN_HPP_
91400ce5ff9349b8e77193a72cc54b0ea45363f2
082eac8933b1ce8a2e35410226a1a54505a0ca9e
/TriggerBoxSpecificActor/TriggerBoxSpecificActor.h
46c7564674a912b52143012d3b9a01d0be28e2cb
[ "MIT" ]
permissive
CEPBEP/unrealcpp
3926c2ffe19f2f69507f0c812ac96204dde90d3e
9a9829637cf80e0e52f7eb6661615ff3fdefa8d0
refs/heads/master
2020-03-16T17:32:03.590373
2018-05-09T10:06:00
2018-05-09T10:06:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
886
h
// Harrison McGuire // UE4 Version 4.19.0 // https://github.com/Harrison1/unrealcpp // https://severallevels.io // https://harrisonmcguire.com #pragma once #include "CoreMinimal.h" #include "Engine/TriggerBox.h" #include "TriggerBoxSpecificActor.generated.h" UCLASS() class UNREALCPP_API ATriggerBoxSpecificActor : public ATriggerBox { GENERATED_BODY() protected: // Called when the game starts or when spawned virtual void BeginPlay() override; public: // constructor sets default values for this actor's properties ATriggerBoxSpecificActor(); // overlap begin function UFUNCTION() void OnOverlapBegin(class AActor* OverlappedActor, class AActor* OtherActor); // overlap end function UFUNCTION() void OnOverlapEnd(class AActor* OverlappedActor, class AActor* OtherActor); // specific actor for overlap UPROPERTY(EditAnywhere) class AActor* SpecificActor; };
5b17c789bdf350ef1ee017dcb883533e3e544bfa
1b8b93d4489cf852481de79a26807d38c8e08cd6
/Modelowanie/Modelowanie/Particle.h
fd9f704fafd61bfc225bff965c5566dc2e093c27
[]
no_license
alexx1307/MUFB_Projekt
1b9624a5a195da4f635d0afee6e433d5986e820e
2bf384dd366e5e11e3909917ff78b4eaf3e91020
refs/heads/master
2016-09-06T03:10:03.586730
2013-05-28T21:38:53
2013-05-28T21:38:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
480
h
#pragma once #include "Vector.h" class IPhysics; class Particle { static IPhysics physics; double mass; Vector position; Vector force; public: Particle(void); ~Particle(void); static void setPhysics(IPhysics physics); //metoda sluzaca do dodania nowej sily(wypadkowa) void addForce(Vector force); //ustalenie sily na zadana wartosc void setForce(Vector force); //przesuwa czasteczke (jesli jest bulletem) i aktualizuje dzialajaca sile void update(int deltaTime); };
2f9238aa2b045af6e242cabb3a7601b48f264aa8
f4d715360146080fcb06f3c78c6fa2a3efc179e1
/23_new2/GPIO.h
3c5bd967bfda96210e765c614d120fb44da7446a
[]
no_license
slonegd/cppmcu_example
4e1d058b0cecdc54323a121bc1a03e014cb33dd8
d954987fdba33b54e1c4c98b24df73ac2296366d
refs/heads/master
2020-03-26T11:01:14.203753
2019-03-13T13:17:44
2019-03-13T13:17:44
144,824,647
0
0
null
null
null
null
UTF-8
C++
false
false
8,202
h
#pragma once #include "registr.h" #include "stm32f0xx.h" namespace GPIO { struct MODER_t { enum Mode { Input = 0b00, Output, Alternate, Analog }; Mode MODER0 :2; Mode MODER1 :2; Mode MODER2 :2; Mode MODER3 :2; Mode MODER4 :2; Mode MODER5 :2; Mode MODER6 :2; Mode MODER7 :2; Mode MODER8 :2; Mode MODER9 :2; Mode MODER10 :2; Mode MODER11 :2; Mode MODER12 :2; Mode MODER13 :2; Mode MODER14 :2; Mode MODER15 :2; }; struct OTYPER_t { enum OutType {PushPull = 0b0, OpenDrain}; OutType OT0 :1; OutType OT1 :1; OutType OT2 :1; OutType OT3 :1; OutType OT4 :1; OutType OT5 :1; OutType OT6 :1; OutType OT7 :1; OutType OT8 :1; OutType OT9 :1; OutType OT10 :1; OutType OT11 :1; OutType OT12 :1; OutType OT13 :1; OutType OT14 :1; OutType OT15 :1; uint32_t res1 :16; }; struct OSPEEDR_t{ enum OutSpeed { Low = 0b00, Medium, High, #if defined(STM32F4) // задел на будущее VeryHigh #endif }; OutSpeed OSPEEDR0 :2; OutSpeed OSPEEDR1 :2; OutSpeed OSPEEDR2 :2; OutSpeed OSPEEDR3 :2; OutSpeed OSPEEDR4 :2; OutSpeed OSPEEDR5 :2; OutSpeed OSPEEDR6 :2; OutSpeed OSPEEDR7 :2; OutSpeed OSPEEDR8 :2; OutSpeed OSPEEDR9 :2; OutSpeed OSPEEDR10 :2; OutSpeed OSPEEDR11 :2; OutSpeed OSPEEDR12 :2; OutSpeed OSPEEDR13 :2; OutSpeed OSPEEDR14 :2; OutSpeed OSPEEDR15 :2; }; struct PUPDR_t { enum PullResistor { No = 0b00, Up, Down }; PullResistor PUPDR0 :2; PullResistor PUPDR1 :2; PullResistor PUPDR2 :2; PullResistor PUPDR3 :2; PullResistor PUPDR4 :2; PullResistor PUPDR5 :2; PullResistor PUPDR6 :2; PullResistor PUPDR7 :2; PullResistor PUPDR8 :2; PullResistor PUPDR9 :2; PullResistor PUPDR10 :2; PullResistor PUPDR11 :2; PullResistor PUPDR12 :2; PullResistor PUPDR13 :2; PullResistor PUPDR14 :2; PullResistor PUPDR15 :2; }; struct DR_t { // для IDR ODR union { uint32_t reg; struct { bool _0 :1; bool _1 :1; bool _2 :1; bool _3 :1; bool _4 :1; bool _5 :1; bool _6 :1; bool _7 :1; bool _8 :1; bool _9 :1; bool _10 :1; bool _11 :1; bool _12 :1; bool _13 :1; bool _14 :1; bool _15 :1; uint32_t res1 :16; } bits; }; }; struct AFR_t { enum AF { _0 = 0b0000, _1, _2, _3, _4, _5, _6, _7, #if defined(STM32F4) _8, _9, _10, _11, _12, _13, _14, _15 #endif }; AF AFR0 : 4; AF AFR1 : 4; AF AFR2 : 4; AF AFR3 : 4; AF AFR4 : 4; AF AFR5 : 4; AF AFR6 : 4; AF AFR7 : 4; AF AFR8 : 4; AF AFR9 : 4; AF AFR10 : 4; AF AFR11 : 4; AF AFR12 : 4; AF AFR13 : 4; AF AFR14 : 4; AF AFR15 : 4; }; } // namespace GPIO { template<uint32_t adr> struct GPIO_t { __IO GPIO::MODER_t MODER; // mode register, offset: 0x00 __IO GPIO::OTYPER_t OTYPER; // output type register, offset: 0x04 __IO GPIO::OSPEEDR_t OSPEEDR; // output speed register, offset: 0x08 __IO GPIO::PUPDR_t PUPDR; // pull-up/pull-down register, offset: 0x0C __IO GPIO::DR_t IDR; // input data register, offset: 0x10 __IO GPIO::DR_t ODR; // output data register, offset: 0x14 __IO uint32_t BSRR; // bit set/reset register, offset: 0x18 __IO uint32_t LCKR; // configuration lock register, offset: 0x1C __IO GPIO::AFR_t AFR; // alternate function registers, offset: 0x20-0x24 GPIO_t() = delete; static constexpr uint32_t Base = adr; }; enum class PinMode { Input, Output, Alternate_1 }; class Port { __IO GPIO::MODER_t MODER; // mode register, offset: 0x00 __IO GPIO::OTYPER_t OTYPER; // output type register, offset: 0x04 __IO GPIO::OSPEEDR_t OSPEEDR; // output speed register, offset: 0x08 __IO GPIO::PUPDR_t PUPDR; // pull-up/pull-down register, offset: 0x0C __IO GPIO::DR_t IDR; // input data register, offset: 0x10 __IO GPIO::DR_t ODR; // output data register, offset: 0x14 __IO uint32_t BSRR; // bit set/reset register, offset: 0x18 __IO uint32_t LCKR; // configuration lock register, offset: 0x1C __IO GPIO::AFR_t AFR; // alternate function registers, offset: 0x20-0x24 public: using Mode = GPIO::MODER_t ::Mode; using AF = GPIO::AFR_t ::AF; Port() = default; // шаблонный фабричный метод, чтобы получить правильный объект // сам класс не шаблонный, потому его не надо инстанцировать // RCC как параметр шаблона для дальнейшего тестирования этого метода template<Periph p, class RCC = RCC> static Port& make() { // тут же включаем тактирование переферии RCC::make().template clockEnable<p>(); if constexpr (p == Periph::PA) return *reinterpret_cast<Port*>(GPIOA_BASE); else if constexpr (p == Periph::PB) return *reinterpret_cast<Port*>(GPIOB_BASE); else if constexpr (p == Periph::PC) return *reinterpret_cast<Port*>(GPIOC_BASE); else if constexpr (p == Periph::PD) return *reinterpret_cast<Port*>(GPIOD_BASE); else if constexpr (p == Periph::PF) return *reinterpret_cast<Port*>(GPIOF_BASE); } void set (size_t n) { BSRR |= (1 << n); } void clear (size_t n) { BSRR |= (1 << (n + 16)); } bool isSet (size_t n) { return IDR.reg & (1 << n); } void toggle(size_t n) { isSet(n) ? clear(n) : set(n); } // переписываем в шаблонные параметры то, что компилятор не мог соптимизировать template<size_t n> void set (Mode mode) { if constexpr (n == 0) MODER.MODER0 = mode; else if constexpr (n == 1) MODER.MODER1 = mode; else if constexpr (n == 2) MODER.MODER2 = mode; else if constexpr (n == 3) MODER.MODER3 = mode; else if constexpr (n == 4) MODER.MODER4 = mode; else if constexpr (n == 5) MODER.MODER5 = mode; else if constexpr (n == 6) MODER.MODER6 = mode; else if constexpr (n == 7) MODER.MODER7 = mode; else if constexpr (n == 8) MODER.MODER8 = mode; else if constexpr (n == 9) MODER.MODER9 = mode; else if constexpr (n == 10) MODER.MODER10 = mode; else if constexpr (n == 11) MODER.MODER11 = mode; else if constexpr (n == 12) MODER.MODER12 = mode; else if constexpr (n == 13) MODER.MODER13 = mode; else if constexpr (n == 14) MODER.MODER14 = mode; else if constexpr (n == 15) MODER.MODER15 = mode; } template<size_t n> void set (AF af) { if constexpr (n == 0) AFR.AFR0 = af; else if constexpr (n == 1) AFR.AFR1 = af; else if constexpr (n == 2) AFR.AFR2 = af; else if constexpr (n == 3) AFR.AFR3 = af; else if constexpr (n == 4) AFR.AFR4 = af; else if constexpr (n == 5) AFR.AFR5 = af; else if constexpr (n == 6) AFR.AFR6 = af; else if constexpr (n == 7) AFR.AFR7 = af; else if constexpr (n == 8) AFR.AFR8 = af; else if constexpr (n == 9) AFR.AFR9 = af; else if constexpr (n == 10) AFR.AFR10 = af; else if constexpr (n == 11) AFR.AFR11 = af; else if constexpr (n == 12) AFR.AFR12 = af; else if constexpr (n == 13) AFR.AFR13 = af; else if constexpr (n == 14) AFR.AFR14 = af; else if constexpr (n == 15) AFR.AFR15 = af; } template<size_t n, PinMode mode> void init() { if constexpr (mode == PinMode::Input) { set<n> (Mode::Input); } else if constexpr (mode == PinMode::Output) { set<n> (Mode::Output); } else if constexpr (mode == PinMode::Alternate_1) { set<n> (Mode::Alternate); set<n> (AF::_1); } } }; // далее см. pin.h
cfaafe01e9a9a58468f11e6a32738d8d12672d8e
b454e81927970ea26ce565fb7a5f51ac17ad6c5b
/src/engine/PulsecountEngine.cpp
c5318fd66101ddcb3156cc1c9985a87121f8fbf3
[ "BSL-1.0" ]
permissive
aiiyansin/cpp.react
e9d39deeaa705c70c4a31ad48e3d0bb3a2f33ba8
d3b5faa260398105a89580f15c1d752e7d4e9373
refs/heads/master
2022-12-18T06:14:50.152335
2020-10-01T08:14:09
2020-10-01T08:14:09
300,200,154
1
0
BSL-1.0
2020-10-01T08:13:02
2020-10-01T08:13:01
null
UTF-8
C++
false
false
8,355
cpp
// Copyright Sebastian Jeckel 2017. // 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) #if 0 #include "react/engine/PulsecountEngine.h" #include <cstdint> #include <utility> #include "react/common/Types.h" /***************************************/ REACT_IMPL_BEGIN /**************************************/ namespace pulsecount { /////////////////////////////////////////////////////////////////////////////////////////////////// /// Constants /////////////////////////////////////////////////////////////////////////////////////////////////// static const uint chunk_size = 8; static const uint dfs_threshold = 3; /////////////////////////////////////////////////////////////////////////////////////////////////// /// MarkerTask /////////////////////////////////////////////////////////////////////////////////////////////////// class MarkerTask: public task { public: using BufferT = NodeBuffer<Node,chunk_size>; template <typename TInput> MarkerTask(TInput srcBegin, TInput srcEnd) : nodes_( srcBegin, srcEnd ) {} MarkerTask(MarkerTask& other, SplitTag) : nodes_( other.nodes_, SplitTag( ) ) {} task* execute() { uint splitCount = 0; while (! nodes_.IsEmpty()) { Node& node = splitCount > dfs_threshold ? *nodes_.PopBack() : *nodes_.PopFront(); // Increment counter of each successor and add it to smaller stack for (auto* succ : node.Successors) { succ->IncCounter(); // Skip if already marked as reachable if (! succ->ExchangeMark(ENodeMark::visited)) continue; nodes_.PushBack(succ); if (nodes_.IsFull()) { splitCount++; //Delegate half the work to new task auto& t = *new(task::allocate_additional_child_of(*parent())) MarkerTask(*this, SplitTag{}); spawn(t); } } } return nullptr; } private: BufferT nodes_; }; /////////////////////////////////////////////////////////////////////////////////////////////////// /// UpdaterTask /////////////////////////////////////////////////////////////////////////////////////////////////// class UpdaterTask: public task { public: using BufferT = NodeBuffer<Node,chunk_size>; template <typename TInput> UpdaterTask(Turn& turn, TInput srcBegin, TInput srcEnd) : turn_( turn ), nodes_( srcBegin, srcEnd ) {} UpdaterTask(Turn& turn, Node* node) : turn_( turn ), nodes_( node ) {} UpdaterTask(UpdaterTask& other, SplitTag) : turn_( other.turn_ ), nodes_( other.nodes_, SplitTag( ) ) {} task* execute() { uint splitCount = 0; while (!nodes_.IsEmpty()) { Node& node = splitCount > dfs_threshold ? *nodes_.PopBack() : *nodes_.PopFront(); if (node.Mark() == ENodeMark::should_update) node.Tick(&turn_); // Defer if node was dynamically attached to a predecessor that // has not pulsed yet if (node.State == ENodeState::dyn_defer) continue; // Repeat the update if a node was dynamically attached to a // predecessor that has already pulsed while (node.State == ENodeState::dyn_repeat) node.Tick(&turn_); // Mark successors for update? bool update = node.State == ENodeState::changed; node.State = ENodeState::unchanged; {// node.ShiftMutex Node::ShiftMutexT::scoped_lock lock(node.ShiftMutex, false); for (auto* succ : node.Successors) { if (update) succ->SetMark(ENodeMark::should_update); // Delay tick? if (succ->DecCounter()) continue; // Heavyweight - spawn new task if (succ->IsHeavyweight()) { auto& t = *new(task::allocate_additional_child_of(*parent())) UpdaterTask(turn_, succ); spawn(t); } // Leightweight - add to buffer, split if full else { nodes_.PushBack(succ); if (nodes_.IsFull()) { splitCount++; //Delegate half the work to new task auto& t = *new(task::allocate_additional_child_of(*parent())) UpdaterTask(*this, SplitTag{}); spawn(t); } } } node.SetMark(ENodeMark::unmarked); }// ~node.ShiftMutex } return nullptr; } private: Turn& turn_; BufferT nodes_; }; /////////////////////////////////////////////////////////////////////////////////////////////////// /// Turn /////////////////////////////////////////////////////////////////////////////////////////////////// Turn::Turn(TurnIdT id, TransactionFlagsT flags) : TurnBase( id, flags ) {} /////////////////////////////////////////////////////////////////////////////////////////////////// /// PulsecountEngine /////////////////////////////////////////////////////////////////////////////////////////////////// void EngineBase::AttachNode(Node& node, Node& parent) { parent.Successors.Add(node); } void EngineBase::DetachNode(Node& node, Node& parent) { parent.Successors.Remove(node); } void EngineBase::OnInputChange(Node& node, Turn& turn) { changedInputs_.push_back(&node); node.State = ENodeState::changed; } template <typename TTask, typename TIt, typename ... TArgs> void spawnTasks ( task& rootTask, task_list& spawnList, const size_t count, TIt start, TIt end, TArgs& ... args ) { assert(1 + count <= static_cast<size_t>((std::numeric_limits<int>::max)())); rootTask.set_ref_count(1 + static_cast<int>(count)); for (size_t i=0; i < (count - 1); i++) { spawnList.push_back(*new(rootTask.allocate_child()) TTask(args ..., start, start + chunk_size)); start += chunk_size; } spawnList.push_back(*new(rootTask.allocate_child()) TTask(args ..., start, end)); rootTask.spawn_and_wait_for_all(spawnList); spawnList.clear(); } void EngineBase::Propagate(Turn& turn) { const size_t initialTaskCount = (changedInputs_.size() - 1) / chunk_size + 1; spawnTasks<MarkerTask>(rootTask_, spawnList_, initialTaskCount, changedInputs_.begin(), changedInputs_.end()); spawnTasks<UpdaterTask>(rootTask_, spawnList_, initialTaskCount, changedInputs_.begin(), changedInputs_.end(), turn); changedInputs_.clear(); } void EngineBase::OnNodePulse(Node& node, Turn& turn) { node.State = ENodeState::changed; } void EngineBase::OnNodeIdlePulse(Node& node, Turn& turn) { node.State = ENodeState::unchanged; } void EngineBase::OnDynamicNodeAttach(Node& node, Node& parent, Turn& turn) {// parent.ShiftMutex (write) NodeShiftMutexT::scoped_lock lock(parent.ShiftMutex, true); parent.Successors.Add(node); // Has already nudged its neighbors? if (parent.Mark() == ENodeMark::unmarked) { node.State = ENodeState::dyn_repeat; } else { node.State = ENodeState::dyn_defer; node.IncCounter(); node.SetMark(ENodeMark::should_update); } }// ~parent.ShiftMutex (write) void EngineBase::OnDynamicNodeDetach(Node& node, Node& parent, Turn& turn) {// parent.ShiftMutex (write) NodeShiftMutexT::scoped_lock lock(parent.ShiftMutex, true); parent.Successors.Remove(node); }// ~parent.ShiftMutex (write) } // ~namespace pulsecount /****************************************/ REACT_IMPL_END /***************************************/ #endif
9c88a3ea305f5764e5d426ce14a7d024998857cc
6ced41da926682548df646099662e79d7a6022c5
/aws-cpp-sdk-securityhub/include/aws/securityhub/model/AwsRedshiftClusterIamRole.h
1aff1e2ac0132a12c6873691238fd1f3a956defe
[ "Apache-2.0", "MIT", "JSON" ]
permissive
irods/aws-sdk-cpp
139104843de529f615defa4f6b8e20bc95a6be05
2c7fb1a048c96713a28b730e1f48096bd231e932
refs/heads/main
2023-07-25T12:12:04.363757
2022-08-26T15:33:31
2022-08-26T15:33:31
141,315,346
0
1
Apache-2.0
2022-08-26T17:45:09
2018-07-17T16:24:06
C++
UTF-8
C++
false
false
4,871
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/securityhub/SecurityHub_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace SecurityHub { namespace Model { /** * <p>An IAM role that the cluster can use to access other Amazon Web Services * services.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/securityhub-2018-10-26/AwsRedshiftClusterIamRole">AWS * API Reference</a></p> */ class AWS_SECURITYHUB_API AwsRedshiftClusterIamRole { public: AwsRedshiftClusterIamRole(); AwsRedshiftClusterIamRole(Aws::Utils::Json::JsonView jsonValue); AwsRedshiftClusterIamRole& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The status of the IAM role's association with the cluster.</p> <p>Valid * values: <code>in-sync</code> | <code>adding</code> | <code>removing</code> </p> */ inline const Aws::String& GetApplyStatus() const{ return m_applyStatus; } /** * <p>The status of the IAM role's association with the cluster.</p> <p>Valid * values: <code>in-sync</code> | <code>adding</code> | <code>removing</code> </p> */ inline bool ApplyStatusHasBeenSet() const { return m_applyStatusHasBeenSet; } /** * <p>The status of the IAM role's association with the cluster.</p> <p>Valid * values: <code>in-sync</code> | <code>adding</code> | <code>removing</code> </p> */ inline void SetApplyStatus(const Aws::String& value) { m_applyStatusHasBeenSet = true; m_applyStatus = value; } /** * <p>The status of the IAM role's association with the cluster.</p> <p>Valid * values: <code>in-sync</code> | <code>adding</code> | <code>removing</code> </p> */ inline void SetApplyStatus(Aws::String&& value) { m_applyStatusHasBeenSet = true; m_applyStatus = std::move(value); } /** * <p>The status of the IAM role's association with the cluster.</p> <p>Valid * values: <code>in-sync</code> | <code>adding</code> | <code>removing</code> </p> */ inline void SetApplyStatus(const char* value) { m_applyStatusHasBeenSet = true; m_applyStatus.assign(value); } /** * <p>The status of the IAM role's association with the cluster.</p> <p>Valid * values: <code>in-sync</code> | <code>adding</code> | <code>removing</code> </p> */ inline AwsRedshiftClusterIamRole& WithApplyStatus(const Aws::String& value) { SetApplyStatus(value); return *this;} /** * <p>The status of the IAM role's association with the cluster.</p> <p>Valid * values: <code>in-sync</code> | <code>adding</code> | <code>removing</code> </p> */ inline AwsRedshiftClusterIamRole& WithApplyStatus(Aws::String&& value) { SetApplyStatus(std::move(value)); return *this;} /** * <p>The status of the IAM role's association with the cluster.</p> <p>Valid * values: <code>in-sync</code> | <code>adding</code> | <code>removing</code> </p> */ inline AwsRedshiftClusterIamRole& WithApplyStatus(const char* value) { SetApplyStatus(value); return *this;} /** * <p>The ARN of the IAM role.</p> */ inline const Aws::String& GetIamRoleArn() const{ return m_iamRoleArn; } /** * <p>The ARN of the IAM role.</p> */ inline bool IamRoleArnHasBeenSet() const { return m_iamRoleArnHasBeenSet; } /** * <p>The ARN of the IAM role.</p> */ inline void SetIamRoleArn(const Aws::String& value) { m_iamRoleArnHasBeenSet = true; m_iamRoleArn = value; } /** * <p>The ARN of the IAM role.</p> */ inline void SetIamRoleArn(Aws::String&& value) { m_iamRoleArnHasBeenSet = true; m_iamRoleArn = std::move(value); } /** * <p>The ARN of the IAM role.</p> */ inline void SetIamRoleArn(const char* value) { m_iamRoleArnHasBeenSet = true; m_iamRoleArn.assign(value); } /** * <p>The ARN of the IAM role.</p> */ inline AwsRedshiftClusterIamRole& WithIamRoleArn(const Aws::String& value) { SetIamRoleArn(value); return *this;} /** * <p>The ARN of the IAM role.</p> */ inline AwsRedshiftClusterIamRole& WithIamRoleArn(Aws::String&& value) { SetIamRoleArn(std::move(value)); return *this;} /** * <p>The ARN of the IAM role.</p> */ inline AwsRedshiftClusterIamRole& WithIamRoleArn(const char* value) { SetIamRoleArn(value); return *this;} private: Aws::String m_applyStatus; bool m_applyStatusHasBeenSet; Aws::String m_iamRoleArn; bool m_iamRoleArnHasBeenSet; }; } // namespace Model } // namespace SecurityHub } // namespace Aws
56616a1cb246c128b82bbbfc574e82b8ba64e958
b005e76d8f20308335dadc9fd0a5a64e3813d777
/DP/DP_longest_common_subsequence.cpp
ceca4a08edee0044d6ae7a7e0082b93cee85a9da
[]
no_license
saa27/Data-Structures
7951ab0e2cfdb4ff9afb8386f25dcd26570fb49f
8823680b3654917ca637700dd060715815567819
refs/heads/master
2023-06-22T13:30:03.479668
2021-07-10T05:07:48
2021-07-10T05:07:48
280,473,117
0
0
null
null
null
null
UTF-8
C++
false
false
607
cpp
#include <bits/stdc++.h> using namespace std; int max(int a, int b) { return (a > b)? a : b; } int lcs(string x, string y, int a, int b){ int l[a+1][b+1]; int i,j; for(i=0;i<=a;i++){ for(j =0;j<=b;j++){ if(i==0 || j==0) l[i][j] = 0; else if(x[i-1] == y[j-1]) l[i][j] = l[i-1][j-1] + 1; else l[i][j] = max(l[i-1][j],l[i][j-1]); } } return l[a][b]; } int main(){ string x="AGGTAB",y="GXTXAYB"; int a = x.length(); int b = y.length(); cout<<lcs(x,y,a,b); }
28fe4338149ad201090e162a7a40cf7f99765c8b
0add5dd73742d371fb8c2fd0575bde1c9717822d
/Source/GUAO_EveryThing/Private/Characters/GamePawns/Football/FootballSkin.cpp
1b90338533ff1b25dd0a9009f02a141b19a18f78
[]
no_license
GuAoDiao/GUAO_EveryThing
ff56a01085fab74104a92a2ce33928083b268c9d
5dd6415e9649ac0f18b6c2c9e76a9405818e5d8b
refs/heads/master
2020-03-12T13:29:44.860723
2018-06-07T09:45:22
2018-06-07T09:45:22
130,643,541
3
1
null
null
null
null
UTF-8
C++
false
false
394
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "FootballSkin.h" IMPLEMENT_GAMEPAWNSKIN_CLASS("FootballSkin", FFootballSkin); FFootballSkin::FFootballSkin(UStaticMeshComponent* StaticMeshComp) : FRoleSkin(StaticMeshComp) { MaterialNames.Add(TEXT("FootballBlack")); MaterialNames.Add(TEXT("FootballWhite")); LoadAllGameSkinMaterial(); }
9f1c29f018c529dd3668af52e517b5a3777dbadb
2f13cf37f1e63c8f564976cc45d5ebe6a3030baa
/IpFilter.h
53554dc2083e0a1efaa352993908e56303fefa2e
[]
no_license
Pavel-Alyukaev/Otus_ip
544ffd82b2a9d1e005d5ec66444ec6e0ae450b64
51eee6af9f8031ffc7adc68e6162bb917652ca7f
refs/heads/master
2020-12-14T21:40:37.451525
2020-01-29T16:13:01
2020-01-29T16:13:01
234,876,768
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
670
h
#pragma once #include <vector> #include <string> typedef std::vector<std::vector<short> > Pool; class IpFilter { private: Pool m_ipPool; public: IpFilter() {}; ~IpFilter() {}; //Чтение ip адресов void setIpPool(); void loadIpPool(std::istream&& stream); //Печать ip адресов void printIp(const Pool& pool) const; void printIp() const; void saveIp(const Pool& pool, std::ostream& file) const; void saveIp(std::ostream& file) const; void sortIpPool(); Pool filter(std::vector<short> mask1, short mask2 = -1); friend std::vector<std::string> split(const std::string& str, char d); };
5c32cd3ae1550a44fb593867ad54bba10ebc8c99
ff0116e624284d382dca4bb896078b0c1f34fb76
/mainwindow.cpp
c55b870ebf9d645566662ed75170575d2508a031
[]
no_license
RobHSmith/Qt-Based-Traffic-Light-GUI
2a82e0729843e9735e9e2ae3c03b239ec9714821
86fecaf216ca8c455ec4e441b59fe62aec3d8af2
refs/heads/main
2023-08-16T14:04:52.819531
2021-10-18T15:42:25
2021-10-18T15:42:25
416,798,211
0
0
null
null
null
null
UTF-8
C++
false
false
14,738
cpp
#include <QTimer> #include <iostream> #include "mainwindow.h" #include "D:\Graduate\Code Development\build-Combined_UI_v6-Desktop_Qt_6_1_2_MinGW_64_bit-Debug\ui_mainwindow.h" #define NUMTLIGHT 6 //number of traffic lights #define SENSVIEW 200 //distance sensor can see (m) std::vector<int> ptime = {5,6,8,4,4,8}; //global initialization for phase timing - updateCountdown cannot accept inputs, so this is needed MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow){ ui->setupUi(this); //Formatting int countfont = 30; int labelfont = 20; int titlefont = 25; MainWindow::fontsize(ui->countdown,countfont); MainWindow::fontsize(ui->countdown_2,countfont); MainWindow::fontsize(ui->countdown_3,countfont); MainWindow::fontsize(ui->countdown_4,countfont); MainWindow::fontsize(ui->countdown_5,countfont); MainWindow::fontsize(ui->countdown_6,countfont); MainWindow::fontsize(ui->label_1_1,labelfont); MainWindow::fontsize(ui->label_1_2,labelfont); MainWindow::fontsize(ui->label_2_1,labelfont); MainWindow::fontsize(ui->label_2_2,labelfont); MainWindow::fontsize(ui->label_3_1,labelfont); MainWindow::fontsize(ui->label_3_2,labelfont); MainWindow::fontsize(ui->label_4_1,labelfont); MainWindow::fontsize(ui->label_4_2,labelfont); MainWindow::fontsize(ui->label_5_1,labelfont); MainWindow::fontsize(ui->label_5_2,labelfont); MainWindow::fontsize(ui->label_6_1,labelfont); MainWindow::fontsize(ui->label_6_2,labelfont); MainWindow::fontsize(ui->d2light,countfont); MainWindow::fontsize(ui->d2light_2,countfont); MainWindow::fontsize(ui->d2light_3,countfont); MainWindow::fontsize(ui->d2light_4,countfont); MainWindow::fontsize(ui->d2light_5,countfont); MainWindow::fontsize(ui->d2light_6,countfont); MainWindow::fontsize(ui->title1,titlefont); MainWindow::fontsize(ui->title2,titlefont); MainWindow::fontsize(ui->title3,titlefont); MainWindow::fontsize(ui->title4,titlefont); MainWindow::fontsize(ui->title5,titlefont); MainWindow::fontsize(ui->title6,titlefont); //declare number of traffic lights in scope int num = NUMTLIGHT; //initialize vector of pointers for(int m = 0;m < num;m++){ p_shared.push_back(nullptr); } for(int i = 0;i < num;i++){ //Connect Pointer to TrafficLight p_shared[i] = std::make_shared<TrafficLight>(nullptr,i); //Initialize Time time[i].setHMS(0,0,1); } //Only works if tl_widgets set to TrafficLight class - no solution for only extracting tl_widgets //QList<QFrame*> complist1 = ui->centralwidget->findChildren<QFrame*>(QString(),Qt::FindDirectChildrenOnly); //QList<QWidget*> complist2 = ui->centralwidget->findChildren<QWidget*>(QString(),Qt::FindDirectChildrenOnly); //QVector<QFrame*> compvec1 = complist1.toVector(); //QVector<QWidget*> compvec2 = complist2.toVector(); //Initialize countdown displays ui->countdown->setText(time[0].toString("m:ss")); ui->countdown_2->setText(time[1].toString("m:ss")); ui->countdown_3->setText(time[2].toString("m:ss")); ui->countdown_4->setText(time[3].toString("m:ss")); ui->countdown_5->setText(time[4].toString("m:ss")); ui->countdown_6->setText(time[5].toString("m:ss")); //Initialize distance countdown displays ui->d2light->setNum(p_shared[0]->dist); ui->d2light_2->setNum(p_shared[1]->dist); ui->d2light_3->setNum(p_shared[2]->dist); ui->d2light_4->setNum(p_shared[3]->dist); ui->d2light_5->setNum(p_shared[4]->dist); ui->d2light_6->setNum(p_shared[5]->dist); //Connect Phase Timers QTimer *ctimer = new QTimer(this); connect(ctimer,&QTimer::timeout,this,&MainWindow::updateCountdown); ctimer -> start(1000); //Connect Distance Timers QTimer *dtimer = new QTimer(this); connect(dtimer,&QTimer::timeout,this,&MainWindow::updateDistance); dtimer->start(1000); } MainWindow::~MainWindow() { delete ui; } //function to update displayed time until traffic light phase change void MainWindow::updateCountdown(){ //declare number of lights in scope unsigned long long num = NUMTLIGHT; //declare sensor view distance in scope int sensview = SENSVIEW; //create vector "num" long to hold strings to be displayed std::vector<QString> tstr{num}; //update time and corresponding string for(unsigned long long j = 0;j < num;j++){ time[j] = time[j].addSecs(-1); tstr[j] = time[j].toString("m:ss"); } //set display to reflect remaining phase time and remove countdown if distance is 0 or beyond sensor range if(p_shared[0]->dist != 0 && p_shared[0]->dist < sensview){ ui->countdown->setText(tstr[0]); }else{ ui->countdown->setText(nullptr); } if(p_shared[1]->dist != 0 && p_shared[1]->dist < sensview){ ui->countdown_2->setText(tstr[1]); }else{ ui->countdown_2->setText(nullptr); } if(p_shared[2]->dist != 0 && p_shared[2]->dist < sensview){ ui->countdown_3->setText(tstr[2]); }else{ ui->countdown_3->setText(nullptr); } if(p_shared[3]->dist != 0 && p_shared[3]->dist < sensview){ ui->countdown_4->setText(tstr[3]); }else{ ui->countdown_4->setText(nullptr); } if(p_shared[4]->dist != 0 && p_shared[4]->dist < sensview){ ui->countdown_5->setText(tstr[4]); }else{ ui->countdown_5->setText(nullptr); } if(p_shared[5]->dist != 0 && p_shared[5]->dist < sensview){ ui->countdown_6->setText(tstr[5]); }else if(p_shared[5]->dist == 0){ close(); }else{ ui->countdown_6->setText(nullptr); } //switch to next phase for(unsigned long long k = 0;k < num;k++){ if(tstr[k] == "0:00"){ //update timings p_shared[k]->timing = p_shared[k]->read_ini("D:/Graduate/Code Development/Combined_UI_v3/timing.ini"); p_shared[k]->rlight = p_shared[k]->timing.at(3).second.at(k); //set the total cycle time for the light (s) p_shared[k]->glight = p_shared[k]->timing.at(1).second.at(k); //set the end of the green phase (s) p_shared[k]->ylight = p_shared[k]->timing.at(2).second.at(k); //set the end of the yellow phase (s) //switch color of tl_widget if(!p_shared[k]){ std::cerr << "ASSIGN POINTER\n"; }else if(ptime[k] == p_shared[k]->glight){ //green light time ptime[k] = p_shared[k]->ylight; switch(k){ case 0: ui->tl_widget->setStyleSheet("background-color: rgb(255, 255, 0); color: rgb(255, 255, 255)"); break; case 1: ui->tl_widget_2->setStyleSheet("background-color: rgb(255, 255, 0); color: rgb(255, 255, 255)"); break; case 2: ui->tl_widget_3->setStyleSheet("background-color: rgb(255, 255, 0); color: rgb(255, 255, 255)"); break; case 3: ui->tl_widget_4->setStyleSheet("background-color: rgb(255, 255, 0); color: rgb(255, 255, 255)"); break; case 4: ui->tl_widget_5->setStyleSheet("background-color: rgb(255, 255, 0); color: rgb(255, 255, 255)"); break; case 5: ui->tl_widget_6->setStyleSheet("background-color: rgb(255, 255, 0); color: rgb(255, 255, 255)"); break; } }else if(ptime[k] == p_shared[k]->ylight){ //yellow light time ptime[k] = p_shared[k]->rlight; switch(k){ case 0: ui->tl_widget->setStyleSheet("background-color: rgb(255, 0, 0); color: rgb(255, 255, 255)"); break; case 1: ui->tl_widget_2->setStyleSheet("background-color: rgb(255, 0, 0); color: rgb(255, 255, 255)"); break; case 2: ui->tl_widget_3->setStyleSheet("background-color: rgb(255, 0, 0); color: rgb(255, 255, 255)"); break; case 3: ui->tl_widget_4->setStyleSheet("background-color: rgb(255, 0, 0); color: rgb(255, 255, 255)"); break; case 4: ui->tl_widget_5->setStyleSheet("background-color: rgb(255, 0, 0); color: rgb(255, 255, 255)"); break; case 5: ui->tl_widget_6->setStyleSheet("background-color: rgb(255, 0, 0); color: rgb(255, 255, 255)"); break; } }else if(ptime[k] == p_shared[k]->rlight){ //red light time ptime[k] = p_shared[k]->glight; switch(k){ case 0: ui->tl_widget->setStyleSheet("background-color: rgb(0, 255, 0); color: rgb(255, 255, 255)"); break; case 1: ui->tl_widget_2->setStyleSheet("background-color: rgb(0, 255, 0); color: rgb(255, 255, 255)"); break; case 2: ui->tl_widget_3->setStyleSheet("background-color: rgb(0, 255, 0); color: rgb(255, 255, 255)"); break; case 3: ui->tl_widget_4->setStyleSheet("background-color: rgb(0, 255, 0); color: rgb(255, 255, 255)"); break; case 4: ui->tl_widget_5->setStyleSheet("background-color: rgb(0, 255, 0); color: rgb(255, 255, 255)"); break; case 5: ui->tl_widget_6->setStyleSheet("background-color: rgb(0, 255, 0); color: rgb(255, 255, 255)"); break; } }else{ std::cerr << "BROKEN SYSTEM\n"; } //reset timer to next phase's timing time[k].setHMS(0,0,ptime[k]); } } } //function to update displayed distance btw ego vehicle and intersection void MainWindow::updateDistance(){ //declare number of lights w/in scope int num = NUMTLIGHT; //declare sensor view w/in scope int sensview = SENSVIEW; //calculate distance left from vehicle to light based on speed (TO BE REMOVED WHEN POSSIBLE) for(int m = 0;m < num;m++){ if(p_shared[m]->dist != 0){ p_shared[m]->dist = p_shared[m]->dist - p_shared[m]->speed; }else{ //if distance goes to 0, keep it there p_shared[m]->dist = 0; } } //import distance left from vehicle to light //set display to reflect remaining difference make blocks transparent if associated distance is 0 or beyond sensor range if(p_shared[0]->dist != 0 && p_shared[0]->dist < sensview){ ui->d2light->setNum(p_shared[0]->dist); ui->title1->setText("Traffic Light 1"); ui->label_1_1->setText("Time to Phase Change"); ui->label_1_2->setText("Distance to Light"); ui->tl_widget->show(); }else{ ui->title1->setText(nullptr); ui->d2light->setText(nullptr); ui->label_1_1->setText(nullptr); ui->label_1_2->setText(nullptr); ui->tl_widget->hide(); } if(p_shared[1]->dist != 0 && p_shared[1]->dist < sensview){ ui->d2light_2->setNum(p_shared[1]->dist); ui->title2->setText("Traffic Light 2"); ui->label_2_1->setText("Time to Phase Change"); ui->label_2_2->setText("Distance to Light"); ui->tl_widget_2->show(); }else{ ui->title2->setText(nullptr); ui->d2light_2->setText(nullptr); ui->label_2_1->setText(nullptr); ui->label_2_2->setText(nullptr); ui->tl_widget_2->hide(); } if(p_shared[2]->dist != 0 && p_shared[2]->dist < sensview){ ui->d2light_3->setNum(p_shared[2]->dist); ui->title3->setText("Traffic Light 3"); ui->label_3_1->setText("Time to Phase Change"); ui->label_3_2->setText("Distance to Light"); ui->tl_widget_3->show(); }else{ ui->title3->setText(nullptr); ui->d2light_3->setText(nullptr); ui->label_3_1->setText(nullptr); ui->label_3_2->setText(nullptr); ui->tl_widget_3->hide(); } if(p_shared[3]->dist != 0 && p_shared[3]->dist < sensview){ ui->d2light_4->setNum(p_shared[3]->dist); ui->title4->setText("Traffic Light 4"); ui->label_4_1->setText("Time to Phase Change"); ui->label_4_2->setText("Distance to Light"); ui->tl_widget_4->show(); }else{ ui->title4->setText(nullptr); ui->d2light_4->setText(nullptr); ui->label_4_1->setText(nullptr); ui->label_4_2->setText(nullptr); ui->tl_widget_4->hide(); } if(p_shared[4]->dist != 0 && p_shared[4]->dist < sensview){ ui->d2light_5->setNum(p_shared[4]->dist); ui->title5->setText("Traffic Light 5"); ui->label_5_1->setText("Time to Phase Change"); ui->label_5_2->setText("Distance to Light"); ui->tl_widget_5->show(); }else{ ui->title5->setText(nullptr); ui->d2light_5->setText(nullptr); ui->label_5_1->setText(nullptr); ui->label_5_2->setText(nullptr); ui->tl_widget_5->hide(); } if(p_shared[5]->dist != 0 && p_shared[5]->dist < sensview){ ui->d2light_6->setNum(p_shared[5]->dist); ui->title6->setText("Traffic Light 6"); ui->label_6_1->setText("Time to Phase Change"); ui->label_6_2->setText("Distance to Light"); ui->tl_widget_6->show(); }else{ ui->title6->setText(nullptr); ui->d2light_6->setText(nullptr); ui->label_6_1->setText(nullptr); ui->label_6_2->setText(nullptr); ui->tl_widget_6->hide(); } } //function to change the font size of a label widget on the UI void MainWindow::fontsize(QLabel *sellabel, int size){ QFont fontholder = sellabel->font(); fontholder.setPointSize(size); sellabel->setFont(fontholder); }
b82220bc54047a1a07cb61b35127e50c9eeb7ddd
fc6d835bc3125052721c66f5302fbff71ae3454d
/leetcode/58_最后一个单词的长度.cpp
53855cd4eaf8af754fdac2a804cd68137d4fa317
[]
no_license
Scofyyy/leetcode
c1b0a6af9acd10a39f4548b0761af7bff7980b72
edac9340d117f47799bef3cbafa75ff3fc5f3def
refs/heads/master
2020-08-24T09:17:28.451782
2019-12-26T08:11:29
2019-12-26T08:11:29
216,801,451
0
0
null
null
null
null
UTF-8
C++
false
false
826
cpp
#include <string> #include <algorithm> using namespace std; class Solution { int lengthOfLastWord(string s) { int size = s.size()-1; int ans = 0; int flag = 0; for(int i=size-1;i>=0;i--) { if(s[i]!=' ') { ans++; flag = 1; } if(flag==1&&s[i]==' ') { return ans; } } return ans; } }; //solution 2 class Solution { public: int lengthOfLastWord(string s) { int ans = 0; for(int i=s.size()-1;i>=0;i--) { if(s[i]!=' ') { ans++; } else { if(ans) break; } } return ans; } };
116165c831e7a095261054ce5254abdfaa3354ff
0d7886bd7e7625e935b1d55a55f3b5c056ecb67b
/Learn/程序清单 6-4.cpp
a3b05ffb74028d526db7386a2ae3fdb03db2c7db
[]
no_license
MasterWangdaoyong/My-C--Primer-Plus
ad1c06ff56f2a575c43a7d4dd1666dac83cf2704
a204a87ce6fb387d487d9157c17e787306118c1b
refs/heads/master
2021-04-06T02:29:16.293949
2021-01-17T14:00:06
2021-01-17T14:00:06
124,376,847
1
0
null
null
null
null
UTF-8
C++
false
false
700
cpp
// or // 程序清单 6-4.cpp // C++ Primer Plus // // Created by 王道勇 on 2017/5/29. // Copyright © 2017年 王道勇. All rights reserved. // #include <iostream> int main() { using namespace std; cout << "This program may reformat your hard disk.\n" "and destroy all your data.\nDo you wish to continue? <y/n> "; char ch; cin >> ch; if (ch == 'y' || ch == 'Y') cout << "You were warned!\a\a\n"; else if (ch == 'n' || ch == 'N') cout << "A wise choice ... bye\n"; else cout << "That wasn't a y or n! Apparently you " "can't follow\ninstructions, so I'll trash your disk anyway.\a\a\a\n"; return 0; }
7aa36796026e5aedf28c9934248dfd5698f9c0c5
f950882940764ace71e51a1512c16a5ac3bc47bc
/src/GisEngine/GisGeometry/Geometry.h
eb1132618facb140b5b4bb4b6d87b98ca0df7a9c
[]
no_license
ViacheslavN/GIS
3291a5685b171dc98f6e82595dccc9f235e67bdf
e81b964b866954de9db6ee6977bbdf6635e79200
refs/heads/master
2021-01-23T19:45:24.548502
2018-03-12T09:55:02
2018-03-12T09:55:02
22,220,159
2
0
null
null
null
null
UTF-8
C++
false
false
6,032
h
#ifndef GIS_ENGINE_GEOMETRY_I_GEOMETRY_H_ #define GIS_ENGINE_GEOMETRY_I_GEOMETRY_H_ #include <set> #include "Common/Common.h" #include "Common/Units.h" #include "CommonLibrary/IRefCnt.h" #include "Common/GisEngineCommon.h" #include "CommonLibrary/stream.h" namespace GisEngine { namespace GisGeometry { enum ePolygonOpType { PolyIntersection, PolyUnion, PolyDifference, PolyXor }; enum eTOJoinType { ToJtSquare, ToJtRound, ToJtMiter }; struct ISpatialReference; struct ITopologicalOperator; struct IEnvelope; COMMON_LIB_REFPTR_TYPEDEF(ISpatialReference); COMMON_LIB_REFPTR_TYPEDEF(ITopologicalOperator); COMMON_LIB_REFPTR_TYPEDEF(IEnvelope); struct ISpatialReference : public CommonLib::AutoRefCounter, public GisCommon::IStreamSerialize, public GisCommon::IXMLSerialize { public: ISpatialReference(){}; virtual ~ISpatialReference(){} virtual bool IsValid() = 0; virtual void* GetHandle() = 0; virtual bool Project(ISpatialReference* destSpatRef, CommonLib::CGeoShape* pShape) = 0; virtual bool Project(ISpatialReference* destSpatRef, GisBoundingBox& bbox) = 0; virtual bool Project(ISpatialReference *destSpatRef, GisXYPoint* pPoint) = 0; virtual const CommonLib::CString& GetProjectionString() const = 0; virtual int GetProjectionCode() const = 0; virtual bool IsProjection() const = 0; virtual bool IsEqual(ISpatialReference* pSpatRef) const= 0; virtual ISpatialReferencePtr clone() const = 0; virtual GisCommon::Units GetUnits() const = 0; }; struct ITopologicalOperator : public CommonLib::AutoRefCounter { ITopologicalOperator(){} virtual ~ITopologicalOperator(){} virtual CommonLib::IGeoShapePtr Intersect(CommonLib::CGeoShape* shape1, CommonLib::CGeoShape* shape2) const = 0; virtual CommonLib::IGeoShapePtr AddShapeToIntersect(CommonLib::CGeoShape* shape) = 0; virtual CommonLib::IGeoShapePtr ClearIntersect() = 0; virtual CommonLib::IGeoShapePtr Intersect(CommonLib::CGeoShape* shape) const = 0; virtual bool IsIntersection(const CommonLib::CGeoShape* pShapeL, const CommonLib::CGeoShape* pShapeR, CommonLib::CGeoShape* pShapeRes = 0) = 0; virtual CommonLib::IGeoShapePtr Union(CommonLib::CGeoShape* shape1, CommonLib::CGeoShape* shape2) const = 0; virtual CommonLib::IGeoShapePtr AddShapeToUnion(CommonLib::CGeoShape* shape) = 0; virtual CommonLib::IGeoShapePtr Union(CommonLib::CGeoShape* shape) const = 0; virtual CommonLib::IGeoShapePtr ClearUnion() = 0; virtual CommonLib::IGeoShapePtr GetDifference(CommonLib::CGeoShape* shape1, CommonLib::CGeoShape* shape2) const = 0; virtual CommonLib::IGeoShapePtr GetSymmetricDifference(CommonLib::CGeoShape* shape1, CommonLib::CGeoShape* shape2) const = 0; virtual bool Contains(CommonLib::CGeoShape* shape1, CommonLib::CGeoShape* shape2) const = 0; virtual CommonLib::IGeoShapePtr Clip(CommonLib::CGeoShape* shape, const GisBoundingBox& box) const = 0; virtual CommonLib::IGeoShapePtr CalcConvexHull(CommonLib::CGeoShape* shape) const = 0; virtual CommonLib::IGeoShapePtr CalcBuffer(CommonLib::CGeoShape* shape, double distance) const = 0; virtual double CalcDistance(CommonLib::CGeoShape* shape1, CommonLib::CGeoShape* shape2) const = 0; virtual CommonLib::IGeoShapePtr QuerySubCurve (CommonLib::CGeoShape* shape, int geomidx, double dist_from, double dist_to) const = 0; virtual GisXYPoint QuerySubPoint (CommonLib::CGeoShape* shape, int geomidx, double dist) const = 0; virtual double QuerySubAngle (CommonLib::CGeoShape* shape, int geomidx, double dist) const = 0; virtual void QuerySubPointAndAngle(CommonLib::CGeoShape* shape, int geomidx, double dist,GisXYPoint *pPoint,double *pAngle, bool firstTime) const = 0; virtual double CalcDistanceToPoint(CommonLib::CGeoShape* shape, const GisXYPoint& pnt, GisXYPoint* pnt_out) const = 0; virtual double CalcDistanceToPoint(const GisXYPoint* pnt_in, size_t npnt_in, const GisXYPoint& pnt, GisXYPoint& pnt_out, size_t &outidx) const = 0; virtual double CalcLineLength(CommonLib::CGeoShape* shape) const = 0; virtual double CalcPolygonArea(CommonLib::CGeoShape* shape) const = 0; virtual double CalcPolygonPerimeter(CommonLib::CGeoShape* shape) const = 0; virtual bool IsPointInside(CommonLib::CGeoShape* shape, const GisXYPoint& pnt) const = 0; virtual bool IsPointOutside(CommonLib::CGeoShape* shape, const GisXYPoint& pnt) const = 0; virtual bool IsPointOnBorder(CommonLib::CGeoShape* shape, const GisXYPoint& pnt) const = 0; virtual bool IsIntersectionNotNull(CommonLib::CGeoShape* shape1, CommonLib::CGeoShape* shape2) const = 0; virtual bool IsClippingNotNull(CommonLib::CGeoShape* shape, const GisBoundingBox& box) const = 0; virtual bool IsSimple(CommonLib::CGeoShape* shape) const = 0; virtual void Simplify(CommonLib::CGeoShape* shape) const = 0; virtual bool CreateBufferZone(const CommonLib::CGeoShape* shape, CommonLib::CGeoShape* pShapeRes, double dDelta, eTOJoinType type) const = 0; }; struct IEnvelope : public CommonLib::AutoRefCounter { IEnvelope(){} virtual ~IEnvelope(){} virtual GisBoundingBox& GetBoundingBox() = 0; virtual void SetBoundingBox(const GisBoundingBox& box) = 0; virtual ISpatialReferencePtr GetSpatialReference() const = 0; virtual void SetSpatialReference(ISpatialReference* spatRef) = 0; virtual void Expand(IEnvelope* envelope) = 0; virtual bool Intersect(IEnvelope* envelope) = 0; virtual void Project(ISpatialReference* spatRef) = 0; virtual IEnvelopePtr clone() const = 0; virtual CommonLib::shape_compress_params GetCompressParams() const = 0; }; } } #endif
2e4db8e2ab5ee83e7904e9c3c8f7a7d8079e8751
038df27dfb74a68f7b2fef2f63e5cc6bfe720962
/helpers/generator/generator.hpp
9b1d32d7bbcfdfbf15cce7edf3dc4e1232c21941
[ "MIT" ]
permissive
klmr/fast_io
6226db934bbda0b78ae1fac80d20c635106db2c1
1393ef01b82dffa87f3008ec0898431865870a1f
refs/heads/master
2022-07-28T12:34:10.173427
2020-05-25T11:25:38
2020-05-25T11:25:38
266,780,867
2
0
NOASSERTION
2020-05-25T13:03:19
2020-05-25T13:03:19
null
UTF-8
C++
false
false
5,640
hpp
/////////////////////////////////////////////////////////////////////////////// // Copyright (c) Lewis Baker // Licenced under MIT license. See LICENSE.txt for details. /////////////////////////////////////////////////////////////////////////////// #ifndef CPPCORO_GENERATOR_HPP_INCLUDED #define CPPCORO_GENERATOR_HPP_INCLUDED #include <coroutine> #include <type_traits> #include <utility> #include <exception> #include <iterator> #include <functional> namespace cppcoro { template<typename T> class generator; namespace detail { template<typename T> class generator_promise { public: using value_type = std::remove_reference_t<T>; using reference_type = std::conditional_t<std::is_reference_v<T>, T, T&>; using pointer_type = value_type*; generator_promise() = default; generator<T> get_return_object() noexcept; constexpr std::suspend_always initial_suspend() const { return {}; } constexpr std::suspend_always final_suspend() const { return {}; } template< typename U = T, std::enable_if_t<!std::is_rvalue_reference<U>::value, int> = 0> std::suspend_always yield_value(std::remove_reference_t<T>& value) noexcept { m_value = std::addressof(value); return {}; } std::suspend_always yield_value(std::remove_reference_t<T>&& value) noexcept { m_value = std::addressof(value); return {}; } void unhandled_exception() { m_exception = std::current_exception(); } void return_void() { } reference_type value() const noexcept { return static_cast<reference_type>(*m_value); } // Don't allow any use of 'co_await' inside the generator coroutine. template<typename U> std::suspend_never await_transform(U&& value) = delete; void rethrow_if_exception() { if (m_exception) { std::rethrow_exception(m_exception); } } private: pointer_type m_value; std::exception_ptr m_exception; }; struct generator_sentinel {}; template<typename T> class generator_iterator { using coroutine_handle = std::coroutine_handle<generator_promise<T>>; public: using iterator_category = std::input_iterator_tag; // What type should we use for counting elements of a potentially infinite sequence? using difference_type = std::ptrdiff_t; using value_type = typename generator_promise<T>::value_type; using reference = typename generator_promise<T>::reference_type; using pointer = typename generator_promise<T>::pointer_type; // Iterator needs to be default-constructible to satisfy the Range concept. generator_iterator() noexcept : m_coroutine(nullptr) {} explicit generator_iterator(coroutine_handle coroutine) noexcept : m_coroutine(coroutine) {} friend bool operator==(const generator_iterator& it, generator_sentinel) noexcept { return !it.m_coroutine || it.m_coroutine.done(); } friend bool operator!=(const generator_iterator& it, generator_sentinel s) noexcept { return !(it == s); } friend bool operator==(generator_sentinel s, const generator_iterator& it) noexcept { return (it == s); } friend bool operator!=(generator_sentinel s, const generator_iterator& it) noexcept { return it != s; } generator_iterator& operator++() { m_coroutine.resume(); if (m_coroutine.done()) { m_coroutine.promise().rethrow_if_exception(); } return *this; } // Need to provide post-increment operator to implement the 'Range' concept. void operator++(int) { (void)operator++(); } reference operator*() const noexcept { return m_coroutine.promise().value(); } pointer operator->() const noexcept { return std::addressof(operator*()); } private: coroutine_handle m_coroutine; }; } template<typename T> class [[nodiscard]] generator { public: using promise_type = detail::generator_promise<T>; using iterator = detail::generator_iterator<T>; generator() noexcept : m_coroutine(nullptr) {} generator(generator&& other) noexcept : m_coroutine(other.m_coroutine) { other.m_coroutine = nullptr; } generator(const generator& other) = delete; ~generator() { if (m_coroutine) { m_coroutine.destroy(); } } generator& operator=(generator other) noexcept { swap(other); return *this; } iterator begin() { if (m_coroutine) { m_coroutine.resume(); if (m_coroutine.done()) { m_coroutine.promise().rethrow_if_exception(); } } return iterator{ m_coroutine }; } detail::generator_sentinel end() noexcept { return detail::generator_sentinel{}; } void swap(generator& other) noexcept { std::swap(m_coroutine, other.m_coroutine); } private: friend class detail::generator_promise<T>; explicit generator(std::coroutine_handle<promise_type> coroutine) noexcept : m_coroutine(coroutine) {} std::coroutine_handle<promise_type> m_coroutine; }; template<typename T> void swap(generator<T>& a, generator<T>& b) { a.swap(b); } namespace detail { template<typename T> generator<T> generator_promise<T>::get_return_object() noexcept { using coroutine_handle = std::coroutine_handle<generator_promise<T>>; return generator<T>{ coroutine_handle::from_promise(*this) }; } } template<typename FUNC, typename T> generator<std::invoke_result_t<FUNC&, typename generator<T>::iterator::reference>> fmap(FUNC func, generator<T> source) { for (auto&& value : source) { co_yield std::invoke(func, static_cast<decltype(value)>(value)); } } } #endif
ed1055e7f74b52ea178ddf4864080d9cd3033246
7573e25f68f7cc4a38c3306c3888840788c7e74e
/@hstlife/addons/hst_life_phone/cfgPatches.hpp
9b8a4225518d2bb2c09d1548934ea303a91dc4df
[]
no_license
Kruk939/Hastati-HardRP-Kelly-Island
adb9639e469a73c8eef84a2fa90c648410e81a7f
1ec8bf2c989d13275d03791275d8ab5d9cd69d70
refs/heads/master
2021-01-13T09:22:05.711557
2016-11-15T17:07:01
2016-11-15T17:07:01
69,752,492
3
2
null
2016-11-13T19:53:33
2016-10-01T17:23:29
SQF
UTF-8
C++
false
false
134
hpp
class CfgPatches { class hst_life_phone { units[] = {}; weapons[] = {}; requiredVersion = 0.1; requiredAddons[] = {}; }; };
0ef3a14de3b17119d9778f38630d96bcb2b42a83
e35e71086793ff18e213fd291cd3c0cbdac16940
/Fireplanet/main.cpp
6b3bd91f990241e039b7b7003f585c5287097993
[]
no_license
betelge/fireplanet
09ed3ec8617a56b2d451955f1b3a6a72470b5a4b
d37c0a7a964a3fc29303a10afb5ecb4de51dc76f
refs/heads/master
2020-06-28T11:27:08.076199
2016-09-09T01:31:29
2016-09-09T01:31:29
67,696,776
0
0
null
null
null
null
UTF-8
C++
false
false
4,851
cpp
// @jasminko #include <fstream> #include <iostream> #include <GL/glew.h> #include <GL/freeglut.h> #include "shader.h" #include "lodepng.h" #define VERTEX_SOURCE "vertex.glsl" #define FRAGMENT_SOURCE "fragment.glsl" #define NOISE_SOURCE "noise3D.glsl" // The noise function called from the fragent shader #define TEXTURE_FILE "../assets/fire_profile.png" #define WINDOW_SIZE 512 Shader* planetShader = nullptr; // The shader program used to draw the planet GLuint texture = 0; // The fire texture handle std::string loadFile(std::string filename) { std::ifstream file(filename); if (!file) { std::cerr << "Can't load " << filename << std::endl; return ""; } // Populates a std::string with the file contents std::string content ((std::istreambuf_iterator<char>(file)), (std::istreambuf_iterator<char>())); return content; } GLuint loadTexture(std::string filename) { //load and decode std::vector<unsigned char> image; unsigned width, height; unsigned error = lodepng::decode(image, width, height, filename); if (error) std::cout << "Texture decoder error " << error << ": " << lodepng_error_text(error) << std::endl; GLuint textureHandle = 0; glGenTextures(1, &textureHandle); glBindTexture(GL_TEXTURE_2D, textureHandle); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, // Populates texture in video memory GL_RGBA, GL_UNSIGNED_BYTE, (GLvoid*)&image[0]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // Set samling filters to smooth glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glGenerateMipmap(GL_TEXTURE_2D); // Generates all higher mipmap levels // OpenGL error check for debug build #ifdef _DEBUG GLenum err = glGetError(); #endif return textureHandle; } bool init() { // Load shader sources std::string vertexSource = loadFile(VERTEX_SOURCE); std::string fragmentSource = loadFile(FRAGMENT_SOURCE); std::string noiseSource = loadFile(NOISE_SOURCE); // Contains the noise function used in the fragment shader // Compile and link shader planetShader = new Shader(vertexSource, fragmentSource + noiseSource); // Appends noise function planetShader->initialize(); if (!planetShader->issuccessfullyLinked()) { std::cerr << "Shader was not sucessfully compiled and linked" << std::endl; std::cerr << "Log:" << std::endl << planetShader->getErrorLog() << std::endl; return false; } // Load texture texture = loadTexture(TEXTURE_FILE); return true; } // Fix window size void resize(int width, int height) { glutReshapeWindow(WINDOW_SIZE, WINDOW_SIZE); } // display callback void display() { // Bind shader program. The OpenGL driver should optimize away redundant calls. glUseProgram(planetShader->getHandle()); glClearColor(0, 0, 0, 0); // Black glClear(GL_COLOR_BUFFER_BIT); // Clears color, ignores non-existing depth buffer // Make time 64 second periodic and normalize it to [0, 1] int time = glutGet(GLUT_ELAPSED_TIME); // Gets application time in milliseconds float timef = (time % 64000) / (float) 64000; // Set time uniform GLuint timeUniform = glGetUniformLocation(planetShader->getHandle(), "time"); glUniform1f(timeUniform, timef); // Bind our texture to unit 0 and set sampler uniform accordingly const int TEXTURE_UNIT = 0; glActiveTexture(GL_TEXTURE0 + TEXTURE_UNIT); glBindTexture(GL_TEXTURE_2D, texture); GLuint samplerUniform = glGetUniformLocation(planetShader->getHandle(), "texture"); glUniform1i(samplerUniform, TEXTURE_UNIT); /* Draws a full screen triangle. No vertex attributes are used. Instead the vertex shader uses gl_VertexID to span the triangle and the fragment shader uses texture coordinates to draw a round shaded planet. */ glDrawArrays(GL_TRIANGLES, 0, 3); glutSwapBuffers(); } int main(int argc, char *argv[]) { // Initialize GLUT glutInit(&argc, argv); glutInitContextVersion(2, 1); // Request OpenGL 2.1 // Request a double buffered color frame buffer without depth and alpha glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE); glutInitWindowSize(WINDOW_SIZE, WINDOW_SIZE); glutCreateWindow("Fireplanet"); // Initialize GLEW glewExperimental = true; // Needed for newer OpenGL versions GLenum error = glewInit(); if (error != GLEW_OK) { std::cout << "glewInit failed" << std::endl; return -1; } glutDisplayFunc(display); // Set display callback glutIdleFunc(display); // Forces constant redrawing by using display as idle callback glutReshapeFunc(resize); // Disables window resizing // Initialize everything we need to start the main display loop bool success = init(); if (!success) { std::cerr << "Program initialization failed" << std::endl; return -1; } // Main GLUT loop. Polls events and draws by calling display() glutMainLoop(); // Clean up if (planetShader != nullptr) delete planetShader; return 0; }
bfcb0c30d90b314c9775bbf54e4bc7cadd7f2b78
317956c4f20290e81feb799f870cc329a767b305
/app/src/main/cpp/TvFilter.cpp
66415226ba6e40499010f5bbafc926e7f80cef75
[]
no_license
boksha/nativeTestApp
acda9116202fad0acdd38f11aa497fb4ada7c4ee
fcc2c0e8f4da0249b750e7a8aa3982ad047ac776
refs/heads/master
2021-09-11T06:46:44.065089
2018-01-16T16:00:24
2018-01-16T16:00:24
115,346,317
0
0
null
null
null
null
UTF-8
C++
false
false
1,519
cpp
// // Created by miodrag.milosevic on 12/29/2017. // #include "TvFilter.h" #include "color.h" void TvFilter::transformPixels(jint *pixelArray, jint imageWidth, jint imageHeight) { jint R, G, B, A; for (jint x = 0; x < imageWidth; x++) { for (jint y = 0; y < imageHeight; y += GAP) { A = R = G = B = 0; for (jint w = 0; w < GAP; w++) { jint index = (y + w) * imageWidth + x; if (index < imageWidth * imageHeight) { //median value A = Color::alpha(pixelArray[index]); R += Color::red(pixelArray[index]); G += Color::green(pixelArray[index]); B += Color::blue(pixelArray[index]); } } for (jint w = 0; w < GAP; w++) { jint index = (y + w) * imageWidth + x; if (index < imageWidth * imageHeight) { if (w == 0) { pixelArray[(y + w) * imageWidth + x] = Color::argb(A, R / GAP, 0, 0); } if (w == 1) { pixelArray[(y + w) * imageWidth + x] = Color::argb(A, 0, G / GAP, 0); } if (w == 2) { pixelArray[(y + w) * imageWidth + x] = Color::argb(A, 0, 0, B / GAP); } // if (w == 3) { // pixels[(y + w) * width + x] =Color.argb(A,255, 255, 255); // } } } } } }
f7b73c7e809acf62f14a1ce37e920f7bbfa15407
fafaa4cd9bc46e8426af6e173e976c9c74098030
/my_server/MapGroupKernel/LeaveWord.h
11f920f28221f1b24727421bbf007ec523fd9764
[]
no_license
XinJiangQingMang/fight
2c7cf0af9a3f027eda7b355c193041160053d4a0
41846b583064f2c576d3f238aebcebcbb3bafd17
refs/heads/master
2021-06-12T05:31:38.338725
2016-12-11T05:08:17
2016-12-11T05:08:17
null
0
0
null
null
null
null
GB18030
C++
false
false
2,088
h
//********************************************************** // 代码编辑器 //********************************************************** // PlayerLeaveWord.h: interface for the CLeaveWord class. // 仙剑修, 2002.10.11 ////////////////////////////////////////////////////////////////////// #if !defined(AFX_PLAYERLEAVEWORD_H__6547133F_17B9_4978_93AB_BAA88B109312__INCLUDED_) #define AFX_PLAYERLEAVEWORD_H__6547133F_17B9_4978_93AB_BAA88B109312__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <windows.h> #include "define.h" #include "TimeOut.h" #include "Myheap.h" //////////////////////////////////////////////////////////////////////////////////////////// enum LEAVEWORDDATA { LEAVEWORDDATA_ID = 0, // LEAVEWORDDATA_USER = 1, LEAVEWORDDATA_SENDER, LEAVEWORDDATA_TIME, LEAVEWORDDATA_WORDS, }; //////////////////////////////////////////////////////////////////////////////////////////// const int PLAYER_WORDS_PER_TIME = 1; // 玩家每次读取5条留言 const int NEW_WORDS_PER_MINUTE = 5; // 每分钟自动读取几条新留言 const int DELETE_LEAVEWORD_DAYS = 31; // 31天以上留言会自动删除 const int SECS_PER_AUTOFLUSH = 60; // 每分钟自动刷新一次 //////////////////////////////////////////////////////////////////////////////////////////// class CUser; class CLeaveWord { public: CLeaveWord(); virtual ~CLeaveWord(); public: bool Create (PROCESS_ID idProcess); ULONG Release () { delete this; return 0; } bool InsertWords (LPCTSTR szSender, LPCTSTR szRecvUser, LPCTSTR szWords); // int CountWords (LPCTSTR szRecvUser); bool ShowWords (CUser* pUser, int nMaxNum = PLAYER_WORDS_PER_TIME); void OnTimer (DWORD tCurr); protected: DWORD m_idLastMsg; CTimeOut m_tAutoFlush; protected: // ctrl PROCESS_ID m_idProcess; public: // ctrl MYHEAP_DECLARATION(s_heap) }; #endif // !defined(AFX_PLAYERLEAVEWORD_H__6547133F_17B9_4978_93AB_BAA88B109312__INCLUDED_)
23cc862e056a302369b7cd4f018d44ccfa8223f8
dfca502b5d88e3c67054b617399dc30a757e1eea
/src/main.cpp
fc8a1860b98b5a2a21f6e203dd4f946ed35f86ae
[]
no_license
chen0510566/CarND-P8-Kidnapped-Vehicle-Project
e625f3a02d2bc46c9dc4078e22d3dbc0f7d689ac
eafba075e89a8a093f9d62d7bcce0746a6c07018
refs/heads/master
2021-01-21T20:06:42.579542
2017-07-01T12:38:28
2017-07-01T12:38:28
92,187,795
0
0
null
null
null
null
UTF-8
C++
false
false
7,531
cpp
/* * main.cpp * Reads in data and runs 2D particle filter. * Created on: Dec 13, 2016 * Author: Tiffany Huang */ #include <iostream> #include <ctime> #include <iomanip> #include <random> #include "particle_filter.h" #include "helper_functions.h" using namespace std; //#define DEBUG_OUTPUT int main() { // parameters related to grading. int time_steps_before_lock_required = 100; // number of time steps before accuracy is checked by grader. double max_runtime = 45; // Max allowable runtime to pass [sec] double max_translation_error = 1; // Max allowable translation error to pass [m] double max_yaw_error = 0.05; // Max allowable yaw error [rad] // Start timer. int start = clock(); //Set up parameters here double delta_t = 0.1; // Time elapsed between measurements [sec] double sensor_range = 50; // Sensor range [m] /* * Sigmas - just an estimate, usually comes from uncertainty of sensor, but * if you used fused data from multiple sensors, it's difficult to find * these uncertainties directly. */ double sigma_pos[3] = {0.3, 0.3, 0.01}; // GPS measurement uncertainty [x [m], y [m], theta [rad]] double sigma_landmark[2] = {0.3, 0.3}; // Landmark measurement uncertainty [x [m], y [m]] // noise generation default_random_engine gen; normal_distribution<double> N_x_init(0, sigma_pos[0]); normal_distribution<double> N_y_init(0, sigma_pos[1]); normal_distribution<double> N_theta_init(0, sigma_pos[2]); normal_distribution<double> N_obs_x(0, sigma_landmark[0]); normal_distribution<double> N_obs_y(0, sigma_landmark[1]); double n_x, n_y, n_theta, n_range, n_heading; // Read map data Map map; if (!read_map_data("data/map_data.txt", map)) { cout << "Error: Could not open map file" << endl; return -1; } // Read position data vector<control_s> position_meas; if (!read_control_data("data/control_data.txt", position_meas)) { cout << "Error: Could not open position/control measurement file" << endl; return -1; } // Read ground truth data vector<ground_truth> gt; if (!read_gt_data("data/gt_data.txt", gt)) { cout << "Error: Could not open ground truth data file" << endl; return -1; } // Run particle filter! int num_time_steps = position_meas.size(); ParticleFilter pf; double total_error[3] = {0, 0, 0}; double cum_mean_error[3] = {0, 0, 0}; for (int i = 0; i < num_time_steps; ++i) { cout << "Time step: " << i << endl; // Read in landmark observations for current time step. ostringstream file; file << "data/observation/observations_" << setfill('0') << setw(6) << i + 1 << ".txt"; vector<LandmarkObs> observations; if (!read_landmark_data(file.str(), observations)) { cout << "Error: Could not open observation file " << i + 1 << endl; return -1; } // Initialize particle filter if this is the first time step. if (!pf.initialized()) { n_x = N_x_init(gen); n_y = N_y_init(gen); n_theta = N_theta_init(gen); pf.init(gt[i].x + n_x, gt[i].y + n_y, gt[i].theta + n_theta, sigma_pos); } else { // Predict the vehicle's next state (noiseless). /**@todo should add noise to the velocity and yawrate. why not directly add noise to velocity and yawrate instead of adding to position ?*/ pf.prediction(delta_t, sigma_pos, position_meas[i - 1].velocity, position_meas[i - 1].yawrate); } // simulate the addition of noise to noiseless observation data. vector<LandmarkObs> noisy_observations; LandmarkObs obs; for (int j = 0; j < observations.size(); ++j) { n_x = N_obs_x(gen); n_y = N_obs_y(gen); obs = observations[j]; obs.x = obs.x + n_x; obs.y = obs.y + n_y; noisy_observations.push_back(obs); } // Update the weights and resample pf.updateWeights(sensor_range, sigma_landmark, noisy_observations, map); pf.resample(); // Calculate and output the average weighted error of the particle filter over all time steps so far. vector<Particle> particles = pf.particles; int num_particles = particles.size(); double highest_weight = 0.0; Particle best_particle; for (int i = 0; i < num_particles; ++i) { if (particles[i].weight > highest_weight) { highest_weight = particles[i].weight; best_particle = particles[i]; } } #ifdef DEBUG_OUTPUT std::cout<<"----------------------------"<<i<<"------------------------"<<std::endl; std::cout<<"weight:"<<highest_weight<<"\testimation: "<<best_particle.x<<"\t"<<best_particle.y<<"\t"<<best_particle.theta<<std::endl; std::cout<<"ground truth:"<<gt[i].x<<"\t"<<gt[i].y<<"\t"<<gt[i].theta<<std::endl; #endif double *avg_error = getError(gt[i].x, gt[i].y, gt[i].theta, best_particle.x, best_particle.y, best_particle.theta); for (int j = 0; j < 3; ++j) { total_error[j] += avg_error[j]; cum_mean_error[j] = total_error[j] / (double) (i + 1); } // Print the cumulative weighted error cout << "Cumulative mean weighted error: x " << cum_mean_error[0] << " y " << cum_mean_error[1] << " yaw " << cum_mean_error[2] << endl; // If the error is too high, say so and then exit. if (i >= time_steps_before_lock_required) { if (cum_mean_error[0] > max_translation_error || cum_mean_error[1] > max_translation_error || cum_mean_error[2] > max_yaw_error) { if (cum_mean_error[0] > max_translation_error) { cout << "Your x error, " << cum_mean_error[0] << " is larger than the maximum allowable error, " << max_translation_error << endl; } else { if (cum_mean_error[1] > max_translation_error) { cout << "Your y error, " << cum_mean_error[1] << " is larger than the maximum allowable error, " << max_translation_error << endl; } else { cout << "Your yaw error, " << cum_mean_error[2] << " is larger than the maximum allowable error, " << max_yaw_error << endl; } } return -1; } } } // Output the runtime for the filter. int stop = clock(); double runtime = (stop - start) / double(CLOCKS_PER_SEC); cout << "Runtime (sec): " << runtime << endl; // Print success if accuracy and runtime are sufficient (and this isn't just the starter code). if (runtime < max_runtime && pf.initialized()) { cout << "Success! Your particle filter passed!" << endl; } else { if (!pf.initialized()) { cout << "This is the starter code. You haven't initialized your filter." << endl; } else { cout << "Your runtime " << runtime << " is larger than the maximum allowable runtime, " << max_runtime << endl; return -1; } } return 0; }
faac417b85492f633129ec284259e982c4c8ae11
7c7ba64a2f18eb0f8713185e5491ef4557f996fe
/EndGame/EndGame/Src/SubSystems/RenderSubSystem/RendererApi.cpp
8304d24d56aaaacab102ae365dfb156fc4240426
[ "MIT" ]
permissive
siddharthgarg4/EndGame
f86963b5776984c26d2203ea3d8537a680b13a80
ba608714b3eacb5dc05d0c852db573231c867d8b
refs/heads/master
2022-11-27T03:21:53.787321
2020-07-30T21:12:02
2020-07-30T21:12:02
266,642,356
0
0
null
null
null
null
UTF-8
C++
false
false
240
cpp
// // RendererApi.cpp // // // Created by Siddharth on 19/06/20. // #include "RendererApi.hpp" namespace EndGame { //temporary setting rendererapi->api to OpenGl RendererApi::Api RendererApi::api = RendererApi::Api::OpenGl; }
0ec8b21e759003af7b453d55d966d2131df27444
ea401c3e792a50364fe11f7cea0f35f99e8f4bde
/released_plugins/v3d_plugins/bigneuron_AmosSironi_PrzemyslawGlowacki_SQBTree_plugin/libs/boost_1_58_0/boost/asio/ssl/detail/openssl_init.hpp
221709aa03bf0091973842040da738bbd078c858
[ "MIT" ]
permissive
Vaa3D/vaa3d_tools
edb696aa3b9b59acaf83d6d27c6ae0a14bf75fe9
e6974d5223ae70474efaa85e1253f5df1814fae8
refs/heads/master
2023-08-03T06:12:01.013752
2023-08-02T07:26:01
2023-08-02T07:26:01
50,527,925
107
86
MIT
2023-05-22T23:43:48
2016-01-27T18:19:17
C++
UTF-8
C++
false
false
3,063
hpp
// // ssl/detail/openssl_init.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // 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) // #ifndef BOOST_ASIO_SSL_DETAIL_OPENSSL_INIT_HPP #define BOOST_ASIO_SSL_DETAIL_OPENSSL_INIT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <cstring> #include <boost/asio/detail/noncopyable.hpp> #include <boost/asio/detail/shared_ptr.hpp> #include <boost/asio/ssl/detail/openssl_types.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace ssl { namespace detail { class openssl_init_base : private noncopyable { protected: // Class that performs the actual initialisation. class do_init; // Helper function to manage a do_init singleton. The static instance of the // openssl_init object ensures that this function is always called before // main, and therefore before any other threads can get started. The do_init // instance must be static in this function to ensure that it gets // initialised before any other global objects try to use it. BOOST_ASIO_DECL static boost::asio::detail::shared_ptr<do_init> instance(); #if !defined(SSL_OP_NO_COMPRESSION) \ && (OPENSSL_VERSION_NUMBER >= 0x00908000L) // Get an empty stack of compression methods, to be used when disabling // compression. BOOST_ASIO_DECL static STACK_OF(SSL_COMP)* get_null_compression_methods(); #endif // !defined(SSL_OP_NO_COMPRESSION) // && (OPENSSL_VERSION_NUMBER >= 0x00908000L) }; template <bool Do_Init = true> class openssl_init : private openssl_init_base { public: // Constructor. openssl_init() : ref_(instance()) { using namespace std; // For memmove. // Ensure openssl_init::instance_ is linked in. openssl_init* tmp = &instance_; memmove(&tmp, &tmp, sizeof(openssl_init*)); } // Destructor. ~openssl_init() { } #if !defined(SSL_OP_NO_COMPRESSION) \ && (OPENSSL_VERSION_NUMBER >= 0x00908000L) using openssl_init_base::get_null_compression_methods; #endif // !defined(SSL_OP_NO_COMPRESSION) // && (OPENSSL_VERSION_NUMBER >= 0x00908000L) private: // Instance to force initialisation of openssl at global scope. static openssl_init instance_; // Reference to singleton do_init object to ensure that openssl does not get // cleaned up until the last user has finished with it. boost::asio::detail::shared_ptr<do_init> ref_; }; template <bool Do_Init> openssl_init<Do_Init> openssl_init<Do_Init>::instance_; } // namespace detail } // namespace ssl } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #if defined(BOOST_ASIO_HEADER_ONLY) # include <boost/asio/ssl/detail/impl/openssl_init.ipp> #endif // defined(BOOST_ASIO_HEADER_ONLY) #endif // BOOST_ASIO_SSL_DETAIL_OPENSSL_INIT_HPP
ed1f1d697df82dccd2ea89bce27af20863a1a1c3
1c57e996dbbb390a2e4654de855e7f3fd04b69c5
/test/GenomeTest/QualityTest.cpp
161da295cd4970266fda96c6f68bbaa0603d80ed
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
BrainTwister/GeneHunter
20a906e6607a6058acd4f72fbfccb7d6d8f13578
c8990fac4ef48c4a3322053b34095e70ae591dd8
refs/heads/master
2020-05-30T06:38:35.699017
2017-01-31T14:35:34
2017-01-31T14:35:34
19,794,742
4
1
null
2016-09-23T15:47:57
2014-05-14T20:18:32
C++
UTF-8
C++
false
false
270
cpp
#include "GenomeLib/Quality.h" #include <gtest/gtest.h> using namespace GeneHunter; TEST(QualityTest, Default) { EXPECT_NEAR(1.0, static_cast<double>(FastqSanger::data[33]), 1e-4); EXPECT_NEAR(5.01187e-10, static_cast<double>(FastqSanger::data[126]), 1e-4); }
b9c6b0d13b1bf74410efa2f530a87b73db92aea0
07ee17f9fb57c0ccc9e4fe2c18410bd3f3eeec34
/darkstar/SimObjects/Inc/cdPlayerDlg.h
30ce11b470169deebf32ffff687478b7b6a21d71
[]
no_license
AlexHuck/TribesRebirth
1ea6ba27bc2af10527259d4d6cd4561a1793bccd
cf52c2e8c63f3da79e38cb3c153288d12003b123
refs/heads/master
2021-09-11T00:35:45.407177
2021-08-29T14:36:56
2021-08-29T14:36:56
226,741,338
0
0
null
2019-12-08T22:30:13
2019-12-08T22:30:12
null
UTF-8
C++
false
false
763
h
//------------------------------------------------------------------------------ // Description // // $Workfile$ // $Revision$ // $Author $ // $Modtime $ // //------------------------------------------------------------------------------ #ifndef _CDPLAYERDLG_H_ #define _CDPLAYERDLG_H_ #include <types.h> #include <gwDialog.h> #include <simBase.h> #include <redbook.h> class CDPlayerDlg : public GWDialog, public SimObject { private: typedef SimObject Parent; Redbook *pRb; Int32 curTrack; public: CDPlayerDlg(); bool onAdd(); void onCommand(int id, HWND hwndCtl, UINT codeNotify); void render(); void onDestroy(); // simobject methods bool processEvent(const SimEvent *event); }; #endif //_CDPLAYERDLG_H_
954fb06cb1f4ca049ac66394f287c1e7f91265d5
6c35f94aba4acd56c2e2ac594d7eaa41412509b6
/src/game/content/ennemis/Ennemi009.h
df5c1fe719c90cb466d03819a5f309f8ea864f77
[]
no_license
NicolasR/ZeldaNSQ
ce250a873e5781f7add45ca68d113f4eec53b8b8
875db791576c709660e372b87e1f6a2db1c77111
refs/heads/master
2021-07-21T10:37:51.007267
2017-11-10T14:30:17
2017-11-10T14:30:17
141,019,856
2
0
null
2018-07-15T10:56:40
2018-07-15T10:56:39
null
UTF-8
C++
false
false
780
h
/* Zelda Navi's Quest Copyright (C) 2013-2014 Vincent Jouillat Please send bugreports with examples or suggestions to www.zeldaroth.fr */ #ifndef __ENNEMI009_H__ #define __ENNEMI009_H__ #include "../../../engine/resources/WImage.h" #include "../../../engine/util/time/Chrono.h" #include "../types/Ennemi.h" class Ennemi009 : public Ennemi { public : Ennemi009(int x, int y); ~Ennemi009(); void ennLoop(); void draw(int offsetX, int offsetY); int getX(); int getY(); BoundingBox* getBoundingBox(); void reset(); private : int anim; int animMax; int vanim; WImage* image; Chrono chrono; BoundingBox box; }; #endif // Ennemi009.h
fd953869396fdace5594e94152da61011c3a7c2b
46a5d6e94017324b4b88c8c827cb2c62bee167ce
/excelformat/BasicExcel.cpp
49aa4cbe5ca41f62598dfd6f1cd1a551747a33be
[]
no_license
Roflincopter/massspec-convert
e7b1b93adff43e29fbc689a15a8cafd3a649ac75
a7cf68daf4565f4b58157f9933ca7e81c58e4d92
refs/heads/master
2020-12-30T09:58:02.769803
2014-04-09T11:50:44
2014-04-09T11:50:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
207,821
cpp
#include "ExcelFormat.hpp" #ifdef _MSC_VER #include <malloc.h> // for alloca() #endif #ifdef _WIN32 namespace WinCompFiles { CompoundFile::CompoundFile() { _pStg = NULL; } CompoundFile::~CompoundFile() { Close(); } // Compound File functions bool CompoundFile::Create(const wchar_t* filename) { HRESULT hr = StgCreateDocfile(filename, STGM_READWRITE|STGM_CREATE|STGM_SHARE_EXCLUSIVE, 0, &_pStg); return SUCCEEDED(hr); } bool CompoundFile::Open(const wchar_t* filename, ios_base::openmode mode/*=ios_base::in|ios_base::out*/) { int stgm_mode; if ((mode & (ios_base::in|ios_base::out)) == (ios_base::in|ios_base::out)) stgm_mode = STGM_READWRITE | STGM_SHARE_EXCLUSIVE; else if (mode & ios_base::out) stgm_mode = STGM_WRITE | STGM_SHARE_EXCLUSIVE; else stgm_mode = STGM_READ | STGM_SHARE_EXCLUSIVE; HRESULT hr = StgOpenStorage(filename, NULL, stgm_mode, NULL, 0, &_pStg); return SUCCEEDED(hr); } bool CompoundFile::Close() { if (_pStg) { _pStg->Release(); _pStg = NULL; return true; } else return false; } bool CompoundFile::IsOpen() { return _pStg != NULL; } // File functions CF_RESULT CompoundFile::MakeFile(const wchar_t* path) { IStream* pStream = NULL; HRESULT hr = _pStg->CreateStream(path, STGM_READWRITE|STGM_CREATE|STGM_SHARE_EXCLUSIVE, 0, 0, &pStream); if (pStream) pStream->Release(); return SUCCEEDED(hr)? SUCCESS: INVALID_PATH; } CF_RESULT CompoundFile::FileSize(const wchar_t* path, ULONGLONG& size) { IStream* pStream = NULL; // needs STGM_READWRITE in the StgCreateDocfile() call if (FAILED(_pStg->OpenStream(path, NULL, STGM_READ|STGM_SHARE_EXCLUSIVE, 0, &pStream))) return INVALID_PATH; STATSTG stat; HRESULT hr = pStream->Stat(&stat, STATFLAG_NONAME); if (pStream) pStream->Release(); if (SUCCEEDED(hr)) { size = stat.cbSize.QuadPart; return SUCCESS; } else return INVALID_PATH; } CF_RESULT CompoundFile::ReadFile(const wchar_t* path, char* data, ULONG size) { IStream* pStream = NULL; if (FAILED(_pStg->OpenStream(path, NULL, STGM_READ|STGM_SHARE_EXCLUSIVE, 0, &pStream))) return INVALID_PATH; ULONG read; HRESULT hr = pStream->Read(data, size, &read); if (pStream) pStream->Release(); return SUCCEEDED(hr)? SUCCESS: INVALID_PATH; } CF_RESULT CompoundFile::ReadFile(const wchar_t* path, vector<char>&data) { data.clear(); ULONGLONG dataSize; CF_RESULT ret = FileSize(path, dataSize); if (ret == SUCCESS) { if (dataSize) { if (dataSize == (ULONG)dataSize) { data.resize((size_t)dataSize); ret = ReadFile(path, &*(data.begin()), (ULONG)dataSize); } else ret = INVALID_SIZE; } else ret = SUCCESS; } return ret; } CF_RESULT CompoundFile::WriteFile(const wchar_t* path, const char* data, ULONG size) { IStream* pStream = NULL; if (FAILED(_pStg->OpenStream(path, NULL, STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &pStream))) return INVALID_PATH; ULONG written; HRESULT hr = pStream->Write(data, size, &written); if (pStream) pStream->Release(); return SUCCEEDED(hr)? SUCCESS: INVALID_PATH; } CF_RESULT CompoundFile::WriteFile(const wchar_t* path, const vector<char>&data, ULONG size) { IStream* pStream = NULL; if (FAILED(_pStg->OpenStream(path, NULL, STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &pStream))) return INVALID_PATH; ULONG written; HRESULT hr = pStream->Write(&*(data.begin()), size, &written); if (pStream) pStream->Release(); return SUCCEEDED(hr)? SUCCESS: INVALID_PATH; } // ANSI char functions bool CompoundFile::Create(const char* filename) { return Create(widen_string(filename).c_str()); } bool CompoundFile::Open(const char* filename, ios_base::openmode mode/*=ios_base::in|ios_base::out*/) { return Open(widen_string(filename).c_str(), mode); } CF_RESULT CompoundFile::MakeFile(const char* path) { return MakeFile(widen_string(path).c_str()); } CF_RESULT CompoundFile::FileSize(const char* path, ULONGLONG& size) { return FileSize(widen_string(path).c_str(), size); } CF_RESULT CompoundFile::ReadFile(const char* path, char* data, ULONG size) { return ReadFile(widen_string(path).c_str(), data, size); } CF_RESULT CompoundFile::ReadFile(const char* path, vector<char>& data) { return ReadFile(widen_string(path).c_str(), data); } CF_RESULT CompoundFile::WriteFile(const char* path, const char* data, ULONG size) { return WriteFile(widen_string(path).c_str(), data, size); } CF_RESULT CompoundFile::WriteFile(const char* path, const vector<char>& data, ULONG size) { return WriteFile(widen_string(path).c_str(), data, size); } } // namespace WinCompFiles #else // _WIN32 #if _MSC_VER>=1400 // VS 2005 #include <share.h> // _SH_DENYRW #endif namespace YCompoundFiles { /********************************** Start of Class Block *************************************/ // PURPOSE: Manage a file by treating it as blocks of data of a certain size. Block::Block() : blockSize_(512), fileSize_(0), indexEnd_(0), filename_(0) {} bool Block::Create(const wchar_t* filename) // PURPOSE: Create a new block file and open it. // PURPOSE: If file is present, truncate it and then open it. // PROMISE: Return true if file is successfully created and opened, false if otherwise. { // Create new file size_t filenameLength = wcslen(filename); char* name = new char[filenameLength+1]; wcstombs(name, filename, filenameLength); name[filenameLength] = 0; // Open the file while truncating any existing file bool ret = this->Open(filename, ios_base::in | ios_base::out | ios_base::trunc); delete[] name; return ret; } bool Block::Open(const wchar_t* filename, ios_base::openmode mode) // PURPOSE: Open an existing block file. // PROMISE: Return true if file is successfully opened, false if otherwise. { // Open existing file for reading or writing or both size_t filenameLength = wcslen(filename); filename_.resize(filenameLength+1, 0); wcstombs(&*(filename_.begin()), filename, filenameLength); #if _MSC_VER>=1400 // VS 2005 file_.open(&*(filename_.begin()), mode | ios_base::binary, _SH_DENYRW); #else file_.open(&*(filename_.begin()), mode | ios_base::binary); #endif if (!file_.is_open()) return false; mode_ = mode; // Calculate filesize if (mode & ios_base::in) { file_.seekg(0, ios_base::end); fileSize_ = (ULONG) file_.tellg(); } else if (mode & ios_base::out) { file_.seekp(0, ios_base::end); fileSize_ = (ULONG) file_.tellp(); } else { this->Close(); return false; } // Calculate last index + 1 indexEnd_ = fileSize_/blockSize_ + (fileSize_ % blockSize_ ? 1 : 0); return true; } bool Block::Close() // PURPOSE: Close the opened block file. // PROMISE: Return true if file is successfully closed, false if otherwise. { file_.close(); file_.clear(); filename_.clear(); fileSize_ = 0; indexEnd_ = 0; blockSize_ = 512; return !file_.is_open(); } bool Block::IsOpen() // PURPOSE: Check if the block file is still opened. // PROMISE: Return true if file is still opened, false if otherwise. { return file_.is_open(); } bool Block::Read(SECT index, char* block) // PURPOSE: Read a block of data from the opened file at the index position. // EXPLAIN: index is from [0..]. // PROMISE: Return true if data are successfully read, false if otherwise. { if (!(mode_ & ios_base::in)) return false; if (index < indexEnd_) { file_.seekg(index * blockSize_); file_.read(block, blockSize_); return !file_.fail(); } else return false; } bool Block::Write(SECT index, const char* block) // PURPOSE: Write a block of data to the opened file at the index position. // EXPLAIN: index is from [0..]. // PROMISE: Return true if data are successfully written, false if otherwise. { if (!(mode_ & ios_base::out)) return false; file_.seekp(index * blockSize_); file_.write(block, blockSize_); if (indexEnd_ <= index) { indexEnd_ = index + 1; fileSize_ += blockSize_; } // flush the file immediatelly file_.flush(); // return false on error return file_.good(); } bool Block::Swap(SECT index1, SECT index2) // PURPOSE: Swap two blocks of data in the opened file at the index positions. // EXPLAIN: index1 and index2 are from [0..]. // PROMISE: Return true if data are successfully swapped, false if otherwise. { if (!(mode_ & ios_base::out)) return false; if (index1 < indexEnd_ && index2 < indexEnd_) { if (index1 == index2) return true; char* block1 = new char[blockSize_]; if (!this->Read(index1, block1)) return false; char* block2 = new char[blockSize_]; if (!this->Read(index2, block2)) return false; if (!this->Write(index1, block2)) return false; if (!this->Write(index2, block1)) return false; delete[] block1; delete[] block2; return true; } else return false; } bool Block::Move(SECT from, SECT to) // PURPOSE: Move a block of data in the opened file from an index position to another index position. // EXPLAIN: from and to are from [0..]. // PROMISE: Return true if data are successfully moved, false if otherwise. { if (!(mode_ & ios_base::out)) return false; if (from<indexEnd_ && to<indexEnd_) { if (to > from) { for(SECT i=from; i!=to; ++i) { if (!this->Swap(i, i+1)) return false; } } else { for(SECT i=from; i!=to; --i) { if (!this->Swap(i, i-1)) return false; } } return true; } else return false; } bool Block::Insert(SECT index, const char* block) // PURPOSE: Insert a new block of data in the opened file at the index position. // EXPLAIN: index is from [0..]. // PROMISE: Return true if data are successfully inserted, false if otherwise. { if (!(mode_ & ios_base::out)) return false; if (index <= indexEnd_) { // Write block to end of file if (!this->Write(indexEnd_, block)) return false; // Move block to index if necessary if (index < indexEnd_-1) return this->Move(indexEnd_-1, index); else return true; } else { // Write block to index after end of file return this->Write(index, block); } } bool Block::Erase(SECT index) // PURPOSE: Erase a block of data in the opened file at the index position. // EXPLAIN: index is from [0..]. // PROMISE: Return true if data are successfully erased, false if otherwise. { if (!(mode_ & ios_base::out)) return false; if (index < indexEnd_) { fileSize_ -= blockSize_; indexEnd_ -= 1; // Read entire file except the block to be deleted into memory. char* buffer = new char[fileSize_]; for(SECT i=0, j=0; i!=indexEnd_+1; ++i) { file_.seekg(i*blockSize_); if (i != index) { file_.read(buffer+j*blockSize_, blockSize_); ++j; } } // Close / Clear / Open may lead to bugs when another process accesss the file (ie.: Anti-Virus) // file_.close(); // file_.open(&*(filename_.begin()), ios_base::out | ios_base::trunc | ios_base::binary); file_.write(buffer, fileSize_); // Write the new file. // flush the file immediatelly file_.flush(); // file_.close(); // file_.open(&*(filename_.begin()), mode_ | ios_base::binary); delete[] buffer; return true; } else return false; } bool Block::Erase(vector<SECT>& indices) // PURPOSE: Erase blocks of data in the opened file at the index positions. // EXPLAIN: Each index in indices is from [0..]. // PROMISE: Return true if data are successfully erased, false if otherwise. { if (!(mode_ & ios_base::out)) return false; // Read entire file except the blocks to be deleted into memory. ULONG maxIndices = (ULONG) indices.size(); fileSize_ -= maxIndices*blockSize_; char* buffer = new char[fileSize_]; for(SECT i=0, k=0; i!=indexEnd_; ++i) { file_.seekg(i*blockSize_); bool toDelete = false; for(size_t j=0; j<maxIndices; ++j) { if (i == indices[j]) { toDelete = true; break; } } if (!toDelete) { file_.read(buffer+k*blockSize_, blockSize_); ++k; } } indexEnd_ -= maxIndices; file_.write(buffer, fileSize_); // Write the new file. // flush the file immediatelly file_.flush(); delete[] buffer; return true; } /********************************** End of Class Block ***************************************/ /********************************** Start of Class Header ************************************/ // PURPOSE: Read and write data to a compound file header. CompoundFile::Header::Header() { _abSig = LONGINT_CONST(0xE11AB1A1E011CFD0); memset(&_clid, 0, sizeof(_clid)); _ulMinorVersion = 0x3B; _uDllVersion = 3; _uByteOrder = 0xFFFE; _uSectorShift = 9; _uMiniSectorShift = 6; _ulReserved1 = 0; _ulReserved2 = 0; _csectFat = 1; _sectDirStat = 1; _signature = 0; _ulMiniSectorCutOff = 0x1000; _usReserved = 0; _sectMiniFatStart = ENDOFCHAIN; _csectMiniFat = 0; _sectDifStart = ENDOFCHAIN; _csectDif = 0; _sectFat[0] = 0; // Initial BAT indices at block 0 (=block 1 in Block) fill(_sectFat+1, _sectFat+109, FREESECT); // Rest of the BATArray is empty Initialize(); } void CompoundFile::Header::Write(char* block) // PURPOSE: Write header information into a block of data. // REQUIRE: Block of data must be at least 512 bytes in size. { LittleEndian::Write(block, _abSig, 0x0000, 8); // LittleEndian::Write(block, _clid, 0x0008, 16); LittleEndian::Write(block, *(const LONGINT*)&_clid.Data1, 0x0008, 8); LittleEndian::Write(block, *(const LONGINT*)&_clid.Data4, 0x0010, 8); LittleEndian::Write(block, _ulMinorVersion, 0x0018, 2); LittleEndian::Write(block, _uDllVersion, 0x001A, 2); LittleEndian::Write(block, _uByteOrder, 0x001C, 2); LittleEndian::Write(block, _uSectorShift, 0x001E, 2); LittleEndian::Write(block, _uMiniSectorShift, 0x0020, 2); LittleEndian::Write(block, _usReserved, 0x0022, 2); LittleEndian::Write(block, _ulReserved1, 0x0024, 4); LittleEndian::Write(block, _ulReserved2, 0x0028, 4); LittleEndian::Write(block, _csectFat, 0x002C, 4); LittleEndian::Write(block, _sectDirStat, 0x0030, 4); LittleEndian::Write(block, _signature, 0x0034, 4); LittleEndian::Write(block, _ulMiniSectorCutOff, 0x0038, 4); LittleEndian::Write(block, _sectMiniFatStart, 0x003C, 4); LittleEndian::Write(block, _csectMiniFat, 0x0040, 4); LittleEndian::Write(block, _sectDifStart, 0x0044, 4); LittleEndian::Write(block, _csectDif, 0x0048, 4); for(int i=0; i<109; ++i) LittleEndian::Write(block, _sectFat[i], 0x004C+i*4, 4); } void CompoundFile::Header::Read(char* block) // PURPOSE: Read header information from a block of data. // REQUIRE: Block of data must be at least 512 bytes in size. { LittleEndian::Read(block, _abSig, 0x0000, 8); // LittleEndian::Read(block, _clid, 0x0008, 16); LittleEndian::Read(block, *(LONGINT*)&_clid.Data1, 0x0008, 8); LittleEndian::Read(block, *(LONGINT*)&_clid.Data4, 0x0010, 8); LittleEndian::Read(block, _ulMinorVersion, 0x0018, 2); LittleEndian::Read(block, _uDllVersion, 0x001A, 2); LittleEndian::Read(block, _uByteOrder, 0x001C, 2); LittleEndian::Read(block, _uSectorShift, 0x001E, 2); LittleEndian::Read(block, _uMiniSectorShift, 0x0020, 2); LittleEndian::Read(block, _usReserved, 0x0022, 2); LittleEndian::Read(block, _ulReserved1, 0x0024, 4); LittleEndian::Read(block, _ulReserved2, 0x0028, 4); LittleEndian::Read(block, _csectFat, 0x002C, 4); LittleEndian::Read(block, _sectDirStat, 0x0030, 4); LittleEndian::Read(block, _signature, 0x0034, 4); LittleEndian::Read(block, _ulMiniSectorCutOff, 0x0038, 4); LittleEndian::Read(block, _sectMiniFatStart, 0x003C, 4); LittleEndian::Read(block, _csectMiniFat, 0x0040, 4); LittleEndian::Read(block, _sectDifStart, 0x0044, 4); LittleEndian::Read(block, _csectDif, 0x0048, 4); for(int i=0; i<109; ++i) LittleEndian::Read(block, _sectFat[i], 0x004C+i*4, 4); Initialize(); } void CompoundFile::Header::Initialize() { bigBlockSize_ = 1 << _uSectorShift; // Calculate each big block size. smallBlockSize_ = 1 << _uMiniSectorShift; // Calculate each small block size. } /********************************** End of Class Header **************************************/ /********************************** Start of Class DirectoryEntry **********************************/ // PURPOSE: Read and write data to a compound file property. CompoundFile::DirectoryEntry::DirectoryEntry() { fill(name_, name_+32, 0); _cb_namesize = 0; _mse = STGTY_STORAGE; _bflags = DE_BLACK; _sidLeftSib = -1; _sidRightSib = -1; _sidChild = -1; memset(&_clsId, 0, sizeof(_clsId)); _dwUserFlags = 0; _time[0].dwHighDateTime = 0; _time[0].dwLowDateTime = 0; _time[1].dwHighDateTime = 0; _time[1].dwLowDateTime = 0; _sectStart = ENDOFCHAIN; _ulSize = 0; _dptPropType = 0; } void CompoundFile::DirectoryEntry::Write(char* block) // PURPOSE: Write property information from a block of data. // REQUIRE: Block of data must be at least 128 bytes in size. { LittleEndian::WriteString(block, name_, 0x00, 32); LittleEndian::Write(block, _cb_namesize, 0x40, 2); LittleEndian::Write(block, _mse, 0x42, 1); LittleEndian::Write(block, _bflags, 0x43, 1); LittleEndian::Write(block, _sidLeftSib, 0x44, 4); LittleEndian::Write(block, _sidRightSib, 0x48, 4); LittleEndian::Write(block, _sidChild, 0x4C, 4); // LittleEndian::Write(block, _clsId, 0x50, 16); LittleEndian::Write(block, *(const LONGINT*)&_clsId.Data1, 0x50, 16); LittleEndian::Write(block, *(const LONGINT*)&_clsId.Data4, 0x58, 16); LittleEndian::Write(block, _dwUserFlags, 0x60, 4); LittleEndian::Write(block, _time[0].dwLowDateTime, 0x64, 4); LittleEndian::Write(block, _time[0].dwHighDateTime, 0x68, 4); LittleEndian::Write(block, _time[1].dwLowDateTime, 0x6C, 4); LittleEndian::Write(block, _time[1].dwHighDateTime, 0x70, 4); LittleEndian::Write(block, _sectStart, 0x74, 4); LittleEndian::Write(block, _ulSize, 0x78, 4); LittleEndian::Write(block, _dptPropType, 0x7C, 2); } void CompoundFile::DirectoryEntry::Read(char* block) // PURPOSE: Read property information from a block of data. // REQUIRE: Block of data must be at least 128 bytes in size. { LittleEndian::ReadString(block, name_, 0x00, 32); LittleEndian::Read(block, _cb_namesize, 0x40, 2); LittleEndian::Read(block, _mse, 0x42, 1); LittleEndian::Read(block, _bflags, 0x43, 1); LittleEndian::Read(block, _sidLeftSib, 0x44, 4); LittleEndian::Read(block, _sidRightSib, 0x48, 4); LittleEndian::Read(block, _sidChild, 0x4C, 4); // LittleEndian::Read(block, _clsId, 0x50, 16); LittleEndian::Read(block, *(LONGINT*)&_clsId.Data1, 0x50, 16); LittleEndian::Read(block, *(LONGINT*)&_clsId.Data4, 0x58, 16); LittleEndian::Read(block, _dwUserFlags, 0x60, 4); LittleEndian::Read(block, _time[0].dwLowDateTime, 0x64, 4); LittleEndian::Read(block, _time[0].dwHighDateTime, 0x68, 4); LittleEndian::Read(block, _time[1].dwLowDateTime, 0x6C, 4); LittleEndian::Read(block, _time[1].dwHighDateTime, 0x70, 4); LittleEndian::Read(block, _sectStart, 0x74, 4); LittleEndian::Read(block, _ulSize, 0x78, 4); LittleEndian::Read(block, _dptPropType, 0x7C, 2); } /********************************** End of Class DirectoryEntry ************************************/ /********************************** Start of Class PropertyTree **********************************/ CompoundFile::PropertyTree::PropertyTree() {} CompoundFile::PropertyTree::~PropertyTree() { size_t maxChildren = children_.size(); for(size_t i=0; i<maxChildren; ++i) delete children_[i]; } /********************************** End of Class PropertyTree ************************************/ /********************************** Start of Class CompoundFile ******************************/ // PURPOSE: Manage a compound file. CompoundFile::CompoundFile() : block_(512), dirEntries_(0), propertyTrees_(0), blocksIndices_(0), sblocksIndices_(0) {} CompoundFile::~CompoundFile() {this->Close();} /************************* Compound File Functions ***************************/ bool CompoundFile::Create(const wchar_t* filename) // PURPOSE: Create a new compound file and open it. // PURPOSE: If file is present, truncate it and then open it. // PROMISE: Return true if file is successfully created and opened, false if otherwise. { Close(); if (!file_.Create(filename)) return false; // Write compound file header header_ = Header(); SaveHeader(); // Save BAT blocksIndices_.clear(); blocksIndices_.resize(128, -1); blocksIndices_[0] = FATSECT; blocksIndices_[1] = ENDOFCHAIN; SaveBAT(); // Save properties DirectoryEntry* root = new DirectoryEntry; wcscpy(root->name_, L"Root Entry"); root->_mse = STGTY_ROOT; dirEntries_.push_back(root); SaveProperties(); // Set property tree propertyTrees_ = new PropertyTree; propertyTrees_->parent_ = 0; propertyTrees_->self_ = dirEntries_[0]; propertyTrees_->index_ = 0; currentDirectory_ = propertyTrees_; return true; } bool CompoundFile::Open(const wchar_t* filename, ios_base::openmode mode) // PURPOSE: Open an existing compound file. // PROMISE: Return true if file is successfully opened, false if otherwise. { Close(); if (!file_.Open(filename, mode)) return false; // Load header if (!LoadHeader()) return false; // Load BAT information LoadBAT(); // Load properties propertyTrees_ = new PropertyTree; LoadProperties(); currentDirectory_ = propertyTrees_; return true; } bool CompoundFile::Close() // PURPOSE: Close the opened compound file. // PURPOSE: Reset BAT indices, SBAT indices, properties and properties tree information. // PROMISE: Return true if file is successfully closed, false if otherwise. { blocksIndices_.clear(); sblocksIndices_.clear(); ULONG maxProperties = (ULONG) dirEntries_.size(); for(size_t i=0; i<maxProperties; ++i) { if (dirEntries_[i]) delete dirEntries_[i]; } dirEntries_.clear(); if (propertyTrees_) { delete propertyTrees_; propertyTrees_ = 0; } previousDirectories_.clear(); currentDirectory_ = 0; if (file_.IsOpen()) file_.Close(); return true; } bool CompoundFile::IsOpen() // PURPOSE: Check if the compound file is still opened. // PROMISE: Return true if file is still opened, false if otherwise. { return file_.IsOpen(); } /************************* Directory Functions ***************************/ int CompoundFile::ChangeDirectory(const wchar_t* path) // PURPOSE: Change to a different directory in the compound file. // PROMISE: Current directory will not be changed if directory is not present. { previousDirectories_.push_back(currentDirectory_); // Handle special cases if (wcscmp(path, L".") == 0) { // Current directory previousDirectories_.pop_back(); return SUCCESS; } if (wcscmp(path, L"..") == 0) { // Go up 1 directory if (currentDirectory_->parent_ != 0) { currentDirectory_ = currentDirectory_->parent_; } previousDirectories_.pop_back(); return SUCCESS; } if (wcscmp(path, L"\\") == 0) { // Go to root directory currentDirectory_ = propertyTrees_; previousDirectories_.pop_back(); return SUCCESS; } // Handle normal cases ULONG ipos = 0; ULONG npos = 0; size_t pathLength = wcslen(path); if (pathLength > 0 && path[0] == L'\\') { // Start from root directory currentDirectory_ = propertyTrees_; ++ipos; ++npos; } do { for(; npos<pathLength; ++npos) { if (path[npos] == L'\\') break; } wchar_t* directory = new wchar_t[npos-ipos+1]; copy(path+ipos, path+npos, directory); directory[npos-ipos] = 0; currentDirectory_ = FindProperty(currentDirectory_, directory); delete[] directory; ipos = npos + 1; npos = ipos; if (currentDirectory_ == 0) { // Directory not found currentDirectory_ = previousDirectories_.back(); previousDirectories_.pop_back(); return DIRECTORY_NOT_FOUND; } } while(npos < pathLength); previousDirectories_.pop_back(); return SUCCESS; } int CompoundFile::MakeDirectory(const wchar_t* path) // PURPOSE: Create a new directory in the compound file. // PROMISE: Directory will not be created if it is already present or // PROMISE: a file with the same name is present. { previousDirectories_.push_back(currentDirectory_); DirectoryEntry* property = new DirectoryEntry; property->_mse = STGTY_STORAGE; int ret = MakeProperty(path, property); currentDirectory_ = previousDirectories_.back(); previousDirectories_.pop_back(); SaveHeader(); SaveBAT(); SaveProperties(); return ret; } /************************* File Functions ***************************/ int CompoundFile::MakeFile(const wchar_t* path) // PURPOSE: Create a new file in the compound file. // PROMISE: File will not be created if it is already present or // PROMISE: a directory with the same name is present. { previousDirectories_.push_back(currentDirectory_); DirectoryEntry* property = new DirectoryEntry; property->_mse = STGTY_STREAM; int ret = MakeProperty(path, property); currentDirectory_ = previousDirectories_.back(); previousDirectories_.pop_back(); SaveHeader(); SaveBAT(); SaveProperties(); return ret; } int CompoundFile::FileSize(const wchar_t* path, ULONG& size) // PURPOSE: Get the size of a file in the compound file. // PROMISE: Return the data size stored in the Root Entry if path = "\". // PROMISE: size will not be set if file is not present in the compound file. { // Special case of reading root entry if (wcscmp(path, L"\\") == 0) { size = propertyTrees_->self_->_ulSize; return SUCCESS; } // Check to see if file is present in the specified directory. PropertyTree* property = FindProperty(path); if (!property) return FILE_NOT_FOUND; else { size = property->self_->_ulSize; return SUCCESS; } } int CompoundFile::ReadFile(const wchar_t* path, char* data) // PURPOSE: Read a file's data in the compound file. // REQUIRE: data must be large enough to receive the file's data. // REQUIRE: The required data size can be obtained by using FileSize(). // PROMISE: Returns the small blocks of data stored by the Root Entry if path = "\". // PROMISE: data will not be set if file is not present in the compound file. { // Special case of reading root entry char* buffer; if (wcscmp(path, L"\\") == 0) { buffer = new char[DataSize(propertyTrees_->self_->_sectStart, true)]; ReadData(propertyTrees_->self_->_sectStart, buffer, true); copy(buffer, buffer+propertyTrees_->self_->_ulSize, data); delete[] buffer; return SUCCESS; } // Check to see if file is present in the specified directory. PropertyTree* property = FindProperty(path); if (!property) return FILE_NOT_FOUND; if (property->self_->_ulSize >= 4096) { // Data stored in normal big blocks buffer = new char[DataSize(property->self_->_sectStart, true)]; ReadData(property->self_->_sectStart, buffer, true); } else { // Data stored in small blocks buffer = new char[DataSize(property->self_->_sectStart, false)]; ReadData(property->self_->_sectStart, buffer, false); } // Truncated the retrieved data to the actual file size. copy(buffer, buffer+property->self_->_ulSize, data); delete[] buffer; return SUCCESS; } int CompoundFile::ReadFile(const wchar_t* path, vector<char>& data) // PURPOSE: Read a file's data in the compound file. // PROMISE: Returns the small blocks of data stored by the Root Entry if path = "\". // PROMISE: data will not be set if file is not present in the compound file. { data.clear(); ULONG dataSize; int ret = FileSize(path, dataSize); if (ret != SUCCESS) return ret; data.resize(dataSize); return ReadFile(path, &*(data.begin())); } int CompoundFile::WriteFile(const wchar_t* path, const char* data, ULONG size) // PURPOSE: Write data to a file in the compound file. // PROMISE: The file's original data will be replaced by the new data. { PropertyTree* property = FindProperty(path); if (!property) return FILE_NOT_FOUND; if (property->self_->_ulSize >= 4096) { if (size >= 4096) property->self_->_sectStart = WriteData(data, size, property->self_->_sectStart, true); else { property->self_->_sectStart = WriteData(0, 0, property->self_->_sectStart, true); property->self_->_sectStart = WriteData(data, size, property->self_->_sectStart, false); } } else { if (size < 4096) property->self_->_sectStart = WriteData(data, size, property->self_->_sectStart, false); else { property->self_->_sectStart = WriteData(0, 0, property->self_->_sectStart, false); property->self_->_sectStart = WriteData(data, size, property->self_->_sectStart, true); } } property->self_->_ulSize = size; SaveHeader(); SaveBAT(); SaveProperties(); return SUCCESS; } int CompoundFile::WriteFile(const wchar_t* path, const vector<char>& data, ULONG size) // PURPOSE: Write data to a file in the compound file. // PROMISE: The file's original data will be replaced by the new data. { return WriteFile(path, &*(data.begin()), size); } /*************ANSI char compound file, directory and file functions******************/ bool CompoundFile::Create(const char* filename) { size_t filenameLength = strlen(filename); wchar_t* wname = new wchar_t[filenameLength+1]; mbstowcs(wname, filename, filenameLength); wname[filenameLength] = 0; bool ret = Create(wname); delete[] wname; return ret; } bool CompoundFile::Open(const char* filename, ios_base::openmode mode) { size_t filenameLength = strlen(filename); wchar_t* wname = new wchar_t[filenameLength+1]; mbstowcs(wname, filename, filenameLength); wname[filenameLength] = 0; bool ret = Open(wname, mode); delete[] wname; return ret; } int CompoundFile::ChangeDirectory(const char* path) { size_t pathLength = strlen(path); wchar_t* wpath = new wchar_t[pathLength+1]; mbstowcs(wpath, path, pathLength); wpath[pathLength] = 0; int ret = ChangeDirectory(wpath); delete[] wpath; return ret; } int CompoundFile::MakeDirectory(const char* path) { size_t pathLength = strlen(path); wchar_t* wpath = new wchar_t[pathLength+1]; mbstowcs(wpath, path, pathLength); wpath[pathLength] = 0; int ret = MakeDirectory(wpath); delete[] wpath; return ret; } int CompoundFile::MakeFile(const char* path) { size_t pathLength = strlen(path); wchar_t* wpath = new wchar_t[pathLength+1]; mbstowcs(wpath, path, pathLength); wpath[pathLength] = 0; int ret = MakeFile(wpath); delete[] wpath; return ret; } int CompoundFile::FileSize(const char* path, ULONG& size) { size_t pathLength = strlen(path); wchar_t* wpath = new wchar_t[pathLength+1]; mbstowcs(wpath, path, pathLength); wpath[pathLength] = 0; int ret = FileSize(wpath, size); delete[] wpath; return ret; } int CompoundFile::ReadFile(const char* path, char* data) { size_t pathLength = strlen(path); wchar_t* wpath = new wchar_t[pathLength+1]; mbstowcs(wpath, path, pathLength); wpath[pathLength] = 0; int ret = ReadFile(wpath, data); delete[] wpath; return ret; } int CompoundFile::ReadFile(const char* path, vector<char>& data) { size_t pathLength = strlen(path); wchar_t* wpath = new wchar_t[pathLength+1]; mbstowcs(wpath, path, pathLength); wpath[pathLength] = 0; int ret = ReadFile(wpath, data); delete[] wpath; return ret; } int CompoundFile::WriteFile(const char* path, const char* data, ULONG size) { size_t pathLength = strlen(path); wchar_t* wpath = new wchar_t[pathLength+1]; mbstowcs(wpath, path, pathLength); wpath[pathLength] = 0; int ret = WriteFile(wpath, data, size); delete[] wpath; return ret; } int CompoundFile::WriteFile(const char* path, const vector<char>& data, ULONG size) { size_t pathLength = strlen(path); wchar_t* wpath = new wchar_t[pathLength+1]; mbstowcs(wpath, path, pathLength); wpath[pathLength] = 0; int ret = WriteFile(wpath, data, size); delete[] wpath; return ret; } /*********************** Inaccessible General Functions ***************************/ void CompoundFile::IncreaseLocationReferences(vector<SECT> indices) // PURPOSE: Increase block location references in header, BAT indices and properties, // PURPOSE: which will be affected by the insertion of new indices contained in indices. // PROMISE: Block location references which are smaller than all the new indices // PROMISE: will not be affected. // PROMISE: SBAT location references will not be affected. // PROMISE: Changes will not be written to compound file. { ULONG maxIndices = (ULONG) indices.size(); // Change BAT Array references {for(int i=0; i<109 && header_._sectFat[i]!=FREESECT; ++i) { ULONG count = 0; for(size_t j=0; j<maxIndices; ++j) { if (header_._sectFat[i] >= indices[j] && header_._sectFat[i] != FREESECT) ++count; } header_._sectFat[i] += count; }} // Change XBAT start block if any if (header_._csectDif) { ULONG count = 0; for(size_t j=0; j<maxIndices; ++j) { if (header_._sectDifStart >= indices[j] && header_._sectDifStart != ENDOFCHAIN) ++count; } header_._sectDifStart += count; } // Change SBAT start block if any if (header_._csectMiniFat) { ULONG count = 0; for(size_t j=0; j<maxIndices; ++j) { if (header_._sectMiniFatStart >= indices[j] && header_._sectMiniFatStart != ENDOFCHAIN) ++count; } header_._sectMiniFatStart += count; } // Change BAT block indices size_t maxBATindices = blocksIndices_.size(); {for(size_t i=0; i<maxBATindices && blocksIndices_[i]!=FREESECT; ++i) { ULONG count = 0; for(size_t j=0; j<maxIndices; ++j) { if (blocksIndices_[i] > indices[j] && blocksIndices_[i] != ENDOFCHAIN && blocksIndices_[i] != FATSECT) ++count; } blocksIndices_[i] += count; }} // Change properties start block ULONG count = 0; {for(size_t i=0; i<maxIndices; ++i) { if (header_._sectDirStat >= indices[i] && header_._sectDirStat != ENDOFCHAIN) ++count; }} header_._sectDirStat += count; // Change individual properties start block if their size is more than 4096 ULONG maxProperties = (ULONG) dirEntries_.size(); if (!dirEntries_.empty()) { ULONG count = 0; for(size_t j=0; j<maxIndices; ++j) { if (dirEntries_[0]->_sectStart >= indices[j] && dirEntries_[0]->_sectStart != ENDOFCHAIN) ++count; } dirEntries_[0]->_sectStart += count; } {for(size_t i=1; i<maxProperties; ++i) { if (dirEntries_[i]->_ulSize >= 4096) { ULONG count = 0; for(size_t j=0; j<maxIndices; ++j) { if (dirEntries_[i]->_sectStart >= indices[j] && dirEntries_[i]->_sectStart != ENDOFCHAIN) ++count; } dirEntries_[i]->_sectStart += count; } }} } void CompoundFile::DecreaseLocationReferences(vector<SECT> indices) // PURPOSE: Decrease block location references in header, BAT indices and properties, // PURPOSE: which will be affected by the deletion of indices contained in indices. // PROMISE: BAT indices pointing to a deleted index will be redirected to point to // PROMISE: the location where the deleted index original points to. // PROMISE: Block location references which are smaller than all the new indices // PROMISE: will not be affected. // PROMISE: SBAT location references will not be affected. // PROMISE: Changes will not be written to compound file. { ULONG maxIndices = (ULONG) indices.size(); // Change BAT Array references {for(int i=0; i<109 && header_._sectFat[i]!=FREESECT; ++i) { ULONG count = 0; for(size_t j=0; j<maxIndices; ++j) { if (header_._sectFat[i] > indices[j] && header_._sectFat[i] != FREESECT) ++count; } header_._sectFat[i] -= count; }} // Change XBAT start block if any if (header_._csectDif) { ULONG count = 0; for(size_t j=0; j<maxIndices; ++j) { if (header_._sectDifStart > indices[j] && header_._sectDifStart != ENDOFCHAIN) ++count; } header_._sectDifStart -= count; } // Change SBAT start block if any if (header_._csectMiniFat) { ULONG count = 0; for(size_t j=0; j<maxIndices; ++j) { if (header_._sectMiniFatStart > indices[j] && header_._sectMiniFatStart != ENDOFCHAIN) ++count; } header_._sectMiniFatStart -= count; } // Change BAT block indices // Redirect BAT indices pointing to a deleted index to point to // the location where the deleted index original points to. size_t maxBATindices = blocksIndices_.size(); {for(size_t i=0; i<maxBATindices && blocksIndices_[i]!=FREESECT; ++i) { bool end; do { end = true; for(size_t j=0; j<maxIndices; ++j) { if (blocksIndices_[i] == indices[j]) { blocksIndices_[i] = blocksIndices_[indices[j]]; end = false; break; } } } while(!end); }} // Erase indices to be deleted from the block indices sort (indices.begin(), indices.end(), greater<size_t>()); {for(size_t i=0; i<maxIndices; ++i) { blocksIndices_.erase(blocksIndices_.begin()+indices[i]); blocksIndices_.push_back(-1); }} // Decrease block location references for affected block indices. {for(size_t i=0; i<maxBATindices && blocksIndices_[i]!=FREESECT; ++i) { ULONG count = 0; for(size_t j=0; j<maxIndices; ++j) { if (blocksIndices_[i] > indices[j] && blocksIndices_[i] != ENDOFCHAIN && blocksIndices_[i] != FATSECT) ++count; } blocksIndices_[i] -= count; }} // Change properties start block ULONG count = 0; {for(size_t i=0; i<maxIndices; ++i) { if (header_._sectDirStat > indices[i] && header_._sectDirStat != ENDOFCHAIN) ++count; }} header_._sectDirStat -= count; ULONG maxProperties = (ULONG) dirEntries_.size(); // Change Root Entry start block if (!dirEntries_.empty()) { ULONG count = 0; for(size_t j=0; j<maxIndices; ++j) { if (dirEntries_[0]->_sectStart > indices[j] && dirEntries_[0]->_sectStart != ENDOFCHAIN) ++count; } dirEntries_[0]->_sectStart -= count; } {for(size_t i=1; i<maxProperties; ++i) { if (dirEntries_[i]->_ulSize >= 4096) { // Change individual properties start block if their size is more than 4096 ULONG count = 0; for(size_t j=0; j<maxIndices; ++j) { if (dirEntries_[i]->_sectStart > indices[j] && dirEntries_[i]->_sectStart != ENDOFCHAIN) ++count; } dirEntries_[i]->_sectStart -= count; } }} } void CompoundFile::SplitPath(const wchar_t* path, wchar_t*& parentpath, wchar_t*& propertyname) // PURPOSE: Get a path's parent path and its name. // EXPLAIN: E.g. path = "\\Abc\\def\\ghi => parentpath = "\\Abc\\def", propertyname = "ghi". // REQUIRE: Calling function is responsible for deleting the memory created for // REQUIRE: parentpath and propertyname. { int pathLength = (int) wcslen(path); int npos; for(npos=pathLength-1; npos>0; --npos) { if (path[npos] == L'\\') break; } if (npos != 0) { // Get parent path if available parentpath = new wchar_t[npos+1]; copy(path, path+npos, parentpath); parentpath[npos] = 0; ++npos; } // Get property name (ignore initial "\" if present) if (npos==0 && pathLength>0 && path[0]==L'\\') ++npos; propertyname = new wchar_t[pathLength-npos+1]; copy(path+npos, path+pathLength, propertyname); propertyname[pathLength-npos] = 0; } /*********************** Inaccessible Header Functions ***************************/ bool CompoundFile::LoadHeader() // PURPOSE: Load header information for compound file. // PROMISE: Return true if file header contain magic number, false if otherwise. { file_.Read(0, &*(block_.begin())); header_.Read(&*(block_.begin())); // Check magic number to see if it is a compound file if (header_._abSig != LONGINT_CONST(0xE11AB1A1E011CFD0)) return false; block_.resize(header_.bigBlockSize_); // Resize buffer block file_.SetBlockSize(header_.bigBlockSize_); // Resize block array block size return true; } void CompoundFile::SaveHeader() // PURPOSE: Save header information for compound file. { header_.Write(&*(block_.begin())); file_.Write(0, &*(block_.begin())); } /*********************** Inaccessible BAT Functions ***************************/ void CompoundFile::LoadBAT() // PURPOSE: Load all block allocation table information for compound file. { // Read BAT indices {for(size_t i=0; i<header_._csectFat; ++i) { // Load blocksIndices_ blocksIndices_.resize(blocksIndices_.size()+128, -1); file_.Read(header_._sectFat[i]+1, &*(block_.begin())); for(int j=0; j<128; ++j) LittleEndian::Read(&*(block_.begin()), blocksIndices_[j+i*128], j*4, 4); }} // Read XBAT indices {for(FSINDEX i=0; i<header_._csectDif; ++i) { blocksIndices_.resize(blocksIndices_.size()+128, -1); file_.Read(header_._sectDifStart+i+1, &*(block_.begin())); for(int j=0; j<128; ++j) LittleEndian::Read(&*(block_.begin()), blocksIndices_[j+((i+109)*128)], j*4, 4); }} // Read SBAT indices {for(FSINDEX i=0; i<header_._csectMiniFat; ++i) { sblocksIndices_.resize(sblocksIndices_.size()+128, -1); file_.Read(header_._sectMiniFatStart+i+1, &*(block_.begin())); for(int j=0; j<128; ++j) LittleEndian::Read(&*(block_.begin()), sblocksIndices_[j+i*128], j*4, 4); }} } void CompoundFile::SaveBAT() // PURPOSE: Save all block allocation table information for compound file. { // Write BAT indices {for(FSINDEX i=0; i<header_._csectFat; ++i) { for(int j=0; j<128; ++j) LittleEndian::Write(&*(block_.begin()), blocksIndices_[j+i*128], j*4, 4); file_.Write(header_._sectFat[i]+1, &*(block_.begin())); }} // Write XBAT indices {for(FSINDEX i=0; i<header_._csectDif; ++i) { for(int j=0; j<128; ++j) LittleEndian::Write(&*(block_.begin()), blocksIndices_[j+((i+109)*128)], j*4, 4); file_.Write(header_._sectDifStart+i+1, &*(block_.begin())); }} // Write SBAT indices {for(FSINDEX i=0; i<header_._csectMiniFat; ++i) { for(int j=0; j<128; ++j) LittleEndian::Write(&*(block_.begin()), sblocksIndices_[j+i*128], j*4, 4); file_.Write(header_._sectMiniFatStart+i+1, &*(block_.begin())); }} } ULONG CompoundFile::DataSize(SECT startIndex, bool isBig) // PURPOSE: Gets the total size occupied by a property, starting from startIndex. // EXPLAIN: isBig is true if property uses big blocks, false if it uses small blocks. // PROMISE: Returns the total size occupied by the property which is the total // PROMISE: number of blocks occupied multiply by the block size. { vector<SECT> indices; if (isBig) { GetBlockIndices(startIndex, indices, true); return (ULONG)indices.size() * header_.bigBlockSize_; } else { GetBlockIndices(startIndex, indices, false); return (ULONG)indices.size() * header_.smallBlockSize_; } } ULONG CompoundFile::ReadData(SECT startIndex, char* data, bool isBig) // PURPOSE: Read a property's data, starting from startIndex. // REQUIRE: data must be large enough to receive the property's data // REQUIRE: The required data size can be obtained by using DataSize(). // EXPLAIN: isBig is true if property uses big blocks, false if it uses small blocks. // PROMISE: Returns the total size occupied by the property which is the total // PROMISE: number of blocks occupied multiply by the block size. { vector<SECT> indices; if (isBig) { GetBlockIndices(startIndex, indices, true); ULONG maxIndices = (ULONG) indices.size(); for(size_t i=0; i<maxIndices; ++i) file_.Read(indices[i]+1, data+i*header_.bigBlockSize_); return maxIndices*header_.bigBlockSize_; } else { GetBlockIndices(startIndex, indices, false); size_t minIndex = *min_element(indices.begin(), indices.end()); // size_t maxIndex = *max_element(indices.begin(), indices.end()); size_t smallBlocksPerBigBlock = header_.bigBlockSize_ / header_.smallBlockSize_; size_t minBlock = minIndex / smallBlocksPerBigBlock; // size_t maxBlock = maxIndex / smallBlocksPerBigBlock + // (maxIndex % smallBlocksPerBigBlock ? 1 : 0); // size_t totalBlocks = maxBlock - minBlock; char* buffer = new char[DataSize(dirEntries_[0]->_sectStart, true)]; ReadData(dirEntries_[0]->_sectStart, buffer, true); ULONG maxIndices = (ULONG) indices.size(); for(size_t i=0; i<maxIndices; ++i) { size_t start = (indices[i] - minBlock*smallBlocksPerBigBlock)*header_.smallBlockSize_; copy(buffer+start, buffer+start+header_.smallBlockSize_, data+i*header_.smallBlockSize_); } delete[] buffer; return maxIndices*header_.smallBlockSize_; } } SECT CompoundFile::WriteData(const char* data, ULONG size, SECT startIndex, bool isBig) // PURPOSE: Write data to a property, starting from startIndex. // EXPLAIN: startIndex can be ENDOFCHAIN if property initially has no data. // EXPLAIN: isBig is true if property uses big blocks, false if it uses small blocks. // PROMISE: The file's original data will be replaced by the new data. // PROMISE: Returns the startIndex of new data for the property. { if (isBig) { if (size==0 && startIndex==ENDOFCHAIN) return startIndex; // Get present indices vector<SECT> indices; GetBlockIndices(startIndex, indices, true); ULONG maxPresentBlocks = (ULONG) indices.size(); // Calculate how many blocks does the data need ULONG extraSize = size % header_.bigBlockSize_; ULONG maxNewBlocks = size / header_.bigBlockSize_ + (extraSize ? 1 : 0); // Readjust indices and remove blocks if new data size is smaller than original int extraBlocks = maxPresentBlocks - maxNewBlocks; if (extraBlocks > 0) { // Place new end marker if (maxNewBlocks != 0) blocksIndices_[indices[maxNewBlocks]-1] = ENDOFCHAIN; else startIndex = ENDOFCHAIN; // Get indices of blocks to delete vector<SECT> indicesToRemove(extraBlocks); copy(indices.begin()+maxNewBlocks, indices.end(), indicesToRemove.begin()); indices.erase(indices.begin()+maxNewBlocks, indices.end()); // Remove extra blocks and readjust indices FreeBlocks(indicesToRemove, true); } // Write blocks into available space size_t remainingFullBlocks = size / header_.bigBlockSize_; size_t curIndex=0; if (maxPresentBlocks != 0) { for(; remainingFullBlocks && curIndex<maxPresentBlocks; --remainingFullBlocks, ++curIndex) file_.Write(indices[curIndex]+1, data+curIndex*header_.bigBlockSize_); } // Check if all blocks have been written SECT index; if (indices.empty()) index = 0; else if (curIndex == 0) index = indices[0]; else index = (startIndex != ENDOFCHAIN) ? indices[curIndex-1] : 0; if (remainingFullBlocks != 0) { // Require extra blocks to write data (i.e. new data is larger than original data do { SECT newIndex = GetFreeBlockIndex(true); // Get new free block to write data if (startIndex == ENDOFCHAIN) startIndex = newIndex; // Get start index else LinkBlocks(index, newIndex, true); // Link last index to new index file_.Write(newIndex+1, data+curIndex*header_.bigBlockSize_); ++curIndex; index = newIndex; } while(--remainingFullBlocks); } if (extraSize != 0) { SECT newIndex; if (curIndex >= maxPresentBlocks) { // No more free blocks to write extra block data newIndex = GetFreeBlockIndex(true); // Get new free block to write data if (startIndex == ENDOFCHAIN) startIndex = newIndex; else LinkBlocks(index, newIndex,true); } else newIndex = indices[curIndex]; // Write extra block after increasing its size to the minimum block size vector<char> tempdata(header_.bigBlockSize_, 0); copy(data+curIndex*header_.bigBlockSize_, data+curIndex*header_.bigBlockSize_+extraSize, tempdata.begin()); file_.Write(newIndex+1, &*(tempdata.begin())); } return startIndex; } else { if (size==0 && startIndex==ENDOFCHAIN) return startIndex; if (size != 0 && dirEntries_[0]->_sectStart == ENDOFCHAIN) { SECT newIndex = GetFreeBlockIndex(true); fill (block_.begin(), block_.end(), 0); file_.Insert(newIndex, &*(block_.begin())); IncreaseLocationReferences(vector<SECT>(1, newIndex)); dirEntries_[0]->_sectStart = newIndex; dirEntries_[0]->_ulSize = header_.bigBlockSize_; } // Get present indices vector<SECT> indices; GetBlockIndices(startIndex, indices, false); ULONG maxPresentBlocks = (ULONG) indices.size(); // Calculate how many blocks does the data need ULONG extraSize = size % header_.smallBlockSize_; ULONG maxNewBlocks = size / header_.smallBlockSize_ + (extraSize ? 1 : 0); vector<char> smallBlocksData; int extraBlocks = maxPresentBlocks - maxNewBlocks; if (extraBlocks > 0) { // Readjust indices and remove blocks // Place new end marker if (maxNewBlocks != 0) sblocksIndices_[indices[maxNewBlocks]-1] = ENDOFCHAIN; else startIndex = ENDOFCHAIN; // Get indices of blocks to delete vector<SECT> indicesToRemove(extraBlocks); copy(indices.begin()+maxNewBlocks, indices.end(), indicesToRemove.begin()); indices.erase(indices.begin()+maxNewBlocks, indices.end()); // Remove extra blocks and readjust indices FreeBlocks(indicesToRemove, false); } else if (extraBlocks < 0) { ULONG maxBlocks = dirEntries_[0]->_ulSize / header_.bigBlockSize_ + (dirEntries_[0]->_ulSize % header_.bigBlockSize_ ? 1 : 0); size_t actualSize = maxBlocks * header_.bigBlockSize_; smallBlocksData.resize(actualSize); ReadData(dirEntries_[0]->_sectStart, &*(smallBlocksData.begin()), true); smallBlocksData.resize(dirEntries_[0]->_ulSize); // Readjust indices and add blocks ULONG newBlocksNeeded = -extraBlocks; SECT index = maxPresentBlocks - 1; for(size_t i=0; i<newBlocksNeeded; ++i) { SECT newIndex = GetFreeBlockIndex(false); // Get new free block to write data if (startIndex == ENDOFCHAIN) startIndex = newIndex; // Get start index else LinkBlocks(index, newIndex, false); // Link last index to new index smallBlocksData.insert(smallBlocksData.begin()+newIndex, header_.smallBlockSize_, 0); index = newIndex; } dirEntries_[0]->_ulSize = newBlocksNeeded * header_.smallBlockSize_; } if (smallBlocksData.empty()) { ULONG maxBlocks = dirEntries_[0]->_ulSize / header_.bigBlockSize_ + (dirEntries_[0]->_ulSize % header_.bigBlockSize_ ? 1 : 0); size_t actualSize = maxBlocks * header_.bigBlockSize_; smallBlocksData.resize(actualSize); ReadData(dirEntries_[0]->_sectStart, &*(smallBlocksData.begin()), true); smallBlocksData.resize(dirEntries_[0]->_ulSize); } // Write blocks GetBlockIndices(startIndex, indices, false); size_t fullBlocks = size / header_.smallBlockSize_; for(size_t i=0; i<fullBlocks; ++i) { copy(data+i*header_.smallBlockSize_, data+i*header_.smallBlockSize_+header_.smallBlockSize_, smallBlocksData.begin()+indices[i]*header_.smallBlockSize_); } if (extraSize != 0) { copy(data+fullBlocks*header_.smallBlockSize_, data+fullBlocks*header_.smallBlockSize_+extraSize, smallBlocksData.begin()+indices[fullBlocks]*header_.smallBlockSize_); } WriteData(&*(smallBlocksData.begin()), dirEntries_[0]->_ulSize, dirEntries_[0]->_sectStart, true); return startIndex; } } void CompoundFile::GetBlockIndices(SECT startIndex, vector<SECT>& indices, bool isBig) // PURPOSE: Get the indices of blocks where data are stored, starting from startIndex. // EXPLAIN: isBig is true if property uses big blocks, false if it uses small blocks. { indices.clear(); if (isBig) { for(SECT i=startIndex; i!=ENDOFCHAIN; i=blocksIndices_[i]) indices.push_back(i); } else { for(SECT i=startIndex; i!=ENDOFCHAIN; i=sblocksIndices_[i]) indices.push_back(i); } } SECT CompoundFile::GetFreeBlockIndex(bool isBig) // PURPOSE: Get the index of a new block where data can be stored. // EXPLAIN: isBig is true if property uses big blocks, false if it uses small blocks. // PROMISE: It does not physically create a new block in the compound file. // PROMISE: It only adjust BAT arrays and indices or SBAT arrays and indices so that // PROMISE: it gives the index of a new block where data can be inserted. { SECT index; if (isBig) { // Find first free location index = (SECT) distance(blocksIndices_.begin(), find(blocksIndices_.begin(), blocksIndices_.end(), -1)); if (index == blocksIndices_.size()) { ExpandBATArray(true); index = (SECT) distance(blocksIndices_.begin(), find(blocksIndices_.begin(), blocksIndices_.end(), -1)); } blocksIndices_[index] = ENDOFCHAIN; } else { // Find first free location index = (SECT) distance(sblocksIndices_.begin(), find(sblocksIndices_.begin(), sblocksIndices_.end(), -1)); if (index == sblocksIndices_.size()) { ExpandBATArray(false); index = (SECT) distance(sblocksIndices_.begin(), find(sblocksIndices_.begin(), sblocksIndices_.end(), -1)); } sblocksIndices_[index] = ENDOFCHAIN; } return index; } void CompoundFile::ExpandBATArray(bool isBig) // PURPOSE: Create a new block of BAT or SBAT indices. // EXPLAIN: isBig is true if property uses big blocks, false if it uses small blocks. { SECT newIndex; fill(block_.begin(), block_.end(), -1); if (isBig) { size_t BATindex = distance(&header_._sectFat[0], find(header_._sectFat, header_._sectFat+109, -1)); if (BATindex < 109) { // Set new BAT index location newIndex = (SECT) blocksIndices_.size(); // New index location file_.Insert(newIndex+1, &*(block_.begin())); IncreaseLocationReferences(vector<SECT>(1, newIndex)); // Update BAT array header_._sectFat[BATindex] = newIndex; ++header_._csectFat; } else { // No free BAT indices. Increment using XBAT // Set new XBAT index location if (header_._csectDif != 0) { newIndex = header_._sectDifStart + header_._csectDif; file_.Insert(newIndex, &*(block_.begin())); IncreaseLocationReferences(vector<SECT>(1, newIndex)); } else { newIndex = (SECT) blocksIndices_.size(); file_.Insert(newIndex, &*(block_.begin())); IncreaseLocationReferences(vector<SECT>(1, newIndex)); header_._sectDifStart = newIndex; } ++header_._csectDif; } blocksIndices_.insert(blocksIndices_.begin()+newIndex, FATSECT); blocksIndices_.resize(blocksIndices_.size()+127, FREESECT); } else { // Set new SBAT index location if (header_._csectMiniFat != 0) { newIndex = header_._sectMiniFatStart + header_._csectMiniFat; file_.Insert(newIndex, &*(block_.begin())); IncreaseLocationReferences(vector<SECT>(1, newIndex)); } else { newIndex = GetFreeBlockIndex(true); file_.Insert(newIndex, &*(block_.begin())); IncreaseLocationReferences(vector<SECT>(1, newIndex)); header_._sectMiniFatStart = newIndex; } ++header_._csectMiniFat; sblocksIndices_.resize(sblocksIndices_.size()+128, -1); } } void CompoundFile::LinkBlocks(SECT from, SECT to, bool isBig) // PURPOSE: Link one BAT index to another. // EXPLAIN: isBig is true if property uses big blocks, false if it uses small blocks. { if (isBig) blocksIndices_[from] = to; else sblocksIndices_[from] = to; } void CompoundFile::FreeBlocks(vector<SECT>& indices, bool isBig) // PURPOSE: Delete blocks of data from compound file. // EXPLAIN: indices contains indices to blocks of data to be deleted. // EXPLAIN: isBig is true if property uses big blocks, false if it uses small blocks. { if (isBig) { // Decrease all location references before deleting blocks from file. DecreaseLocationReferences(indices); ULONG maxIndices = (ULONG) indices.size(); {for(size_t i=0; i<maxIndices; ++i) ++indices[i];} // Increase by 1 because block index 1 corresponds to index 0 here file_.Erase(indices); // Shrink BAT indices if necessary vector<SECT> indicesToRemove; while(distance(find(blocksIndices_.begin(), blocksIndices_.end(),-1), blocksIndices_.end()) >= 128) { blocksIndices_.resize(blocksIndices_.size()-128); if (header_._csectDif != 0) { // Shrink XBAT first --header_._csectDif; indicesToRemove.push_back(header_._sectDifStart+header_._csectDif+1); // Add 1 because block index 1 corresponds to index 0 here if (header_._csectDif == 0) header_._sectDifStart = ENDOFCHAIN; } else { // No XBAT, delete last occupied BAT array element size_t BATindex = distance(&header_._sectFat[0], find(header_._sectFat, header_._sectFat+109, -1)); if (BATindex != 109) { --header_._csectFat; indicesToRemove.push_back(header_._sectFat[BATindex-1]+1); // Add 1 because block index 1 corresponds to index 0 here header_._sectFat[BATindex-1] = -1; } } } // Erase extra BAT indices if present if (!indicesToRemove.empty()) file_.Erase(indicesToRemove); } else { // Erase block ULONG maxIndices = (ULONG) indices.size(); ULONG maxBlocks = dirEntries_[0]->_ulSize / header_.bigBlockSize_ + (dirEntries_[0]->_ulSize % header_.bigBlockSize_ ? 1 : 0); size_t size = maxBlocks * header_.bigBlockSize_; char* data = new char[size]; ReadData(dirEntries_[0]->_sectStart, data, true); size_t maxSmallBlocks = dirEntries_[0]->_ulSize / header_.smallBlockSize_; char* newdata = new char[dirEntries_[0]->_ulSize-maxIndices*header_.smallBlockSize_]; {for(size_t i=0, j=0; i<maxSmallBlocks; ++i) { if (find(indices.begin(), indices.end(), i) == indices.end()) { copy(data+i*header_.smallBlockSize_, data+i*header_.smallBlockSize_+header_.smallBlockSize_, newdata+j*header_.smallBlockSize_); ++j; } }} dirEntries_[0]->_sectStart = WriteData(newdata, dirEntries_[0]->_ulSize-maxIndices*header_.smallBlockSize_, dirEntries_[0]->_sectStart, true); dirEntries_[0]->_ulSize -= maxIndices*header_.smallBlockSize_; delete[] data; delete[] newdata; // Change SBAT indices size_t maxSBATindices = sblocksIndices_.size(); {for(size_t i=0; i<maxIndices; ++i) { for(size_t j=0; j<maxSBATindices; ++j) { if (j == indices[i]) continue; if (sblocksIndices_[j] == indices[i]) sblocksIndices_[j] = sblocksIndices_[indices[i]]; if (sblocksIndices_[j] > indices[i] && sblocksIndices_[j] != FREESECT && sblocksIndices_[j] != ENDOFCHAIN) --sblocksIndices_[j]; } }} sort (indices.begin(), indices.end(), greater<size_t>()); {for(size_t i=0; i<maxIndices; ++i) { sblocksIndices_.erase(sblocksIndices_.begin()+indices[i]); sblocksIndices_.push_back(-1); }} vector<SECT> indicesToRemove; while(distance(find(sblocksIndices_.begin(), sblocksIndices_.end(), -1), sblocksIndices_.end()) >= 128) { // Shrink SBAT indices if necessary sblocksIndices_.resize(sblocksIndices_.size()-128); --header_._csectMiniFat; indicesToRemove.push_back(header_._sectMiniFatStart+header_._csectMiniFat); if (header_._csectMiniFat == 0) header_._sectMiniFatStart = ENDOFCHAIN; } FreeBlocks(indicesToRemove, true); } } /*********************** Inaccessible Properties Functions ***************************/ void CompoundFile::LoadProperties() // PURPOSE: Load properties information for compound file. { // Read properties' data from compound file. ULONG propertiesSize = DataSize(header_._sectDirStat, true); char* buffer = new char[propertiesSize]; ReadData(header_._sectDirStat, buffer, true); // Split properties' data into individual property. ULONG maxPropertiesBlock = propertiesSize / header_.bigBlockSize_; ULONG propertiesPerBlock = header_.bigBlockSize_ / 128; ULONG maxProperties = maxPropertiesBlock * propertiesPerBlock; ULONG maxBlocks = maxProperties / propertiesPerBlock + (maxProperties % propertiesPerBlock ? 1 : 0); for(size_t i=0; i<maxBlocks; ++i) { for(size_t j=0; j<4; ++j) { // Read individual property DirectoryEntry* property = new DirectoryEntry; property->Read(buffer+i*512+j*128); if (wcslen(property->name_) == 0) { delete property; break; } dirEntries_.push_back(property); } } delete[] buffer; // Generate property trees propertyTrees_->parent_ = 0; propertyTrees_->self_ = dirEntries_[0]; propertyTrees_->index_ = 0; InsertPropertyTree(propertyTrees_, dirEntries_[dirEntries_[0]->_sidChild], dirEntries_[0]->_sidChild); } void CompoundFile::SaveProperties() // PURPOSE: Save properties information for compound file. { // Calculate total size required by properties ULONG maxProperties = (ULONG) dirEntries_.size(); ULONG propertiesPerBlock = header_.bigBlockSize_ / 128; ULONG maxBlocks = maxProperties / propertiesPerBlock + (maxProperties % propertiesPerBlock ? 1 : 0); ULONG propertiesSize = maxBlocks*header_.bigBlockSize_; char* buffer = new char[propertiesSize]; {for(size_t i=0; i<propertiesSize; ++i) buffer[i] = 0;} {for(size_t i=0; i<maxProperties; ++i) { // Save individual property dirEntries_[i]->Write(buffer+i*128); }} // Write properties' data to compound file. WriteData(buffer, propertiesSize, header_._sectDirStat, true); delete[] buffer; } int CompoundFile::MakeProperty(const wchar_t* path, CompoundFile::DirectoryEntry* property) // PURPOSE: Create a new property in the compound file. // EXPLAIN: path is the full path name for the property. // EXPLAIN: property contains information on the type of property to be created. { wchar_t* parentpath = 0; wchar_t* propertyname = 0; // Change to the specified directory. If specified directory is not present, // create it. if (wcslen(path) != 0) { if (path[0] == L'\\') currentDirectory_ = propertyTrees_; } SplitPath(path, parentpath, propertyname); if (propertyname != 0) { if (parentpath != 0) { if (ChangeDirectory(parentpath) != SUCCESS) { int ret = MakeDirectory(parentpath); if (ret != SUCCESS) { delete[] parentpath; delete[] propertyname; return ret; } else ChangeDirectory(parentpath); } delete[] parentpath; } // Insert property into specified directory size_t propertynameLength = wcslen(propertyname); if (propertynameLength >= 32) { delete[] propertyname; return NAME_TOO_LONG; } wcscpy(property->name_, propertyname); delete[] propertyname; property->_cb_namesize = (WORD) (propertynameLength*2+2); if (FindProperty(currentDirectory_, property->name_) == 0) { // Find location to insert property ULONG maxProperties = (ULONG) dirEntries_.size(); SECT index; for(index=1; index<maxProperties; ++index) { if (*(dirEntries_[index]) > *property) break; } if (index != maxProperties) { // Change references for all properties affected by the new property IncreasePropertyReferences(propertyTrees_, index); } dirEntries_.insert(dirEntries_.begin()+index, property); InsertPropertyTree(currentDirectory_, property, index); return SUCCESS; } else return DUPLICATE_PROPERTY; } else { if (parentpath != 0) delete[] parentpath; return INVALID_PATH; } } CompoundFile::PropertyTree* CompoundFile::FindProperty(SECT index) // PURPOSE: Find property in the compound file, given the index of the property. // PROMISE: Returns a pointer to the property tree of the property if property // PROMISE: is present, 0 if otherwise. { if (previousDirectories_.empty()) previousDirectories_.push_back(propertyTrees_); PropertyTree* currentTree = previousDirectories_.back(); if (currentTree->index_ != index) { size_t maxChildren = currentTree->children_.size(); for(size_t i=0; i<maxChildren; ++i) { previousDirectories_.push_back(currentTree->children_[i]); PropertyTree* child = FindProperty(index); if (child != 0) { previousDirectories_.pop_back(); return child; } } } else { previousDirectories_.pop_back(); return currentTree; } previousDirectories_.pop_back(); return NULL; } CompoundFile::PropertyTree* CompoundFile::FindProperty(const wchar_t* path) // PURPOSE: Find property in the compound file, given the path of the property. // PROMISE: Returns a pointer to the property tree of the property if property // PROMISE: is present, 0 if otherwise. { previousDirectories_.push_back(currentDirectory_); // Change to specified directory wchar_t* parentpath = 0; wchar_t* filename = 0; if (wcslen(path) != 0) { if (path[0] == L'\\') currentDirectory_ = propertyTrees_; } SplitPath(path, parentpath, filename); if (parentpath != 0) { int ret = ChangeDirectory(parentpath); delete[] parentpath; if (ret != SUCCESS) { // Cannot change to specified directory if (filename != 0) delete[] filename; currentDirectory_ = previousDirectories_.back(); previousDirectories_.pop_back(); PropertyTree* property = 0; return property; } } // Check to see if file is present in the specified directory. PropertyTree* property = 0; if (filename != 0) { property = FindProperty(currentDirectory_, filename); delete[] filename; } currentDirectory_ = previousDirectories_.back(); previousDirectories_.pop_back(); return property; } CompoundFile::PropertyTree* CompoundFile::FindProperty(CompoundFile::PropertyTree* parentTree, wchar_t* name) // PURPOSE: Find property in the compound file, given the parent property tree and its name. // PROMISE: Returns a pointer to the property tree of the property if property // PROMISE: is present, 0 if otherwise. { if (parentTree->self_->_sidChild != (CBF_SID)-1) { size_t maxChildren = parentTree->children_.size(); for(size_t i=0; i<maxChildren; ++i) { if (wcscmp(parentTree->children_[i]->self_->name_, name) == 0) return parentTree->children_[i]; } } return NULL; } void CompoundFile::InsertPropertyTree(CompoundFile::PropertyTree* parentTree, CompoundFile::DirectoryEntry* property, SECT index) // PURPOSE: Insert a property and all its siblings and children into the property tree. // REQUIRE: If the property is a new property and its index is already occupied by // REQUIRE: another property, the calling function has to call IncreasePropertyReferences() // REQUIRE: first before calling this function. // EXPLAIN: This function is used by LoadProperty() to initialize the property trees // EXPLAIN: and MakeProperty() thus resulting in the above requirements. // EXPLAIN: parentTree is the parent of the new property. // EXPLAIN: property is the property to be added. // EXPLAIN: index is the index of the new property. // PROMISE: The property will be added as the parent tree's child and the parent's // PROMISE: child property and all the its children previous property and next property // PROMISE: will be readjusted to accomodate the next property. { PropertyTree* tree = new PropertyTree; tree->parent_ = parentTree; tree->self_ = property; tree->index_ = index; if (property->_sidLeftSib != (CBF_SID)-1) { InsertPropertyTree(parentTree, dirEntries_[property->_sidLeftSib], property->_sidLeftSib); } if (property->_sidRightSib != (CBF_SID)-1) { InsertPropertyTree(parentTree, dirEntries_[property->_sidRightSib], property->_sidRightSib); } if (property->_sidChild != (CBF_SID)-1) { InsertPropertyTree(tree, dirEntries_[property->_sidChild], property->_sidChild); } // Sort children size_t maxChildren = parentTree->children_.size(); size_t i; for(i=0; i<maxChildren; ++i) { if (index < parentTree->children_[i]->index_) break; } parentTree->children_.insert(parentTree->children_.begin()+i, tree); // Update children indices UpdateChildrenIndices(parentTree); } void CompoundFile::DeletePropertyTree(CompoundFile::PropertyTree* tree) // PURPOSE: Delete a property from properties. // EXPLAIN: tree is the property tree to be deleted. // PROMISE: The tree's parent's child property and all the its children previous property // PROMISE: and next property will be readjusted to accomodate the deleted property. { // Decrease all property references DecreasePropertyReferences(propertyTrees_, tree->index_); // Remove property if (dirEntries_[tree->index_]) delete dirEntries_[tree->index_]; dirEntries_.erase(dirEntries_.begin()+tree->index_); // Remove property from property trees size_t maxChildren = tree->parent_->children_.size(); size_t i; for(i=0; i<maxChildren; ++i) { if (tree->parent_->children_[i]->index_ == tree->index_) break; } tree->parent_->children_.erase(tree->parent_->children_.begin()+i); // Update children indices UpdateChildrenIndices(tree->parent_); } void CompoundFile::UpdateChildrenIndices(CompoundFile::PropertyTree* parentTree) { // Update indices for 1st to middle child size_t maxChildren = parentTree->children_.size(); if (maxChildren != 0) { vector<PropertyTree*>& children = parentTree->children_; size_t prevChild = 0; children[0]->self_->_sidLeftSib = -1; children[0]->self_->_sidRightSib = -1; size_t curChild; for(curChild=1; curChild<=maxChildren/2; ++curChild) { children[curChild]->self_->_sidLeftSib = children[prevChild]->index_; children[curChild]->self_->_sidRightSib = -1; prevChild = curChild; } // Update middle child --curChild; children[curChild]->parent_->self_->_sidChild = children[curChild]->index_; // Update from middle to last child size_t nextChild = curChild + 1; if (nextChild < maxChildren) { children[curChild]->self_->_sidRightSib = children[nextChild]->index_; for(++curChild, ++nextChild; nextChild<maxChildren; ++curChild, ++nextChild) { children[curChild]->self_->_sidLeftSib = -1; children[curChild]->self_->_sidRightSib = children[nextChild]->index_; } children[curChild]->self_->_sidLeftSib = -1; children[curChild]->self_->_sidRightSib = -1; } } else { parentTree->self_->_sidChild = -1; } } void CompoundFile::IncreasePropertyReferences(CompoundFile::PropertyTree* parentTree, SECT index) // PURPOSE: Increase all property references (previous property, next property // PURPOSE: and child property) which will be affected by the insertion of the new index. // EXPLAIN: The recursive method of going through each property tree is used instead of // EXPLAIN: using the iterative method of going through each property in dirEntries_ is // EXPLAIN: because the index in property tree needs to be updated also. { if (parentTree->index_ >= index) ++parentTree->index_; if (parentTree->self_->_sidLeftSib != (CBF_SID)-1) { if (parentTree->self_->_sidLeftSib >= index) ++parentTree->self_->_sidLeftSib; } if (parentTree->self_->_sidRightSib != (CBF_SID)-1) { if (parentTree->self_->_sidRightSib >= index) ++parentTree->self_->_sidRightSib; } if (parentTree->self_->_sidChild != (CBF_SID)-1) { if (parentTree->self_->_sidChild >= index) ++parentTree->self_->_sidChild; } size_t maxChildren = parentTree->children_.size(); for(size_t i=0; i<maxChildren; ++i) IncreasePropertyReferences(parentTree->children_[i], index); } void CompoundFile::DecreasePropertyReferences(CompoundFile::PropertyTree* parentTree, SECT index) // PURPOSE: Decrease all property references (previous property, next property // PURPOSE: and child property) which will be affected by the deletion of the index. // EXPLAIN: The recursive method of going through each property tree is used instead of // EXPLAIN: using the iterative method of going through each property in dirEntries_ is // EXPLAIN: because the index in property tree needs to be updated also. { if (parentTree->index_ > index) --parentTree->index_; if (parentTree->self_->_sidLeftSib != (CBF_SID)-1) { if (parentTree->self_->_sidLeftSib > index) --parentTree->self_->_sidLeftSib; } if (parentTree->self_->_sidRightSib != (CBF_SID)-1) { if (parentTree->self_->_sidRightSib > index) --parentTree->self_->_sidRightSib; } if (parentTree->self_->_sidChild != (CBF_SID)-1) { if (parentTree->self_->_sidChild > index) --parentTree->self_->_sidChild; } size_t maxChildren = parentTree->children_.size(); for(size_t i=0; i<maxChildren; ++i) DecreasePropertyReferences(parentTree->children_[i], index); } } // YCompoundFiles namespace end #endif // _WIN32 namespace YExcel { using namespace YCompoundFiles; #ifdef _WIN32 using namespace WinCompFiles; #endif /************************************************************************************************************/ Record::Record() : dataSize_(0), recordSize_(4) {} Record::~Record() {} ULONG Record::Read(const char* data) { LittleEndian::Read(data, code_, 0, 2); // Read operation code. LittleEndian::Read(data, dataSize_, 2, 2); // Read size of record. data_.assign(data+4, data+4+dataSize_); recordSize_ = 4 + dataSize_; // Check if next record is a continue record continueIndices_.clear(); short code; LittleEndian::Read(data, code, dataSize_+4, 2); while(code == CODE::CONTINUE) { continueIndices_.push_back(dataSize_); ULONG size; LittleEndian::Read(data, size, recordSize_+2, 2); data_.insert(data_.end(), data+recordSize_+4, data+recordSize_+4+size); dataSize_ += size; recordSize_ += 4 + size; LittleEndian::Read(data, code, recordSize_, 2); } return recordSize_; } ULONG Record::Write(char* data) { LittleEndian::Write(data, code_, 0, 2); // Write operation code. ULONG npos = 2; if (continueIndices_.empty()) { ULONG size = dataSize_; ULONG i=0; while(size > 8224) { LittleEndian::Write(data, 8224, npos, 2); // Write size of record. npos += 2; size -= 8224; copy(data_.begin()+i*8224, data_.begin()+(i+1)*8224, data+npos); npos += 8224; if (size != 0) { ++i; LittleEndian::Write(data, 0x3C, npos, 2); // Write CONTINUE code. npos += 2; } } LittleEndian::Write(data, size, npos, 2); // Write size of record. npos += 2; copy(data_.begin()+i*8224, data_.begin()+i*8224+size, data+npos); npos += size; } else { size_t maxContinue = continueIndices_.size(); ULONG size = continueIndices_[0]; LittleEndian::Write(data, size, npos, 2); // Write size of record npos += 2; copy(data_.begin(), data_.begin()+size, data+npos); npos += size; size_t c = 0; for(c=1; c<maxContinue; ++c) { LittleEndian::Write(data, 0x3C, npos, 2); // Write CONTINUE code. npos += 2; size = continueIndices_[c] - continueIndices_[c-1]; LittleEndian::Write(data, size, npos, 2); npos += 2; copy(data_.begin()+continueIndices_[c-1], data_.begin()+continueIndices_[c], data+npos); npos += size; } LittleEndian::Write(data, 0x3C, npos, 2); // Write CONTINUE code. npos += 2; size = (ULONG)data_.size() - continueIndices_[c-1]; LittleEndian::Write(data, size, npos, 2); npos += 2; copy(data_.begin()+continueIndices_[c-1], data_.end(), data+npos); npos += size; } return npos; } ULONG Record::DataSize() {return dataSize_;} ULONG Record::RecordSize() {return recordSize_;} /************************************************************************************************************/ /************************************************************************************************************/ BOF::BOF() : Record() {code_ = CODE::BOF; dataSize_ = 16; recordSize_ = 20;} ULONG BOF::Read(const char* data) { Record::Read(data); LittleEndian::Read(data_, version_, 0, 2); LittleEndian::Read(data_, type_, 2, 2); LittleEndian::Read(data_, buildIdentifier_, 4, 2); LittleEndian::Read(data_, buildYear_, 6, 2); LittleEndian::Read(data_, fileHistoryFlags_, 8, 4); LittleEndian::Read(data_, lowestExcelVersion_, 12, 4); return RecordSize(); } ULONG BOF::Write(char* data) { data_.resize(dataSize_); LittleEndian::Write(data_, version_, 0, 2); LittleEndian::Write(data_, type_, 2, 2); LittleEndian::Write(data_, buildIdentifier_, 4, 2); LittleEndian::Write(data_, buildYear_, 6, 2); LittleEndian::Write(data_, fileHistoryFlags_, 8, 4); LittleEndian::Write(data_, lowestExcelVersion_, 12, 4); return Record::Write(data); } /************************************************************************************************************/ /************************************************************************************************************/ YEOF::YEOF() : Record() {code_ = CODE::YEOF; dataSize_ = 0; recordSize_ = 4;} /************************************************************************************************************/ /************************************************************************************************************/ SmallString::SmallString() : name_(0), wname_(0) {} SmallString::~SmallString() {Reset();} SmallString::SmallString(const SmallString& s) : name_(0), wname_(0), unicode_(s.unicode_) { if (s.name_) { size_t len = strlen(s.name_); name_ = new char[len+1]; strcpy(name_, s.name_); } if (s.wname_) { size_t len = wcslen(s.wname_); wname_ = new wchar_t[len+1]; wcscpy(wname_, s.wname_); } } SmallString& SmallString::operator=(const SmallString& s) { Reset(); unicode_ = s.unicode_; if (s.name_) { size_t len = strlen(s.name_); name_ = new char[len+1]; strcpy(name_, s.name_); } if (s.wname_) { size_t len = wcslen(s.wname_); wname_ = new wchar_t[len+1]; wcscpy(wname_, s.wname_); } return *this; } const SmallString& SmallString::operator=(const char* str) { unicode_ = 0; Reset(); size_t len = strlen(str); name_ = new char[len+1]; strcpy(name_, str); return *this; } const SmallString& SmallString::operator=(const wchar_t* str) { unicode_ = 1; Reset(); size_t len = wcslen(str); wname_ = new wchar_t[len+1]; wcscpy(wname_, str); return *this; } void SmallString::Reset() { if (name_) {delete[] name_; name_ = NULL;} if (wname_) {delete[] wname_; wname_ = NULL;} } ULONG SmallString::Read(const char* data) { Reset(); char stringSize; LittleEndian::Read(data, stringSize, 0, 1); LittleEndian::Read(data, unicode_, 1, 1); ULONG bytesRead = 2; if (!(unicode_ & 0x01)) { //MF compressed format of UTF16LE string? // ANSI string name_ = new char[stringSize+1]; LittleEndian::ReadString(data, name_, 2, stringSize); name_[stringSize] = 0; bytesRead += stringSize; } else { // UNICODE wname_ = new wchar_t[stringSize+1]; LittleEndian::ReadString(data, wname_, 2, stringSize); wname_[stringSize] = 0; bytesRead += stringSize*2; } return bytesRead; } ULONG SmallString::Write(char* data) { ULONG stringSize = 0; ULONG bytesWrite = 0; if (!(unicode_ & 0x01)) { //MF // ANSI string if (name_) { stringSize = (ULONG) strlen(name_); LittleEndian::Write(data, stringSize, 0, 1); LittleEndian::Write(data, unicode_, 1, 1); LittleEndian::WriteString(data, name_, 2, (int)stringSize); bytesWrite = 2 + stringSize; } else { LittleEndian::Write(data, stringSize, 0, 1); LittleEndian::Write(data, unicode_, 1, 1); bytesWrite = 2; } } else { // UNICODE if (wname_) { stringSize = (ULONG) wcslen(wname_); LittleEndian::Write(data, stringSize, 0, 1); LittleEndian::Write(data, unicode_, 1, 1); LittleEndian::WriteString(data, wname_, 2, (int)stringSize); bytesWrite = 2 + stringSize*2; } else { LittleEndian::Write(data, stringSize, 0, 1); LittleEndian::Write(data, unicode_, 1, 1); bytesWrite = 2; } } return bytesWrite; } ULONG SmallString::DataSize() { return (!(unicode_ & 0x01)) ? StringSize()+2 : StringSize()*2+2; //MF } ULONG SmallString::RecordSize() {return DataSize();} ULONG SmallString::StringSize() { if (!(unicode_ & 0x01)) //MF { if (name_) return (ULONG) strlen(name_); } else { if (wname_) return (ULONG) wcslen(wname_); } return 0; } /************************************************************************************************************/ /************************************************************************************************************/ LargeString::LargeString() : unicode_(-1), richtext_(0), phonetic_(0) {} LargeString::~LargeString() {} LargeString::LargeString(const LargeString& s) : name_(s.name_), wname_(s.wname_), unicode_(s.unicode_), richtext_(s.richtext_), phonetic_(s.phonetic_) {} LargeString& LargeString::operator=(const LargeString& s) { unicode_ = s.unicode_; richtext_ = s.richtext_; phonetic_ = s.phonetic_; name_ = s.name_; wname_ = s.wname_; return *this; } const LargeString& LargeString::operator=(const char* str) { unicode_ = 0; richtext_ = 0; phonetic_ = 0; wname_.clear(); size_t len = strlen(str); name_.resize(len); //MF: don't add an extra 0 byte memcpy(&*(name_.begin()), str, len); return *this; } const LargeString& LargeString::operator=(const wchar_t* str) { unicode_ = 1; richtext_ = 0; phonetic_ = 0; name_.clear(); size_t len = wcslen(str); wname_.resize(len); //MF: don't add an extra 0 byte memcpy(&*(wname_.begin()), str, len*sizeof(wchar_t)); return *this; } ULONG LargeString::Read(const char* data) { short stringSize; LittleEndian::Read(data, stringSize, 0, 2); LittleEndian::Read(data, unicode_, 2, 1); ULONG npos = 3; if (unicode_ & 8) { LittleEndian::Read(data, richtext_, npos, 2); npos += 2; } if (unicode_ & 4) LittleEndian::Read(data, phonetic_, npos, 4); name_.clear(); wname_.clear(); int bytesRead = 2; if (stringSize > 0) bytesRead += ContinueRead(data+2, stringSize); else bytesRead = 3; return bytesRead; } ULONG LargeString::ContinueRead(const char* data, int size) { if (size == 0) return 0; char unicode; LittleEndian::Read(data, unicode, 0, 1); if (unicode_ == -1) unicode_ = unicode; if (unicode_ & 1) { // Present stored string is uncompressed (16 bit) ULONG npos = 1; if (richtext_) npos += 2; if (phonetic_) npos += 4; size_t strpos = wname_.size(); wname_.resize(strpos+size, 0); if (unicode & 1) { LittleEndian::ReadString(data, &*(wname_.begin())+strpos, npos, size); npos += size * SIZEOFWCHAR_T; } else { // String to be read is in ANSI vector<char> name(size); LittleEndian::ReadString(data, &*(name.begin()), npos, size); mbstowcs(&*(wname_.begin())+strpos, &*(name.begin()), size); npos += size; } if (richtext_) npos += 4*richtext_; if (phonetic_) npos += phonetic_; return npos; } else { // Present stored string has character compression (8 bit) ULONG npos = 1; if (richtext_) npos += 2; if (phonetic_) npos += 4; size_t strpos = name_.size(); name_.resize(strpos+size, 0); if (unicode & 1) { // String to be read is in unicode vector<wchar_t> name(size); LittleEndian::ReadString(data, &*(name.begin()), npos, size); wcstombs(&*(name_.begin())+strpos, &*(name.begin()), size); npos += size * SIZEOFWCHAR_T; } else { LittleEndian::ReadString(data, &*(name_.begin())+strpos, npos, size); npos += size; } if (richtext_) npos += 4*richtext_; if (phonetic_) npos += phonetic_; return npos; } } ULONG LargeString::Write(char* data) { short stringSize = 0; int bytesWrite = 0; if (unicode_ & 1) { // UNICODE unicode_ = 1; // Don't handle richtext or phonetic for now. if (!wname_.empty()) { stringSize = (short) wname_.size(); LittleEndian::Write(data, stringSize, 0, 2); LittleEndian::Write(data, unicode_, 2, 1); LittleEndian::WriteString(data, &*(wname_.begin()), 3, stringSize); bytesWrite = 3 + stringSize * SIZEOFWCHAR_T; } else { LittleEndian::Write(data, stringSize, 0, 2); LittleEndian::Write(data, unicode_, 2, 1); bytesWrite = 3; } } else { // ANSI string unicode_ = 0; // Don't handle richtext or phonetic for now. if (!name_.empty()) { stringSize = (short) name_.size(); LittleEndian::Write(data, stringSize, 0, 2); LittleEndian::Write(data, unicode_, 2, 1); LittleEndian::WriteString(data, &*(name_.begin()), 3, stringSize); bytesWrite = 3 + stringSize; } else { LittleEndian::Write(data, stringSize, 0, 2); LittleEndian::Write(data, unicode_, 2, 1); bytesWrite = 3; } } return bytesWrite; } ULONG LargeString::DataSize() { ULONG dataSize = StringSize() + 3; if (richtext_) dataSize += 2 + 4*richtext_; if (phonetic_) dataSize += 4 + phonetic_; return dataSize; } ULONG LargeString::RecordSize() { return DataSize(); } ULONG LargeString::StringSize() { if (unicode_ & 1) return (ULONG) wname_.size() * SIZEOFWCHAR_T; else return (ULONG) name_.size(); } /************************************************************************************************************/ /************************************************************************************************************/ Workbook::Workbook() { bof_.version_ = 1536; bof_.type_ = 5; bof_.buildIdentifier_ = 6560; bof_.buildYear_ = 1997; bof_.fileHistoryFlags_ = 49353; bof_.lowestExcelVersion_ = 774; } ULONG Workbook::Read(const char* data) { ULONG bytesRead = 0; short code; LittleEndian::Read(data, code, 0, 2); while(code != CODE::YEOF) { switch(code) { case CODE::BOF: bytesRead += bof_.Read(data+bytesRead); break; case CODE::WINDOW1: bytesRead += window1_.Read(data+bytesRead); break; case CODE::FONT: fonts_.push_back(Font()); bytesRead += fonts_.back().Read(data+bytesRead); break; //MF case CODE::FORMAT: formats_.push_back(Format()); bytesRead += formats_.back().Read(data+bytesRead); break; case CODE::XF: XFs_.push_back(XF()); bytesRead += XFs_.back().Read(data+bytesRead); break; case CODE::STYLE: styles_.push_back(Style()); bytesRead += styles_.back().Read(data+bytesRead); break; case CODE::BOUNDSHEET: boundSheets_.push_back(BoundSheet()); bytesRead += boundSheets_.back().Read(data+bytesRead); break; case CODE::SST: bytesRead += sst_.Read(data+bytesRead); break; // case CODE::EXTSST: // bytesRead += extSST_.Read(data+bytesRead); // break; default: { Record rec; bytesRead += rec.Read(data+bytesRead); } } LittleEndian::Read(data, code, bytesRead, 2); } bytesRead += eof_.RecordSize(); return bytesRead; } ULONG Workbook::Write(char* data) { ULONG bytesWritten = bof_.Write(data); bytesWritten += window1_.Write(data+bytesWritten); size_t maxFonts = fonts_.size(); {for(size_t i=0; i<maxFonts; ++i) {bytesWritten += fonts_[i].Write(data+bytesWritten);}} //MF size_t maxFormats = formats_.size(); {for(size_t i=0; i<maxFormats; ++i) { if (formats_[i].index_ >= FIRST_USER_FORMAT_IDX) // only write user defined formats bytesWritten += formats_[i].Write(data+bytesWritten); }} size_t maxXFs = XFs_.size(); {for(size_t i=0; i<maxXFs; ++i) {bytesWritten += XFs_[i].Write(data+bytesWritten);}} size_t maxStyles = styles_.size(); {for(size_t i=0; i<maxStyles; ++i) {bytesWritten += styles_[i].Write(data+bytesWritten);}} size_t maxBoundSheets = boundSheets_.size(); {for(size_t i=0; i<maxBoundSheets; ++i) {bytesWritten += boundSheets_[i].Write(data+bytesWritten);}} bytesWritten += sst_.Write(data+bytesWritten); // bytesWritten += extSST_.Write(data+bytesWritten); bytesWritten += eof_.Write(data+bytesWritten); return bytesWritten; } ULONG Workbook::DataSize() { ULONG size = bof_.RecordSize(); size += window1_.RecordSize(); size_t maxFonts = fonts_.size(); {for(size_t i=0; i<maxFonts; ++i) {size += fonts_[i].RecordSize();}} //MF size_t maxFormats = formats_.size(); {for(size_t i=0; i<maxFormats; ++i) { if (formats_[i].index_ >= FIRST_USER_FORMAT_IDX) // only write user defined formats size += formats_[i].RecordSize(); }} size_t maxXFs = XFs_.size(); {for(size_t i=0; i<maxXFs; ++i) {size += XFs_[i].RecordSize();}} size_t maxStyles = styles_.size(); {for(size_t i=0; i<maxStyles; ++i) {size += styles_[i].RecordSize();}} size_t maxBoundSheets = boundSheets_.size(); {for(size_t i=0; i<maxBoundSheets; ++i) size += boundSheets_[i].RecordSize();} size += sst_.RecordSize(); // size += extSST_.RecordSize(); size += eof_.RecordSize(); return size; } ULONG Workbook::RecordSize() {return DataSize();} /************************************************************************************************************/ /************************************************************************************************************/ Workbook::Window1::Window1() : Record(), horizontalPos_(0x78), verticalPos_(0x78), width_(0x3B1F), height_(0x2454), options_(0x38), activeWorksheetIndex_(0), firstVisibleTabIndex_(0), selectedWorksheetNo_(1), worksheetTabBarWidth_(0x258) { code_ = CODE::WINDOW1; dataSize_ = 18; recordSize_ = 22; } ULONG Workbook::Window1::Read(const char* data) { Record::Read(data); LittleEndian::Read(data_, horizontalPos_, 0, 2); LittleEndian::Read(data_, verticalPos_, 2, 2); LittleEndian::Read(data_, width_, 4, 2); LittleEndian::Read(data_, height_, 6, 2); LittleEndian::Read(data_, options_, 8, 2); LittleEndian::Read(data_, activeWorksheetIndex_, 10, 2); LittleEndian::Read(data_, firstVisibleTabIndex_, 12, 2); LittleEndian::Read(data_, selectedWorksheetNo_, 14, 2); LittleEndian::Read(data_, worksheetTabBarWidth_, 16, 2); return RecordSize(); } ULONG Workbook::Window1::Write(char* data) { data_.resize(dataSize_); LittleEndian::Write(data_, horizontalPos_, 0, 2); LittleEndian::Write(data_, verticalPos_, 2, 2); LittleEndian::Write(data_, width_, 4, 2); LittleEndian::Write(data_, height_, 6, 2); LittleEndian::Write(data_, options_, 8, 2); LittleEndian::Write(data_, activeWorksheetIndex_, 10, 2); LittleEndian::Write(data_, firstVisibleTabIndex_, 12, 2); LittleEndian::Write(data_, selectedWorksheetNo_, 14, 2); LittleEndian::Write(data_, worksheetTabBarWidth_, 16, 2); return Record::Write(data); } /************************************************************************************************************/ /************************************************************************************************************/ Workbook::Font::Font() : Record(), height_(200), options_(0), colourIndex_(0x7FFF), weight_(400), escapementType_(0), underlineType_(0), family_(0), characterSet_(0), unused_(0) { code_ = CODE::FONT; dataSize_ = 14; recordSize_ = 18; name_ = L"Arial"; name_.unicode_ = 1; } ULONG Workbook::Font::Read(const char* data) { Record::Read(data); LittleEndian::Read(data_, height_, 0, 2); LittleEndian::Read(data_, options_, 2, 2); LittleEndian::Read(data_, colourIndex_, 4, 2); LittleEndian::Read(data_, weight_, 6, 2); LittleEndian::Read(data_, escapementType_, 8, 2); LittleEndian::Read(data_, underlineType_, 10, 1); LittleEndian::Read(data_, family_, 11, 1); LittleEndian::Read(data_, characterSet_, 12, 1); LittleEndian::Read(data_, unused_, 13, 1); name_.Read(&*(data_.begin())+14); return RecordSize(); } ULONG Workbook::Font::Write(char* data) { data_.resize(DataSize()); LittleEndian::Write(data_, height_, 0, 2); LittleEndian::Write(data_, options_, 2, 2); LittleEndian::Write(data_, colourIndex_, 4, 2); LittleEndian::Write(data_, weight_, 6, 2); LittleEndian::Write(data_, escapementType_, 8, 2); LittleEndian::Write(data_, underlineType_, 10, 1); LittleEndian::Write(data_, family_, 11, 1); LittleEndian::Write(data_, characterSet_, 12, 1); LittleEndian::Write(data_, unused_, 13, 1); name_.Write(&*(data_.begin())+14); return Record::Write(data); } ULONG Workbook::Font::DataSize() {return dataSize_ = 14 + name_.RecordSize();} ULONG Workbook::Font::RecordSize() {return recordSize_ = DataSize()+4;} /************************************************************************************************************/ /************************************************************************************************************/ //MF Workbook::Format::Format() : Record(), index_(0) { code_ = CODE::FORMAT; dataSize_ = 2; recordSize_ = 6; fmtstring_ = XLS_FORMAT_GENERAL; } ULONG Workbook::Format::Read(const char* data) { Record::Read(data); LittleEndian::Read(data_, index_, 0, 2); fmtstring_.Read(&*(data_.begin())+2); return RecordSize(); } ULONG Workbook::Format::Write(char* data) { data_.resize(DataSize()); LittleEndian::Write(data_, index_, 0, 2); fmtstring_.Write(&*(data_.begin())+2); return Record::Write(data); } ULONG Workbook::Format::DataSize() {return dataSize_ = 2 + fmtstring_.RecordSize();} ULONG Workbook::Format::RecordSize() {return recordSize_ = DataSize()+4;} /************************************************************************************************************/ /************************************************************************************************************/ Workbook::XF::XF() : Record(), fontRecordIndex_(0), formatRecordIndex_(0), protectionType_((short)0xFFF5), alignment_(0x20), // EXCEL_HALIGN_GENERAL|EXCEL_VALIGN_BOTTOM rotation_(0x00), textProperties_(0x00), usedAttributes_(0x00), borderLines_(0x0000), colour1_(0x0000), colour2_(0x20C0)//MAKE_COLOR2(64, 65) { code_ = CODE::XF; dataSize_ = 20; recordSize_ = 24; } ULONG Workbook::XF::Read(const char* data) { Record::Read(data); // XF record in BIFF8 format LittleEndian::Read(data_, fontRecordIndex_, 0, 2); LittleEndian::Read(data_, formatRecordIndex_, 2, 2); LittleEndian::Read(data_, protectionType_, 4, 2); LittleEndian::Read(data_, alignment_, 6, 1); LittleEndian::Read(data_, rotation_, 7, 1); LittleEndian::Read(data_, textProperties_, 8, 1); LittleEndian::Read(data_, usedAttributes_, 9, 1); LittleEndian::Read(data_, borderLines_, 10, 4); LittleEndian::Read(data_, colour1_, 14, 4); LittleEndian::Read(data_, colour2_, 18, 2); return RecordSize(); } ULONG Workbook::XF::Write(char* data) { data_.resize(dataSize_); LittleEndian::Write(data_, fontRecordIndex_, 0, 2); LittleEndian::Write(data_, formatRecordIndex_, 2, 2); LittleEndian::Write(data_, protectionType_, 4, 2); LittleEndian::Write(data_, alignment_, 6, 1); LittleEndian::Write(data_, rotation_, 7, 1); LittleEndian::Write(data_, textProperties_, 8, 1); LittleEndian::Write(data_, usedAttributes_, 9, 1); LittleEndian::Write(data_, borderLines_, 10, 4); LittleEndian::Write(data_, colour1_, 14, 4); LittleEndian::Write(data_, colour2_, 18, 2); return Record::Write(data); } /************************************************************************************************************/ /************************************************************************************************************/ Workbook::Style::Style() : Record(), XFRecordIndex_((short)0x8000), identifier_(0), level_((char)0xFF) { code_ = CODE::STYLE; dataSize_ = 2; recordSize_ = 6; } ULONG Workbook::Style::Read(const char* data) { Record::Read(data); LittleEndian::Read(data_, XFRecordIndex_, 0, 2); if (XFRecordIndex_ & 0x8000) { // Built-in styles LittleEndian::Read(data_, identifier_, 2, 1); LittleEndian::Read(data_, level_, 3, 1); } else { // User-defined styles name_.Read(&*(data_.begin())+2); } return RecordSize(); } ULONG Workbook::Style::Write(char* data) { data_.resize(DataSize()); LittleEndian::Write(data_, XFRecordIndex_, 0, 2); if (XFRecordIndex_ & 0x8000) { // Built-in styles LittleEndian::Write(data_, identifier_, 2, 1); LittleEndian::Write(data_, level_, 3, 1); } else { // User-defined styles name_.Write(&*(data_.begin())+2); } return Record::Write(data); } ULONG Workbook::Style::DataSize() {return dataSize_ = (XFRecordIndex_ & 0x8000) ? 4 : 2+name_.RecordSize();} ULONG Workbook::Style::RecordSize() {return recordSize_ = DataSize()+4;} /************************************************************************************************************/ /************************************************************************************************************/ Workbook::BoundSheet::BoundSheet() : Record(), BOFpos_(0x0000), visibility_(0), type_(0) { code_ = CODE::BOUNDSHEET; dataSize_ = 6; dataSize_ = 10; name_ = "Sheet1"; name_.unicode_ = false; } ULONG Workbook::BoundSheet::Read(const char* data) { Record::Read(data); LittleEndian::Read(data_, BOFpos_, 0, 4); LittleEndian::Read(data_, visibility_, 4, 1); LittleEndian::Read(data_, type_, 5, 1); name_.Read(&*(data_.begin())+6); return RecordSize(); } ULONG Workbook::BoundSheet::Write(char* data) { data_.resize(DataSize()); LittleEndian::Write(data_, BOFpos_, 0, 4); LittleEndian::Write(data_, visibility_, 4, 1); LittleEndian::Write(data_, type_, 5, 1); name_.Write(&*(data_.begin())+6); return Record::Write(data); } ULONG Workbook::BoundSheet::DataSize() {return dataSize_ = 6+name_.RecordSize();} ULONG Workbook::BoundSheet::RecordSize() {return recordSize_ = DataSize()+4;} /************************************************************************************************************/ /************************************************************************************************************/ Workbook::SharedStringTable::SharedStringTable() : Record(), stringsTotal_(0), uniqueStringsTotal_(0) { code_ = CODE::SST; dataSize_ = 8; recordSize_ = 12; } ULONG Workbook::SharedStringTable::Read(const char* data) { Record::Read(data); LittleEndian::Read(data_, stringsTotal_, 0, 4); LittleEndian::Read(data_, uniqueStringsTotal_, 4, 4); strings_.clear(); strings_.resize(uniqueStringsTotal_); ULONG npos = 8; if (continueIndices_.empty()) { for(ULONG i=0; i<uniqueStringsTotal_; ++i) npos += strings_[i].Read(&*(data_.begin())+npos); } else { // Require special handling since CONTINUE records are present ULONG maxContinue = (ULONG) continueIndices_.size(); for(ULONG i=0, c=0; i<uniqueStringsTotal_; ++i) { char unicode; ULONG stringSize; LittleEndian::Read(data_, stringSize, npos, 2); LittleEndian::Read(data_, unicode, npos+2, 1); int multiplier = unicode & 1 ? 2 : 1; if (c >= maxContinue || npos+stringSize*multiplier+3 <= continueIndices_[c]) { // String to be read is not split into two records npos += strings_[i].Read(&*(data_.begin())+npos); } else { // String to be read is split into two or more records int bytesRead = 2;// Start from unicode field int size = continueIndices_[c] - npos - 1 - bytesRead; ++c; if (size > 0) { size /= multiplier; // Number of characters available for string in current record. bytesRead += strings_[i].ContinueRead(&*(data_.begin())+npos+bytesRead, size); stringSize -= size; size = 0; } while(c<maxContinue && npos+stringSize+1>continueIndices_[c]) { ULONG dataSize = (continueIndices_[c] - continueIndices_[c-1] - 1) / multiplier; bytesRead += strings_[i].ContinueRead(&*(data_.begin())+npos+bytesRead, dataSize); stringSize -= dataSize + 1; ++c; } if (stringSize > 0) bytesRead += strings_[i].ContinueRead(&*(data_.begin())+npos+bytesRead, stringSize); npos += bytesRead; } } } return npos + 4*(npos/8224 + 1); } ULONG Workbook::SharedStringTable::Write(char* data) { data_.resize(DataSize()); LittleEndian::Write(data_, stringsTotal_, 0, 4); LittleEndian::Write(data_, uniqueStringsTotal_, 4, 4); size_t maxContinue = continueIndices_.size(); for(size_t i=0, c=0, npos=8; i<uniqueStringsTotal_; ++i) { npos += strings_[i].Write(&*(data_.begin())+npos); if (c<maxContinue && npos==continueIndices_[c]) ++c; else if (c<maxContinue && npos>continueIndices_[c]) { // Insert unicode flag where appropriate for CONTINUE records. data_.insert(data_.begin()+continueIndices_[c], strings_[i].unicode_); data_.pop_back(); ++c; ++npos; } } return Record::Write(data); } ULONG Workbook::SharedStringTable::DataSize() { dataSize_ = 8; continueIndices_.clear(); SECT curMax = 8224; for(ULONG i=0; i<uniqueStringsTotal_; ++i) { ULONG stringSize = strings_[i].StringSize(); if (dataSize_+stringSize+3 <= curMax) dataSize_ += stringSize + 3; else { // If have >= 12 bytes (2 for size, 1 for unicode and >=9 for data, can split string // otherwise, end record and start continue record. bool unicode = strings_[i].unicode_ & 1; if (curMax - dataSize_ >= 12) { if (unicode && !((curMax-dataSize_)%2)) --curMax; // Make sure space reserved for unicode strings is even. continueIndices_.push_back(curMax); stringSize -= (curMax - dataSize_ - 3); dataSize_ = curMax; curMax += 8224; size_t additionalContinueRecords = unicode ? stringSize/8222 : stringSize/8223; // 8222 or 8223 because the first byte is for unicode identifier for(size_t j=0; j<additionalContinueRecords; ++j) { if (unicode) { --curMax; continueIndices_.push_back(curMax); curMax += 8223; dataSize_ += 8223; stringSize -= 8222; } else { continueIndices_.push_back(curMax); curMax += 8224; dataSize_ += 8224; stringSize -= 8223; } } dataSize_ += stringSize + 1; } else { continueIndices_.push_back(dataSize_); curMax = dataSize_ + 8224; if (dataSize_+stringSize+3 < curMax) dataSize_ += stringSize + 3; else { // If have >= 12 bytes (2 for size, 1 for unicode and >=9 for data, can split string // otherwise, end record and start continue record. if (curMax - dataSize_ >= 12) { if (unicode && !((curMax-dataSize_)%2)) --curMax; // Make sure space reserved for unicode strings is even. continueIndices_.push_back(curMax); stringSize -= (curMax - dataSize_ - 3); dataSize_ = curMax; curMax += 8224; size_t additionalContinueRecords = unicode ? stringSize/8222 : stringSize/8223; // 8222 or 8223 because the first byte is for unicode identifier for(size_t j=0; j<additionalContinueRecords; ++j) { if (unicode) { --curMax; continueIndices_.push_back(curMax); curMax += 8223; dataSize_ += 8223; stringSize -= 8222; } else { continueIndices_.push_back(curMax); curMax += 8224; dataSize_ += 8224; stringSize -= 8223; } } dataSize_ += stringSize + 1; } } } } } return dataSize_; } ULONG Workbook::SharedStringTable::RecordSize() { ULONG dataSize = DataSize(); return recordSize_ = dataSize + 4*(dataSize/8224 + 1); } /************************************************************************************************************/ Workbook::ExtSST::ExtSST() : Record(), stringsTotal_(0), streamPos_(0), firstStringPos_(0), unused_(0) { code_ = CODE::EXTSST; dataSize_ = 2; recordSize_ = 6; } ULONG Workbook::ExtSST::Read(const char* data) { Record::Read(data); LittleEndian::Read(data_, stringsTotal_, 0, 2); ULONG maxPortions = (dataSize_-2) / 8; streamPos_.clear(); streamPos_.resize(maxPortions); firstStringPos_.clear(); firstStringPos_.resize(maxPortions); unused_.clear(); unused_.resize(maxPortions); for(ULONG i=0, npos=2; i<maxPortions; ++i) { LittleEndian::Read(data_, streamPos_[i], npos, 4); LittleEndian::Read(data_, firstStringPos_[i], npos+4, 2); LittleEndian::Read(data_, unused_[i], npos+6, 2); npos += 8; } return RecordSize(); } ULONG Workbook::ExtSST::Write(char* data) { data_.resize(DataSize()); LittleEndian::Write(data_, stringsTotal_, 0, 2); ULONG maxPortions = (ULONG) streamPos_.size(); for(ULONG i=0, npos=2; i<maxPortions; ++i) { LittleEndian::Write(data_, streamPos_[i], npos, 4); LittleEndian::Write(data_, firstStringPos_[i], npos+4, 2); LittleEndian::Write(data_, unused_[i], npos+6, 2); npos += 8; } return Record::Write(data); } ULONG Workbook::ExtSST::DataSize() { dataSize_ = 2 + (ULONG)streamPos_.size()*8; dataSize_ += (int)(dataSize_/8224)*4; return dataSize_; } ULONG Workbook::ExtSST::RecordSize() { return (recordSize_ = DataSize()+(int)((2+(ULONG)streamPos_.size()*8)/8224)*4)+4; } /************************************************************************************************************/ /************************************************************************************************************/ Worksheet::Worksheet() { bof_.version_ = 1536; bof_.type_ = 16; bof_.buildIdentifier_ = 6560; bof_.buildYear_ = 1997; bof_.fileHistoryFlags_ = 49353; bof_.lowestExcelVersion_ = 774; } ULONG Worksheet::Read(const char* data) { ULONG bytesRead = 0; try { short code; LittleEndian::Read(data, code, 0, 2); while(code != CODE::YEOF) { switch(code) { case CODE::BOF: bytesRead += bof_.Read(data+bytesRead); break; case CODE::INDEX: bytesRead += index_.Read(data+bytesRead); break; case CODE::COLINFO: bytesRead += colinfos_.Read(data+bytesRead); break; case CODE::DIMENSIONS: bytesRead += dimensions_.Read(data+bytesRead); break; case CODE::ROW: bytesRead += cellTable_.Read(data+bytesRead); break; case CODE::WINDOW2: bytesRead += window2_.Read(data+bytesRead); break; case CODE::MERGECELLS: bytesRead += mergedCells_.Read(data+bytesRead); break; // case CODE::SXFORMULA: // bytesRead += 4; // skip SXFORMULA record // break; #ifdef _DEBUG case 0: case (short)0xcdcd: case (short)0xfdfd: // assert(0);//@@ break; #endif default: Record rec; bytesRead += rec.Read(data+bytesRead); } LittleEndian::Read(data, code, bytesRead, 2); } bytesRead += eof_.RecordSize(); } catch(EXCEPTION_YEOF& e) { bytesRead += e._bytesRead; } return bytesRead; } ULONG Worksheet::Write(char* data) { ULONG bytesWritten = bof_.Write(data); bytesWritten += index_.Write(data+bytesWritten); bytesWritten += colinfos_.Write(data+bytesWritten); bytesWritten += dimensions_.Write(data+bytesWritten); bytesWritten += cellTable_.Write(data+bytesWritten); bytesWritten += window2_.Write(data+bytesWritten); bytesWritten += mergedCells_.Write(data+bytesWritten); bytesWritten += eof_.Write(data+bytesWritten); return bytesWritten; } ULONG Worksheet::DataSize() { ULONG dataSize = bof_.RecordSize(); dataSize += index_.RecordSize(); dataSize += colinfos_.RecordSize(); dataSize += dimensions_.RecordSize(); dataSize += cellTable_.RecordSize(); dataSize += window2_.RecordSize(); dataSize += mergedCells_.RecordSize(); dataSize += eof_.RecordSize(); return dataSize; } ULONG Worksheet::RecordSize() {return DataSize();} /************************************************************************************************************/ /************************************************************************************************************/ Worksheet::Index::Index() : Record(), unused1_(0), firstUsedRowIndex_(0), firstUnusedRowIndex_(0), unused2_(0) { code_ = CODE::INDEX; dataSize_ = 16; recordSize_ = 20; DBCellPos_.resize(1); } ULONG Worksheet::Index::Read(const char* data) { Record::Read(data); LittleEndian::Read(data_, unused1_, 0, 4); LittleEndian::Read(data_, firstUsedRowIndex_, 4, 4); LittleEndian::Read(data_, firstUnusedRowIndex_, 8, 4); LittleEndian::Read(data_, unused2_, 12, 4); size_t nm = int(firstUnusedRowIndex_ - firstUsedRowIndex_ - 1) / 32 + 1; DBCellPos_.clear(); DBCellPos_.resize(nm); if (dataSize_>16) { for(size_t i=0; i<nm; ++i) { LittleEndian::Read(data_, DBCellPos_[i], 16+i*4, 4); } } return RecordSize(); } ULONG Worksheet::Index::Write(char* data) { data_.resize(DataSize()); LittleEndian::Write(data_, unused1_, 0, 4); LittleEndian::Write(data_, firstUsedRowIndex_, 4, 4); LittleEndian::Write(data_, firstUnusedRowIndex_, 8, 4); LittleEndian::Write(data_, unused2_, 12, 4); size_t nm = DBCellPos_.size(); for(size_t i=0; i<nm; ++i) { LittleEndian::Write(data_, DBCellPos_[i], 16+i*4, 4); } return Record::Write(data); } ULONG Worksheet::Index::DataSize() {return dataSize_ = 16 + (ULONG)DBCellPos_.size()*4;} ULONG Worksheet::Index::RecordSize() { ULONG dataSize = DataSize(); return recordSize_ = dataSize + 4*(dataSize/8224 + 1); } /************************************************************************************************************/ /************************************************************************************************************/ Worksheet::ColInfo::ColInfo() : Record(), firstColumnIndex_(0),lastColumnIndex_(255), columnWidth_(256*10),XFRecordIndex_(0), options_(0),unused_(0) { code_ = CODE::COLINFO; dataSize_ = 12; recordSize_ = 16; } ULONG Worksheet::ColInfo::Read(const char* data) { Record::Read(data); LittleEndian::Read(data_, firstColumnIndex_, 0, 2); LittleEndian::Read(data_, lastColumnIndex_, 2, 2); LittleEndian::Read(data_, columnWidth_, 4, 2); LittleEndian::Read(data_, XFRecordIndex_, 6, 2); LittleEndian::Read(data_, options_, 8, 2); LittleEndian::Read(data_, unused_, 10, 2); return RecordSize(); } ULONG Worksheet::ColInfo::Write(char* data) { data_.resize(DataSize()); LittleEndian::Write(data_, firstColumnIndex_, 0, 2); LittleEndian::Write(data_, lastColumnIndex_, 2, 2); LittleEndian::Write(data_, columnWidth_, 4, 2); LittleEndian::Write(data_, XFRecordIndex_, 6, 2); LittleEndian::Write(data_, options_, 8, 2); LittleEndian::Write(data_, unused_, 10, 2); return Record::Write(data); } /************************************************************************************************************/ ULONG Worksheet::ColInfos::Read(const char* data) { ColInfo ci; ULONG bytesRead = ci.Read(data); colinfo_.push_back(ci); return bytesRead; } ULONG Worksheet::ColInfos::Write(char* data) { ULONG bytesWritten = 0; for(size_t i=0; i<colinfo_.size(); ++i) bytesWritten += colinfo_[i].Write(data+bytesWritten); return bytesWritten; } ULONG Worksheet::ColInfos::RecordSize() { ULONG dataSize = 0; for(size_t i=0; i<colinfo_.size(); ++i) dataSize += colinfo_[i].RecordSize(); return dataSize; } /************************************************************************************************************/ Worksheet::Dimensions::Dimensions() : Record(), firstUsedRowIndex_(0), lastUsedRowIndexPlusOne_(0), firstUsedColIndex_(0), lastUsedColIndexPlusOne_(0), unused_(0) { code_ = CODE::DIMENSIONS; dataSize_ = 14; recordSize_ = 18; } ULONG Worksheet::Dimensions::Read(const char* data) { Record::Read(data); LittleEndian::Read(data_, firstUsedRowIndex_, 0, 4); LittleEndian::Read(data_, lastUsedRowIndexPlusOne_, 4, 4); LittleEndian::Read(data_, firstUsedColIndex_, 8, 2); LittleEndian::Read(data_, lastUsedColIndexPlusOne_, 10, 2); LittleEndian::Read(data_, unused_, 12, 2); return RecordSize(); } ULONG Worksheet::Dimensions::Write(char* data) { data_.resize(DataSize()); LittleEndian::Write(data_, firstUsedRowIndex_, 0, 4); LittleEndian::Write(data_, lastUsedRowIndexPlusOne_, 4, 4); LittleEndian::Write(data_, firstUsedColIndex_, 8, 2); LittleEndian::Write(data_, lastUsedColIndexPlusOne_, 10, 2); LittleEndian::Write(data_, unused_, 12, 2); return Record::Write(data); } /************************************************************************************************************/ /************************************************************************************************************/ Worksheet::CellTable::RowBlock::CellBlock::Blank::Blank() : Record(), rowIndex_(0), colIndex_(0), XFRecordIndex_(0) { code_ = CODE::BLANK; dataSize_ = 6; recordSize_ = 10; } ULONG Worksheet::CellTable::RowBlock::CellBlock::Blank::Read(const char* data) { Record::Read(data); LittleEndian::Read(data_, rowIndex_, 0, 2); LittleEndian::Read(data_, colIndex_, 2, 2); LittleEndian::Read(data_, XFRecordIndex_, 4, 2); return RecordSize(); } ULONG Worksheet::CellTable::RowBlock::CellBlock::Blank::Write(char* data) { data_.resize(DataSize()); LittleEndian::Write(data_, rowIndex_, 0, 2); LittleEndian::Write(data_, colIndex_, 2, 2); LittleEndian::Write(data_, XFRecordIndex_, 4, 2); return Record::Write(data); } Worksheet::CellTable::RowBlock::CellBlock::BoolErr::BoolErr() : Record(), rowIndex_(0), colIndex_(0), XFRecordIndex_(0), value_(0), error_(0) { code_ = CODE::BOOLERR; dataSize_ = 8; recordSize_ = 12; } ULONG Worksheet::CellTable::RowBlock::CellBlock::BoolErr::Read(const char* data) { Record::Read(data); LittleEndian::Read(data_, rowIndex_, 0, 2); LittleEndian::Read(data_, colIndex_, 2, 2); LittleEndian::Read(data_, XFRecordIndex_, 4, 2); LittleEndian::Read(data_, value_, 6, 1); LittleEndian::Read(data_, error_, 7, 1); return RecordSize(); } ULONG Worksheet::CellTable::RowBlock::CellBlock::BoolErr::Write(char* data) { data_.resize(DataSize()); LittleEndian::Write(data_, rowIndex_, 0, 2); LittleEndian::Write(data_, colIndex_, 2, 2); LittleEndian::Write(data_, XFRecordIndex_, 4, 2); LittleEndian::Write(data_, value_, 6, 1); LittleEndian::Write(data_, error_, 7, 1); return Record::Write(data); } Worksheet::CellTable::RowBlock::CellBlock::LabelSST::LabelSST() : Record(), rowIndex_(0), colIndex_(0), XFRecordIndex_(0), SSTRecordIndex_(0) { code_ = CODE::LABELSST; dataSize_ = 10; recordSize_ = 14; } ULONG Worksheet::CellTable::RowBlock::CellBlock::LabelSST::Read(const char* data) { Record::Read(data); LittleEndian::Read(data_, rowIndex_, 0, 2); LittleEndian::Read(data_, colIndex_, 2, 2); LittleEndian::Read(data_, XFRecordIndex_, 4, 2); LittleEndian::Read(data_, SSTRecordIndex_, 6, 4); return RecordSize(); } ULONG Worksheet::CellTable::RowBlock::CellBlock::LabelSST::Write(char* data) { data_.resize(DataSize()); LittleEndian::Write(data_, rowIndex_, 0, 2); LittleEndian::Write(data_, colIndex_, 2, 2); LittleEndian::Write(data_, XFRecordIndex_, 4, 2); LittleEndian::Write(data_, SSTRecordIndex_, 6, 4); return Record::Write(data); } Worksheet::CellTable::RowBlock::CellBlock::MulBlank::MulBlank() : Record(), rowIndex_(0), firstColIndex_(0), lastColIndex_(0) { code_ = CODE::MULBLANK; dataSize_ = 10; recordSize_ = 14; } ULONG Worksheet::CellTable::RowBlock::CellBlock::MulBlank::Read(const char* data) { Record::Read(data); LittleEndian::Read(data_, rowIndex_, 0, 2); LittleEndian::Read(data_, firstColIndex_, 2, 2); LittleEndian::Read(data_, lastColIndex_, dataSize_-2, 2); size_t nc = lastColIndex_ - firstColIndex_ + 1; XFRecordIndices_.clear(); XFRecordIndices_.resize(nc); for(size_t i=0; i<nc; ++i) LittleEndian::Read(data_, XFRecordIndices_[i], 4+i*2, 2); return RecordSize(); } ULONG Worksheet::CellTable::RowBlock::CellBlock::MulBlank::Write(char* data) { data_.resize(DataSize()); LittleEndian::Write(data_, rowIndex_, 0, 2); LittleEndian::Write(data_, firstColIndex_, 2, 2); LittleEndian::Write(data_, lastColIndex_, dataSize_-2, 2); size_t nc = XFRecordIndices_.size(); for(size_t i=0; i<nc; ++i) LittleEndian::Write(data_, XFRecordIndices_[i], 4+i*2, 2); return Record::Write(data); } ULONG Worksheet::CellTable::RowBlock::CellBlock::MulBlank::DataSize() { return dataSize_ = 6 + (ULONG)XFRecordIndices_.size()*2; } ULONG Worksheet::CellTable::RowBlock::CellBlock::MulBlank::RecordSize() { ULONG dataSize = DataSize(); return recordSize_ = dataSize + 4*(dataSize/8224 + 1); } Worksheet::CellTable::RowBlock::CellBlock::MulRK::XFRK::XFRK() : XFRecordIndex_(0), RKValue_(0) {} void Worksheet::CellTable::RowBlock::CellBlock::MulRK::XFRK::Read(const char* data) { LittleEndian::Read(data, XFRecordIndex_, 0, 2); LittleEndian::Read(data, RKValue_, 2, 4); } void Worksheet::CellTable::RowBlock::CellBlock::MulRK::XFRK::Write(char* data) { LittleEndian::Write(data, XFRecordIndex_, 0, 2); LittleEndian::Write(data, RKValue_, 2, 4); } Worksheet::CellTable::RowBlock::CellBlock::MulRK::MulRK() : Record(), rowIndex_(0), firstColIndex_(0), lastColIndex_(0) { code_ = CODE::MULRK; dataSize_ = 10; recordSize_ = 14; } ULONG Worksheet::CellTable::RowBlock::CellBlock::MulRK::Read(const char* data) { Record::Read(data); LittleEndian::Read(data_, rowIndex_, 0, 2); LittleEndian::Read(data_, firstColIndex_, 2, 2); LittleEndian::Read(data_, lastColIndex_, dataSize_-2, 2); size_t nc = lastColIndex_ - firstColIndex_ + 1; XFRK_.clear(); XFRK_.resize(nc); for(size_t i=0; i<nc; ++i) { XFRK_[i].Read(&*(data_.begin())+4+i*6); } return RecordSize(); } ULONG Worksheet::CellTable::RowBlock::CellBlock::MulRK::Write(char* data) { data_.resize(DataSize()); LittleEndian::Write(data_, rowIndex_, 0, 2); LittleEndian::Write(data_, firstColIndex_, 2, 2); LittleEndian::Write(data_, lastColIndex_, dataSize_-2, 2); size_t nc = XFRK_.size(); for(size_t i=0; i<nc; ++i) { XFRK_[i].Write(&*(data_.begin())+4+i*6); } return Record::Write(data); } ULONG Worksheet::CellTable::RowBlock::CellBlock::MulRK::DataSize() { return dataSize_ = 6 + (ULONG)XFRK_.size()*6; } ULONG Worksheet::CellTable::RowBlock::CellBlock::MulRK::RecordSize() { ULONG dataSize = DataSize(); return recordSize_ = dataSize + 4*(dataSize/8224 + 1); } Worksheet::CellTable::RowBlock::CellBlock::Number::Number() : Record(), rowIndex_(0), colIndex_(0), XFRecordIndex_(0), value_(0) { code_ = CODE::NUMBER; dataSize_ = 14; recordSize_ = 18; } ULONG Worksheet::CellTable::RowBlock::CellBlock::Number::Read(const char* data) { Record::Read(data); LittleEndian::Read(data_, rowIndex_, 0, 2); LittleEndian::Read(data_, colIndex_, 2, 2); LittleEndian::Read(data_, XFRecordIndex_, 4, 2); LONGINT value; LittleEndian::Read(data_, value, 6, 8); intdouble_.intvalue_ = value; value_ = intdouble_.doublevalue_; return RecordSize(); } ULONG Worksheet::CellTable::RowBlock::CellBlock::Number::Write(char* data) { data_.resize(DataSize()); LittleEndian::Write(data_, rowIndex_, 0, 2); LittleEndian::Write(data_, colIndex_, 2, 2); LittleEndian::Write(data_, XFRecordIndex_, 4, 2); intdouble_.doublevalue_ = value_; LONGINT value = intdouble_.intvalue_; LittleEndian::Write(data_, value, 6, 8); return Record::Write(data); } Worksheet::CellTable::RowBlock::CellBlock::RK::RK() : Record(), rowIndex_(0), colIndex_(0), XFRecordIndex_(0), value_(0) {code_ = CODE::RK; dataSize_ = 10; recordSize_ = 14;} ULONG Worksheet::CellTable::RowBlock::CellBlock::RK::Read(const char* data) { Record::Read(data); LittleEndian::Read(data_, rowIndex_, 0, 2); LittleEndian::Read(data_, colIndex_, 2, 2); LittleEndian::Read(data_, XFRecordIndex_, 4, 2); LittleEndian::Read(data_, value_, 6, 4); return RecordSize(); } ULONG Worksheet::CellTable::RowBlock::CellBlock::RK::Write(char* data) { data_.resize(DataSize()); LittleEndian::Write(data_, rowIndex_, 0, 2); LittleEndian::Write(data_, colIndex_, 2, 2); LittleEndian::Write(data_, XFRecordIndex_, 4, 2); LittleEndian::Write(data_, value_, 6, 4); return Record::Write(data); } Worksheet::CellTable::RowBlock::CellBlock::Formula::Formula() : Record(), rowIndex_(0), colIndex_(0), XFRecordIndex_(0), options_(0), unused_(0), type_(-1) { code_ = CODE::FORMULA; dataSize_ = 20; recordSize_ = 24; } // was 18/22 instead of 20/24 ULONG Worksheet::CellTable::RowBlock::CellBlock::Formula::Read(const char* data) { Record::Read(data); LittleEndian::Read(data_, rowIndex_, 0, 2); LittleEndian::Read(data_, colIndex_, 2, 2); LittleEndian::Read(data_, XFRecordIndex_, 4, 2); LittleEndian::ReadString(data_, result_, 6, 8); LittleEndian::Read(data_, options_, 14, 2); LittleEndian::Read(data_, unused_, 16, 4); //MF was ", 16, 2" RPNtoken_.clear(); RPNtoken_.resize(dataSize_-20); //MF was "-18" LittleEndian::ReadString(data_, &*(RPNtoken_.begin()), 20, dataSize_-20); // was 18 instead of 20 ULONG offset = dataSize_ + 4; short code; LittleEndian::Read(data, code, offset, 2); switch(code) { case CODE::ARRAY: type_ = code; array_.Read(data+offset); offset += array_.RecordSize(); break; case CODE::SHRFMLA: type_ = code; shrfmla_.Read(data+offset); offset += shrfmla_.RecordSize(); break; case CODE::SHRFMLA1: type_ = code; shrfmla1_.Read(data+offset); offset += shrfmla1_.RecordSize(); break; case CODE::TABLE: type_ = code; table_.Read(data+offset); offset += table_.RecordSize(); break; } LittleEndian::Read(data, code, offset, 2); if (code == CODE::STRING) string_.Read(data+offset); return RecordSize(); } ULONG Worksheet::CellTable::RowBlock::CellBlock::Formula::Write(char* data) { data_.resize(DataSize()); LittleEndian::Write(data_, rowIndex_, 0, 2); LittleEndian::Write(data_, colIndex_, 2, 2); LittleEndian::Write(data_, XFRecordIndex_, 4, 2); LittleEndian::WriteString(data_, result_, 6, 8); LittleEndian::Write(data_, options_, 14, 2); unused_ = 0; // The chn field should be ignored when you read the BIFF file. If you write a BIFF file, the chn field must be 00000000h. LittleEndian::Write(data_, unused_, 16, 4); //MF was ", 16, 2" LittleEndian::WriteString(data_, &*(RPNtoken_.begin()), 20, (ULONG)RPNtoken_.size()); // was 18 instead of 20 Record::Write(data); ULONG offset = dataSize_ + 4; switch(type_) { case CODE::ARRAY: array_.Write(data+offset); offset += array_.RecordSize(); break; case CODE::SHRFMLA: shrfmla_.Write(data+offset); offset += shrfmla_.RecordSize(); break; case CODE::SHRFMLA1: shrfmla1_.Write(data+offset); offset += shrfmla1_.RecordSize(); break; case CODE::TABLE: table_.Write(data+offset); offset += table_.RecordSize(); break; } if (!string_.empty()) string_.Write(data+offset); return RecordSize(); } ULONG Worksheet::CellTable::RowBlock::CellBlock::Formula::DataSize() { return dataSize_ = 20 + (ULONG)RPNtoken_.size(); // was 18 instead of 20 } ULONG Worksheet::CellTable::RowBlock::CellBlock::Formula::RecordSize() { ULONG dataSize = DataSize(); recordSize_ = dataSize + 4*(dataSize/8224 + 1); switch(type_) { case CODE::ARRAY: recordSize_ += array_.RecordSize(); break; case CODE::SHRFMLA: recordSize_ += shrfmla_.RecordSize(); break; case CODE::SHRFMLA1: recordSize_ += shrfmla1_.RecordSize(); break; case CODE::TABLE: recordSize_ += table_.RecordSize(); break; } if (!string_.empty()) recordSize_ += string_.RecordSize(); return recordSize_; } Worksheet::CellTable::RowBlock::CellBlock::Formula::Array::Array() : Record(), firstRowIndex_(0), lastRowIndex_(0), firstColIndex_(0), lastColIndex_(0), options_(0), unused_(0) {code_ = CODE::ARRAY; dataSize_ = 12; recordSize_ = 16;} ULONG Worksheet::CellTable::RowBlock::CellBlock::Formula::Array::Read(const char* data) { Record::Read(data); LittleEndian::Read(data_, firstRowIndex_, 0, 2); LittleEndian::Read(data_, lastRowIndex_, 2, 2); LittleEndian::Read(data_, firstColIndex_, 4, 1); LittleEndian::Read(data_, lastColIndex_, 5, 1); LittleEndian::Read(data_, options_, 6, 2); LittleEndian::Read(data_, unused_, 8, 4); formula_.clear(); formula_.resize(dataSize_-12); LittleEndian::ReadString(data_, &*(formula_.begin()), 12, dataSize_-12); return RecordSize(); } ULONG Worksheet::CellTable::RowBlock::CellBlock::Formula::Array::Write(char* data) { data_.resize(DataSize()); LittleEndian::Write(data_, firstRowIndex_, 0, 2); LittleEndian::Write(data_, lastRowIndex_, 2, 2); LittleEndian::Write(data_, firstColIndex_, 4, 1); LittleEndian::Write(data_, lastColIndex_, 5, 1); LittleEndian::Write(data_, options_, 6, 2); LittleEndian::Write(data_, unused_, 8, 4); LittleEndian::WriteString(data_, &*(formula_.begin()), 12, (ULONG)formula_.size()); return Record::Write(data); } ULONG Worksheet::CellTable::RowBlock::CellBlock::Formula::Array::DataSize() { return dataSize_ = 12 + (ULONG)formula_.size(); } ULONG Worksheet::CellTable::RowBlock::CellBlock::Formula::Array::RecordSize() { ULONG dataSize = DataSize(); return recordSize_ = dataSize + 4*(dataSize/8224 + 1); } Worksheet::CellTable::RowBlock::CellBlock::Formula::ShrFmla::ShrFmla() : Record(), firstRowIndex_(0), lastRowIndex_(0), firstColIndex_(0), lastColIndex_(0), unused_(0) { code_ = CODE::SHRFMLA; dataSize_ = 8; recordSize_ = 12; } ULONG Worksheet::CellTable::RowBlock::CellBlock::Formula::ShrFmla::Read(const char* data) { Record::Read(data); LittleEndian::Read(data_, firstRowIndex_, 0, 2); LittleEndian::Read(data_, lastRowIndex_, 2, 2); LittleEndian::Read(data_, firstColIndex_, 4, 1); LittleEndian::Read(data_, lastColIndex_, 5, 1); LittleEndian::Read(data_, unused_, 6, 2); formula_.clear(); formula_.resize(dataSize_-8); LittleEndian::ReadString(data_, &*(formula_.begin()), 8, dataSize_-8); return RecordSize(); } ULONG Worksheet::CellTable::RowBlock::CellBlock::Formula::ShrFmla::Write(char* data) { data_.resize(DataSize()); LittleEndian::Write(data_, firstRowIndex_, 0, 2); LittleEndian::Write(data_, lastRowIndex_, 2, 2); LittleEndian::Write(data_, firstColIndex_, 4, 1); LittleEndian::Write(data_, lastColIndex_, 5, 1); LittleEndian::Write(data_, unused_, 6, 2); LittleEndian::WriteString(data_, &*(formula_.begin()), 8, (ULONG)formula_.size()); return Record::Write(data); } ULONG Worksheet::CellTable::RowBlock::CellBlock::Formula::ShrFmla::DataSize() { return dataSize_ = 8 + (ULONG)formula_.size(); } ULONG Worksheet::CellTable::RowBlock::CellBlock::Formula::ShrFmla::RecordSize() { ULONG dataSize = DataSize(); return recordSize_ = dataSize + 4*(dataSize/8224 + 1); } Worksheet::CellTable::RowBlock::CellBlock::Formula::ShrFmla1::ShrFmla1() : Record(), firstRowIndex_(0), lastRowIndex_(0), firstColIndex_(0), lastColIndex_(0), unused_(0) { code_ = CODE::SHRFMLA1; dataSize_ = 8; recordSize_ = 12; } ULONG Worksheet::CellTable::RowBlock::CellBlock::Formula::ShrFmla1::Read(const char* data) { Record::Read(data); LittleEndian::Read(data_, firstRowIndex_, 0, 2); LittleEndian::Read(data_, lastRowIndex_, 2, 2); LittleEndian::Read(data_, firstColIndex_, 4, 1); LittleEndian::Read(data_, lastColIndex_, 5, 1); LittleEndian::Read(data_, unused_, 6, 2); formula_.clear(); formula_.resize(dataSize_-8); LittleEndian::ReadString(data_, &*(formula_.begin()), 8, dataSize_-8); return RecordSize(); } ULONG Worksheet::CellTable::RowBlock::CellBlock::Formula::ShrFmla1::Write(char* data) { data_.resize(DataSize()); LittleEndian::Write(data_, firstRowIndex_, 0, 2); LittleEndian::Write(data_, lastRowIndex_, 2, 2); LittleEndian::Write(data_, firstColIndex_, 4, 1); LittleEndian::Write(data_, lastColIndex_, 5, 1); LittleEndian::Write(data_, unused_, 6, 2); LittleEndian::WriteString(data_, &*(formula_.begin()), 8, (ULONG)formula_.size()); return Record::Write(data); } ULONG Worksheet::CellTable::RowBlock::CellBlock::Formula::ShrFmla1::DataSize() { return dataSize_ = 8 + (ULONG)formula_.size(); } ULONG Worksheet::CellTable::RowBlock::CellBlock::Formula::ShrFmla1::RecordSize() { ULONG dataSize = DataSize(); return recordSize_ = dataSize + 4*(dataSize/8224 + 1); } Worksheet::CellTable::RowBlock::CellBlock::Formula::Table::Table() : Record(), firstRowIndex_(0), lastRowIndex_(0), firstColIndex_(0), lastColIndex_(0), options_(0), inputCellRowIndex_(0), inputCellColIndex_(0), inputCellColumnInputRowIndex_(0), inputCellColumnInputColIndex_(0) {code_ = CODE::TABLE; dataSize_ = 16; recordSize_ = 20;} ULONG Worksheet::CellTable::RowBlock::CellBlock::Formula::Table::Read(const char* data) { Record::Read(data); LittleEndian::Read(data_, firstRowIndex_, 0, 2); LittleEndian::Read(data_, lastRowIndex_, 2, 2); LittleEndian::Read(data_, firstColIndex_, 4, 1); LittleEndian::Read(data_, lastColIndex_, 5, 1); LittleEndian::Read(data_, options_, 6, 2); LittleEndian::Read(data_, inputCellRowIndex_, 8, 2); LittleEndian::Read(data_, inputCellColIndex_, 10, 2); LittleEndian::Read(data_, inputCellColumnInputRowIndex_, 12, 2); LittleEndian::Read(data_, inputCellColumnInputColIndex_, 14, 2); return RecordSize(); } ULONG Worksheet::CellTable::RowBlock::CellBlock::Formula::Table::Write(char* data) { data_.resize(DataSize()); LittleEndian::Write(data_, firstRowIndex_, 0, 2); LittleEndian::Write(data_, lastRowIndex_, 2, 2); LittleEndian::Write(data_, firstColIndex_, 4, 1); LittleEndian::Write(data_, lastColIndex_, 5, 1); LittleEndian::Write(data_, options_, 6, 2); LittleEndian::Write(data_, inputCellRowIndex_, 8, 2); LittleEndian::Write(data_, inputCellColIndex_, 10, 2); LittleEndian::Write(data_, inputCellColumnInputRowIndex_, 12, 2); LittleEndian::Write(data_, inputCellColumnInputColIndex_, 14, 2); return Record::Write(data); } Worksheet::CellTable::RowBlock::CellBlock::Formula::String::String() : Record() { code_ = CODE::STRING; dataSize_ = 0; recordSize_ = 4; flag_ = 0; wstr_ = NULL; } Worksheet::CellTable::RowBlock::CellBlock::Formula::String::~String() { Reset(); } void Worksheet::CellTable::RowBlock::CellBlock::Formula::String::Reset() { if (wstr_) {delete[] wstr_; wstr_ = NULL;} } ULONG Worksheet::CellTable::RowBlock::CellBlock::Formula::String::Read(const char* data) { Reset(); Record::Read(data); //MF short stringSize; LittleEndian::Read(data_, stringSize, 0, 2); LittleEndian::Read(data_, flag_, 2, 1); wstr_ = new wchar_t[stringSize+1]; ULONG bytesRead = 7; if (flag_ == 0) { // compressed UTF16LE string? char* str = (char*) alloca(stringSize+1); LittleEndian::ReadString(data_, str, 3, stringSize); str[stringSize] = 0; mbstowcs(wstr_, str, stringSize); wstr_[stringSize] = 0; bytesRead += stringSize; } else { LittleEndian::ReadString(data_, wstr_, 3, stringSize); wstr_[stringSize] = 0; bytesRead += stringSize*2; } return bytesRead;//RecordSize(); } ULONG Worksheet::CellTable::RowBlock::CellBlock::Formula::String::Write(char* data) { data_.resize(DataSize()); short stringSize = (short) wcslen(wstr_); LittleEndian::Write(data_, stringSize, 0, 2); LittleEndian::Write(data_, flag_, 2, 1); if (flag_ == 0) { // compressed UTF16LE string? char* str = (char*) alloca(stringSize); wcstombs(str, wstr_, stringSize); LittleEndian::WriteString(data_, str, 3, stringSize); } else { LittleEndian::WriteString(data_, wstr_, 3, stringSize); } return Record::Write(data); } ULONG Worksheet::CellTable::RowBlock::CellBlock::Formula::String::DataSize() { if (wstr_) { dataSize_ = 3; if (flag_ == 0) // compressed UTF16LE string? dataSize_ += (ULONG) wcslen(wstr_); else dataSize_ += (ULONG) wcslen(wstr_) * SIZEOFWCHAR_T; } else dataSize_ = 0; return dataSize_; } ULONG Worksheet::CellTable::RowBlock::CellBlock::Formula::String::RecordSize() { ULONG dataSize = DataSize(); return recordSize_ = dataSize + 4*(dataSize/8224 + 1); } /************************************************************************************************************/ /************************************************************************************************************/ Worksheet::CellTable::RowBlock::Row::Row() : Record(), rowIndex_(0), firstCellColIndex_(0), lastCellColIndexPlusOne_(0), height_(255), unused1_(0), unused2_(0), options_(0x100/*MF: documentation says "Always 1" for the 0x100 bit*/) {code_ = CODE::ROW; dataSize_ = 16; recordSize_ = 20;} ULONG Worksheet::CellTable::RowBlock::Row::Read(const char* data) { Record::Read(data); LittleEndian::Read(data_, rowIndex_, 0, 2); LittleEndian::Read(data_, firstCellColIndex_, 2, 2); LittleEndian::Read(data_, lastCellColIndexPlusOne_, 4, 2); LittleEndian::Read(data_, height_, 6, 2); LittleEndian::Read(data_, unused1_, 8, 2); LittleEndian::Read(data_, unused2_, 10, 2); LittleEndian::Read(data_, options_, 12, 4); return RecordSize(); } ULONG Worksheet::CellTable::RowBlock::Row::Write(char* data) { data_.resize(DataSize()); LittleEndian::Write(data_, rowIndex_, 0, 2); LittleEndian::Write(data_, firstCellColIndex_, 2, 2); LittleEndian::Write(data_, lastCellColIndexPlusOne_, 4, 2); LittleEndian::Write(data_, height_, 6, 2); LittleEndian::Write(data_, unused1_, 8, 2); LittleEndian::Write(data_, unused2_, 10, 2); LittleEndian::Write(data_, options_, 12, 4); return Record::Write(data); } /************************************************************************************************************/ /************************************************************************************************************/ Worksheet::CellTable::RowBlock::CellBlock::CellBlock() : type_(-1) { _union.void_ = NULL; } Worksheet::CellTable::RowBlock::CellBlock::~CellBlock() { if (_union.void_) Reset(); } void Worksheet::CellTable::RowBlock::CellBlock::Reset() { switch(type_) { case CODE::BLANK: delete _union.blank_; break; case CODE::MULBLANK: delete _union.mulblank_; break; case CODE::BOOLERR: delete _union.boolerr_; break; case CODE::LABELSST: delete _union.labelsst_; break; case CODE::MULRK: delete _union.mulrk_; break; case CODE::NUMBER: delete _union.number_; break; case CODE::RK: delete _union.rk_; break; case CODE::FORMULA: delete _union.formula_; break; } type_ = -1; _union.void_ = NULL; } void Worksheet::CellTable::RowBlock::CellBlock::SetType(int type) { if (type_ == type) return; if (_union.void_) Reset(); type_ = type; switch(type_) { case CODE::BLANK: _union.blank_ = new Blank; break; case CODE::MULBLANK: _union.mulblank_ = new MulBlank; break; case CODE::BOOLERR: _union.boolerr_ = new BoolErr; break; case CODE::LABELSST: _union.labelsst_ = new LabelSST; break; case CODE::MULRK: _union.mulrk_ = new MulRK; break; case CODE::NUMBER: _union.number_ = new Number; break; case CODE::RK: _union.rk_ = new RK; break; case CODE::FORMULA: _union.formula_ = new Formula; break; default: assert(0); } } ULONG Worksheet::CellTable::RowBlock::CellBlock::Read(const char* data) { ULONG bytesRead = 0; int type; LittleEndian::Read(data, type, 0, 2); SetType(type); switch(type_) { case CODE::BLANK: _union.blank_ = new Blank; bytesRead += _union.blank_->Read(data); break; case CODE::MULBLANK: _union.mulblank_ = new MulBlank; bytesRead += _union.mulblank_->Read(data); break; case CODE::BOOLERR: _union.boolerr_ = new BoolErr; bytesRead += _union.boolerr_->Read(data); break; case CODE::LABELSST: _union.labelsst_ = new LabelSST; bytesRead += _union.labelsst_->Read(data); break; case CODE::MULRK: _union.mulrk_ = new MulRK; bytesRead +=_union. mulrk_->Read(data); break; case CODE::NUMBER: _union.number_ = new Number; bytesRead += _union.number_->Read(data); break; case CODE::RK: _union.rk_ = new RK; bytesRead += _union.rk_->Read(data); break; case CODE::FORMULA: _union.formula_ = new Formula; bytesRead += _union.formula_->Read(data); break; } return bytesRead; } ULONG Worksheet::CellTable::RowBlock::CellBlock::Write(char* data) { ULONG bytesWritten = 0; switch(type_) { case CODE::BLANK: bytesWritten += _union.blank_->Write(data); break; case CODE::MULBLANK: bytesWritten += _union.mulblank_->Write(data); break; case CODE::BOOLERR: bytesWritten += _union.boolerr_->Write(data); break; case CODE::LABELSST: bytesWritten += _union.labelsst_->Write(data); break; case CODE::MULRK: bytesWritten += _union.mulrk_->Write(data); break; case CODE::NUMBER: bytesWritten += _union.number_->Write(data); break; case CODE::RK: bytesWritten += _union.rk_->Write(data); break; case CODE::FORMULA: bytesWritten += _union.formula_->Write(data); break; } return bytesWritten; } ULONG Worksheet::CellTable::RowBlock::CellBlock::DataSize() { switch(type_) { case CODE::BLANK: return _union.blank_->DataSize(); case CODE::MULBLANK: return _union.mulblank_->DataSize(); case CODE::BOOLERR: return _union.boolerr_->DataSize(); case CODE::LABELSST: return _union.labelsst_->DataSize(); case CODE::MULRK: return _union.mulrk_->DataSize(); case CODE::NUMBER: return _union.number_->DataSize(); case CODE::RK: return _union.rk_->DataSize(); case CODE::FORMULA: return _union.formula_->DataSize(); } abort(); return 0; } ULONG Worksheet::CellTable::RowBlock::CellBlock::RecordSize() { switch(type_) { case CODE::BLANK: return _union.blank_->RecordSize(); case CODE::MULBLANK: return _union.mulblank_->RecordSize(); case CODE::BOOLERR: return _union.boolerr_->RecordSize(); case CODE::LABELSST: return _union.labelsst_->RecordSize(); case CODE::MULRK: return _union.mulrk_->RecordSize(); case CODE::NUMBER: return _union.number_->RecordSize(); case CODE::RK: return _union.rk_->RecordSize(); case CODE::FORMULA: return _union.formula_->RecordSize(); } abort(); return 0; } USHORT Worksheet::CellTable::RowBlock::CellBlock::RowIndex() { switch(type_) { case CODE::BLANK: return _union.blank_->rowIndex_; case CODE::MULBLANK: return _union.mulblank_->rowIndex_; case CODE::BOOLERR: return _union.boolerr_->rowIndex_; case CODE::LABELSST: return _union.labelsst_->rowIndex_; case CODE::MULRK: return _union.mulrk_->rowIndex_; case CODE::NUMBER: return _union.number_->rowIndex_; case CODE::RK: return _union.rk_->rowIndex_; case CODE::FORMULA: return _union.formula_->rowIndex_; } abort(); return 0; } USHORT Worksheet::CellTable::RowBlock::CellBlock::ColIndex() { switch(type_) { case CODE::BLANK: return _union.blank_->colIndex_; case CODE::MULBLANK: return _union.mulblank_->firstColIndex_; case CODE::BOOLERR: return _union.boolerr_->colIndex_; case CODE::LABELSST: return _union.labelsst_->colIndex_; case CODE::MULRK: return _union.mulrk_->firstColIndex_; case CODE::NUMBER: return _union.number_->colIndex_; case CODE::RK: return _union.rk_->colIndex_; case CODE::FORMULA: return _union.formula_->colIndex_; } abort(); return 0; } /************************************************************************************************************/ /************************************************************************************************************/ Worksheet::CellTable::RowBlock::DBCell::DBCell() : Record(), firstRowOffset_(0) { code_ = CODE::DBCELL; dataSize_ = 4; recordSize_ = 8; } ULONG Worksheet::CellTable::RowBlock::DBCell::Read(const char* data) { Record::Read(data); LittleEndian::Read(data_, firstRowOffset_, 0, 4); size_t nm = (dataSize_-4) / 2; offsets_.clear(); offsets_.resize(nm); for(size_t i=0; i<nm; ++i) LittleEndian::Read(data_, offsets_[i], 4+i*2, 2); return RecordSize(); } ULONG Worksheet::CellTable::RowBlock::DBCell::Write(char* data) { data_.resize(DataSize()); LittleEndian::Write(data_, firstRowOffset_, 0, 4); size_t nm = offsets_.size(); for(size_t i=0; i<nm; ++i) LittleEndian::Write(data_, offsets_[i], 4+i*2, 2); return Record::Write(data); } ULONG Worksheet::CellTable::RowBlock::DBCell::DataSize() { return dataSize_ = 4+(ULONG)offsets_.size()*2; } ULONG Worksheet::CellTable::RowBlock::DBCell::RecordSize() { ULONG dataSize = DataSize(); return recordSize_ = dataSize + 4*(dataSize/8224 + 1); } /************************************************************************************************************/ /************************************************************************************************************/ ULONG Worksheet::CellTable::RowBlock::Read(const char* data) { ULONG bytesRead = 0; short code; LittleEndian::Read(data, code, 0, 2); Row row; cellBlocks_.reserve(1000); while(code != CODE::DBCELL) { switch(code) { case CODE::ROW: rows_.push_back(row); bytesRead += rows_.back().Read(data+bytesRead); break; case CODE::BLANK: case CODE::MULBLANK: case CODE::BOOLERR: case CODE::LABELSST: case CODE::MULRK: case CODE::NUMBER: case CODE::RK: case CODE::FORMULA: cellBlocks_.push_back(new CellBlock); if (cellBlocks_.size()%1000==0) cellBlocks_.reserve(cellBlocks_.size()+1000); bytesRead += cellBlocks_[cellBlocks_.size()-1]->Read(data+bytesRead); break; default: Record rec; bytesRead += rec.Read(data+bytesRead); } //MF: finish loop and skip reading the following expected records, if there is a EOF marker before DBCELL // (written by the XLS export of MacOS Numbers.app) if (code == CODE::YEOF) throw EXCEPTION_YEOF(bytesRead); LittleEndian::Read(data, code, bytesRead, 2); } bytesRead += dbcell_.Read(data+bytesRead); return bytesRead; } ULONG Worksheet::CellTable::RowBlock::Write(char* data) { ULONG bytesWritten = 0; size_t maxRows = rows_.size(); {for(size_t i=0; i<maxRows; ++i) { bytesWritten += rows_[i].Write(data+bytesWritten); }} size_t maxCellBlocks = cellBlocks_.size(); {for(size_t i=0; i<maxCellBlocks; ++i) { bytesWritten += cellBlocks_[i]->Write(data+bytesWritten); }} bytesWritten += dbcell_.Write(data+bytesWritten); return bytesWritten; } ULONG Worksheet::CellTable::RowBlock::DataSize() { ULONG dataSize = 0; size_t maxRows = rows_.size(); {for(size_t i=0; i<maxRows; ++i) dataSize += rows_[i].RecordSize();} size_t maxCellBlocks = cellBlocks_.size(); {for(size_t i=0; i<maxCellBlocks; ++i) dataSize += cellBlocks_[i]->RecordSize();} dataSize += dbcell_.RecordSize(); return dataSize; } ULONG Worksheet::CellTable::RowBlock::RecordSize() {return DataSize();} /************************************************************************************************************/ /************************************************************************************************************/ ULONG Worksheet::CellTable::Read(const char* data) { ULONG bytesRead = 0; short code; LittleEndian::Read(data, code, 0, 2); RowBlock rowBlock; rowBlocks_.reserve(1000); while(code == CODE::ROW) { rowBlocks_.push_back(rowBlock); bytesRead += rowBlocks_.back().Read(data+bytesRead); LittleEndian::Read(data, code, bytesRead, 2); } return bytesRead; } ULONG Worksheet::CellTable::Write(char* data) { ULONG bytesWritten = 0; size_t maxRowBlocks_ = rowBlocks_.size(); for(size_t i=0; i<maxRowBlocks_; ++i) bytesWritten += rowBlocks_[i].Write(data+bytesWritten); return bytesWritten; } ULONG Worksheet::CellTable::DataSize() { ULONG dataSize = 0; size_t maxRowBlocks_ = rowBlocks_.size(); for(size_t i=0; i<maxRowBlocks_; ++i) dataSize += rowBlocks_[i].RecordSize(); return dataSize; } ULONG Worksheet::CellTable::RecordSize() {return DataSize();} /************************************************************************************************************/ /************************************************************************************************************/ Worksheet::Window2::Window2() : Record(), options_(1718), firstVisibleRowIndex_(0), firstVisibleColIndex_(0), gridLineColourIndex_(64), unused1_(0), magnificationFactorPageBreakPreview_(0), magnificationFactorNormalView_(0), unused2_(0) {code_ = CODE::WINDOW2; dataSize_ = 18; recordSize_ = 22;} ULONG Worksheet::Window2::Read(const char* data) { Record::Read(data); LittleEndian::Read(data_, options_, 0, 2); LittleEndian::Read(data_, firstVisibleRowIndex_, 2, 2); LittleEndian::Read(data_, firstVisibleColIndex_, 4, 2); LittleEndian::Read(data_, gridLineColourIndex_, 6, 2); LittleEndian::Read(data_, unused1_, 8, 2); LittleEndian::Read(data_, magnificationFactorPageBreakPreview_, 10, 2); LittleEndian::Read(data_, magnificationFactorNormalView_, 12, 2); LittleEndian::Read(data_, unused2_, 14, 4); return RecordSize(); } ULONG Worksheet::Window2::Write(char* data) { data_.resize(DataSize()); LittleEndian::Write(data_, options_, 0, 2); LittleEndian::Write(data_, firstVisibleRowIndex_, 2, 2); LittleEndian::Write(data_, firstVisibleColIndex_, 4, 2); LittleEndian::Write(data_, gridLineColourIndex_, 6, 2); LittleEndian::Write(data_, unused1_, 8, 2); LittleEndian::Write(data_, magnificationFactorPageBreakPreview_, 10, 2); LittleEndian::Write(data_, magnificationFactorNormalView_, 12, 2); LittleEndian::Write(data_, unused2_, 14, 4); return Record::Write(data); } /************************************************************************************************************/ /************************************************************************************************************/ ULONG Worksheet::MergedCells::Read(const char* data) { ULONG bytesRead = 0; short code; LittleEndian::Read(data, code, 0, 2); short dataSize; size_t nbMergedCells; MergedCell mergedCell; mergedCellsVector_.reserve(1000); while(code == CODE::MERGECELLS) { bytesRead += 2; LittleEndian::Read(data, dataSize, bytesRead, 2); bytesRead += 2; LittleEndian::Read(data, nbMergedCells, bytesRead, 2); bytesRead += 2; for(size_t i = 0; i < nbMergedCells; i++) { mergedCellsVector_.push_back(mergedCell); bytesRead += mergedCellsVector_.back().Read(data+bytesRead); } LittleEndian::Read(data, code, bytesRead, 2); } return bytesRead; } ULONG Worksheet::MergedCells::Write(char* data) { ULONG bytesWritten = 0; size_t mergedCellsLeft_ = mergedCellsVector_.size(); short maxPackedMergedCells; while(mergedCellsLeft_) { if (mergedCellsLeft_ > 1027) maxPackedMergedCells = 1027; else maxPackedMergedCells = (short) mergedCellsLeft_; short code = CODE::MERGECELLS; LittleEndian::Write(data, code, bytesWritten, 2); bytesWritten += 2; LittleEndian::Write(data, maxPackedMergedCells * 8 + 2, bytesWritten, 2); bytesWritten += 2; LittleEndian::Write(data, maxPackedMergedCells, bytesWritten, 2); bytesWritten += 2; for(short i = 0; i < maxPackedMergedCells; ++i) bytesWritten += mergedCellsVector_[i].Write(data+bytesWritten); mergedCellsLeft_ -= maxPackedMergedCells; } return bytesWritten; } ULONG Worksheet::MergedCells::DataSize() { ULONG dataSize = 0; size_t maxMergedCells_ = mergedCellsVector_.size(); for(size_t i=0; i<maxMergedCells_; ++i) dataSize += mergedCellsVector_[i].RecordSize(); return dataSize; } ULONG Worksheet::MergedCells::RecordSize() { ULONG dataSize = DataSize(); size_t nbMergedCellsPack = 1; size_t mergedCellsCount = mergedCellsVector_.size(); while(mergedCellsCount > 1027) { mergedCellsCount -= 1027; nbMergedCellsPack++; } if (dataSize == 0) return 0; return dataSize + (ULONG)nbMergedCellsPack * 6; } /************************************************************************************************************/ /************************************************************************************************************/ Worksheet::MergedCells::MergedCell::MergedCell() : firstRow_(0), lastRow_(0), firstColumn_(0), lastColumn_(0) { } ULONG Worksheet::MergedCells::MergedCell::Read(const char* data) { vector<char> data_; data_.assign(data, data+DataSize()); // read REF record LittleEndian::Read(data_, firstRow_, 0, 2); LittleEndian::Read(data_, lastRow_, 2, 2); LittleEndian::Read(data_, firstColumn_, 4, 2); LittleEndian::Read(data_, lastColumn_, 6, 2); return RecordSize(); } ULONG Worksheet::MergedCells::MergedCell::Write(char* data) { // write REF record LittleEndian::Write(data, firstRow_, 0, 2); LittleEndian::Write(data, lastRow_, 2, 2); LittleEndian::Write(data, firstColumn_, 4, 2); LittleEndian::Write(data, lastColumn_, 6, 2); return DataSize(); } ULONG Worksheet::MergedCells::MergedCell::DataSize() {return 8;} ULONG Worksheet::MergedCells::MergedCell::RecordSize() {return DataSize();} /************************************************************************************************************/ //MF union to work with a RK value (encoded integer or floating point value) union RKValueUnion { LONGINT intvalue_; double doublevalue_; }; // Convert a double to a RK value. LONG GetRKValueFromDouble(double value) { bool isMultiplied = false; LONG testVal1 = (LONG)value * 100; LONG testVal2 = (LONG)(value * 100); if (testVal1 != testVal2) { isMultiplied = true; value *= 100; } RKValueUnion intdouble; // CODE ADDDED 2010/09/08 by VaKa: missing initialization intdouble.intvalue_ = 0; //MF: should not be neccessary, as intvalue_ and doublevalue_ use the same bytes in memory intdouble.doublevalue_ = value; intdouble.intvalue_ >>= 34; LONG rkValue = (LONG) intdouble.intvalue_; rkValue <<= 2; rkValue |= (isMultiplied? 1: 0); return rkValue; } // Convert an integer to a RK value. LONG GetRKValueFromInteger(int value) { value <<= 2; value |= 2; return value; } // Returns true if the supplied double can be stored as a RK value. bool CanStoreAsRKValue(double value) { LONG testVal1 = 100 * (LONG)(value * 100); LONG testVal2 = LONG(value * 10000); if (testVal1 != testVal2) return false; else return true; } /************************************************************************************************************/ /************************************************************************************************************/ BasicExcel::BasicExcel() {} BasicExcel::BasicExcel(const char* filename) { Load(filename); } BasicExcel::~BasicExcel() { Close(); } void BasicExcel::Close() { if (file_.IsOpen()) file_.Close(); } // Create a new Excel workbook with a given number of spreadsheets (Minimum 1) void BasicExcel::New(int sheets) { workbook_ = Workbook(); worksheets_.clear(); workbook_.fonts_.resize(1); //MF was 4, see XLSFormatManager::get_font_idx() workbook_.XFs_.resize(21); workbook_.styles_.resize(6); workbook_.boundSheets_.resize(1); worksheets_.resize(1); UpdateYExcelWorksheet(); for(int i=0; i<sheets-1; ++i) AddWorksheet(); } // Load an Excel workbook from a file. bool BasicExcel::Load(const char* filename) { if (file_.IsOpen()) file_.Close(); if (file_.Open(filename)) { workbook_ = Workbook(); worksheets_.clear(); vector<char> data; file_.ReadFile("Workbook", data); Read(&*(data.begin()), data.size()); UpdateYExcelWorksheet(); return true; } else return false; } // Load an Excel workbook from a file with Unicode filename. bool BasicExcel::Load(const wchar_t* filename) { if (file_.IsOpen()) file_.Close(); if (file_.Open(filename)) { workbook_ = Workbook(); worksheets_.clear(); vector<char> data; file_.ReadFile("Workbook", data); Read(&*(data.begin()), data.size()); UpdateYExcelWorksheet(); return true; } else return false; } // Save current Excel workbook to opened file. bool BasicExcel::Save() { if (file_.IsOpen()) { // Prepare Raw Worksheets for saving. UpdateWorksheets(); AdjustStreamPositions(); // Calculate bytes needed for a workbook. size_t minBytes = workbook_.RecordSize(); size_t maxWorkSheets = worksheets_.size(); for(size_t i=0; i<maxWorkSheets; ++i) minBytes += worksheets_[i].RecordSize(); // Create new workbook. vector<char> data(minBytes, 0); Write(&*(data).begin()); if (file_.WriteFile("Workbook", data, (ULONG)data.size()) != SUCCESS) return false; else return true; } else return false; } // Save current Excel workbook to a file. bool BasicExcel::SaveAs(const char* filename) { if (file_.IsOpen()) file_.Close(); if (!file_.Create(filename)) return false; if (file_.MakeFile("Workbook") != SUCCESS) return false; return Save(); } // Save current Excel workbook to a file with Unicode filename bool BasicExcel::SaveAs(const wchar_t* filename) { if (file_.IsOpen()) file_.Close(); if (!file_.Create(filename)) return false; if (file_.MakeFile("Workbook") != SUCCESS) return false; return Save(); } // Total number of Excel worksheets in current Excel workbook. int BasicExcel::GetTotalWorkSheets() { return (int) worksheets_.size(); } // Get a pointer to an Excel worksheet at the given index. // Index starts from 0. // Returns 0 if index is invalid. BasicExcelWorksheet* BasicExcel::GetWorksheet(int sheetIndex) { return &*(yesheets_[sheetIndex]); } // Get a pointer to an Excel worksheet that has given ANSI name. // Returns 0 if there is no Excel worksheet with the given name. BasicExcelWorksheet* BasicExcel::GetWorksheet(const char* name) { int maxWorksheets = (int) yesheets_.size(); for(int i=0; i<maxWorksheets; ++i) { if (workbook_.boundSheets_[i].name_.unicode_ & 1) continue; if (strcmp(name, workbook_.boundSheets_[i].name_.name_) == 0) return &*yesheets_[i]; } return NULL; } // Get a pointer to an Excel worksheet that has given Unicode name. // Returns 0 if there is no Excel worksheet with the given name. BasicExcelWorksheet* BasicExcel::GetWorksheet(const wchar_t* name) { int maxWorksheets = (int) yesheets_.size(); for(int i=0; i<maxWorksheets; ++i) { if (!(workbook_.boundSheets_[i].name_.unicode_ & 1)) continue; if (wcscmp(name, workbook_.boundSheets_[i].name_.wname_) == 0) return &*yesheets_[i]; } return NULL; } // Add a new Excel worksheet to the given index. // Name given to worksheet is SheetX, where X is a number which starts from 1. // Index starts from 0. // Worksheet is added to the last position if sheetIndex == -1. // Returns a pointer to the worksheet if successful, 0 if otherwise. BasicExcelWorksheet* BasicExcel::AddWorksheet(int sheetIndex) { int sheetNo = (int)yesheets_.size() + 1; BasicExcelWorksheet* yesheet = 0; do { char sname[50]; sprintf(sname, "Sheet%d", sheetNo++); yesheet = AddWorksheet(sname, sheetIndex); } while(!yesheet); return yesheet; } // Add a new Excel worksheet with given ANSI name to the given index. // Index starts from 0. // Worksheet is added to the last position if sheetIndex == -1. // Returns a pointer to the worksheet if successful, 0 if otherwise. BasicExcelWorksheet* BasicExcel::AddWorksheet(const char* name, int sheetIndex) { int maxWorksheets = (int) yesheets_.size(); for(int i=0; i<maxWorksheets; ++i) { if (workbook_.boundSheets_[i].name_.unicode_ & 1) continue; if (strcmp(name, workbook_.boundSheets_[i].name_.name_) == 0) return NULL; } Workbook::BoundSheet* boundSheet; Worksheet* worksheet; BasicExcelWorksheet* yesheet; if (sheetIndex == -1) { workbook_.boundSheets_.push_back(Workbook::BoundSheet()); worksheets_.push_back(Worksheet()); yesheets_.push_back(new BasicExcelWorksheet(this, (int)worksheets_.size()-1)); boundSheet = &(workbook_.boundSheets_.back()); worksheet = &(worksheets_.back()); yesheet = &*yesheets_.back(); } else { boundSheet = &*(workbook_.boundSheets_.insert(workbook_.boundSheets_.begin()+sheetIndex, Workbook::BoundSheet())); worksheet = &*(worksheets_.insert(worksheets_.begin()+sheetIndex, Worksheet())); yesheet = &**(yesheets_.insert(yesheets_.begin()+sheetIndex, new BasicExcelWorksheet(this, sheetIndex))); int maxSheets = (int) worksheets_.size(); for(int i=sheetIndex+1; i<maxSheets; ++i) yesheets_[i]->sheetIndex_ = i; } boundSheet->name_ = name; worksheet->window2_.options_ &= ~0x200; return yesheet; } // Add a new Excel worksheet with given Unicode name to the given index. // Index starts from 0. // Worksheet is added to the last position if sheetIndex == -1. // Returns a pointer to the worksheet if successful, 0 if otherwise. BasicExcelWorksheet* BasicExcel::AddWorksheet(const wchar_t* name, int sheetIndex) { int maxWorksheets = (int)yesheets_.size(); for(int i=0; i<maxWorksheets; ++i) { if (!(workbook_.boundSheets_[i].name_.unicode_ & 1)) continue; if (wcscmp(name, workbook_.boundSheets_[i].name_.wname_) == 0) return NULL; } Workbook::BoundSheet* boundSheet; Worksheet* worksheet; BasicExcelWorksheet* yesheet; if (sheetIndex == -1) { workbook_.boundSheets_.push_back(Workbook::BoundSheet()); worksheets_.push_back(Worksheet()); yesheets_.push_back(new BasicExcelWorksheet(this, (int)worksheets_.size()-1)); boundSheet = &(workbook_.boundSheets_.back()); worksheet = &(worksheets_.back()); yesheet = &*yesheets_.back(); } else { boundSheet = &*(workbook_.boundSheets_.insert(workbook_.boundSheets_.begin()+sheetIndex, Workbook::BoundSheet())); worksheet = &*(worksheets_.insert(worksheets_.begin()+sheetIndex, Worksheet())); yesheet = &**(yesheets_.insert(yesheets_.begin()+sheetIndex, new BasicExcelWorksheet(this, sheetIndex))); int maxSheets = (int) worksheets_.size(); for(int i=sheetIndex+1; i<maxSheets; ++i) yesheets_[i]->sheetIndex_ = i; } boundSheet->name_ = name; worksheet->window2_.options_ &= ~0x200; return yesheet; } // Delete an Excel worksheet at the given index. // Index starts from 0. // Returns true if successful, false if otherwise. bool BasicExcel::DeleteWorksheet(int sheetIndex) { if (sheetIndex < (int)workbook_.boundSheets_.size()) { workbook_.boundSheets_.erase(workbook_.boundSheets_.begin()+sheetIndex); worksheets_.erase(worksheets_.begin()+sheetIndex); yesheets_.erase(yesheets_.begin()+sheetIndex); return true; } else return false; } // Delete an Excel worksheet that has given ANSI name. // Returns true if successful, false if otherwise. bool BasicExcel::DeleteWorksheet(const char* name) { int maxWorksheets = (int)yesheets_.size(); for(int i=0; i<maxWorksheets; ++i) { if (workbook_.boundSheets_[i].name_.unicode_ & 1) continue; if (strcmp(name, workbook_.boundSheets_[i].name_.name_) == 0) return DeleteWorksheet(i); } return false; } // Delete an Excel worksheet that has given Unicode name. // Returns true if successful, false if otherwise. bool BasicExcel::DeleteWorksheet(const wchar_t* name) { int maxWorksheets = (int) worksheets_.size(); for(int i=0; i<maxWorksheets; ++i) { if (!(workbook_.boundSheets_[i].name_.unicode_ & 1)) continue; if (wcscmp(name, workbook_.boundSheets_[i].name_.wname_) == 0) return DeleteWorksheet(i); } return false; } // Get the worksheet name at the given index. // Index starts from 0. // Returns 0 if name is in Unicode format. char* BasicExcel::GetAnsiSheetName(int sheetIndex) { if (!(workbook_.boundSheets_[sheetIndex].name_.unicode_ & 1)) return workbook_.boundSheets_[sheetIndex].name_.name_; else return NULL; } // Get the worksheet name at the given index. // Index starts from 0. // Returns 0 if name is in Ansi format. wchar_t* BasicExcel::GetUnicodeSheetName(int sheetIndex) { if (workbook_.boundSheets_[sheetIndex].name_.unicode_ & 1) return workbook_.boundSheets_[sheetIndex].name_.wname_; else return NULL; } // Get the worksheet name at the given index. // Index starts from 0. // Returns false if name is in Unicode format. bool BasicExcel::GetSheetName(int sheetIndex, char* name) { if (!(workbook_.boundSheets_[sheetIndex].name_.unicode_ & 1)) { strcpy(name, workbook_.boundSheets_[sheetIndex].name_.name_); return true; } else return false; } // Get the worksheet name at the given index. // Index starts from 0. // Returns false if name is in Ansi format. bool BasicExcel::GetSheetName(int sheetIndex, wchar_t* name) { if (workbook_.boundSheets_[sheetIndex].name_.unicode_ & 1) { wcscpy(name, workbook_.boundSheets_[sheetIndex].name_.wname_); return true; } else return false; } // Rename an Excel worksheet at the given index to the given ANSI name. // Index starts from 0. // Returns true if successful, false if otherwise. bool BasicExcel::RenameWorksheet(int sheetIndex, const char* to) { int maxWorksheets = (int)yesheets_.size(); if (sheetIndex < maxWorksheets) { for(int i=0; i<maxWorksheets; ++i) { if (workbook_.boundSheets_[i].name_.unicode_ & 1) continue; if (strcmp(to, workbook_.boundSheets_[i].name_.name_) == 0) return false; } workbook_.boundSheets_[sheetIndex].name_ = to; return true; } else return false; } // Rename an Excel worksheet at the given index to the given Unicode name. // Index starts from 0. // Returns true if successful, false if otherwise. bool BasicExcel::RenameWorksheet(int sheetIndex, const wchar_t* to) { int maxWorksheets = (int)yesheets_.size(); if (sheetIndex < maxWorksheets) { for(int i=0; i<maxWorksheets; ++i) { if (!(workbook_.boundSheets_[i].name_.unicode_ & 1)) continue; if (wcscmp(to, workbook_.boundSheets_[i].name_.wname_) == 0) return false; } workbook_.boundSheets_[sheetIndex].name_ = to; return true; } else return false; } // Rename an Excel worksheet that has given ANSI name to another ANSI name. // Returns true if successful, false if otherwise. bool BasicExcel::RenameWorksheet(const char* from, const char* to) { int maxWorksheets = (int)yesheets_.size(); for(int i=0; i<maxWorksheets; ++i) { if (workbook_.boundSheets_[i].name_.unicode_ & 1) continue; if (strcmp(from, workbook_.boundSheets_[i].name_.name_) == 0) { for(int j=0; j<maxWorksheets; ++j) { if (workbook_.boundSheets_[j].name_.unicode_ & 1) continue; if (strcmp(to, workbook_.boundSheets_[j].name_.name_) == 0) return false; } workbook_.boundSheets_[i].name_ = to; return true; } } return false; } // Rename an Excel worksheet that has given Unicode name to another Unicode name. // Returns true if successful, false if otherwise. bool BasicExcel::RenameWorksheet(const wchar_t* from, const wchar_t* to) { int maxWorksheets = (int) worksheets_.size(); for(int i=0; i<maxWorksheets; ++i) { if (!(workbook_.boundSheets_[i].name_.unicode_ & 1)) continue; if (wcscmp(from, workbook_.boundSheets_[i].name_.wname_) == 0) { for(int j=0; j<maxWorksheets; ++j) { if (!(workbook_.boundSheets_[j].name_.unicode_ & 1)) continue; if (wcscmp(to, workbook_.boundSheets_[j].name_.wname_) == 0) return false; } workbook_.boundSheets_[i].name_ = to; return true; } } return false; } size_t BasicExcel::Read(const char* data, size_t dataSize) { size_t bytesRead = 0; short code; LittleEndian::Read(data, code, 0, 2); BOF bof; Record rec; while(code == CODE::BOF) { bof.Read(data+bytesRead); switch(bof.type_) { case WORKBOOK_GLOBALS: bytesRead += workbook_.Read(data+bytesRead); break; case VISUAL_BASIC_MODULE: bytesRead += rec.Read(data+bytesRead); break; case WORKSHEET: worksheets_.push_back(Worksheet()); bytesRead += worksheets_.back().Read(data+bytesRead); break; case CHART: bytesRead += rec.Read(data+bytesRead); break; default: bytesRead += rec.Read(data+bytesRead); break; } if (bytesRead < dataSize) LittleEndian::Read(data, code, bytesRead, 2); else break; } return bytesRead; } size_t BasicExcel::Write(char* data) { size_t bytesWritten = 0; bytesWritten += workbook_.Write(data+bytesWritten); size_t maxWorkSheets = worksheets_.size(); for(size_t i=0; i<maxWorkSheets; ++i) bytesWritten += worksheets_[i].Write(data+bytesWritten); return bytesWritten; } void BasicExcel::AdjustStreamPositions() { // AdjustExtSSTPositions(); AdjustBoundSheetBOFPositions(); AdjustDBCellPositions(); } void BasicExcel::AdjustBoundSheetBOFPositions() { ULONG offset = workbook_.RecordSize(); size_t maxBoundSheets = workbook_.boundSheets_.size(); for(size_t i=0; i<maxBoundSheets; ++i) { workbook_.boundSheets_[i].BOFpos_ = offset; offset += worksheets_[i].RecordSize(); } } void BasicExcel::AdjustDBCellPositions() { int offset = workbook_.RecordSize(); int maxSheets = (int) worksheets_.size(); for(int i=0; i<maxSheets; ++i) { offset += worksheets_[i].bof_.RecordSize(); offset += worksheets_[i].index_.RecordSize(); offset += worksheets_[i].colinfos_.RecordSize(); offset += worksheets_[i].dimensions_.RecordSize(); size_t maxRowBlocks_ = worksheets_[i].cellTable_.rowBlocks_.size(); for(size_t j=0; j<maxRowBlocks_; ++j) { ULONG firstRowOffset = 0; size_t maxRows = worksheets_[i].cellTable_.rowBlocks_[j].rows_.size(); {for(size_t k=0; k<maxRows; ++k) { offset += worksheets_[i].cellTable_.rowBlocks_[j].rows_[k].RecordSize(); firstRowOffset += worksheets_[i].cellTable_.rowBlocks_[j].rows_[k].RecordSize(); }} USHORT cellOffset = (USHORT)firstRowOffset - 20; // a ROW record is 20 bytes long size_t maxCellBlocks = worksheets_[i].cellTable_.rowBlocks_[j].cellBlocks_.size(); {for(size_t k=0; k<maxCellBlocks; ++k) { offset += worksheets_[i].cellTable_.rowBlocks_[j].cellBlocks_[k]->RecordSize(); firstRowOffset += worksheets_[i].cellTable_.rowBlocks_[j].cellBlocks_[k]->RecordSize(); }} // Adjust Index DBCellPos_ absolute offset worksheets_[i].index_.DBCellPos_[j] = offset; offset += worksheets_[i].cellTable_.rowBlocks_[j].dbcell_.RecordSize(); // Adjust DBCell first row offsets worksheets_[i].cellTable_.rowBlocks_[j].dbcell_.firstRowOffset_ = firstRowOffset; // Adjust DBCell offsets size_t l=0; {for(size_t k=0; k<maxRows; ++k) { for(; l<maxCellBlocks; ++l) { if (worksheets_[i].cellTable_.rowBlocks_[j].rows_[k].rowIndex_ <= worksheets_[i].cellTable_.rowBlocks_[j].cellBlocks_[l]->RowIndex()) { worksheets_[i].cellTable_.rowBlocks_[j].dbcell_.offsets_[k] = cellOffset; break; } cellOffset += (USHORT)worksheets_[i].cellTable_.rowBlocks_[j].cellBlocks_[l]->RecordSize(); } cellOffset = 0; }} } offset += worksheets_[i].cellTable_.RecordSize(); offset += worksheets_[i].window2_.RecordSize(); offset += worksheets_[i].eof_.RecordSize(); } } void BasicExcel::AdjustExtSSTPositions() { ULONG offset = workbook_.bof_.RecordSize(); offset += workbook_.bof_.RecordSize(); offset += workbook_.window1_.RecordSize(); size_t maxFonts = workbook_.fonts_.size(); {for(size_t i=0; i<maxFonts; ++i) {offset += workbook_.fonts_[i].RecordSize();}} //MF size_t maxFormats = workbook_.formats_.size(); {for(size_t i=0; i<maxFormats; ++i) { if (workbook_.formats_[i].index_ >= FIRST_USER_FORMAT_IDX) // only write user defined formats offset += workbook_.formats_[i].RecordSize(); }} size_t maxXFs = workbook_.XFs_.size(); {for(size_t i=0; i<maxXFs; ++i) {offset += workbook_.XFs_[i].RecordSize();}} size_t maxStyles = workbook_.styles_.size(); {for(size_t i=0; i<maxStyles; ++i) {offset += workbook_.styles_[i].RecordSize();}} size_t maxBoundSheets = workbook_.boundSheets_.size(); {for(size_t i=0; i<maxBoundSheets; ++i) {offset += workbook_.boundSheets_[i].RecordSize();}} workbook_.extSST_.stringsTotal_ = 10; ULONG maxPortions = workbook_.sst_.uniqueStringsTotal_ / workbook_.extSST_.stringsTotal_ + (workbook_.sst_.uniqueStringsTotal_%workbook_.extSST_.stringsTotal_ ? 1 : 0); workbook_.extSST_.streamPos_.resize(maxPortions); workbook_.extSST_.firstStringPos_.resize(maxPortions); workbook_.extSST_.unused_.resize(maxPortions); ULONG relativeOffset = 8; for(size_t i=0; i<maxPortions; ++i) { workbook_.extSST_.streamPos_[i] = offset + 4 + relativeOffset; workbook_.extSST_.firstStringPos_[i] = 4 + (USHORT)relativeOffset; workbook_.extSST_.unused_[i] = 0; for(size_t j=0; (int)j<workbook_.extSST_.stringsTotal_; ++j) { if (i*workbook_.extSST_.stringsTotal_+j >= workbook_.sst_.strings_.size()) break; ULONG stringSize = workbook_.sst_.strings_[i*workbook_.extSST_.stringsTotal_+j].StringSize(); if (relativeOffset+stringSize+3 < 8224) relativeOffset += stringSize + 3; else { // If have >= 12 bytes (2 for size, 1 for unicode and >=9 for data, can split string // otherwise, end record and start continue record. if (8224 - relativeOffset >= 12) { stringSize -= (8224 - relativeOffset - 3); offset += 12 + relativeOffset; relativeOffset = 0; size_t additionalContinueRecords = stringSize / 8223; // 8223 because the first byte is for unicode for(size_t k=0; k<additionalContinueRecords; ++k) stringSize -= 8223; relativeOffset += stringSize + 1; } else { if (relativeOffset+stringSize+3 < 8224) relativeOffset += stringSize + 3; else { // If have >= 12 bytes (2 for size, 1 for unicode and >=9 for data, can split string // otherwise, end record and start continue record. if (8224 - relativeOffset >= 12) { stringSize -= (8224 - relativeOffset - 3); offset += 12 + relativeOffset; relativeOffset = 0; size_t additionalContinueRecords = stringSize / 8223; // 8223 because the first byte is for unicode for(size_t k=0; k<additionalContinueRecords; ++k) stringSize -= 8223; relativeOffset += stringSize + 1; } } } } } } } // Update yesheets_ using information from worksheets_. void BasicExcel::UpdateYExcelWorksheet() { int maxWorksheets = (int) worksheets_.size(); yesheets_.clear(); yesheets_.reserve(maxWorksheets); for(int i=0; i<maxWorksheets; ++i) { yesheets_.push_back(new BasicExcelWorksheet(this, i)); for(size_t j=0; j<worksheets_[i].colinfos_.colinfo_.size(); ++j) yesheets_[i]->colInfos_.colinfo_.push_back(worksheets_[i].colinfos_.colinfo_[j]); } } // Update worksheets_ using information from yesheets_. void BasicExcel::UpdateWorksheets() { // Constants. const int maxWorksheets = (int) yesheets_.size(); Worksheet::CellTable::RowBlock rowBlock; Worksheet::CellTable::RowBlock::Row row; Worksheet::CellTable::RowBlock::CellBlock::MulRK::XFRK xfrk; LargeString largeString; Worksheet::ColInfo oneCol; map<vector<char>, size_t> stringMap; map<vector<char>, size_t>::iterator stringMapIt; map<vector<wchar_t>, size_t> wstringMap; map<vector<wchar_t>, size_t>::iterator wstringMapIt; // Reset worksheets and string table. worksheets_.clear(); worksheets_.resize(maxWorksheets); workbook_.sst_.stringsTotal_ = 0; workbook_.sst_.uniqueStringsTotal_ = 0; workbook_.sst_.strings_.clear(); for(int s=0; s<maxWorksheets; ++s) { const BasicExcelWorksheet& sheet = *yesheets_[s]; Worksheet& rawSheet = worksheets_[s]; int maxRows = sheet.GetTotalRows(); int maxCols = sheet.GetTotalCols(); // Modify Index rawSheet.index_.firstUsedRowIndex_ = 100000; // Use 100000 to indicate that firstUsedRowIndex is not set yet since maximum allowed rows in Excel is 65535. rawSheet.index_.firstUnusedRowIndex_ = maxRows; //Modify ColInfo rawSheet.colinfos_ = sheet.colInfos_; // Modify Dimensions rawSheet.dimensions_.firstUsedRowIndex_ = 100000; // Use 100000 to indicate that firstUsedRowIndex is not set yet since maximum allowed rows in Excel is 65535. rawSheet.dimensions_.firstUsedColIndex_ = 1000; // Use 1000 to indicate that firstUsedColIndex is not set yet since maximum allowed columns in Excel is 255. rawSheet.dimensions_.lastUsedRowIndexPlusOne_ = maxRows; rawSheet.dimensions_.lastUsedColIndexPlusOne_ = maxCols; // Make first sheet selected and other sheets unselected if (s > 0) rawSheet.window2_.options_ &= ~0x200; // References and pointers to shorten code vector<Worksheet::CellTable::RowBlock>& rRowBlocks = rawSheet.cellTable_.rowBlocks_; vector<SmartPtr<Worksheet::CellTable::RowBlock::CellBlock> >* pCellBlocks; Worksheet::CellTable::RowBlock::CellBlock* pCell; rRowBlocks.resize(maxRows/32 + (maxRows%32 ? 1 : 0)); for(int r=0, curRowBlock=0; r<maxRows; ++r) { if (r % 32 == 0) { // New row block for every 32 rows. pCellBlocks = &(rRowBlocks[curRowBlock++].cellBlocks_); } bool newRow = true; // Keep track whether current row contains data. pCellBlocks->reserve(1000); for(int c=0; c<maxCols; ++c) { const BasicExcelCell* cell = sheet.Cell(r, c); int cellType = cell->Type(); // if (cellType != BasicExcelCell::UNDEFINED) // Current cell contains some data // Write cell content, even if blank in order to keep format { if (rawSheet.index_.firstUsedRowIndex_ == 100000) { // Set firstUsedRowIndex. rawSheet.index_.firstUsedRowIndex_ = r; rawSheet.dimensions_.firstUsedRowIndex_ = r; // Resize DBCellPos. size_t nm = int(rawSheet.index_.firstUnusedRowIndex_ - rawSheet.index_.firstUsedRowIndex_ - 1) / 32 + 1; rawSheet.index_.DBCellPos_.resize(nm); } if (rawSheet.dimensions_.firstUsedColIndex_ == 1000) { // Set firstUsedColIndex. rawSheet.dimensions_.firstUsedColIndex_ = c; } if (newRow) { // Prepare Row and DBCell for new row with data. Worksheet::CellTable::RowBlock& rRowBlock = rRowBlocks[curRowBlock-1]; rRowBlock.rows_.push_back(row); rRowBlock.rows_.back().rowIndex_ = r; rRowBlock.rows_.back().lastCellColIndexPlusOne_ = maxCols; rRowBlock.dbcell_.offsets_.push_back(0); newRow = false; } // Create new cellblock to store cell. pCellBlocks->push_back(new Worksheet::CellTable::RowBlock::CellBlock); if (pCellBlocks->size()%1000==0) pCellBlocks->reserve(pCellBlocks->size()+1000); pCell = &*(pCellBlocks->back()); // Store cell. switch(cellType) { case BasicExcelCell::INT: { // Check whether it is a single cell or range of cells. int cl = c + 1; for(; cl<maxCols; ++cl) { const BasicExcelCell* cellNext = sheet.Cell(r, cl); if (cellNext->Type()==BasicExcelCell::UNDEFINED || cellNext->Type()!=cell->Type()) break; } if (cl > c+1) { // MULRK cells pCell->SetType(CODE::MULRK); pCell->_union.mulrk_->rowIndex_ = r; pCell->_union.mulrk_->firstColIndex_ = c; pCell->_union.mulrk_->lastColIndex_ = cl - 1; pCell->_union.mulrk_->XFRK_.resize(cl-c); for(size_t i=0; c<cl; ++c, ++i) { cell = sheet.Cell(r, c); pCell->_union.mulrk_->XFRK_[i].RKValue_ = GetRKValueFromInteger(cell->GetInteger()); pCell->_union.mulrk_->XFRK_[i].XFRecordIndex_ = cell->GetXFormatIdx(); //MF set format index } --c; } else { // Single cell pCell->SetType(CODE::RK); pCell->_union.rk_->rowIndex_ = r; pCell->_union.rk_->colIndex_ = c; pCell->_union.rk_->value_ = GetRKValueFromInteger(cell->GetInteger()); pCell->_union.rk_->XFRecordIndex_ = cell->GetXFormatIdx(); //MF set format index } break; } case BasicExcelCell::DOUBLE: { // Check whether it is a single cell or range of cells. // Double values which cannot be stored as RK values will be stored as single cells. bool canStoreAsRKValue = CanStoreAsRKValue(cell->GetDouble()); int cl = c + 1; for(; cl<maxCols; ++cl) { const BasicExcelCell* cellNext = sheet.Cell(r, cl); if (cellNext->Type()==BasicExcelCell::UNDEFINED || cellNext->Type()!=cell->Type() || canStoreAsRKValue!=CanStoreAsRKValue(cellNext->GetDouble())) break; } if (cl > c+1 && canStoreAsRKValue) { // MULRK cells pCell->SetType(CODE::MULRK); pCell->_union.mulrk_->rowIndex_ = r; pCell->_union.mulrk_->firstColIndex_ = c; pCell->_union.mulrk_->lastColIndex_ = cl - 1; pCell->_union.mulrk_->XFRK_.resize(cl-c); for(size_t i=0; c<cl; ++c, ++i) { cell = sheet.Cell(r, c); pCell->_union.mulrk_->XFRK_[i].RKValue_ = GetRKValueFromDouble(cell->GetDouble()); pCell->_union.mulrk_->XFRK_[i].XFRecordIndex_ = cell->GetXFormatIdx(); //MF set format index } --c; } else { // Single cell if (canStoreAsRKValue) { pCell->SetType(CODE::RK); pCell->_union.rk_->rowIndex_ = r; pCell->_union.rk_->colIndex_ = c; pCell->_union.rk_->value_ = GetRKValueFromDouble(cell->GetDouble()); pCell->_union.rk_->XFRecordIndex_ = cell->GetXFormatIdx(); //MF set format index } else { pCell->SetType(CODE::NUMBER); pCell->_union.number_->rowIndex_ = r; pCell->_union.number_->colIndex_ = c; pCell->_union.number_->value_ = cell->GetDouble(); pCell->_union.number_->XFRecordIndex_ = cell->GetXFormatIdx(); //MF set format index } } break; } case BasicExcelCell::STRING: { // Fill cell information pCell->SetType(CODE::LABELSST); pCell->_union.labelsst_->rowIndex_ = r; pCell->_union.labelsst_->colIndex_ = c; // Get cell string vector<char> str(cell->GetStringLength()+1); cell->Get(&*(str.begin())); str.pop_back(); // Remove null character because LargeString does not store null character. // Check if string is present in Shared string table. ++workbook_.sst_.stringsTotal_; ULONG maxUniqueStrings = workbook_.sst_.uniqueStringsTotal_; size_t strIndex = 0; stringMapIt = stringMap.find(str); if (stringMapIt != stringMap.end()) strIndex = stringMapIt->second; else strIndex = maxUniqueStrings; if (strIndex < maxUniqueStrings) { // String is present in Shared string table. pCell->_union.labelsst_->SSTRecordIndex_ = strIndex; } else { // New unique string. stringMap[str] = maxUniqueStrings; workbook_.sst_.strings_.push_back(largeString); workbook_.sst_.strings_[maxUniqueStrings].name_ = str; workbook_.sst_.strings_[maxUniqueStrings].unicode_ = 0; pCell->_union.labelsst_->SSTRecordIndex_ = maxUniqueStrings; ++workbook_.sst_.uniqueStringsTotal_; } pCell->_union.labelsst_->XFRecordIndex_ = cell->GetXFormatIdx(); //MF set format index break; } case BasicExcelCell::WSTRING: { // Fill cell information pCell->SetType(CODE::LABELSST); pCell->_union.labelsst_->rowIndex_ = r; pCell->_union.labelsst_->colIndex_ = c; // Get cell string vector<wchar_t> str(cell->GetStringLength()+1); cell->Get(&*(str.begin())); str.pop_back(); // Remove null character because LargeString does not store null character. // Check if string is present in Shared string table. ++workbook_.sst_.stringsTotal_; size_t maxUniqueStrings = workbook_.sst_.strings_.size(); size_t strIndex = 0; wstringMapIt = wstringMap.find(str); if (wstringMapIt != wstringMap.end()) strIndex = wstringMapIt->second; else strIndex = maxUniqueStrings; if (strIndex < maxUniqueStrings) { // String is present in Shared string table. pCell->_union.labelsst_->SSTRecordIndex_ = strIndex; } else { // New unique string wstringMap[str] = maxUniqueStrings; workbook_.sst_.strings_.push_back(largeString); workbook_.sst_.strings_[maxUniqueStrings].wname_ = str; workbook_.sst_.strings_[maxUniqueStrings].unicode_ = 1; pCell->_union.labelsst_->SSTRecordIndex_ = maxUniqueStrings; ++workbook_.sst_.uniqueStringsTotal_; } pCell->_union.labelsst_->XFRecordIndex_ = cell->GetXFormatIdx(); //MF set format index break; } //MF: handle formulas case BasicExcelCell::FORMULA: { // Fill cell information pCell->SetType(CODE::FORMULA); pCell->_union.formula_->rowIndex_ = r; pCell->_union.formula_->colIndex_ = c; pCell->_union.formula_->XFRecordIndex_ = cell->GetXFormatIdx(); cell->get_formula(pCell); break; } // handle blank case to keep formatting case BasicExcelCell::UNDEFINED: { // Fill cell information pCell->SetType(CODE::BLANK); pCell->_union.blank_->colIndex_ = c; pCell->_union.blank_->rowIndex_ = r; pCell->_union.blank_->XFRecordIndex_ = cell->GetXFormatIdx(); break; } } } } } // assemble the MERGECELL records for(int mr=0; mr<maxRows; ++mr) { for(int c=0; c<maxCols; ++c) { const BasicExcelCell* cell = sheet.Cell(mr,c); // Merged cells if (cell->GetMergedRows() > 1 || cell->GetMergedColumns() > 1) { YExcel::Worksheet::MergedCells::MergedCell mergedCell; mergedCell.firstRow_ = mr; mergedCell.firstColumn_ = c; mergedCell.lastRow_ = mr + cell->GetMergedRows() - 1; mergedCell.lastColumn_ = c + cell->GetMergedColumns() - 1; rawSheet.mergedCells_.mergedCellsVector_.push_back(mergedCell); } } } // If worksheet has no data if (rawSheet.index_.firstUsedRowIndex_ == 100000) { // Set firstUsedRowIndex. rawSheet.index_.firstUsedRowIndex_ = 0; rawSheet.dimensions_.firstUsedRowIndex_ = 0; // Resize DBCellPos. size_t nm = int(rawSheet.index_.firstUnusedRowIndex_ - rawSheet.index_.firstUsedRowIndex_ - 1) / 32 + 1; rawSheet.index_.DBCellPos_.resize(nm); } if (rawSheet.dimensions_.firstUsedColIndex_ == 1000) { // Set firstUsedColIndex. rawSheet.dimensions_.firstUsedColIndex_ = 0; } } } /************************************************************************************************************/ /************************************************************************************************************/ BasicExcelWorksheet::BasicExcelWorksheet(BasicExcel* excel, int sheetIndex) : excel_(excel), sheetIndex_(sheetIndex) { UpdateCells(); } // Get the current worksheet name. // Returns 0 if name is in Unicode format. char* BasicExcelWorksheet::GetAnsiSheetName() { if (!(excel_->workbook_.boundSheets_[sheetIndex_].name_.unicode_ & 1)) return excel_->workbook_.boundSheets_[sheetIndex_].name_.name_; else return NULL; } // Get the current worksheet name. // Returns 0 if name is in Ansi format. wchar_t* BasicExcelWorksheet::GetUnicodeSheetName() { if (excel_->workbook_.boundSheets_[sheetIndex_].name_.unicode_ & 1) return excel_->workbook_.boundSheets_[sheetIndex_].name_.wname_; else return NULL; } // Get the current worksheet name. // Returns false if name is in Unicode format. bool BasicExcelWorksheet::GetSheetName(char* name) { if (!(excel_->workbook_.boundSheets_[sheetIndex_].name_.unicode_ & 1)) { strcpy(name, excel_->workbook_.boundSheets_[sheetIndex_].name_.name_); return true; } else return false; } // Get the current worksheet name. // Returns false if name is in Ansi format. bool BasicExcelWorksheet::GetSheetName(wchar_t* name) { if (excel_->workbook_.boundSheets_[sheetIndex_].name_.unicode_ & 1) { wcscpy(name, excel_->workbook_.boundSheets_[sheetIndex_].name_.wname_); return true; } else return false; } // Rename current Excel worksheet to another ANSI name. // Returns true if successful, false if otherwise. bool BasicExcelWorksheet::Rename(const char* to) { int maxWorksheets = (int) excel_->workbook_.boundSheets_.size(); for(int i=0; i<maxWorksheets; ++i) { if (excel_->workbook_.boundSheets_[i].name_.unicode_ & 1) continue; if (strcmp(to, excel_->workbook_.boundSheets_[i].name_.name_) == 0) return false; } excel_->workbook_.boundSheets_[sheetIndex_].name_ = to; return true; } // Rename current Excel worksheet to another Unicode name. // Returns true if successful, false if otherwise. bool BasicExcelWorksheet::Rename(const wchar_t* to) { int maxWorksheets = (int) excel_->workbook_.boundSheets_.size(); for(int i=0; i<maxWorksheets; ++i) { if (!(excel_->workbook_.boundSheets_[i].name_.unicode_ & 1)) continue; if (wcscmp(to, excel_->workbook_.boundSheets_[i].name_.wname_) == 0) return false; } excel_->workbook_.boundSheets_[sheetIndex_].name_ = to; return true; } ///< Print entire worksheet to an output stream, separating each column with the defined delimiter and enclosing text using the defined textQualifier. ///< Leave out the textQualifier argument if do not wish to have any text qualifiers. void BasicExcelWorksheet::Print(ostream& os, char delimiter, char textQualifier) const { for(int r=0; r<maxRows_; ++r) { for(int c=0; c<maxCols_; ++c) { const BasicExcelCell* cell = Cell(r, c); switch(cell->Type()) { case BasicExcelCell::UNDEFINED: break; case BasicExcelCell::INT: os << cell->GetInteger(); break; case BasicExcelCell::DOUBLE: os << setprecision(15) << cell->GetDouble(); break; case BasicExcelCell::STRING: { if (textQualifier != '\0') { // Get string. size_t maxLength = cell->GetStringLength(); vector<char> cellString(maxLength+1); cell->Get(&*(cellString.begin())); // Duplicate textQualifier if found in string. ULONG npos = 0; vector<char>::iterator it; while((it=find(cellString.begin()+npos, cellString.end(), textQualifier)) != cellString.end()) npos = (ULONG) distance(cellString.begin(), cellString.insert(it, textQualifier)) + 2; // Print out string enclosed with textQualifier. os << textQualifier << &*(cellString.begin()) << textQualifier; } else os << cell->GetString(); break; } case BasicExcelCell::WSTRING: { // Print out string enclosed with textQualifier (does not work). //os << textQualifier << cell->GetWString() << textQualifier; break; } } if (c < maxCols_-1) os << delimiter; } os << endl; } } // Total number of rows in current Excel worksheet. int BasicExcelWorksheet::GetTotalRows() const { return maxRows_; } // Total number of columns in current Excel worksheet. int BasicExcelWorksheet::GetTotalCols() const { return maxCols_; } // Return a pointer to an Excel cell. // row and col starts from 0. // Returns NULL if row exceeds 65535 or col exceeds 255. BasicExcelCell* BasicExcelWorksheet::Cell(int row, int col) { // Check to ensure row and col do not exceed the maximum allowable range for an Excel worksheet. if (row>65535 || col>255) return NULL; // Increase size of the cell matrix if necessary if (col >= maxCols_) { // Increase the number of columns. maxCols_ = col + 1; for(int i=0; i<maxRows_; ++i) cells_[i].resize(maxCols_); } if (row >= maxRows_) { // Increase the number of rows. maxRows_ = row + 1; cells_.resize(maxRows_, vector<BasicExcelCell>(maxCols_)); } return &(cells_[row][col]); } // Return a pointer to an Excel cell. // row and col starts from 0. // Returns NULL if row exceeds 65535 or col exceeds 255. const BasicExcelCell* BasicExcelWorksheet::Cell(int row, int col) const { // row and col do not exceed the current worksheet size if (row >= maxRows_) return NULL; if (col >= maxCols_) return NULL; return &(cells_[row][col]); } // Erase content of a cell. row and col starts from 0. // Returns true if successful, false if row or col exceeds range. bool BasicExcelWorksheet::EraseCell(int row, int col) { if (row<maxRows_ && col<maxCols_) { cells_[row][col].EraseContents(); return true; } else return false; } //MF: calculate sheet dimension from row blocks, only looking at non-empty cells static void calculate_dimension(vector<Worksheet::CellTable::RowBlock>& rRowBlocks, int& maxRows_, int& maxCols_) { int maxRow = 0; int maxCol = 0; for(size_t i=0; i<rRowBlocks.size(); ++i) { vector<SmartPtr<Worksheet::CellTable::RowBlock::CellBlock> >& rCellBlocks = rRowBlocks[i].cellBlocks_; for(size_t j=0; j<rCellBlocks.size(); ++j) { int row = rCellBlocks[j]->RowIndex(); int col = rCellBlocks[j]->ColIndex(); switch(rCellBlocks[j]->type_) { case CODE::BLANK: case CODE::MULBLANK: break; case CODE::MULRK: { int maxCols = rCellBlocks[j]->_union.mulrk_->lastColIndex_ - rCellBlocks[j]->_union.mulrk_->firstColIndex_ + 1; col += maxCols; // fall through } default: if (row > maxRow) maxRow = row; if (col > maxCol) maxCol = col; } } } maxRows_ = maxRow + 1; maxCols_ = maxCol + 1; } void BasicExcelWorksheet::SetColWidth(const int colindex, const USHORT colwidth) { Worksheet::ColInfo tmpColInfo; tmpColInfo.firstColumnIndex_ = tmpColInfo.lastColumnIndex_ = colindex; tmpColInfo.columnWidth_ = colwidth; colInfos_.colinfo_.push_back(tmpColInfo); } // Get the colwidth for the given col USHORT BasicExcelWorksheet::GetColWidth(const int colindex) { for(size_t i=0; i<colInfos_.colinfo_.size(); ++i) { if (colindex == colInfos_.colinfo_[i].firstColumnIndex_) return colInfos_.colinfo_[i].columnWidth_; } return 0; } // Update cells using information from BasicExcel.worksheets_ void BasicExcelWorksheet::UpdateCells() { // Define some references vector<Worksheet::CellTable::RowBlock>& rRowBlocks = excel_->worksheets_[sheetIndex_].cellTable_.rowBlocks_; const vector<YExcel::Worksheet::MergedCells::MergedCell>& mergedCells = excel_->worksheets_[sheetIndex_].mergedCells_.mergedCellsVector_; vector<wchar_t> wstr; vector<char> str; //MF calculate sheet dimension independent from the DIMENSIONS record calculate_dimension(rRowBlocks, maxRows_, maxCols_); // const Worksheet::Dimensions& dimension = excel_->worksheets_[sheetIndex_].dimensions_; // maxRows_ = dimension.lastUsedRowIndexPlusOne_; // maxCols_ = dimension.lastUsedColIndexPlusOne_; // Resize the cells to the size of the worksheet vector<BasicExcelCell> cellCol(maxCols_); cells_.resize(maxRows_, cellCol); size_t maxRowBlocks = rRowBlocks.size(); for(size_t i=0; i<maxRowBlocks; ++i) { vector<SmartPtr<Worksheet::CellTable::RowBlock::CellBlock> >& rCellBlocks = rRowBlocks[i].cellBlocks_; size_t maxCells = rCellBlocks.size(); for(size_t j=0; j<maxCells; ++j) { int row = rCellBlocks[j]->RowIndex(); int col = rCellBlocks[j]->ColIndex(); if (row >= maxRows_) { // skip empty rows a the bottom continue; // // resize on unexpected row values // maxRows_ = row + 1; // cells_.resize(maxRows_, cellCol); } if (col >= maxCols_) { // skip empty columns a the right sheet border continue; // // resize on unexpected column values // if (col >= (int)cells_[row].size()) // cells_[row].resize(col+1); } switch(rCellBlocks[j]->type_) { case CODE::BLANK: cells_[row][col].SetXFormatIdx(rCellBlocks[j]->_union.blank_->XFRecordIndex_); //MF read format index break; case CODE::MULBLANK: { size_t maxCols = rCellBlocks[j]->_union.mulblank_->lastColIndex_ - rCellBlocks[j]->_union.mulblank_->firstColIndex_ + 1; for(size_t k=0; k<maxCols; ++k,++col) { //MF resize on unexpected column values if (col >= maxCols_) { if (col >= (int)cells_[row].size()) cells_[row].resize(col+1); } cells_[row][col].SetXFormatIdx(rCellBlocks[j]->_union.mulblank_->XFRecordIndices_[k]); //MF read format index } break;} case CODE::BOOLERR: if (rCellBlocks[j]->_union.boolerr_->error_ == 0) cells_[row][col].Set(rCellBlocks[j]->_union.boolerr_->value_); //MF was "boolerr_.code_" in VC6 version cells_[row][col].SetXFormatIdx(rCellBlocks[j]->_union.boolerr_->XFRecordIndex_); //MF read format index break; case CODE::LABELSST: { vector<LargeString>& ss = excel_->workbook_.sst_.strings_; if (ss[rCellBlocks[j]->_union.labelsst_->SSTRecordIndex_].unicode_ & 1) { wstr = ss[rCellBlocks[j]->_union.labelsst_->SSTRecordIndex_].wname_; wstr.resize(wstr.size()+1); wstr.back() = L'\0'; cells_[row][col].Set(&*(wstr.begin())); } else { str = ss[rCellBlocks[j]->_union.labelsst_->SSTRecordIndex_].name_; str.resize(str.size()+1); str.back() = '\0'; cells_[row][col].Set(&*(str.begin())); } cells_[row][col].SetXFormatIdx(rCellBlocks[j]->_union.labelsst_->XFRecordIndex_); //MF read format index break;} case CODE::MULRK: { size_t maxCols = rCellBlocks[j]->_union.mulrk_->lastColIndex_ - rCellBlocks[j]->_union.mulrk_->firstColIndex_ + 1; for(size_t k=0; k<maxCols; ++k,++col) { //MF resize on unexpected column values if (col >= maxCols_) { if (col >= (int)cells_[row].size()) cells_[row].resize(col+1); break; // skip invalid column values } // Get values of the whole range const Worksheet::CellTable::RowBlock::CellBlock::MulRK::XFRK& xfrk = rCellBlocks[j]->_union.mulrk_->XFRK_[k]; cells_[row][col].SetRKValue(xfrk.RKValue_); cells_[row][col].SetXFormatIdx(xfrk.XFRecordIndex_); //MF read format index } break;} case CODE::NUMBER: cells_[row][col].Set(rCellBlocks[j]->_union.number_->value_); cells_[row][col].SetXFormatIdx(rCellBlocks[j]->_union.number_->XFRecordIndex_); //MF read format index break; case CODE::RK: { cells_[row][col].SetRKValue(rCellBlocks[j]->_union.rk_->value_); cells_[row][col].SetXFormatIdx(rCellBlocks[j]->_union.rk_->XFRecordIndex_); //MF read format index break;} //MF: handle formulas case CODE::FORMULA: { const Worksheet::CellTable::RowBlock::CellBlock::Formula& formula = *rCellBlocks[j]->_union.formula_; cells_[row][col].SetFormula(formula); cells_[row][col].SetXFormatIdx(formula.XFRecordIndex_); //MF read format index break;} } } } // handle merged cells information for(size_t k=0; k<mergedCells.size(); k++) { int row = mergedCells[k].firstRow_; int col = mergedCells[k].firstColumn_; if (row<(int)cells_.size() && col<(int)cells_[row].size()) { cells_[row][col].SetMergedRows(mergedCells[k].lastRow_ - mergedCells[k].firstRow_ + 1); cells_[row][col].SetMergedColumns(mergedCells[k].lastColumn_ - mergedCells[k].firstColumn_ + 1); } } } void BasicExcelWorksheet::MergeCells(int row, int col, USHORT rowRange, USHORT colRange) { BasicExcelCell* cell = Cell(row, col); cell->SetMergedRows(rowRange); cell->SetMergedColumns(colRange); /* Assembling MERGECELL records is accomplished in BasicExcel::UpdateWorksheets() Worksheet::MergedCells::MergedCell mergedCell; mergedCell.firstRow_ = row; mergedCell.lastRow_ = row + rowRange - 1; mergedCell.firstColumn_ = col; mergedCell.lastColumn_ = col + colRange - 1; Worksheet& worksheet = excel_->worksheets_[sheetIndex_]; worksheet.mergedCells_.mergedCellsVector_.push_back(mergedCell); */ } /************************************************************************************************************/ /************************************************************************************************************/ BasicExcelCell::BasicExcelCell() : type_(UNDEFINED), _xf_idx(0), //MF mergedRows_(1), mergedColumns_(1) { } // Get type of value stored in current Excel cell. // Returns one of the enums. int BasicExcelCell::Type() const {return type_;} // Get an integer value. // Returns false if cell does not contain an integer or a double. bool BasicExcelCell::Get(int& val) const { if (type_ == INT) { val = ival_; return true; } else if (type_ == DOUBLE) { val = (int)dval_; return true; } else if (type_ == FORMULA) { const unsigned char* presult = _pFormula->_result; //MF: If the two most significant bytes of the result field are 0xFFFF, the formula evaluates to a string, a boolean or an error value. if (presult[6]==0xFF && presult[7]==0xFF) return false; double dresult; memcpy(&dresult, presult, 8); val = (int)dresult; return true; } else return false; } // Get a double value. // Returns false if cell does not contain a double or an integer. bool BasicExcelCell::Get(double& val) const { if (type_ == DOUBLE) { val = dval_; return true; } else if (type_ == INT) { val = (double)ival_; return true; } else if (type_ == FORMULA) { const unsigned char* presult = _pFormula->_result; //MF: If the two most significant bytes of the result field are 0xFFFF, the formula evaluates to a string, a boolean or an error value. if (presult[6]==0xFF && presult[7]==0xFF) return false; double dresult; memcpy(&dresult, presult, 8); val = dresult; return true; } else return false; } // Get an ANSI string. // Returns false if cell does not contain an ANSI string. bool BasicExcelCell::Get(char* str) const { if (type_ == STRING) { if (str_.empty()) *str = '\0'; else strcpy(str, &*(str_.begin())); return true; } else { assert(type_==STRING); return false; } } // Get an Unicode string. // Returns false if cell does not contain an Unicode string. bool BasicExcelCell::Get(wchar_t* str) const { if (type_ == WSTRING) { if (wstr_.empty()) *str = L'\0'; else wcscpy(str, &*(wstr_.begin())); return true; } else { assert(type_==WSTRING); return false; } } // Return length of ANSI or Unicode string (excluding null character). size_t BasicExcelCell::GetStringLength() const { if (type_ == STRING) return str_.size() - 1; else { assert(type_==WSTRING); return wstr_.size() - 1; } } // Get an integer value. // Returns 0 if cell does not contain an integer. int BasicExcelCell::GetInteger() const { int val; if (Get(val)) return val; else return 0; } // Get a double value. // Returns 0.0 if cell does not contain a double. double BasicExcelCell::GetDouble() const { double val; if (Get(val)) return val; else return 0.0; } // Get an ANSI string. // Returns NULL if cell does not contain an ANSI string. const char* BasicExcelCell::GetString() const { vector<char> str(str_.size()); if (type_ == STRING) { if (!str.empty() && Get(&*(str.begin()))) return &*(str_.begin()); } else if (type_ == FORMULA) { return _pFormula->str_.c_str(); } return NULL; } // Get an Unicode string. // Returns NULL if cell does not contain an Unicode string. const wchar_t* BasicExcelCell::GetWString() const { vector<wchar_t> wstr(wstr_.size()); if (type_ == WSTRING) { if (!wstr.empty() && Get(&*(wstr.begin()))) return &*(wstr_.begin()); } else if (type_ == FORMULA) { return _pFormula->wstr_.c_str(); } return NULL; } // Set content of current Excel cell to an integer. void BasicExcelCell::Set(int val) { SetInteger(val); } // Set content of current Excel cell to a double. void BasicExcelCell::Set(double val) { SetDouble(val); } // Set content of current Excel cell to an ANSI string. void BasicExcelCell::Set(const char* str) { SetString(str); } // Set content of current Excel cell to an Unicode string. void BasicExcelCell::Set(const wchar_t* str) { SetWString(str); } // Set content of current Excel cell to an integer. void BasicExcelCell::SetInteger(int val) { type_ = INT; ival_ = val; } // Set content of current Excel cell to a double. void BasicExcelCell::SetDouble(double val) { type_ = DOUBLE; dval_ = val; } //MF: Set content of current Excel cell to a double or integer value. void BasicExcelCell::SetRKValue(int rkValue) { bool isMultiplied = rkValue & 1; bool rkInteger = (rkValue & 2)? true: false; if (rkInteger) { rkValue >>= 2; if (isMultiplied) { if ((rkValue % 100) == 0) { type_ = INT; ival_ = rkValue / 100; } else { type_ = DOUBLE; // OpenOffice Calc stores double values with less than 3 decimal places as "integer" RKValues (MS Office doesn't use this case). dval_ = rkValue / 100.; } } else { type_ = INT; ival_ = rkValue; } } else { RKValueUnion intdouble; intdouble.intvalue_ = rkValue >> 2; // only valid if the integer flag (rkValue & 2) is not set intdouble.intvalue_ <<= 34; if (isMultiplied) intdouble.doublevalue_ /= 100; type_ = DOUBLE; dval_ = intdouble.doublevalue_; } } // Set content of current Excel cell to an ANSI string. void BasicExcelCell::SetString(const char* str) { size_t length = strlen(str); if (length > 0) { type_ = STRING; str_ = vector<char>(length+1); strcpy(&*(str_.begin()), str); wstr_.clear(); } else EraseContents(); } // Set content of current Excel cell to an Unicode string. void BasicExcelCell::SetWString(const wchar_t* str) { size_t length = wcslen(str); if (length > 0) { type_ = WSTRING; wstr_ = vector<wchar_t>(length+1); wcscpy(&*(wstr_.begin()), str); str_.clear(); } else EraseContents(); } //MF void BasicExcelCell::SetFormula(const Worksheet::CellTable::RowBlock::CellBlock::Formula& f) { type_ = BasicExcelCell::FORMULA; _pFormula = new Formula(f); } BasicExcelCell::Formula::Formula(const Worksheet::CellTable::RowBlock::CellBlock::Formula& f) : _formula_type(0) { _formula_type = f.type_; if (_formula_type == CODE::SHRFMLA1) { shrformula_ = f.shrfmla1_.formula_; firstRowIndex_ = f.shrfmla1_.firstRowIndex_; lastRowIndex_ = f.shrfmla1_.lastRowIndex_; firstColIndex_ = f.shrfmla1_.firstColIndex_; lastColIndex_ = f.shrfmla1_.lastColIndex_; unused_ = f.shrfmla1_.unused_; } else { firstRowIndex_ = 0; lastRowIndex_ = 0; firstColIndex_ = 0; lastColIndex_ = 0; unused_ = 0; } _formula = f.RPNtoken_; // store result values memcpy(_result, f.result_, 8); if (f.string_.wstr_) { wstr_ = f.string_.wstr_; str_ = ::narrow_string(wstr_); } } bool BasicExcelCell::get_formula(Worksheet::CellTable::RowBlock::CellBlock* pCell) const { if (type_==FORMULA && _pFormula) { pCell->_union.formula_->type_ = _pFormula->_formula_type; memcpy(pCell->_union.formula_->result_, _pFormula->_result, 8); if (pCell->_union.formula_->type_ == CODE::SHRFMLA1) { pCell->_union.formula_->shrfmla1_.formula_ = _pFormula->shrformula_; pCell->_union.formula_->shrfmla1_.firstRowIndex_ = _pFormula->firstRowIndex_; pCell->_union.formula_->shrfmla1_.lastRowIndex_ = _pFormula->lastRowIndex_; pCell->_union.formula_->shrfmla1_.firstColIndex_ = _pFormula->firstColIndex_; pCell->_union.formula_->shrfmla1_.lastColIndex_ = _pFormula->lastColIndex_; pCell->_union.formula_->shrfmla1_.unused_ = _pFormula->unused_; } else { pCell->_union.formula_->shrfmla1_.firstRowIndex_ = 0; pCell->_union.formula_->shrfmla1_.lastRowIndex_ = 0; pCell->_union.formula_->shrfmla1_.firstColIndex_ = 0; pCell->_union.formula_->shrfmla1_.lastColIndex_ = 0; pCell->_union.formula_->shrfmla1_.unused_ = 0; } pCell->_union.formula_->RPNtoken_ = _pFormula->_formula; if (!_pFormula->wstr_.empty()) { size_t stringSize = _pFormula->wstr_.size(); wchar_t* wstr = new wchar_t[stringSize]; memcpy(wstr, &*_pFormula->wstr_.begin(), stringSize); pCell->_union.formula_->string_.wstr_ = wstr; } else pCell->_union.formula_->string_.wstr_ = NULL; return true; } return false; } // Erase the content of current Excel cell. // Set type to UNDEFINED. void BasicExcelCell::EraseContents() { type_ = UNDEFINED; str_.clear(); wstr_.clear(); } ///< Print cell to output stream. ///< Print a null character if cell is undefined. ostream& operator<<(ostream& os, const BasicExcelCell& cell) { switch(cell.Type()) { case BasicExcelCell::UNDEFINED: os << '\0'; break; case BasicExcelCell::INT: os << cell.GetInteger(); break; case BasicExcelCell::DOUBLE: os << cell.GetDouble(); break; case BasicExcelCell::STRING: os << cell.GetString(); break; case BasicExcelCell::WSTRING: os << cell.GetWString(); break; } return os; } } // namespace YExcel